forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to src/web/auth.rsClear filter

2026-09-23

✨ feat: school identity is the uuid; drop the slugAhmet Kaan Gümüş · 2918040
✨ feat: school identity is the uuid; drop the slug

The school slug is gone from every surface: the session cookie prefix,
the /schools/{id} builder routes, FILES_PATH blob dirs, the hab/2 frame
school value, DTOs, and the /limits contract. SchoolId::try_parse is the
one wire parse (hyphenated uuid only); a non-uuid frame school answers
unknown_school. Register gets a public picker via the new unauthenticated
GET /auth/schools returning active [{id, name}]. The control migration
drops school_slug and the slug column, which invalidates every existing
session — old cookie prefixes cannot resolve.
Local-Gate: 3fafffd98aec59c68e2606833b87785d0abf2fee (1510 passed, 425s)

2026-09-14

🗃️ feat: pre-prod schema: person join key, drop school password copyAhmet Kaan Gümüş · 804bd3c
🗃️ feat: pre-prod schema: person join key, drop school password copy

app_user no longer stores password_hash (login already verifies
control person). School rows carry person uuid + created_at.
class_blueprint is uuid-keyed; exam child rows composite-FK to
(exam, question); pool/solution images are child tables;
graded_at/marked_at/enrollment timestamps added.

Left alone: occupancy/refcount counters (cap locks, not lies),
ledger source, menu derived id, school.slug PK, fee_plan JSONB.
🧹 style: zero clippy/rustc warnings project-wideAhmet Kaan Gümüş · c782987
🧹 style: zero clippy/rustc warnings project-wide

Box the large LoginResponse::LoggedIn variant and drop the
let-and-return in login_as_school.

2026-09-13

✨ feat: person-scoped login; select school afterAhmet Kaan Gümüş · fae1f79
✨ feat: person-scoped login; select school after

Login is username+password only. A person is global, memberships are
per-school (role stays on app_user), and POST /auth/school binds when
the account belongs to more than one school.

2026-09-12

2026-09-11

🧹 chore: split profile, badge, builder into domain/db/service layersAhmet Kaan Gümüş · 7f616c0
🧹 chore: split profile, badge, builder into domain/db/service layers

C3 identity lane. Moves, not rewrites:

- badge: BadgeStats::load / BadgeAward::list_for / sync (UPSERT with the
  earned_at = NONE idempotency stays whole) -> db::badge, with the
  award-key mint and the persistence tests; BadgeStat/BadgeStats/earned/
  BadgeAward (pure rules) stay in domain::badge; service::badge wraps
  list_for/sync for the web layer.
- profile: ProfileStats::load (+ PomodoroTotals, persistence tests) ->
  db::profile; newtypes + getters stay; service::profile::load wraps.
- builder: find_by_username/read/create(create_session)/find_by_token/
  delete_by_token -> db::builder; the idempotent seed ensure ->
  service::builder (ensure_admin precedent); both tests ride their fns.
- preferences, key: fully pure (validated newtypes, composite-id
  helpers) — stay domain-only, no db/service modules created.

Entity fields the split constructs from are now pub(crate) (Builder,
BuilderSession, ProfileStats), matching the user split.

Callers re-pointed crate-wide: web/{users,exams/mod,questions,homework,
sessions,auth,extractor,builder,tenant_state}, service/exam_attempt.rs
(badge::sync after start), database.rs (control seed), tests/
{builder_api,e2e,integration}; cross-lane compile fixups in
domain/pomodoro.rs and domain/session_attendance.rs (their lanes
re-point on merge). constant.rs doc link -> crate::db::badge::list_for.
🧹 chore: split note/session/settings into domain/db/service layersAhmet Kaan Gümüş · efea304
🧹 chore: split note/session/settings into domain/db/service layers

Pilot wave of the three-layer split. All query execution for the three
domains now lives in src/db/{note,session,settings}.rs as free fns taking
db first; web handlers call service::<x>::* only; domain keeps pure types.

- service/settings.rs gains the PATCH workflow (apply) and SETTINGS_LOCK —
  it spans a multi-call pair (retire names, CAS save, restore), so it is a
  service lock, not a db lock. The service takes its own input records
  (SettingsPatch/*Input) so wire DTOs stay in web and list validation keeps
  its original order, including the try_kept grandfathering that needs the
  stored list.
- Note/Session/Settings fields the db layer mints or CAS-binds become
  pub(crate); Settings::record_id becomes pub(crate).
- Unit tests rode with their fns: note delete cascade → db/note, session
  purge → db/session, settings load/save/CAS → db/settings, the whole
  settings edit workflow suite → service/settings.
- Doc links re-pointed (user, class_blueprint, bank_question, exam,
  note_file, tests/regress_roles); NoteId::generate's stale
  'Note::list_for_user' link now names db::note::list_for.
- Known residual for a later wave: web/notes.rs:411 file.delete() is
  note_file-domain persistence (note_file splits in C3).

2026-09-05

✨ feat: builder API — the vendor creates, suspends, enters and deletes schoolsAhmet Kaan Gümüş · 1ab298d
✨ feat: builder API — the vendor creates, suspends, enters and deletes schools

`POST /builder/login|logout`, `GET /builder/me`; `POST|GET /schools`,
`GET|PATCH|DELETE /schools/{slug}`, `POST /schools/{slug}/admin-password`,
`POST /schools/{slug}/enter`. Builder sessions live in the control database
behind their own strict per-IP login tier; deleting a school drops its
database and its files subtree.
✨ feat: one database per school behind a control registry; login names the schoolAhmet Kaan Gümüş · b7dfc0c
✨ feat: one database per school behind a control registry; login names the school

Namespace `hezarfen` now holds one DATABASE per school (name = slug) plus a
`control` database with the school registry, builder accounts and builder
sessions. `Tenants` keeps one separately-connected handle per school; the
shadow `web::tenant_state::State` resolves the school from the
`<slug>.<token>` cookie so every handler's `st.db` is school-scoped by
construction. `POST /auth/login` / `register` carry `school`; a suspended
school answers 403 everywhere. `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed the
vendor account; the boot admin seed is gone. No customers, no compat shims.

2026-08-13

📝 feat: generate README endpoint table from the served OpenAPI specAhmet Kaan Gümüş · bf8046e
📝 feat: generate README endpoint table from the served OpenAPI spec

tests/doc_sync.rs renders the 275-row table from /api-docs/openapi.json
(auth floor from declared 403s, else the handler's Require* extractor,
asserting exactly one floor per operation), drift-gated in the suite;
UPDATE_DOCS=1 regenerates. Static rows are router-verified and plain
.route() registrations must reach the table or the suite fails.
Curated prose folded into handler doc comments; CLAUDE.md convention
updated (table generated; full suite = cargo nextest run).

2026-08-02

fix: 🔩 clear the deferred backlog and ship class phase 2Ahmet Kaan Gümüş · afff737
fix: 🔩 clear the deferred backlog and ship class phase 2

Ten defects and two features, worked as one series because the doc
surfaces and the const table are shared.

Defects closed:

- Cross-exam answer-key leak. The bank copies `correct` into every
  instantiation, so reviewing exam A handed out the key to a question
  the caller was still writing in exam B. Review now blanks those
  questions rather than closing: the join matches on `from_bank` AND
  `banked_as` (a question can carry both — instantiated, then re-saved
  to the bank — so a coalesce misses a copy), redacting `correct`, the
  correctness flag and that question's `auto_score` share. Keyed on the
  template, never the exam, so the rest of the review reads normally.
- `set_role` was not atomic with its sweeps. The role write and every
  grant it invalidates now commit as one transaction; the board rooms
  are told after COMMIT from the cascade's own result slot. Built
  best-of-N; the losing charter left the one sweep outside whose failure
  strands an event seat no route can free.
- Board rosters held below-student ids, which 400d the creator's next
  roster PATCH. Repaired at boot, and a PATCH may now send back the
  roster it was served: an id already present that stopped qualifying is
  dropped, a new one still refused.
- `note_file` blobs leaked. The delete transaction returns the rows it
  removed and the handler unlinks exactly those, not a pre-read snapshot.
- Rate limiting failed open on a saturated map. Never-seen clients now
  share one metered overflow budget instead of arriving unmetered.
- Whiteboards: `GET /boards` takes `?open=`, `/strokes` no longer leaks
  a clear marker the socket filters out, and a locked board refuses its
  creator's clear (409) — the lock now means one thing on every path.
- Blueprint skips named the wrong record: `Attached::Gone` was two facts
  under one name, split into `Gone` (class) and `PivotGone` (course).

Features:

- Event audience `kind=class` — live from `class_member`, membership
  checked in one select because the (class, user) pair is the row id.
- Grade blueprints: a grade's course template, retro-pumped best-effort
  with a skip list. Attachments carry a provenance tag, so removal
  spares what a human placed. A course deleted out from under a
  blueprint is pruned from the template by the pump that finds it.

Forcing functions, because a hand-kept copy drifts:

- `protected_routes_require_session` is derived from the emitted
  OpenAPI: 248 -> 254 operations swept, was 80 typed by hand.
- Every JSON-bodied operation declares 422 (74 sites), pinned both ways
  — and multipart routes, which answer 400, are pinned to NOT declare it.
- The SurrealQL registration-freeze guard is pinned against the Rust it
  copies; both mutations of it fail the test.
- `migration_mark` gates one-time backfills. The roster repair rescanned
  every board against every user on every boot (773ms at 300/2000 with
  nothing to write); it is now skipped once done.

Verified by a three-lens verifier panel — which caught the `banked_as`
half of the answer-key leak by executing a probe, after the first fix
had been reported complete — and by a podman boot against the existing
volume: both new fields defined, the marker written, boot 2 skipping the
scan, and the live API answering on the new routes.

2026-07-30

chore: 🧹 drop the coordination for replicas we never runAhmet Kaan Gümüş · a9cfe7b
chore: 🧹 drop the coordination for replicas we never run

The backend runs as one process against one database, deployed
stop-the-world. The machinery that let several of them agree was built
ahead of a multi-replica rollout that stayed parked, so none of it was
ever load-bearing: the boot lease elected a leader out of a field of
one, the ai_worker table announced a worker to nobody, and the chat
claim queue only ever claimed its own writes.

Boot now migrates and seeds straight-line; a chat turn is dispatched by
the handler that accepted it; the 503 gate reads the in-process
registry. The retired columns and tables are unset and removed in
separate batches, repair before REMOVE.

What stays, with its reason corrected rather than removed: cap.rs,
field_update.rs, the refcounts, the CAS retry loops and the in-process
locks. Those close write skew between concurrent requests inside one
process, which two replicas made worse but never caused.

A turn orphaned by a restart or a panic is no longer reclaimed. It
settles as timed_out within CHATBOT_PENDING_STALE_SECS.

The design survives in the ledger if a second process is ever wanted.

2026-07-27

fix: 🪢 guard writes in the database, not the processAhmet Kaan Gümüş · 6c87eca
fix: 🪢 guard writes in the database, not the process

Two replicas are live; every process-local lock silently stopped
meaning anything. Move the invariants into the writes themselves:

- count caps (enroll/register/files/threads) become a counter column
  claimed by UPDATE .. WHERE n < cap (domain/cap.rs), backfilled once,
  decremented in the same transaction as every child delete
- exam freeze, re-draft and grade gates ride inside the write's own
  transaction (IF .. THROW); SESSION/WORK_ENTRY/EVENT locks die, range
  checks fold into the UPDATE's WHERE (FieldUpdate::ordered)
- appointment decisions CAS on status+proposed window+decided_by;
  bank/exam updates CAS on their editable columns
- rate limiter syncs local windows to a shared minute row every 2s,
  fail-open when the database is down
- paged GETs run LIMIT/START in the database (domain/page.rs); sites
  that post-filter in Rust stay web-sliced and say so
- exams.rs (3629 lines) splits into web/exams/{mod,attempts,questions,
  images,review}; image uploads single-source in web/image.rs; the
  bare-seq key rule lives once in domain/key.rs; migration SQL moves
  to migration_sql.rs

Every new guard is mutation-proven (removing it fails a named test).
Migration adds counter columns + rate_limit table; backfill is
one-time, guarded by = NONE, and verified against the live volume.

Traps recorded: SurrealQL 'x ?? 0 > 0' parses as 'x ?? (0 > 0)'; the
embedded mem engine drops one of two concurrent writes yet answers Ok.

2026-07-26

fix: 🆔 stop handing out a register id that matches no userAhmet Kaan Gümüş · 14334bc
fix: 🆔 stop handing out a register id that matches no user

The uniform-201 answer to a taken username carried a freshly minted ULID
so the two paths would look alike, which meant a client storing
`response.id` held an id resolving to nothing.

Register now answers `{username, role}` — the only facts true of both
paths — built once before the branch, so a divergent body is not
something a later edit can reintroduce by hand. The anti-enumeration
behaviour is unchanged: same 201, same bytes, argon2 still paid before
the availability check.

2026-07-25

feat: 📐 publish every hard limit instead of making the frontend guessAhmet Kaan Gümüş · 7152aa9
feat: 📐 publish every hard limit instead of making the frontend guess

Every bound the API enforces lived in one of two places the frontend
could not read: a `pub const` in `constant.rs`, or English prose in a
doc comment ("1–20 entries", "`1`–`100`"). So the frontend kept its own
copy of each number, and the copies drifted the moment one moved.

Two surfaces now carry them, because clients consume them two ways.
`GET /limits` is one JSON document grouped by resource, built by naming
the constants directly — a runtime fetch, no codegen step, and it
carries what OpenAPI holds awkwardly (`reserved_usernames`, the raster
`image_content_types`, the closed role/kind/mode/status sets). The spec
gets the other half: 105 `max_length`/`minimum`/`min_items` bounds on the
request DTOs, which is what `openapi-typescript` and friends turn into
validators for free.

`/limits` is unauthenticated — the register form needs the username and
password bounds before a session exists, and none of it is secret, it is
the same rule a 400 already spells out. It is also exempt from the
database guard: it reads no row, and a frontend booting against a
reconnecting backend is exactly when it needs the contract, not a 503
that sends it back to the hard-coded copy.

Its `rate` group is the one part that is not compile-time. The
rate-limit tiers are env-tunable, so the endpoint reports this server's
live values off `AppState` rather than the shipped defaults — a client
should learn its budget here, not by collecting a 429.

`MAX_CHATBOT_THREAD_TITLE_LEN` moves to `constant.rs` on the way past.
It was private in `domain/chatbot_thread.rs`, reaching neither surface,
and its own comment asked to be moved the next time anyone was here.

Three tests keep both surfaces honest, because each is a hand-kept
mirror and a mirror nothing checks is one that goes stale. A constant
must reach `/limits` or an exclusion list that states why it does not; a
bound may not be declared outside `constant.rs` at all; and the emitted
spec is fetched and compared field by field against the constants —
never against literals, which would just be a third copy that passes
while both are wrong. That last one is unavoidable rather than
belt-and-braces: utoipa 5.5 takes a literal only, so
`max_length = MAX_NOTE_TITLE_LEN` does not compile.

Two duplicated `maximum = 500` literals are now pinned to
`MAX_PAGE_LIMIT`, which `constant.rs` previously only asked a human to
keep in step.
fix: 🔑 bound argon2's memory, and stop register leaking usernamesAhmet Kaan Gümüş · d31f9ce
fix: 🔑 bound argon2's memory, and stop register leaking usernames

Two auth problems, both about a cost paid off the request path.

684f18b correctly moved argon2 onto `spawn_blocking`, but that pool is
unbounded: tokio grows it to 512 threads and argon2's default `m_cost`
is 19 MiB, so a distributed login flood could claim ~8.7 GB and get the
process OOM-killed. Before the move, concurrency was implicitly capped
at the 12 async workers. A semaphore of `nproc * 2` now gates all three
wrappers — 200 concurrent hashes drop from ~2.2 GB to ~0.63 GB peak RSS
with no wall-clock cost, since throughput was already core-bound. Both
login branches take a permit, and a (impossible) closed-semaphore error
maps exactly like a pool panic does, so no branch becomes
distinguishable by status.

The decoy hash is also pre-warmed at boot, off the runtime: it used to
initialise lazily, so the first unknown-username login paid two argon2
hashes instead of one and stood out.

`POST /auth/register` answered 409 on a taken username, which handed out
the entire user list to anyone unauthenticated and made the login-side
decoy that 684f18b preserved decorative. It now answers 201 with a body
shaped exactly like a real creation. The write is still rejected — only
the response is uniform. Register already hashed before the availability
check, so both paths already cost the same argon2 work; a comment and a
timing floor in the test pin that ordering, since reversing it would
re-open the oracle by latency.

Accepted cost, deliberately: a user who collides gets no distinct error.

The three tests that proved their point *via* the 409 could not just be
flipped to expect 201 — that would assert nothing. They now observe the
rejection where it is still visible: exactly one row exists, and the
first registration's password still logs in while the duplicate's is
refused. That is strictly stronger than the old assertion, which never
checked that the row had not been overwritten.
fix: 🔑 argon2 no longer starves the async runtime - hash and verify passwords on `spawn_blocking`; argon2 is deliberately CPU-expensive, so running it on an async worker stalled the whole runtime and pushed requests past `REQUEST_TIMEOUT_SECS` into a 503 - login verifies in the match arm instead of a match guard, since guards cannot await - the decoy verification that hides username enumeration moves off the runtime too, along with the one-time decoy hash - the seed's admin hash goes through the same path - make the blocking `hash`/`verify`/`verify_decoy` private so no request path can call them again by accidentAhmet Kaan Gümüş · cf04258
fix: 🔑 argon2 no longer starves the async runtime
- hash and verify passwords on `spawn_blocking`; argon2 is deliberately
  CPU-expensive, so running it on an async worker stalled the whole
  runtime and pushed requests past `REQUEST_TIMEOUT_SECS` into a 503
- login verifies in the match arm instead of a match guard, since guards
  cannot await
- the decoy verification that hides username enumeration moves off the
  runtime too, along with the one-time decoy hash
- the seed's admin hash goes through the same path
- make the blocking `hash`/`verify`/`verify_decoy` private so no request
  path can call them again by accident

2026-07-18

🔒 fix(cors): never send credentials in mirror modeAhmet Kaan Gümüş · 6faa816
🔒 fix(cors): never send credentials in mirror mode

Unset CORS_ALLOWED_ORIGINS reflected any origin AND advertised
allow-credentials — a credential-theft hole held shut only by the
cookie's SameSite=Lax, two independent switches guarding one door.

Mirror mode (dev) now runs uncredentialed; the allowlist branch keeps
credentials. cors_layer takes the allowlist as a parameter (env read
once in build_router) so tests drive both modes without env races.
Boot warns when COOKIE_SECURE is on without an allowlist. Cookie-using
browser frontends must list their origin in CORS_ALLOWED_ORIGINS —
including cross-port localhost dev setups.

2026-07-13

✨ feat(auth): strict username charset + reserved namesAhmet Kaan Gümüş · 4384914
✨ feat(auth): strict username charset + reserved names

Usernames accepted any ASCII between the length checks — control
characters, spaces, quotes, and HTML metacharacters all passed, which
enables log injection (\n, ESC), lookalike impersonation ('admin
support'), and stored XSS wherever a frontend renders names unescaped.

- allowlist: lowercase letters, digits, single interior . _ -
- must start and end with a letter or digit; no consecutive separators
- staff-looking names (admin, administrator, root, support, system,
  moderator, staff) rejected at /auth/register only — the
  ADMIN_USERNAME bootstrap still seeds them through the same newtype
- duplicate-register 409 kept: usernames are public handles, the
  existence leak is deliberate

Existing rows are not revalidated or migrated.

2026-07-11

✨ feat(web): axum handlers, DTOs, and auth extractorsAhmet Kaan Gümüş · 3c4822c
✨ feat(web): axum handlers, DTOs, and auth extractors

The HTTP layer over the domain. DTOs are plain strings on the wire;
handlers parse them into validated newtypes before touching the
database. Responses share one UserResponse shape (id, username, role).

Auth is a session cookie: login sets an HttpOnly, SameSite=Lax
`session` cookie (Secure when configured) backed by a server-side row;
logout is idempotent. Extractors encode access control by type —
CurrentUser for any logged-in caller, RequireTeacher / RequireAdmin
for role-gated routes — with the role re-read every request so a change
takes effect on the next call.

Routers: auth (register/login/logout/me), users (admin listing + role
changes), notes (per-user CRUD), events + attendance, and exams +
results. Ownership and role rules live in the handlers: event/exam
edits are creator-or-manager+, grading is teacher+ and never targets
oneself, and admins can't change their own role.