File attachments with school-set size cap
Browse files at this commitf1b532bba631a123ff3efd12b8a933ab122c0177Parent: 32949bd- feat
- file attachments with school-set size cap
25 changed files +1546 -120
- .env.example +4 -0
- Cargo.lock +27 -0
- Cargo.toml +3 -2
- README.md +38 -14
- compose.yaml +1 -0
- src/config.rs +4 -0
- src/constant.rs +20 -0
- src/database.rs +9 -0
- src/domain/mod.rs +1 -0
- src/domain/note.rs +8 -0
- src/domain/note_file.rs +255 -0
- src/domain/settings.rs +123 -19
- src/error.rs +5 -0
- src/lib.rs +3 -3
- src/main.rs +4 -0
- src/state.rs +5 -0
- src/web/exam_ws.rs +1 -0
- src/web/notes.rs +370 -4
- src/web/settings.rs +16 -3
- tests/common/mod.rs +98 -1
- tests/e2e.rs +3 -0
- tests/integration.rs +446 -51
- tests/pagination.rs +26 -4
- tests/persistence.rs +74 -19
- tests/rate_limit.rs +2 -0
.env.examplemodified+4 -0
| @@ -7,6 +7,10 @@ DB_PATH=./data/hezarfen.db | |||
| 7 | DB_NAMESPACE=hezarfen | 7 | DB_NAMESPACE=hezarfen |
| 8 | DB_DATABASE=hezarfen | 8 | DB_DATABASE=hezarfen |
| 9 | 9 | ||
| 10 | +# Directory for uploaded note-file blobs (created at startup). Keep it beside | ||
| 11 | +# the database so one volume persists both. | ||
| 12 | +FILES_PATH=./data/files | ||
| 13 | + | ||
| 10 | # Optional log filter. | 14 | # Optional log filter. |
| 11 | RUST_LOG=info,hezarfen_backend=debug | 15 | RUST_LOG=info,hezarfen_backend=debug |
| 12 | 16 | ||
Cargo.lockmodified+27 -0
| @@ -279,6 +279,7 @@ dependencies = [ | |||
| 279 | "matchit", | 279 | "matchit", |
| 280 | "memchr", | 280 | "memchr", |
| 281 | "mime", | 281 | "mime", |
| 282 | + "multer", | ||
| 282 | "percent-encoding", | 283 | "percent-encoding", |
| 283 | "pin-project-lite", | 284 | "pin-project-lite", |
| 284 | "serde_core", | 285 | "serde_core", |
| @@ -1141,6 +1142,15 @@ dependencies = [ | |||
| 1141 | "zeroize", | 1142 | "zeroize", |
| 1142 | ] | 1143 | ] |
| 1143 | 1144 | ||
| 1145 | +[[package]] | ||
| 1146 | +name = "encoding_rs" | ||
| 1147 | +version = "0.8.35" | ||
| 1148 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1149 | +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" | ||
| 1150 | +dependencies = [ | ||
| 1151 | + "cfg-if", | ||
| 1152 | +] | ||
| 1153 | + | ||
| 1144 | [[package]] | 1154 | [[package]] |
| 1145 | name = "equivalent" | 1155 | name = "equivalent" |
| 1146 | version = "1.0.2" | 1156 | version = "1.0.2" |
| @@ -2352,6 +2362,23 @@ dependencies = [ | |||
| 2352 | "windows-sys 0.61.2", | 2362 | "windows-sys 0.61.2", |
| 2353 | ] | 2363 | ] |
| 2354 | 2364 | ||
| 2365 | +[[package]] | ||
| 2366 | +name = "multer" | ||
| 2367 | +version = "3.1.0" | ||
| 2368 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2369 | +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" | ||
| 2370 | +dependencies = [ | ||
| 2371 | + "bytes", | ||
| 2372 | + "encoding_rs", | ||
| 2373 | + "futures-util", | ||
| 2374 | + "http", | ||
| 2375 | + "httparse", | ||
| 2376 | + "memchr", | ||
| 2377 | + "mime", | ||
| 2378 | + "spin", | ||
| 2379 | + "version_check", | ||
| 2380 | +] | ||
| 2381 | + | ||
| 2355 | [[package]] | 2382 | [[package]] |
| 2356 | name = "ndarray" | 2383 | name = "ndarray" |
| 2357 | version = "0.17.2" | 2384 | version = "0.17.2" |
Cargo.tomlmodified+3 -2
| @@ -13,8 +13,9 @@ disallowed_types = "deny" | |||
| 13 | tokio = { version = "1", features = ["full"] } | 13 | tokio = { version = "1", features = ["full"] } |
| 14 | # IntervalStream for the live exam-monitor SSE tick. | 14 | # IntervalStream for the live exam-monitor SSE tick. |
| 15 | tokio-stream = "0.1" | 15 | tokio-stream = "0.1" |
| 16 | -# "ws" backs the live exam room (WebSocket at /exams/{id}/attempt/ws). | 16 | +# "ws" backs the live exam room (WebSocket at /exams/{id}/attempt/ws); |
| 17 | -axum = { version = "0.8", features = ["ws"] } | 17 | +# "multipart" backs note file uploads (POST /notes/{id}/files). |
| 18 | +axum = { version = "0.8", features = ["ws", "multipart"] } | ||
| 18 | axum-extra = { version = "0.10", features = ["cookie"] } | 19 | axum-extra = { version = "0.10", features = ["cookie"] } |
| 19 | tower-http = { version = "0.6", features = ["trace", "cors"] } | 20 | tower-http = { version = "0.6", features = ["trace", "cors"] } |
| 20 | surrealdb = { version = "3", default-features = false, features = ["kv-surrealkv", "kv-mem"] } | 21 | surrealdb = { version = "3", default-features = false, features = ["kv-surrealkv", "kv-mem"] } |
README.mdmodified+38 -14
| @@ -3,7 +3,10 @@ | |||
| 3 | Note, attendance, course + weighted exam mark backend. **Rust (edition 2024) · axum · SurrealDB 3 (embedded surrealkv) · tokio.** | 3 | Note, attendance, course + weighted exam mark backend. **Rust (edition 2024) · axum · SurrealDB 3 (embedded surrealkv) · tokio.** |
| 4 | 4 | ||
| 5 | Session-cookie auth with four hierarchical roles (`student < teacher < manager | 5 | Session-cookie auth with four hierarchical roles (`student < teacher < manager |
| 6 | -< admin`). Notes are per-user. Attendance is event + attendees: create an event, | 6 | +< admin`). Notes are per-user and carry **file attachments** (PDFs, documents, |
| 7 | +…): blobs live on disk next to the database, metadata in the database, and the | ||
| 8 | +per-file size cap is school policy in settings (`max_file_bytes`, default | ||
| 9 | +5 MiB). Attendance is event + attendees: create an event, | ||
| 7 | then mark users present / absent / late / excused. Marks are course-shaped | 10 | then mark users present / absent / late / excused. Marks are course-shaped |
| 8 | (Google Classroom style): a teacher creates a course, enrolls students, adds | 11 | (Google Classroom style): a teacher creates a course, enrolls students, adds |
| 9 | exams inside it, and grades — enrolling, sitting exams, roll call, and marks are | 12 | exams inside it, and grades — enrolling, sitting exams, roll call, and marks are |
| @@ -22,9 +25,9 @@ sessions** with teacher-taken roll call (students never self-mark a lesson), | |||
| 22 | staff clock in/out on a server-stamped **work log**, and every user has an | 25 | staff clock in/out on a server-stamped **work log**, and every user has an |
| 23 | **attendance report** (event + per-course lesson tallies with rates). | 26 | **attendance report** (event + per-course lesson tallies with rates). |
| 24 | School-varying policy is data, not code: exam kinds (each with its weight in | 27 | School-varying policy is data, not code: exam kinds (each with its weight in |
| 25 | -course averages), attendance statuses, and grade-display bands live in an | 28 | +course averages), attendance statuses, grade-display bands, and the note-file |
| 26 | -editable **settings** singleton, and academic **terms** are plain rows courses | 29 | +size limit live in an editable **settings** singleton, and academic **terms** |
| 27 | -can link to (see "Per-school policy"). | 30 | +are plain rows courses can link to (see "Per-school policy"). |
| 28 | 31 | ||
| 29 | Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …) | 32 | Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …) |
| 30 | constructed only after its restrictions pass — invalid input can't be | 33 | constructed only after its restrictions pass — invalid input can't be |
| @@ -40,8 +43,10 @@ cargo run | |||
| 40 | ``` | 43 | ``` |
| 41 | 44 | ||
| 42 | Boots on `http://127.0.0.1:8080`, storing data in `./data/hezarfen.db` | 45 | Boots on `http://127.0.0.1:8080`, storing data in `./data/hezarfen.db` |
| 43 | -(embedded surrealkv — no external DB server). Interactive API docs (Swagger UI) | 46 | +(embedded surrealkv — no external DB server) and uploaded note files in |
| 44 | -are served at `/swagger`, the raw OpenAPI spec at `/api-docs/openapi.json`. | 47 | +`./data/files/` (`FILES_PATH`, created at startup). Interactive API docs |
| 48 | +(Swagger UI) are served at `/swagger`, the raw OpenAPI spec at | ||
| 49 | +`/api-docs/openapi.json`. | ||
| 45 | 50 | ||
| 46 | ## Run in a container (podman) | 51 | ## Run in a container (podman) |
| 47 | 52 | ||
| @@ -54,7 +59,8 @@ podman compose down # stop (data survives in the volume) | |||
| 54 | The `Containerfile` is a two-stage build (Rust builder with cargo cache | 59 | The `Containerfile` is a two-stage build (Rust builder with cargo cache |
| 55 | mounts, `debian:trixie-slim` runtime, non-root user). Since the database is | 60 | mounts, `debian:trixie-slim` runtime, non-root user). Since the database is |
| 56 | embedded there is only one service; its data lives in the named volume | 61 | embedded there is only one service; its data lives in the named volume |
| 57 | -`hezarfen-data`, mounted at `/data`. `HOST` is forced to `0.0.0.0` inside the | 62 | +`hezarfen-data`, mounted at `/data` — the database and the uploaded note |
| 63 | +files (`/data/files`) together, so that one volume persists everything. `HOST` is forced to `0.0.0.0` inside the | ||
| 58 | container so the published port works. Production knobs (`COOKIE_SECURE`, | 64 | container so the published port works. Production knobs (`COOKIE_SECURE`, |
| 59 | `CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in | 65 | `CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in |
| 60 | `compose.yaml` — uncomment as needed. Works with `docker compose` too. | 66 | `compose.yaml` — uncomment as needed. Works with `docker compose` too. |
| @@ -154,7 +160,7 @@ effect on the user's very next call (no re-login). | |||
| 154 | | Action | Minimum role | Notes | | 160 | | Action | Minimum role | Notes | |
| 155 | |------------------------------------------|--------------|-----------------------------------------------| | 161 | |------------------------------------------|--------------|-----------------------------------------------| |
| 156 | | Register / login / view own account | (any) | Registration always creates a `student` | | 162 | | Register / login / view own account | (any) | Registration always creates a `student` | |
| 157 | -| View events, own notes; CRUD notes | student | Everyone can read events and keep notes | | 163 | +| View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves | |
| 158 | | Mark **own** attendance | student | Anyone can mark themselves | | 164 | | Mark **own** attendance | student | Anyone can mark themselves | |
| 159 | | Mark **another user's** attendance | teacher | | | 165 | | Mark **another user's** attendance | teacher | | |
| 160 | | Create events; remove attendance rows | teacher | | | 166 | | Create events; remove attendance rows | teacher | | |
| @@ -182,7 +188,7 @@ effect on the user's very next call (no re-login). | |||
| 182 | | Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself | | 188 | | Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself | |
| 183 | | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields | | 189 | | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields | |
| 184 | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | | 190 | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | |
| 185 | -| Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands) and the academic calendar are management's call | | 191 | +| Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call | |
| 186 | | List users; look up one user; change a user's role; edit **any** user's personal info | admin | An admin cannot change **their own** role | | 192 | | List users; look up one user; change a user's role; edit **any** user's personal info | admin | An admin cannot change **their own** role | |
| 187 | 193 | ||
| 188 | ### Bootstrapping the first admin | 194 | ### Bootstrapping the first admin |
| @@ -263,7 +269,11 @@ their existing shapes: the student exam-room reads | |||
| 263 | | GET | `/notes` | student | List own notes · paged | | 269 | | GET | `/notes` | student | List own notes · paged | |
| 264 | | GET | `/notes/{id}` | student | Get own note | | 270 | | GET | `/notes/{id}` | student | Get own note | |
| 265 | | PATCH | `/notes/{id}` | student | `{title?, content?}` | | 271 | | PATCH | `/notes/{id}` | student | `{title?, content?}` | |
| 266 | -| DELETE | `/notes/{id}` | student | Delete own note | | 272 | +| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) | |
| 273 | +| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) — ≤ the school's `max_file_bytes`, ≤ 10 files per note | | ||
| 274 | +| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) · paged | | ||
| 275 | +| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) | | ||
| 276 | +| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file | | ||
| 267 | | POST | `/events` | teacher | `{title, description?, starts_at?, ends_at?}` | | 277 | | POST | `/events` | teacher | `{title, description?, starts_at?, ends_at?}` | |
| 268 | | GET | `/events` | student | List all events · paged | | 278 | | GET | `/events` | student | List all events · paged | |
| 269 | | GET | `/events/{id}` | student | Get event | | 279 | | GET | `/events/{id}` | student | Get event | |
| @@ -323,8 +333,8 @@ their existing shapes: the student exam-room reads | |||
| 323 | | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) | | 333 | | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) | |
| 324 | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | 334 | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | |
| 325 | | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) | | 335 | | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) | |
| 326 | -| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands` | | 336 | +| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes` | |
| 327 | -| PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale; concurrent edits merge, never silently revert each other (see "Per-school policy") | | 337 | +| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other (see "Per-school policy") | |
| 328 | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | | 338 | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | |
| 329 | | GET | `/terms` | student | List terms, newest first · paged | | 339 | | GET | `/terms` | student | List terms, newest first · paged | |
| 330 | | GET | `/terms/{id}` | student | Get one term | | 340 | | GET | `/terms/{id}` | student | Get one term | |
| @@ -381,7 +391,7 @@ unlike emails). | |||
| 381 | 391 | ||
| 382 | Every school runs differently; the parts that vary are data, not code. One | 392 | Every school runs differently; the parts that vary are data, not code. One |
| 383 | editable `settings` singleton (`GET /settings` for any signed-in user, | 393 | editable `settings` singleton (`GET /settings` for any signed-in user, |
| 384 | -`PATCH /settings` for manager+) carries three knobs: | 394 | +`PATCH /settings` for manager+) carries four knobs: |
| 385 | 395 | ||
| 386 | - **`exam_kinds`** — the accepted `kind` values for new exams, each an | 396 | - **`exam_kinds`** — the accepted `kind` values for new exams, each an |
| 387 | object `{name, weight}`. The weight (`1`–`100`) is how many times an exam | 397 | object `{name, weight}`. The weight (`1`–`100`) is how many times an exam |
| @@ -403,6 +413,10 @@ editable `settings` singleton (`GET /settings` for any signed-in user, | |||
| 403 | averaging stay `0`–`100` forever — bands only add `grade`, | 413 | averaging stay `0`–`100` forever — bands only add `grade`, |
| 404 | `average_grade`, and `overall_grade` labels to the mark report, so a school | 414 | `average_grade`, and `overall_grade` labels to the mark report, so a school |
| 405 | can switch display scales without touching a single stored mark. | 415 | can switch display scales without touching a single stored mark. |
| 416 | +- **`max_file_bytes`** — the per-file size cap for note uploads, in bytes: | ||
| 417 | + `1024` (1 KiB) to `26214400` (25 MiB; a server hard cap — uploads buffer in | ||
| 418 | + memory), default `5242880` (5 MiB). Checked at upload time only: | ||
| 419 | + lowering it never touches already-stored files. | ||
| 406 | 420 | ||
| 407 | A `PATCH` replaces only the fields it carries, each wholesale, and validation | 421 | A `PATCH` replaces only the fields it carries, each wholesale, and validation |
| 408 | is all-or-nothing. Concurrent edits are safe: each save applies only if the | 422 | is all-or-nothing. Concurrent edits are safe: each save applies only if the |
| @@ -702,6 +716,14 @@ curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \ | |||
| 702 | -d '{"title":"first","content":"hello"}' | 716 | -d '{"title":"first","content":"hello"}' |
| 703 | curl -s -b $JAR $BASE/notes | 717 | curl -s -b $JAR $BASE/notes |
| 704 | 718 | ||
| 719 | +# note files (multipart; -F sets filename + content type from the file) | ||
| 720 | +NO=$(curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \ | ||
| 721 | + -d '{"title":"with file"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) | ||
| 722 | +FI=$(curl -s -b $JAR $BASE/notes/$NO/files -F 'file=@plan.pdf' \ | ||
| 723 | + | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) | ||
| 724 | +curl -s -b $JAR $BASE/notes/$NO/files # list metadata | ||
| 725 | +curl -s -b $JAR -OJ $BASE/notes/$NO/files/$FI # download, original filename | ||
| 726 | + | ||
| 705 | # events + attendance | 727 | # events + attendance |
| 706 | # Creating events needs teacher+; grant it first (see "Bootstrapping" above — | 728 | # Creating events needs teacher+; grant it first (see "Bootstrapping" above — |
| 707 | # e.g. UPDATE user SET role='teacher' WHERE username='ali'), else this is 403. | 729 | # e.g. UPDATE user SET role='teacher' WHERE username='ali'), else this is 403. |
| @@ -758,7 +780,7 @@ src/ | |||
| 758 | error.rs ValidationError + AppError -> HTTP responses | 780 | error.rs ValidationError + AppError -> HTTP responses |
| 759 | database.rs embedded surrealkv connect + SCHEMAFULL migration | 781 | database.rs embedded surrealkv connect + SCHEMAFULL migration |
| 760 | rate_limit.rs fixed-window per-IP limiter (both tiers) + middleware | 782 | rate_limit.rs fixed-window per-IP limiter (both tiers) + middleware |
| 761 | - state.rs AppState { db, cookie_secure, rate_limit } | 783 | + state.rs AppState { db, files_path, cookie_secure, rate_limit } |
| 762 | domain/ validated newtypes + entities (derive SurrealValue), | 784 | domain/ validated newtypes + entities (derive SurrealValue), |
| 763 | each owning its persistence | 785 | each owning its persistence |
| 764 | user.rs UserId · Username · Password · PasswordHash · User (has role) | 786 | user.rs UserId · Username · Password · PasswordHash · User (has role) |
| @@ -766,6 +788,8 @@ src/ | |||
| 766 | session.rs SessionId · SessionToken · Session (7-day expiry) | 788 | session.rs SessionId · SessionToken · Session (7-day expiry) |
| 767 | timestamp.rs Timestamp (unix-millisecond instant) | 789 | timestamp.rs Timestamp (unix-millisecond instant) |
| 768 | note.rs NoteId · NoteTitle · NoteContent · Note | 790 | note.rs NoteId · NoteTitle · NoteContent · Note |
| 791 | + note_file.rs NoteFileId · FileName · FileContentType · NoteFile (metadata row; | ||
| 792 | + blob on disk under FILES_PATH, named by the row's ULID) | ||
| 769 | event.rs EventId · EventTitle · EventDescription · Event | 793 | event.rs EventId · EventTitle · EventDescription · Event |
| 770 | attendance.rs AttendanceId · AttendanceStatus · Attendance | 794 | attendance.rs AttendanceId · AttendanceStatus · Attendance |
| 771 | course.rs CourseId · CourseTitle · CourseDescription · Course | 795 | course.rs CourseId · CourseTitle · CourseDescription · Course |
compose.yamlmodified+1 -0
| @@ -13,6 +13,7 @@ services: | |||
| 13 | DB_PATH: /data/hezarfen.db | 13 | DB_PATH: /data/hezarfen.db |
| 14 | DB_NAMESPACE: hezarfen | 14 | DB_NAMESPACE: hezarfen |
| 15 | DB_DATABASE: hezarfen | 15 | DB_DATABASE: hezarfen |
| 16 | + FILES_PATH: /data/files | ||
| 16 | RUST_LOG: info,hezarfen_backend=debug | 17 | RUST_LOG: info,hezarfen_backend=debug |
| 17 | # First-boot admin seed: created once if the username doesn't exist yet. | 18 | # First-boot admin seed: created once if the username doesn't exist yet. |
| 18 | # Local-dev credentials — change or remove before exposing this anywhere. | 19 | # Local-dev credentials — change or remove before exposing this anywhere. |
src/config.rsmodified+4 -0
| @@ -15,6 +15,9 @@ pub struct Config { | |||
| 15 | pub db_path: String, | 15 | pub db_path: String, |
| 16 | pub db_ns: String, | 16 | pub db_ns: String, |
| 17 | pub db_name: String, | 17 | pub db_name: String, |
| 18 | + /// Directory for uploaded note-file blobs (`FILES_PATH`). Kept beside the | ||
| 19 | + /// database inside the same volume so one mount persists everything. | ||
| 20 | + pub files_path: String, | ||
| 18 | /// Add the `Secure` attribute to the session cookie (HTTPS-only). Off by | 21 | /// Add the `Secure` attribute to the session cookie (HTTPS-only). Off by |
| 19 | /// default so plain-HTTP local dev keeps working; enable behind TLS. | 22 | /// default so plain-HTTP local dev keeps working; enable behind TLS. |
| 20 | pub cookie_secure: bool, | 23 | pub cookie_secure: bool, |
| @@ -36,6 +39,7 @@ impl Config { | |||
| 36 | db_path: env::var("DB_PATH").unwrap_or_else(|_| "./data/hezarfen.db".into()), | 39 | db_path: env::var("DB_PATH").unwrap_or_else(|_| "./data/hezarfen.db".into()), |
| 37 | db_ns: env::var("DB_NAMESPACE").unwrap_or_else(|_| "hezarfen".into()), | 40 | db_ns: env::var("DB_NAMESPACE").unwrap_or_else(|_| "hezarfen".into()), |
| 38 | db_name: env::var("DB_DATABASE").unwrap_or_else(|_| "hezarfen".into()), | 41 | db_name: env::var("DB_DATABASE").unwrap_or_else(|_| "hezarfen".into()), |
| 42 | + files_path: env::var("FILES_PATH").unwrap_or_else(|_| "./data/files".into()), | ||
| 39 | cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()), | 43 | cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()), |
| 40 | rate_limit: RateLimitConfig { | 44 | rate_limit: RateLimitConfig { |
| 41 | auth_per_minute: parse_limit( | 45 | auth_per_minute: parse_limit( |
src/constant.rsmodified+20 -0
| @@ -35,6 +35,26 @@ pub const MAX_PHONE_DIGITS: usize = 15; | |||
| 35 | pub const MAX_NOTE_TITLE_LEN: usize = 200; | 35 | pub const MAX_NOTE_TITLE_LEN: usize = 200; |
| 36 | pub const MAX_NOTE_CONTENT_LEN: usize = 10_000; | 36 | pub const MAX_NOTE_CONTENT_LEN: usize = 10_000; |
| 37 | 37 | ||
| 38 | +/// How many files one note may carry. | ||
| 39 | +pub const MAX_NOTE_FILES: usize = 10; | ||
| 40 | + | ||
| 41 | +/// Bounds for a note file's original filename and its MIME content type. | ||
| 42 | +pub const MAX_FILE_NAME_LEN: usize = 255; | ||
| 43 | +pub const MAX_FILE_CONTENT_TYPE_LEN: usize = 100; | ||
| 44 | + | ||
| 45 | +/// The school-adjustable per-file upload size limit (`max_file_bytes` in | ||
| 46 | +/// settings): its default and the inclusive range a manager may set. The | ||
| 47 | +/// ceiling is a server-protection hard cap — uploads buffer in memory and land | ||
| 48 | +/// in single disk files, so it must stay modest no matter the school's wish. | ||
| 49 | +pub const DEFAULT_MAX_FILE_BYTES: i64 = 5 * 1024 * 1024; | ||
| 50 | +pub const MIN_MAX_FILE_BYTES: i64 = 1024; | ||
| 51 | +pub const MAX_MAX_FILE_BYTES: i64 = 25 * 1024 * 1024; | ||
| 52 | + | ||
| 53 | +/// Headroom on top of `MAX_MAX_FILE_BYTES` for the upload route's HTTP body | ||
| 54 | +/// cap: multipart boundaries, part headers, and the filename ride alongside | ||
| 55 | +/// the file bytes themselves. | ||
| 56 | +pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024; | ||
| 57 | + | ||
| 38 | pub const MAX_EVENT_TITLE_LEN: usize = 200; | 58 | pub const MAX_EVENT_TITLE_LEN: usize = 200; |
| 39 | pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; | 59 | pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; |
| 40 | 60 | ||
src/database.rsmodified+9 -0
| @@ -11,6 +11,7 @@ pub type Database = Surreal<Db>; | |||
| 11 | pub const USER_TABLE: &str = "user"; | 11 | pub const USER_TABLE: &str = "user"; |
| 12 | pub const SESSION_TABLE: &str = "session"; | 12 | pub const SESSION_TABLE: &str = "session"; |
| 13 | pub const NOTE_TABLE: &str = "note"; | 13 | pub const NOTE_TABLE: &str = "note"; |
| 14 | +pub const NOTE_FILE_TABLE: &str = "note_file"; | ||
| 14 | pub const EVENT_TABLE: &str = "event"; | 15 | pub const EVENT_TABLE: &str = "event"; |
| 15 | pub const ATTENDANCE_TABLE: &str = "attendance"; | 16 | pub const ATTENDANCE_TABLE: &str = "attendance"; |
| 16 | pub const EXAM_TABLE: &str = "exam"; | 17 | pub const EXAM_TABLE: &str = "exam"; |
| @@ -57,6 +58,13 @@ const MIGRATION: &str = " | |||
| 57 | DEFINE FIELD IF NOT EXISTS content ON note TYPE string; | 58 | DEFINE FIELD IF NOT EXISTS content ON note TYPE string; |
| 58 | DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user; | 59 | DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user; |
| 59 | 60 | ||
| 61 | + DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL; | ||
| 62 | + DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record<note>; | ||
| 63 | + DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string; | ||
| 64 | + DEFINE FIELD IF NOT EXISTS content_type ON note_file TYPE string; | ||
| 65 | + DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int; | ||
| 66 | + DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note; | ||
| 67 | + | ||
| 60 | DEFINE TABLE IF NOT EXISTS event SCHEMAFULL; | 68 | DEFINE TABLE IF NOT EXISTS event SCHEMAFULL; |
| 61 | DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>; | 69 | DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>; |
| 62 | DEFINE FIELD IF NOT EXISTS title ON event TYPE string; | 70 | DEFINE FIELD IF NOT EXISTS title ON event TYPE string; |
| @@ -174,6 +182,7 @@ const MIGRATION: &str = " | |||
| 174 | DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array<object>; | 182 | DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array<object>; |
| 175 | DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; | 183 | DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; |
| 176 | DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; | 184 | DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; |
| 185 | + DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>; | ||
| 177 | "; | 186 | "; |
| 178 | 187 | ||
| 179 | /// Open the file-backed database and apply the schema. | 188 | /// Open the file-backed database and apply the schema. |
src/domain/mod.rsmodified+1 -0
| @@ -13,6 +13,7 @@ pub mod exam_attempt; | |||
| 13 | pub mod exam_question; | 13 | pub mod exam_question; |
| 14 | pub mod exam_result; | 14 | pub mod exam_result; |
| 15 | pub mod note; | 15 | pub mod note; |
| 16 | +pub mod note_file; | ||
| 16 | pub mod profile; | 17 | pub mod profile; |
| 17 | pub mod role; | 18 | pub mod role; |
| 18 | pub mod session; | 19 | pub mod session; |
src/domain/note.rsmodified+8 -0
| @@ -127,7 +127,15 @@ impl Note { | |||
| 127 | updated.ok_or(AppError::NotFound) | 127 | updated.ok_or(AppError::NotFound) |
| 128 | } | 128 | } |
| 129 | 129 | ||
| 130 | + /// Delete the note and cascade-remove its attachment rows. Blob files on | ||
| 131 | + /// disk are the web layer's to remove (it lists them before calling this); | ||
| 132 | + /// a crash in between leaves at worst an unreachable blob, never a row | ||
| 133 | + /// pointing at nothing. | ||
| 130 | pub async fn delete(self, db: &Database) -> Result<Note, AppError> { | 134 | pub async fn delete(self, db: &Database) -> Result<Note, AppError> { |
| 135 | + db.query("DELETE note_file WHERE note = $note") | ||
| 136 | + .bind(("note", self.id.record())) | ||
| 137 | + .await? | ||
| 138 | + .check()?; | ||
| 131 | let deleted: Option<Note> = db.delete(self.id.record()).await?; | 139 | let deleted: Option<Note> = db.delete(self.id.record()).await?; |
| 132 | deleted.ok_or(AppError::NotFound) | 140 | deleted.ok_or(AppError::NotFound) |
| 133 | } | 141 | } |
src/domain/note_file.rsadded+255 -0
| @@ -0,0 +1,255 @@ | |||
| 1 | +//! A file attached to a note. The row carries metadata only (original | ||
| 2 | +//! filename, MIME type, byte size); the bytes themselves live on disk under | ||
| 3 | +//! [`crate::config::Config::files_path`], in a file named by this row's key — | ||
| 4 | +//! a server-generated ULID, so no user input ever shapes a disk path. The web | ||
| 5 | +//! layer owns the blob I/O and its ordering (blob before row on upload, row | ||
| 6 | +//! before blob on delete); this module owns the rows. | ||
| 7 | + | ||
| 8 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 9 | +use ulid::Ulid; | ||
| 10 | + | ||
| 11 | +use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN}; | ||
| 12 | +use crate::database::{Database, NOTE_FILE_TABLE}; | ||
| 13 | +use crate::domain::note::NoteId; | ||
| 14 | +use crate::error::{AppError, ValidationError}; | ||
| 15 | + | ||
| 16 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 17 | +pub struct NoteFileId(RecordId); | ||
| 18 | + | ||
| 19 | +impl NoteFileId { | ||
| 20 | + pub fn generate() -> Self { | ||
| 21 | + Self(RecordId::new(NOTE_FILE_TABLE, Ulid::new().to_string())) | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + pub fn from_key(key: &str) -> Self { | ||
| 25 | + Self(RecordId::new(NOTE_FILE_TABLE, key)) | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + pub fn record(&self) -> RecordId { | ||
| 29 | + self.0.clone() | ||
| 30 | + } | ||
| 31 | + | ||
| 32 | + pub fn key(&self) -> &str { | ||
| 33 | + match &self.0.key { | ||
| 34 | + RecordIdKey::String(key) => key, | ||
| 35 | + _ => "", | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +/// The uploader's original filename, kept for display and download headers. | ||
| 41 | +/// Never used as a disk path — but path separators and control characters are | ||
| 42 | +/// refused anyway: they are not filenames, only header/log injection attempts. | ||
| 43 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 44 | +pub struct FileName(String); | ||
| 45 | + | ||
| 46 | +impl FileName { | ||
| 47 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 48 | + let value = value.trim(); | ||
| 49 | + if value.is_empty() { | ||
| 50 | + return Err(ValidationError::Empty("filename")); | ||
| 51 | + } | ||
| 52 | + if value.chars().count() > MAX_FILE_NAME_LEN { | ||
| 53 | + return Err(ValidationError::TooLong { | ||
| 54 | + field: "filename", | ||
| 55 | + max: MAX_FILE_NAME_LEN, | ||
| 56 | + got: value.chars().count(), | ||
| 57 | + }); | ||
| 58 | + } | ||
| 59 | + if value | ||
| 60 | + .chars() | ||
| 61 | + .any(|c| c.is_control() || c == '/' || c == '\\') | ||
| 62 | + { | ||
| 63 | + return Err(ValidationError::Invalid { | ||
| 64 | + field: "filename", | ||
| 65 | + reason: "must not contain path separators or control characters", | ||
| 66 | + }); | ||
| 67 | + } | ||
| 68 | + Ok(Self(value.to_string())) | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + pub fn as_str(&self) -> &str { | ||
| 72 | + &self.0 | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// The MIME type the client declared for the file. Blank defaults to | ||
| 77 | +/// `application/octet-stream`; it is echoed back on download, so it is held | ||
| 78 | +/// to header-safe ASCII. | ||
| 79 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 80 | +pub struct FileContentType(String); | ||
| 81 | + | ||
| 82 | +impl FileContentType { | ||
| 83 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 84 | + let value = value.trim(); | ||
| 85 | + if value.is_empty() { | ||
| 86 | + return Ok(Self("application/octet-stream".to_string())); | ||
| 87 | + } | ||
| 88 | + if value.chars().count() > MAX_FILE_CONTENT_TYPE_LEN { | ||
| 89 | + return Err(ValidationError::TooLong { | ||
| 90 | + field: "content_type", | ||
| 91 | + max: MAX_FILE_CONTENT_TYPE_LEN, | ||
| 92 | + got: value.chars().count(), | ||
| 93 | + }); | ||
| 94 | + } | ||
| 95 | + if !value.is_ascii() { | ||
| 96 | + return Err(ValidationError::NotAscii("content_type")); | ||
| 97 | + } | ||
| 98 | + if value.chars().any(|c| c.is_ascii_control()) { | ||
| 99 | + return Err(ValidationError::Invalid { | ||
| 100 | + field: "content_type", | ||
| 101 | + reason: "must not contain control characters", | ||
| 102 | + }); | ||
| 103 | + } | ||
| 104 | + Ok(Self(value.to_string())) | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + pub fn as_str(&self) -> &str { | ||
| 108 | + &self.0 | ||
| 109 | + } | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 113 | +pub struct NoteFile { | ||
| 114 | + id: NoteFileId, | ||
| 115 | + note: NoteId, | ||
| 116 | + name: FileName, | ||
| 117 | + content_type: FileContentType, | ||
| 118 | + size: i64, | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +impl NoteFile { | ||
| 122 | + /// Assemble a new attachment row (id generated here) without persisting | ||
| 123 | + /// it. The caller writes the blob to disk under the fresh id first, then | ||
| 124 | + /// calls [`Self::insert`] — so a stored row always points at a real blob. | ||
| 125 | + pub fn new(note: &NoteId, name: FileName, content_type: FileContentType, size: i64) -> Self { | ||
| 126 | + Self { | ||
| 127 | + id: NoteFileId::generate(), | ||
| 128 | + note: note.clone(), | ||
| 129 | + name, | ||
| 130 | + content_type, | ||
| 131 | + size, | ||
| 132 | + } | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + pub fn get_id(&self) -> &NoteFileId { | ||
| 136 | + &self.id | ||
| 137 | + } | ||
| 138 | + | ||
| 139 | + pub fn get_name(&self) -> &FileName { | ||
| 140 | + &self.name | ||
| 141 | + } | ||
| 142 | + | ||
| 143 | + pub fn get_content_type(&self) -> &FileContentType { | ||
| 144 | + &self.content_type | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + pub fn get_size(&self) -> i64 { | ||
| 148 | + self.size | ||
| 149 | + } | ||
| 150 | + | ||
| 151 | + /// Persist the row assembled by [`Self::new`]. | ||
| 152 | + pub async fn insert(self, db: &Database) -> Result<NoteFile, AppError> { | ||
| 153 | + let created: Option<NoteFile> = db.create(self.id.record()).content(self).await?; | ||
| 154 | + created.ok_or_else(|| AppError::Internal("failed to create note file".into())) | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + /// Read a file's row only if it belongs to `note` — callers have already | ||
| 158 | + /// checked the note belongs to the requesting user. | ||
| 159 | + pub async fn read_for( | ||
| 160 | + id: &NoteFileId, | ||
| 161 | + note: &NoteId, | ||
| 162 | + db: &Database, | ||
| 163 | + ) -> Result<Option<NoteFile>, AppError> { | ||
| 164 | + let file: Option<NoteFile> = db.select(id.record()).await?; | ||
| 165 | + Ok(file.filter(|file| &file.note == note)) | ||
| 166 | + } | ||
| 167 | + | ||
| 168 | + /// All of `note`'s attachment rows, newest first. | ||
| 169 | + pub async fn list_for(note: &NoteId, db: &Database) -> Result<Vec<NoteFile>, AppError> { | ||
| 170 | + let mut result = db | ||
| 171 | + .query("SELECT * FROM note_file WHERE note = $note ORDER BY id DESC") | ||
| 172 | + .bind(("note", note.record())) | ||
| 173 | + .await? | ||
| 174 | + .check()?; | ||
| 175 | + Ok(result.take::<Vec<NoteFile>>(0)?) | ||
| 176 | + } | ||
| 177 | + | ||
| 178 | + pub async fn delete(self, db: &Database) -> Result<NoteFile, AppError> { | ||
| 179 | + let deleted: Option<NoteFile> = db.delete(self.id.record()).await?; | ||
| 180 | + deleted.ok_or(AppError::NotFound) | ||
| 181 | + } | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +#[cfg(test)] | ||
| 185 | +mod tests { | ||
| 186 | + use super::*; | ||
| 187 | + | ||
| 188 | + #[tokio::test] | ||
| 189 | + async fn filename_rules() { | ||
| 190 | + assert_eq!( | ||
| 191 | + FileName::try_new(" ödev.pdf ").unwrap().as_str(), | ||
| 192 | + "ödev.pdf" | ||
| 193 | + ); | ||
| 194 | + assert!(FileName::try_new("").is_err()); | ||
| 195 | + assert!(FileName::try_new(" ").is_err()); | ||
| 196 | + assert!(FileName::try_new(&"x".repeat(256)).is_err()); | ||
| 197 | + // Path separators and control characters are injection, not filenames. | ||
| 198 | + assert!(FileName::try_new("a/b.pdf").is_err()); | ||
| 199 | + assert!(FileName::try_new("a\\b.pdf").is_err()); | ||
| 200 | + assert!(FileName::try_new("a\nb.pdf").is_err()); | ||
| 201 | + assert!(FileName::try_new("a\x00b").is_err()); | ||
| 202 | + } | ||
| 203 | + | ||
| 204 | + #[tokio::test] | ||
| 205 | + async fn content_type_rules() { | ||
| 206 | + assert_eq!( | ||
| 207 | + FileContentType::try_new("application/pdf") | ||
| 208 | + .unwrap() | ||
| 209 | + .as_str(), | ||
| 210 | + "application/pdf" | ||
| 211 | + ); | ||
| 212 | + // Blank means the client didn't say — fall back, don't fail. | ||
| 213 | + assert_eq!( | ||
| 214 | + FileContentType::try_new("").unwrap().as_str(), | ||
| 215 | + "application/octet-stream" | ||
| 216 | + ); | ||
| 217 | + assert!(FileContentType::try_new(&"x".repeat(101)).is_err()); | ||
| 218 | + assert!(FileContentType::try_new("appli¢ation/pdf").is_err()); | ||
| 219 | + assert!(FileContentType::try_new("a\r\nb").is_err()); | ||
| 220 | + } | ||
| 221 | + | ||
| 222 | + #[tokio::test] | ||
| 223 | + async fn rows_scope_to_their_note() { | ||
| 224 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 225 | + let note_a = NoteId::generate(); | ||
| 226 | + let note_b = NoteId::generate(); | ||
| 227 | + let file = NoteFile::new( | ||
| 228 | + ¬e_a, | ||
| 229 | + FileName::try_new("plan.pdf").unwrap(), | ||
| 230 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 231 | + 3, | ||
| 232 | + ) | ||
| 233 | + .insert(&db) | ||
| 234 | + .await | ||
| 235 | + .unwrap(); | ||
| 236 | + | ||
| 237 | + // Readable under its own note, invisible under another. | ||
| 238 | + let found = NoteFile::read_for(file.get_id(), ¬e_a, &db) | ||
| 239 | + .await | ||
| 240 | + .unwrap(); | ||
| 241 | + assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); | ||
| 242 | + assert!( | ||
| 243 | + NoteFile::read_for(file.get_id(), ¬e_b, &db) | ||
| 244 | + .await | ||
| 245 | + .unwrap() | ||
| 246 | + .is_none() | ||
| 247 | + ); | ||
| 248 | + | ||
| 249 | + assert_eq!(NoteFile::list_for(¬e_a, &db).await.unwrap().len(), 1); | ||
| 250 | + assert!(NoteFile::list_for(¬e_b, &db).await.unwrap().is_empty()); | ||
| 251 | + | ||
| 252 | + file.delete(&db).await.unwrap(); | ||
| 253 | + assert!(NoteFile::list_for(¬e_a, &db).await.unwrap().is_empty()); | ||
| 254 | + } | ||
| 255 | +} | ||
src/domain/settings.rsmodified+123 -19
| @@ -1,17 +1,22 @@ | |||
| 1 | //! School-adjustable policy: which exam kinds exist (and how much each | 1 | //! School-adjustable policy: which exam kinds exist (and how much each |
| 2 | //! weighs in course averages), which attendance statuses the roll call | 2 | //! weighs in course averages), which attendance statuses the roll call |
| 3 | -//! accepts, and how numeric marks display as grades. | 3 | +//! accepts, how numeric marks display as grades, and how large an uploaded |
| 4 | +//! note file may be. | ||
| 4 | //! | 5 | //! |
| 5 | //! One singleton record (`settings:school` — one school per deployment). An | 6 | //! One singleton record (`settings:school` — one school per deployment). An |
| 6 | //! absent record means "the defaults from `constant.rs`", so a fresh or | 7 | //! absent record means "the defaults from `constant.rs`", so a fresh or |
| 7 | -//! pre-existing database needs no seeding and behaves exactly as before. | 8 | +//! pre-existing database needs no seeding and behaves exactly as before. The |
| 9 | +//! same holds per field: `max_file_bytes` is `option<int>` and reads as the | ||
| 10 | +//! default while unset, so rows saved before the field existed keep working | ||
| 11 | +//! without a backfill (backfills crash boots — `DEFAULT` never rescues | ||
| 12 | +//! existing rows, and `UPDATE` re-validates whole records). | ||
| 8 | 13 | ||
| 9 | use surrealdb::types::{RecordId, SurrealValue}; | 14 | use surrealdb::types::{RecordId, SurrealValue}; |
| 10 | 15 | ||
| 11 | use crate::constant::{ | 16 | use crate::constant::{ |
| 12 | - DEFAULT_ATTENDANCE_STATUSES, DEFAULT_EXAM_KINDS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, | 17 | + DEFAULT_ATTENDANCE_STATUSES, DEFAULT_EXAM_KINDS, DEFAULT_MAX_FILE_BYTES, MAX_EXAM_KIND_WEIGHT, |
| 13 | - MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, | 18 | + MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_FILE_BYTES, MAX_SETTINGS_ITEM_LEN, |
| 14 | - MIN_EXAM_KIND_WEIGHT, MIN_MARK, | 19 | + MAX_SETTINGS_LIST_LEN, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_FILE_BYTES, |
| 15 | }; | 20 | }; |
| 16 | use crate::database::{Database, SETTINGS_TABLE}; | 21 | use crate::database::{Database, SETTINGS_TABLE}; |
| 17 | use crate::error::{AppError, ValidationError}; | 22 | use crate::error::{AppError, ValidationError}; |
| @@ -106,6 +111,9 @@ pub struct Settings { | |||
| 106 | exam_kinds: Vec<ExamKindDef>, | 111 | exam_kinds: Vec<ExamKindDef>, |
| 107 | attendance_statuses: Vec<String>, | 112 | attendance_statuses: Vec<String>, |
| 108 | grade_bands: Vec<GradeBand>, | 113 | grade_bands: Vec<GradeBand>, |
| 114 | + /// Per-file byte cap for note uploads. `None` = the row predates the | ||
| 115 | + /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`. | ||
| 116 | + max_file_bytes: Option<i64>, | ||
| 109 | } | 117 | } |
| 110 | 118 | ||
| 111 | impl Settings { | 119 | impl Settings { |
| @@ -126,6 +134,7 @@ impl Settings { | |||
| 126 | .to_vec(), | 134 | .to_vec(), |
| 127 | attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(), | 135 | attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(), |
| 128 | grade_bands: Vec::new(), | 136 | grade_bands: Vec::new(), |
| 137 | + max_file_bytes: None, | ||
| 129 | } | 138 | } |
| 130 | } | 139 | } |
| 131 | 140 | ||
| @@ -134,12 +143,21 @@ impl Settings { | |||
| 134 | /// core attendance statuses can never be removed (the attendance rate's | 143 | /// core attendance statuses can never be removed (the attendance rate's |
| 135 | /// semantics are defined over them). Bands may be empty (numeric-only | 144 | /// semantics are defined over them). Bands may be empty (numeric-only |
| 136 | /// display), otherwise their mins are unique and one band must start at 0 | 145 | /// display), otherwise their mins are unique and one band must start at 0 |
| 137 | - /// so every mark maps to a label. | 146 | + /// so every mark maps to a label. The upload cap must sit inside the |
| 147 | + /// server's hard bounds — the ceiling protects memory and disk, whatever | ||
| 148 | + /// the school would prefer. | ||
| 138 | pub fn try_new( | 149 | pub fn try_new( |
| 139 | exam_kinds: Vec<ExamKindDef>, | 150 | exam_kinds: Vec<ExamKindDef>, |
| 140 | attendance_statuses: Vec<String>, | 151 | attendance_statuses: Vec<String>, |
| 141 | grade_bands: Vec<GradeBand>, | 152 | grade_bands: Vec<GradeBand>, |
| 153 | + max_file_bytes: i64, | ||
| 142 | ) -> Result<Self, ValidationError> { | 154 | ) -> Result<Self, ValidationError> { |
| 155 | + if !(MIN_MAX_FILE_BYTES..=MAX_MAX_FILE_BYTES).contains(&max_file_bytes) { | ||
| 156 | + return Err(ValidationError::Invalid { | ||
| 157 | + field: "max_file_bytes", | ||
| 158 | + reason: "must be between 1024 (1 KiB) and 26214400 (25 MiB)", | ||
| 159 | + }); | ||
| 160 | + } | ||
| 143 | // Per-entry rules (name shape, weight range) hold structurally on any | 161 | // Per-entry rules (name shape, weight range) hold structurally on any |
| 144 | // `ExamKindDef`; here only the list-level rules need checking. | 162 | // `ExamKindDef`; here only the list-level rules need checking. |
| 145 | let names: Vec<String> = exam_kinds | 163 | let names: Vec<String> = exam_kinds |
| @@ -188,6 +206,7 @@ impl Settings { | |||
| 188 | exam_kinds, | 206 | exam_kinds, |
| 189 | attendance_statuses, | 207 | attendance_statuses, |
| 190 | grade_bands, | 208 | grade_bands, |
| 209 | + max_file_bytes: Some(max_file_bytes), | ||
| 191 | }) | 210 | }) |
| 192 | } | 211 | } |
| 193 | 212 | ||
| @@ -214,6 +233,12 @@ impl Settings { | |||
| 214 | &self.grade_bands | 233 | &self.grade_bands |
| 215 | } | 234 | } |
| 216 | 235 | ||
| 236 | + /// The per-file upload cap in bytes; the built-in default while the | ||
| 237 | + /// school never set one (including rows saved before the field existed). | ||
| 238 | + pub fn get_max_file_bytes(&self) -> i64 { | ||
| 239 | + self.max_file_bytes.unwrap_or(DEFAULT_MAX_FILE_BYTES) | ||
| 240 | + } | ||
| 241 | + | ||
| 217 | /// The label of the band `mark` falls into: the band with the greatest | 242 | /// The label of the band `mark` falls into: the band with the greatest |
| 218 | /// `min` at or below it. `None` when no bands are configured. Takes an | 243 | /// `min` at or below it. `None` when no bands are configured. Takes an |
| 219 | /// `f64` so course averages label the same way plain marks do. | 244 | /// `f64` so course averages label the same way plain marks do. |
| @@ -263,7 +288,8 @@ impl Settings { | |||
| 263 | UPDATE $id CONTENT $new | 288 | UPDATE $id CONTENT $new |
| 264 | WHERE exam_kinds = $ek | 289 | WHERE exam_kinds = $ek |
| 265 | AND attendance_statuses = $st | 290 | AND attendance_statuses = $st |
| 266 | - AND grade_bands = $gb; | 291 | + AND grade_bands = $gb |
| 292 | + AND max_file_bytes = $mf; | ||
| 267 | COMMIT TRANSACTION;", | 293 | COMMIT TRANSACTION;", |
| 268 | ) | 294 | ) |
| 269 | .bind(("expected", expected.clone())) | 295 | .bind(("expected", expected.clone())) |
| @@ -272,6 +298,7 @@ impl Settings { | |||
| 272 | .bind(("ek", expected.exam_kinds.clone())) | 298 | .bind(("ek", expected.exam_kinds.clone())) |
| 273 | .bind(("st", expected.attendance_statuses.clone())) | 299 | .bind(("st", expected.attendance_statuses.clone())) |
| 274 | .bind(("gb", expected.grade_bands.clone())) | 300 | .bind(("gb", expected.grade_bands.clone())) |
| 301 | + .bind(("mf", expected.max_file_bytes)) | ||
| 275 | .await? | 302 | .await? |
| 276 | .check()?; | 303 | .check()?; |
| 277 | // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An | 304 | // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An |
| @@ -346,6 +373,7 @@ mod tests { | |||
| 346 | defaults.get_exam_kinds().to_vec(), | 373 | defaults.get_exam_kinds().to_vec(), |
| 347 | defaults.get_attendance_statuses().to_vec(), | 374 | defaults.get_attendance_statuses().to_vec(), |
| 348 | defaults.get_grade_bands().to_vec(), | 375 | defaults.get_grade_bands().to_vec(), |
| 376 | + defaults.get_max_file_bytes(), | ||
| 349 | ) | 377 | ) |
| 350 | .unwrap(); | 378 | .unwrap(); |
| 351 | assert_eq!(rebuilt.get_exam_kinds(), defaults.get_exam_kinds()); | 379 | assert_eq!(rebuilt.get_exam_kinds(), defaults.get_exam_kinds()); |
| @@ -377,15 +405,31 @@ mod tests { | |||
| 377 | #[tokio::test] | 405 | #[tokio::test] |
| 378 | async fn lists_are_bounded_and_deduped() { | 406 | async fn lists_are_bounded_and_deduped() { |
| 379 | let statuses = Settings::defaults().get_attendance_statuses().to_vec(); | 407 | let statuses = Settings::defaults().get_attendance_statuses().to_vec(); |
| 380 | - let s = Settings::try_new(kinds(&["lab", "quiz"]), statuses.clone(), vec![]).unwrap(); | 408 | + let s = Settings::try_new( |
| 409 | + kinds(&["lab", "quiz"]), | ||
| 410 | + statuses.clone(), | ||
| 411 | + vec![], | ||
| 412 | + DEFAULT_MAX_FILE_BYTES, | ||
| 413 | + ) | ||
| 414 | + .unwrap(); | ||
| 381 | assert_eq!(names(&s), ["lab", "quiz"]); | 415 | assert_eq!(names(&s), ["lab", "quiz"]); |
| 382 | // Empty list and case-insensitive duplicate names are rejected. | 416 | // Empty list and case-insensitive duplicate names are rejected. |
| 383 | - assert!(Settings::try_new(vec![], statuses.clone(), vec![]).is_err()); | 417 | + assert!( |
| 384 | - assert!(Settings::try_new(kinds(&["Lab", "lab"]), statuses.clone(), vec![]).is_err()); | 418 | + Settings::try_new(vec![], statuses.clone(), vec![], DEFAULT_MAX_FILE_BYTES).is_err() |
| 419 | + ); | ||
| 420 | + assert!( | ||
| 421 | + Settings::try_new( | ||
| 422 | + kinds(&["Lab", "lab"]), | ||
| 423 | + statuses.clone(), | ||
| 424 | + vec![], | ||
| 425 | + DEFAULT_MAX_FILE_BYTES | ||
| 426 | + ) | ||
| 427 | + .is_err() | ||
| 428 | + ); | ||
| 385 | let too_many: Vec<ExamKindDef> = (0..21) | 429 | let too_many: Vec<ExamKindDef> = (0..21) |
| 386 | .map(|i| ExamKindDef::try_new(&format!("kind{i}"), 1).unwrap()) | 430 | .map(|i| ExamKindDef::try_new(&format!("kind{i}"), 1).unwrap()) |
| 387 | .collect(); | 431 | .collect(); |
| 388 | - assert!(Settings::try_new(too_many, statuses, vec![]).is_err()); | 432 | + assert!(Settings::try_new(too_many, statuses, vec![], DEFAULT_MAX_FILE_BYTES).is_err()); |
| 389 | } | 433 | } |
| 390 | 434 | ||
| 391 | #[tokio::test] | 435 | #[tokio::test] |
| @@ -398,6 +442,7 @@ mod tests { | |||
| 398 | ], | 442 | ], |
| 399 | statuses, | 443 | statuses, |
| 400 | vec![], | 444 | vec![], |
| 445 | + DEFAULT_MAX_FILE_BYTES, | ||
| 401 | ) | 446 | ) |
| 402 | .unwrap(); | 447 | .unwrap(); |
| 403 | assert_eq!(s.exam_kind_weight("final"), Some(3)); | 448 | assert_eq!(s.exam_kind_weight("final"), Some(3)); |
| @@ -412,13 +457,13 @@ mod tests { | |||
| 412 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); | 457 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); |
| 413 | // Extras on top of the core are fine. | 458 | // Extras on top of the core are fine. |
| 414 | let extended = statuses_with(&["online"]); | 459 | let extended = statuses_with(&["online"]); |
| 415 | - assert!(Settings::try_new(kinds.clone(), extended, vec![]).is_ok()); | 460 | + assert!(Settings::try_new(kinds.clone(), extended, vec![], DEFAULT_MAX_FILE_BYTES).is_ok()); |
| 416 | // Dropping any core status is not. | 461 | // Dropping any core status is not. |
| 417 | let missing: Vec<String> = statuses_with(&[]) | 462 | let missing: Vec<String> = statuses_with(&[]) |
| 418 | .into_iter() | 463 | .into_iter() |
| 419 | .filter(|s| s != "late") | 464 | .filter(|s| s != "late") |
| 420 | .collect(); | 465 | .collect(); |
| 421 | - assert!(Settings::try_new(kinds, missing, vec![]).is_err()); | 466 | + assert!(Settings::try_new(kinds, missing, vec![], DEFAULT_MAX_FILE_BYTES).is_err()); |
| 422 | } | 467 | } |
| 423 | 468 | ||
| 424 | fn statuses_with(extra: &[&str]) -> Vec<String> { | 469 | fn statuses_with(extra: &[&str]) -> Vec<String> { |
| @@ -444,6 +489,7 @@ mod tests { | |||
| 444 | defaults.get_exam_kinds().to_vec(), | 489 | defaults.get_exam_kinds().to_vec(), |
| 445 | defaults.get_attendance_statuses().to_vec(), | 490 | defaults.get_attendance_statuses().to_vec(), |
| 446 | b, | 491 | b, |
| 492 | + DEFAULT_MAX_FILE_BYTES, | ||
| 447 | ) | 493 | ) |
| 448 | }; | 494 | }; |
| 449 | // Empty = numeric-only display. | 495 | // Empty = numeric-only display. |
| @@ -455,6 +501,53 @@ mod tests { | |||
| 455 | assert!(ok(bands(&[(0, "FF"), (50, "CC"), (85, "AA")])).is_ok()); | 501 | assert!(ok(bands(&[(0, "FF"), (50, "CC"), (85, "AA")])).is_ok()); |
| 456 | } | 502 | } |
| 457 | 503 | ||
| 504 | + #[tokio::test] | ||
| 505 | + async fn max_file_bytes_is_bounded() { | ||
| 506 | + let defaults = Settings::defaults(); | ||
| 507 | + let with_cap = |cap: i64| { | ||
| 508 | + Settings::try_new( | ||
| 509 | + defaults.get_exam_kinds().to_vec(), | ||
| 510 | + defaults.get_attendance_statuses().to_vec(), | ||
| 511 | + vec![], | ||
| 512 | + cap, | ||
| 513 | + ) | ||
| 514 | + }; | ||
| 515 | + for cap in [ | ||
| 516 | + MIN_MAX_FILE_BYTES, | ||
| 517 | + DEFAULT_MAX_FILE_BYTES, | ||
| 518 | + MAX_MAX_FILE_BYTES, | ||
| 519 | + ] { | ||
| 520 | + assert_eq!(with_cap(cap).unwrap().get_max_file_bytes(), cap); | ||
| 521 | + } | ||
| 522 | + assert!(with_cap(MIN_MAX_FILE_BYTES - 1).is_err()); | ||
| 523 | + assert!(with_cap(MAX_MAX_FILE_BYTES + 1).is_err()); | ||
| 524 | + assert!(with_cap(0).is_err()); | ||
| 525 | + assert!(with_cap(-1).is_err()); | ||
| 526 | + } | ||
| 527 | + | ||
| 528 | + #[tokio::test] | ||
| 529 | + async fn a_row_predating_max_file_bytes_reads_the_default() { | ||
| 530 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 531 | + // The defaults carry no explicit cap, so this writes a row without the | ||
| 532 | + // field — exactly what a volume from before the field looks like. | ||
| 533 | + Settings::defaults().save(&db).await.unwrap(); | ||
| 534 | + let loaded = Settings::load(&db).await.unwrap(); | ||
| 535 | + assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES); | ||
| 536 | + // And a snapshot of that old row still passes the compare-and-set. | ||
| 537 | + let saved = Settings::try_new( | ||
| 538 | + loaded.get_exam_kinds().to_vec(), | ||
| 539 | + loaded.get_attendance_statuses().to_vec(), | ||
| 540 | + vec![], | ||
| 541 | + 4096, | ||
| 542 | + ) | ||
| 543 | + .unwrap() | ||
| 544 | + .save_if_unchanged(&loaded, &db) | ||
| 545 | + .await | ||
| 546 | + .unwrap() | ||
| 547 | + .expect("a merge over an old-shape row applies"); | ||
| 548 | + assert_eq!(saved.get_max_file_bytes(), 4096); | ||
| 549 | + } | ||
| 550 | + | ||
| 458 | #[tokio::test] | 551 | #[tokio::test] |
| 459 | async fn load_save_roundtrip_on_the_singleton() { | 552 | async fn load_save_roundtrip_on_the_singleton() { |
| 460 | let db = crate::database::init_mem().await.unwrap(); | 553 | let db = crate::database::init_mem().await.unwrap(); |
| @@ -471,6 +564,7 @@ mod tests { | |||
| 471 | kinds(&["lab"]), | 564 | kinds(&["lab"]), |
| 472 | statuses.clone(), | 565 | statuses.clone(), |
| 473 | bands(&[(0, "F"), (50, "P")]), | 566 | bands(&[(0, "F"), (50, "P")]), |
| 567 | + 2048, | ||
| 474 | ) | 568 | ) |
| 475 | .unwrap() | 569 | .unwrap() |
| 476 | .save(&db) | 570 | .save(&db) |
| @@ -480,8 +574,9 @@ mod tests { | |||
| 480 | assert_eq!(names(&loaded), ["lab"]); | 574 | assert_eq!(names(&loaded), ["lab"]); |
| 481 | assert_eq!(loaded.get_grade_bands().len(), 2); | 575 | assert_eq!(loaded.get_grade_bands().len(), 2); |
| 482 | assert_eq!(loaded.grade_label(60.0), Some("P")); | 576 | assert_eq!(loaded.grade_label(60.0), Some("P")); |
| 577 | + assert_eq!(loaded.get_max_file_bytes(), 2048); | ||
| 483 | // A second save lands on the same singleton row, not a new one. | 578 | // A second save lands on the same singleton row, not a new one. |
| 484 | - Settings::try_new(kinds(&["quiz"]), statuses, vec![]) | 579 | + Settings::try_new(kinds(&["quiz"]), statuses, vec![], DEFAULT_MAX_FILE_BYTES) |
| 485 | .unwrap() | 580 | .unwrap() |
| 486 | .save(&db) | 581 | .save(&db) |
| 487 | .await | 582 | .await |
| @@ -500,11 +595,16 @@ mod tests { | |||
| 500 | // Editor A snapshots the policy (the defaults — no row yet)... | 595 | // Editor A snapshots the policy (the defaults — no row yet)... |
| 501 | let stale = Settings::load(&db).await.unwrap(); | 596 | let stale = Settings::load(&db).await.unwrap(); |
| 502 | // ...then editor B lands a new exam-kind list first. | 597 | // ...then editor B lands a new exam-kind list first. |
| 503 | - Settings::try_new(kinds(&["lab"]), statuses.clone(), vec![]) | 598 | + Settings::try_new( |
| 504 | - .unwrap() | 599 | + kinds(&["lab"]), |
| 505 | - .save(&db) | 600 | + statuses.clone(), |
| 506 | - .await | 601 | + vec![], |
| 507 | - .unwrap(); | 602 | + DEFAULT_MAX_FILE_BYTES, |
| 603 | + ) | ||
| 604 | + .unwrap() | ||
| 605 | + .save(&db) | ||
| 606 | + .await | ||
| 607 | + .unwrap(); | ||
| 508 | 608 | ||
| 509 | // A's merge over the stale snapshot (kinds kept "as loaded", bands | 609 | // A's merge over the stale snapshot (kinds kept "as loaded", bands |
| 510 | // changed) — exactly what a concurrent PATCH /settings computes — | 610 | // changed) — exactly what a concurrent PATCH /settings computes — |
| @@ -513,6 +613,7 @@ mod tests { | |||
| 513 | stale.get_exam_kinds().to_vec(), | 613 | stale.get_exam_kinds().to_vec(), |
| 514 | stale.get_attendance_statuses().to_vec(), | 614 | stale.get_attendance_statuses().to_vec(), |
| 515 | bands(&[(0, "F"), (50, "P")]), | 615 | bands(&[(0, "F"), (50, "P")]), |
| 616 | + stale.get_max_file_bytes(), | ||
| 516 | ) | 617 | ) |
| 517 | .unwrap() | 618 | .unwrap() |
| 518 | .save_if_unchanged(&stale, &db) | 619 | .save_if_unchanged(&stale, &db) |
| @@ -535,6 +636,7 @@ mod tests { | |||
| 535 | fresh.get_exam_kinds().to_vec(), | 636 | fresh.get_exam_kinds().to_vec(), |
| 536 | fresh.get_attendance_statuses().to_vec(), | 637 | fresh.get_attendance_statuses().to_vec(), |
| 537 | bands(&[(0, "F"), (50, "P")]), | 638 | bands(&[(0, "F"), (50, "P")]), |
| 639 | + fresh.get_max_file_bytes(), | ||
| 538 | ) | 640 | ) |
| 539 | .unwrap() | 641 | .unwrap() |
| 540 | .save_if_unchanged(&fresh, &db) | 642 | .save_if_unchanged(&fresh, &db) |
| @@ -555,6 +657,7 @@ mod tests { | |||
| 555 | kinds(&["lab"]), | 657 | kinds(&["lab"]), |
| 556 | current.get_attendance_statuses().to_vec(), | 658 | current.get_attendance_statuses().to_vec(), |
| 557 | vec![], | 659 | vec![], |
| 660 | + current.get_max_file_bytes(), | ||
| 558 | ) | 661 | ) |
| 559 | .unwrap() | 662 | .unwrap() |
| 560 | .save_if_unchanged(¤t, &db) | 663 | .save_if_unchanged(¤t, &db) |
| @@ -574,6 +677,7 @@ mod tests { | |||
| 574 | defaults.get_exam_kinds().to_vec(), | 677 | defaults.get_exam_kinds().to_vec(), |
| 575 | defaults.get_attendance_statuses().to_vec(), | 678 | defaults.get_attendance_statuses().to_vec(), |
| 576 | bands(&[(0, "FF"), (50, "CC"), (85, "AA")]), | 679 | bands(&[(0, "FF"), (50, "CC"), (85, "AA")]), |
| 680 | + DEFAULT_MAX_FILE_BYTES, | ||
| 577 | ) | 681 | ) |
| 578 | .unwrap(); | 682 | .unwrap(); |
| 579 | assert_eq!(s.grade_label(0.0), Some("FF")); | 683 | assert_eq!(s.grade_label(0.0), Some("FF")); |
src/error.rsmodified+5 -0
| @@ -51,6 +51,10 @@ pub enum AppError { | |||
| 51 | Forbidden(&'static str), | 51 | Forbidden(&'static str), |
| 52 | #[error("conflict: {0}")] | 52 | #[error("conflict: {0}")] |
| 53 | Conflict(&'static str), | 53 | Conflict(&'static str), |
| 54 | + /// A request body (file upload) over the allowed size. Owned string: the | ||
| 55 | + /// school-configured limit is only known at runtime. | ||
| 56 | + #[error("payload too large: {0}")] | ||
| 57 | + PayloadTooLarge(String), | ||
| 54 | #[error("too many requests")] | 58 | #[error("too many requests")] |
| 55 | TooManyRequests { retry_after_secs: u64 }, | 59 | TooManyRequests { retry_after_secs: u64 }, |
| 56 | #[error("database error")] | 60 | #[error("database error")] |
| @@ -82,6 +86,7 @@ impl IntoResponse for AppError { | |||
| 82 | AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), | 86 | AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), |
| 83 | AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()), | 87 | AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()), |
| 84 | AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()), | 88 | AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()), |
| 89 | + AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()), | ||
| 85 | AppError::Db(e) => { | 90 | AppError::Db(e) => { |
| 86 | tracing::error!("database error: {e}"); | 91 | tracing::error!("database error: {e}"); |
| 87 | ( | 92 | ( |
src/lib.rsmodified+3 -3
| @@ -32,14 +32,14 @@ use crate::state::AppState; | |||
| 32 | info( | 32 | info( |
| 33 | title = "Hezarfen Backend API", | 33 | title = "Hezarfen Backend API", |
| 34 | version = env!("CARGO_PKG_VERSION"), | 34 | version = env!("CARGO_PKG_VERSION"), |
| 35 | - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. 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. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands) lives in an editable settings singleton, and courses may link to academic terms. 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.", | 35 | + 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). 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. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. 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. 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.", |
| 36 | ), | 36 | ), |
| 37 | modifiers(&SecurityAddon), | 37 | modifiers(&SecurityAddon), |
| 38 | tags( | 38 | tags( |
| 39 | (name = "meta", description = "Liveness and service metadata"), | 39 | (name = "meta", description = "Liveness and service metadata"), |
| 40 | (name = "auth", description = "Registration, login, session lifecycle"), | 40 | (name = "auth", description = "Registration, login, session lifecycle"), |
| 41 | (name = "users", description = "User info: self-service profile, name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile administration (admin only)"), | 41 | (name = "users", description = "User info: self-service profile, name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile administration (admin only)"), |
| 42 | - (name = "notes", description = "Per-user notes CRUD"), | 42 | + (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), |
| 43 | (name = "events", description = "Events and attendance"), | 43 | (name = "events", description = "Events and attendance"), |
| 44 | (name = "courses", description = "Courses, enrollment (students only), course exams, and course sessions"), | 44 | (name = "courses", description = "Courses, enrollment (students only), course exams, and course sessions"), |
| 45 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), | 45 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), |
| @@ -47,7 +47,7 @@ use crate::state::AppState; | |||
| 47 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), | 47 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), |
| 48 | (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), | 48 | (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), |
| 49 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"), | 49 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"), |
| 50 | - (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands. Read: any authenticated user; edit: manager+"), | 50 | + (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file note-upload size limit (`max_file_bytes`). Read: any authenticated user; edit: manager+"), |
| 51 | (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), | 51 | (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), |
| 52 | ), | 52 | ), |
| 53 | )] | 53 | )] |
src/main.rsmodified+4 -0
| @@ -18,8 +18,12 @@ async fn main() -> anyhow::Result<()> { | |||
| 18 | let cfg = Config::from_env(); | 18 | let cfg = Config::from_env(); |
| 19 | let db = database::init(&cfg).await?; | 19 | let db = database::init(&cfg).await?; |
| 20 | seed_admin(&cfg, &db).await?; | 20 | seed_admin(&cfg, &db).await?; |
| 21 | + tokio::fs::create_dir_all(&cfg.files_path) | ||
| 22 | + .await | ||
| 23 | + .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?; | ||
| 21 | let app = build_router(AppState { | 24 | let app = build_router(AppState { |
| 22 | db, | 25 | db, |
| 26 | + files_path: cfg.files_path.clone().into(), | ||
| 23 | cookie_secure: cfg.cookie_secure, | 27 | cookie_secure: cfg.cookie_secure, |
| 24 | rate_limit: cfg.rate_limit.clone(), | 28 | rate_limit: cfg.rate_limit.clone(), |
| 25 | exam_presence: Default::default(), | 29 | exam_presence: Default::default(), |
src/state.rsmodified+5 -0
| @@ -1,4 +1,5 @@ | |||
| 1 | use std::collections::HashMap; | 1 | use std::collections::HashMap; |
| 2 | +use std::path::PathBuf; | ||
| 2 | use std::sync::{Arc, Mutex}; | 3 | use std::sync::{Arc, Mutex}; |
| 3 | 4 | ||
| 4 | use crate::database::Database; | 5 | use crate::database::Database; |
| @@ -8,6 +9,10 @@ use crate::rate_limit::RateLimitConfig; | |||
| 8 | #[derive(Clone)] | 9 | #[derive(Clone)] |
| 9 | pub struct AppState { | 10 | pub struct AppState { |
| 10 | pub db: Database, | 11 | pub db: Database, |
| 12 | + /// Directory holding uploaded note-file blobs, one file per | ||
| 13 | + /// `note_file` row, named by the row's key | ||
| 14 | + /// (from [`crate::config::Config::files_path`]). | ||
| 15 | + pub files_path: PathBuf, | ||
| 11 | /// Whether the session cookie carries the `Secure` attribute | 16 | /// Whether the session cookie carries the `Secure` attribute |
| 12 | /// (from [`crate::config::Config::cookie_secure`]). | 17 | /// (from [`crate::config::Config::cookie_secure`]). |
| 13 | pub cookie_secure: bool, | 18 | pub cookie_secure: bool, |
src/web/exam_ws.rsmodified+1 -0
| @@ -399,6 +399,7 @@ fn error_frame(err: &AppError) -> Value { | |||
| 399 | AppError::Unauthorized => "unauthorized".to_string(), | 399 | AppError::Unauthorized => "unauthorized".to_string(), |
| 400 | AppError::Forbidden(message) => (*message).to_string(), | 400 | AppError::Forbidden(message) => (*message).to_string(), |
| 401 | AppError::Conflict(message) => (*message).to_string(), | 401 | AppError::Conflict(message) => (*message).to_string(), |
| 402 | + AppError::PayloadTooLarge(message) => message.clone(), | ||
| 402 | AppError::TooManyRequests { .. } => "too many requests".to_string(), | 403 | AppError::TooManyRequests { .. } => "too many requests".to_string(), |
| 403 | AppError::Db(_) | AppError::Internal(_) => { | 404 | AppError::Db(_) | AppError::Internal(_) => { |
| 404 | tracing::error!("exam room error: {err}"); | 405 | tracing::error!("exam room error: {err}"); |
src/web/notes.rsmodified+370 -4
| @@ -1,21 +1,40 @@ | |||
| 1 | +use std::path::{Path as FsPath, PathBuf}; | ||
| 2 | + | ||
| 1 | use axum::Json; | 3 | use axum::Json; |
| 2 | -use axum::extract::{Path, Query, State}; | 4 | +use axum::extract::multipart::MultipartError; |
| 3 | -use axum::http::StatusCode; | 5 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; |
| 6 | +use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; | ||
| 7 | +use axum::http::{HeaderValue, StatusCode}; | ||
| 8 | +use axum::response::{IntoResponse, Response}; | ||
| 4 | use serde::{Deserialize, Serialize}; | 9 | use serde::{Deserialize, Serialize}; |
| 5 | use utoipa::ToSchema; | 10 | use utoipa::ToSchema; |
| 6 | use utoipa_axum::router::OpenApiRouter; | 11 | use utoipa_axum::router::OpenApiRouter; |
| 7 | use utoipa_axum::routes; | 12 | use utoipa_axum::routes; |
| 8 | 13 | ||
| 14 | +use crate::constant::{MAX_MAX_FILE_BYTES, MAX_NOTE_FILES, UPLOAD_BODY_OVERHEAD_BYTES}; | ||
| 9 | use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; | 15 | use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; |
| 10 | -use crate::error::{AppError, ErrorResponse}; | 16 | +use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; |
| 17 | +use crate::domain::settings::Settings; | ||
| 18 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 11 | use crate::state::AppState; | 19 | use crate::state::AppState; |
| 12 | 20 | ||
| 13 | use super::{CurrentUser, Page, PageParams, paginate}; | 21 | use super::{CurrentUser, Page, PageParams, paginate}; |
| 14 | 22 | ||
| 15 | pub fn routes() -> OpenApiRouter<AppState> { | 23 | pub fn routes() -> OpenApiRouter<AppState> { |
| 24 | + // The file routes get their own HTTP body cap: the server-wide hard | ||
| 25 | + // ceiling plus multipart framing headroom (axum's 2 MB default would | ||
| 26 | + // reject legal uploads). The school's actual — usually smaller — limit | ||
| 27 | + // from settings is enforced while the stream is read. | ||
| 28 | + let files = OpenApiRouter::new() | ||
| 29 | + .routes(routes!(upload_file, list_files)) | ||
| 30 | + .routes(routes!(download_file, delete_file)) | ||
| 31 | + .layer(DefaultBodyLimit::max( | ||
| 32 | + MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, | ||
| 33 | + )); | ||
| 16 | OpenApiRouter::new() | 34 | OpenApiRouter::new() |
| 17 | .routes(routes!(create, list)) | 35 | .routes(routes!(create, list)) |
| 18 | .routes(routes!(get_one, update, delete_one)) | 36 | .routes(routes!(get_one, update, delete_one)) |
| 37 | + .merge(files) | ||
| 19 | } | 38 | } |
| 20 | 39 | ||
| 21 | #[derive(Deserialize, ToSchema)] | 40 | #[derive(Deserialize, ToSchema)] |
| @@ -165,7 +184,7 @@ async fn update( | |||
| 165 | Ok(Json(NoteResponse::new(&updated))) | 184 | Ok(Json(NoteResponse::new(&updated))) |
| 166 | } | 185 | } |
| 167 | 186 | ||
| 168 | -/// Delete a note owned by the current user. | 187 | +/// Delete a note owned by the current user, along with its files. |
| 169 | #[utoipa::path( | 188 | #[utoipa::path( |
| 170 | delete, | 189 | delete, |
| 171 | path = "/{id}", | 190 | path = "/{id}", |
| @@ -186,6 +205,353 @@ async fn delete_one( | |||
| 186 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) | 205 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| 187 | .await? | 206 | .await? |
| 188 | .ok_or(AppError::NotFound)?; | 207 | .ok_or(AppError::NotFound)?; |
| 208 | + // Rows go first (the note delete cascades them), blobs after: a crash in | ||
| 209 | + // between strands at worst an unreachable blob, never a row whose blob is | ||
| 210 | + // already gone. | ||
| 211 | + let files = NoteFile::list_for(note.get_id(), &st.db).await?; | ||
| 189 | note.delete(&st.db).await?; | 212 | note.delete(&st.db).await?; |
| 213 | + for file in &files { | ||
| 214 | + remove_blob(&st.files_path, file.get_id()).await; | ||
| 215 | + } | ||
| 190 | Ok(StatusCode::NO_CONTENT) | 216 | Ok(StatusCode::NO_CONTENT) |
| 191 | } | 217 | } |
| 218 | + | ||
| 219 | +/// A note file's stored metadata; the bytes themselves come from the | ||
| 220 | +/// download endpoint. | ||
| 221 | +#[derive(Serialize, ToSchema)] | ||
| 222 | +struct NoteFileResponse { | ||
| 223 | + id: String, | ||
| 224 | + /// The uploader's original filename. | ||
| 225 | + #[schema(example = "homework.pdf")] | ||
| 226 | + name: String, | ||
| 227 | + /// MIME type as declared on upload. | ||
| 228 | + #[schema(example = "application/pdf")] | ||
| 229 | + content_type: String, | ||
| 230 | + /// File size in bytes. | ||
| 231 | + #[schema(example = 24_576)] | ||
| 232 | + size: i64, | ||
| 233 | +} | ||
| 234 | + | ||
| 235 | +impl NoteFileResponse { | ||
| 236 | + fn new(file: &NoteFile) -> Self { | ||
| 237 | + Self { | ||
| 238 | + id: file.get_id().key().to_string(), | ||
| 239 | + name: file.get_name().as_str().to_string(), | ||
| 240 | + content_type: file.get_content_type().as_str().to_string(), | ||
| 241 | + size: file.get_size(), | ||
| 242 | + } | ||
| 243 | + } | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +/// Schema-only mirror of the upload form; the handler reads the multipart | ||
| 247 | +/// stream directly. | ||
| 248 | +#[derive(ToSchema)] | ||
| 249 | +#[allow(dead_code)] | ||
| 250 | +struct UploadFileForm { | ||
| 251 | + /// The file part. Its `filename` (required) and `Content-Type` are stored | ||
| 252 | + /// alongside the bytes. | ||
| 253 | + #[schema(value_type = String, format = Binary)] | ||
| 254 | + file: String, | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +/// Attach a file to a note owned by the current user. `multipart/form-data` | ||
| 258 | +/// with the file under a `file` field; its `filename` is required. At most | ||
| 259 | +/// 10 files per note; each file at most the school's `max_file_bytes` | ||
| 260 | +/// (settings, default 5 MiB). | ||
| 261 | +#[utoipa::path( | ||
| 262 | + post, | ||
| 263 | + path = "/{id}/files", | ||
| 264 | + tag = "notes", | ||
| 265 | + security(("session_cookie" = [])), | ||
| 266 | + params(("id" = String, Path, description = "Note id")), | ||
| 267 | + request_body(content = UploadFileForm, content_type = "multipart/form-data"), | ||
| 268 | + responses( | ||
| 269 | + (status = 201, description = "File stored", body = NoteFileResponse), | ||
| 270 | + (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse), | ||
| 271 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 272 | + (status = 404, description = "Note not found", body = ErrorResponse), | ||
| 273 | + (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse), | ||
| 274 | + (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse), | ||
| 275 | + ), | ||
| 276 | +)] | ||
| 277 | +async fn upload_file( | ||
| 278 | + State(st): State<AppState>, | ||
| 279 | + CurrentUser(user): CurrentUser, | ||
| 280 | + Path(id): Path<String>, | ||
| 281 | + mut multipart: Multipart, | ||
| 282 | +) -> Result<(StatusCode, Json<NoteFileResponse>), AppError> { | ||
| 283 | + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) | ||
| 284 | + .await? | ||
| 285 | + .ok_or(AppError::NotFound)?; | ||
| 286 | + if NoteFile::list_for(note.get_id(), &st.db).await?.len() >= MAX_NOTE_FILES { | ||
| 287 | + return Err(AppError::Conflict( | ||
| 288 | + "the note already holds the maximum of 10 files — delete one first", | ||
| 289 | + )); | ||
| 290 | + } | ||
| 291 | + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); | ||
| 292 | + | ||
| 293 | + let mut field = loop { | ||
| 294 | + match multipart.next_field().await.map_err(multipart_error)? { | ||
| 295 | + Some(field) if field.name() == Some("file") => break field, | ||
| 296 | + Some(_) => continue, // ignore stray extra fields | ||
| 297 | + None => { | ||
| 298 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 299 | + field: "file", | ||
| 300 | + reason: "the multipart body must carry a 'file' field", | ||
| 301 | + })); | ||
| 302 | + } | ||
| 303 | + } | ||
| 304 | + }; | ||
| 305 | + let name = FileName::try_new(field.file_name().unwrap_or_default())?; | ||
| 306 | + let content_type = FileContentType::try_new(field.content_type().unwrap_or_default())?; | ||
| 307 | + | ||
| 308 | + // Read the part chunkwise so an oversized upload dies at the limit, not | ||
| 309 | + // after buffering whole. The check is on real bytes received — a lying | ||
| 310 | + // Content-Length can't sneak past it. | ||
| 311 | + let mut data = Vec::new(); | ||
| 312 | + while let Some(chunk) = field.chunk().await.map_err(multipart_error)? { | ||
| 313 | + if data.len() + chunk.len() > limit as usize { | ||
| 314 | + return Err(AppError::PayloadTooLarge(format!( | ||
| 315 | + "the file exceeds the school's limit of {limit} bytes" | ||
| 316 | + ))); | ||
| 317 | + } | ||
| 318 | + data.extend_from_slice(&chunk); | ||
| 319 | + } | ||
| 320 | + if data.is_empty() { | ||
| 321 | + return Err(AppError::Validation(ValidationError::Empty("file"))); | ||
| 322 | + } | ||
| 323 | + | ||
| 324 | + // Blob first, row second — a stored row always points at a real blob. If | ||
| 325 | + // the row insert fails, take the fresh blob back out. | ||
| 326 | + let file = NoteFile::new(note.get_id(), name, content_type, data.len() as i64); | ||
| 327 | + let path = blob_path(&st.files_path, file.get_id()); | ||
| 328 | + tokio::fs::write(&path, &data) | ||
| 329 | + .await | ||
| 330 | + .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; | ||
| 331 | + match file.insert(&st.db).await { | ||
| 332 | + Ok(created) => Ok((StatusCode::CREATED, Json(NoteFileResponse::new(&created)))), | ||
| 333 | + Err(err) => { | ||
| 334 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 335 | + Err(err) | ||
| 336 | + } | ||
| 337 | + } | ||
| 338 | +} | ||
| 339 | + | ||
| 340 | +/// List a note's files (metadata only), newest first. Paged via | ||
| 341 | +/// `?limit=&offset=`. | ||
| 342 | +#[utoipa::path( | ||
| 343 | + get, | ||
| 344 | + path = "/{id}/files", | ||
| 345 | + tag = "notes", | ||
| 346 | + security(("session_cookie" = [])), | ||
| 347 | + params(("id" = String, Path, description = "Note id"), PageParams), | ||
| 348 | + responses( | ||
| 349 | + (status = 200, description = "A page of the note's files", body = Page<NoteFileResponse>), | ||
| 350 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | ||
| 351 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 352 | + (status = 404, description = "Note not found", body = ErrorResponse), | ||
| 353 | + ), | ||
| 354 | +)] | ||
| 355 | +async fn list_files( | ||
| 356 | + State(st): State<AppState>, | ||
| 357 | + CurrentUser(user): CurrentUser, | ||
| 358 | + Path(id): Path<String>, | ||
| 359 | + Query(page): Query<PageParams>, | ||
| 360 | +) -> Result<Json<Page<NoteFileResponse>>, AppError> { | ||
| 361 | + let (limit, offset) = page.resolve()?; | ||
| 362 | + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) | ||
| 363 | + .await? | ||
| 364 | + .ok_or(AppError::NotFound)?; | ||
| 365 | + let files = NoteFile::list_for(note.get_id(), &st.db).await?; | ||
| 366 | + let total = files.len() as i64; | ||
| 367 | + let items = paginate(&files, limit, offset) | ||
| 368 | + .iter() | ||
| 369 | + .map(NoteFileResponse::new) | ||
| 370 | + .collect(); | ||
| 371 | + Ok(Json(Page::new(items, total, limit, offset))) | ||
| 372 | +} | ||
| 373 | + | ||
| 374 | +/// Download a note file's bytes. `Content-Type` is the one declared on | ||
| 375 | +/// upload; `Content-Disposition` carries the original filename. | ||
| 376 | +#[utoipa::path( | ||
| 377 | + get, | ||
| 378 | + path = "/{id}/files/{file_id}", | ||
| 379 | + tag = "notes", | ||
| 380 | + security(("session_cookie" = [])), | ||
| 381 | + params( | ||
| 382 | + ("id" = String, Path, description = "Note id"), | ||
| 383 | + ("file_id" = String, Path, description = "File id"), | ||
| 384 | + ), | ||
| 385 | + responses( | ||
| 386 | + (status = 200, description = "The file bytes", content_type = "application/octet-stream"), | ||
| 387 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 388 | + (status = 404, description = "Note or file not found", body = ErrorResponse), | ||
| 389 | + ), | ||
| 390 | +)] | ||
| 391 | +async fn download_file( | ||
| 392 | + State(st): State<AppState>, | ||
| 393 | + CurrentUser(user): CurrentUser, | ||
| 394 | + Path((id, file_id)): Path<(String, String)>, | ||
| 395 | +) -> Result<Response, AppError> { | ||
| 396 | + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) | ||
| 397 | + .await? | ||
| 398 | + .ok_or(AppError::NotFound)?; | ||
| 399 | + let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) | ||
| 400 | + .await? | ||
| 401 | + .ok_or(AppError::NotFound)?; | ||
| 402 | + let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id())) | ||
| 403 | + .await | ||
| 404 | + .map_err(|err| { | ||
| 405 | + // The row exists but its blob doesn't — that's server-side damage | ||
| 406 | + // (a lost volume path), not a client 404. | ||
| 407 | + AppError::Internal(format!( | ||
| 408 | + "missing blob for note file {}: {err}", | ||
| 409 | + file.get_id().key() | ||
| 410 | + )) | ||
| 411 | + })?; | ||
| 412 | + // The stored content type is validated ASCII without control characters, | ||
| 413 | + // so it always parses; the fallback is for belt and braces. | ||
| 414 | + let content_type = HeaderValue::from_str(file.get_content_type().as_str()) | ||
| 415 | + .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")); | ||
| 416 | + let disposition = HeaderValue::from_str(&content_disposition(file.get_name().as_str())) | ||
| 417 | + .unwrap_or_else(|_| HeaderValue::from_static("attachment")); | ||
| 418 | + Ok(( | ||
| 419 | + [ | ||
| 420 | + (CONTENT_TYPE, content_type), | ||
| 421 | + (CONTENT_DISPOSITION, disposition), | ||
| 422 | + ], | ||
| 423 | + bytes, | ||
| 424 | + ) | ||
| 425 | + .into_response()) | ||
| 426 | +} | ||
| 427 | + | ||
| 428 | +/// Delete a note file (row first, then its blob). | ||
| 429 | +#[utoipa::path( | ||
| 430 | + delete, | ||
| 431 | + path = "/{id}/files/{file_id}", | ||
| 432 | + tag = "notes", | ||
| 433 | + security(("session_cookie" = [])), | ||
| 434 | + params( | ||
| 435 | + ("id" = String, Path, description = "Note id"), | ||
| 436 | + ("file_id" = String, Path, description = "File id"), | ||
| 437 | + ), | ||
| 438 | + responses( | ||
| 439 | + (status = 204, description = "Deleted"), | ||
| 440 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 441 | + (status = 404, description = "Note or file not found", body = ErrorResponse), | ||
| 442 | + ), | ||
| 443 | +)] | ||
| 444 | +async fn delete_file( | ||
| 445 | + State(st): State<AppState>, | ||
| 446 | + CurrentUser(user): CurrentUser, | ||
| 447 | + Path((id, file_id)): Path<(String, String)>, | ||
| 448 | +) -> Result<StatusCode, AppError> { | ||
| 449 | + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) | ||
| 450 | + .await? | ||
| 451 | + .ok_or(AppError::NotFound)?; | ||
| 452 | + let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) | ||
| 453 | + .await? | ||
| 454 | + .ok_or(AppError::NotFound)?; | ||
| 455 | + let file = file.delete(&st.db).await?; | ||
| 456 | + remove_blob(&st.files_path, file.get_id()).await; | ||
| 457 | + Ok(StatusCode::NO_CONTENT) | ||
| 458 | +} | ||
| 459 | + | ||
| 460 | +/// Where a file row's blob lives: one file under the configured directory, | ||
| 461 | +/// named by the row's server-generated key — user input never shapes a path. | ||
| 462 | +fn blob_path(files_path: &FsPath, id: &NoteFileId) -> PathBuf { | ||
| 463 | + files_path.join(id.key()) | ||
| 464 | +} | ||
| 465 | + | ||
| 466 | +/// Best-effort blob removal after its row is gone. Failure only strands an | ||
| 467 | +/// unreachable file on disk, so it is logged rather than surfaced. | ||
| 468 | +async fn remove_blob(files_path: &FsPath, id: &NoteFileId) { | ||
| 469 | + let path = blob_path(files_path, id); | ||
| 470 | + if let Err(err) = tokio::fs::remove_file(&path).await | ||
| 471 | + && err.kind() != std::io::ErrorKind::NotFound | ||
| 472 | + { | ||
| 473 | + tracing::warn!("failed to remove blob {}: {err}", path.display()); | ||
| 474 | + } | ||
| 475 | +} | ||
| 476 | + | ||
| 477 | +/// Multipart read failures: the route-level body cap maps to 413 like the | ||
| 478 | +/// school-limit check; anything else is a malformed body. | ||
| 479 | +fn multipart_error(err: MultipartError) -> AppError { | ||
| 480 | + if err.status() == StatusCode::PAYLOAD_TOO_LARGE { | ||
| 481 | + AppError::PayloadTooLarge("the upload exceeds the server's absolute body cap".to_string()) | ||
| 482 | + } else { | ||
| 483 | + AppError::Validation(ValidationError::Invalid { | ||
| 484 | + field: "file", | ||
| 485 | + reason: "malformed multipart body", | ||
| 486 | + }) | ||
| 487 | + } | ||
| 488 | +} | ||
| 489 | + | ||
| 490 | +/// `Content-Disposition` for a download: an ASCII-safe `filename` fallback | ||
| 491 | +/// plus the RFC 5987 `filename*` form so non-ASCII names (`ödev.pdf`) survive. | ||
| 492 | +fn content_disposition(name: &str) -> String { | ||
| 493 | + let fallback: String = name | ||
| 494 | + .chars() | ||
| 495 | + .map(|c| { | ||
| 496 | + if c.is_ascii_graphic() && c != '"' && c != '\\' || c == ' ' { | ||
| 497 | + c | ||
| 498 | + } else { | ||
| 499 | + '_' | ||
| 500 | + } | ||
| 501 | + }) | ||
| 502 | + .collect(); | ||
| 503 | + format!( | ||
| 504 | + "attachment; filename=\"{fallback}\"; filename*=UTF-8''{}", | ||
| 505 | + rfc5987_encode(name) | ||
| 506 | + ) | ||
| 507 | +} | ||
| 508 | + | ||
| 509 | +/// Percent-encode everything outside RFC 5987's `attr-char` set, on UTF-8 | ||
| 510 | +/// bytes. | ||
| 511 | +fn rfc5987_encode(value: &str) -> String { | ||
| 512 | + let mut out = String::with_capacity(value.len()); | ||
| 513 | + for byte in value.bytes() { | ||
| 514 | + match byte { | ||
| 515 | + b'a'..=b'z' | ||
| 516 | + | b'A'..=b'Z' | ||
| 517 | + | b'0'..=b'9' | ||
| 518 | + | b'!' | ||
| 519 | + | b'#' | ||
| 520 | + | b'$' | ||
| 521 | + | b'&' | ||
| 522 | + | b'+' | ||
| 523 | + | b'-' | ||
| 524 | + | b'.' | ||
| 525 | + | b'^' | ||
| 526 | + | b'_' | ||
| 527 | + | b'`' | ||
| 528 | + | b'|' | ||
| 529 | + | b'~' => out.push(byte as char), | ||
| 530 | + _ => out.push_str(&format!("%{byte:02X}")), | ||
| 531 | + } | ||
| 532 | + } | ||
| 533 | + out | ||
| 534 | +} | ||
| 535 | + | ||
| 536 | +#[cfg(test)] | ||
| 537 | +mod tests { | ||
| 538 | + use super::*; | ||
| 539 | + | ||
| 540 | + #[tokio::test] | ||
| 541 | + async fn disposition_keeps_ascii_and_encodes_the_rest() { | ||
| 542 | + assert_eq!( | ||
| 543 | + content_disposition("plan.pdf"), | ||
| 544 | + "attachment; filename=\"plan.pdf\"; filename*=UTF-8''plan.pdf" | ||
| 545 | + ); | ||
| 546 | + // Non-ASCII survives in the RFC 5987 form; the fallback degrades. | ||
| 547 | + assert_eq!( | ||
| 548 | + content_disposition("ödev 1.pdf"), | ||
| 549 | + "attachment; filename=\"_dev 1.pdf\"; filename*=UTF-8''%C3%B6dev%201.pdf" | ||
| 550 | + ); | ||
| 551 | + // Quotes can't break out of the quoted fallback. | ||
| 552 | + assert_eq!( | ||
| 553 | + content_disposition("a\"b.pdf"), | ||
| 554 | + "attachment; filename=\"a_b.pdf\"; filename*=UTF-8''a%22b.pdf" | ||
| 555 | + ); | ||
| 556 | + } | ||
| 557 | +} | ||
src/web/settings.rsmodified+16 -3
| @@ -60,6 +60,9 @@ struct SettingsResponse { | |||
| 60 | attendance_statuses: Vec<String>, | 60 | attendance_statuses: Vec<String>, |
| 61 | /// Grade-display bands, highest first. Empty = marks display numeric-only. | 61 | /// Grade-display bands, highest first. Empty = marks display numeric-only. |
| 62 | grade_bands: Vec<GradeBandDto>, | 62 | grade_bands: Vec<GradeBandDto>, |
| 63 | + /// Per-file size limit for note uploads, in bytes. | ||
| 64 | + #[schema(example = 5_242_880)] | ||
| 65 | + max_file_bytes: i64, | ||
| 63 | } | 66 | } |
| 64 | 67 | ||
| 65 | impl SettingsResponse { | 68 | impl SettingsResponse { |
| @@ -82,6 +85,7 @@ impl SettingsResponse { | |||
| 82 | label: band.get_label().to_string(), | 85 | label: band.get_label().to_string(), |
| 83 | }) | 86 | }) |
| 84 | .collect(), | 87 | .collect(), |
| 88 | + max_file_bytes: settings.get_max_file_bytes(), | ||
| 85 | } | 89 | } |
| 86 | } | 90 | } |
| 87 | } | 91 | } |
| @@ -97,6 +101,10 @@ struct UpdateSettings { | |||
| 97 | /// Replaces the whole set when present. `[]` clears the bands (numeric-only | 101 | /// Replaces the whole set when present. `[]` clears the bands (numeric-only |
| 98 | /// marks); otherwise mins are unique and one band must start at `0`. | 102 | /// marks); otherwise mins are unique and one band must start at `0`. |
| 99 | grade_bands: Option<Vec<GradeBandDto>>, | 103 | grade_bands: Option<Vec<GradeBandDto>>, |
| 104 | + /// Per-file size limit for note uploads, in bytes: | ||
| 105 | + /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap. | ||
| 106 | + #[schema(example = 5_242_880)] | ||
| 107 | + max_file_bytes: Option<i64>, | ||
| 100 | } | 108 | } |
| 101 | 109 | ||
| 102 | /// The school's current policy. Any authenticated user — clients need it to | 110 | /// The school's current policy. Any authenticated user — clients need it to |
| @@ -126,7 +134,8 @@ async fn get_settings( | |||
| 126 | /// new writes are held to the new lists. Kind weights, though, apply live: | 134 | /// new writes are held to the new lists. Kind weights, though, apply live: |
| 127 | /// mark reports read them at request time, so editing a weight re-weights | 135 | /// mark reports read them at request time, so editing a weight re-weights |
| 128 | /// every exam of that kind, and an exam whose kind was removed from the list | 136 | /// every exam of that kind, and an exam whose kind was removed from the list |
| 129 | -/// counts with weight 1 until the kind returns. | 137 | +/// counts with weight 1 until the kind returns. `max_file_bytes` likewise |
| 138 | +/// applies at upload time only — already-stored files keep their size. | ||
| 130 | #[utoipa::path( | 139 | #[utoipa::path( |
| 131 | patch, | 140 | patch, |
| 132 | path = "/", | 141 | path = "/", |
| @@ -135,7 +144,7 @@ async fn get_settings( | |||
| 135 | request_body = UpdateSettings, | 144 | request_body = UpdateSettings, |
| 136 | responses( | 145 | responses( |
| 137 | (status = 200, description = "Updated policy", body = SettingsResponse), | 146 | (status = 200, description = "Updated policy", body = SettingsResponse), |
| 138 | - (status = 400, description = "Invalid lists or bands", body = ErrorResponse), | 147 | + (status = 400, description = "Invalid lists, bands, or file limit", body = ErrorResponse), |
| 139 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 148 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 140 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 149 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 141 | (status = 409, description = "Concurrent edits kept changing the settings mid-save", body = ErrorResponse), | 150 | (status = 409, description = "Concurrent edits kept changing the settings mid-save", body = ErrorResponse), |
| @@ -171,8 +180,12 @@ async fn update_settings( | |||
| 171 | .collect::<Result<Vec<_>, _>>()?, | 180 | .collect::<Result<Vec<_>, _>>()?, |
| 172 | None => current.get_grade_bands().to_vec(), | 181 | None => current.get_grade_bands().to_vec(), |
| 173 | }; | 182 | }; |
| 183 | + let max_file_bytes = req | ||
| 184 | + .max_file_bytes | ||
| 185 | + .unwrap_or_else(|| current.get_max_file_bytes()); | ||
| 174 | 186 | ||
| 175 | - let settings = Settings::try_new(exam_kinds, attendance_statuses, grade_bands)?; | 187 | + let settings = |
| 188 | + Settings::try_new(exam_kinds, attendance_statuses, grade_bands, max_file_bytes)?; | ||
| 176 | if let Some(saved) = settings.save_if_unchanged(¤t, &st.db).await? { | 189 | if let Some(saved) = settings.save_if_unchanged(¤t, &st.db).await? { |
| 177 | return Ok(Json(SettingsResponse::new(&saved))); | 190 | return Ok(Json(SettingsResponse::new(&saved))); |
| 178 | } | 191 | } |
tests/common/mod.rsmodified+98 -1
| @@ -2,14 +2,18 @@ | |||
| 2 | //! Drives an `axum::Router` in-process via `tower::ServiceExt::oneshot`. | 2 | //! Drives an `axum::Router` in-process via `tower::ServiceExt::oneshot`. |
| 3 | #![allow(dead_code)] | 3 | #![allow(dead_code)] |
| 4 | 4 | ||
| 5 | +use std::path::PathBuf; | ||
| 6 | +use std::sync::OnceLock; | ||
| 7 | + | ||
| 5 | use axum::Router; | 8 | use axum::Router; |
| 6 | use axum::body::Body; | 9 | use axum::body::Body; |
| 7 | -use axum::http::{Request, StatusCode}; | 10 | +use axum::http::{HeaderMap, Request, StatusCode}; |
| 8 | use hezarfen_backend::database::Database; | 11 | use hezarfen_backend::database::Database; |
| 9 | use hezarfen_backend::rate_limit::RateLimitConfig; | 12 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 10 | use hezarfen_backend::state::AppState; | 13 | use hezarfen_backend::state::AppState; |
| 11 | use hezarfen_backend::{build_router, database}; | 14 | use hezarfen_backend::{build_router, database}; |
| 12 | use serde_json::{Value, json}; | 15 | use serde_json::{Value, json}; |
| 16 | +use tempfile::TempDir; | ||
| 13 | use tower::ServiceExt; | 17 | use tower::ServiceExt; |
| 14 | 18 | ||
| 15 | pub struct Res { | 19 | pub struct Res { |
| @@ -19,6 +23,18 @@ pub struct Res { | |||
| 19 | pub cookie: Option<String>, | 23 | pub cookie: Option<String>, |
| 20 | } | 24 | } |
| 21 | 25 | ||
| 26 | +/// One shared blob directory for every in-memory app in this test process. | ||
| 27 | +/// Blob names are per-row ULIDs, so apps never collide; the static keeps the | ||
| 28 | +/// `TempDir` (and so the directory) alive for the whole run. | ||
| 29 | +static FILES_DIR: OnceLock<TempDir> = OnceLock::new(); | ||
| 30 | + | ||
| 31 | +pub fn files_dir() -> PathBuf { | ||
| 32 | + FILES_DIR | ||
| 33 | + .get_or_init(|| tempfile::tempdir().expect("files tempdir")) | ||
| 34 | + .path() | ||
| 35 | + .to_path_buf() | ||
| 36 | +} | ||
| 37 | + | ||
| 22 | /// A router plus a handle to its (shared) in-memory database. Tests that need to | 38 | /// A router plus a handle to its (shared) in-memory database. Tests that need to |
| 23 | /// grant roles use the handle to seed them directly — the app's only role | 39 | /// grant roles use the handle to seed them directly — the app's only role |
| 24 | /// bootstrap path is out-of-band, exactly like production's manual SQL. | 40 | /// bootstrap path is out-of-band, exactly like production's manual SQL. |
| @@ -26,6 +42,7 @@ pub async fn app_and_db() -> (Router, Database) { | |||
| 26 | let db = database::init_mem().await.expect("in-memory db"); | 42 | let db = database::init_mem().await.expect("in-memory db"); |
| 27 | let app = build_router(AppState { | 43 | let app = build_router(AppState { |
| 28 | db: db.clone(), | 44 | db: db.clone(), |
| 45 | + files_path: files_dir(), | ||
| 29 | cookie_secure: false, | 46 | cookie_secure: false, |
| 30 | // Off, so suites hammering the API never trip a limit; the dedicated | 47 | // Off, so suites hammering the API never trip a limit; the dedicated |
| 31 | // `rate_limit` test binary opts into tight configs on purpose. | 48 | // `rate_limit` test binary opts into tight configs on purpose. |
| @@ -107,6 +124,86 @@ pub async fn send( | |||
| 107 | } | 124 | } |
| 108 | } | 125 | } |
| 109 | 126 | ||
| 127 | +/// Send one request with a raw body and content type; returns the raw | ||
| 128 | +/// response (status, headers, body bytes) — for driving the file endpoints. | ||
| 129 | +pub async fn send_raw( | ||
| 130 | + app: &Router, | ||
| 131 | + method: &str, | ||
| 132 | + uri: &str, | ||
| 133 | + cookie: Option<&str>, | ||
| 134 | + content_type: Option<&str>, | ||
| 135 | + body: Vec<u8>, | ||
| 136 | +) -> (StatusCode, HeaderMap, Vec<u8>) { | ||
| 137 | + let mut builder = Request::builder().method(method).uri(uri); | ||
| 138 | + if let Some(c) = cookie { | ||
| 139 | + builder = builder.header("cookie", c); | ||
| 140 | + } | ||
| 141 | + if let Some(ct) = content_type { | ||
| 142 | + builder = builder.header("content-type", ct); | ||
| 143 | + } | ||
| 144 | + let response = app | ||
| 145 | + .clone() | ||
| 146 | + .oneshot(builder.body(Body::from(body)).unwrap()) | ||
| 147 | + .await | ||
| 148 | + .unwrap(); | ||
| 149 | + let status = response.status(); | ||
| 150 | + let headers = response.headers().clone(); | ||
| 151 | + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) | ||
| 152 | + .await | ||
| 153 | + .unwrap() | ||
| 154 | + .to_vec(); | ||
| 155 | + (status, headers, bytes) | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +const MULTIPART_BOUNDARY: &str = "hezarfen-test-boundary"; | ||
| 159 | + | ||
| 160 | +/// A `multipart/form-data` body with a single `file` part. | ||
| 161 | +pub fn multipart_file(filename: &str, content_type: &str, bytes: &[u8]) -> Vec<u8> { | ||
| 162 | + let mut body = Vec::new(); | ||
| 163 | + body.extend_from_slice(format!("--{MULTIPART_BOUNDARY}\r\n").as_bytes()); | ||
| 164 | + body.extend_from_slice( | ||
| 165 | + format!("Content-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\n") | ||
| 166 | + .as_bytes(), | ||
| 167 | + ); | ||
| 168 | + body.extend_from_slice(format!("Content-Type: {content_type}\r\n\r\n").as_bytes()); | ||
| 169 | + body.extend_from_slice(bytes); | ||
| 170 | + body.extend_from_slice(format!("\r\n--{MULTIPART_BOUNDARY}--\r\n").as_bytes()); | ||
| 171 | + body | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +/// Upload `bytes` as a file onto `note` (no assertion). Parses the JSON body | ||
| 175 | +/// like `send`. | ||
| 176 | +pub async fn upload_file( | ||
| 177 | + app: &Router, | ||
| 178 | + cookie: &str, | ||
| 179 | + note: &str, | ||
| 180 | + filename: &str, | ||
| 181 | + content_type: &str, | ||
| 182 | + bytes: &[u8], | ||
| 183 | +) -> Res { | ||
| 184 | + let (status, _, body) = send_raw( | ||
| 185 | + app, | ||
| 186 | + "POST", | ||
| 187 | + &format!("/notes/{note}/files"), | ||
| 188 | + Some(cookie), | ||
| 189 | + Some(&format!( | ||
| 190 | + "multipart/form-data; boundary={MULTIPART_BOUNDARY}" | ||
| 191 | + )), | ||
| 192 | + multipart_file(filename, content_type, bytes), | ||
| 193 | + ) | ||
| 194 | + .await; | ||
| 195 | + let body = if body.is_empty() { | ||
| 196 | + Value::Null | ||
| 197 | + } else { | ||
| 198 | + serde_json::from_slice(&body).unwrap_or(Value::Null) | ||
| 199 | + }; | ||
| 200 | + Res { | ||
| 201 | + status, | ||
| 202 | + body, | ||
| 203 | + cookie: None, | ||
| 204 | + } | ||
| 205 | +} | ||
| 206 | + | ||
| 110 | /// Register (password `secret1`) then log in; returns the session `Cookie` value. | 207 | /// Register (password `secret1`) then log in; returns the session `Cookie` value. |
| 111 | pub async fn login(app: &Router, username: &str) -> String { | 208 | pub async fn login(app: &Router, username: &str) -> String { |
| 112 | let creds = json!({ "username": username, "password": "secret1" }); | 209 | let creds = json!({ "username": username, "password": "secret1" }); |
tests/e2e.rsmodified+3 -0
| @@ -15,6 +15,9 @@ async fn spawn_server() -> (String, Database) { | |||
| 15 | let db = database::init_mem().await.expect("in-memory db"); | 15 | let db = database::init_mem().await.expect("in-memory db"); |
| 16 | let app = build_router(AppState { | 16 | let app = build_router(AppState { |
| 17 | db: db.clone(), | 17 | db: db.clone(), |
| 18 | + // Kept (not auto-deleted) so the directory outlives this helper; | ||
| 19 | + // it's under the OS temp dir, reclaimed like any other temp file. | ||
| 20 | + files_path: tempfile::tempdir().expect("files dir").keep(), | ||
| 18 | cookie_secure: false, | 21 | cookie_secure: false, |
| 19 | // Every request here comes from 127.0.0.1, so per-IP limits would | 22 | // Every request here comes from 127.0.0.1, so per-IP limits would |
| 20 | // meter the whole suite as one client. Off; `rate_limit.rs` covers it. | 23 | // meter the whole suite as one client. Off; `rate_limit.rs` covers it. |
tests/integration.rsmodified+446 -51
| @@ -428,6 +428,372 @@ async fn note_validation_and_missing_ids() { | |||
| 428 | ); | 428 | ); |
| 429 | } | 429 | } |
| 430 | 430 | ||
| 431 | +// --- note files ------------------------------------------------------------ | ||
| 432 | + | ||
| 433 | +/// Create a note as `cookie`; returns its id. | ||
| 434 | +async fn create_note(app: &axum::Router, cookie: &str, title: &str) -> String { | ||
| 435 | + let res = send( | ||
| 436 | + app, | ||
| 437 | + "POST", | ||
| 438 | + "/notes", | ||
| 439 | + Some(cookie), | ||
| 440 | + Some(json!({ "title": title })), | ||
| 441 | + ) | ||
| 442 | + .await; | ||
| 443 | + assert_eq!(res.status, StatusCode::CREATED, "create note {title}"); | ||
| 444 | + id_of(&res.body) | ||
| 445 | +} | ||
| 446 | + | ||
| 447 | +#[tokio::test] | ||
| 448 | +async fn note_files_upload_download_delete_roundtrip() { | ||
| 449 | + let app = mem_app().await; | ||
| 450 | + let ali = login(&app, "ali").await; | ||
| 451 | + let note = create_note(&app, &ali, "with file").await; | ||
| 452 | + | ||
| 453 | + let bytes = b"%PDF-1.4 fake but binary \x00\x01\x02".to_vec(); | ||
| 454 | + let up = common::upload_file(&app, &ali, ¬e, "plan.pdf", "application/pdf", &bytes).await; | ||
| 455 | + assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); | ||
| 456 | + assert_eq!(up.body["name"], "plan.pdf"); | ||
| 457 | + assert_eq!(up.body["content_type"], "application/pdf"); | ||
| 458 | + assert_eq!(up.body["size"], bytes.len() as i64); | ||
| 459 | + let file_id = id_of(&up.body); | ||
| 460 | + | ||
| 461 | + // Listed under the note (paged envelope). | ||
| 462 | + let list = send( | ||
| 463 | + &app, | ||
| 464 | + "GET", | ||
| 465 | + &format!("/notes/{note}/files"), | ||
| 466 | + Some(&ali), | ||
| 467 | + None, | ||
| 468 | + ) | ||
| 469 | + .await; | ||
| 470 | + assert_eq!(list.status, StatusCode::OK); | ||
| 471 | + assert_eq!(common::total(&list.body), 1); | ||
| 472 | + assert_eq!(common::items(&list.body)[0]["name"], "plan.pdf"); | ||
| 473 | + | ||
| 474 | + // Download returns the exact bytes with the declared type and filename. | ||
| 475 | + let (status, headers, body) = common::send_raw( | ||
| 476 | + &app, | ||
| 477 | + "GET", | ||
| 478 | + &format!("/notes/{note}/files/{file_id}"), | ||
| 479 | + Some(&ali), | ||
| 480 | + None, | ||
| 481 | + Vec::new(), | ||
| 482 | + ) | ||
| 483 | + .await; | ||
| 484 | + assert_eq!(status, StatusCode::OK); | ||
| 485 | + assert_eq!(body, bytes); | ||
| 486 | + assert_eq!(headers["content-type"], "application/pdf"); | ||
| 487 | + assert_eq!( | ||
| 488 | + headers["content-disposition"], | ||
| 489 | + "attachment; filename=\"plan.pdf\"; filename*=UTF-8''plan.pdf" | ||
| 490 | + ); | ||
| 491 | + | ||
| 492 | + // Delete; the file is gone from the list, download 404s, blob removed. | ||
| 493 | + assert_eq!( | ||
| 494 | + send( | ||
| 495 | + &app, | ||
| 496 | + "DELETE", | ||
| 497 | + &format!("/notes/{note}/files/{file_id}"), | ||
| 498 | + Some(&ali), | ||
| 499 | + None | ||
| 500 | + ) | ||
| 501 | + .await | ||
| 502 | + .status, | ||
| 503 | + StatusCode::NO_CONTENT | ||
| 504 | + ); | ||
| 505 | + let list = send( | ||
| 506 | + &app, | ||
| 507 | + "GET", | ||
| 508 | + &format!("/notes/{note}/files"), | ||
| 509 | + Some(&ali), | ||
| 510 | + None, | ||
| 511 | + ) | ||
| 512 | + .await; | ||
| 513 | + assert_eq!(common::total(&list.body), 0); | ||
| 514 | + assert_eq!( | ||
| 515 | + send( | ||
| 516 | + &app, | ||
| 517 | + "GET", | ||
| 518 | + &format!("/notes/{note}/files/{file_id}"), | ||
| 519 | + Some(&ali), | ||
| 520 | + None | ||
| 521 | + ) | ||
| 522 | + .await | ||
| 523 | + .status, | ||
| 524 | + StatusCode::NOT_FOUND | ||
| 525 | + ); | ||
| 526 | + assert!( | ||
| 527 | + !common::files_dir().join(&file_id).exists(), | ||
| 528 | + "blob must be unlinked with its row" | ||
| 529 | + ); | ||
| 530 | +} | ||
| 531 | + | ||
| 532 | +#[tokio::test] | ||
| 533 | +async fn note_files_are_scoped_to_the_notes_owner() { | ||
| 534 | + let app = mem_app().await; | ||
| 535 | + let ali = login(&app, "ali").await; | ||
| 536 | + let veli = login(&app, "veli").await; | ||
| 537 | + let note = create_note(&app, &ali, "mine").await; | ||
| 538 | + let up = common::upload_file(&app, &ali, ¬e, "a.txt", "text/plain", b"hi").await; | ||
| 539 | + assert_eq!(up.status, StatusCode::CREATED); | ||
| 540 | + let file_id = id_of(&up.body); | ||
| 541 | + | ||
| 542 | + // Another user can't upload to, list, download from, or delete on the note. | ||
| 543 | + let foreign = common::upload_file(&app, &veli, ¬e, "b.txt", "text/plain", b"x").await; | ||
| 544 | + assert_eq!(foreign.status, StatusCode::NOT_FOUND); | ||
| 545 | + assert_eq!( | ||
| 546 | + send( | ||
| 547 | + &app, | ||
| 548 | + "GET", | ||
| 549 | + &format!("/notes/{note}/files"), | ||
| 550 | + Some(&veli), | ||
| 551 | + None | ||
| 552 | + ) | ||
| 553 | + .await | ||
| 554 | + .status, | ||
| 555 | + StatusCode::NOT_FOUND | ||
| 556 | + ); | ||
| 557 | + for method in ["GET", "DELETE"] { | ||
| 558 | + assert_eq!( | ||
| 559 | + send( | ||
| 560 | + &app, | ||
| 561 | + method, | ||
| 562 | + &format!("/notes/{note}/files/{file_id}"), | ||
| 563 | + Some(&veli), | ||
| 564 | + None | ||
| 565 | + ) | ||
| 566 | + .await | ||
| 567 | + .status, | ||
| 568 | + StatusCode::NOT_FOUND, | ||
| 569 | + "{method}" | ||
| 570 | + ); | ||
| 571 | + } | ||
| 572 | + | ||
| 573 | + // A file id under someone else's note id doesn't resolve either. | ||
| 574 | + let veli_note = create_note(&app, &veli, "veli's").await; | ||
| 575 | + assert_eq!( | ||
| 576 | + send( | ||
| 577 | + &app, | ||
| 578 | + "GET", | ||
| 579 | + &format!("/notes/{veli_note}/files/{file_id}"), | ||
| 580 | + Some(&veli), | ||
| 581 | + None | ||
| 582 | + ) | ||
| 583 | + .await | ||
| 584 | + .status, | ||
| 585 | + StatusCode::NOT_FOUND | ||
| 586 | + ); | ||
| 587 | +} | ||
| 588 | + | ||
| 589 | +#[tokio::test] | ||
| 590 | +async fn note_file_size_follows_the_school_limit() { | ||
| 591 | + let (app, db) = app_and_db().await; | ||
| 592 | + let boss = login_as(&app, &db, "boss", "manager").await; | ||
| 593 | + let ali = login(&app, "ali").await; | ||
| 594 | + let note = create_note(&app, &ali, "sized").await; | ||
| 595 | + | ||
| 596 | + // Lower the school cap to 1 KiB. | ||
| 597 | + let res = send( | ||
| 598 | + &app, | ||
| 599 | + "PATCH", | ||
| 600 | + "/settings", | ||
| 601 | + Some(&boss), | ||
| 602 | + Some(json!({ "max_file_bytes": 1024 })), | ||
| 603 | + ) | ||
| 604 | + .await; | ||
| 605 | + assert_eq!(res.status, StatusCode::OK); | ||
| 606 | + assert_eq!(res.body["max_file_bytes"], 1024); | ||
| 607 | + | ||
| 608 | + // Over the cap dies with 413; at the cap passes. | ||
| 609 | + let big = common::upload_file(&app, &ali, ¬e, "big.bin", "", &vec![7u8; 1025]).await; | ||
| 610 | + assert_eq!(big.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", big.body); | ||
| 611 | + let fits = common::upload_file(&app, &ali, ¬e, "fits.bin", "", &vec![7u8; 1024]).await; | ||
| 612 | + assert_eq!(fits.status, StatusCode::CREATED, "{}", fits.body); | ||
| 613 | + // A blank part content type falls back to octet-stream. | ||
| 614 | + assert_eq!(fits.body["content_type"], "application/octet-stream"); | ||
| 615 | + | ||
| 616 | + // Raising the cap unlocks bigger files at once. | ||
| 617 | + assert_eq!( | ||
| 618 | + send( | ||
| 619 | + &app, | ||
| 620 | + "PATCH", | ||
| 621 | + "/settings", | ||
| 622 | + Some(&boss), | ||
| 623 | + Some(json!({ "max_file_bytes": 10_000 })), | ||
| 624 | + ) | ||
| 625 | + .await | ||
| 626 | + .status, | ||
| 627 | + StatusCode::OK | ||
| 628 | + ); | ||
| 629 | + let now_fits = common::upload_file(&app, &ali, ¬e, "big.bin", "", &vec![7u8; 1025]).await; | ||
| 630 | + assert_eq!(now_fits.status, StatusCode::CREATED); | ||
| 631 | +} | ||
| 632 | + | ||
| 633 | +#[tokio::test] | ||
| 634 | +async fn settings_bound_the_file_limit() { | ||
| 635 | + let (app, db) = app_and_db().await; | ||
| 636 | + let boss = login_as(&app, &db, "boss", "manager").await; | ||
| 637 | + | ||
| 638 | + // The default is visible to any authenticated user. | ||
| 639 | + let res = send(&app, "GET", "/settings", Some(&boss), None).await; | ||
| 640 | + assert_eq!(res.body["max_file_bytes"], 5 * 1024 * 1024); | ||
| 641 | + | ||
| 642 | + // Outside the hard bounds -> 400 (and the stored value is untouched). | ||
| 643 | + for bad in [0, 1023, 25 * 1024 * 1024 + 1] { | ||
| 644 | + let res = send( | ||
| 645 | + &app, | ||
| 646 | + "PATCH", | ||
| 647 | + "/settings", | ||
| 648 | + Some(&boss), | ||
| 649 | + Some(json!({ "max_file_bytes": bad })), | ||
| 650 | + ) | ||
| 651 | + .await; | ||
| 652 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "cap {bad}"); | ||
| 653 | + } | ||
| 654 | + let res = send(&app, "GET", "/settings", Some(&boss), None).await; | ||
| 655 | + assert_eq!(res.body["max_file_bytes"], 5 * 1024 * 1024); | ||
| 656 | + | ||
| 657 | + // Editing another field leaves the cap alone. | ||
| 658 | + let res = send( | ||
| 659 | + &app, | ||
| 660 | + "PATCH", | ||
| 661 | + "/settings", | ||
| 662 | + Some(&boss), | ||
| 663 | + Some(json!({ "max_file_bytes": 2048 })), | ||
| 664 | + ) | ||
| 665 | + .await; | ||
| 666 | + assert_eq!(res.status, StatusCode::OK); | ||
| 667 | + let res = send( | ||
| 668 | + &app, | ||
| 669 | + "PATCH", | ||
| 670 | + "/settings", | ||
| 671 | + Some(&boss), | ||
| 672 | + Some(json!({ "grade_bands": [{ "min": 0, "label": "F" }] })), | ||
| 673 | + ) | ||
| 674 | + .await; | ||
| 675 | + assert_eq!(res.status, StatusCode::OK); | ||
| 676 | + assert_eq!(res.body["max_file_bytes"], 2048); | ||
| 677 | +} | ||
| 678 | + | ||
| 679 | +#[tokio::test] | ||
| 680 | +async fn note_file_count_is_capped() { | ||
| 681 | + let app = mem_app().await; | ||
| 682 | + let ali = login(&app, "ali").await; | ||
| 683 | + let note = create_note(&app, &ali, "full").await; | ||
| 684 | + | ||
| 685 | + for i in 0..10 { | ||
| 686 | + let up = common::upload_file(&app, &ali, ¬e, &format!("f{i}.txt"), "", b"x").await; | ||
| 687 | + assert_eq!(up.status, StatusCode::CREATED, "file {i}"); | ||
| 688 | + } | ||
| 689 | + let over = common::upload_file(&app, &ali, ¬e, "f10.txt", "", b"x").await; | ||
| 690 | + assert_eq!(over.status, StatusCode::CONFLICT); | ||
| 691 | + | ||
| 692 | + // Deleting one frees a slot. | ||
| 693 | + let list = send( | ||
| 694 | + &app, | ||
| 695 | + "GET", | ||
| 696 | + &format!("/notes/{note}/files"), | ||
| 697 | + Some(&ali), | ||
| 698 | + None, | ||
| 699 | + ) | ||
| 700 | + .await; | ||
| 701 | + let victim = id_of(&common::items(&list.body)[0]); | ||
| 702 | + assert_eq!( | ||
| 703 | + send( | ||
| 704 | + &app, | ||
| 705 | + "DELETE", | ||
| 706 | + &format!("/notes/{note}/files/{victim}"), | ||
| 707 | + Some(&ali), | ||
| 708 | + None | ||
| 709 | + ) | ||
| 710 | + .await | ||
| 711 | + .status, | ||
| 712 | + StatusCode::NO_CONTENT | ||
| 713 | + ); | ||
| 714 | + let retry = common::upload_file(&app, &ali, ¬e, "f10.txt", "", b"x").await; | ||
| 715 | + assert_eq!(retry.status, StatusCode::CREATED); | ||
| 716 | +} | ||
| 717 | + | ||
| 718 | +#[tokio::test] | ||
| 719 | +async fn note_file_upload_validation() { | ||
| 720 | + let app = mem_app().await; | ||
| 721 | + let ali = login(&app, "ali").await; | ||
| 722 | + let note = create_note(&app, &ali, "strict").await; | ||
| 723 | + | ||
| 724 | + // Empty file, filename with a path separator, no file field at all: 400. | ||
| 725 | + let empty = common::upload_file(&app, &ali, ¬e, "e.txt", "", b"").await; | ||
| 726 | + assert_eq!(empty.status, StatusCode::BAD_REQUEST, "{}", empty.body); | ||
| 727 | + let traversal = common::upload_file(&app, &ali, ¬e, "../../etc/passwd", "", b"data").await; | ||
| 728 | + assert_eq!(traversal.status, StatusCode::BAD_REQUEST); | ||
| 729 | + | ||
| 730 | + // A body whose only part isn't named "file" has no upload in it. | ||
| 731 | + let stray = common::multipart_file("y.txt", "", b"data"); | ||
| 732 | + let stray = String::from_utf8(stray) | ||
| 733 | + .unwrap() | ||
| 734 | + .replace("name=\"file\"", "name=\"attachment\""); | ||
| 735 | + let (status, _, _) = common::send_raw( | ||
| 736 | + &app, | ||
| 737 | + "POST", | ||
| 738 | + &format!("/notes/{note}/files"), | ||
| 739 | + Some(&ali), | ||
| 740 | + Some("multipart/form-data; boundary=hezarfen-test-boundary"), | ||
| 741 | + stray.into_bytes(), | ||
| 742 | + ) | ||
| 743 | + .await; | ||
| 744 | + assert_eq!(status, StatusCode::BAD_REQUEST); | ||
| 745 | + | ||
| 746 | + // Non-ASCII filenames are fine — stored and encoded on download. | ||
| 747 | + let turkish = | ||
| 748 | + common::upload_file(&app, &ali, ¬e, "ödev 1.pdf", "application/pdf", b"pdf").await; | ||
| 749 | + assert_eq!(turkish.status, StatusCode::CREATED); | ||
| 750 | + let (status, headers, _) = common::send_raw( | ||
| 751 | + &app, | ||
| 752 | + "GET", | ||
| 753 | + &format!("/notes/{note}/files/{}", id_of(&turkish.body)), | ||
| 754 | + Some(&ali), | ||
| 755 | + None, | ||
| 756 | + Vec::new(), | ||
| 757 | + ) | ||
| 758 | + .await; | ||
| 759 | + assert_eq!(status, StatusCode::OK); | ||
| 760 | + assert_eq!( | ||
| 761 | + headers["content-disposition"], | ||
| 762 | + "attachment; filename=\"_dev 1.pdf\"; filename*=UTF-8''%C3%B6dev%201.pdf" | ||
| 763 | + ); | ||
| 764 | +} | ||
| 765 | + | ||
| 766 | +#[tokio::test] | ||
| 767 | +async fn deleting_a_note_removes_its_files() { | ||
| 768 | + let (app, db) = app_and_db().await; | ||
| 769 | + let ali = login(&app, "ali").await; | ||
| 770 | + let note = create_note(&app, &ali, "doomed").await; | ||
| 771 | + let up = common::upload_file(&app, &ali, ¬e, "gone.txt", "", b"bye").await; | ||
| 772 | + assert_eq!(up.status, StatusCode::CREATED); | ||
| 773 | + let file_id = id_of(&up.body); | ||
| 774 | + | ||
| 775 | + assert_eq!( | ||
| 776 | + send(&app, "DELETE", &format!("/notes/{note}"), Some(&ali), None) | ||
| 777 | + .await | ||
| 778 | + .status, | ||
| 779 | + StatusCode::NO_CONTENT | ||
| 780 | + ); | ||
| 781 | + | ||
| 782 | + // Row and blob are both gone. | ||
| 783 | + let mut rows = db | ||
| 784 | + .query("SELECT * FROM note_file") | ||
| 785 | + .await | ||
| 786 | + .unwrap() | ||
| 787 | + .check() | ||
| 788 | + .unwrap(); | ||
| 789 | + let left: Vec<serde_json::Value> = rows.take(0).unwrap(); | ||
| 790 | + assert!(left.is_empty(), "note_file rows must cascade: {left:?}"); | ||
| 791 | + assert!( | ||
| 792 | + !common::files_dir().join(&file_id).exists(), | ||
| 793 | + "blob must be unlinked when its note dies" | ||
| 794 | + ); | ||
| 795 | +} | ||
| 796 | + | ||
| 431 | // --- events + attendance ------------------------------------------------- | 797 | // --- events + attendance ------------------------------------------------- |
| 432 | 798 | ||
| 433 | #[tokio::test] | 799 | #[tokio::test] |
| @@ -582,15 +948,17 @@ async fn attendance_marking_and_upsert() { | |||
| 582 | 948 | ||
| 583 | // Two rows total. | 949 | // Two rows total. |
| 584 | assert_eq!( | 950 | assert_eq!( |
| 585 | - common::items(&send( | 951 | + common::items( |
| 586 | - &app, | 952 | + &send( |
| 587 | - "GET", | 953 | + &app, |
| 588 | - &format!("/events/{event_id}/attendance"), | 954 | + "GET", |
| 589 | - Some(&ali), | 955 | + &format!("/events/{event_id}/attendance"), |
| 590 | - None | 956 | + Some(&ali), |
| 957 | + None | ||
| 958 | + ) | ||
| 959 | + .await | ||
| 960 | + .body | ||
| 591 | ) | 961 | ) |
| 592 | - .await | ||
| 593 | - .body) | ||
| 594 | .len(), | 962 | .len(), |
| 595 | 2 | 963 | 2 |
| 596 | ); | 964 | ); |
| @@ -609,15 +977,17 @@ async fn attendance_marking_and_upsert() { | |||
| 609 | StatusCode::NO_CONTENT | 977 | StatusCode::NO_CONTENT |
| 610 | ); | 978 | ); |
| 611 | assert_eq!( | 979 | assert_eq!( |
| 612 | - common::items(&send( | 980 | + common::items( |
| 613 | - &app, | 981 | + &send( |
| 614 | - "GET", | 982 | + &app, |
| 615 | - &format!("/events/{event_id}/attendance"), | 983 | + "GET", |
| 616 | - Some(&ali), | 984 | + &format!("/events/{event_id}/attendance"), |
| 617 | - None | 985 | + Some(&ali), |
| 986 | + None | ||
| 987 | + ) | ||
| 988 | + .await | ||
| 989 | + .body | ||
| 618 | ) | 990 | ) |
| 619 | - .await | ||
| 620 | - .body) | ||
| 621 | .len(), | 991 | .len(), |
| 622 | 1 | 992 | 1 |
| 623 | ); | 993 | ); |
| @@ -902,15 +1272,17 @@ async fn exams_are_course_scoped_and_course_guarded() { | |||
| 902 | 1 | 1272 | 1 |
| 903 | ); | 1273 | ); |
| 904 | assert_eq!( | 1274 | assert_eq!( |
| 905 | - common::items(&send( | 1275 | + common::items( |
| 906 | - &app, | 1276 | + &send( |
| 907 | - "GET", | 1277 | + &app, |
| 908 | - &format!("/courses/{course_id}/exams"), | 1278 | + "GET", |
| 909 | - Some(&ali), | 1279 | + &format!("/courses/{course_id}/exams"), |
| 910 | - None | 1280 | + Some(&ali), |
| 1281 | + None | ||
| 1282 | + ) | ||
| 1283 | + .await | ||
| 1284 | + .body | ||
| 911 | ) | 1285 | ) |
| 912 | - .await | ||
| 913 | - .body) | ||
| 914 | .len(), | 1286 | .len(), |
| 915 | 1 | 1287 | 1 |
| 916 | ); | 1288 | ); |
| @@ -1086,15 +1458,17 @@ async fn grading_upsert_and_own_result() { | |||
| 1086 | 1458 | ||
| 1087 | // Teacher sees the full list (one row). | 1459 | // Teacher sees the full list (one row). |
| 1088 | assert_eq!( | 1460 | assert_eq!( |
| 1089 | - common::items(&send( | 1461 | + common::items( |
| 1090 | - &app, | 1462 | + &send( |
| 1091 | - "GET", | 1463 | + &app, |
| 1092 | - &format!("/exams/{exam_id}/results"), | 1464 | + "GET", |
| 1093 | - Some(&teacher), | 1465 | + &format!("/exams/{exam_id}/results"), |
| 1094 | - None | 1466 | + Some(&teacher), |
| 1467 | + None | ||
| 1468 | + ) | ||
| 1469 | + .await | ||
| 1470 | + .body | ||
| 1095 | ) | 1471 | ) |
| 1096 | - .await | ||
| 1097 | - .body) | ||
| 1098 | .len(), | 1472 | .len(), |
| 1099 | 1 | 1473 | 1 |
| 1100 | ); | 1474 | ); |
| @@ -1693,15 +2067,17 @@ async fn exam_creation_lives_under_courses() { | |||
| 1693 | StatusCode::OK | 2067 | StatusCode::OK |
| 1694 | ); | 2068 | ); |
| 1695 | assert_eq!( | 2069 | assert_eq!( |
| 1696 | - common::items(&send( | 2070 | + common::items( |
| 1697 | - &app, | 2071 | + &send( |
| 1698 | - "GET", | 2072 | + &app, |
| 1699 | - &format!("/courses/{course_id}/exams"), | 2073 | + "GET", |
| 1700 | - Some(&alice), | 2074 | + &format!("/courses/{course_id}/exams"), |
| 1701 | - None | 2075 | + Some(&alice), |
| 2076 | + None | ||
| 2077 | + ) | ||
| 2078 | + .await | ||
| 2079 | + .body | ||
| 1702 | ) | 2080 | ) |
| 1703 | - .await | ||
| 1704 | - .body) | ||
| 1705 | .len(), | 2081 | .len(), |
| 1706 | 1 | 2082 | 1 |
| 1707 | ); | 2083 | ); |
| @@ -1769,7 +2145,12 @@ async fn grading_requires_enrollment() { | |||
| 1769 | StatusCode::BAD_REQUEST | 2145 | StatusCode::BAD_REQUEST |
| 1770 | ); | 2146 | ); |
| 1771 | assert_eq!( | 2147 | assert_eq!( |
| 1772 | - common::items(&send(&app, "GET", &grade_uri, Some(&teacher), None).await.body).len(), | 2148 | + common::items( |
| 2149 | + &send(&app, "GET", &grade_uri, Some(&teacher), None) | ||
| 2150 | + .await | ||
| 2151 | + .body | ||
| 2152 | + ) | ||
| 2153 | + .len(), | ||
| 1773 | 1 | 2154 | 1 |
| 1774 | ); | 2155 | ); |
| 1775 | assert_eq!( | 2156 | assert_eq!( |
| @@ -3027,15 +3408,17 @@ async fn graders_cannot_grade_themselves() { | |||
| 3027 | 3408 | ||
| 3028 | // And the rejected attempts wrote nothing. | 3409 | // And the rejected attempts wrote nothing. |
| 3029 | assert_eq!( | 3410 | assert_eq!( |
| 3030 | - common::items(&send( | 3411 | + common::items( |
| 3031 | - &app, | 3412 | + &send( |
| 3032 | - "GET", | 3413 | + &app, |
| 3033 | - &format!("/exams/{exam_id}/results"), | 3414 | + "GET", |
| 3034 | - Some(&teacher), | 3415 | + &format!("/exams/{exam_id}/results"), |
| 3035 | - None | 3416 | + Some(&teacher), |
| 3417 | + None | ||
| 3418 | + ) | ||
| 3419 | + .await | ||
| 3420 | + .body | ||
| 3036 | ) | 3421 | ) |
| 3037 | - .await | ||
| 3038 | - .body) | ||
| 3039 | .len(), | 3422 | .len(), |
| 3040 | 0 | 3423 | 0 |
| 3041 | ); | 3424 | ); |
| @@ -3122,7 +3505,12 @@ async fn promotion_out_of_student_freezes_the_seat() { | |||
| 3122 | None, | 3505 | None, |
| 3123 | ) | 3506 | ) |
| 3124 | .await; | 3507 | .await; |
| 3125 | - assert_eq!(res.status, StatusCode::CREATED, "student sits: {}", res.body); | 3508 | + assert_eq!( |
| 3509 | + res.status, | ||
| 3510 | + StatusCode::CREATED, | ||
| 3511 | + "student sits: {}", | ||
| 3512 | + res.body | ||
| 3513 | + ); | ||
| 3126 | 3514 | ||
| 3127 | // Promote the enrolled student to teacher; the enrollment row survives. | 3515 | // Promote the enrolled student to teacher; the enrollment row survives. |
| 3128 | set_role(&db, "veli", "teacher").await; | 3516 | set_role(&db, "veli", "teacher").await; |
| @@ -3336,6 +3724,7 @@ async fn session_cookie_secure_attribute_follows_config() { | |||
| 3336 | let db = database::init_mem().await.unwrap(); | 3724 | let db = database::init_mem().await.unwrap(); |
| 3337 | let app = build_router(AppState { | 3725 | let app = build_router(AppState { |
| 3338 | db, | 3726 | db, |
| 3727 | + files_path: common::files_dir(), | ||
| 3339 | cookie_secure: true, | 3728 | cookie_secure: true, |
| 3340 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), | 3729 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| 3341 | exam_presence: Default::default(), | 3730 | exam_presence: Default::default(), |
| @@ -6129,7 +6518,13 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { | |||
| 6129 | None, | 6518 | None, |
| 6130 | ) | 6519 | ) |
| 6131 | .await; | 6520 | .await; |
| 6132 | - assert_eq!(common::items(&res.body)[0]["choices"].as_array().unwrap().len(), 2); | 6521 | + assert_eq!( |
| 6522 | + common::items(&res.body)[0]["choices"] | ||
| 6523 | + .as_array() | ||
| 6524 | + .unwrap() | ||
| 6525 | + .len(), | ||
| 6526 | + 2 | ||
| 6527 | + ); | ||
| 6133 | assert_eq!(common::items(&res.body)[0]["correct"], 1); | 6528 | assert_eq!(common::items(&res.body)[0]["correct"], 1); |
| 6134 | } | 6529 | } |
| 6135 | 6530 | ||
tests/pagination.rsmodified+26 -4
| @@ -60,7 +60,14 @@ async fn envelope_windows_and_total_is_stable() { | |||
| 60 | assert_eq!(total(&res.body), 25); | 60 | assert_eq!(total(&res.body), 25); |
| 61 | 61 | ||
| 62 | // Past the end — an empty page, not an error, and `total` stays honest. | 62 | // Past the end — an empty page, not an error, and `total` stays honest. |
| 63 | - let res = send(&app, "GET", "/users?limit=10&offset=999", Some(&admin), None).await; | 63 | + let res = send( |
| 64 | + &app, | ||
| 65 | + "GET", | ||
| 66 | + "/users?limit=10&offset=999", | ||
| 67 | + Some(&admin), | ||
| 68 | + None, | ||
| 69 | + ) | ||
| 70 | + .await; | ||
| 64 | assert_eq!(res.status, StatusCode::OK); | 71 | assert_eq!(res.status, StatusCode::OK); |
| 65 | assert!(items(&res.body).is_empty(), "offset past the end is empty"); | 72 | assert!(items(&res.body).is_empty(), "offset past the end is empty"); |
| 66 | assert_eq!(total(&res.body), 25); | 73 | assert_eq!(total(&res.body), 25); |
| @@ -140,7 +147,11 @@ async fn user_search_is_paged_not_capped() { | |||
| 140 | // Unpaged: every match comes back — no 10-row ceiling. | 147 | // Unpaged: every match comes back — no 10-row ceiling. |
| 141 | let res = send(&app, "GET", "/users/search?q=grp", Some(&teacher), None).await; | 148 | let res = send(&app, "GET", "/users/search?q=grp", Some(&teacher), None).await; |
| 142 | assert_eq!(res.status, StatusCode::OK); | 149 | assert_eq!(res.status, StatusCode::OK); |
| 143 | - assert_eq!(total(&res.body), 12, "all matches counted, not capped at 10"); | 150 | + assert_eq!( |
| 151 | + total(&res.body), | ||
| 152 | + 12, | ||
| 153 | + "all matches counted, not capped at 10" | ||
| 154 | + ); | ||
| 144 | assert_eq!(items(&res.body).len(), 12); | 155 | assert_eq!(items(&res.body).len(), 12); |
| 145 | 156 | ||
| 146 | // Windowed like any other list — the tail is the remainder. | 157 | // Windowed like any other list — the tail is the remainder. |
| @@ -156,8 +167,19 @@ async fn user_search_is_paged_not_capped() { | |||
| 156 | assert_eq!(items(&res.body).len(), 2, "offset 10 of 12 leaves 2"); | 167 | assert_eq!(items(&res.body).len(), 2, "offset 10 of 12 leaves 2"); |
| 157 | 168 | ||
| 158 | // Paging bounds are enforced, and a blank query is still refused. | 169 | // Paging bounds are enforced, and a blank query is still refused. |
| 159 | - let res = send(&app, "GET", "/users/search?q=grp&limit=0", Some(&teacher), None).await; | 170 | + let res = send( |
| 171 | + &app, | ||
| 172 | + "GET", | ||
| 173 | + "/users/search?q=grp&limit=0", | ||
| 174 | + Some(&teacher), | ||
| 175 | + None, | ||
| 176 | + ) | ||
| 177 | + .await; | ||
| 160 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "limit=0 is a 400"); | 178 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "limit=0 is a 400"); |
| 161 | let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await; | 179 | let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await; |
| 162 | - assert_eq!(res.status, StatusCode::BAD_REQUEST, "blank q is still a 400"); | 180 | + assert_eq!( |
| 181 | + res.status, | ||
| 182 | + StatusCode::BAD_REQUEST, | ||
| 183 | + "blank q is still a 400" | ||
| 184 | + ); | ||
| 163 | } | 185 | } |
tests/persistence.rsmodified+74 -19
| @@ -36,6 +36,7 @@ fn config_at(dir: &TempDir) -> Config { | |||
| 36 | db_path: dir.path().join("hezarfen.db").to_str().unwrap().to_string(), | 36 | db_path: dir.path().join("hezarfen.db").to_str().unwrap().to_string(), |
| 37 | db_ns: "hezarfen".into(), | 37 | db_ns: "hezarfen".into(), |
| 38 | db_name: "hezarfen".into(), | 38 | db_name: "hezarfen".into(), |
| 39 | + files_path: dir.path().join("files").to_str().unwrap().to_string(), | ||
| 39 | cookie_secure: false, | 40 | cookie_secure: false, |
| 40 | rate_limit: RateLimitConfig::unlimited(), | 41 | rate_limit: RateLimitConfig::unlimited(), |
| 41 | admin_username: None, | 42 | admin_username: None, |
| @@ -43,9 +44,12 @@ fn config_at(dir: &TempDir) -> Config { | |||
| 43 | } | 44 | } |
| 44 | } | 45 | } |
| 45 | 46 | ||
| 46 | -fn state(db: Database) -> AppState { | 47 | +/// Mirror `main`: the blob directory is created at boot, beside the database. |
| 48 | +fn state(db: Database, cfg: &Config) -> AppState { | ||
| 49 | + std::fs::create_dir_all(&cfg.files_path).expect("files dir"); | ||
| 47 | AppState { | 50 | AppState { |
| 48 | db, | 51 | db, |
| 52 | + files_path: cfg.files_path.clone().into(), | ||
| 49 | cookie_secure: false, | 53 | cookie_secure: false, |
| 50 | rate_limit: RateLimitConfig::unlimited(), | 54 | rate_limit: RateLimitConfig::unlimited(), |
| 51 | exam_presence: Default::default(), | 55 | exam_presence: Default::default(), |
| @@ -56,10 +60,9 @@ fn state(db: Database) -> AppState { | |||
| 56 | #[tokio::test] | 60 | #[tokio::test] |
| 57 | async fn file_engine_runs_full_flow() { | 61 | async fn file_engine_runs_full_flow() { |
| 58 | let dir = tempfile::tempdir().unwrap(); | 62 | let dir = tempfile::tempdir().unwrap(); |
| 59 | - let db = database::init(&config_at(&dir)) | 63 | + let cfg = config_at(&dir); |
| 60 | - .await | 64 | + let db = database::init(&cfg).await.expect("open file db"); |
| 61 | - .expect("open file db"); | 65 | + let app = build_router(state(db, &cfg)); |
| 62 | - let app = build_router(state(db)); | ||
| 63 | 66 | ||
| 64 | let creds = json!({ "username": "ali", "password": "secret1" }); | 67 | let creds = json!({ "username": "ali", "password": "secret1" }); |
| 65 | assert_eq!( | 68 | assert_eq!( |
| @@ -83,12 +86,7 @@ async fn file_engine_runs_full_flow() { | |||
| 83 | .await; | 86 | .await; |
| 84 | assert_eq!(note.status, StatusCode::CREATED); | 87 | assert_eq!(note.status, StatusCode::CREATED); |
| 85 | assert_eq!( | 88 | assert_eq!( |
| 86 | - common::items( | 89 | + common::items(&send(&app, "GET", "/notes", Some(&cookie), None).await.body,).len(), |
| 87 | - &send(&app, "GET", "/notes", Some(&cookie), None) | ||
| 88 | - .await | ||
| 89 | - .body, | ||
| 90 | - ) | ||
| 91 | - .len(), | ||
| 92 | 1 | 90 | 1 |
| 93 | ); | 91 | ); |
| 94 | } | 92 | } |
| @@ -104,7 +102,7 @@ async fn data_survives_reopen() { | |||
| 104 | // First boot: create a user and a note, then drop the handle. | 102 | // First boot: create a user and a note, then drop the handle. |
| 105 | { | 103 | { |
| 106 | let db = database::init(&cfg).await.expect("first open"); | 104 | let db = database::init(&cfg).await.expect("first open"); |
| 107 | - let app = build_router(state(db)); | 105 | + let app = build_router(state(db, &cfg)); |
| 108 | assert_eq!( | 106 | assert_eq!( |
| 109 | send(&app, "POST", "/auth/register", None, Some(creds.clone())) | 107 | send(&app, "POST", "/auth/register", None, Some(creds.clone())) |
| 110 | .await | 108 | .await |
| @@ -132,7 +130,7 @@ async fn data_survives_reopen() { | |||
| 132 | // Second boot from the same path: the user and note are still there. | 130 | // Second boot from the same path: the user and note are still there. |
| 133 | { | 131 | { |
| 134 | let db = reopen(&cfg).await; | 132 | let db = reopen(&cfg).await; |
| 135 | - let app = build_router(state(db)); | 133 | + let app = build_router(state(db, &cfg)); |
| 136 | let login = send(&app, "POST", "/auth/login", None, Some(creds)).await; | 134 | let login = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 137 | assert_eq!(login.status, StatusCode::OK, "user survived reopen"); | 135 | assert_eq!(login.status, StatusCode::OK, "user survived reopen"); |
| 138 | let cookie = login.cookie.unwrap(); | 136 | let cookie = login.cookie.unwrap(); |
| @@ -149,6 +147,63 @@ async fn data_survives_reopen() { | |||
| 149 | } | 147 | } |
| 150 | } | 148 | } |
| 151 | 149 | ||
| 150 | +/// A note's uploaded file — its metadata row in the database and its blob on | ||
| 151 | +/// disk — comes back after a close + reopen, byte for byte. | ||
| 152 | +#[tokio::test] | ||
| 153 | +async fn note_files_survive_reopen() { | ||
| 154 | + let dir = tempfile::tempdir().unwrap(); | ||
| 155 | + let cfg = config_at(&dir); | ||
| 156 | + let creds = json!({ "username": "ali", "password": "secret1" }); | ||
| 157 | + let bytes = b"%PDF-1.4 persisted".to_vec(); | ||
| 158 | + let file_uri; | ||
| 159 | + | ||
| 160 | + // First boot: create a note and upload a file onto it. | ||
| 161 | + { | ||
| 162 | + let db = database::init(&cfg).await.expect("first open"); | ||
| 163 | + let app = build_router(state(db, &cfg)); | ||
| 164 | + send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; | ||
| 165 | + let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) | ||
| 166 | + .await | ||
| 167 | + .cookie | ||
| 168 | + .unwrap(); | ||
| 169 | + let note = send( | ||
| 170 | + &app, | ||
| 171 | + "POST", | ||
| 172 | + "/notes", | ||
| 173 | + Some(&cookie), | ||
| 174 | + Some(json!({ "title": "with attachment" })), | ||
| 175 | + ) | ||
| 176 | + .await; | ||
| 177 | + let note_id = note.body["id"].as_str().unwrap().to_string(); | ||
| 178 | + let up = common::upload_file( | ||
| 179 | + &app, | ||
| 180 | + &cookie, | ||
| 181 | + ¬e_id, | ||
| 182 | + "plan.pdf", | ||
| 183 | + "application/pdf", | ||
| 184 | + &bytes, | ||
| 185 | + ) | ||
| 186 | + .await; | ||
| 187 | + assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); | ||
| 188 | + file_uri = format!("/notes/{note_id}/files/{}", up.body["id"].as_str().unwrap()); | ||
| 189 | + } | ||
| 190 | + | ||
| 191 | + // Second boot: metadata and bytes are both still there. | ||
| 192 | + { | ||
| 193 | + let db = reopen(&cfg).await; | ||
| 194 | + let app = build_router(state(db, &cfg)); | ||
| 195 | + let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | ||
| 196 | + .await | ||
| 197 | + .cookie | ||
| 198 | + .unwrap(); | ||
| 199 | + let (status, headers, body) = | ||
| 200 | + common::send_raw(&app, "GET", &file_uri, Some(&cookie), None, Vec::new()).await; | ||
| 201 | + assert_eq!(status, StatusCode::OK); | ||
| 202 | + assert_eq!(body, bytes, "blob bytes survived reopen"); | ||
| 203 | + assert_eq!(headers["content-type"], "application/pdf"); | ||
| 204 | + } | ||
| 205 | +} | ||
| 206 | + | ||
| 152 | /// Personal info written through `PATCH /users/me` is still on the account | 207 | /// Personal info written through `PATCH /users/me` is still on the account |
| 153 | /// after a close + reopen. | 208 | /// after a close + reopen. |
| 154 | #[tokio::test] | 209 | #[tokio::test] |
| @@ -160,7 +215,7 @@ async fn profile_survives_reopen() { | |||
| 160 | // First boot: register and fill in the profile. | 215 | // First boot: register and fill in the profile. |
| 161 | { | 216 | { |
| 162 | let db = database::init(&cfg).await.expect("first open"); | 217 | let db = database::init(&cfg).await.expect("first open"); |
| 163 | - let app = build_router(state(db)); | 218 | + let app = build_router(state(db, &cfg)); |
| 164 | assert_eq!( | 219 | assert_eq!( |
| 165 | send(&app, "POST", "/auth/register", None, Some(creds.clone())) | 220 | send(&app, "POST", "/auth/register", None, Some(creds.clone())) |
| 166 | .await | 221 | .await |
| @@ -191,7 +246,7 @@ async fn profile_survives_reopen() { | |||
| 191 | // Second boot: the info comes back from disk. | 246 | // Second boot: the info comes back from disk. |
| 192 | { | 247 | { |
| 193 | let db = reopen(&cfg).await; | 248 | let db = reopen(&cfg).await; |
| 194 | - let app = build_router(state(db)); | 249 | + let app = build_router(state(db, &cfg)); |
| 195 | let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | 250 | let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) |
| 196 | .await | 251 | .await |
| 197 | .cookie | 252 | .cookie |
| @@ -220,7 +275,7 @@ async fn course_marks_survive_reopen() { | |||
| 220 | // course, enrolls the student, grades 80. | 275 | // course, enrolls the student, grades 80. |
| 221 | { | 276 | { |
| 222 | let db = database::init(&cfg).await.expect("first open"); | 277 | let db = database::init(&cfg).await.expect("first open"); |
| 223 | - let app = build_router(state(db.clone())); | 278 | + let app = build_router(state(db.clone(), &cfg)); |
| 224 | for creds in [&teacher_creds, &student_creds] { | 279 | for creds in [&teacher_creds, &student_creds] { |
| 225 | assert_eq!( | 280 | assert_eq!( |
| 226 | send(&app, "POST", "/auth/register", None, Some((*creds).clone())) | 281 | send(&app, "POST", "/auth/register", None, Some((*creds).clone())) |
| @@ -288,7 +343,7 @@ async fn course_marks_survive_reopen() { | |||
| 288 | // are all rebuilt from disk. | 343 | // are all rebuilt from disk. |
| 289 | { | 344 | { |
| 290 | let db = reopen(&cfg).await; | 345 | let db = reopen(&cfg).await; |
| 291 | - let app = build_router(state(db)); | 346 | + let app = build_router(state(db, &cfg)); |
| 292 | let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) | 347 | let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) |
| 293 | .await | 348 | .await |
| 294 | .cookie | 349 | .cookie |
| @@ -330,7 +385,7 @@ async fn settings_and_terms_survive_reopen() { | |||
| 330 | let term; | 385 | let term; |
| 331 | { | 386 | { |
| 332 | let db = database::init(&cfg).await.expect("open file db"); | 387 | let db = database::init(&cfg).await.expect("open file db"); |
| 333 | - let app = build_router(state(db.clone())); | 388 | + let app = build_router(state(db.clone(), &cfg)); |
| 334 | 389 | ||
| 335 | let creds = json!({ "username": "boss", "password": "secret1" }); | 390 | let creds = json!({ "username": "boss", "password": "secret1" }); |
| 336 | send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; | 391 | send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; |
| @@ -380,7 +435,7 @@ async fn settings_and_terms_survive_reopen() { | |||
| 380 | 435 | ||
| 381 | // New handle at the same path — a fresh boot, migration re-applied. | 436 | // New handle at the same path — a fresh boot, migration re-applied. |
| 382 | let db = reopen(&cfg).await; | 437 | let db = reopen(&cfg).await; |
| 383 | - let app = build_router(state(db)); | 438 | + let app = build_router(state(db, &cfg)); |
| 384 | let creds = json!({ "username": "boss", "password": "secret1" }); | 439 | let creds = json!({ "username": "boss", "password": "secret1" }); |
| 385 | let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | 440 | let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) |
| 386 | .await | 441 | .await |
tests/rate_limit.rsmodified+2 -0
| @@ -21,6 +21,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router { | |||
| 21 | let db = database::init_mem().await.expect("in-memory db"); | 21 | let db = database::init_mem().await.expect("in-memory db"); |
| 22 | build_router(AppState { | 22 | build_router(AppState { |
| 23 | db, | 23 | db, |
| 24 | + files_path: tempfile::tempdir().expect("files dir").keep(), | ||
| 24 | cookie_secure: false, | 25 | cookie_secure: false, |
| 25 | rate_limit, | 26 | rate_limit, |
| 26 | exam_presence: Default::default(), | 27 | exam_presence: Default::default(), |
| @@ -311,6 +312,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String { | |||
| 311 | let db = database::init_mem().await.expect("in-memory db"); | 312 | let db = database::init_mem().await.expect("in-memory db"); |
| 312 | let app = build_router(AppState { | 313 | let app = build_router(AppState { |
| 313 | db, | 314 | db, |
| 315 | + files_path: tempfile::tempdir().expect("files dir").keep(), | ||
| 314 | cookie_secure: false, | 316 | cookie_secure: false, |
| 315 | rate_limit, | 317 | rate_limit, |
| 316 | exam_presence: Default::default(), | 318 | exam_presence: Default::default(), |