forge
Explore
Log in

Don't you dare go Hollow

πŸ“ publish every hard limit instead of making the frontend guess

Browse files at this commit

7152aa9ae3d8acfe9130af8a734cb7b8ea39af9aAhmet Kaan GümüşParent: 61bd820
  • feat
    • πŸ“ publish every hard limit instead of making the frontend guess
Show full message
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.
README.mdmodified+114 -1
@@ -112,7 +112,11 @@ the client then polls the message or reads it off an SSE stream (see
112112
113113 Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)
114114 constructed only after its restrictions pass β€” invalid input can't be
115-represented. Those same types derive `surrealdb::types::SurrealValue`, so one
115+represented. Those restrictions are published rather than left to be guessed:
116+**`GET /limits`** (no auth) serves every fixed bound and closed value set the
117+API enforces, read straight from the constants the newtypes use, so a frontend
118+validates against the server's own rules instead of a hand-kept copy (see
119+"Validation limits"). Those same types derive `surrealdb::types::SurrealValue`, so one
116120 typed value flows from HTTP request into the `SCHEMAFULL` database. Record ids
117121 are ULIDs (time-sortable).
118122
@@ -240,6 +244,113 @@ Timezones and clock differences cannot corrupt data, by construction:
240244
241245 Keep the single server's clock NTP-synced; that's the only clock that matters.
242246
247+## Validation limits
248+
249+Every fixed bound the API enforces is published at `GET /limits` (no auth), so
250+a client never has to hard-code a copy that drifts the day a constant moves.
251+The handler reads `src/constant.rs` directly β€” a changed constant changes the
252+response in the same commit.
253+
254+```json
255+{
256+ "user": { "min_username_len": 3, "max_username_len": 32,
257+ "username_separators": [".", "_", "-"],
258+ "reserved_usernames": ["admin", "…"],
259+ "min_password_len": 6, "max_password_len": 128,
260+ "max_name_len": 100, "max_email_len": 254,
261+ "min_phone_digits": 7, "max_phone_digits": 15,
262+ "roles": ["parent", "student", "teacher", "manager", "admin"],
263+ "themes": ["light", "dark"], "languages": ["tr", "en"],
264+ "session_duration_days": 7 },
265+ "note": { "max_title_len": 200, "max_content_len": 10000, "max_files": 10 },
266+ "file": { "max_name_len": 255, "max_content_type_len": 100,
267+ "min_max_file_bytes": 1024, "max_max_file_bytes": 26214400,
268+ "default_max_file_bytes": 5242880,
269+ "image_content_types": ["image/png", "image/jpeg", "image/webp", "image/gif"] },
270+ "message": { "max_subject_len": 200, "max_body_len": 10000, "max_label_len": 50 },
271+ "event": { "max_title_len": 200, "max_description_len": 2000 },
272+ "course": { "kinds": ["course", "study", "club"], "max_title_len": 200, "…": 0 },
273+ "exam": { "modes": ["sync", "async", "open"],
274+ "question_kinds": ["choice", "text"],
275+ "min_duration_ms": 60000, "max_duration_ms": 86400000,
276+ "max_attempts": 100, "unlimited_attempts": 0,
277+ "min_mark": 0, "max_mark": 100, "…": 0 },
278+ "homework": { "statuses": ["done", "incomplete", "missing"],
279+ "max_files_per_submission": 10, "max_assigned": 200, "…": 0 },
280+ "question_pool": { "max_title_len": 200, "max_body_len": 10000, "max_solution_body_len": 10000 },
281+ "appointment": { "max_note_len": 500, "max_reason_len": 1000, "max_slot_occurrences": 52 },
282+ "chatbot": { "max_message_len": 8000, "max_thread_title_len": 200,
283+ "min_max_message_len": 100, "…": 0 },
284+ "settings": { "max_list_len": 20, "max_item_len": 50,
285+ "min_exam_kind_weight": 1, "max_exam_kind_weight": 100,
286+ "max_grade_bands": 20, "max_grade_label_len": 20,
287+ "required_attendance_statuses": ["present", "absent", "late", "excused"] },
288+ "request": { "max_page_limit": 500, "schedule_past_grace_ms": 60000,
289+ "request_timeout_secs": 30 },
290+ "rate": { "window_secs": 60, "auth_per_minute": 10,
291+ "api_per_minute": 300, "chatbot_per_minute": 20 }
292+}
293+```
294+
295+The `rate` group is the one part that is **not** compile-time: those tiers are
296+environment-tunable, so the endpoint serves *this* server's live values (read
297+from its running limiters), not the shipped defaults. `0` means the tier is
298+off. A client should read its budget here rather than discovering it by
299+collecting a `429`.
300+
301+### Two surfaces, one source
302+
303+The bounds are published twice, on purpose, because clients consume them two
304+different ways:
305+
306+| Surface | Shape | Use it when |
307+|---------|-------|-------------|
308+| `GET /limits` | One JSON document, grouped by resource, closed value sets included | Runtime fetch. No codegen step, survives a deploy skew, and carries things OpenAPI holds awkwardly (`reserved_usernames`, `image_content_types`) |
309+| `/api-docs/openapi.json` | Per-field `maxLength` / `minLength` / `minimum` / `maximum` / `maxItems` on the request schemas | Build-time codegen β€” `openapi-typescript`, `orval`, and friends turn these into types *and* validators automatically |
310+
311+Both are generated from the same `src/constant.rs`, and **neither is allowed to
312+drift from it**, which is enforced rather than asked for:
313+
314+- `tests/limits_completeness.rs` parses every `pub const` out of `constant.rs`
315+ and fails unless each one is either referenced by `src/web/limits.rs` or
316+ listed as a deliberate exclusion *with a reason*. A new constant breaks the
317+ suite until someone decides, consciously, whether clients need it.
318+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 104 published
319+ bounds back out of the emitted JSON, and asserts each equals its constant.
320+ This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal
321+ only** β€” a `const` there does not compile β€” so the annotations are
322+ unavoidably a second copy of each number. The test is what makes that copy
323+ safe. It also pins the `limit` query parameter's `maximum` to
324+ `MAX_PAGE_LIMIT`, a duplication `constant.rs` previously only *asked* a human
325+ to maintain.
326+- A third check in `limits_completeness.rs` refuses to let a validation bound
327+ be declared **outside** `constant.rs` at all. Without it a limit can hide in
328+ a domain module and reach neither surface β€” which is exactly where
329+ `MAX_CHATBOT_THREAD_TITLE_LEN` was found sitting, private and unpublished.
330+
331+Notes:
332+
333+- **No auth.** The registration and login forms need the username and password
334+ bounds before a session exists, and none of these are secrets β€” they are the
335+ same rules a `400` already spells out in prose.
336+- **Answers during a database outage.** `/limits` touches no row, so it is
337+ exempt from the guard that answers `503` while the database reconnects β€” a
338+ frontend booting against a degraded backend is exactly when it needs the
339+ contract. Every route that does read the database still refuses.
340+- **Fetch once.** The values are compile-time constants, so the response only
341+ changes with a deploy. Cache it for the session; the `ETag`/`304` path makes
342+ a revalidation cheap if you'd rather re-check.
343+- **`/limits` is not `/settings`.** School-adjustable policy β€” the exam kinds
344+ and their weights, the attendance statuses, the grade bands, the live
345+ `max_file_bytes` and chatbot knobs β€” is on `GET /settings` and changes when a
346+ manager edits it. What `/limits` carries for those knobs is the fixed range a
347+ manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the
348+ attendance statuses no school may remove.
349+- **Closed value sets ride along.** `roles`, `themes`, `languages`, course
350+ `kinds`, exam `modes`, `question_kinds`, homework `statuses`, and the
351+ uploadable `image_content_types` are the exact accepted spellings β€” build
352+ pickers from these rather than from a literal list.
353+
243354 ## Rate limiting
244355
245356 Requests are limited per client IP over a fixed 60-second window, in two tiers:
@@ -449,6 +560,7 @@ window filtering, before paging; negative values are a `400` naming the field.
449560 | GET | `/health` | no | Liveness check |
450561 | GET | `/` | no | Same as `/health` |
451562 | GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |
563+| GET | `/limits` | no | Every fixed validation bound, grouped by resource β€” see Validation limits |
452564 | GET | `/swagger` | no | Interactive API docs (Swagger UI) |
453565 | GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |
454566 | GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |
@@ -1987,6 +2099,7 @@ src/
19872099 courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs
19882100 bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs
19892101 settings.rs terms.rs ai.rs chatbot.rs
2102+ limits.rs GET /limits: every constant.rs bound served as JSON
19902103 ```
19912104
19922105 Tests: `cargo test` β€” unit (in-source), integration (`tower::oneshot` + in-memory
src/constant.rsmodified+4 -0
@@ -307,6 +307,10 @@ pub const DEFAULT_MAX_CHATBOT_MESSAGE_LEN: i64 = 4_000;
307307 pub const MIN_MAX_CHATBOT_MESSAGE_LEN: i64 = 100;
308308 pub const MAX_MAX_CHATBOT_MESSAGE_LEN: i64 = MAX_CHATBOT_MESSAGE_LEN as i64;
309309
310+/// Bound on a chat thread's display name. A thread is named by hand or not at
311+/// all β€” nothing auto-titles one β€” so this only has to fit a line a user typed.
312+pub const MAX_CHATBOT_THREAD_TITLE_LEN: usize = 200;
313+
310314 /// How many prior user/assistant turns of a thread are replayed to the
311315 /// AI service as context (`chatbot_history_turns` in settings): its default and
312316 /// the inclusive range a manager may set. Every turn is re-sent on every
src/domain/chatbot_thread.rsmodified+1 -5
@@ -7,6 +7,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
77 use tokio::sync::Mutex;
88 use ulid::Ulid;
99
10+use crate::constant::MAX_CHATBOT_THREAD_TITLE_LEN;
1011 use crate::database::{CHATBOT_THREAD_TABLE, Database};
1112 use crate::domain::settings::Settings;
1213 use crate::domain::timestamp::Timestamp;
@@ -20,11 +21,6 @@ use crate::validate::validate_required;
2021 /// inserts. Same reasoning, and the same shape, as `ENROLL_LOCK`.
2122 static CHATBOT_THREAD_LOCK: Mutex<()> = Mutex::const_new(());
2223
23-/// Bound on a thread's display name. Local to this module because
24-/// `constant.rs` is another task's file; move it there with the rest of the
25-/// chat limits when they are next touched.
26-const MAX_CHATBOT_THREAD_TITLE_LEN: usize = 200;
27-
2824 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
2925 pub struct ChatbotThreadId(RecordId);
3026
src/lib.rsmodified+11 -2
@@ -35,11 +35,11 @@ use crate::state::AppState;
3535 info(
3636 title = "Hezarfen Backend API",
3737 version = env!("CARGO_PKG_VERSION"),
38- description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents β€” stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images β€” an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only β€” staff run them, they don't take part. Every event carries an audience β€” the whole school, one role, a course's enrollment, or a registration list β€” that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds β€” `course` (a regular class), `study` (a supervised study session β€” etΓΌt), and `club` (a student club β€” kulΓΌp) β€” may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) β€” an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole class or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences β€” theme (`light`/`dark`) and language (`tr`/`en`) β€” self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports β€” and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem β€” same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it β€” rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it β€” text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze β€” and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason β€” the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts β€” a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one β€” one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` β€” transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope β€” paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.",
38+ description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents β€” stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images β€” an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only β€” staff run them, they don't take part. Every event carries an audience β€” the whole school, one role, a course's enrollment, or a registration list β€” that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds β€” `course` (a regular class), `study` (a supervised study session β€” etΓΌt), and `club` (a student club β€” kulΓΌp) β€” may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) β€” an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole class or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences β€” theme (`light`/`dark`) and language (`tr`/`en`) β€” self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports β€” and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem β€” same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it β€” rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it β€” text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze β€” and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason β€” the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts β€” a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one β€” one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` β€” transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope β€” paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound β€” field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) β€” is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down β€” a client booting against a degraded backend still gets the contract.",
3939 ),
4040 modifiers(&SecurityAddon),
4141 tags(
42- (name = "meta", description = "Liveness and service metadata"),
42+ (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /limits` publishes every fixed bound the API enforces β€” field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) β€” so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off)"),
4343 (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling β€” public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
4444 (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are indistinguishable (the taken one carries a throwaway id that resolves to no row) β€” a deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"),
4545 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner β€” nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed β€” or its name cleared β€” with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) β€” both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` β€” the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no AI service connected, sending answers `503` and writes nothing"),
@@ -89,6 +89,7 @@ pub fn build_router(state: AppState) -> Router {
8989 .route("/", get(health))
9090 .routes(routes!(health))
9191 .routes(routes!(server_time))
92+ .merge(web::limits::routes())
9293 .nest("/ai", web::ai::routes())
9394 .nest("/auth", web::auth::routes(&state.rate_limit))
9495 .nest("/chatbot", web::chatbot::routes())
@@ -166,6 +167,14 @@ pub fn build_router(state: AppState) -> Router {
166167 /// both return their response immediately and do the work afterwards, so
167168 /// neither is measured against the timeout.
168169 async fn db_guard(health: state::DbHealth, req: Request, next: Next) -> Response {
170+ // `/limits` never touches the database β€” it serializes constants and this
171+ // process's own configuration. Refusing it during an outage would be a
172+ // pure own-goal: a frontend booting into a degraded backend is exactly
173+ // when it needs the validation contract, and answering `503` would push it
174+ // back to the hard-coded copy this endpoint exists to delete.
175+ if req.uri().path() == "/limits" {
176+ return next.run(req).await;
177+ }
169178 if !health.is_up() {
170179 return AppError::DbUnavailable.into_response();
171180 }
src/rate_limit.rsmodified+9 -0
@@ -86,6 +86,15 @@ struct Bucket {
8686 count: u32,
8787 }
8888
89+impl<K> RateLimiter<K> {
90+ /// Requests allowed per window, `0` meaning the tier is off. Read by
91+ /// `GET /limits` so a client learns its own budget instead of discovering
92+ /// it by getting a `429`.
93+ pub fn max_per_window(&self) -> u32 {
94+ self.max
95+ }
96+}
97+
8998 /// The per-user tier, keyed by user record key instead of client IP. Lives in
9099 /// [`crate::state::AppState`] and is called from inside a handler, after
91100 /// `CurrentUser` has identified the caller.
src/web/appointments.rsmodified+4 -3
@@ -43,6 +43,7 @@ struct PublishSlots {
4343 starts_at: i64,
4444 ends_at: i64,
4545 /// Free-text hint shown to requesters ("office hours", "veli gârüşmesi").
46+ #[schema(max_length = 500)]
4647 note: Option<String>,
4748 /// Repeat the same window every week up to and including `until`.
4849 #[serde(default)]
@@ -58,7 +59,7 @@ struct BookAppointment {
5859 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
5960 slot: String,
6061 /// Why you want the meeting β€” required, the teacher decides on it.
61- #[schema(example = "Ders notlarını konuşmak istiyorum")]
62+ #[schema(max_length = 1000, example = "Ders notlarını konuşmak istiyorum")]
6263 reason: String,
6364 }
6465
@@ -66,7 +67,7 @@ struct BookAppointment {
6667 struct CancelRequest {
6768 /// Optional free-text reason. Blank or absent records no reason; over-long
6869 /// (past `MAX_APPOINTMENT_REASON_LEN`) answers `400`.
69- #[schema(example = "Rahatsızlandım, katılamayacağım")]
70+ #[schema(max_length = 1000, example = "Rahatsızlandım, katılamayacağım")]
7071 reason: Option<String>,
7172 }
7273
@@ -74,7 +75,7 @@ struct CancelRequest {
7475 struct RejectRequest {
7576 /// Optional free-text reason. Blank or absent records no reason; over-long
7677 /// (past `MAX_APPOINTMENT_REASON_LEN`) answers `400`.
77- #[schema(example = "Bu saatte müsait değilim")]
78+ #[schema(max_length = 1000, example = "Bu saatte müsait değilim")]
7879 reason: Option<String>,
7980 }
8081
src/web/auth.rsmodified+2 -2
@@ -39,9 +39,9 @@ pub fn routes(rate_limit: &RateLimitConfig) -> OpenApiRouter<AppState> {
3939
4040 #[derive(Deserialize, ToSchema)]
4141 struct Credentials {
42- #[schema(example = "ada")]
42+ #[schema(example = "ada", min_length = 3, max_length = 32)]
4343 username: String,
44- #[schema(example = "correct horse battery")]
44+ #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
4545 password: String,
4646 }
4747
src/web/bank_questions.rsmodified+6 -3
@@ -94,17 +94,18 @@ struct CreateBankQuestion {
9494 /// template is instantiated.
9595 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
9696 subject_id: String,
97- #[schema(example = "What is 2 + 2?")]
97+ #[schema(example = "What is 2 + 2?", max_length = 2000)]
9898 text: String,
9999 /// `choice` or `text`.
100100 #[schema(example = "choice")]
101101 kind: String,
102102 /// This template's default point value, `1`–`100`.
103- #[schema(example = 10)]
103+ #[schema(example = 10, minimum = 1, maximum = 100)]
104104 points: i64,
105105 /// The options of a `choice` question (2–10 of them); omit for `text`.
106106 /// Each carries an `id` naming it within this payload β€” the server mints
107107 /// the stored ids and returns them.
108+ #[schema(min_items = 2, max_items = 10)]
108109 choices: Option<Vec<ChoiceBody>>,
109110 /// The `id` of the right option, as sent in `choices`; required for
110111 /// `choice`, absent for `text`.
@@ -117,7 +118,9 @@ struct UpdateBankQuestion {
117118 /// Re-tag the template's origin subject. Omit to keep the current one
118119 /// (which is `null` if that subject has since been deleted).
119120 subject_id: Option<String>,
121+ #[schema(max_length = 2000)]
120122 text: Option<String>,
123+ #[schema(minimum = 1, maximum = 100)]
121124 points: Option<i64>,
122125 /// `choice` or `text`. Switching kinds needs the other fields to follow:
123126 /// send `choices` + `correct` when moving to `choice`, explicit `null`s
@@ -128,7 +131,7 @@ struct UpdateBankQuestion {
128131 /// with to keep it β€” its picture rides along. Only options whose id is
129132 /// absent from the new list lose their picture.
130133 #[serde(default, deserialize_with = "set_or_clear")]
131- #[schema(value_type = Option<Vec<ChoiceBody>>)]
134+ #[schema(value_type = Option<Vec<ChoiceBody>>, min_items = 2, max_items = 10)]
132135 choices: Option<Option<Vec<ChoiceBody>>>,
133136 /// The `id` of the right option. Omit to keep; `null` to clear (text
134137 /// questions only).
src/web/chatbot.rsmodified+9 -5
@@ -63,7 +63,7 @@ const MIN_CHUNK_CHARS: usize = 24;
6363 struct CreateChatbotThread {
6464 /// Optional thread name, up to 200 characters. Blank counts as absent β€”
6565 /// an untitled thread is normal (the UI labels it from its first turn).
66- #[schema(example = "Fizik ΓΆdevi")]
66+ #[schema(max_length = 200, example = "Fizik ΓΆdevi")]
6767 title: Option<String>,
6868 }
6969
@@ -164,7 +164,7 @@ async fn list_threads(
164164 struct RenameChatbotThread {
165165 /// The new name, up to 200 characters. `null` β€” or blank β€” clears it back
166166 /// to untitled, the same rule the create route applies.
167- #[schema(example = "Fizik ΓΆdevi")]
167+ #[schema(max_length = 200, example = "Fizik ΓΆdevi")]
168168 title: Option<String>,
169169 }
170170
@@ -240,9 +240,13 @@ async fn own_thread(id: &str, user: &UserId, db: &Database) -> Result<ChatbotThr
240240
241241 #[derive(Deserialize, ToSchema)]
242242 struct SendChatbotMessage {
243- /// What to ask. Required, and capped by the school's
244- /// `max_chatbot_message_len` (`GET /settings`).
245- #[schema(example = "Newton'un ikinci yasasΔ±nΔ± aΓ§Δ±klar mΔ±sΔ±n?")]
243+ /// What to ask. Required. `maxLength` here is the server's hard ceiling;
244+ /// the live cap is the school's `max_chatbot_message_len` (`GET /settings`),
245+ /// which is always at or below it.
246+ #[schema(
247+ example = "Newton'un ikinci yasasΔ±nΔ± aΓ§Δ±klar mΔ±sΔ±n?",
248+ max_length = 8_000
249+ )]
246250 content: String,
247251 }
248252
src/web/courses.rsmodified+15 -8
@@ -56,8 +56,9 @@ pub fn routes() -> OpenApiRouter<AppState> {
5656
5757 #[derive(Deserialize, ToSchema)]
5858 struct CreateCourse {
59- #[schema(example = "Algebra")]
59+ #[schema(max_length = 200, example = "Algebra")]
6060 title: String,
61+ #[schema(max_length = 2000)]
6162 description: Option<String>,
6263 /// `course` (a regular class β€” the default), `study` (a supervised study
6364 /// session β€” etΓΌt), or `club` (a student club β€” kulΓΌp). Behaviorally
@@ -73,7 +74,9 @@ struct CreateCourse {
7374
7475 #[derive(Deserialize, ToSchema)]
7576 struct UpdateCourse {
77+ #[schema(max_length = 200)]
7678 title: Option<String>,
79+ #[schema(max_length = 2000)]
7780 description: Option<String>,
7881 /// `course`, `study` (etΓΌt), or `club` (kulΓΌp). Omit to keep the current
7982 /// kind.
@@ -108,14 +111,15 @@ struct AssignTeacher {
108111
109112 #[derive(Deserialize, ToSchema)]
110113 struct CreateExamInCourse {
111- #[schema(example = "Midterm")]
114+ #[schema(max_length = 200, example = "Midterm")]
112115 title: String,
116+ #[schema(max_length = 2000)]
113117 description: Option<String>,
114118 /// The assessment form β€” one of the school's exam kinds (`GET /settings`;
115119 /// defaults: `homework`, `quiz`, `midterm`, `final`, `project`, `oral`).
116120 /// The kind's settings-configured weight decides how heavily the exam
117121 /// counts into the course average.
118- #[schema(example = "midterm")]
122+ #[schema(max_length = 50, example = "midterm")]
119123 kind: String,
120124 /// `sync` (one fixed window for everyone), `async` (each student starts
121125 /// inside the window and gets `duration_ms`), or `open` (no window β€” sit
@@ -131,11 +135,11 @@ struct CreateExamInCourse {
131135 ends_at: Option<i64>,
132136 /// Per-attempt time budget, milliseconds β€” required for `async`, optional
133137 /// for `open` (omit for unlimited time), forbidden for `sync`.
134- #[schema(example = 5_400_000_i64)]
138+ #[schema(minimum = 60_000, maximum = 86_400_000, example = 5_400_000_i64)]
135139 duration_ms: Option<i64>,
136140 /// How many attempts each student gets, `1`–`100`, or `0` for unlimited.
137141 /// Defaults to `1` β€” the classic single sitting.
138- #[schema(example = 1)]
142+ #[schema(minimum = 0, maximum = 100, example = 1)]
139143 max_attempts: Option<i64>,
140144 /// Whether a student who left the exam room may come back in and keep
141145 /// answering. Defaults to `true`; editable live while the exam runs.
@@ -893,8 +897,9 @@ async fn list_course_exams(
893897
894898 #[derive(Deserialize, ToSchema)]
895899 struct CreateSubject {
896- #[schema(example = "Limits and continuity")]
900+ #[schema(max_length = 200, example = "Limits and continuity")]
897901 name: String,
902+ #[schema(max_length = 2000)]
898903 description: Option<String>,
899904 }
900905
@@ -987,8 +992,9 @@ async fn list_course_subjects(
987992
988993 #[derive(Deserialize, ToSchema)]
989994 struct CreateHomework {
990- #[schema(example = "Read chapter 3 and answer Q1-Q5")]
995+ #[schema(max_length = 200, example = "Read chapter 3 and answer Q1-Q5")]
991996 title: String,
997+ #[schema(max_length = 2000)]
992998 description: Option<String>,
993999 /// The course subject this homework belongs to
9941000 /// (`GET /courses/{id}/subjects`). Required β€” every homework is tagged with
@@ -1002,6 +1008,7 @@ struct CreateHomework {
10021008 /// The students this homework is for: a list of enrolled student ids. Omit,
10031009 /// send `null`, or send `[]` to assign the whole enrolled course (whoever is
10041010 /// enrolled when they submit); a subset caps at 200 named students.
1011+ #[schema(max_items = 200)]
10051012 assigned: Option<Vec<String>>,
10061013 }
10071014
@@ -1120,7 +1127,7 @@ async fn list_course_homework(
11201127 #[derive(Deserialize, ToSchema)]
11211128 struct CreateSessionInCourse {
11221129 /// What the lesson covers. Optional.
1123- #[schema(example = "Limits and continuity")]
1130+ #[schema(max_length = 200, example = "Limits and continuity")]
11241131 topic: Option<String>,
11251132 /// Who teaches the session. Defaults to the caller; must hold the
11261133 /// `teacher` role or higher.
src/web/events.rsmodified+5 -2
@@ -124,8 +124,9 @@ impl AudienceDto {
124124
125125 #[derive(Deserialize, ToSchema)]
126126 struct CreateEvent {
127- #[schema(example = "Sprint demo")]
127+ #[schema(max_length = 200, example = "Sprint demo")]
128128 title: String,
129+ #[schema(max_length = 2000)]
129130 description: Option<String>,
130131 /// Who the event is for (its expected-attendee roster). Omit for a
131132 /// school-wide event.
@@ -138,7 +139,9 @@ struct CreateEvent {
138139
139140 #[derive(Deserialize, ToSchema)]
140141 struct UpdateEvent {
142+ #[schema(max_length = 200)]
141143 title: Option<String>,
144+ #[schema(max_length = 2000)]
142145 description: Option<String>,
143146 /// Replaces the audience wholesale when present; omit to keep the current
144147 /// one. Attendance rows for people the change drops out of the roster stay
@@ -160,7 +163,7 @@ struct UpdateEvent {
160163 struct MarkAttendance {
161164 /// One of the school's attendance statuses (`GET /settings`; the core
162165 /// four are `present`, `absent`, `late`, `excused`).
163- #[schema(example = "present")]
166+ #[schema(max_length = 50, example = "present")]
164167 status: String,
165168 /// Target user id β€” must be in the event's audience. Defaults to the
166169 /// caller when omitted.
src/web/exams.rsmodified+13 -6
@@ -136,7 +136,9 @@ pub fn routes() -> OpenApiRouter<AppState> {
136136
137137 #[derive(Deserialize, ToSchema)]
138138 struct UpdateExam {
139+ #[schema(max_length = 200)]
139140 title: Option<String>,
141+ #[schema(max_length = 2000)]
140142 description: Option<String>,
141143 /// The assessment form β€” one of the school's exam kinds (`GET /settings`).
142144 /// Changing it re-weights the exam: the course average uses the kind's
@@ -164,11 +166,12 @@ struct UpdateExam {
164166 /// to keep; `null` to clear. Changing it mid-exam moves every running
165167 /// attempt's deadline.
166168 #[serde(default, deserialize_with = "set_or_clear")]
167- #[schema(value_type = Option<i64>)]
169+ #[schema(value_type = Option<i64>, minimum = 60000, maximum = 86400000)]
168170 duration_ms: Option<Option<i64>>,
169171 /// Attempt limit: `1`–`100`, or `0` for unlimited. Omit to keep. Editable
170172 /// live β€” raising it grants retakes on the spot; lowering it only blocks
171173 /// future starts.
174+ #[schema(minimum = 0, maximum = 100)]
172175 max_attempts: Option<i64>,
173176 /// Whether students who left the exam room may come back in. Omit to
174177 /// keep. Editable live β€” the teacher's door handle for the running room.
@@ -185,7 +188,7 @@ struct UpdateExam {
185188 #[derive(Deserialize, ToSchema)]
186189 struct GradeResult {
187190 /// The mark to record, `0`–`100`.
188- #[schema(example = 85)]
191+ #[schema(example = 85, minimum = 0, maximum = 100)]
189192 mark: i64,
190193 /// The student being graded.
191194 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
@@ -1332,17 +1335,18 @@ struct CreateQuestion {
13321335 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
13331336 subject_id: String,
13341337 /// The question itself.
1335- #[schema(example = "What is 2 + 2?")]
1338+ #[schema(example = "What is 2 + 2?", max_length = 2000)]
13361339 text: String,
13371340 /// `choice` or `text`.
13381341 #[schema(example = "choice")]
13391342 kind: String,
13401343 /// This question's share of the auto-score, `1`–`100`.
1341- #[schema(example = 10)]
1344+ #[schema(example = 10, minimum = 1, maximum = 100)]
13421345 points: i64,
13431346 /// The options of a `choice` question (2–10 of them); omit for `text`.
13441347 /// Each carries an `id` naming it within this payload β€” the server mints
13451348 /// the stored ids and returns them.
1349+ #[schema(min_items = 2, max_items = 10)]
13461350 choices: Option<Vec<ChoiceBody>>,
13471351 /// The `id` of the right option, as sent in `choices`; required for
13481352 /// `choice`, absent for `text`.
@@ -1356,7 +1360,9 @@ struct UpdateQuestion {
13561360 /// keep the current one β€” a question always has a subject, so there is no
13571361 /// clearing it.
13581362 subject_id: Option<String>,
1363+ #[schema(max_length = 2000)]
13591364 text: Option<String>,
1365+ #[schema(minimum = 1, maximum = 100)]
13601366 points: Option<i64>,
13611367 /// `choice` or `text`. Switching kinds needs the other fields to follow:
13621368 /// send `choices` + `correct` when moving to `choice`, explicit `null`s
@@ -1368,7 +1374,7 @@ struct UpdateQuestion {
13681374 /// absent from the new list lose their picture, so reordering, renaming,
13691375 /// and deleting one option leave the rest untouched.
13701376 #[serde(default, deserialize_with = "set_or_clear")]
1371- #[schema(value_type = Option<Vec<ChoiceBody>>)]
1377+ #[schema(value_type = Option<Vec<ChoiceBody>>, min_items = 2, max_items = 10)]
13721378 choices: Option<Option<Vec<ChoiceBody>>>,
13731379 /// The `id` of the right option. Omit to keep; `null` to clear (text
13741380 /// questions only).
@@ -2635,6 +2641,7 @@ struct SaveAnswer {
26352641 /// The picked option's `id` β€” required for `choice` questions.
26362642 selected: Option<String>,
26372643 /// The typed answer β€” required for `text` questions (empty clears the draft).
2644+ #[schema(max_length = 10000)]
26382645 text: Option<String>,
26392646 }
26402647
@@ -3218,7 +3225,7 @@ async fn delete_answer_image(
32183225 // as answered. A typed answer keeps its row.
32193226 if let Some(answer) = ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db).await? {
32203227 let blank = answer.get_selected().is_none()
3221- && answer.get_text().map_or(true, |t| t.as_str().is_empty());
3228+ && answer.get_text().is_none_or(|t| t.as_str().is_empty());
32223229 if blank {
32233230 ExamAnswer::delete(question.get_id(), user.get_id(), seq, &st.db).await?;
32243231 }
src/web/homework.rsmodified+8 -3
@@ -239,10 +239,11 @@ async fn get_homework(
239239 #[derive(Deserialize, ToSchema)]
240240 struct UpdateHomework {
241241 /// Re-title. Omit to keep the current title.
242+ #[schema(max_length = 200)]
242243 title: Option<String>,
243244 /// Re-describe. Omit to keep; send `null` (or `""`) to clear.
244245 #[serde(default, deserialize_with = "set_or_clear")]
245- #[schema(value_type = Option<String>)]
246+ #[schema(value_type = Option<String>, max_length = 2_000)]
246247 description: Option<Option<String>>,
247248 /// New due date, UTC unix-milliseconds. Omit to keep; a newly set value
248249 /// must not be in the past (a kept one may already be past).
@@ -256,7 +257,7 @@ struct UpdateHomework {
256257 /// / `null` for the whole course. Omit to keep. Narrowing is refused (409)
257258 /// while it would orphan a student who already submitted or was graded.
258259 #[serde(default, deserialize_with = "set_or_clear")]
259- #[schema(value_type = Option<Vec<String>>)]
260+ #[schema(value_type = Option<Vec<String>>, max_items = 200)]
260261 assigned: Option<Option<Vec<String>>>,
261262 }
262263
@@ -564,7 +565,10 @@ struct SubmitHomework {
564565 /// replaces any previous text, and omitting it (or sending `""`) clears it.
565566 /// Files are managed separately via `.../submission/files` and are never
566567 /// touched here.
567- #[schema(example = "Answers to questions 1–4 are in the attached photo.")]
568+ #[schema(
569+ example = "Answers to questions 1–4 are in the attached photo.",
570+ max_length = 5_000
571+ )]
568572 text: Option<String>,
569573 }
570574
@@ -951,6 +955,7 @@ struct GradeHomework {
951955 status: String,
952956 /// An optional 0–100 mark on top of the status; omit to grade on status
953957 /// alone.
958+ #[schema(minimum = 0, maximum = 100)]
954959 mark: Option<i64>,
955960 }
956961
src/web/limits.rsadded+417 -0
@@ -0,0 +1,417 @@
1+//! `GET /limits` β€” every compile-time validation bound, served as data.
2+//!
3+//! The frontend has to enforce the same rules the newtypes do (a `maxlength`
4+//! on an input, a client-side check before a doomed request). Hard-coding them
5+//! there means two copies that silently drift apart the day one moves. This
6+//! endpoint is the single source: every field below reads a `crate::constant`
7+//! item directly, so a changed constant changes the response in the same
8+//! commit.
9+//!
10+//! School-adjustable policy (exam kinds, attendance statuses, grade bands, the
11+//! live `max_file_bytes`) lives in `GET /settings` β€” this route carries only
12+//! the fixed bounds those settings must themselves stay inside.
13+
14+use axum::Json;
15+use axum::extract::State;
16+use serde::Serialize;
17+use utoipa::ToSchema;
18+use utoipa_axum::router::OpenApiRouter;
19+use utoipa_axum::routes;
20+
21+use crate::constant::*;
22+use crate::domain::preferences::{Language, Theme};
23+use crate::domain::role::Role;
24+use crate::state::AppState;
25+
26+pub fn routes() -> OpenApiRouter<AppState> {
27+ OpenApiRouter::new().routes(routes!(get_limits))
28+}
29+
30+/// Account fields: credentials, profile, and the closed role set.
31+#[derive(Serialize, ToSchema)]
32+struct UserLimits {
33+ min_username_len: usize,
34+ max_username_len: usize,
35+ /// Separators allowed inside a username β€” never at the edges, never doubled.
36+ #[schema(example = json!([".", "_", "-"]))]
37+ username_separators: Vec<String>,
38+ /// Names `POST /auth/register` refuses (they read as staff).
39+ reserved_usernames: Vec<&'static str>,
40+ min_password_len: usize,
41+ max_password_len: usize,
42+ max_name_len: usize,
43+ max_email_len: usize,
44+ /// Digit count, ignoring spaces and punctuation.
45+ min_phone_digits: usize,
46+ max_phone_digits: usize,
47+ /// Every role, lowest privilege first.
48+ #[schema(example = json!(["parent", "student", "teacher", "manager", "admin"]))]
49+ roles: Vec<&'static str>,
50+ /// Accepted `theme` preference values (`null` clears it).
51+ #[schema(example = json!(["light", "dark"]))]
52+ themes: Vec<&'static str>,
53+ /// Accepted `language` preference values (`null` clears it).
54+ #[schema(example = json!(["tr", "en"]))]
55+ languages: Vec<&'static str>,
56+ /// How long a login session stays valid, days.
57+ session_duration_days: i64,
58+}
59+
60+/// Note bodies and their attachments.
61+#[derive(Serialize, ToSchema)]
62+struct NoteLimits {
63+ max_title_len: usize,
64+ max_content_len: usize,
65+ /// How many files one note may carry.
66+ max_files: usize,
67+}
68+
69+/// Uploaded-file metadata, shared by every upload route.
70+#[derive(Serialize, ToSchema)]
71+struct FileLimits {
72+ max_name_len: usize,
73+ max_content_type_len: usize,
74+ /// Inclusive range a manager may set `max_file_bytes` to in `/settings`;
75+ /// the live value is on `GET /settings`, this is the hard ceiling above it.
76+ min_max_file_bytes: i64,
77+ max_max_file_bytes: i64,
78+ default_max_file_bytes: i64,
79+ /// Content types an inline image (question illustrations, option pictures,
80+ /// pool photos, answer drawings) may declare. Raster only β€” no SVG.
81+ #[schema(example = json!(["image/png", "image/jpeg", "image/webp", "image/gif"]))]
82+ image_content_types: Vec<&'static str>,
83+}
84+
85+/// One-to-one messages.
86+#[derive(Serialize, ToSchema)]
87+struct MessageLimits {
88+ max_subject_len: usize,
89+ max_body_len: usize,
90+ /// The sender's optional free-text badge.
91+ max_label_len: usize,
92+}
93+
94+/// Events and their registration lists.
95+#[derive(Serialize, ToSchema)]
96+struct EventLimits {
97+ max_title_len: usize,
98+ max_description_len: usize,
99+}
100+
101+/// Courses, their curriculum subjects, and lesson sessions.
102+#[derive(Serialize, ToSchema)]
103+struct CourseLimits {
104+ max_title_len: usize,
105+ max_description_len: usize,
106+ /// The only accepted `kind` values β€” behaviorally identical labels.
107+ #[schema(example = json!(["course", "study", "club"]))]
108+ kinds: Vec<&'static str>,
109+ max_subject_name_len: usize,
110+ max_subject_description_len: usize,
111+ max_session_topic_len: usize,
112+ max_term_name_len: usize,
113+}
114+
115+/// Exams, their questions, answers, and marks.
116+#[derive(Serialize, ToSchema)]
117+struct ExamLimits {
118+ max_title_len: usize,
119+ max_description_len: usize,
120+ /// The only accepted `mode` values; an exam with no mode is offline-graded.
121+ #[schema(example = json!(["sync", "async", "open"]))]
122+ modes: Vec<&'static str>,
123+ /// Inclusive bounds for `duration_ms` (1 minute – 24 hours).
124+ min_duration_ms: i64,
125+ max_duration_ms: i64,
126+ /// Upper bound for `max_attempts`; `unlimited_attempts` (0) means no limit.
127+ max_attempts: i64,
128+ unlimited_attempts: i64,
129+ /// The only accepted question `kind` values.
130+ #[schema(example = json!(["choice", "text"]))]
131+ question_kinds: Vec<&'static str>,
132+ max_question_text_len: usize,
133+ min_question_points: i64,
134+ max_question_points: i64,
135+ min_question_choices: usize,
136+ max_question_choices: usize,
137+ max_choice_text_len: usize,
138+ max_answer_text_len: usize,
139+ min_mark: i64,
140+ max_mark: i64,
141+ /// Cadence of the exam-room WebSocket's `state` frames, seconds.
142+ ws_tick_secs: u64,
143+ /// Ceiling on a `question_id` sent over the exam-room WebSocket.
144+ ws_max_question_id_len: usize,
145+}
146+
147+/// Homework assignments and submissions.
148+#[derive(Serialize, ToSchema)]
149+struct HomeworkLimits {
150+ max_title_len: usize,
151+ max_description_len: usize,
152+ /// A submission's optional free-text note.
153+ max_text_len: usize,
154+ max_files_per_submission: usize,
155+ /// How many students an explicit `assigned` subset may name.
156+ max_assigned: usize,
157+ /// The only accepted teacher-set `status` values.
158+ #[schema(example = json!(["done", "incomplete", "missing"]))]
159+ statuses: Vec<&'static str>,
160+}
161+
162+/// The school question pool and its solutions.
163+#[derive(Serialize, ToSchema)]
164+struct QuestionPoolLimits {
165+ max_title_len: usize,
166+ max_body_len: usize,
167+ max_solution_body_len: usize,
168+}
169+
170+/// Teacher availability slots and the bookings on them.
171+#[derive(Serialize, ToSchema)]
172+struct AppointmentLimits {
173+ /// A published slot's optional note.
174+ max_note_len: usize,
175+ /// The requester's required reason.
176+ max_reason_len: usize,
177+ /// How many slots one weekly-repeating publish may expand into.
178+ max_slot_occurrences: usize,
179+}
180+
181+/// The AI chatbot. Each range bounds the matching `/settings` knob; the live
182+/// values are on `GET /settings`.
183+#[derive(Serialize, ToSchema)]
184+struct ChatbotLimits {
185+ /// Hard ceiling on a message, above which no school setting can reach.
186+ max_message_len: usize,
187+ /// A thread's display name. Threads are named by hand or left untitled β€”
188+ /// nothing auto-titles one.
189+ max_thread_title_len: usize,
190+ min_max_message_len: i64,
191+ max_max_message_len: i64,
192+ default_max_message_len: i64,
193+ min_history_turns: i64,
194+ max_history_turns: i64,
195+ default_history_turns: i64,
196+ min_max_threads: i64,
197+ max_max_threads: i64,
198+ default_max_threads: i64,
199+}
200+
201+/// Bounds on the school-editable lists in `PATCH /settings`.
202+#[derive(Serialize, ToSchema)]
203+struct SettingsLimits {
204+ /// Entry count for the exam-kind and attendance-status lists.
205+ max_list_len: usize,
206+ /// Per-entry characters in those lists.
207+ max_item_len: usize,
208+ min_exam_kind_weight: i64,
209+ max_exam_kind_weight: i64,
210+ max_grade_bands: usize,
211+ max_grade_label_len: usize,
212+ /// Attendance statuses no school may remove.
213+ #[schema(example = json!(["present", "absent", "late", "excused"]))]
214+ required_attendance_statuses: Vec<&'static str>,
215+}
216+
217+/// The request budgets a caller is held to before it starts getting `429`s
218+/// with a `Retry-After`. Unlike everything else here these are **deployment**
219+/// configuration, not compile-time constants β€” they come from environment
220+/// variables, so the numbers are this server's live values rather than fixed
221+/// ones. `0` means the tier is switched off.
222+#[derive(Serialize, ToSchema)]
223+struct RateLimits {
224+ /// Fixed window every tier is counted over, seconds.
225+ window_secs: u64,
226+ /// Per-IP budget for `/auth/login` and `/auth/register`.
227+ #[schema(example = 10)]
228+ auth_per_minute: u32,
229+ /// Per-IP budget across the whole API, this endpoint included.
230+ #[schema(example = 300)]
231+ api_per_minute: u32,
232+ /// Per-*user* budget for sending chatbot messages (keyed by account, not
233+ /// address, so it survives a changing IP).
234+ #[schema(example = 20)]
235+ chatbot_per_minute: u32,
236+}
237+
238+/// Rules that hold across every endpoint.
239+#[derive(Serialize, ToSchema)]
240+struct RequestLimits {
241+ /// Upper bound on a list endpoint's `?limit=`. Omitting it returns
242+ /// everything remaining.
243+ max_page_limit: i64,
244+ /// How far in the past a submitted schedule instant may lie before it is
245+ /// refused as backdated β€” the grace that absorbs clock skew.
246+ schedule_past_grace_ms: i64,
247+ /// Ceiling on how long one request may take before it is aborted.
248+ request_timeout_secs: u64,
249+}
250+
251+/// Every fixed limit the API enforces, grouped by the resource it applies to.
252+#[derive(Serialize, ToSchema)]
253+struct LimitsResponse {
254+ user: UserLimits,
255+ note: NoteLimits,
256+ file: FileLimits,
257+ message: MessageLimits,
258+ event: EventLimits,
259+ course: CourseLimits,
260+ exam: ExamLimits,
261+ homework: HomeworkLimits,
262+ question_pool: QuestionPoolLimits,
263+ appointment: AppointmentLimits,
264+ chatbot: ChatbotLimits,
265+ settings: SettingsLimits,
266+ request: RequestLimits,
267+ rate: RateLimits,
268+}
269+
270+impl LimitsResponse {
271+ fn new(st: &AppState) -> Self {
272+ Self {
273+ user: UserLimits {
274+ min_username_len: MIN_USERNAME_LEN,
275+ max_username_len: MAX_USERNAME_LEN,
276+ username_separators: USERNAME_SEPARATORS.iter().map(char::to_string).collect(),
277+ reserved_usernames: RESERVED_USERNAMES.to_vec(),
278+ min_password_len: MIN_PASSWORD_LEN,
279+ max_password_len: MAX_PASSWORD_LEN,
280+ max_name_len: MAX_NAME_LEN,
281+ max_email_len: MAX_EMAIL_LEN,
282+ min_phone_digits: MIN_PHONE_DIGITS,
283+ max_phone_digits: MAX_PHONE_DIGITS,
284+ roles: Role::ALL.iter().map(|role| role.as_str()).collect(),
285+ themes: Theme::ALL.iter().map(|theme| theme.as_str()).collect(),
286+ languages: Language::ALL
287+ .iter()
288+ .map(|language| language.as_str())
289+ .collect(),
290+ session_duration_days: SESSION_DURATION_DAYS,
291+ },
292+ note: NoteLimits {
293+ max_title_len: MAX_NOTE_TITLE_LEN,
294+ max_content_len: MAX_NOTE_CONTENT_LEN,
295+ max_files: MAX_NOTE_FILES,
296+ },
297+ file: FileLimits {
298+ max_name_len: MAX_FILE_NAME_LEN,
299+ max_content_type_len: MAX_FILE_CONTENT_TYPE_LEN,
300+ min_max_file_bytes: MIN_MAX_FILE_BYTES,
301+ max_max_file_bytes: MAX_MAX_FILE_BYTES,
302+ default_max_file_bytes: DEFAULT_MAX_FILE_BYTES,
303+ image_content_types: QUESTION_IMAGE_CONTENT_TYPES.to_vec(),
304+ },
305+ message: MessageLimits {
306+ max_subject_len: MAX_MESSAGE_SUBJECT_LEN,
307+ max_body_len: MAX_MESSAGE_BODY_LEN,
308+ max_label_len: MAX_MESSAGE_LABEL_LEN,
309+ },
310+ event: EventLimits {
311+ max_title_len: MAX_EVENT_TITLE_LEN,
312+ max_description_len: MAX_EVENT_DESCRIPTION_LEN,
313+ },
314+ course: CourseLimits {
315+ max_title_len: MAX_COURSE_TITLE_LEN,
316+ max_description_len: MAX_COURSE_DESCRIPTION_LEN,
317+ kinds: COURSE_KINDS.to_vec(),
318+ max_subject_name_len: MAX_SUBJECT_NAME_LEN,
319+ max_subject_description_len: MAX_SUBJECT_DESCRIPTION_LEN,
320+ max_session_topic_len: MAX_SESSION_TOPIC_LEN,
321+ max_term_name_len: MAX_TERM_NAME_LEN,
322+ },
323+ exam: ExamLimits {
324+ max_title_len: MAX_EXAM_TITLE_LEN,
325+ max_description_len: MAX_EXAM_DESCRIPTION_LEN,
326+ modes: EXAM_MODES.to_vec(),
327+ min_duration_ms: MIN_EXAM_DURATION_MS,
328+ max_duration_ms: MAX_EXAM_DURATION_MS,
329+ max_attempts: MAX_EXAM_ATTEMPTS,
330+ unlimited_attempts: UNLIMITED_EXAM_ATTEMPTS,
331+ question_kinds: QUESTION_KINDS.to_vec(),
332+ max_question_text_len: MAX_QUESTION_TEXT_LEN,
333+ min_question_points: MIN_QUESTION_POINTS,
334+ max_question_points: MAX_QUESTION_POINTS,
335+ min_question_choices: MIN_QUESTION_CHOICES,
336+ max_question_choices: MAX_QUESTION_CHOICES,
337+ max_choice_text_len: MAX_CHOICE_TEXT_LEN,
338+ max_answer_text_len: MAX_ANSWER_TEXT_LEN,
339+ min_mark: MIN_MARK,
340+ max_mark: MAX_MARK,
341+ ws_tick_secs: EXAM_WS_TICK_SECS,
342+ ws_max_question_id_len: MAX_QUESTION_ID_LEN,
343+ },
344+ homework: HomeworkLimits {
345+ max_title_len: MAX_HOMEWORK_TITLE_LEN,
346+ max_description_len: MAX_HOMEWORK_DESCRIPTION_LEN,
347+ max_text_len: MAX_HOMEWORK_TEXT_LEN,
348+ max_files_per_submission: MAX_HOMEWORK_FILES_PER_SUBMISSION,
349+ max_assigned: MAX_HOMEWORK_ASSIGNED,
350+ statuses: HOMEWORK_STATUSES.to_vec(),
351+ },
352+ question_pool: QuestionPoolLimits {
353+ max_title_len: MAX_POOL_QUESTION_TITLE_LEN,
354+ max_body_len: MAX_POOL_QUESTION_BODY_LEN,
355+ max_solution_body_len: MAX_SOLUTION_BODY_LEN,
356+ },
357+ appointment: AppointmentLimits {
358+ max_note_len: MAX_APPOINTMENT_NOTE_LEN,
359+ max_reason_len: MAX_APPOINTMENT_REASON_LEN,
360+ max_slot_occurrences: MAX_SLOT_OCCURRENCES,
361+ },
362+ chatbot: ChatbotLimits {
363+ max_message_len: MAX_CHATBOT_MESSAGE_LEN,
364+ max_thread_title_len: MAX_CHATBOT_THREAD_TITLE_LEN,
365+ min_max_message_len: MIN_MAX_CHATBOT_MESSAGE_LEN,
366+ max_max_message_len: MAX_MAX_CHATBOT_MESSAGE_LEN,
367+ default_max_message_len: DEFAULT_MAX_CHATBOT_MESSAGE_LEN,
368+ min_history_turns: MIN_CHATBOT_HISTORY_TURNS,
369+ max_history_turns: MAX_CHATBOT_HISTORY_TURNS,
370+ default_history_turns: DEFAULT_CHATBOT_HISTORY_TURNS,
371+ min_max_threads: MIN_MAX_CHATBOT_THREADS,
372+ max_max_threads: MAX_MAX_CHATBOT_THREADS,
373+ default_max_threads: DEFAULT_MAX_CHATBOT_THREADS,
374+ },
375+ settings: SettingsLimits {
376+ max_list_len: MAX_SETTINGS_LIST_LEN,
377+ max_item_len: MAX_SETTINGS_ITEM_LEN,
378+ min_exam_kind_weight: MIN_EXAM_KIND_WEIGHT,
379+ max_exam_kind_weight: MAX_EXAM_KIND_WEIGHT,
380+ max_grade_bands: MAX_GRADE_BANDS,
381+ max_grade_label_len: MAX_GRADE_LABEL_LEN,
382+ required_attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.to_vec(),
383+ },
384+ rate: RateLimits {
385+ window_secs: 60,
386+ auth_per_minute: st.rate_limit.auth_per_minute,
387+ api_per_minute: st.rate_limit.api_per_minute,
388+ chatbot_per_minute: st.chatbot_limit.max_per_window(),
389+ },
390+ request: RequestLimits {
391+ max_page_limit: MAX_PAGE_LIMIT,
392+ schedule_past_grace_ms: SCHEDULE_PAST_GRACE_MS,
393+ request_timeout_secs: REQUEST_TIMEOUT_SECS,
394+ },
395+ }
396+ }
397+}
398+
399+/// Every fixed validation bound the API enforces. Unauthenticated: the
400+/// registration and login forms need the username and password bounds before a
401+/// session exists, and none of these values are secrets β€” they are the same
402+/// rules a 400 would spell out.
403+///
404+/// The values are compile-time constants, so the response only ever changes
405+/// with a deploy β€” cache it for the session rather than re-fetching per form.
406+/// School-adjustable policy (exam kinds, attendance statuses, grade bands, the
407+/// live `max_file_bytes` and chatbot knobs) is on `GET /settings` instead; what
408+/// appears here for those is the fixed range a manager may set them within.
409+#[utoipa::path(
410+ get,
411+ path = "/limits",
412+ tag = "meta",
413+ responses((status = 200, description = "Every fixed validation bound", body = LimitsResponse)),
414+)]
415+async fn get_limits(State(st): State<AppState>) -> Json<LimitsResponse> {
416+ Json(LimitsResponse::new(&st))
417+}
src/web/messages.rsmodified+3 -3
@@ -30,13 +30,13 @@ struct SendMessage {
3030 /// The receiving user's id (find people via `GET /users/search`).
3131 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
3232 recipient_id: String,
33- #[schema(example = "About today's study session")]
33+ #[schema(example = "About today's study session", max_length = 200)]
3434 subject: String,
35- #[schema(example = "I may be 10 minutes late.")]
35+ #[schema(example = "I may be 10 minutes late.", max_length = 10000)]
3636 body: Option<String>,
3737 /// Optional free-text tag the UI shows as a badge ("EtΓΌt", "SΔ±nav", …).
3838 /// Blank counts as absent.
39- #[schema(example = "EtΓΌt")]
39+ #[schema(example = "EtΓΌt", max_length = 50)]
4040 label: Option<String>,
4141 }
4242
src/web/mod.rsmodified+2 -1
@@ -15,6 +15,7 @@ pub mod events;
1515 pub mod exam_ws;
1616 pub mod exams;
1717 pub mod homework;
18+pub mod limits;
1819 pub mod marks;
1920 pub mod messages;
2021 pub mod notes;
@@ -282,7 +283,7 @@ pub(crate) async fn read_upload(
282283 pub(crate) struct ChoiceBody {
283284 #[serde(default)]
284285 pub id: Option<String>,
285- #[schema(example = "42")]
286+ #[schema(example = "42", max_length = 500)]
286287 pub text: String,
287288 }
288289
src/web/notes.rsmodified+4 -2
@@ -38,15 +38,17 @@ pub fn routes() -> OpenApiRouter<AppState> {
3838
3939 #[derive(Deserialize, ToSchema)]
4040 struct CreateNote {
41- #[schema(example = "Groceries")]
41+ #[schema(example = "Groceries", max_length = 200)]
4242 title: String,
43- #[schema(example = "milk, eggs")]
43+ #[schema(example = "milk, eggs", max_length = 10000)]
4444 content: Option<String>,
4545 }
4646
4747 #[derive(Deserialize, ToSchema)]
4848 struct UpdateNote {
49+ #[schema(max_length = 200)]
4950 title: Option<String>,
51+ #[schema(max_length = 10000)]
5052 content: Option<String>,
5153 }
5254
src/web/questions.rsmodified+3 -3
@@ -95,15 +95,15 @@ async fn question_or_404(st: &AppState, id: &str) -> Result<PoolQuestion, AppErr
9595
9696 #[derive(Deserialize, ToSchema)]
9797 struct AskQuestion {
98- #[schema(example = "Bu integrali Γ§ΓΆzemedim")]
98+ #[schema(example = "Bu integrali Γ§ΓΆzemedim", max_length = 200)]
9999 title: String,
100- #[schema(example = "∫x·eˣ dx nasıl adım adım çâzülür?")]
100+ #[schema(example = "∫x·eˣ dx nasıl adım adım çâzülür?", max_length = 10000)]
101101 body: String,
102102 }
103103
104104 #[derive(Deserialize, ToSchema)]
105105 struct OfferSolution {
106- #[schema(example = "KΔ±smi integrasyon: u = x, dv = eΛ£ dx …")]
106+ #[schema(example = "KΔ±smi integrasyon: u = x, dv = eΛ£ dx …", max_length = 10000)]
107107 body: String,
108108 }
109109
src/web/sessions.rsmodified+2 -1
@@ -36,6 +36,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
3636
3737 #[derive(Deserialize, ToSchema)]
3838 struct UpdateSession {
39+ #[schema(max_length = 200)]
3940 topic: Option<String>,
4041 /// Reassign the session's teacher. Omit to keep; must be teacher+.
4142 teacher_id: Option<String>,
@@ -53,7 +54,7 @@ struct UpdateSession {
5354 struct MarkRollCall {
5455 /// One of the school's attendance statuses (`GET /settings`; the core
5556 /// four are `present`, `absent`, `late`, `excused`).
56- #[schema(example = "present")]
57+ #[schema(max_length = 50, example = "present")]
5758 status: String,
5859 /// Whose roll-call state to record: an enrolled student, or the session's
5960 /// teacher (the latter requires manager+).
src/web/settings.rsmodified+13 -9
@@ -23,11 +23,11 @@ pub fn routes() -> OpenApiRouter<AppState> {
2323 #[derive(Serialize, Deserialize, ToSchema)]
2424 struct ExamKindDto {
2525 /// The `kind` value exams carry, 1–50 characters.
26- #[schema(example = "midterm")]
26+ #[schema(example = "midterm", max_length = 50)]
2727 name: String,
2828 /// The kind's weight in the course average, `1`–`100`. Editing it
2929 /// re-weights every exam of this kind at once.
30- #[schema(example = 2)]
30+ #[schema(example = 2, minimum = 1, maximum = 100)]
3131 weight: i64,
3232 }
3333
@@ -36,10 +36,10 @@ struct ExamKindDto {
3636 #[derive(Serialize, Deserialize, ToSchema)]
3737 struct GradeBandDto {
3838 /// Lowest mark of the band, `0`–`100`. One band must start at `0`.
39- #[schema(example = 85)]
39+ #[schema(example = 85, minimum = 0, maximum = 100)]
4040 min: i64,
4141 /// What that range shows as, 1–20 characters (`"AA"`, `"5"`, `"pass"`).
42- #[schema(example = "AA")]
42+ #[schema(example = "AA", max_length = 20)]
4343 label: String,
4444 }
4545
@@ -108,28 +108,32 @@ impl SettingsResponse {
108108 struct UpdateSettings {
109109 /// Replaces the whole list when present: 1–20 entries with unique names,
110110 /// each name 1–50 characters, each weight `1`–`100`.
111+ #[schema(max_items = 20)]
111112 exam_kinds: Option<Vec<ExamKindDto>>,
112113 /// Replaces the whole list when present; must keep `present`, `absent`,
113- /// `late`, `excused` (the attendance rate is defined over them).
114+ /// `late`, `excused` (the attendance rate is defined over them). Each entry
115+ /// is 1–50 characters.
116+ #[schema(max_items = 20)]
114117 attendance_statuses: Option<Vec<String>>,
115118 /// Replaces the whole set when present. `[]` clears the bands (numeric-only
116119 /// marks); otherwise mins are unique and one band must start at `0`.
120+ #[schema(max_items = 20)]
117121 grade_bands: Option<Vec<GradeBandDto>>,
118122 /// Per-file size limit for note uploads, in bytes:
119123 /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap.
120- #[schema(example = 5_242_880)]
124+ #[schema(example = 5_242_880, minimum = 1_024, maximum = 26_214_400)]
121125 max_file_bytes: Option<i64>,
122126 /// How many prior turns of a thread the chatbot is given as context,
123127 /// `1`–`50`. Every turn is re-sent on every reply, so this costs tokens.
124- #[schema(example = 10)]
128+ #[schema(example = 10, minimum = 1, maximum = 50)]
125129 chatbot_history_turns: Option<i64>,
126130 /// How many chatbot threads one user may keep, `1`–`500`. At the cap
127131 /// the user deletes an old thread before starting a new one.
128- #[schema(example = 50)]
132+ #[schema(example = 50, minimum = 1, maximum = 500)]
129133 max_chatbot_threads: Option<i64>,
130134 /// Character limit on one chat message, `100`–`8000`. The ceiling is a
131135 /// server hard cap.
132- #[schema(example = 4000)]
136+ #[schema(example = 4000, minimum = 100, maximum = 8_000)]
133137 max_chatbot_message_len: Option<i64>,
134138 }
135139
src/web/subjects.rsmodified+2 -0
@@ -26,7 +26,9 @@ pub fn routes() -> OpenApiRouter<AppState> {
2626
2727 #[derive(Deserialize, ToSchema)]
2828 struct UpdateSubject {
29+ #[schema(max_length = 200)]
2930 name: Option<String>,
31+ #[schema(max_length = 2000)]
3032 description: Option<String>,
3133 }
3234
src/web/terms.rsmodified+2 -1
@@ -22,7 +22,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
2222
2323 #[derive(Deserialize, ToSchema)]
2424 struct CreateTerm {
25- #[schema(example = "2026 Fall")]
25+ #[schema(example = "2026 Fall", max_length = 100)]
2626 name: String,
2727 /// Term start, UTC unix-milliseconds. May lie in the past β€” a school
2828 /// adopting the app mid-year backfills its calendar legitimately.
@@ -35,6 +35,7 @@ struct CreateTerm {
3535
3636 #[derive(Deserialize, ToSchema)]
3737 struct UpdateTerm {
38+ #[schema(max_length = 100)]
3839 name: Option<String>,
3940 starts_at: Option<i64>,
4041 ends_at: Option<i64>,
src/web/users.rsmodified+5 -3
@@ -49,12 +49,14 @@ struct SetRole {
4949 /// current value, an empty string clears it, anything else is validated and set.
5050 #[derive(Deserialize, ToSchema)]
5151 struct UpdateProfile {
52- #[schema(example = "Ada")]
52+ #[schema(example = "Ada", max_length = 100)]
5353 name: Option<String>,
54- #[schema(example = "Lovelace")]
54+ #[schema(example = "Lovelace", max_length = 100)]
5555 surname: Option<String>,
56- #[schema(example = "ada@example.com")]
56+ #[schema(example = "ada@example.com", max_length = 254)]
5757 email: Option<String>,
58+ /// Any punctuation and spacing; it is the digit count that must land in
59+ /// `7`–`15`, so no character-length bound applies.
5860 #[schema(example = "+90 555 123 45 67")]
5961 phone: Option<String>,
6062 /// Birth date in `YYYY-MM-DD` form.
tests/integration.rsmodified+117 -0
@@ -46,6 +46,123 @@ async fn time_serves_server_clock_without_auth() {
4646 assert!(before <= now && now <= after);
4747 }
4848
49+#[tokio::test]
50+async fn limits_publishes_the_bounds_the_api_actually_enforces() {
51+ let app = mem_app().await;
52+
53+ let res = send(&app, "GET", "/limits", None, None).await;
54+ assert_eq!(res.status, StatusCode::OK);
55+
56+ // Every group is present β€” a frontend reads one document, not thirteen.
57+ for group in [
58+ "user",
59+ "note",
60+ "file",
61+ "message",
62+ "event",
63+ "course",
64+ "exam",
65+ "homework",
66+ "question_pool",
67+ "appointment",
68+ "chatbot",
69+ "settings",
70+ "request",
71+ ] {
72+ assert!(res.body[group].is_object(), "missing group: {group}");
73+ }
74+
75+ // The published value must equal the one the constants carry β€” the whole
76+ // point is that the frontend stops keeping its own copy.
77+ assert_eq!(
78+ res.body["user"]["max_username_len"],
79+ json!(hezarfen_backend::constant::MAX_USERNAME_LEN)
80+ );
81+ assert_eq!(res.body["exam"]["modes"], json!(["sync", "async", "open"]));
82+ assert_eq!(
83+ res.body["user"]["roles"],
84+ json!(["parent", "student", "teacher", "manager", "admin"])
85+ );
86+
87+ // The request budgets a caller is actually held to, read live off this
88+ // server rather than from a constant β€” a client should learn its budget
89+ // here, not by collecting a 429.
90+ assert!(res.body["rate"]["auth_per_minute"].is_number());
91+ assert!(res.body["rate"]["api_per_minute"].is_number());
92+ assert!(res.body["rate"]["chatbot_per_minute"].is_number());
93+ assert_eq!(res.body["rate"]["window_secs"], json!(60));
94+
95+ // Structural sanity over EVERY published pair, which is what a spot-check
96+ // of a few named fields cannot give: any `min_x` must not exceed its
97+ // `max_x`. This is what catches a mapping that wired a floor to a ceiling
98+ // β€” the one mistake a "does the constant appear?" check cannot see.
99+ let groups = res.body.as_object().expect("limits is an object");
100+ let mut checked = 0;
101+ for (group, fields) in groups {
102+ let fields = fields.as_object().expect("each group is an object");
103+ for (key, value) in fields {
104+ let Some(bare) = key.strip_prefix("min_") else {
105+ continue;
106+ };
107+ let Some(max) = fields.get(&format!("max_{bare}")) else {
108+ continue;
109+ };
110+ let (min, max) = (
111+ value.as_i64().expect("min is an integer"),
112+ max.as_i64().expect("max is an integer"),
113+ );
114+ assert!(
115+ min <= max,
116+ "{group}.{key} ({min}) exceeds its maximum ({max}) β€” the pair is inverted"
117+ );
118+ checked += 1;
119+ }
120+ }
121+ assert!(
122+ checked >= 10,
123+ "only {checked} min/max pairs were checked β€” the pairing broke, not the values"
124+ );
125+
126+ // …and the endpoint that enforces it must agree: one over the published
127+ // maximum is refused. This is what catches a constant moving without the
128+ // limits response, or the reverse.
129+ let max = res.body["user"]["max_username_len"]
130+ .as_u64()
131+ .expect("max_username_len is an integer") as usize;
132+ let too_long = json!({ "username": "a".repeat(max + 1), "password": "secret1" });
133+ let res = send(&app, "POST", "/auth/register", None, Some(too_long)).await;
134+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
135+}
136+
137+#[tokio::test]
138+async fn limits_still_answers_while_the_database_is_down() {
139+ // A frontend booting against a backend whose database is reconnecting is
140+ // precisely when it needs the validation contract. `/limits` touches no
141+ // row, so the outage guard must let it through β€” otherwise the client
142+ // falls back to the hard-coded copy this endpoint exists to remove.
143+ let db_up = hezarfen_backend::state::DbHealth::default();
144+ let app = build_router(AppState {
145+ db: database::init_mem().await.expect("in-memory db"),
146+ files_path: tempfile::tempdir().expect("files dir").keep(),
147+ cookie_secure: false,
148+ rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
149+ chatbot_limit: Default::default(),
150+ exam_presence: Default::default(),
151+ db_up: db_up.clone(),
152+ ai: None,
153+ });
154+ db_up.set(false);
155+
156+ let res = send(&app, "GET", "/limits", None, None).await;
157+ assert_eq!(res.status, StatusCode::OK);
158+ assert!(res.body["user"]["max_username_len"].is_number());
159+
160+ // Everything that does touch the database still refuses, so the exemption
161+ // is scoped to the one static route and has not disarmed the guard.
162+ let res = send(&app, "GET", "/settings", None, None).await;
163+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE);
164+}
165+
49166 #[tokio::test]
50167 async fn register_validates_input() {
51168 let app = mem_app().await;
tests/limits_completeness.rsadded+257 -0
@@ -0,0 +1,257 @@
1+//! The forcing function behind `GET /limits`.
2+//!
3+//! `src/web/limits.rs` is a hand-written mapping of `src/constant.rs` into a
4+//! JSON document. That is a mirror, and mirrors drift: the day someone adds a
5+//! constant, nothing about the compiler or the test suite would notice that
6+//! the endpoint promising "every fixed bound" quietly stopped being complete.
7+//! The frontend would then be back to guessing that one value β€” the exact
8+//! problem the endpoint exists to remove.
9+//!
10+//! So this test reads both files as text and asserts every `pub const` in
11+//! `constant.rs` is either referenced by `limits.rs` or listed below as a
12+//! deliberate exclusion with a reason. A new constant fails the suite until
13+//! someone makes that call consciously.
14+//!
15+//! Text, not reflection, because Rust cannot enumerate a module's constants at
16+//! runtime. The trade-off is that this proves a constant is *mentioned*, not
17+//! that it lands on a sensible JSON key β€” `integration::limits_publishes_the_
18+//! bounds_the_api_actually_enforces` covers the values themselves.
19+
20+use std::collections::BTreeSet;
21+use std::fs;
22+
23+/// Constants that deliberately stay out of `GET /limits`, each with the reason
24+/// it is not a client-facing bound. Adding a name here is a decision, not a
25+/// formality: it says a frontend has no business knowing this number.
26+const EXCLUDED: &[(&str, &str)] = &[
27+ // Server-internal operational timing. A client cannot act on any of these,
28+ // and publishing them would invite a frontend to build its own retry or
29+ // liveness logic against numbers we want free to change.
30+ (
31+ "DB_KEEPALIVE_INTERVAL_SECS",
32+ "database socket keepalive cadence",
33+ ),
34+ ("DB_PING_TIMEOUT_SECS", "database liveness probe deadline"),
35+ (
36+ "DB_CONNECT_BACKOFF_MAX_SECS",
37+ "boot reconnect backoff ceiling",
38+ ),
39+ (
40+ "SETTINGS_UPDATE_RETRIES",
41+ "internal compare-and-set retry count",
42+ ),
43+ (
44+ "UPLOAD_BODY_OVERHEAD_BYTES",
45+ "multipart headroom over max_file_bytes; the client sizes against \
46+ max_file_bytes itself, which /limits does publish",
47+ ),
48+ // The AI bridge is a backend↔AI-service contract over QUIC. No browser
49+ // ever speaks it; the services that do are configured out of band.
50+ ("AI_PROTOCOL", "QUIC bridge wire identifier"),
51+ ("AI_ALPN", "QUIC bridge ALPN"),
52+ ("AI_MAX_FRAME_BYTES", "QUIC bridge frame ceiling"),
53+ ("AI_DEFAULT_REQUEST_TIMEOUT_SECS", "AI inference deadline"),
54+ ("AI_MAX_CONCURRENT_PER_WORKER", "AI worker concurrency cap"),
55+ (
56+ "AI_DEFAULT_CONCURRENT_PER_WORKER",
57+ "AI worker concurrency default",
58+ ),
59+ ("AI_IDLE_TIMEOUT_SECS", "QUIC connection idle timeout"),
60+ ("AI_KEEPALIVE_SECS", "QUIC connection keepalive"),
61+ ("AI_HANDSHAKE_TIMEOUT_SECS", "AI service handshake deadline"),
62+ (
63+ "AI_CHAT_CAPABILITY",
64+ "capability string an AI service declares",
65+ ),
66+ (
67+ "CHAT_STREAM_POLL_MS",
68+ "server-side poll cadence behind the SSE stream",
69+ ),
70+ (
71+ "CHATBOT_PENDING_STALE_SECS",
72+ "when a stuck answer is declared failed",
73+ ),
74+ // Seed data for the settings singleton, not a bound. The live list is on
75+ // `GET /settings`, which is where a client must read it β€” publishing the
76+ // default too would invite rendering it instead of the school's actual one.
77+ (
78+ "DEFAULT_EXAM_KINDS",
79+ "settings seed; the live list is on GET /settings",
80+ ),
81+];
82+
83+/// Every `pub const` declared in `src/constant.rs`.
84+fn declared_constants(source: &str) -> BTreeSet<String> {
85+ source
86+ .lines()
87+ .filter_map(|line| line.strip_prefix("pub const "))
88+ .filter_map(|rest| rest.split(&[':', ' '][..]).next())
89+ .filter(|name| !name.is_empty())
90+ .map(str::to_string)
91+ .collect()
92+}
93+
94+/// True when `limits.rs` mentions the constant as a whole word β€” the response
95+/// is built by naming each constant directly, so a mention is the reference.
96+fn references(source: &str, name: &str) -> bool {
97+ source.match_indices(name).any(|(at, _)| {
98+ let before = source[..at].chars().next_back();
99+ let after = source[at + name.len()..].chars().next();
100+ let boundary = |c: Option<char>| !matches!(c, Some(c) if c.is_alphanumeric() || c == '_');
101+ boundary(before) && boundary(after)
102+ })
103+}
104+
105+#[test]
106+fn every_constant_is_published_or_deliberately_excluded() {
107+ let root = env!("CARGO_MANIFEST_DIR");
108+ let constants =
109+ fs::read_to_string(format!("{root}/src/constant.rs")).expect("read constant.rs");
110+ let limits = fs::read_to_string(format!("{root}/src/web/limits.rs")).expect("read limits.rs");
111+
112+ let declared = declared_constants(&constants);
113+ assert!(
114+ declared.len() > 50,
115+ "parsed only {} constants β€” the `pub const` parse broke, not the mapping",
116+ declared.len()
117+ );
118+
119+ let excluded: BTreeSet<&str> = EXCLUDED.iter().map(|(name, _)| *name).collect();
120+ let missing: Vec<&String> = declared
121+ .iter()
122+ .filter(|name| !excluded.contains(name.as_str()) && !references(&limits, name))
123+ .collect();
124+
125+ assert!(
126+ missing.is_empty(),
127+ "these constants are in src/constant.rs but reach neither GET /limits nor the \
128+ EXCLUDED list in this test:\n {}\n\nAdd each to src/web/limits.rs so clients \
129+ stop guessing it, or to EXCLUDED with the reason it is not client-facing.",
130+ missing
131+ .iter()
132+ .map(|name| name.as_str())
133+ .collect::<Vec<_>>()
134+ .join("\n ")
135+ );
136+}
137+
138+/// Constants outside `constant.rs` that the sweep below may ignore β€” either
139+/// because they are not a client-facing bound at all, or because they are
140+/// published by a route that reads the *live* value instead of the constant.
141+const NOT_A_CLIENT_BOUND: &[(&str, &str)] = &[
142+ // Client-facing, but deliberately not compile-time constants: these are
143+ // per-deployment defaults an operator overrides by environment variable,
144+ // so `constant.rs` is the wrong home for them. `GET /limits` publishes the
145+ // running server's ACTUAL tiers (from AppState) in its `rate` group, which
146+ // is strictly better than publishing the default a deployment may not use.
147+ (
148+ "DEFAULT_AUTH_RATE_LIMIT",
149+ "env-tunable; live value served in /limits `rate`",
150+ ),
151+ (
152+ "DEFAULT_API_RATE_LIMIT",
153+ "env-tunable; live value served in /limits `rate`",
154+ ),
155+ (
156+ "DEFAULT_CHATBOT_RATE_LIMIT",
157+ "env-tunable; live value served in /limits `rate`",
158+ ),
159+ ("MILLIS_PER_DAY", "unit conversion, not a limit"),
160+ ("MILLIS_PER_WEEK", "unit conversion, not a limit"),
161+ ("MAX_BODY", "ETag middleware's own buffering ceiling"),
162+ ("PURGE_AT", "rate-limiter bucket eviction threshold"),
163+ (
164+ "MAX_ERROR_CODE_LEN",
165+ "bounds a code the SERVER writes from an AI service's reply; no client sends it",
166+ ),
167+ ("REPLY_CHUNKS", "how the SSE stream slices an answer"),
168+ ("MIN_CHUNK_CHARS", "how the SSE stream slices an answer"),
169+];
170+
171+#[test]
172+fn validation_bounds_live_in_constant_rs() {
173+ // The completeness test above only guards `constant.rs`, so a bound
174+ // declared anywhere else is invisible to it β€” it reaches neither `/limits`
175+ // nor the OpenAPI spec, and no test notices. That is not hypothetical:
176+ // `MAX_CHATBOT_THREAD_TITLE_LEN` sat private in `domain/chatbot_thread.rs`
177+ // and escaped both surfaces until this sweep found it. This test makes the
178+ // constants file the only legal home for a client-facing bound.
179+ let root = env!("CARGO_MANIFEST_DIR");
180+ let allowed: BTreeSet<&str> = NOT_A_CLIENT_BOUND.iter().map(|(name, _)| *name).collect();
181+
182+ let mut strays = Vec::new();
183+ let mut stack = vec![format!("{root}/src")];
184+ while let Some(dir) = stack.pop() {
185+ for entry in fs::read_dir(&dir).expect("read src dir") {
186+ let path = entry.expect("dir entry").path();
187+ if path.is_dir() {
188+ stack.push(path.to_string_lossy().into_owned());
189+ continue;
190+ }
191+ if path.extension().is_none_or(|ext| ext != "rs") || path.ends_with("constant.rs") {
192+ continue;
193+ }
194+ let source = fs::read_to_string(&path).expect("read source");
195+ for line in source.lines() {
196+ let trimmed = line.trim_start();
197+ // Only `const NAME: <numeric> = <digit>` β€” a bound. Arrays of
198+ // accepted values (`Role::ALL`) and string constants are not.
199+ let Some(rest) = trimmed
200+ .strip_prefix("pub const ")
201+ .or_else(|| trimmed.strip_prefix("const "))
202+ else {
203+ continue;
204+ };
205+ let Some((name, tail)) = rest.split_once(':') else {
206+ continue;
207+ };
208+ let looks_numeric = ["usize", "i64", "u64", "i32", "u32", "u16", "u8", "f64"]
209+ .iter()
210+ .any(|ty| tail.trim_start().starts_with(ty));
211+ // `DEFAULT_` and the `_LIMIT`/`_CAP` suffixes matter as much as
212+ // the `MAX_`/`MIN_` prefixes: the rate-limit tiers are named
213+ // `DEFAULT_API_RATE_LIMIT`, and a sweep keyed only on prefixes
214+ // walked straight past a budget every client is held to.
215+ let bound_shaped = name.starts_with("MAX_")
216+ || name.starts_with("MIN_")
217+ || name.starts_with("DEFAULT_")
218+ || name.ends_with("_LIMIT")
219+ || name.ends_with("_CAP");
220+ if looks_numeric && bound_shaped && !allowed.contains(name) {
221+ let file = path.strip_prefix(root).unwrap_or(&path);
222+ strays.push(format!(" {name} in {}", file.display()));
223+ }
224+ }
225+ }
226+ }
227+
228+ assert!(
229+ strays.is_empty(),
230+ "these validation bounds live outside src/constant.rs, so they reach neither \
231+ GET /limits nor the OpenAPI spec and no test guards them:\n{}\n\nMove each into \
232+ src/constant.rs (and map it in src/web/limits.rs), or add it to \
233+ NOT_A_CLIENT_BOUND with the reason it is not a client-facing limit.",
234+ strays.join("\n")
235+ );
236+}
237+
238+#[test]
239+fn exclusions_are_real_constants() {
240+ // An exclusion for a deleted constant is dead weight that also silently
241+ // widens the allowlist if the name is ever reused for something public.
242+ let root = env!("CARGO_MANIFEST_DIR");
243+ let constants =
244+ fs::read_to_string(format!("{root}/src/constant.rs")).expect("read constant.rs");
245+ let declared = declared_constants(&constants);
246+
247+ let stale: Vec<&str> = EXCLUDED
248+ .iter()
249+ .map(|(name, _)| *name)
250+ .filter(|name| !declared.contains(*name))
251+ .collect();
252+
253+ assert!(
254+ stale.is_empty(),
255+ "EXCLUDED names constants that no longer exist in src/constant.rs: {stale:?} β€” drop them"
256+ );
257+}
tests/spec_bounds.rsadded+721 -0
@@ -0,0 +1,721 @@
1+//! The OpenAPI document must not lie about its own bounds.
2+//!
3+//! utoipa 5.5's `#[schema(max_length = …)]` accepts a **literal only** β€” a
4+//! `const` there fails to compile with "no `literal` value found after this
5+//! point". So every annotation in `src/web/*.rs` is unavoidably a hand-copied
6+//! duplicate of a number in `src/constant.rs`, and a copy nothing checks is a
7+//! copy that silently goes stale. A frontend generating validators from
8+//! `/api-docs/openapi.json` would then enforce yesterday's rule and get 400s it
9+//! cannot explain.
10+//!
11+//! This test closes that loop from the far end: it builds the real router,
12+//! fetches the emitted spec, and asserts each published bound still equals the
13+//! constant the server actually validates against. The expectations below are
14+//! the constants β€” never literals β€” because a test written against literals
15+//! would be a third copy and would pass while both were wrong.
16+
17+use axum::body::Body;
18+use axum::http::Request;
19+use hezarfen_backend::constant::*;
20+use hezarfen_backend::state::AppState;
21+use hezarfen_backend::{build_router, database};
22+use serde_json::Value;
23+use tower::ServiceExt;
24+
25+/// The emitted OpenAPI document, as the server serves it.
26+async fn spec() -> Value {
27+ let db = database::init_mem().await.expect("in-memory db");
28+ let app = build_router(AppState {
29+ db,
30+ files_path: tempfile::tempdir().expect("files dir").keep(),
31+ cookie_secure: false,
32+ rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
33+ chatbot_limit: Default::default(),
34+ exam_presence: Default::default(),
35+ db_up: Default::default(),
36+ ai: None,
37+ });
38+ let res = app
39+ .oneshot(
40+ Request::builder()
41+ .uri("/api-docs/openapi.json")
42+ .body(Body::empty())
43+ .expect("request"),
44+ )
45+ .await
46+ .expect("spec response");
47+ let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
48+ .await
49+ .expect("spec body");
50+ serde_json::from_slice(&bytes).expect("spec is json")
51+}
52+
53+/// Every published request-schema bound, paired with the constant it must
54+/// equal. Columns: schema, field, JSON Schema keyword, expected value.
55+///
56+/// Add a row whenever you add a `#[schema(max_length = …)]`-style attribute to
57+/// a request DTO β€” the annotation is the promise, this row is the proof.
58+fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
59+ vec![
60+ // --- auth / users / notes / messages ---
61+ (
62+ "Credentials",
63+ "username",
64+ "minLength",
65+ MIN_USERNAME_LEN as i64,
66+ ),
67+ (
68+ "Credentials",
69+ "username",
70+ "maxLength",
71+ MAX_USERNAME_LEN as i64,
72+ ),
73+ (
74+ "Credentials",
75+ "password",
76+ "minLength",
77+ MIN_PASSWORD_LEN as i64,
78+ ),
79+ (
80+ "Credentials",
81+ "password",
82+ "maxLength",
83+ MAX_PASSWORD_LEN as i64,
84+ ),
85+ ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64),
86+ ("UpdateProfile", "surname", "maxLength", MAX_NAME_LEN as i64),
87+ ("UpdateProfile", "email", "maxLength", MAX_EMAIL_LEN as i64),
88+ (
89+ "CreateNote",
90+ "title",
91+ "maxLength",
92+ MAX_NOTE_TITLE_LEN as i64,
93+ ),
94+ (
95+ "CreateNote",
96+ "content",
97+ "maxLength",
98+ MAX_NOTE_CONTENT_LEN as i64,
99+ ),
100+ (
101+ "UpdateNote",
102+ "title",
103+ "maxLength",
104+ MAX_NOTE_TITLE_LEN as i64,
105+ ),
106+ (
107+ "UpdateNote",
108+ "content",
109+ "maxLength",
110+ MAX_NOTE_CONTENT_LEN as i64,
111+ ),
112+ (
113+ "SendMessage",
114+ "subject",
115+ "maxLength",
116+ MAX_MESSAGE_SUBJECT_LEN as i64,
117+ ),
118+ (
119+ "SendMessage",
120+ "body",
121+ "maxLength",
122+ MAX_MESSAGE_BODY_LEN as i64,
123+ ),
124+ (
125+ "SendMessage",
126+ "label",
127+ "maxLength",
128+ MAX_MESSAGE_LABEL_LEN as i64,
129+ ),
130+ // --- events / appointments / courses / subjects / sessions ---
131+ (
132+ "CreateEvent",
133+ "title",
134+ "maxLength",
135+ MAX_EVENT_TITLE_LEN as i64,
136+ ),
137+ (
138+ "CreateEvent",
139+ "description",
140+ "maxLength",
141+ MAX_EVENT_DESCRIPTION_LEN as i64,
142+ ),
143+ (
144+ "UpdateEvent",
145+ "title",
146+ "maxLength",
147+ MAX_EVENT_TITLE_LEN as i64,
148+ ),
149+ (
150+ "UpdateEvent",
151+ "description",
152+ "maxLength",
153+ MAX_EVENT_DESCRIPTION_LEN as i64,
154+ ),
155+ (
156+ "MarkAttendance",
157+ "status",
158+ "maxLength",
159+ MAX_SETTINGS_ITEM_LEN as i64,
160+ ),
161+ (
162+ "PublishSlots",
163+ "note",
164+ "maxLength",
165+ MAX_APPOINTMENT_NOTE_LEN as i64,
166+ ),
167+ (
168+ "BookAppointment",
169+ "reason",
170+ "maxLength",
171+ MAX_APPOINTMENT_REASON_LEN as i64,
172+ ),
173+ (
174+ "CancelRequest",
175+ "reason",
176+ "maxLength",
177+ MAX_APPOINTMENT_REASON_LEN as i64,
178+ ),
179+ (
180+ "RejectRequest",
181+ "reason",
182+ "maxLength",
183+ MAX_APPOINTMENT_REASON_LEN as i64,
184+ ),
185+ (
186+ "CreateCourse",
187+ "title",
188+ "maxLength",
189+ MAX_COURSE_TITLE_LEN as i64,
190+ ),
191+ (
192+ "CreateCourse",
193+ "description",
194+ "maxLength",
195+ MAX_COURSE_DESCRIPTION_LEN as i64,
196+ ),
197+ (
198+ "UpdateCourse",
199+ "title",
200+ "maxLength",
201+ MAX_COURSE_TITLE_LEN as i64,
202+ ),
203+ (
204+ "UpdateCourse",
205+ "description",
206+ "maxLength",
207+ MAX_COURSE_DESCRIPTION_LEN as i64,
208+ ),
209+ (
210+ "CreateExamInCourse",
211+ "title",
212+ "maxLength",
213+ MAX_EXAM_TITLE_LEN as i64,
214+ ),
215+ (
216+ "CreateExamInCourse",
217+ "description",
218+ "maxLength",
219+ MAX_EXAM_DESCRIPTION_LEN as i64,
220+ ),
221+ (
222+ "CreateExamInCourse",
223+ "kind",
224+ "maxLength",
225+ MAX_SETTINGS_ITEM_LEN as i64,
226+ ),
227+ (
228+ "CreateExamInCourse",
229+ "duration_ms",
230+ "minimum",
231+ MIN_EXAM_DURATION_MS,
232+ ),
233+ (
234+ "CreateExamInCourse",
235+ "duration_ms",
236+ "maximum",
237+ MAX_EXAM_DURATION_MS,
238+ ),
239+ (
240+ "CreateExamInCourse",
241+ "max_attempts",
242+ "minimum",
243+ UNLIMITED_EXAM_ATTEMPTS,
244+ ),
245+ (
246+ "CreateExamInCourse",
247+ "max_attempts",
248+ "maximum",
249+ MAX_EXAM_ATTEMPTS,
250+ ),
251+ (
252+ "CreateSubject",
253+ "name",
254+ "maxLength",
255+ MAX_SUBJECT_NAME_LEN as i64,
256+ ),
257+ (
258+ "CreateSubject",
259+ "description",
260+ "maxLength",
261+ MAX_SUBJECT_DESCRIPTION_LEN as i64,
262+ ),
263+ (
264+ "CreateHomework",
265+ "title",
266+ "maxLength",
267+ MAX_HOMEWORK_TITLE_LEN as i64,
268+ ),
269+ (
270+ "CreateHomework",
271+ "description",
272+ "maxLength",
273+ MAX_HOMEWORK_DESCRIPTION_LEN as i64,
274+ ),
275+ (
276+ "CreateHomework",
277+ "assigned",
278+ "maxItems",
279+ MAX_HOMEWORK_ASSIGNED as i64,
280+ ),
281+ (
282+ "CreateSessionInCourse",
283+ "topic",
284+ "maxLength",
285+ MAX_SESSION_TOPIC_LEN as i64,
286+ ),
287+ (
288+ "UpdateSession",
289+ "topic",
290+ "maxLength",
291+ MAX_SESSION_TOPIC_LEN as i64,
292+ ),
293+ (
294+ "MarkRollCall",
295+ "status",
296+ "maxLength",
297+ MAX_SETTINGS_ITEM_LEN as i64,
298+ ),
299+ (
300+ "UpdateSubject",
301+ "name",
302+ "maxLength",
303+ MAX_SUBJECT_NAME_LEN as i64,
304+ ),
305+ (
306+ "UpdateSubject",
307+ "description",
308+ "maxLength",
309+ MAX_SUBJECT_DESCRIPTION_LEN as i64,
310+ ),
311+ // --- exams / questions / question bank ---
312+ (
313+ "UpdateExam",
314+ "title",
315+ "maxLength",
316+ MAX_EXAM_TITLE_LEN as i64,
317+ ),
318+ (
319+ "UpdateExam",
320+ "description",
321+ "maxLength",
322+ MAX_EXAM_DESCRIPTION_LEN as i64,
323+ ),
324+ ("UpdateExam", "duration_ms", "minimum", MIN_EXAM_DURATION_MS),
325+ ("UpdateExam", "duration_ms", "maximum", MAX_EXAM_DURATION_MS),
326+ (
327+ "UpdateExam",
328+ "max_attempts",
329+ "minimum",
330+ UNLIMITED_EXAM_ATTEMPTS,
331+ ),
332+ ("UpdateExam", "max_attempts", "maximum", MAX_EXAM_ATTEMPTS),
333+ ("GradeResult", "mark", "minimum", MIN_MARK),
334+ ("GradeResult", "mark", "maximum", MAX_MARK),
335+ (
336+ "CreateQuestion",
337+ "text",
338+ "maxLength",
339+ MAX_QUESTION_TEXT_LEN as i64,
340+ ),
341+ ("CreateQuestion", "points", "minimum", MIN_QUESTION_POINTS),
342+ ("CreateQuestion", "points", "maximum", MAX_QUESTION_POINTS),
343+ (
344+ "CreateQuestion",
345+ "choices",
346+ "minItems",
347+ MIN_QUESTION_CHOICES as i64,
348+ ),
349+ (
350+ "CreateQuestion",
351+ "choices",
352+ "maxItems",
353+ MAX_QUESTION_CHOICES as i64,
354+ ),
355+ (
356+ "UpdateQuestion",
357+ "text",
358+ "maxLength",
359+ MAX_QUESTION_TEXT_LEN as i64,
360+ ),
361+ ("UpdateQuestion", "points", "minimum", MIN_QUESTION_POINTS),
362+ ("UpdateQuestion", "points", "maximum", MAX_QUESTION_POINTS),
363+ (
364+ "UpdateQuestion",
365+ "choices",
366+ "minItems",
367+ MIN_QUESTION_CHOICES as i64,
368+ ),
369+ (
370+ "UpdateQuestion",
371+ "choices",
372+ "maxItems",
373+ MAX_QUESTION_CHOICES as i64,
374+ ),
375+ (
376+ "SaveAnswer",
377+ "text",
378+ "maxLength",
379+ MAX_ANSWER_TEXT_LEN as i64,
380+ ),
381+ (
382+ "AskQuestion",
383+ "title",
384+ "maxLength",
385+ MAX_POOL_QUESTION_TITLE_LEN as i64,
386+ ),
387+ (
388+ "AskQuestion",
389+ "body",
390+ "maxLength",
391+ MAX_POOL_QUESTION_BODY_LEN as i64,
392+ ),
393+ (
394+ "OfferSolution",
395+ "body",
396+ "maxLength",
397+ MAX_SOLUTION_BODY_LEN as i64,
398+ ),
399+ (
400+ "CreateBankQuestion",
401+ "text",
402+ "maxLength",
403+ MAX_QUESTION_TEXT_LEN as i64,
404+ ),
405+ (
406+ "CreateBankQuestion",
407+ "points",
408+ "minimum",
409+ MIN_QUESTION_POINTS,
410+ ),
411+ (
412+ "CreateBankQuestion",
413+ "points",
414+ "maximum",
415+ MAX_QUESTION_POINTS,
416+ ),
417+ (
418+ "CreateBankQuestion",
419+ "choices",
420+ "minItems",
421+ MIN_QUESTION_CHOICES as i64,
422+ ),
423+ (
424+ "CreateBankQuestion",
425+ "choices",
426+ "maxItems",
427+ MAX_QUESTION_CHOICES as i64,
428+ ),
429+ (
430+ "UpdateBankQuestion",
431+ "text",
432+ "maxLength",
433+ MAX_QUESTION_TEXT_LEN as i64,
434+ ),
435+ (
436+ "UpdateBankQuestion",
437+ "points",
438+ "minimum",
439+ MIN_QUESTION_POINTS,
440+ ),
441+ (
442+ "UpdateBankQuestion",
443+ "points",
444+ "maximum",
445+ MAX_QUESTION_POINTS,
446+ ),
447+ (
448+ "UpdateBankQuestion",
449+ "choices",
450+ "minItems",
451+ MIN_QUESTION_CHOICES as i64,
452+ ),
453+ (
454+ "UpdateBankQuestion",
455+ "choices",
456+ "maxItems",
457+ MAX_QUESTION_CHOICES as i64,
458+ ),
459+ (
460+ "ChoiceBody",
461+ "text",
462+ "maxLength",
463+ MAX_CHOICE_TEXT_LEN as i64,
464+ ),
465+ // --- homework / settings / terms / chatbot ---
466+ (
467+ "UpdateHomework",
468+ "title",
469+ "maxLength",
470+ MAX_HOMEWORK_TITLE_LEN as i64,
471+ ),
472+ (
473+ "UpdateHomework",
474+ "description",
475+ "maxLength",
476+ MAX_HOMEWORK_DESCRIPTION_LEN as i64,
477+ ),
478+ (
479+ "UpdateHomework",
480+ "assigned",
481+ "maxItems",
482+ MAX_HOMEWORK_ASSIGNED as i64,
483+ ),
484+ (
485+ "SubmitHomework",
486+ "text",
487+ "maxLength",
488+ MAX_HOMEWORK_TEXT_LEN as i64,
489+ ),
490+ ("GradeHomework", "mark", "minimum", MIN_MARK),
491+ ("GradeHomework", "mark", "maximum", MAX_MARK),
492+ (
493+ "ExamKindDto",
494+ "name",
495+ "maxLength",
496+ MAX_SETTINGS_ITEM_LEN as i64,
497+ ),
498+ ("ExamKindDto", "weight", "minimum", MIN_EXAM_KIND_WEIGHT),
499+ ("ExamKindDto", "weight", "maximum", MAX_EXAM_KIND_WEIGHT),
500+ ("GradeBandDto", "min", "minimum", MIN_MARK),
501+ ("GradeBandDto", "min", "maximum", MAX_MARK),
502+ (
503+ "GradeBandDto",
504+ "label",
505+ "maxLength",
506+ MAX_GRADE_LABEL_LEN as i64,
507+ ),
508+ (
509+ "UpdateSettings",
510+ "exam_kinds",
511+ "maxItems",
512+ MAX_SETTINGS_LIST_LEN as i64,
513+ ),
514+ (
515+ "UpdateSettings",
516+ "attendance_statuses",
517+ "maxItems",
518+ MAX_SETTINGS_LIST_LEN as i64,
519+ ),
520+ (
521+ "UpdateSettings",
522+ "grade_bands",
523+ "maxItems",
524+ MAX_GRADE_BANDS as i64,
525+ ),
526+ (
527+ "UpdateSettings",
528+ "max_file_bytes",
529+ "minimum",
530+ MIN_MAX_FILE_BYTES,
531+ ),
532+ (
533+ "UpdateSettings",
534+ "max_file_bytes",
535+ "maximum",
536+ MAX_MAX_FILE_BYTES,
537+ ),
538+ (
539+ "UpdateSettings",
540+ "chatbot_history_turns",
541+ "minimum",
542+ MIN_CHATBOT_HISTORY_TURNS,
543+ ),
544+ (
545+ "UpdateSettings",
546+ "chatbot_history_turns",
547+ "maximum",
548+ MAX_CHATBOT_HISTORY_TURNS,
549+ ),
550+ (
551+ "UpdateSettings",
552+ "max_chatbot_threads",
553+ "minimum",
554+ MIN_MAX_CHATBOT_THREADS,
555+ ),
556+ (
557+ "UpdateSettings",
558+ "max_chatbot_threads",
559+ "maximum",
560+ MAX_MAX_CHATBOT_THREADS,
561+ ),
562+ (
563+ "UpdateSettings",
564+ "max_chatbot_message_len",
565+ "minimum",
566+ MIN_MAX_CHATBOT_MESSAGE_LEN,
567+ ),
568+ (
569+ "UpdateSettings",
570+ "max_chatbot_message_len",
571+ "maximum",
572+ MAX_MAX_CHATBOT_MESSAGE_LEN,
573+ ),
574+ ("CreateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64),
575+ ("UpdateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64),
576+ (
577+ "SendChatbotMessage",
578+ "content",
579+ "maxLength",
580+ MAX_CHATBOT_MESSAGE_LEN as i64,
581+ ),
582+ // --- chatbot thread titles (constant promoted out of
583+ // domain/chatbot_thread.rs, where it escaped both surfaces) ---
584+ (
585+ "CreateChatbotThread",
586+ "title",
587+ "maxLength",
588+ MAX_CHATBOT_THREAD_TITLE_LEN as i64,
589+ ),
590+ (
591+ "RenameChatbotThread",
592+ "title",
593+ "maxLength",
594+ MAX_CHATBOT_THREAD_TITLE_LEN as i64,
595+ ),
596+ ]
597+}
598+
599+#[tokio::test]
600+async fn published_bounds_match_the_constants() {
601+ let spec = spec().await;
602+ let schemas = &spec["components"]["schemas"];
603+
604+ let mut wrong = Vec::new();
605+ for (schema, field, keyword, want) in expectations() {
606+ let got = schemas[schema]["properties"][field][keyword].as_i64();
607+ if got != Some(want) {
608+ wrong.push(format!(
609+ " {schema}.{field}: spec says {keyword}={got:?}, constant says {want}"
610+ ));
611+ }
612+ }
613+
614+ assert!(
615+ wrong.is_empty(),
616+ "the OpenAPI spec disagrees with src/constant.rs β€” a client generating \
617+ validators from it would enforce the wrong rule:\n{}\n\nutoipa takes \
618+ literals only, so fix the `#[schema(...)]` attribute to match the constant.",
619+ wrong.join("\n")
620+ );
621+}
622+
623+#[tokio::test]
624+async fn every_page_limit_param_matches_its_constant() {
625+ // `#[param(maximum = 500)]` is written out beside MAX_PAGE_LIMIT, and
626+ // constant.rs merely *asks* a human to keep the two in step. This makes
627+ // that request enforceable.
628+ //
629+ // EVERY `limit` parameter, not the first one found: `src/web/page.rs` is
630+ // the shared one, but `src/web/users.rs` declares its own search paging
631+ // with the literal repeated. Checking one would have left the other free
632+ // to drift β€” which is exactly the bug this test was written to prevent.
633+ let spec = spec().await;
634+
635+ let limits: Vec<_> = spec["paths"]
636+ .as_object()
637+ .expect("paths")
638+ .values()
639+ .filter_map(|path| path.as_object())
640+ .flat_map(|path| path.values())
641+ .filter_map(|op| op["parameters"].as_array())
642+ .flatten()
643+ .filter(|param| param["name"] == "limit")
644+ .collect();
645+
646+ assert!(
647+ !limits.is_empty(),
648+ "no endpoint publishes a `limit` query parameter β€” the paging contract vanished"
649+ );
650+
651+ let drifted: Vec<String> = limits
652+ .iter()
653+ .filter(|param| param["schema"]["maximum"].as_i64() != Some(MAX_PAGE_LIMIT))
654+ .map(|param| format!(" {:?}", param["schema"]["maximum"]))
655+ .collect();
656+
657+ assert!(
658+ drifted.is_empty(),
659+ "{} of {} published `limit` parameters disagree with MAX_PAGE_LIMIT ({}):\n{}\n\n\
660+ Update the `#[param(maximum = ...)]` that drifted (src/web/page.rs is the shared \
661+ one; src/web/users.rs declares its own).",
662+ drifted.len(),
663+ limits.len(),
664+ MAX_PAGE_LIMIT,
665+ drifted.join("\n")
666+ );
667+}
668+
669+/// Every `#[schema(...)]` bound in the web layer must have a row in
670+/// [`expectations`] β€” otherwise the table is itself a mirror that silently
671+/// lags, and a new annotation gets published with nothing checking it.
672+///
673+/// This is not hypothetical: the `CreateHomework.assigned` row was added by a
674+/// text substitution that silently matched nothing after rustfmt rewrapped the
675+/// anchor line. The suite stayed green with the row missing. This test is what
676+/// catches that class.
677+#[test]
678+fn expectations_cover_every_annotation() {
679+ let root = env!("CARGO_MANIFEST_DIR");
680+ let keywords = [
681+ "max_length",
682+ "min_length",
683+ "minimum",
684+ "maximum",
685+ "min_items",
686+ "max_items",
687+ ];
688+
689+ let mut annotated = 0;
690+ for entry in std::fs::read_dir(format!("{root}/src/web")).expect("read src/web") {
691+ let path = entry.expect("dir entry").path();
692+ if path.extension().is_none_or(|ext| ext != "rs") {
693+ continue;
694+ }
695+ let source = std::fs::read_to_string(&path).expect("read source");
696+ // Scan whole attributes, not lines: rustfmt wraps a long
697+ // `#[schema(example = "…", max_length = 5_000)]` across several lines,
698+ // and a line-based count silently misses the wrapped keyword.
699+ //
700+ // `#[param(...)]` bounds are query parameters, covered by
701+ // `every_page_limit_param_matches_its_constant` instead.
702+ for (at, _) in source.match_indices("#[schema(") {
703+ let rest = &source[at..];
704+ let end = rest.find(")]").map_or(rest.len(), |end| end + 2);
705+ let attribute = &rest[..end];
706+ annotated += keywords
707+ .iter()
708+ .filter(|kw| attribute.contains(&format!("{kw} = ")))
709+ .count();
710+ }
711+ }
712+
713+ assert_eq!(
714+ annotated,
715+ expectations().len(),
716+ "src/web/ carries {annotated} `#[schema(...)]` bounds but the expectations table \
717+ has {} rows β€” every annotation needs a row, or it is published with nothing \
718+ asserting it still matches its constant.",
719+ expectations().len()
720+ );
721+}