From 7152aa9ae3d8acfe9130af8a734cb7b8ea39af9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 25 Jul 2026 17:31:52 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=93=90=20publish=20every=20hard?= =?UTF-8?q?=20limit=20instead=20of=20making=20the=20frontend=20guess?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.md | 115 +++++- src/constant.rs | 4 + src/domain/chatbot_thread.rs | 6 +- src/lib.rs | 13 +- src/rate_limit.rs | 9 + src/web/appointments.rs | 7 +- src/web/auth.rs | 4 +- src/web/bank_questions.rs | 9 +- src/web/chatbot.rs | 14 +- src/web/courses.rs | 23 +- src/web/events.rs | 7 +- src/web/exams.rs | 19 +- src/web/homework.rs | 11 +- src/web/limits.rs | 417 ++++++++++++++++++++ src/web/messages.rs | 6 +- src/web/mod.rs | 3 +- src/web/notes.rs | 6 +- src/web/questions.rs | 6 +- src/web/sessions.rs | 3 +- src/web/settings.rs | 22 +- src/web/subjects.rs | 2 + src/web/terms.rs | 3 +- src/web/users.rs | 8 +- tests/integration.rs | 117 ++++++ tests/limits_completeness.rs | 257 +++++++++++++ tests/spec_bounds.rs | 721 +++++++++++++++++++++++++++++++++++ 26 files changed, 1749 insertions(+), 63 deletions(-) create mode 100644 src/web/limits.rs create mode 100644 tests/limits_completeness.rs create mode 100644 tests/spec_bounds.rs diff --git a/README.md b/README.md index 06735b9..ae368c4 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,11 @@ the client then polls the message or reads it off an SSE stream (see Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …) constructed only after its restrictions pass — invalid input can't be -represented. Those same types derive `surrealdb::types::SurrealValue`, so one +represented. Those restrictions are published rather than left to be guessed: +**`GET /limits`** (no auth) serves every fixed bound and closed value set the +API enforces, read straight from the constants the newtypes use, so a frontend +validates against the server's own rules instead of a hand-kept copy (see +"Validation limits"). Those same types derive `surrealdb::types::SurrealValue`, so one typed value flows from HTTP request into the `SCHEMAFULL` database. Record ids are ULIDs (time-sortable). @@ -240,6 +244,113 @@ Timezones and clock differences cannot corrupt data, by construction: Keep the single server's clock NTP-synced; that's the only clock that matters. +## Validation limits + +Every fixed bound the API enforces is published at `GET /limits` (no auth), so +a client never has to hard-code a copy that drifts the day a constant moves. +The handler reads `src/constant.rs` directly — a changed constant changes the +response in the same commit. + +```json +{ + "user": { "min_username_len": 3, "max_username_len": 32, + "username_separators": [".", "_", "-"], + "reserved_usernames": ["admin", "…"], + "min_password_len": 6, "max_password_len": 128, + "max_name_len": 100, "max_email_len": 254, + "min_phone_digits": 7, "max_phone_digits": 15, + "roles": ["parent", "student", "teacher", "manager", "admin"], + "themes": ["light", "dark"], "languages": ["tr", "en"], + "session_duration_days": 7 }, + "note": { "max_title_len": 200, "max_content_len": 10000, "max_files": 10 }, + "file": { "max_name_len": 255, "max_content_type_len": 100, + "min_max_file_bytes": 1024, "max_max_file_bytes": 26214400, + "default_max_file_bytes": 5242880, + "image_content_types": ["image/png", "image/jpeg", "image/webp", "image/gif"] }, + "message": { "max_subject_len": 200, "max_body_len": 10000, "max_label_len": 50 }, + "event": { "max_title_len": 200, "max_description_len": 2000 }, + "course": { "kinds": ["course", "study", "club"], "max_title_len": 200, "…": 0 }, + "exam": { "modes": ["sync", "async", "open"], + "question_kinds": ["choice", "text"], + "min_duration_ms": 60000, "max_duration_ms": 86400000, + "max_attempts": 100, "unlimited_attempts": 0, + "min_mark": 0, "max_mark": 100, "…": 0 }, + "homework": { "statuses": ["done", "incomplete", "missing"], + "max_files_per_submission": 10, "max_assigned": 200, "…": 0 }, + "question_pool": { "max_title_len": 200, "max_body_len": 10000, "max_solution_body_len": 10000 }, + "appointment": { "max_note_len": 500, "max_reason_len": 1000, "max_slot_occurrences": 52 }, + "chatbot": { "max_message_len": 8000, "max_thread_title_len": 200, + "min_max_message_len": 100, "…": 0 }, + "settings": { "max_list_len": 20, "max_item_len": 50, + "min_exam_kind_weight": 1, "max_exam_kind_weight": 100, + "max_grade_bands": 20, "max_grade_label_len": 20, + "required_attendance_statuses": ["present", "absent", "late", "excused"] }, + "request": { "max_page_limit": 500, "schedule_past_grace_ms": 60000, + "request_timeout_secs": 30 }, + "rate": { "window_secs": 60, "auth_per_minute": 10, + "api_per_minute": 300, "chatbot_per_minute": 20 } +} +``` + +The `rate` group is the one part that is **not** compile-time: those tiers are +environment-tunable, so the endpoint serves *this* server's live values (read +from its running limiters), not the shipped defaults. `0` means the tier is +off. A client should read its budget here rather than discovering it by +collecting a `429`. + +### Two surfaces, one source + +The bounds are published twice, on purpose, because clients consume them two +different ways: + +| Surface | Shape | Use it when | +|---------|-------|-------------| +| `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`) | +| `/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 | + +Both are generated from the same `src/constant.rs`, and **neither is allowed to +drift from it**, which is enforced rather than asked for: + +- `tests/limits_completeness.rs` parses every `pub const` out of `constant.rs` + and fails unless each one is either referenced by `src/web/limits.rs` or + listed as a deliberate exclusion *with a reason*. A new constant breaks the + suite until someone decides, consciously, whether clients need it. +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 104 published + bounds back out of the emitted JSON, and asserts each equals its constant. + This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal + only** — a `const` there does not compile — so the annotations are + unavoidably a second copy of each number. The test is what makes that copy + safe. It also pins the `limit` query parameter's `maximum` to + `MAX_PAGE_LIMIT`, a duplication `constant.rs` previously only *asked* a human + to maintain. +- A third check in `limits_completeness.rs` refuses to let a validation bound + be declared **outside** `constant.rs` at all. Without it a limit can hide in + a domain module and reach neither surface — which is exactly where + `MAX_CHATBOT_THREAD_TITLE_LEN` was found sitting, private and unpublished. + +Notes: + +- **No auth.** The registration and login forms need the username and password + bounds before a session exists, and none of these are secrets — they are the + same rules a `400` already spells out in prose. +- **Answers during a database outage.** `/limits` touches no row, so it is + exempt from the guard that answers `503` while the database reconnects — a + frontend booting against a degraded backend is exactly when it needs the + contract. Every route that does read the database still refuses. +- **Fetch once.** The values are compile-time constants, so the response only + changes with a deploy. Cache it for the session; the `ETag`/`304` path makes + a revalidation cheap if you'd rather re-check. +- **`/limits` is not `/settings`.** School-adjustable policy — the exam kinds + and their weights, the attendance statuses, the grade bands, the live + `max_file_bytes` and chatbot knobs — is on `GET /settings` and changes when a + manager edits it. What `/limits` carries for those knobs is the fixed range a + manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the + attendance statuses no school may remove. +- **Closed value sets ride along.** `roles`, `themes`, `languages`, course + `kinds`, exam `modes`, `question_kinds`, homework `statuses`, and the + uploadable `image_content_types` are the exact accepted spellings — build + pickers from these rather than from a literal list. + ## Rate limiting 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. | GET | `/health` | no | Liveness check | | GET | `/` | no | Same as `/health` | | GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) | +| GET | `/limits` | no | Every fixed validation bound, grouped by resource — see Validation limits | | GET | `/swagger` | no | Interactive API docs (Swagger UI) | | GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec | | 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/ courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs settings.rs terms.rs ai.rs chatbot.rs + limits.rs GET /limits: every constant.rs bound served as JSON ``` Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory diff --git a/src/constant.rs b/src/constant.rs index 45047fc..cf3c9c6 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -307,6 +307,10 @@ pub const DEFAULT_MAX_CHATBOT_MESSAGE_LEN: i64 = 4_000; pub const MIN_MAX_CHATBOT_MESSAGE_LEN: i64 = 100; pub const MAX_MAX_CHATBOT_MESSAGE_LEN: i64 = MAX_CHATBOT_MESSAGE_LEN as i64; +/// Bound on a chat thread's display name. A thread is named by hand or not at +/// all — nothing auto-titles one — so this only has to fit a line a user typed. +pub const MAX_CHATBOT_THREAD_TITLE_LEN: usize = 200; + /// How many prior user/assistant turns of a thread are replayed to the /// AI service as context (`chatbot_history_turns` in settings): its default and /// the inclusive range a manager may set. Every turn is re-sent on every diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index b89fd19..70ee691 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -7,6 +7,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; use ulid::Ulid; +use crate::constant::MAX_CHATBOT_THREAD_TITLE_LEN; use crate::database::{CHATBOT_THREAD_TABLE, Database}; use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; @@ -20,11 +21,6 @@ use crate::validate::validate_required; /// inserts. Same reasoning, and the same shape, as `ENROLL_LOCK`. static CHATBOT_THREAD_LOCK: Mutex<()> = Mutex::const_new(()); -/// Bound on a thread's display name. Local to this module because -/// `constant.rs` is another task's file; move it there with the rest of the -/// chat limits when they are next touched. -const MAX_CHATBOT_THREAD_TITLE_LEN: usize = 200; - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ChatbotThreadId(RecordId); diff --git a/src/lib.rs b/src/lib.rs index adef32a..0976818 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,11 +35,11 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - 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.", + 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.", ), modifiers(&SecurityAddon), tags( - (name = "meta", description = "Liveness and service metadata"), + (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)"), (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"), (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`"), (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 { .route("/", get(health)) .routes(routes!(health)) .routes(routes!(server_time)) + .merge(web::limits::routes()) .nest("/ai", web::ai::routes()) .nest("/auth", web::auth::routes(&state.rate_limit)) .nest("/chatbot", web::chatbot::routes()) @@ -166,6 +167,14 @@ pub fn build_router(state: AppState) -> Router { /// both return their response immediately and do the work afterwards, so /// neither is measured against the timeout. async fn db_guard(health: state::DbHealth, req: Request, next: Next) -> Response { + // `/limits` never touches the database — it serializes constants and this + // process's own configuration. Refusing it during an outage would be a + // pure own-goal: a frontend booting into a degraded backend is exactly + // when it needs the validation contract, and answering `503` would push it + // back to the hard-coded copy this endpoint exists to delete. + if req.uri().path() == "/limits" { + return next.run(req).await; + } if !health.is_up() { return AppError::DbUnavailable.into_response(); } diff --git a/src/rate_limit.rs b/src/rate_limit.rs index c401145..5a1f757 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -86,6 +86,15 @@ struct Bucket { count: u32, } +impl RateLimiter { + /// Requests allowed per window, `0` meaning the tier is off. Read by + /// `GET /limits` so a client learns its own budget instead of discovering + /// it by getting a `429`. + pub fn max_per_window(&self) -> u32 { + self.max + } +} + /// The per-user tier, keyed by user record key instead of client IP. Lives in /// [`crate::state::AppState`] and is called from inside a handler, after /// `CurrentUser` has identified the caller. diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 942b3fc..b9627f5 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -43,6 +43,7 @@ struct PublishSlots { starts_at: i64, ends_at: i64, /// Free-text hint shown to requesters ("office hours", "veli görüşmesi"). + #[schema(max_length = 500)] note: Option, /// Repeat the same window every week up to and including `until`. #[serde(default)] @@ -58,7 +59,7 @@ struct BookAppointment { #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] slot: String, /// Why you want the meeting — required, the teacher decides on it. - #[schema(example = "Ders notlarını konuşmak istiyorum")] + #[schema(max_length = 1000, example = "Ders notlarını konuşmak istiyorum")] reason: String, } @@ -66,7 +67,7 @@ struct BookAppointment { struct CancelRequest { /// Optional free-text reason. Blank or absent records no reason; over-long /// (past `MAX_APPOINTMENT_REASON_LEN`) answers `400`. - #[schema(example = "Rahatsızlandım, katılamayacağım")] + #[schema(max_length = 1000, example = "Rahatsızlandım, katılamayacağım")] reason: Option, } @@ -74,7 +75,7 @@ struct CancelRequest { struct RejectRequest { /// Optional free-text reason. Blank or absent records no reason; over-long /// (past `MAX_APPOINTMENT_REASON_LEN`) answers `400`. - #[schema(example = "Bu saatte müsait değilim")] + #[schema(max_length = 1000, example = "Bu saatte müsait değilim")] reason: Option, } diff --git a/src/web/auth.rs b/src/web/auth.rs index 0c4ad10..cddedd4 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -39,9 +39,9 @@ pub fn routes(rate_limit: &RateLimitConfig) -> OpenApiRouter { #[derive(Deserialize, ToSchema)] struct Credentials { - #[schema(example = "ada")] + #[schema(example = "ada", min_length = 3, max_length = 32)] username: String, - #[schema(example = "correct horse battery")] + #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] password: String, } diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index cd0c458..400f7a1 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -94,17 +94,18 @@ struct CreateBankQuestion { /// template is instantiated. #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] subject_id: String, - #[schema(example = "What is 2 + 2?")] + #[schema(example = "What is 2 + 2?", max_length = 2000)] text: String, /// `choice` or `text`. #[schema(example = "choice")] kind: String, /// This template's default point value, `1`–`100`. - #[schema(example = 10)] + #[schema(example = 10, minimum = 1, maximum = 100)] points: i64, /// The options of a `choice` question (2–10 of them); omit for `text`. /// Each carries an `id` naming it within this payload — the server mints /// the stored ids and returns them. + #[schema(min_items = 2, max_items = 10)] choices: Option>, /// The `id` of the right option, as sent in `choices`; required for /// `choice`, absent for `text`. @@ -117,7 +118,9 @@ struct UpdateBankQuestion { /// Re-tag the template's origin subject. Omit to keep the current one /// (which is `null` if that subject has since been deleted). subject_id: Option, + #[schema(max_length = 2000)] text: Option, + #[schema(minimum = 1, maximum = 100)] points: Option, /// `choice` or `text`. Switching kinds needs the other fields to follow: /// send `choices` + `correct` when moving to `choice`, explicit `null`s @@ -128,7 +131,7 @@ struct UpdateBankQuestion { /// with to keep it — its picture rides along. Only options whose id is /// absent from the new list lose their picture. #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option>)] + #[schema(value_type = Option>, min_items = 2, max_items = 10)] choices: Option>>, /// The `id` of the right option. Omit to keep; `null` to clear (text /// questions only). diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 4828312..ca2041d 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -63,7 +63,7 @@ const MIN_CHUNK_CHARS: usize = 24; struct CreateChatbotThread { /// Optional thread name, up to 200 characters. Blank counts as absent — /// an untitled thread is normal (the UI labels it from its first turn). - #[schema(example = "Fizik ödevi")] + #[schema(max_length = 200, example = "Fizik ödevi")] title: Option, } @@ -164,7 +164,7 @@ async fn list_threads( struct RenameChatbotThread { /// The new name, up to 200 characters. `null` — or blank — clears it back /// to untitled, the same rule the create route applies. - #[schema(example = "Fizik ödevi")] + #[schema(max_length = 200, example = "Fizik ödevi")] title: Option, } @@ -240,9 +240,13 @@ async fn own_thread(id: &str, user: &UserId, db: &Database) -> Result OpenApiRouter { #[derive(Deserialize, ToSchema)] struct CreateCourse { - #[schema(example = "Algebra")] + #[schema(max_length = 200, example = "Algebra")] title: String, + #[schema(max_length = 2000)] description: Option, /// `course` (a regular class — the default), `study` (a supervised study /// session — etüt), or `club` (a student club — kulüp). Behaviorally @@ -73,7 +74,9 @@ struct CreateCourse { #[derive(Deserialize, ToSchema)] struct UpdateCourse { + #[schema(max_length = 200)] title: Option, + #[schema(max_length = 2000)] description: Option, /// `course`, `study` (etüt), or `club` (kulüp). Omit to keep the current /// kind. @@ -108,14 +111,15 @@ struct AssignTeacher { #[derive(Deserialize, ToSchema)] struct CreateExamInCourse { - #[schema(example = "Midterm")] + #[schema(max_length = 200, example = "Midterm")] title: String, + #[schema(max_length = 2000)] description: Option, /// The assessment form — one of the school's exam kinds (`GET /settings`; /// defaults: `homework`, `quiz`, `midterm`, `final`, `project`, `oral`). /// The kind's settings-configured weight decides how heavily the exam /// counts into the course average. - #[schema(example = "midterm")] + #[schema(max_length = 50, example = "midterm")] kind: String, /// `sync` (one fixed window for everyone), `async` (each student starts /// inside the window and gets `duration_ms`), or `open` (no window — sit @@ -131,11 +135,11 @@ struct CreateExamInCourse { ends_at: Option, /// Per-attempt time budget, milliseconds — required for `async`, optional /// for `open` (omit for unlimited time), forbidden for `sync`. - #[schema(example = 5_400_000_i64)] + #[schema(minimum = 60_000, maximum = 86_400_000, example = 5_400_000_i64)] duration_ms: Option, /// How many attempts each student gets, `1`–`100`, or `0` for unlimited. /// Defaults to `1` — the classic single sitting. - #[schema(example = 1)] + #[schema(minimum = 0, maximum = 100, example = 1)] max_attempts: Option, /// Whether a student who left the exam room may come back in and keep /// answering. Defaults to `true`; editable live while the exam runs. @@ -893,8 +897,9 @@ async fn list_course_exams( #[derive(Deserialize, ToSchema)] struct CreateSubject { - #[schema(example = "Limits and continuity")] + #[schema(max_length = 200, example = "Limits and continuity")] name: String, + #[schema(max_length = 2000)] description: Option, } @@ -987,8 +992,9 @@ async fn list_course_subjects( #[derive(Deserialize, ToSchema)] struct CreateHomework { - #[schema(example = "Read chapter 3 and answer Q1-Q5")] + #[schema(max_length = 200, example = "Read chapter 3 and answer Q1-Q5")] title: String, + #[schema(max_length = 2000)] description: Option, /// The course subject this homework belongs to /// (`GET /courses/{id}/subjects`). Required — every homework is tagged with @@ -1002,6 +1008,7 @@ struct CreateHomework { /// The students this homework is for: a list of enrolled student ids. Omit, /// send `null`, or send `[]` to assign the whole enrolled course (whoever is /// enrolled when they submit); a subset caps at 200 named students. + #[schema(max_items = 200)] assigned: Option>, } @@ -1120,7 +1127,7 @@ async fn list_course_homework( #[derive(Deserialize, ToSchema)] struct CreateSessionInCourse { /// What the lesson covers. Optional. - #[schema(example = "Limits and continuity")] + #[schema(max_length = 200, example = "Limits and continuity")] topic: Option, /// Who teaches the session. Defaults to the caller; must hold the /// `teacher` role or higher. diff --git a/src/web/events.rs b/src/web/events.rs index 457e5e7..588aab5 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -124,8 +124,9 @@ impl AudienceDto { #[derive(Deserialize, ToSchema)] struct CreateEvent { - #[schema(example = "Sprint demo")] + #[schema(max_length = 200, example = "Sprint demo")] title: String, + #[schema(max_length = 2000)] description: Option, /// Who the event is for (its expected-attendee roster). Omit for a /// school-wide event. @@ -138,7 +139,9 @@ struct CreateEvent { #[derive(Deserialize, ToSchema)] struct UpdateEvent { + #[schema(max_length = 200)] title: Option, + #[schema(max_length = 2000)] description: Option, /// Replaces the audience wholesale when present; omit to keep the current /// one. Attendance rows for people the change drops out of the roster stay @@ -160,7 +163,7 @@ struct UpdateEvent { struct MarkAttendance { /// One of the school's attendance statuses (`GET /settings`; the core /// four are `present`, `absent`, `late`, `excused`). - #[schema(example = "present")] + #[schema(max_length = 50, example = "present")] status: String, /// Target user id — must be in the event's audience. Defaults to the /// caller when omitted. diff --git a/src/web/exams.rs b/src/web/exams.rs index efec2b4..0ddb9f9 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -136,7 +136,9 @@ pub fn routes() -> OpenApiRouter { #[derive(Deserialize, ToSchema)] struct UpdateExam { + #[schema(max_length = 200)] title: Option, + #[schema(max_length = 2000)] description: Option, /// The assessment form — one of the school's exam kinds (`GET /settings`). /// Changing it re-weights the exam: the course average uses the kind's @@ -164,11 +166,12 @@ struct UpdateExam { /// to keep; `null` to clear. Changing it mid-exam moves every running /// attempt's deadline. #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option)] + #[schema(value_type = Option, minimum = 60000, maximum = 86400000)] duration_ms: Option>, /// Attempt limit: `1`–`100`, or `0` for unlimited. Omit to keep. Editable /// live — raising it grants retakes on the spot; lowering it only blocks /// future starts. + #[schema(minimum = 0, maximum = 100)] max_attempts: Option, /// Whether students who left the exam room may come back in. Omit to /// keep. Editable live — the teacher's door handle for the running room. @@ -185,7 +188,7 @@ struct UpdateExam { #[derive(Deserialize, ToSchema)] struct GradeResult { /// The mark to record, `0`–`100`. - #[schema(example = 85)] + #[schema(example = 85, minimum = 0, maximum = 100)] mark: i64, /// The student being graded. #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] @@ -1332,17 +1335,18 @@ struct CreateQuestion { #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] subject_id: String, /// The question itself. - #[schema(example = "What is 2 + 2?")] + #[schema(example = "What is 2 + 2?", max_length = 2000)] text: String, /// `choice` or `text`. #[schema(example = "choice")] kind: String, /// This question's share of the auto-score, `1`–`100`. - #[schema(example = 10)] + #[schema(example = 10, minimum = 1, maximum = 100)] points: i64, /// The options of a `choice` question (2–10 of them); omit for `text`. /// Each carries an `id` naming it within this payload — the server mints /// the stored ids and returns them. + #[schema(min_items = 2, max_items = 10)] choices: Option>, /// The `id` of the right option, as sent in `choices`; required for /// `choice`, absent for `text`. @@ -1356,7 +1360,9 @@ struct UpdateQuestion { /// keep the current one — a question always has a subject, so there is no /// clearing it. subject_id: Option, + #[schema(max_length = 2000)] text: Option, + #[schema(minimum = 1, maximum = 100)] points: Option, /// `choice` or `text`. Switching kinds needs the other fields to follow: /// send `choices` + `correct` when moving to `choice`, explicit `null`s @@ -1368,7 +1374,7 @@ struct UpdateQuestion { /// absent from the new list lose their picture, so reordering, renaming, /// and deleting one option leave the rest untouched. #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option>)] + #[schema(value_type = Option>, min_items = 2, max_items = 10)] choices: Option>>, /// The `id` of the right option. Omit to keep; `null` to clear (text /// questions only). @@ -2635,6 +2641,7 @@ struct SaveAnswer { /// The picked option's `id` — required for `choice` questions. selected: Option, /// The typed answer — required for `text` questions (empty clears the draft). + #[schema(max_length = 10000)] text: Option, } @@ -3218,7 +3225,7 @@ async fn delete_answer_image( // as answered. A typed answer keeps its row. if let Some(answer) = ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db).await? { let blank = answer.get_selected().is_none() - && answer.get_text().map_or(true, |t| t.as_str().is_empty()); + && answer.get_text().is_none_or(|t| t.as_str().is_empty()); if blank { ExamAnswer::delete(question.get_id(), user.get_id(), seq, &st.db).await?; } diff --git a/src/web/homework.rs b/src/web/homework.rs index 6b9e5db..282baee 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -239,10 +239,11 @@ async fn get_homework( #[derive(Deserialize, ToSchema)] struct UpdateHomework { /// Re-title. Omit to keep the current title. + #[schema(max_length = 200)] title: Option, /// Re-describe. Omit to keep; send `null` (or `""`) to clear. #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option)] + #[schema(value_type = Option, max_length = 2_000)] description: Option>, /// New due date, UTC unix-milliseconds. Omit to keep; a newly set value /// must not be in the past (a kept one may already be past). @@ -256,7 +257,7 @@ struct UpdateHomework { /// / `null` for the whole course. Omit to keep. Narrowing is refused (409) /// while it would orphan a student who already submitted or was graded. #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option>)] + #[schema(value_type = Option>, max_items = 200)] assigned: Option>>, } @@ -564,7 +565,10 @@ struct SubmitHomework { /// replaces any previous text, and omitting it (or sending `""`) clears it. /// Files are managed separately via `.../submission/files` and are never /// touched here. - #[schema(example = "Answers to questions 1–4 are in the attached photo.")] + #[schema( + example = "Answers to questions 1–4 are in the attached photo.", + max_length = 5_000 + )] text: Option, } @@ -951,6 +955,7 @@ struct GradeHomework { status: String, /// An optional 0–100 mark on top of the status; omit to grade on status /// alone. + #[schema(minimum = 0, maximum = 100)] mark: Option, } diff --git a/src/web/limits.rs b/src/web/limits.rs new file mode 100644 index 0000000..b353a9e --- /dev/null +++ b/src/web/limits.rs @@ -0,0 +1,417 @@ +//! `GET /limits` — every compile-time validation bound, served as data. +//! +//! The frontend has to enforce the same rules the newtypes do (a `maxlength` +//! on an input, a client-side check before a doomed request). Hard-coding them +//! there means two copies that silently drift apart the day one moves. This +//! endpoint is the single source: every field below reads a `crate::constant` +//! item directly, so a changed constant changes the response in the same +//! commit. +//! +//! School-adjustable policy (exam kinds, attendance statuses, grade bands, the +//! live `max_file_bytes`) lives in `GET /settings` — this route carries only +//! the fixed bounds those settings must themselves stay inside. + +use axum::Json; +use axum::extract::State; +use serde::Serialize; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::constant::*; +use crate::domain::preferences::{Language, Theme}; +use crate::domain::role::Role; +use crate::state::AppState; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new().routes(routes!(get_limits)) +} + +/// Account fields: credentials, profile, and the closed role set. +#[derive(Serialize, ToSchema)] +struct UserLimits { + min_username_len: usize, + max_username_len: usize, + /// Separators allowed inside a username — never at the edges, never doubled. + #[schema(example = json!([".", "_", "-"]))] + username_separators: Vec, + /// Names `POST /auth/register` refuses (they read as staff). + reserved_usernames: Vec<&'static str>, + min_password_len: usize, + max_password_len: usize, + max_name_len: usize, + max_email_len: usize, + /// Digit count, ignoring spaces and punctuation. + min_phone_digits: usize, + max_phone_digits: usize, + /// Every role, lowest privilege first. + #[schema(example = json!(["parent", "student", "teacher", "manager", "admin"]))] + roles: Vec<&'static str>, + /// Accepted `theme` preference values (`null` clears it). + #[schema(example = json!(["light", "dark"]))] + themes: Vec<&'static str>, + /// Accepted `language` preference values (`null` clears it). + #[schema(example = json!(["tr", "en"]))] + languages: Vec<&'static str>, + /// How long a login session stays valid, days. + session_duration_days: i64, +} + +/// Note bodies and their attachments. +#[derive(Serialize, ToSchema)] +struct NoteLimits { + max_title_len: usize, + max_content_len: usize, + /// How many files one note may carry. + max_files: usize, +} + +/// Uploaded-file metadata, shared by every upload route. +#[derive(Serialize, ToSchema)] +struct FileLimits { + max_name_len: usize, + max_content_type_len: usize, + /// Inclusive range a manager may set `max_file_bytes` to in `/settings`; + /// the live value is on `GET /settings`, this is the hard ceiling above it. + min_max_file_bytes: i64, + max_max_file_bytes: i64, + default_max_file_bytes: i64, + /// Content types an inline image (question illustrations, option pictures, + /// pool photos, answer drawings) may declare. Raster only — no SVG. + #[schema(example = json!(["image/png", "image/jpeg", "image/webp", "image/gif"]))] + image_content_types: Vec<&'static str>, +} + +/// One-to-one messages. +#[derive(Serialize, ToSchema)] +struct MessageLimits { + max_subject_len: usize, + max_body_len: usize, + /// The sender's optional free-text badge. + max_label_len: usize, +} + +/// Events and their registration lists. +#[derive(Serialize, ToSchema)] +struct EventLimits { + max_title_len: usize, + max_description_len: usize, +} + +/// Courses, their curriculum subjects, and lesson sessions. +#[derive(Serialize, ToSchema)] +struct CourseLimits { + max_title_len: usize, + max_description_len: usize, + /// The only accepted `kind` values — behaviorally identical labels. + #[schema(example = json!(["course", "study", "club"]))] + kinds: Vec<&'static str>, + max_subject_name_len: usize, + max_subject_description_len: usize, + max_session_topic_len: usize, + max_term_name_len: usize, +} + +/// Exams, their questions, answers, and marks. +#[derive(Serialize, ToSchema)] +struct ExamLimits { + max_title_len: usize, + max_description_len: usize, + /// The only accepted `mode` values; an exam with no mode is offline-graded. + #[schema(example = json!(["sync", "async", "open"]))] + modes: Vec<&'static str>, + /// Inclusive bounds for `duration_ms` (1 minute – 24 hours). + min_duration_ms: i64, + max_duration_ms: i64, + /// Upper bound for `max_attempts`; `unlimited_attempts` (0) means no limit. + max_attempts: i64, + unlimited_attempts: i64, + /// The only accepted question `kind` values. + #[schema(example = json!(["choice", "text"]))] + question_kinds: Vec<&'static str>, + max_question_text_len: usize, + min_question_points: i64, + max_question_points: i64, + min_question_choices: usize, + max_question_choices: usize, + max_choice_text_len: usize, + max_answer_text_len: usize, + min_mark: i64, + max_mark: i64, + /// Cadence of the exam-room WebSocket's `state` frames, seconds. + ws_tick_secs: u64, + /// Ceiling on a `question_id` sent over the exam-room WebSocket. + ws_max_question_id_len: usize, +} + +/// Homework assignments and submissions. +#[derive(Serialize, ToSchema)] +struct HomeworkLimits { + max_title_len: usize, + max_description_len: usize, + /// A submission's optional free-text note. + max_text_len: usize, + max_files_per_submission: usize, + /// How many students an explicit `assigned` subset may name. + max_assigned: usize, + /// The only accepted teacher-set `status` values. + #[schema(example = json!(["done", "incomplete", "missing"]))] + statuses: Vec<&'static str>, +} + +/// The school question pool and its solutions. +#[derive(Serialize, ToSchema)] +struct QuestionPoolLimits { + max_title_len: usize, + max_body_len: usize, + max_solution_body_len: usize, +} + +/// Teacher availability slots and the bookings on them. +#[derive(Serialize, ToSchema)] +struct AppointmentLimits { + /// A published slot's optional note. + max_note_len: usize, + /// The requester's required reason. + max_reason_len: usize, + /// How many slots one weekly-repeating publish may expand into. + max_slot_occurrences: usize, +} + +/// The AI chatbot. Each range bounds the matching `/settings` knob; the live +/// values are on `GET /settings`. +#[derive(Serialize, ToSchema)] +struct ChatbotLimits { + /// Hard ceiling on a message, above which no school setting can reach. + max_message_len: usize, + /// A thread's display name. Threads are named by hand or left untitled — + /// nothing auto-titles one. + max_thread_title_len: usize, + min_max_message_len: i64, + max_max_message_len: i64, + default_max_message_len: i64, + min_history_turns: i64, + max_history_turns: i64, + default_history_turns: i64, + min_max_threads: i64, + max_max_threads: i64, + default_max_threads: i64, +} + +/// Bounds on the school-editable lists in `PATCH /settings`. +#[derive(Serialize, ToSchema)] +struct SettingsLimits { + /// Entry count for the exam-kind and attendance-status lists. + max_list_len: usize, + /// Per-entry characters in those lists. + max_item_len: usize, + min_exam_kind_weight: i64, + max_exam_kind_weight: i64, + max_grade_bands: usize, + max_grade_label_len: usize, + /// Attendance statuses no school may remove. + #[schema(example = json!(["present", "absent", "late", "excused"]))] + required_attendance_statuses: Vec<&'static str>, +} + +/// The request budgets a caller is held to before it starts getting `429`s +/// with a `Retry-After`. Unlike everything else here these are **deployment** +/// configuration, not compile-time constants — they come from environment +/// variables, so the numbers are this server's live values rather than fixed +/// ones. `0` means the tier is switched off. +#[derive(Serialize, ToSchema)] +struct RateLimits { + /// Fixed window every tier is counted over, seconds. + window_secs: u64, + /// Per-IP budget for `/auth/login` and `/auth/register`. + #[schema(example = 10)] + auth_per_minute: u32, + /// Per-IP budget across the whole API, this endpoint included. + #[schema(example = 300)] + api_per_minute: u32, + /// Per-*user* budget for sending chatbot messages (keyed by account, not + /// address, so it survives a changing IP). + #[schema(example = 20)] + chatbot_per_minute: u32, +} + +/// Rules that hold across every endpoint. +#[derive(Serialize, ToSchema)] +struct RequestLimits { + /// Upper bound on a list endpoint's `?limit=`. Omitting it returns + /// everything remaining. + max_page_limit: i64, + /// How far in the past a submitted schedule instant may lie before it is + /// refused as backdated — the grace that absorbs clock skew. + schedule_past_grace_ms: i64, + /// Ceiling on how long one request may take before it is aborted. + request_timeout_secs: u64, +} + +/// Every fixed limit the API enforces, grouped by the resource it applies to. +#[derive(Serialize, ToSchema)] +struct LimitsResponse { + user: UserLimits, + note: NoteLimits, + file: FileLimits, + message: MessageLimits, + event: EventLimits, + course: CourseLimits, + exam: ExamLimits, + homework: HomeworkLimits, + question_pool: QuestionPoolLimits, + appointment: AppointmentLimits, + chatbot: ChatbotLimits, + settings: SettingsLimits, + request: RequestLimits, + rate: RateLimits, +} + +impl LimitsResponse { + fn new(st: &AppState) -> Self { + Self { + user: UserLimits { + min_username_len: MIN_USERNAME_LEN, + max_username_len: MAX_USERNAME_LEN, + username_separators: USERNAME_SEPARATORS.iter().map(char::to_string).collect(), + reserved_usernames: RESERVED_USERNAMES.to_vec(), + min_password_len: MIN_PASSWORD_LEN, + max_password_len: MAX_PASSWORD_LEN, + max_name_len: MAX_NAME_LEN, + max_email_len: MAX_EMAIL_LEN, + min_phone_digits: MIN_PHONE_DIGITS, + max_phone_digits: MAX_PHONE_DIGITS, + roles: Role::ALL.iter().map(|role| role.as_str()).collect(), + themes: Theme::ALL.iter().map(|theme| theme.as_str()).collect(), + languages: Language::ALL + .iter() + .map(|language| language.as_str()) + .collect(), + session_duration_days: SESSION_DURATION_DAYS, + }, + note: NoteLimits { + max_title_len: MAX_NOTE_TITLE_LEN, + max_content_len: MAX_NOTE_CONTENT_LEN, + max_files: MAX_NOTE_FILES, + }, + file: FileLimits { + max_name_len: MAX_FILE_NAME_LEN, + max_content_type_len: MAX_FILE_CONTENT_TYPE_LEN, + min_max_file_bytes: MIN_MAX_FILE_BYTES, + max_max_file_bytes: MAX_MAX_FILE_BYTES, + default_max_file_bytes: DEFAULT_MAX_FILE_BYTES, + image_content_types: QUESTION_IMAGE_CONTENT_TYPES.to_vec(), + }, + message: MessageLimits { + max_subject_len: MAX_MESSAGE_SUBJECT_LEN, + max_body_len: MAX_MESSAGE_BODY_LEN, + max_label_len: MAX_MESSAGE_LABEL_LEN, + }, + event: EventLimits { + max_title_len: MAX_EVENT_TITLE_LEN, + max_description_len: MAX_EVENT_DESCRIPTION_LEN, + }, + course: CourseLimits { + max_title_len: MAX_COURSE_TITLE_LEN, + max_description_len: MAX_COURSE_DESCRIPTION_LEN, + kinds: COURSE_KINDS.to_vec(), + max_subject_name_len: MAX_SUBJECT_NAME_LEN, + max_subject_description_len: MAX_SUBJECT_DESCRIPTION_LEN, + max_session_topic_len: MAX_SESSION_TOPIC_LEN, + max_term_name_len: MAX_TERM_NAME_LEN, + }, + exam: ExamLimits { + max_title_len: MAX_EXAM_TITLE_LEN, + max_description_len: MAX_EXAM_DESCRIPTION_LEN, + modes: EXAM_MODES.to_vec(), + min_duration_ms: MIN_EXAM_DURATION_MS, + max_duration_ms: MAX_EXAM_DURATION_MS, + max_attempts: MAX_EXAM_ATTEMPTS, + unlimited_attempts: UNLIMITED_EXAM_ATTEMPTS, + question_kinds: QUESTION_KINDS.to_vec(), + max_question_text_len: MAX_QUESTION_TEXT_LEN, + min_question_points: MIN_QUESTION_POINTS, + max_question_points: MAX_QUESTION_POINTS, + min_question_choices: MIN_QUESTION_CHOICES, + max_question_choices: MAX_QUESTION_CHOICES, + max_choice_text_len: MAX_CHOICE_TEXT_LEN, + max_answer_text_len: MAX_ANSWER_TEXT_LEN, + min_mark: MIN_MARK, + max_mark: MAX_MARK, + ws_tick_secs: EXAM_WS_TICK_SECS, + ws_max_question_id_len: MAX_QUESTION_ID_LEN, + }, + homework: HomeworkLimits { + max_title_len: MAX_HOMEWORK_TITLE_LEN, + max_description_len: MAX_HOMEWORK_DESCRIPTION_LEN, + max_text_len: MAX_HOMEWORK_TEXT_LEN, + max_files_per_submission: MAX_HOMEWORK_FILES_PER_SUBMISSION, + max_assigned: MAX_HOMEWORK_ASSIGNED, + statuses: HOMEWORK_STATUSES.to_vec(), + }, + question_pool: QuestionPoolLimits { + max_title_len: MAX_POOL_QUESTION_TITLE_LEN, + max_body_len: MAX_POOL_QUESTION_BODY_LEN, + max_solution_body_len: MAX_SOLUTION_BODY_LEN, + }, + appointment: AppointmentLimits { + max_note_len: MAX_APPOINTMENT_NOTE_LEN, + max_reason_len: MAX_APPOINTMENT_REASON_LEN, + max_slot_occurrences: MAX_SLOT_OCCURRENCES, + }, + chatbot: ChatbotLimits { + max_message_len: MAX_CHATBOT_MESSAGE_LEN, + max_thread_title_len: MAX_CHATBOT_THREAD_TITLE_LEN, + min_max_message_len: MIN_MAX_CHATBOT_MESSAGE_LEN, + max_max_message_len: MAX_MAX_CHATBOT_MESSAGE_LEN, + default_max_message_len: DEFAULT_MAX_CHATBOT_MESSAGE_LEN, + min_history_turns: MIN_CHATBOT_HISTORY_TURNS, + max_history_turns: MAX_CHATBOT_HISTORY_TURNS, + default_history_turns: DEFAULT_CHATBOT_HISTORY_TURNS, + min_max_threads: MIN_MAX_CHATBOT_THREADS, + max_max_threads: MAX_MAX_CHATBOT_THREADS, + default_max_threads: DEFAULT_MAX_CHATBOT_THREADS, + }, + settings: SettingsLimits { + max_list_len: MAX_SETTINGS_LIST_LEN, + max_item_len: MAX_SETTINGS_ITEM_LEN, + min_exam_kind_weight: MIN_EXAM_KIND_WEIGHT, + max_exam_kind_weight: MAX_EXAM_KIND_WEIGHT, + max_grade_bands: MAX_GRADE_BANDS, + max_grade_label_len: MAX_GRADE_LABEL_LEN, + required_attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.to_vec(), + }, + rate: RateLimits { + window_secs: 60, + auth_per_minute: st.rate_limit.auth_per_minute, + api_per_minute: st.rate_limit.api_per_minute, + chatbot_per_minute: st.chatbot_limit.max_per_window(), + }, + request: RequestLimits { + max_page_limit: MAX_PAGE_LIMIT, + schedule_past_grace_ms: SCHEDULE_PAST_GRACE_MS, + request_timeout_secs: REQUEST_TIMEOUT_SECS, + }, + } + } +} + +/// Every fixed validation bound the API enforces. Unauthenticated: the +/// registration and login forms need the username and password bounds before a +/// session exists, and none of these values are secrets — they are the same +/// rules a 400 would spell out. +/// +/// The values are compile-time constants, so the response only ever changes +/// with a deploy — cache it for the session rather than re-fetching per form. +/// School-adjustable policy (exam kinds, attendance statuses, grade bands, the +/// live `max_file_bytes` and chatbot knobs) is on `GET /settings` instead; what +/// appears here for those is the fixed range a manager may set them within. +#[utoipa::path( + get, + path = "/limits", + tag = "meta", + responses((status = 200, description = "Every fixed validation bound", body = LimitsResponse)), +)] +async fn get_limits(State(st): State) -> Json { + Json(LimitsResponse::new(&st)) +} diff --git a/src/web/messages.rs b/src/web/messages.rs index 32b163f..eca02c9 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -30,13 +30,13 @@ struct SendMessage { /// The receiving user's id (find people via `GET /users/search`). #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] recipient_id: String, - #[schema(example = "About today's study session")] + #[schema(example = "About today's study session", max_length = 200)] subject: String, - #[schema(example = "I may be 10 minutes late.")] + #[schema(example = "I may be 10 minutes late.", max_length = 10000)] body: Option, /// Optional free-text tag the UI shows as a badge ("Etüt", "Sınav", …). /// Blank counts as absent. - #[schema(example = "Etüt")] + #[schema(example = "Etüt", max_length = 50)] label: Option, } diff --git a/src/web/mod.rs b/src/web/mod.rs index 6fed325..3584363 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -15,6 +15,7 @@ pub mod events; pub mod exam_ws; pub mod exams; pub mod homework; +pub mod limits; pub mod marks; pub mod messages; pub mod notes; @@ -282,7 +283,7 @@ pub(crate) async fn read_upload( pub(crate) struct ChoiceBody { #[serde(default)] pub id: Option, - #[schema(example = "42")] + #[schema(example = "42", max_length = 500)] pub text: String, } diff --git a/src/web/notes.rs b/src/web/notes.rs index 2c9c200..43635a5 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -38,15 +38,17 @@ pub fn routes() -> OpenApiRouter { #[derive(Deserialize, ToSchema)] struct CreateNote { - #[schema(example = "Groceries")] + #[schema(example = "Groceries", max_length = 200)] title: String, - #[schema(example = "milk, eggs")] + #[schema(example = "milk, eggs", max_length = 10000)] content: Option, } #[derive(Deserialize, ToSchema)] struct UpdateNote { + #[schema(max_length = 200)] title: Option, + #[schema(max_length = 10000)] content: Option, } diff --git a/src/web/questions.rs b/src/web/questions.rs index c4a8c34..99e72a7 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -95,15 +95,15 @@ async fn question_or_404(st: &AppState, id: &str) -> Result OpenApiRouter { #[derive(Deserialize, ToSchema)] struct UpdateSession { + #[schema(max_length = 200)] topic: Option, /// Reassign the session's teacher. Omit to keep; must be teacher+. teacher_id: Option, @@ -53,7 +54,7 @@ struct UpdateSession { struct MarkRollCall { /// One of the school's attendance statuses (`GET /settings`; the core /// four are `present`, `absent`, `late`, `excused`). - #[schema(example = "present")] + #[schema(max_length = 50, example = "present")] status: String, /// Whose roll-call state to record: an enrolled student, or the session's /// teacher (the latter requires manager+). diff --git a/src/web/settings.rs b/src/web/settings.rs index 26c6599..83fcfa3 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -23,11 +23,11 @@ pub fn routes() -> OpenApiRouter { #[derive(Serialize, Deserialize, ToSchema)] struct ExamKindDto { /// The `kind` value exams carry, 1–50 characters. - #[schema(example = "midterm")] + #[schema(example = "midterm", max_length = 50)] name: String, /// The kind's weight in the course average, `1`–`100`. Editing it /// re-weights every exam of this kind at once. - #[schema(example = 2)] + #[schema(example = 2, minimum = 1, maximum = 100)] weight: i64, } @@ -36,10 +36,10 @@ struct ExamKindDto { #[derive(Serialize, Deserialize, ToSchema)] struct GradeBandDto { /// Lowest mark of the band, `0`–`100`. One band must start at `0`. - #[schema(example = 85)] + #[schema(example = 85, minimum = 0, maximum = 100)] min: i64, /// What that range shows as, 1–20 characters (`"AA"`, `"5"`, `"pass"`). - #[schema(example = "AA")] + #[schema(example = "AA", max_length = 20)] label: String, } @@ -108,28 +108,32 @@ impl SettingsResponse { struct UpdateSettings { /// Replaces the whole list when present: 1–20 entries with unique names, /// each name 1–50 characters, each weight `1`–`100`. + #[schema(max_items = 20)] exam_kinds: Option>, /// Replaces the whole list when present; must keep `present`, `absent`, - /// `late`, `excused` (the attendance rate is defined over them). + /// `late`, `excused` (the attendance rate is defined over them). Each entry + /// is 1–50 characters. + #[schema(max_items = 20)] attendance_statuses: Option>, /// Replaces the whole set when present. `[]` clears the bands (numeric-only /// marks); otherwise mins are unique and one band must start at `0`. + #[schema(max_items = 20)] grade_bands: Option>, /// Per-file size limit for note uploads, in bytes: /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap. - #[schema(example = 5_242_880)] + #[schema(example = 5_242_880, minimum = 1_024, maximum = 26_214_400)] max_file_bytes: Option, /// How many prior turns of a thread the chatbot is given as context, /// `1`–`50`. Every turn is re-sent on every reply, so this costs tokens. - #[schema(example = 10)] + #[schema(example = 10, minimum = 1, maximum = 50)] chatbot_history_turns: Option, /// How many chatbot threads one user may keep, `1`–`500`. At the cap /// the user deletes an old thread before starting a new one. - #[schema(example = 50)] + #[schema(example = 50, minimum = 1, maximum = 500)] max_chatbot_threads: Option, /// Character limit on one chat message, `100`–`8000`. The ceiling is a /// server hard cap. - #[schema(example = 4000)] + #[schema(example = 4000, minimum = 100, maximum = 8_000)] max_chatbot_message_len: Option, } diff --git a/src/web/subjects.rs b/src/web/subjects.rs index c9bffe3..2a27ff6 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -26,7 +26,9 @@ pub fn routes() -> OpenApiRouter { #[derive(Deserialize, ToSchema)] struct UpdateSubject { + #[schema(max_length = 200)] name: Option, + #[schema(max_length = 2000)] description: Option, } diff --git a/src/web/terms.rs b/src/web/terms.rs index b48374d..faf22fd 100644 --- a/src/web/terms.rs +++ b/src/web/terms.rs @@ -22,7 +22,7 @@ pub fn routes() -> OpenApiRouter { #[derive(Deserialize, ToSchema)] struct CreateTerm { - #[schema(example = "2026 Fall")] + #[schema(example = "2026 Fall", max_length = 100)] name: String, /// Term start, UTC unix-milliseconds. May lie in the past — a school /// adopting the app mid-year backfills its calendar legitimately. @@ -35,6 +35,7 @@ struct CreateTerm { #[derive(Deserialize, ToSchema)] struct UpdateTerm { + #[schema(max_length = 100)] name: Option, starts_at: Option, ends_at: Option, diff --git a/src/web/users.rs b/src/web/users.rs index e8617c1..cf3ce0d 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -49,12 +49,14 @@ struct SetRole { /// current value, an empty string clears it, anything else is validated and set. #[derive(Deserialize, ToSchema)] struct UpdateProfile { - #[schema(example = "Ada")] + #[schema(example = "Ada", max_length = 100)] name: Option, - #[schema(example = "Lovelace")] + #[schema(example = "Lovelace", max_length = 100)] surname: Option, - #[schema(example = "ada@example.com")] + #[schema(example = "ada@example.com", max_length = 254)] email: Option, + /// Any punctuation and spacing; it is the digit count that must land in + /// `7`–`15`, so no character-length bound applies. #[schema(example = "+90 555 123 45 67")] phone: Option, /// Birth date in `YYYY-MM-DD` form. diff --git a/tests/integration.rs b/tests/integration.rs index 50132de..00a0036 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -46,6 +46,123 @@ async fn time_serves_server_clock_without_auth() { assert!(before <= now && now <= after); } +#[tokio::test] +async fn limits_publishes_the_bounds_the_api_actually_enforces() { + let app = mem_app().await; + + let res = send(&app, "GET", "/limits", None, None).await; + assert_eq!(res.status, StatusCode::OK); + + // Every group is present — a frontend reads one document, not thirteen. + for group in [ + "user", + "note", + "file", + "message", + "event", + "course", + "exam", + "homework", + "question_pool", + "appointment", + "chatbot", + "settings", + "request", + ] { + assert!(res.body[group].is_object(), "missing group: {group}"); + } + + // The published value must equal the one the constants carry — the whole + // point is that the frontend stops keeping its own copy. + assert_eq!( + res.body["user"]["max_username_len"], + json!(hezarfen_backend::constant::MAX_USERNAME_LEN) + ); + assert_eq!(res.body["exam"]["modes"], json!(["sync", "async", "open"])); + assert_eq!( + res.body["user"]["roles"], + json!(["parent", "student", "teacher", "manager", "admin"]) + ); + + // The request budgets a caller is actually held to, read live off this + // server rather than from a constant — a client should learn its budget + // here, not by collecting a 429. + assert!(res.body["rate"]["auth_per_minute"].is_number()); + assert!(res.body["rate"]["api_per_minute"].is_number()); + assert!(res.body["rate"]["chatbot_per_minute"].is_number()); + assert_eq!(res.body["rate"]["window_secs"], json!(60)); + + // Structural sanity over EVERY published pair, which is what a spot-check + // of a few named fields cannot give: any `min_x` must not exceed its + // `max_x`. This is what catches a mapping that wired a floor to a ceiling + // — the one mistake a "does the constant appear?" check cannot see. + let groups = res.body.as_object().expect("limits is an object"); + let mut checked = 0; + for (group, fields) in groups { + let fields = fields.as_object().expect("each group is an object"); + for (key, value) in fields { + let Some(bare) = key.strip_prefix("min_") else { + continue; + }; + let Some(max) = fields.get(&format!("max_{bare}")) else { + continue; + }; + let (min, max) = ( + value.as_i64().expect("min is an integer"), + max.as_i64().expect("max is an integer"), + ); + assert!( + min <= max, + "{group}.{key} ({min}) exceeds its maximum ({max}) — the pair is inverted" + ); + checked += 1; + } + } + assert!( + checked >= 10, + "only {checked} min/max pairs were checked — the pairing broke, not the values" + ); + + // …and the endpoint that enforces it must agree: one over the published + // maximum is refused. This is what catches a constant moving without the + // limits response, or the reverse. + let max = res.body["user"]["max_username_len"] + .as_u64() + .expect("max_username_len is an integer") as usize; + let too_long = json!({ "username": "a".repeat(max + 1), "password": "secret1" }); + let res = send(&app, "POST", "/auth/register", None, Some(too_long)).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); +} + +#[tokio::test] +async fn limits_still_answers_while_the_database_is_down() { + // A frontend booting against a backend whose database is reconnecting is + // precisely when it needs the validation contract. `/limits` touches no + // row, so the outage guard must let it through — otherwise the client + // falls back to the hard-coded copy this endpoint exists to remove. + let db_up = hezarfen_backend::state::DbHealth::default(); + let app = build_router(AppState { + db: database::init_mem().await.expect("in-memory db"), + files_path: tempfile::tempdir().expect("files dir").keep(), + cookie_secure: false, + rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), + chatbot_limit: Default::default(), + exam_presence: Default::default(), + db_up: db_up.clone(), + ai: None, + }); + db_up.set(false); + + let res = send(&app, "GET", "/limits", None, None).await; + assert_eq!(res.status, StatusCode::OK); + assert!(res.body["user"]["max_username_len"].is_number()); + + // Everything that does touch the database still refuses, so the exemption + // is scoped to the one static route and has not disarmed the guard. + let res = send(&app, "GET", "/settings", None, None).await; + assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE); +} + #[tokio::test] async fn register_validates_input() { let app = mem_app().await; diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs new file mode 100644 index 0000000..23362a0 --- /dev/null +++ b/tests/limits_completeness.rs @@ -0,0 +1,257 @@ +//! The forcing function behind `GET /limits`. +//! +//! `src/web/limits.rs` is a hand-written mapping of `src/constant.rs` into a +//! JSON document. That is a mirror, and mirrors drift: the day someone adds a +//! constant, nothing about the compiler or the test suite would notice that +//! the endpoint promising "every fixed bound" quietly stopped being complete. +//! The frontend would then be back to guessing that one value — the exact +//! problem the endpoint exists to remove. +//! +//! So this test reads both files as text and asserts every `pub const` in +//! `constant.rs` is either referenced by `limits.rs` or listed below as a +//! deliberate exclusion with a reason. A new constant fails the suite until +//! someone makes that call consciously. +//! +//! Text, not reflection, because Rust cannot enumerate a module's constants at +//! runtime. The trade-off is that this proves a constant is *mentioned*, not +//! that it lands on a sensible JSON key — `integration::limits_publishes_the_ +//! bounds_the_api_actually_enforces` covers the values themselves. + +use std::collections::BTreeSet; +use std::fs; + +/// Constants that deliberately stay out of `GET /limits`, each with the reason +/// it is not a client-facing bound. Adding a name here is a decision, not a +/// formality: it says a frontend has no business knowing this number. +const EXCLUDED: &[(&str, &str)] = &[ + // Server-internal operational timing. A client cannot act on any of these, + // and publishing them would invite a frontend to build its own retry or + // liveness logic against numbers we want free to change. + ( + "DB_KEEPALIVE_INTERVAL_SECS", + "database socket keepalive cadence", + ), + ("DB_PING_TIMEOUT_SECS", "database liveness probe deadline"), + ( + "DB_CONNECT_BACKOFF_MAX_SECS", + "boot reconnect backoff ceiling", + ), + ( + "SETTINGS_UPDATE_RETRIES", + "internal compare-and-set retry count", + ), + ( + "UPLOAD_BODY_OVERHEAD_BYTES", + "multipart headroom over max_file_bytes; the client sizes against \ + max_file_bytes itself, which /limits does publish", + ), + // The AI bridge is a backend↔AI-service contract over QUIC. No browser + // ever speaks it; the services that do are configured out of band. + ("AI_PROTOCOL", "QUIC bridge wire identifier"), + ("AI_ALPN", "QUIC bridge ALPN"), + ("AI_MAX_FRAME_BYTES", "QUIC bridge frame ceiling"), + ("AI_DEFAULT_REQUEST_TIMEOUT_SECS", "AI inference deadline"), + ("AI_MAX_CONCURRENT_PER_WORKER", "AI worker concurrency cap"), + ( + "AI_DEFAULT_CONCURRENT_PER_WORKER", + "AI worker concurrency default", + ), + ("AI_IDLE_TIMEOUT_SECS", "QUIC connection idle timeout"), + ("AI_KEEPALIVE_SECS", "QUIC connection keepalive"), + ("AI_HANDSHAKE_TIMEOUT_SECS", "AI service handshake deadline"), + ( + "AI_CHAT_CAPABILITY", + "capability string an AI service declares", + ), + ( + "CHAT_STREAM_POLL_MS", + "server-side poll cadence behind the SSE stream", + ), + ( + "CHATBOT_PENDING_STALE_SECS", + "when a stuck answer is declared failed", + ), + // Seed data for the settings singleton, not a bound. The live list is on + // `GET /settings`, which is where a client must read it — publishing the + // default too would invite rendering it instead of the school's actual one. + ( + "DEFAULT_EXAM_KINDS", + "settings seed; the live list is on GET /settings", + ), +]; + +/// Every `pub const` declared in `src/constant.rs`. +fn declared_constants(source: &str) -> BTreeSet { + source + .lines() + .filter_map(|line| line.strip_prefix("pub const ")) + .filter_map(|rest| rest.split(&[':', ' '][..]).next()) + .filter(|name| !name.is_empty()) + .map(str::to_string) + .collect() +} + +/// True when `limits.rs` mentions the constant as a whole word — the response +/// is built by naming each constant directly, so a mention is the reference. +fn references(source: &str, name: &str) -> bool { + source.match_indices(name).any(|(at, _)| { + let before = source[..at].chars().next_back(); + let after = source[at + name.len()..].chars().next(); + let boundary = |c: Option| !matches!(c, Some(c) if c.is_alphanumeric() || c == '_'); + boundary(before) && boundary(after) + }) +} + +#[test] +fn every_constant_is_published_or_deliberately_excluded() { + let root = env!("CARGO_MANIFEST_DIR"); + let constants = + fs::read_to_string(format!("{root}/src/constant.rs")).expect("read constant.rs"); + let limits = fs::read_to_string(format!("{root}/src/web/limits.rs")).expect("read limits.rs"); + + let declared = declared_constants(&constants); + assert!( + declared.len() > 50, + "parsed only {} constants — the `pub const` parse broke, not the mapping", + declared.len() + ); + + let excluded: BTreeSet<&str> = EXCLUDED.iter().map(|(name, _)| *name).collect(); + let missing: Vec<&String> = declared + .iter() + .filter(|name| !excluded.contains(name.as_str()) && !references(&limits, name)) + .collect(); + + assert!( + missing.is_empty(), + "these constants are in src/constant.rs but reach neither GET /limits nor the \ + EXCLUDED list in this test:\n {}\n\nAdd each to src/web/limits.rs so clients \ + stop guessing it, or to EXCLUDED with the reason it is not client-facing.", + missing + .iter() + .map(|name| name.as_str()) + .collect::>() + .join("\n ") + ); +} + +/// Constants outside `constant.rs` that the sweep below may ignore — either +/// because they are not a client-facing bound at all, or because they are +/// published by a route that reads the *live* value instead of the constant. +const NOT_A_CLIENT_BOUND: &[(&str, &str)] = &[ + // Client-facing, but deliberately not compile-time constants: these are + // per-deployment defaults an operator overrides by environment variable, + // so `constant.rs` is the wrong home for them. `GET /limits` publishes the + // running server's ACTUAL tiers (from AppState) in its `rate` group, which + // is strictly better than publishing the default a deployment may not use. + ( + "DEFAULT_AUTH_RATE_LIMIT", + "env-tunable; live value served in /limits `rate`", + ), + ( + "DEFAULT_API_RATE_LIMIT", + "env-tunable; live value served in /limits `rate`", + ), + ( + "DEFAULT_CHATBOT_RATE_LIMIT", + "env-tunable; live value served in /limits `rate`", + ), + ("MILLIS_PER_DAY", "unit conversion, not a limit"), + ("MILLIS_PER_WEEK", "unit conversion, not a limit"), + ("MAX_BODY", "ETag middleware's own buffering ceiling"), + ("PURGE_AT", "rate-limiter bucket eviction threshold"), + ( + "MAX_ERROR_CODE_LEN", + "bounds a code the SERVER writes from an AI service's reply; no client sends it", + ), + ("REPLY_CHUNKS", "how the SSE stream slices an answer"), + ("MIN_CHUNK_CHARS", "how the SSE stream slices an answer"), +]; + +#[test] +fn validation_bounds_live_in_constant_rs() { + // The completeness test above only guards `constant.rs`, so a bound + // declared anywhere else is invisible to it — it reaches neither `/limits` + // nor the OpenAPI spec, and no test notices. That is not hypothetical: + // `MAX_CHATBOT_THREAD_TITLE_LEN` sat private in `domain/chatbot_thread.rs` + // and escaped both surfaces until this sweep found it. This test makes the + // constants file the only legal home for a client-facing bound. + let root = env!("CARGO_MANIFEST_DIR"); + let allowed: BTreeSet<&str> = NOT_A_CLIENT_BOUND.iter().map(|(name, _)| *name).collect(); + + let mut strays = Vec::new(); + let mut stack = vec![format!("{root}/src")]; + while let Some(dir) = stack.pop() { + for entry in fs::read_dir(&dir).expect("read src dir") { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + stack.push(path.to_string_lossy().into_owned()); + continue; + } + if path.extension().is_none_or(|ext| ext != "rs") || path.ends_with("constant.rs") { + continue; + } + let source = fs::read_to_string(&path).expect("read source"); + for line in source.lines() { + let trimmed = line.trim_start(); + // Only `const NAME: = ` — a bound. Arrays of + // accepted values (`Role::ALL`) and string constants are not. + let Some(rest) = trimmed + .strip_prefix("pub const ") + .or_else(|| trimmed.strip_prefix("const ")) + else { + continue; + }; + let Some((name, tail)) = rest.split_once(':') else { + continue; + }; + let looks_numeric = ["usize", "i64", "u64", "i32", "u32", "u16", "u8", "f64"] + .iter() + .any(|ty| tail.trim_start().starts_with(ty)); + // `DEFAULT_` and the `_LIMIT`/`_CAP` suffixes matter as much as + // the `MAX_`/`MIN_` prefixes: the rate-limit tiers are named + // `DEFAULT_API_RATE_LIMIT`, and a sweep keyed only on prefixes + // walked straight past a budget every client is held to. + let bound_shaped = name.starts_with("MAX_") + || name.starts_with("MIN_") + || name.starts_with("DEFAULT_") + || name.ends_with("_LIMIT") + || name.ends_with("_CAP"); + if looks_numeric && bound_shaped && !allowed.contains(name) { + let file = path.strip_prefix(root).unwrap_or(&path); + strays.push(format!(" {name} in {}", file.display())); + } + } + } + } + + assert!( + strays.is_empty(), + "these validation bounds live outside src/constant.rs, so they reach neither \ + GET /limits nor the OpenAPI spec and no test guards them:\n{}\n\nMove each into \ + src/constant.rs (and map it in src/web/limits.rs), or add it to \ + NOT_A_CLIENT_BOUND with the reason it is not a client-facing limit.", + strays.join("\n") + ); +} + +#[test] +fn exclusions_are_real_constants() { + // An exclusion for a deleted constant is dead weight that also silently + // widens the allowlist if the name is ever reused for something public. + let root = env!("CARGO_MANIFEST_DIR"); + let constants = + fs::read_to_string(format!("{root}/src/constant.rs")).expect("read constant.rs"); + let declared = declared_constants(&constants); + + let stale: Vec<&str> = EXCLUDED + .iter() + .map(|(name, _)| *name) + .filter(|name| !declared.contains(*name)) + .collect(); + + assert!( + stale.is_empty(), + "EXCLUDED names constants that no longer exist in src/constant.rs: {stale:?} — drop them" + ); +} diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs new file mode 100644 index 0000000..392f76c --- /dev/null +++ b/tests/spec_bounds.rs @@ -0,0 +1,721 @@ +//! The OpenAPI document must not lie about its own bounds. +//! +//! utoipa 5.5's `#[schema(max_length = …)]` accepts a **literal only** — a +//! `const` there fails to compile with "no `literal` value found after this +//! point". So every annotation in `src/web/*.rs` is unavoidably a hand-copied +//! duplicate of a number in `src/constant.rs`, and a copy nothing checks is a +//! copy that silently goes stale. A frontend generating validators from +//! `/api-docs/openapi.json` would then enforce yesterday's rule and get 400s it +//! cannot explain. +//! +//! This test closes that loop from the far end: it builds the real router, +//! fetches the emitted spec, and asserts each published bound still equals the +//! constant the server actually validates against. The expectations below are +//! the constants — never literals — because a test written against literals +//! would be a third copy and would pass while both were wrong. + +use axum::body::Body; +use axum::http::Request; +use hezarfen_backend::constant::*; +use hezarfen_backend::state::AppState; +use hezarfen_backend::{build_router, database}; +use serde_json::Value; +use tower::ServiceExt; + +/// The emitted OpenAPI document, as the server serves it. +async fn spec() -> Value { + let db = database::init_mem().await.expect("in-memory db"); + let app = build_router(AppState { + db, + files_path: tempfile::tempdir().expect("files dir").keep(), + cookie_secure: false, + rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), + chatbot_limit: Default::default(), + exam_presence: Default::default(), + db_up: Default::default(), + ai: None, + }); + let res = app + .oneshot( + Request::builder() + .uri("/api-docs/openapi.json") + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("spec response"); + let bytes = axum::body::to_bytes(res.into_body(), usize::MAX) + .await + .expect("spec body"); + serde_json::from_slice(&bytes).expect("spec is json") +} + +/// Every published request-schema bound, paired with the constant it must +/// equal. Columns: schema, field, JSON Schema keyword, expected value. +/// +/// Add a row whenever you add a `#[schema(max_length = …)]`-style attribute to +/// a request DTO — the annotation is the promise, this row is the proof. +fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { + vec![ + // --- auth / users / notes / messages --- + ( + "Credentials", + "username", + "minLength", + MIN_USERNAME_LEN as i64, + ), + ( + "Credentials", + "username", + "maxLength", + MAX_USERNAME_LEN as i64, + ), + ( + "Credentials", + "password", + "minLength", + MIN_PASSWORD_LEN as i64, + ), + ( + "Credentials", + "password", + "maxLength", + MAX_PASSWORD_LEN as i64, + ), + ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64), + ("UpdateProfile", "surname", "maxLength", MAX_NAME_LEN as i64), + ("UpdateProfile", "email", "maxLength", MAX_EMAIL_LEN as i64), + ( + "CreateNote", + "title", + "maxLength", + MAX_NOTE_TITLE_LEN as i64, + ), + ( + "CreateNote", + "content", + "maxLength", + MAX_NOTE_CONTENT_LEN as i64, + ), + ( + "UpdateNote", + "title", + "maxLength", + MAX_NOTE_TITLE_LEN as i64, + ), + ( + "UpdateNote", + "content", + "maxLength", + MAX_NOTE_CONTENT_LEN as i64, + ), + ( + "SendMessage", + "subject", + "maxLength", + MAX_MESSAGE_SUBJECT_LEN as i64, + ), + ( + "SendMessage", + "body", + "maxLength", + MAX_MESSAGE_BODY_LEN as i64, + ), + ( + "SendMessage", + "label", + "maxLength", + MAX_MESSAGE_LABEL_LEN as i64, + ), + // --- events / appointments / courses / subjects / sessions --- + ( + "CreateEvent", + "title", + "maxLength", + MAX_EVENT_TITLE_LEN as i64, + ), + ( + "CreateEvent", + "description", + "maxLength", + MAX_EVENT_DESCRIPTION_LEN as i64, + ), + ( + "UpdateEvent", + "title", + "maxLength", + MAX_EVENT_TITLE_LEN as i64, + ), + ( + "UpdateEvent", + "description", + "maxLength", + MAX_EVENT_DESCRIPTION_LEN as i64, + ), + ( + "MarkAttendance", + "status", + "maxLength", + MAX_SETTINGS_ITEM_LEN as i64, + ), + ( + "PublishSlots", + "note", + "maxLength", + MAX_APPOINTMENT_NOTE_LEN as i64, + ), + ( + "BookAppointment", + "reason", + "maxLength", + MAX_APPOINTMENT_REASON_LEN as i64, + ), + ( + "CancelRequest", + "reason", + "maxLength", + MAX_APPOINTMENT_REASON_LEN as i64, + ), + ( + "RejectRequest", + "reason", + "maxLength", + MAX_APPOINTMENT_REASON_LEN as i64, + ), + ( + "CreateCourse", + "title", + "maxLength", + MAX_COURSE_TITLE_LEN as i64, + ), + ( + "CreateCourse", + "description", + "maxLength", + MAX_COURSE_DESCRIPTION_LEN as i64, + ), + ( + "UpdateCourse", + "title", + "maxLength", + MAX_COURSE_TITLE_LEN as i64, + ), + ( + "UpdateCourse", + "description", + "maxLength", + MAX_COURSE_DESCRIPTION_LEN as i64, + ), + ( + "CreateExamInCourse", + "title", + "maxLength", + MAX_EXAM_TITLE_LEN as i64, + ), + ( + "CreateExamInCourse", + "description", + "maxLength", + MAX_EXAM_DESCRIPTION_LEN as i64, + ), + ( + "CreateExamInCourse", + "kind", + "maxLength", + MAX_SETTINGS_ITEM_LEN as i64, + ), + ( + "CreateExamInCourse", + "duration_ms", + "minimum", + MIN_EXAM_DURATION_MS, + ), + ( + "CreateExamInCourse", + "duration_ms", + "maximum", + MAX_EXAM_DURATION_MS, + ), + ( + "CreateExamInCourse", + "max_attempts", + "minimum", + UNLIMITED_EXAM_ATTEMPTS, + ), + ( + "CreateExamInCourse", + "max_attempts", + "maximum", + MAX_EXAM_ATTEMPTS, + ), + ( + "CreateSubject", + "name", + "maxLength", + MAX_SUBJECT_NAME_LEN as i64, + ), + ( + "CreateSubject", + "description", + "maxLength", + MAX_SUBJECT_DESCRIPTION_LEN as i64, + ), + ( + "CreateHomework", + "title", + "maxLength", + MAX_HOMEWORK_TITLE_LEN as i64, + ), + ( + "CreateHomework", + "description", + "maxLength", + MAX_HOMEWORK_DESCRIPTION_LEN as i64, + ), + ( + "CreateHomework", + "assigned", + "maxItems", + MAX_HOMEWORK_ASSIGNED as i64, + ), + ( + "CreateSessionInCourse", + "topic", + "maxLength", + MAX_SESSION_TOPIC_LEN as i64, + ), + ( + "UpdateSession", + "topic", + "maxLength", + MAX_SESSION_TOPIC_LEN as i64, + ), + ( + "MarkRollCall", + "status", + "maxLength", + MAX_SETTINGS_ITEM_LEN as i64, + ), + ( + "UpdateSubject", + "name", + "maxLength", + MAX_SUBJECT_NAME_LEN as i64, + ), + ( + "UpdateSubject", + "description", + "maxLength", + MAX_SUBJECT_DESCRIPTION_LEN as i64, + ), + // --- exams / questions / question bank --- + ( + "UpdateExam", + "title", + "maxLength", + MAX_EXAM_TITLE_LEN as i64, + ), + ( + "UpdateExam", + "description", + "maxLength", + MAX_EXAM_DESCRIPTION_LEN as i64, + ), + ("UpdateExam", "duration_ms", "minimum", MIN_EXAM_DURATION_MS), + ("UpdateExam", "duration_ms", "maximum", MAX_EXAM_DURATION_MS), + ( + "UpdateExam", + "max_attempts", + "minimum", + UNLIMITED_EXAM_ATTEMPTS, + ), + ("UpdateExam", "max_attempts", "maximum", MAX_EXAM_ATTEMPTS), + ("GradeResult", "mark", "minimum", MIN_MARK), + ("GradeResult", "mark", "maximum", MAX_MARK), + ( + "CreateQuestion", + "text", + "maxLength", + MAX_QUESTION_TEXT_LEN as i64, + ), + ("CreateQuestion", "points", "minimum", MIN_QUESTION_POINTS), + ("CreateQuestion", "points", "maximum", MAX_QUESTION_POINTS), + ( + "CreateQuestion", + "choices", + "minItems", + MIN_QUESTION_CHOICES as i64, + ), + ( + "CreateQuestion", + "choices", + "maxItems", + MAX_QUESTION_CHOICES as i64, + ), + ( + "UpdateQuestion", + "text", + "maxLength", + MAX_QUESTION_TEXT_LEN as i64, + ), + ("UpdateQuestion", "points", "minimum", MIN_QUESTION_POINTS), + ("UpdateQuestion", "points", "maximum", MAX_QUESTION_POINTS), + ( + "UpdateQuestion", + "choices", + "minItems", + MIN_QUESTION_CHOICES as i64, + ), + ( + "UpdateQuestion", + "choices", + "maxItems", + MAX_QUESTION_CHOICES as i64, + ), + ( + "SaveAnswer", + "text", + "maxLength", + MAX_ANSWER_TEXT_LEN as i64, + ), + ( + "AskQuestion", + "title", + "maxLength", + MAX_POOL_QUESTION_TITLE_LEN as i64, + ), + ( + "AskQuestion", + "body", + "maxLength", + MAX_POOL_QUESTION_BODY_LEN as i64, + ), + ( + "OfferSolution", + "body", + "maxLength", + MAX_SOLUTION_BODY_LEN as i64, + ), + ( + "CreateBankQuestion", + "text", + "maxLength", + MAX_QUESTION_TEXT_LEN as i64, + ), + ( + "CreateBankQuestion", + "points", + "minimum", + MIN_QUESTION_POINTS, + ), + ( + "CreateBankQuestion", + "points", + "maximum", + MAX_QUESTION_POINTS, + ), + ( + "CreateBankQuestion", + "choices", + "minItems", + MIN_QUESTION_CHOICES as i64, + ), + ( + "CreateBankQuestion", + "choices", + "maxItems", + MAX_QUESTION_CHOICES as i64, + ), + ( + "UpdateBankQuestion", + "text", + "maxLength", + MAX_QUESTION_TEXT_LEN as i64, + ), + ( + "UpdateBankQuestion", + "points", + "minimum", + MIN_QUESTION_POINTS, + ), + ( + "UpdateBankQuestion", + "points", + "maximum", + MAX_QUESTION_POINTS, + ), + ( + "UpdateBankQuestion", + "choices", + "minItems", + MIN_QUESTION_CHOICES as i64, + ), + ( + "UpdateBankQuestion", + "choices", + "maxItems", + MAX_QUESTION_CHOICES as i64, + ), + ( + "ChoiceBody", + "text", + "maxLength", + MAX_CHOICE_TEXT_LEN as i64, + ), + // --- homework / settings / terms / chatbot --- + ( + "UpdateHomework", + "title", + "maxLength", + MAX_HOMEWORK_TITLE_LEN as i64, + ), + ( + "UpdateHomework", + "description", + "maxLength", + MAX_HOMEWORK_DESCRIPTION_LEN as i64, + ), + ( + "UpdateHomework", + "assigned", + "maxItems", + MAX_HOMEWORK_ASSIGNED as i64, + ), + ( + "SubmitHomework", + "text", + "maxLength", + MAX_HOMEWORK_TEXT_LEN as i64, + ), + ("GradeHomework", "mark", "minimum", MIN_MARK), + ("GradeHomework", "mark", "maximum", MAX_MARK), + ( + "ExamKindDto", + "name", + "maxLength", + MAX_SETTINGS_ITEM_LEN as i64, + ), + ("ExamKindDto", "weight", "minimum", MIN_EXAM_KIND_WEIGHT), + ("ExamKindDto", "weight", "maximum", MAX_EXAM_KIND_WEIGHT), + ("GradeBandDto", "min", "minimum", MIN_MARK), + ("GradeBandDto", "min", "maximum", MAX_MARK), + ( + "GradeBandDto", + "label", + "maxLength", + MAX_GRADE_LABEL_LEN as i64, + ), + ( + "UpdateSettings", + "exam_kinds", + "maxItems", + MAX_SETTINGS_LIST_LEN as i64, + ), + ( + "UpdateSettings", + "attendance_statuses", + "maxItems", + MAX_SETTINGS_LIST_LEN as i64, + ), + ( + "UpdateSettings", + "grade_bands", + "maxItems", + MAX_GRADE_BANDS as i64, + ), + ( + "UpdateSettings", + "max_file_bytes", + "minimum", + MIN_MAX_FILE_BYTES, + ), + ( + "UpdateSettings", + "max_file_bytes", + "maximum", + MAX_MAX_FILE_BYTES, + ), + ( + "UpdateSettings", + "chatbot_history_turns", + "minimum", + MIN_CHATBOT_HISTORY_TURNS, + ), + ( + "UpdateSettings", + "chatbot_history_turns", + "maximum", + MAX_CHATBOT_HISTORY_TURNS, + ), + ( + "UpdateSettings", + "max_chatbot_threads", + "minimum", + MIN_MAX_CHATBOT_THREADS, + ), + ( + "UpdateSettings", + "max_chatbot_threads", + "maximum", + MAX_MAX_CHATBOT_THREADS, + ), + ( + "UpdateSettings", + "max_chatbot_message_len", + "minimum", + MIN_MAX_CHATBOT_MESSAGE_LEN, + ), + ( + "UpdateSettings", + "max_chatbot_message_len", + "maximum", + MAX_MAX_CHATBOT_MESSAGE_LEN, + ), + ("CreateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64), + ("UpdateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64), + ( + "SendChatbotMessage", + "content", + "maxLength", + MAX_CHATBOT_MESSAGE_LEN as i64, + ), + // --- chatbot thread titles (constant promoted out of + // domain/chatbot_thread.rs, where it escaped both surfaces) --- + ( + "CreateChatbotThread", + "title", + "maxLength", + MAX_CHATBOT_THREAD_TITLE_LEN as i64, + ), + ( + "RenameChatbotThread", + "title", + "maxLength", + MAX_CHATBOT_THREAD_TITLE_LEN as i64, + ), + ] +} + +#[tokio::test] +async fn published_bounds_match_the_constants() { + let spec = spec().await; + let schemas = &spec["components"]["schemas"]; + + let mut wrong = Vec::new(); + for (schema, field, keyword, want) in expectations() { + let got = schemas[schema]["properties"][field][keyword].as_i64(); + if got != Some(want) { + wrong.push(format!( + " {schema}.{field}: spec says {keyword}={got:?}, constant says {want}" + )); + } + } + + assert!( + wrong.is_empty(), + "the OpenAPI spec disagrees with src/constant.rs — a client generating \ + validators from it would enforce the wrong rule:\n{}\n\nutoipa takes \ + literals only, so fix the `#[schema(...)]` attribute to match the constant.", + wrong.join("\n") + ); +} + +#[tokio::test] +async fn every_page_limit_param_matches_its_constant() { + // `#[param(maximum = 500)]` is written out beside MAX_PAGE_LIMIT, and + // constant.rs merely *asks* a human to keep the two in step. This makes + // that request enforceable. + // + // EVERY `limit` parameter, not the first one found: `src/web/page.rs` is + // the shared one, but `src/web/users.rs` declares its own search paging + // with the literal repeated. Checking one would have left the other free + // to drift — which is exactly the bug this test was written to prevent. + let spec = spec().await; + + let limits: Vec<_> = spec["paths"] + .as_object() + .expect("paths") + .values() + .filter_map(|path| path.as_object()) + .flat_map(|path| path.values()) + .filter_map(|op| op["parameters"].as_array()) + .flatten() + .filter(|param| param["name"] == "limit") + .collect(); + + assert!( + !limits.is_empty(), + "no endpoint publishes a `limit` query parameter — the paging contract vanished" + ); + + let drifted: Vec = limits + .iter() + .filter(|param| param["schema"]["maximum"].as_i64() != Some(MAX_PAGE_LIMIT)) + .map(|param| format!(" {:?}", param["schema"]["maximum"])) + .collect(); + + assert!( + drifted.is_empty(), + "{} of {} published `limit` parameters disagree with MAX_PAGE_LIMIT ({}):\n{}\n\n\ + Update the `#[param(maximum = ...)]` that drifted (src/web/page.rs is the shared \ + one; src/web/users.rs declares its own).", + drifted.len(), + limits.len(), + MAX_PAGE_LIMIT, + drifted.join("\n") + ); +} + +/// Every `#[schema(...)]` bound in the web layer must have a row in +/// [`expectations`] — otherwise the table is itself a mirror that silently +/// lags, and a new annotation gets published with nothing checking it. +/// +/// This is not hypothetical: the `CreateHomework.assigned` row was added by a +/// text substitution that silently matched nothing after rustfmt rewrapped the +/// anchor line. The suite stayed green with the row missing. This test is what +/// catches that class. +#[test] +fn expectations_cover_every_annotation() { + let root = env!("CARGO_MANIFEST_DIR"); + let keywords = [ + "max_length", + "min_length", + "minimum", + "maximum", + "min_items", + "max_items", + ]; + + let mut annotated = 0; + for entry in std::fs::read_dir(format!("{root}/src/web")).expect("read src/web") { + let path = entry.expect("dir entry").path(); + if path.extension().is_none_or(|ext| ext != "rs") { + continue; + } + let source = std::fs::read_to_string(&path).expect("read source"); + // Scan whole attributes, not lines: rustfmt wraps a long + // `#[schema(example = "…", max_length = 5_000)]` across several lines, + // and a line-based count silently misses the wrapped keyword. + // + // `#[param(...)]` bounds are query parameters, covered by + // `every_page_limit_param_matches_its_constant` instead. + for (at, _) in source.match_indices("#[schema(") { + let rest = &source[at..]; + let end = rest.find(")]").map_or(rest.len(), |end| end + 2); + let attribute = &rest[..end]; + annotated += keywords + .iter() + .filter(|kw| attribute.contains(&format!("{kw} = "))) + .count(); + } + } + + assert_eq!( + annotated, + expectations().len(), + "src/web/ carries {annotated} `#[schema(...)]` bounds but the expectations table \ + has {} rows — every annotation needs a row, or it is published with nothing \ + asserting it still matches its constant.", + expectations().len() + ); +}