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