forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on 914d095f7fa0ebf0c3565bfc15c983bb719c19f2Filtered to src/web/notes.rsClear filter

2026-09-12

2026-09-11

🧹 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: 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-05

📝 fix: stop a demotion confiscating the owner's own notesAhmet Kaan Gümüş · 528403a
📝 fix: stop a demotion confiscating the owner's own notes

Every note and note-file route required `student`, on top of a query
already scoped to the owner. A demotion to `parent` therefore locked the
account out of its own notes: `GET /notes`, `PATCH`, `DELETE` and all
four file routes answered 403 to the owner. Nothing else in the crate
reads a note, `set_role` has no note arm and no route cascades one, so
the `note` rows, the `note_file` rows and their on-disk blobs were left
reachable and deletable by nobody, forever — with no per-user note cap
to bound the pile.

Notes are purely personal, own-scoped data: no school content, no second
reader. A role change must not confiscate them, so the role bar drops to
`CurrentUser` and the owner scoping that was always underneath it is now
the whole authorization. Nobody but the owner reaches a note or its
files; a stranger's id stays a 404, exactly as before. The note-file
routes were already safe to widen — every one of them re-derives the
owner by reading the note first and only then resolves the file under
that note, so a file is never reachable by id alone.

The utoipa 403s on the nine routes go with the bar (there is no 403 left
to answer), and the `notes` tag plus the README intro, roles section,
permission matrix and route table now say ownership rather than role.

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-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-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: 🧩 a PATCH writes only the fields it was givenAhmet Kaan Gümüş · 85b408e
fix: 🧩 a PATCH writes only the fields it was given

- every PATCH handler loaded the row and refilled the fields the
  request omitted from that stale snapshot, so two concurrent partial
  PATCHes touching different fields lost each other: whoever wrote
  last silently reverted a field it was never asked to change
- field-scoping the write did not fix this — the value bound to the
  SET still came from a stale read
- add domain/field_update.rs: .set(column, Option<T>) skips an absent
  field entirely, so it is neither written nor bound, and an all-absent
  PATCH writes nothing at all
- convert notes, events, terms, homework, work entries and courses,
  each with a 20-round concurrent-PATCH regression that fails against
  the old code on round 0 and passes after
- nullable columns stay clearable: an event's schedule, a course's
  capacity and term, and homework's assigned subset keep the
  double-option so an explicit null still writes NONE, while an
  omitted field is left alone
- homework's old fallback was worse than a no-op: it could re-narrow
  the assigned subset over a concurrent widening, behind the guard
  that exists to stop exactly that
- cross-field validation still reads the stored row where it must
  (event and term ranges need both ends) — read for the check, never
  written back
- HOMEWORK_LOCK was taken after the row read, so it never covered the
  read-modify-write it looked like it guarded

2026-07-22

2026-07-19

🐛 fix: authz holes and stale-read races from the bug huntAhmet Kaan Gümüş · de938d8
🐛 fix: authz holes and stale-read races from the bug hunt

- messages: a PATCH rejected on the folder no longer half-applies the
  read flag; the whole body validates before any write
- messages: the delete-from-trash gate rides in the UPDATE's WHERE
  instead of a check-then-act window
- notes: all nine handlers now require the student role — the read-only
  parent role could create notes and upload files (new RequireStudent)
- reports: a parent link whose student side changed role is inert;
  ensure_can_observe re-reads the target's live role like enrollments
- exams: update_exam takes the EXAM_LOCK writer lease before reading
  the row its merge defaults and draft/mode gates judge

Re-link keeping one tie while linked_by moves to the latest linker is
deliberate (matches re-enroll); doc reworded to say so.
✨ feat(exams): images on questions and choice optionsAhmet Kaan Gümüş · dbeb122
✨ feat(exams): images on questions and choice options

Teachers pin one illustration to any question (the map above the
prompt) and one picture per option on choice questions — the options
themselves can be images. Multipart upload per slot, replace by
re-upload, frozen with the question once attempts exist.

- rows in question_image (deterministic id per slot, UPSERT = replace);
  blobs beside note files under FILES_PATH, capped by max_file_bytes
- raster allowlist png/jpeg/webp/gif — SVG can script and these bytes
  render inline to students; served with nosniff + private, no-store
- students fetch bytes behind the sitting wall (enrollment + started
  attempt, no early peek); course managers anytime
- replacing a question's choices drops its option pictures (the
  illustration stays) — old pictures belong to the old options
- blob cleanup wired into image replace/delete and question, exam,
  and course deletes (exam cascade result slot shifted 5 -> 6)

2026-07-18

🐛 fix: six correctness holes from full-code auditAhmet Kaan Gümüş · ecbd550
🐛 fix: six correctness holes from full-code audit

- register response resolved people from {target, caller} only; a
  re-register returns the original placer's row, so registered_by
  degraded to a bare ULID username — resolve from the row itself
- note-file cap was count-then-write with no lock (SurrealDB does not
  conflict-check cross-record counts against inserts): concurrent
  uploads pushed a note past 10 files; the cap now lives inside
  NoteFile::insert under FILE_CAP_LOCK, web pre-check dropped
- ends_at-only registration events (pure signup deadlines) never closed
  signups; the gate read starts_at alone — close at starts_at ?? ends_at
- WorkEntry::check_out deleted the open row and created the closed one
  in separate calls — a failure between them silently destroyed the
  whole stint; take and re-file share one transaction now
- Exam::delete removed the exam row outside the child-cascade
  transaction — a failure left an empty exam shell; folded in
- ExamAttempt::start treated any create failure as a lost double-start
  and returned the latest attempt as a resume, passing a finished
  sitting off as 200 on a transient error; resume only when the
  read-back attempt is still in progress

Regression tests (failing-first) cover the first three; the remaining
three are fault-injection-only windows validated by the existing suites.

2026-07-15

✨ feat(notes): file attachments with school-set size capAhmet Kaan Gümüş · f1b532b
✨ feat(notes): file attachments with school-set size cap

Blobs live on disk under FILES_PATH (same volume as the DB), named by
the row's ULID so user input never shapes a path; the note_file row
keeps only metadata. DB-blob storage rejected: multi-MB PDFs bloat
surrealkv's LSM tree and buffer whole in RAM on every read.

- POST/GET /notes/{id}/files, GET/DELETE /notes/{id}/files/{file_id};
  owner-only through the owning note, staff included
- max_file_bytes in settings (1 KiB-25 MiB hard cap, default 5 MiB),
  enforced on streamed bytes (413), inside the settings CAS guard;
  option<int> so pre-field volumes boot without a backfill
- 10 files per note; deleting a note removes rows first, blobs after,
  so a crash strands at worst an unreachable blob
✨ feat(web)!: paginate every list endpointAhmet Kaan Gümüş · f3d2b0a
✨ feat(web)!: paginate every list endpoint

Every array-returning GET now accepts `?limit=&offset=` and returns a
`{ items, total, limit, offset }` envelope instead of a bare array.
Paging is opt-in: omitting `limit` returns the full list (limit echoes
null), so callers that need the whole set — an exam's questions during a
sitting, roster/grade pickers — are never silently truncated. `total`
always carries the unpaged count, so a frontend can render "100 of 256"
and drive a pager without a second request.

Windowing is a slice over the already-ordered domain list (the domain
layer is untouched); endpoints that embed people run that join over the
page alone. `limit` must be 1..=500 and `offset` >= 0 (else 400); an
offset past the end yields an empty page, not an error.

Covers all 17 list GETs, including /courses/me, /work/me, /work/{user},
and /users/search — whose hard 10-row cap is dropped in favour of the
same paging. Not paged: /exams/{id}/attempt/{questions,answers}, the
marks & attendance report objects, /exams/{id}/live, and /settings.

Shared machinery lives in web::page (Page<T>, PageParams, paginate).
Docs updated across the OpenAPI spec (utoipa query params + Page_*
response schemas), the Swagger UI it feeds, and the README (a Paging
section plus a `· paged` tag on every list row).

BREAKING CHANGE: list endpoints return a pagination envelope, not a bare
JSON array — clients must read `.items`. /users/search no longer caps at
10 results.

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.