From f1b532bba631a123ff3efd12b8a933ab122c0177 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 16 Jul 2026 00:18:00 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(notes):=20file=20attachments?= =?UTF-8?q?=20with=20school-set=20size=20cap?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Blobs live on disk under FILES_PATH (same volume as the DB), named by the row's ULID so user input never shapes a path; the note_file row keeps only metadata. DB-blob storage rejected: multi-MB PDFs bloat surrealkv's LSM tree and buffer whole in RAM on every read. - POST/GET /notes/{id}/files, GET/DELETE /notes/{id}/files/{file_id}; owner-only through the owning note, staff included - max_file_bytes in settings (1 KiB-25 MiB hard cap, default 5 MiB), enforced on streamed bytes (413), inside the settings CAS guard; option so pre-field volumes boot without a backfill - 10 files per note; deleting a note removes rows first, blobs after, so a crash strands at worst an unreachable blob --- .env.example | 4 + Cargo.lock | 27 +++ Cargo.toml | 5 +- README.md | 52 +++-- compose.yaml | 1 + src/config.rs | 4 + src/constant.rs | 20 ++ src/database.rs | 9 + src/domain/mod.rs | 1 + src/domain/note.rs | 8 + src/domain/note_file.rs | 255 +++++++++++++++++++++ src/domain/settings.rs | 142 ++++++++++-- src/error.rs | 5 + src/lib.rs | 6 +- src/main.rs | 4 + src/state.rs | 5 + src/web/exam_ws.rs | 1 + src/web/notes.rs | 374 +++++++++++++++++++++++++++++- src/web/settings.rs | 19 +- tests/common/mod.rs | 99 +++++++- tests/e2e.rs | 3 + tests/integration.rs | 497 +++++++++++++++++++++++++++++++++++----- tests/pagination.rs | 30 ++- tests/persistence.rs | 93 ++++++-- tests/rate_limit.rs | 2 + 25 files changed, 1546 insertions(+), 120 deletions(-) create mode 100644 src/domain/note_file.rs diff --git a/.env.example b/.env.example index 268236f..9662ad1 100644 --- a/.env.example +++ b/.env.example @@ -7,6 +7,10 @@ DB_PATH=./data/hezarfen.db DB_NAMESPACE=hezarfen DB_DATABASE=hezarfen +# Directory for uploaded note-file blobs (created at startup). Keep it beside +# the database so one volume persists both. +FILES_PATH=./data/files + # Optional log filter. RUST_LOG=info,hezarfen_backend=debug diff --git a/Cargo.lock b/Cargo.lock index f3f1404..a844508 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -279,6 +279,7 @@ dependencies = [ "matchit", "memchr", "mime", + "multer", "percent-encoding", "pin-project-lite", "serde_core", @@ -1141,6 +1142,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -2352,6 +2362,23 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + [[package]] name = "ndarray" version = "0.17.2" diff --git a/Cargo.toml b/Cargo.toml index 5ad6ce1..b94e76e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,8 +13,9 @@ disallowed_types = "deny" tokio = { version = "1", features = ["full"] } # IntervalStream for the live exam-monitor SSE tick. tokio-stream = "0.1" -# "ws" backs the live exam room (WebSocket at /exams/{id}/attempt/ws). -axum = { version = "0.8", features = ["ws"] } +# "ws" backs the live exam room (WebSocket at /exams/{id}/attempt/ws); +# "multipart" backs note file uploads (POST /notes/{id}/files). +axum = { version = "0.8", features = ["ws", "multipart"] } axum-extra = { version = "0.10", features = ["cookie"] } tower-http = { version = "0.6", features = ["trace", "cors"] } surrealdb = { version = "3", default-features = false, features = ["kv-surrealkv", "kv-mem"] } diff --git a/README.md b/README.md index 98d0ee1..b7a9804 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,10 @@ Note, attendance, course + weighted exam mark backend. **Rust (edition 2024) · axum · SurrealDB 3 (embedded surrealkv) · tokio.** Session-cookie auth with four hierarchical roles (`student < teacher < manager -< admin`). Notes are per-user. Attendance is event + attendees: create an event, +< admin`). Notes are per-user and carry **file attachments** (PDFs, documents, +…): blobs live on disk next to the database, metadata in the database, and the +per-file size cap is school policy in settings (`max_file_bytes`, default +5 MiB). Attendance is event + attendees: create an event, then mark users present / absent / late / excused. Marks are course-shaped (Google Classroom style): a teacher creates a course, enrolls students, adds 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), staff clock in/out on a server-stamped **work log**, and every user has an **attendance report** (event + per-course lesson tallies with rates). School-varying policy is data, not code: exam kinds (each with its weight in -course averages), attendance statuses, and grade-display bands live in an -editable **settings** singleton, and academic **terms** are plain rows courses -can link to (see "Per-school policy"). +course averages), attendance statuses, grade-display bands, and the note-file +size limit live in an editable **settings** singleton, and academic **terms** +are plain rows courses can link to (see "Per-school policy"). Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …) constructed only after its restrictions pass — invalid input can't be @@ -40,8 +43,10 @@ cargo run ``` Boots on `http://127.0.0.1:8080`, storing data in `./data/hezarfen.db` -(embedded surrealkv — no external DB server). Interactive API docs (Swagger UI) -are served at `/swagger`, the raw OpenAPI spec at `/api-docs/openapi.json`. +(embedded surrealkv — no external DB server) and uploaded note files in +`./data/files/` (`FILES_PATH`, created at startup). Interactive API docs +(Swagger UI) are served at `/swagger`, the raw OpenAPI spec at +`/api-docs/openapi.json`. ## Run in a container (podman) @@ -54,7 +59,8 @@ podman compose down # stop (data survives in the volume) The `Containerfile` is a two-stage build (Rust builder with cargo cache mounts, `debian:trixie-slim` runtime, non-root user). Since the database is embedded there is only one service; its data lives in the named volume -`hezarfen-data`, mounted at `/data`. `HOST` is forced to `0.0.0.0` inside the +`hezarfen-data`, mounted at `/data` — the database and the uploaded note +files (`/data/files`) together, so that one volume persists everything. `HOST` is forced to `0.0.0.0` inside the container so the published port works. Production knobs (`COOKIE_SECURE`, `CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in `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). | Action | Minimum role | Notes | |------------------------------------------|--------------|-----------------------------------------------| | Register / login / view own account | (any) | Registration always creates a `student` | -| View events, own notes; CRUD notes | student | Everyone can read events and keep notes | +| 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 | | Mark **own** attendance | student | Anyone can mark themselves | | Mark **another user's** attendance | teacher | | | Create events; remove attendance rows | teacher | | @@ -182,7 +188,7 @@ effect on the user's very next call (no re-login). | Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself | | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | -| Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands) and the academic calendar are management's call | +| 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 | | 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 | ### Bootstrapping the first admin @@ -263,7 +269,11 @@ their existing shapes: the student exam-room reads | GET | `/notes` | student | List own notes · paged | | GET | `/notes/{id}` | student | Get own note | | PATCH | `/notes/{id}` | student | `{title?, content?}` | -| DELETE | `/notes/{id}` | student | Delete own note | +| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) | +| 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 | +| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) · paged | +| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) | +| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file | | POST | `/events` | teacher | `{title, description?, starts_at?, ends_at?}` | | GET | `/events` | student | List all events · paged | | GET | `/events/{id}` | student | Get event | @@ -323,8 +333,8 @@ their existing shapes: the student exam-room reads | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) | -| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands` | -| PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale; concurrent edits merge, never silently revert each other (see "Per-school policy") | +| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes` | +| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other (see "Per-school policy") | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | | GET | `/terms` | student | List terms, newest first · paged | | GET | `/terms/{id}` | student | Get one term | @@ -381,7 +391,7 @@ unlike emails). Every school runs differently; the parts that vary are data, not code. One editable `settings` singleton (`GET /settings` for any signed-in user, -`PATCH /settings` for manager+) carries three knobs: +`PATCH /settings` for manager+) carries four knobs: - **`exam_kinds`** — the accepted `kind` values for new exams, each an 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, averaging stay `0`–`100` forever — bands only add `grade`, `average_grade`, and `overall_grade` labels to the mark report, so a school can switch display scales without touching a single stored mark. +- **`max_file_bytes`** — the per-file size cap for note uploads, in bytes: + `1024` (1 KiB) to `26214400` (25 MiB; a server hard cap — uploads buffer in + memory), default `5242880` (5 MiB). Checked at upload time only: + lowering it never touches already-stored files. A `PATCH` replaces only the fields it carries, each wholesale, and validation 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' \ -d '{"title":"first","content":"hello"}' curl -s -b $JAR $BASE/notes +# note files (multipart; -F sets filename + content type from the file) +NO=$(curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \ + -d '{"title":"with file"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) +FI=$(curl -s -b $JAR $BASE/notes/$NO/files -F 'file=@plan.pdf' \ + | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) +curl -s -b $JAR $BASE/notes/$NO/files # list metadata +curl -s -b $JAR -OJ $BASE/notes/$NO/files/$FI # download, original filename + # events + attendance # Creating events needs teacher+; grant it first (see "Bootstrapping" above — # e.g. UPDATE user SET role='teacher' WHERE username='ali'), else this is 403. @@ -758,7 +780,7 @@ src/ error.rs ValidationError + AppError -> HTTP responses database.rs embedded surrealkv connect + SCHEMAFULL migration rate_limit.rs fixed-window per-IP limiter (both tiers) + middleware - state.rs AppState { db, cookie_secure, rate_limit } + state.rs AppState { db, files_path, cookie_secure, rate_limit } domain/ validated newtypes + entities (derive SurrealValue), each owning its persistence user.rs UserId · Username · Password · PasswordHash · User (has role) @@ -766,6 +788,8 @@ src/ session.rs SessionId · SessionToken · Session (7-day expiry) timestamp.rs Timestamp (unix-millisecond instant) note.rs NoteId · NoteTitle · NoteContent · Note + note_file.rs NoteFileId · FileName · FileContentType · NoteFile (metadata row; + blob on disk under FILES_PATH, named by the row's ULID) event.rs EventId · EventTitle · EventDescription · Event attendance.rs AttendanceId · AttendanceStatus · Attendance course.rs CourseId · CourseTitle · CourseDescription · Course diff --git a/compose.yaml b/compose.yaml index d88118f..24ee654 100644 --- a/compose.yaml +++ b/compose.yaml @@ -13,6 +13,7 @@ services: DB_PATH: /data/hezarfen.db DB_NAMESPACE: hezarfen DB_DATABASE: hezarfen + FILES_PATH: /data/files RUST_LOG: info,hezarfen_backend=debug # First-boot admin seed: created once if the username doesn't exist yet. # Local-dev credentials — change or remove before exposing this anywhere. diff --git a/src/config.rs b/src/config.rs index 8d9c8e2..3a57661 100644 --- a/src/config.rs +++ b/src/config.rs @@ -15,6 +15,9 @@ pub struct Config { pub db_path: String, pub db_ns: String, pub db_name: String, + /// Directory for uploaded note-file blobs (`FILES_PATH`). Kept beside the + /// database inside the same volume so one mount persists everything. + pub files_path: String, /// Add the `Secure` attribute to the session cookie (HTTPS-only). Off by /// default so plain-HTTP local dev keeps working; enable behind TLS. pub cookie_secure: bool, @@ -36,6 +39,7 @@ impl Config { db_path: env::var("DB_PATH").unwrap_or_else(|_| "./data/hezarfen.db".into()), db_ns: env::var("DB_NAMESPACE").unwrap_or_else(|_| "hezarfen".into()), db_name: env::var("DB_DATABASE").unwrap_or_else(|_| "hezarfen".into()), + files_path: env::var("FILES_PATH").unwrap_or_else(|_| "./data/files".into()), cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()), rate_limit: RateLimitConfig { auth_per_minute: parse_limit( diff --git a/src/constant.rs b/src/constant.rs index 87a323e..39c43ef 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -35,6 +35,26 @@ pub const MAX_PHONE_DIGITS: usize = 15; pub const MAX_NOTE_TITLE_LEN: usize = 200; pub const MAX_NOTE_CONTENT_LEN: usize = 10_000; +/// How many files one note may carry. +pub const MAX_NOTE_FILES: usize = 10; + +/// Bounds for a note file's original filename and its MIME content type. +pub const MAX_FILE_NAME_LEN: usize = 255; +pub const MAX_FILE_CONTENT_TYPE_LEN: usize = 100; + +/// The school-adjustable per-file upload size limit (`max_file_bytes` in +/// settings): its default and the inclusive range a manager may set. The +/// ceiling is a server-protection hard cap — uploads buffer in memory and land +/// in single disk files, so it must stay modest no matter the school's wish. +pub const DEFAULT_MAX_FILE_BYTES: i64 = 5 * 1024 * 1024; +pub const MIN_MAX_FILE_BYTES: i64 = 1024; +pub const MAX_MAX_FILE_BYTES: i64 = 25 * 1024 * 1024; + +/// Headroom on top of `MAX_MAX_FILE_BYTES` for the upload route's HTTP body +/// cap: multipart boundaries, part headers, and the filename ride alongside +/// the file bytes themselves. +pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024; + pub const MAX_EVENT_TITLE_LEN: usize = 200; pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; diff --git a/src/database.rs b/src/database.rs index 009af27..88dc81e 100644 --- a/src/database.rs +++ b/src/database.rs @@ -11,6 +11,7 @@ pub type Database = Surreal; pub const USER_TABLE: &str = "user"; pub const SESSION_TABLE: &str = "session"; pub const NOTE_TABLE: &str = "note"; +pub const NOTE_FILE_TABLE: &str = "note_file"; pub const EVENT_TABLE: &str = "event"; pub const ATTENDANCE_TABLE: &str = "attendance"; pub const EXAM_TABLE: &str = "exam"; @@ -57,6 +58,13 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS content ON note TYPE string; DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user; + DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record; + DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string; + DEFINE FIELD IF NOT EXISTS content_type ON note_file TYPE string; + DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int; + DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note; + DEFINE TABLE IF NOT EXISTS event SCHEMAFULL; DEFINE FIELD IF NOT EXISTS creator ON event TYPE record; DEFINE FIELD IF NOT EXISTS title ON event TYPE string; @@ -174,6 +182,7 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array; DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; + DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option; "; /// Open the file-backed database and apply the schema. diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 8dd365e..def3c35 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -13,6 +13,7 @@ pub mod exam_attempt; pub mod exam_question; pub mod exam_result; pub mod note; +pub mod note_file; pub mod profile; pub mod role; pub mod session; diff --git a/src/domain/note.rs b/src/domain/note.rs index fe3777a..652861a 100644 --- a/src/domain/note.rs +++ b/src/domain/note.rs @@ -127,7 +127,15 @@ impl Note { updated.ok_or(AppError::NotFound) } + /// Delete the note and cascade-remove its attachment rows. Blob files on + /// disk are the web layer's to remove (it lists them before calling this); + /// a crash in between leaves at worst an unreachable blob, never a row + /// pointing at nothing. pub async fn delete(self, db: &Database) -> Result { + db.query("DELETE note_file WHERE note = $note") + .bind(("note", self.id.record())) + .await? + .check()?; let deleted: Option = db.delete(self.id.record()).await?; deleted.ok_or(AppError::NotFound) } diff --git a/src/domain/note_file.rs b/src/domain/note_file.rs new file mode 100644 index 0000000..fe0b731 --- /dev/null +++ b/src/domain/note_file.rs @@ -0,0 +1,255 @@ +//! A file attached to a note. The row carries metadata only (original +//! filename, MIME type, byte size); the bytes themselves live on disk under +//! [`crate::config::Config::files_path`], in a file named by this row's key — +//! a server-generated ULID, so no user input ever shapes a disk path. The web +//! layer owns the blob I/O and its ordering (blob before row on upload, row +//! before blob on delete); this module owns the rows. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN}; +use crate::database::{Database, NOTE_FILE_TABLE}; +use crate::domain::note::NoteId; +use crate::error::{AppError, ValidationError}; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct NoteFileId(RecordId); + +impl NoteFileId { + pub fn generate() -> Self { + Self(RecordId::new(NOTE_FILE_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(NOTE_FILE_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// The uploader's original filename, kept for display and download headers. +/// Never used as a disk path — but path separators and control characters are +/// refused anyway: they are not filenames, only header/log injection attempts. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct FileName(String); + +impl FileName { + pub fn try_new(value: &str) -> Result { + let value = value.trim(); + if value.is_empty() { + return Err(ValidationError::Empty("filename")); + } + if value.chars().count() > MAX_FILE_NAME_LEN { + return Err(ValidationError::TooLong { + field: "filename", + max: MAX_FILE_NAME_LEN, + got: value.chars().count(), + }); + } + if value + .chars() + .any(|c| c.is_control() || c == '/' || c == '\\') + { + return Err(ValidationError::Invalid { + field: "filename", + reason: "must not contain path separators or control characters", + }); + } + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// The MIME type the client declared for the file. Blank defaults to +/// `application/octet-stream`; it is echoed back on download, so it is held +/// to header-safe ASCII. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct FileContentType(String); + +impl FileContentType { + pub fn try_new(value: &str) -> Result { + let value = value.trim(); + if value.is_empty() { + return Ok(Self("application/octet-stream".to_string())); + } + if value.chars().count() > MAX_FILE_CONTENT_TYPE_LEN { + return Err(ValidationError::TooLong { + field: "content_type", + max: MAX_FILE_CONTENT_TYPE_LEN, + got: value.chars().count(), + }); + } + if !value.is_ascii() { + return Err(ValidationError::NotAscii("content_type")); + } + if value.chars().any(|c| c.is_ascii_control()) { + return Err(ValidationError::Invalid { + field: "content_type", + reason: "must not contain control characters", + }); + } + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct NoteFile { + id: NoteFileId, + note: NoteId, + name: FileName, + content_type: FileContentType, + size: i64, +} + +impl NoteFile { + /// Assemble a new attachment row (id generated here) without persisting + /// it. The caller writes the blob to disk under the fresh id first, then + /// calls [`Self::insert`] — so a stored row always points at a real blob. + pub fn new(note: &NoteId, name: FileName, content_type: FileContentType, size: i64) -> Self { + Self { + id: NoteFileId::generate(), + note: note.clone(), + name, + content_type, + size, + } + } + + pub fn get_id(&self) -> &NoteFileId { + &self.id + } + + pub fn get_name(&self) -> &FileName { + &self.name + } + + pub fn get_content_type(&self) -> &FileContentType { + &self.content_type + } + + pub fn get_size(&self) -> i64 { + self.size + } + + /// Persist the row assembled by [`Self::new`]. + pub async fn insert(self, db: &Database) -> Result { + let created: Option = db.create(self.id.record()).content(self).await?; + created.ok_or_else(|| AppError::Internal("failed to create note file".into())) + } + + /// Read a file's row only if it belongs to `note` — callers have already + /// checked the note belongs to the requesting user. + pub async fn read_for( + id: &NoteFileId, + note: &NoteId, + db: &Database, + ) -> Result, AppError> { + let file: Option = db.select(id.record()).await?; + Ok(file.filter(|file| &file.note == note)) + } + + /// All of `note`'s attachment rows, newest first. + pub async fn list_for(note: &NoteId, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM note_file WHERE note = $note ORDER BY id DESC") + .bind(("note", note.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn delete(self, db: &Database) -> Result { + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn filename_rules() { + assert_eq!( + FileName::try_new(" ödev.pdf ").unwrap().as_str(), + "ödev.pdf" + ); + assert!(FileName::try_new("").is_err()); + assert!(FileName::try_new(" ").is_err()); + assert!(FileName::try_new(&"x".repeat(256)).is_err()); + // Path separators and control characters are injection, not filenames. + assert!(FileName::try_new("a/b.pdf").is_err()); + assert!(FileName::try_new("a\\b.pdf").is_err()); + assert!(FileName::try_new("a\nb.pdf").is_err()); + assert!(FileName::try_new("a\x00b").is_err()); + } + + #[tokio::test] + async fn content_type_rules() { + assert_eq!( + FileContentType::try_new("application/pdf") + .unwrap() + .as_str(), + "application/pdf" + ); + // Blank means the client didn't say — fall back, don't fail. + assert_eq!( + FileContentType::try_new("").unwrap().as_str(), + "application/octet-stream" + ); + assert!(FileContentType::try_new(&"x".repeat(101)).is_err()); + assert!(FileContentType::try_new("appli¢ation/pdf").is_err()); + assert!(FileContentType::try_new("a\r\nb").is_err()); + } + + #[tokio::test] + async fn rows_scope_to_their_note() { + let db = crate::database::init_mem().await.unwrap(); + let note_a = NoteId::generate(); + let note_b = NoteId::generate(); + let file = NoteFile::new( + ¬e_a, + FileName::try_new("plan.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ) + .insert(&db) + .await + .unwrap(); + + // Readable under its own note, invisible under another. + let found = NoteFile::read_for(file.get_id(), ¬e_a, &db) + .await + .unwrap(); + assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); + assert!( + NoteFile::read_for(file.get_id(), ¬e_b, &db) + .await + .unwrap() + .is_none() + ); + + assert_eq!(NoteFile::list_for(¬e_a, &db).await.unwrap().len(), 1); + assert!(NoteFile::list_for(¬e_b, &db).await.unwrap().is_empty()); + + file.delete(&db).await.unwrap(); + assert!(NoteFile::list_for(¬e_a, &db).await.unwrap().is_empty()); + } +} diff --git a/src/domain/settings.rs b/src/domain/settings.rs index 78008d8..9c8e9d6 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -1,17 +1,22 @@ //! School-adjustable policy: which exam kinds exist (and how much each //! weighs in course averages), which attendance statuses the roll call -//! accepts, and how numeric marks display as grades. +//! accepts, how numeric marks display as grades, and how large an uploaded +//! note file may be. //! //! One singleton record (`settings:school` — one school per deployment). An //! absent record means "the defaults from `constant.rs`", so a fresh or -//! pre-existing database needs no seeding and behaves exactly as before. +//! pre-existing database needs no seeding and behaves exactly as before. The +//! same holds per field: `max_file_bytes` is `option` and reads as the +//! default while unset, so rows saved before the field existed keep working +//! without a backfill (backfills crash boots — `DEFAULT` never rescues +//! existing rows, and `UPDATE` re-validates whole records). use surrealdb::types::{RecordId, SurrealValue}; use crate::constant::{ - DEFAULT_ATTENDANCE_STATUSES, DEFAULT_EXAM_KINDS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, - MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, - MIN_EXAM_KIND_WEIGHT, MIN_MARK, + DEFAULT_ATTENDANCE_STATUSES, DEFAULT_EXAM_KINDS, DEFAULT_MAX_FILE_BYTES, MAX_EXAM_KIND_WEIGHT, + MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_FILE_BYTES, MAX_SETTINGS_ITEM_LEN, + MAX_SETTINGS_LIST_LEN, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_FILE_BYTES, }; use crate::database::{Database, SETTINGS_TABLE}; use crate::error::{AppError, ValidationError}; @@ -106,6 +111,9 @@ pub struct Settings { exam_kinds: Vec, attendance_statuses: Vec, grade_bands: Vec, + /// Per-file byte cap for note uploads. `None` = the row predates the + /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`. + max_file_bytes: Option, } impl Settings { @@ -126,6 +134,7 @@ impl Settings { .to_vec(), attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(), grade_bands: Vec::new(), + max_file_bytes: None, } } @@ -134,12 +143,21 @@ impl Settings { /// core attendance statuses can never be removed (the attendance rate's /// semantics are defined over them). Bands may be empty (numeric-only /// display), otherwise their mins are unique and one band must start at 0 - /// so every mark maps to a label. + /// so every mark maps to a label. The upload cap must sit inside the + /// server's hard bounds — the ceiling protects memory and disk, whatever + /// the school would prefer. pub fn try_new( exam_kinds: Vec, attendance_statuses: Vec, grade_bands: Vec, + max_file_bytes: i64, ) -> Result { + if !(MIN_MAX_FILE_BYTES..=MAX_MAX_FILE_BYTES).contains(&max_file_bytes) { + return Err(ValidationError::Invalid { + field: "max_file_bytes", + reason: "must be between 1024 (1 KiB) and 26214400 (25 MiB)", + }); + } // Per-entry rules (name shape, weight range) hold structurally on any // `ExamKindDef`; here only the list-level rules need checking. let names: Vec = exam_kinds @@ -188,6 +206,7 @@ impl Settings { exam_kinds, attendance_statuses, grade_bands, + max_file_bytes: Some(max_file_bytes), }) } @@ -214,6 +233,12 @@ impl Settings { &self.grade_bands } + /// The per-file upload cap in bytes; the built-in default while the + /// school never set one (including rows saved before the field existed). + pub fn get_max_file_bytes(&self) -> i64 { + self.max_file_bytes.unwrap_or(DEFAULT_MAX_FILE_BYTES) + } + /// The label of the band `mark` falls into: the band with the greatest /// `min` at or below it. `None` when no bands are configured. Takes an /// `f64` so course averages label the same way plain marks do. @@ -263,7 +288,8 @@ impl Settings { UPDATE $id CONTENT $new WHERE exam_kinds = $ek AND attendance_statuses = $st - AND grade_bands = $gb; + AND grade_bands = $gb + AND max_file_bytes = $mf; COMMIT TRANSACTION;", ) .bind(("expected", expected.clone())) @@ -272,6 +298,7 @@ impl Settings { .bind(("ek", expected.exam_kinds.clone())) .bind(("st", expected.attendance_statuses.clone())) .bind(("gb", expected.grade_bands.clone())) + .bind(("mf", expected.max_file_bytes)) .await? .check()?; // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An @@ -346,6 +373,7 @@ mod tests { defaults.get_exam_kinds().to_vec(), defaults.get_attendance_statuses().to_vec(), defaults.get_grade_bands().to_vec(), + defaults.get_max_file_bytes(), ) .unwrap(); assert_eq!(rebuilt.get_exam_kinds(), defaults.get_exam_kinds()); @@ -377,15 +405,31 @@ mod tests { #[tokio::test] async fn lists_are_bounded_and_deduped() { let statuses = Settings::defaults().get_attendance_statuses().to_vec(); - let s = Settings::try_new(kinds(&["lab", "quiz"]), statuses.clone(), vec![]).unwrap(); + let s = Settings::try_new( + kinds(&["lab", "quiz"]), + statuses.clone(), + vec![], + DEFAULT_MAX_FILE_BYTES, + ) + .unwrap(); assert_eq!(names(&s), ["lab", "quiz"]); // Empty list and case-insensitive duplicate names are rejected. - assert!(Settings::try_new(vec![], statuses.clone(), vec![]).is_err()); - assert!(Settings::try_new(kinds(&["Lab", "lab"]), statuses.clone(), vec![]).is_err()); + assert!( + Settings::try_new(vec![], statuses.clone(), vec![], DEFAULT_MAX_FILE_BYTES).is_err() + ); + assert!( + Settings::try_new( + kinds(&["Lab", "lab"]), + statuses.clone(), + vec![], + DEFAULT_MAX_FILE_BYTES + ) + .is_err() + ); let too_many: Vec = (0..21) .map(|i| ExamKindDef::try_new(&format!("kind{i}"), 1).unwrap()) .collect(); - assert!(Settings::try_new(too_many, statuses, vec![]).is_err()); + assert!(Settings::try_new(too_many, statuses, vec![], DEFAULT_MAX_FILE_BYTES).is_err()); } #[tokio::test] @@ -398,6 +442,7 @@ mod tests { ], statuses, vec![], + DEFAULT_MAX_FILE_BYTES, ) .unwrap(); assert_eq!(s.exam_kind_weight("final"), Some(3)); @@ -412,13 +457,13 @@ mod tests { let kinds = Settings::defaults().get_exam_kinds().to_vec(); // Extras on top of the core are fine. let extended = statuses_with(&["online"]); - assert!(Settings::try_new(kinds.clone(), extended, vec![]).is_ok()); + assert!(Settings::try_new(kinds.clone(), extended, vec![], DEFAULT_MAX_FILE_BYTES).is_ok()); // Dropping any core status is not. let missing: Vec = statuses_with(&[]) .into_iter() .filter(|s| s != "late") .collect(); - assert!(Settings::try_new(kinds, missing, vec![]).is_err()); + assert!(Settings::try_new(kinds, missing, vec![], DEFAULT_MAX_FILE_BYTES).is_err()); } fn statuses_with(extra: &[&str]) -> Vec { @@ -444,6 +489,7 @@ mod tests { defaults.get_exam_kinds().to_vec(), defaults.get_attendance_statuses().to_vec(), b, + DEFAULT_MAX_FILE_BYTES, ) }; // Empty = numeric-only display. @@ -455,6 +501,53 @@ mod tests { assert!(ok(bands(&[(0, "FF"), (50, "CC"), (85, "AA")])).is_ok()); } + #[tokio::test] + async fn max_file_bytes_is_bounded() { + let defaults = Settings::defaults(); + let with_cap = |cap: i64| { + Settings::try_new( + defaults.get_exam_kinds().to_vec(), + defaults.get_attendance_statuses().to_vec(), + vec![], + cap, + ) + }; + for cap in [ + MIN_MAX_FILE_BYTES, + DEFAULT_MAX_FILE_BYTES, + MAX_MAX_FILE_BYTES, + ] { + assert_eq!(with_cap(cap).unwrap().get_max_file_bytes(), cap); + } + assert!(with_cap(MIN_MAX_FILE_BYTES - 1).is_err()); + assert!(with_cap(MAX_MAX_FILE_BYTES + 1).is_err()); + assert!(with_cap(0).is_err()); + assert!(with_cap(-1).is_err()); + } + + #[tokio::test] + async fn a_row_predating_max_file_bytes_reads_the_default() { + let db = crate::database::init_mem().await.unwrap(); + // The defaults carry no explicit cap, so this writes a row without the + // field — exactly what a volume from before the field looks like. + Settings::defaults().save(&db).await.unwrap(); + let loaded = Settings::load(&db).await.unwrap(); + assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES); + // And a snapshot of that old row still passes the compare-and-set. + let saved = Settings::try_new( + loaded.get_exam_kinds().to_vec(), + loaded.get_attendance_statuses().to_vec(), + vec![], + 4096, + ) + .unwrap() + .save_if_unchanged(&loaded, &db) + .await + .unwrap() + .expect("a merge over an old-shape row applies"); + assert_eq!(saved.get_max_file_bytes(), 4096); + } + #[tokio::test] async fn load_save_roundtrip_on_the_singleton() { let db = crate::database::init_mem().await.unwrap(); @@ -471,6 +564,7 @@ mod tests { kinds(&["lab"]), statuses.clone(), bands(&[(0, "F"), (50, "P")]), + 2048, ) .unwrap() .save(&db) @@ -480,8 +574,9 @@ mod tests { assert_eq!(names(&loaded), ["lab"]); assert_eq!(loaded.get_grade_bands().len(), 2); assert_eq!(loaded.grade_label(60.0), Some("P")); + assert_eq!(loaded.get_max_file_bytes(), 2048); // A second save lands on the same singleton row, not a new one. - Settings::try_new(kinds(&["quiz"]), statuses, vec![]) + Settings::try_new(kinds(&["quiz"]), statuses, vec![], DEFAULT_MAX_FILE_BYTES) .unwrap() .save(&db) .await @@ -500,11 +595,16 @@ mod tests { // Editor A snapshots the policy (the defaults — no row yet)... let stale = Settings::load(&db).await.unwrap(); // ...then editor B lands a new exam-kind list first. - Settings::try_new(kinds(&["lab"]), statuses.clone(), vec![]) - .unwrap() - .save(&db) - .await - .unwrap(); + Settings::try_new( + kinds(&["lab"]), + statuses.clone(), + vec![], + DEFAULT_MAX_FILE_BYTES, + ) + .unwrap() + .save(&db) + .await + .unwrap(); // A's merge over the stale snapshot (kinds kept "as loaded", bands // changed) — exactly what a concurrent PATCH /settings computes — @@ -513,6 +613,7 @@ mod tests { stale.get_exam_kinds().to_vec(), stale.get_attendance_statuses().to_vec(), bands(&[(0, "F"), (50, "P")]), + stale.get_max_file_bytes(), ) .unwrap() .save_if_unchanged(&stale, &db) @@ -535,6 +636,7 @@ mod tests { fresh.get_exam_kinds().to_vec(), fresh.get_attendance_statuses().to_vec(), bands(&[(0, "F"), (50, "P")]), + fresh.get_max_file_bytes(), ) .unwrap() .save_if_unchanged(&fresh, &db) @@ -555,6 +657,7 @@ mod tests { kinds(&["lab"]), current.get_attendance_statuses().to_vec(), vec![], + current.get_max_file_bytes(), ) .unwrap() .save_if_unchanged(¤t, &db) @@ -574,6 +677,7 @@ mod tests { defaults.get_exam_kinds().to_vec(), defaults.get_attendance_statuses().to_vec(), bands(&[(0, "FF"), (50, "CC"), (85, "AA")]), + DEFAULT_MAX_FILE_BYTES, ) .unwrap(); assert_eq!(s.grade_label(0.0), Some("FF")); diff --git a/src/error.rs b/src/error.rs index 49fc18d..5281773 100644 --- a/src/error.rs +++ b/src/error.rs @@ -51,6 +51,10 @@ pub enum AppError { Forbidden(&'static str), #[error("conflict: {0}")] Conflict(&'static str), + /// A request body (file upload) over the allowed size. Owned string: the + /// school-configured limit is only known at runtime. + #[error("payload too large: {0}")] + PayloadTooLarge(String), #[error("too many requests")] TooManyRequests { retry_after_secs: u64 }, #[error("database error")] @@ -82,6 +86,7 @@ impl IntoResponse for AppError { AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()), AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()), + AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()), AppError::Db(e) => { tracing::error!("database error: {e}"); ( diff --git a/src/lib.rs b/src/lib.rs index a8f2549..1501232 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,14 +32,14 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. 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.", + 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.", ), modifiers(&SecurityAddon), tags( (name = "meta", description = "Liveness and service metadata"), (name = "auth", description = "Registration, login, session lifecycle"), (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)"), - (name = "notes", description = "Per-user notes CRUD"), + (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`)"), (name = "events", description = "Events and attendance"), (name = "courses", description = "Courses, enrollment (students only), course exams, and course sessions"), (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; (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), (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"), (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)"), - (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+"), + (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+"), (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), ), )] diff --git a/src/main.rs b/src/main.rs index 8594372..5b4e9d5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,8 +18,12 @@ async fn main() -> anyhow::Result<()> { let cfg = Config::from_env(); let db = database::init(&cfg).await?; seed_admin(&cfg, &db).await?; + tokio::fs::create_dir_all(&cfg.files_path) + .await + .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?; let app = build_router(AppState { db, + files_path: cfg.files_path.clone().into(), cookie_secure: cfg.cookie_secure, rate_limit: cfg.rate_limit.clone(), exam_presence: Default::default(), diff --git a/src/state.rs b/src/state.rs index 0c685d2..37a5cab 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::path::PathBuf; use std::sync::{Arc, Mutex}; use crate::database::Database; @@ -8,6 +9,10 @@ use crate::rate_limit::RateLimitConfig; #[derive(Clone)] pub struct AppState { pub db: Database, + /// Directory holding uploaded note-file blobs, one file per + /// `note_file` row, named by the row's key + /// (from [`crate::config::Config::files_path`]). + pub files_path: PathBuf, /// Whether the session cookie carries the `Secure` attribute /// (from [`crate::config::Config::cookie_secure`]). pub cookie_secure: bool, diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 31eb898..d342a88 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -399,6 +399,7 @@ fn error_frame(err: &AppError) -> Value { AppError::Unauthorized => "unauthorized".to_string(), AppError::Forbidden(message) => (*message).to_string(), AppError::Conflict(message) => (*message).to_string(), + AppError::PayloadTooLarge(message) => message.clone(), AppError::TooManyRequests { .. } => "too many requests".to_string(), AppError::Db(_) | AppError::Internal(_) => { tracing::error!("exam room error: {err}"); diff --git a/src/web/notes.rs b/src/web/notes.rs index 3f6a8b1..0701443 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -1,21 +1,40 @@ +use std::path::{Path as FsPath, PathBuf}; + use axum::Json; -use axum::extract::{Path, Query, State}; -use axum::http::StatusCode; +use axum::extract::multipart::MultipartError; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; +use axum::http::{HeaderValue, StatusCode}; +use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +use crate::constant::{MAX_MAX_FILE_BYTES, MAX_NOTE_FILES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; -use crate::error::{AppError, ErrorResponse}; +use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; +use crate::domain::settings::Settings; +use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::{CurrentUser, Page, PageParams, paginate}; pub fn routes() -> OpenApiRouter { + // The file routes get their own HTTP body cap: the server-wide hard + // ceiling plus multipart framing headroom (axum's 2 MB default would + // reject legal uploads). The school's actual — usually smaller — limit + // from settings is enforced while the stream is read. + let files = OpenApiRouter::new() + .routes(routes!(upload_file, list_files)) + .routes(routes!(download_file, delete_file)) + .layer(DefaultBodyLimit::max( + MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, + )); OpenApiRouter::new() .routes(routes!(create, list)) .routes(routes!(get_one, update, delete_one)) + .merge(files) } #[derive(Deserialize, ToSchema)] @@ -165,7 +184,7 @@ async fn update( Ok(Json(NoteResponse::new(&updated))) } -/// Delete a note owned by the current user. +/// Delete a note owned by the current user, along with its files. #[utoipa::path( delete, path = "/{id}", @@ -186,6 +205,353 @@ async fn delete_one( let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; + // Rows go first (the note delete cascades them), blobs after: a crash in + // between strands at worst an unreachable blob, never a row whose blob is + // already gone. + let files = NoteFile::list_for(note.get_id(), &st.db).await?; note.delete(&st.db).await?; + for file in &files { + remove_blob(&st.files_path, file.get_id()).await; + } Ok(StatusCode::NO_CONTENT) } + +/// A note file's stored metadata; the bytes themselves come from the +/// download endpoint. +#[derive(Serialize, ToSchema)] +struct NoteFileResponse { + id: String, + /// The uploader's original filename. + #[schema(example = "homework.pdf")] + name: String, + /// MIME type as declared on upload. + #[schema(example = "application/pdf")] + content_type: String, + /// File size in bytes. + #[schema(example = 24_576)] + size: i64, +} + +impl NoteFileResponse { + fn new(file: &NoteFile) -> Self { + Self { + id: file.get_id().key().to_string(), + name: file.get_name().as_str().to_string(), + content_type: file.get_content_type().as_str().to_string(), + size: file.get_size(), + } + } +} + +/// Schema-only mirror of the upload form; the handler reads the multipart +/// stream directly. +#[derive(ToSchema)] +#[allow(dead_code)] +struct UploadFileForm { + /// The file part. Its `filename` (required) and `Content-Type` are stored + /// alongside the bytes. + #[schema(value_type = String, format = Binary)] + file: String, +} + +/// Attach a file to a note owned by the current user. `multipart/form-data` +/// with the file under a `file` field; its `filename` is required. At most +/// 10 files per note; each file at most the school's `max_file_bytes` +/// (settings, default 5 MiB). +#[utoipa::path( + post, + path = "/{id}/files", + tag = "notes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Note id")), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "File stored", body = NoteFileResponse), + (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Note not found", body = ErrorResponse), + (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse), + (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse), + ), +)] +async fn upload_file( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if NoteFile::list_for(note.get_id(), &st.db).await?.len() >= MAX_NOTE_FILES { + return Err(AppError::Conflict( + "the note already holds the maximum of 10 files — delete one first", + )); + } + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + + let mut field = loop { + match multipart.next_field().await.map_err(multipart_error)? { + Some(field) if field.name() == Some("file") => break field, + Some(_) => continue, // ignore stray extra fields + None => { + return Err(AppError::Validation(ValidationError::Invalid { + field: "file", + reason: "the multipart body must carry a 'file' field", + })); + } + } + }; + let name = FileName::try_new(field.file_name().unwrap_or_default())?; + let content_type = FileContentType::try_new(field.content_type().unwrap_or_default())?; + + // Read the part chunkwise so an oversized upload dies at the limit, not + // after buffering whole. The check is on real bytes received — a lying + // Content-Length can't sneak past it. + let mut data = Vec::new(); + while let Some(chunk) = field.chunk().await.map_err(multipart_error)? { + if data.len() + chunk.len() > limit as usize { + return Err(AppError::PayloadTooLarge(format!( + "the file exceeds the school's limit of {limit} bytes" + ))); + } + data.extend_from_slice(&chunk); + } + if data.is_empty() { + return Err(AppError::Validation(ValidationError::Empty("file"))); + } + + // Blob first, row second — a stored row always points at a real blob. If + // the row insert fails, take the fresh blob back out. + let file = NoteFile::new(note.get_id(), name, content_type, data.len() as i64); + let path = blob_path(&st.files_path, file.get_id()); + tokio::fs::write(&path, &data) + .await + .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; + match file.insert(&st.db).await { + Ok(created) => Ok((StatusCode::CREATED, Json(NoteFileResponse::new(&created)))), + Err(err) => { + let _ = tokio::fs::remove_file(&path).await; + Err(err) + } + } +} + +/// List a note's files (metadata only), newest first. Paged via +/// `?limit=&offset=`. +#[utoipa::path( + get, + path = "/{id}/files", + tag = "notes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Note id"), PageParams), + responses( + (status = 200, description = "A page of the note's files", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Note not found", body = ErrorResponse), + ), +)] +async fn list_files( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let files = NoteFile::list_for(note.get_id(), &st.db).await?; + let total = files.len() as i64; + let items = paginate(&files, limit, offset) + .iter() + .map(NoteFileResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Download a note file's bytes. `Content-Type` is the one declared on +/// upload; `Content-Disposition` carries the original filename. +#[utoipa::path( + get, + path = "/{id}/files/{file_id}", + tag = "notes", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Note id"), + ("file_id" = String, Path, description = "File id"), + ), + responses( + (status = 200, description = "The file bytes", content_type = "application/octet-stream"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Note or file not found", body = ErrorResponse), + ), +)] +async fn download_file( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, file_id)): Path<(String, String)>, +) -> Result { + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id())) + .await + .map_err(|err| { + // The row exists but its blob doesn't — that's server-side damage + // (a lost volume path), not a client 404. + AppError::Internal(format!( + "missing blob for note file {}: {err}", + file.get_id().key() + )) + })?; + // The stored content type is validated ASCII without control characters, + // so it always parses; the fallback is for belt and braces. + let content_type = HeaderValue::from_str(file.get_content_type().as_str()) + .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")); + let disposition = HeaderValue::from_str(&content_disposition(file.get_name().as_str())) + .unwrap_or_else(|_| HeaderValue::from_static("attachment")); + Ok(( + [ + (CONTENT_TYPE, content_type), + (CONTENT_DISPOSITION, disposition), + ], + bytes, + ) + .into_response()) +} + +/// Delete a note file (row first, then its blob). +#[utoipa::path( + delete, + path = "/{id}/files/{file_id}", + tag = "notes", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Note id"), + ("file_id" = String, Path, description = "File id"), + ), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Note or file not found", body = ErrorResponse), + ), +)] +async fn delete_file( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, file_id)): Path<(String, String)>, +) -> Result { + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let file = file.delete(&st.db).await?; + remove_blob(&st.files_path, file.get_id()).await; + Ok(StatusCode::NO_CONTENT) +} + +/// Where a file row's blob lives: one file under the configured directory, +/// named by the row's server-generated key — user input never shapes a path. +fn blob_path(files_path: &FsPath, id: &NoteFileId) -> PathBuf { + files_path.join(id.key()) +} + +/// Best-effort blob removal after its row is gone. Failure only strands an +/// unreachable file on disk, so it is logged rather than surfaced. +async fn remove_blob(files_path: &FsPath, id: &NoteFileId) { + let path = blob_path(files_path, id); + if let Err(err) = tokio::fs::remove_file(&path).await + && err.kind() != std::io::ErrorKind::NotFound + { + tracing::warn!("failed to remove blob {}: {err}", path.display()); + } +} + +/// Multipart read failures: the route-level body cap maps to 413 like the +/// school-limit check; anything else is a malformed body. +fn multipart_error(err: MultipartError) -> AppError { + if err.status() == StatusCode::PAYLOAD_TOO_LARGE { + AppError::PayloadTooLarge("the upload exceeds the server's absolute body cap".to_string()) + } else { + AppError::Validation(ValidationError::Invalid { + field: "file", + reason: "malformed multipart body", + }) + } +} + +/// `Content-Disposition` for a download: an ASCII-safe `filename` fallback +/// plus the RFC 5987 `filename*` form so non-ASCII names (`ödev.pdf`) survive. +fn content_disposition(name: &str) -> String { + let fallback: String = name + .chars() + .map(|c| { + if c.is_ascii_graphic() && c != '"' && c != '\\' || c == ' ' { + c + } else { + '_' + } + }) + .collect(); + format!( + "attachment; filename=\"{fallback}\"; filename*=UTF-8''{}", + rfc5987_encode(name) + ) +} + +/// Percent-encode everything outside RFC 5987's `attr-char` set, on UTF-8 +/// bytes. +fn rfc5987_encode(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for byte in value.bytes() { + match byte { + b'a'..=b'z' + | b'A'..=b'Z' + | b'0'..=b'9' + | b'!' + | b'#' + | b'$' + | b'&' + | b'+' + | b'-' + | b'.' + | b'^' + | b'_' + | b'`' + | b'|' + | b'~' => out.push(byte as char), + _ => out.push_str(&format!("%{byte:02X}")), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn disposition_keeps_ascii_and_encodes_the_rest() { + assert_eq!( + content_disposition("plan.pdf"), + "attachment; filename=\"plan.pdf\"; filename*=UTF-8''plan.pdf" + ); + // Non-ASCII survives in the RFC 5987 form; the fallback degrades. + assert_eq!( + content_disposition("ödev 1.pdf"), + "attachment; filename=\"_dev 1.pdf\"; filename*=UTF-8''%C3%B6dev%201.pdf" + ); + // Quotes can't break out of the quoted fallback. + assert_eq!( + content_disposition("a\"b.pdf"), + "attachment; filename=\"a_b.pdf\"; filename*=UTF-8''a%22b.pdf" + ); + } +} diff --git a/src/web/settings.rs b/src/web/settings.rs index 47afed5..b79a05d 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -60,6 +60,9 @@ struct SettingsResponse { attendance_statuses: Vec, /// Grade-display bands, highest first. Empty = marks display numeric-only. grade_bands: Vec, + /// Per-file size limit for note uploads, in bytes. + #[schema(example = 5_242_880)] + max_file_bytes: i64, } impl SettingsResponse { @@ -82,6 +85,7 @@ impl SettingsResponse { label: band.get_label().to_string(), }) .collect(), + max_file_bytes: settings.get_max_file_bytes(), } } } @@ -97,6 +101,10 @@ struct UpdateSettings { /// Replaces the whole set when present. `[]` clears the bands (numeric-only /// marks); otherwise mins are unique and one band must start at `0`. grade_bands: Option>, + /// Per-file size limit for note uploads, in bytes: + /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap. + #[schema(example = 5_242_880)] + max_file_bytes: Option, } /// The school's current policy. Any authenticated user — clients need it to @@ -126,7 +134,8 @@ async fn get_settings( /// new writes are held to the new lists. Kind weights, though, apply live: /// mark reports read them at request time, so editing a weight re-weights /// every exam of that kind, and an exam whose kind was removed from the list -/// counts with weight 1 until the kind returns. +/// counts with weight 1 until the kind returns. `max_file_bytes` likewise +/// applies at upload time only — already-stored files keep their size. #[utoipa::path( patch, path = "/", @@ -135,7 +144,7 @@ async fn get_settings( request_body = UpdateSettings, responses( (status = 200, description = "Updated policy", body = SettingsResponse), - (status = 400, description = "Invalid lists or bands", body = ErrorResponse), + (status = 400, description = "Invalid lists, bands, or file limit", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 409, description = "Concurrent edits kept changing the settings mid-save", body = ErrorResponse), @@ -171,8 +180,12 @@ async fn update_settings( .collect::, _>>()?, None => current.get_grade_bands().to_vec(), }; + let max_file_bytes = req + .max_file_bytes + .unwrap_or_else(|| current.get_max_file_bytes()); - let settings = Settings::try_new(exam_kinds, attendance_statuses, grade_bands)?; + let settings = + Settings::try_new(exam_kinds, attendance_statuses, grade_bands, max_file_bytes)?; if let Some(saved) = settings.save_if_unchanged(¤t, &st.db).await? { return Ok(Json(SettingsResponse::new(&saved))); } diff --git a/tests/common/mod.rs b/tests/common/mod.rs index a1f04ac..767237a 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -2,14 +2,18 @@ //! Drives an `axum::Router` in-process via `tower::ServiceExt::oneshot`. #![allow(dead_code)] +use std::path::PathBuf; +use std::sync::OnceLock; + use axum::Router; use axum::body::Body; -use axum::http::{Request, StatusCode}; +use axum::http::{HeaderMap, Request, StatusCode}; use hezarfen_backend::database::Database; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::AppState; use hezarfen_backend::{build_router, database}; use serde_json::{Value, json}; +use tempfile::TempDir; use tower::ServiceExt; pub struct Res { @@ -19,6 +23,18 @@ pub struct Res { pub cookie: Option, } +/// One shared blob directory for every in-memory app in this test process. +/// Blob names are per-row ULIDs, so apps never collide; the static keeps the +/// `TempDir` (and so the directory) alive for the whole run. +static FILES_DIR: OnceLock = OnceLock::new(); + +pub fn files_dir() -> PathBuf { + FILES_DIR + .get_or_init(|| tempfile::tempdir().expect("files tempdir")) + .path() + .to_path_buf() +} + /// A router plus a handle to its (shared) in-memory database. Tests that need to /// grant roles use the handle to seed them directly — the app's only role /// bootstrap path is out-of-band, exactly like production's manual SQL. @@ -26,6 +42,7 @@ pub async fn app_and_db() -> (Router, Database) { let db = database::init_mem().await.expect("in-memory db"); let app = build_router(AppState { db: db.clone(), + files_path: files_dir(), cookie_secure: false, // Off, so suites hammering the API never trip a limit; the dedicated // `rate_limit` test binary opts into tight configs on purpose. @@ -107,6 +124,86 @@ pub async fn send( } } +/// Send one request with a raw body and content type; returns the raw +/// response (status, headers, body bytes) — for driving the file endpoints. +pub async fn send_raw( + app: &Router, + method: &str, + uri: &str, + cookie: Option<&str>, + content_type: Option<&str>, + body: Vec, +) -> (StatusCode, HeaderMap, Vec) { + let mut builder = Request::builder().method(method).uri(uri); + if let Some(c) = cookie { + builder = builder.header("cookie", c); + } + if let Some(ct) = content_type { + builder = builder.header("content-type", ct); + } + let response = app + .clone() + .oneshot(builder.body(Body::from(body)).unwrap()) + .await + .unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(); + (status, headers, bytes) +} + +const MULTIPART_BOUNDARY: &str = "hezarfen-test-boundary"; + +/// A `multipart/form-data` body with a single `file` part. +pub fn multipart_file(filename: &str, content_type: &str, bytes: &[u8]) -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(format!("--{MULTIPART_BOUNDARY}\r\n").as_bytes()); + body.extend_from_slice( + format!("Content-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\n") + .as_bytes(), + ); + body.extend_from_slice(format!("Content-Type: {content_type}\r\n\r\n").as_bytes()); + body.extend_from_slice(bytes); + body.extend_from_slice(format!("\r\n--{MULTIPART_BOUNDARY}--\r\n").as_bytes()); + body +} + +/// Upload `bytes` as a file onto `note` (no assertion). Parses the JSON body +/// like `send`. +pub async fn upload_file( + app: &Router, + cookie: &str, + note: &str, + filename: &str, + content_type: &str, + bytes: &[u8], +) -> Res { + let (status, _, body) = send_raw( + app, + "POST", + &format!("/notes/{note}/files"), + Some(cookie), + Some(&format!( + "multipart/form-data; boundary={MULTIPART_BOUNDARY}" + )), + multipart_file(filename, content_type, bytes), + ) + .await; + let body = if body.is_empty() { + Value::Null + } else { + serde_json::from_slice(&body).unwrap_or(Value::Null) + }; + Res { + status, + body, + cookie: None, + } +} + /// Register (password `secret1`) then log in; returns the session `Cookie` value. pub async fn login(app: &Router, username: &str) -> String { let creds = json!({ "username": username, "password": "secret1" }); diff --git a/tests/e2e.rs b/tests/e2e.rs index 37491c3..d99a961 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -15,6 +15,9 @@ async fn spawn_server() -> (String, Database) { let db = database::init_mem().await.expect("in-memory db"); let app = build_router(AppState { db: db.clone(), + // Kept (not auto-deleted) so the directory outlives this helper; + // it's under the OS temp dir, reclaimed like any other temp file. + files_path: tempfile::tempdir().expect("files dir").keep(), cookie_secure: false, // Every request here comes from 127.0.0.1, so per-IP limits would // meter the whole suite as one client. Off; `rate_limit.rs` covers it. diff --git a/tests/integration.rs b/tests/integration.rs index 9fb3715..754aca3 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -428,6 +428,372 @@ async fn note_validation_and_missing_ids() { ); } +// --- note files ------------------------------------------------------------ + +/// Create a note as `cookie`; returns its id. +async fn create_note(app: &axum::Router, cookie: &str, title: &str) -> String { + let res = send( + app, + "POST", + "/notes", + Some(cookie), + Some(json!({ "title": title })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "create note {title}"); + id_of(&res.body) +} + +#[tokio::test] +async fn note_files_upload_download_delete_roundtrip() { + let app = mem_app().await; + let ali = login(&app, "ali").await; + let note = create_note(&app, &ali, "with file").await; + + let bytes = b"%PDF-1.4 fake but binary \x00\x01\x02".to_vec(); + let up = common::upload_file(&app, &ali, ¬e, "plan.pdf", "application/pdf", &bytes).await; + assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); + assert_eq!(up.body["name"], "plan.pdf"); + assert_eq!(up.body["content_type"], "application/pdf"); + assert_eq!(up.body["size"], bytes.len() as i64); + let file_id = id_of(&up.body); + + // Listed under the note (paged envelope). + let list = send( + &app, + "GET", + &format!("/notes/{note}/files"), + Some(&ali), + None, + ) + .await; + assert_eq!(list.status, StatusCode::OK); + assert_eq!(common::total(&list.body), 1); + assert_eq!(common::items(&list.body)[0]["name"], "plan.pdf"); + + // Download returns the exact bytes with the declared type and filename. + let (status, headers, body) = common::send_raw( + &app, + "GET", + &format!("/notes/{note}/files/{file_id}"), + Some(&ali), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, bytes); + assert_eq!(headers["content-type"], "application/pdf"); + assert_eq!( + headers["content-disposition"], + "attachment; filename=\"plan.pdf\"; filename*=UTF-8''plan.pdf" + ); + + // Delete; the file is gone from the list, download 404s, blob removed. + assert_eq!( + send( + &app, + "DELETE", + &format!("/notes/{note}/files/{file_id}"), + Some(&ali), + None + ) + .await + .status, + StatusCode::NO_CONTENT + ); + let list = send( + &app, + "GET", + &format!("/notes/{note}/files"), + Some(&ali), + None, + ) + .await; + assert_eq!(common::total(&list.body), 0); + assert_eq!( + send( + &app, + "GET", + &format!("/notes/{note}/files/{file_id}"), + Some(&ali), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); + assert!( + !common::files_dir().join(&file_id).exists(), + "blob must be unlinked with its row" + ); +} + +#[tokio::test] +async fn note_files_are_scoped_to_the_notes_owner() { + let app = mem_app().await; + let ali = login(&app, "ali").await; + let veli = login(&app, "veli").await; + let note = create_note(&app, &ali, "mine").await; + let up = common::upload_file(&app, &ali, ¬e, "a.txt", "text/plain", b"hi").await; + assert_eq!(up.status, StatusCode::CREATED); + let file_id = id_of(&up.body); + + // Another user can't upload to, list, download from, or delete on the note. + let foreign = common::upload_file(&app, &veli, ¬e, "b.txt", "text/plain", b"x").await; + assert_eq!(foreign.status, StatusCode::NOT_FOUND); + assert_eq!( + send( + &app, + "GET", + &format!("/notes/{note}/files"), + Some(&veli), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); + for method in ["GET", "DELETE"] { + assert_eq!( + send( + &app, + method, + &format!("/notes/{note}/files/{file_id}"), + Some(&veli), + None + ) + .await + .status, + StatusCode::NOT_FOUND, + "{method}" + ); + } + + // A file id under someone else's note id doesn't resolve either. + let veli_note = create_note(&app, &veli, "veli's").await; + assert_eq!( + send( + &app, + "GET", + &format!("/notes/{veli_note}/files/{file_id}"), + Some(&veli), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn note_file_size_follows_the_school_limit() { + let (app, db) = app_and_db().await; + let boss = login_as(&app, &db, "boss", "manager").await; + let ali = login(&app, "ali").await; + let note = create_note(&app, &ali, "sized").await; + + // Lower the school cap to 1 KiB. + let res = send( + &app, + "PATCH", + "/settings", + Some(&boss), + Some(json!({ "max_file_bytes": 1024 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["max_file_bytes"], 1024); + + // Over the cap dies with 413; at the cap passes. + let big = common::upload_file(&app, &ali, ¬e, "big.bin", "", &vec![7u8; 1025]).await; + assert_eq!(big.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", big.body); + let fits = common::upload_file(&app, &ali, ¬e, "fits.bin", "", &vec![7u8; 1024]).await; + assert_eq!(fits.status, StatusCode::CREATED, "{}", fits.body); + // A blank part content type falls back to octet-stream. + assert_eq!(fits.body["content_type"], "application/octet-stream"); + + // Raising the cap unlocks bigger files at once. + assert_eq!( + send( + &app, + "PATCH", + "/settings", + Some(&boss), + Some(json!({ "max_file_bytes": 10_000 })), + ) + .await + .status, + StatusCode::OK + ); + let now_fits = common::upload_file(&app, &ali, ¬e, "big.bin", "", &vec![7u8; 1025]).await; + assert_eq!(now_fits.status, StatusCode::CREATED); +} + +#[tokio::test] +async fn settings_bound_the_file_limit() { + let (app, db) = app_and_db().await; + let boss = login_as(&app, &db, "boss", "manager").await; + + // The default is visible to any authenticated user. + let res = send(&app, "GET", "/settings", Some(&boss), None).await; + assert_eq!(res.body["max_file_bytes"], 5 * 1024 * 1024); + + // Outside the hard bounds -> 400 (and the stored value is untouched). + for bad in [0, 1023, 25 * 1024 * 1024 + 1] { + let res = send( + &app, + "PATCH", + "/settings", + Some(&boss), + Some(json!({ "max_file_bytes": bad })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "cap {bad}"); + } + let res = send(&app, "GET", "/settings", Some(&boss), None).await; + assert_eq!(res.body["max_file_bytes"], 5 * 1024 * 1024); + + // Editing another field leaves the cap alone. + let res = send( + &app, + "PATCH", + "/settings", + Some(&boss), + Some(json!({ "max_file_bytes": 2048 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + let res = send( + &app, + "PATCH", + "/settings", + Some(&boss), + Some(json!({ "grade_bands": [{ "min": 0, "label": "F" }] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["max_file_bytes"], 2048); +} + +#[tokio::test] +async fn note_file_count_is_capped() { + let app = mem_app().await; + let ali = login(&app, "ali").await; + let note = create_note(&app, &ali, "full").await; + + for i in 0..10 { + let up = common::upload_file(&app, &ali, ¬e, &format!("f{i}.txt"), "", b"x").await; + assert_eq!(up.status, StatusCode::CREATED, "file {i}"); + } + let over = common::upload_file(&app, &ali, ¬e, "f10.txt", "", b"x").await; + assert_eq!(over.status, StatusCode::CONFLICT); + + // Deleting one frees a slot. + let list = send( + &app, + "GET", + &format!("/notes/{note}/files"), + Some(&ali), + None, + ) + .await; + let victim = id_of(&common::items(&list.body)[0]); + assert_eq!( + send( + &app, + "DELETE", + &format!("/notes/{note}/files/{victim}"), + Some(&ali), + None + ) + .await + .status, + StatusCode::NO_CONTENT + ); + let retry = common::upload_file(&app, &ali, ¬e, "f10.txt", "", b"x").await; + assert_eq!(retry.status, StatusCode::CREATED); +} + +#[tokio::test] +async fn note_file_upload_validation() { + let app = mem_app().await; + let ali = login(&app, "ali").await; + let note = create_note(&app, &ali, "strict").await; + + // Empty file, filename with a path separator, no file field at all: 400. + let empty = common::upload_file(&app, &ali, ¬e, "e.txt", "", b"").await; + assert_eq!(empty.status, StatusCode::BAD_REQUEST, "{}", empty.body); + let traversal = common::upload_file(&app, &ali, ¬e, "../../etc/passwd", "", b"data").await; + assert_eq!(traversal.status, StatusCode::BAD_REQUEST); + + // A body whose only part isn't named "file" has no upload in it. + let stray = common::multipart_file("y.txt", "", b"data"); + let stray = String::from_utf8(stray) + .unwrap() + .replace("name=\"file\"", "name=\"attachment\""); + let (status, _, _) = common::send_raw( + &app, + "POST", + &format!("/notes/{note}/files"), + Some(&ali), + Some("multipart/form-data; boundary=hezarfen-test-boundary"), + stray.into_bytes(), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + + // Non-ASCII filenames are fine — stored and encoded on download. + let turkish = + common::upload_file(&app, &ali, ¬e, "ödev 1.pdf", "application/pdf", b"pdf").await; + assert_eq!(turkish.status, StatusCode::CREATED); + let (status, headers, _) = common::send_raw( + &app, + "GET", + &format!("/notes/{note}/files/{}", id_of(&turkish.body)), + Some(&ali), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + headers["content-disposition"], + "attachment; filename=\"_dev 1.pdf\"; filename*=UTF-8''%C3%B6dev%201.pdf" + ); +} + +#[tokio::test] +async fn deleting_a_note_removes_its_files() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; + let note = create_note(&app, &ali, "doomed").await; + let up = common::upload_file(&app, &ali, ¬e, "gone.txt", "", b"bye").await; + assert_eq!(up.status, StatusCode::CREATED); + let file_id = id_of(&up.body); + + assert_eq!( + send(&app, "DELETE", &format!("/notes/{note}"), Some(&ali), None) + .await + .status, + StatusCode::NO_CONTENT + ); + + // Row and blob are both gone. + let mut rows = db + .query("SELECT * FROM note_file") + .await + .unwrap() + .check() + .unwrap(); + let left: Vec = rows.take(0).unwrap(); + assert!(left.is_empty(), "note_file rows must cascade: {left:?}"); + assert!( + !common::files_dir().join(&file_id).exists(), + "blob must be unlinked when its note dies" + ); +} + // --- events + attendance ------------------------------------------------- #[tokio::test] @@ -582,15 +948,17 @@ async fn attendance_marking_and_upsert() { // Two rows total. assert_eq!( - common::items(&send( - &app, - "GET", - &format!("/events/{event_id}/attendance"), - Some(&ali), - None + common::items( + &send( + &app, + "GET", + &format!("/events/{event_id}/attendance"), + Some(&ali), + None + ) + .await + .body ) - .await - .body) .len(), 2 ); @@ -609,15 +977,17 @@ async fn attendance_marking_and_upsert() { StatusCode::NO_CONTENT ); assert_eq!( - common::items(&send( - &app, - "GET", - &format!("/events/{event_id}/attendance"), - Some(&ali), - None + common::items( + &send( + &app, + "GET", + &format!("/events/{event_id}/attendance"), + Some(&ali), + None + ) + .await + .body ) - .await - .body) .len(), 1 ); @@ -902,15 +1272,17 @@ async fn exams_are_course_scoped_and_course_guarded() { 1 ); assert_eq!( - common::items(&send( - &app, - "GET", - &format!("/courses/{course_id}/exams"), - Some(&ali), - None + common::items( + &send( + &app, + "GET", + &format!("/courses/{course_id}/exams"), + Some(&ali), + None + ) + .await + .body ) - .await - .body) .len(), 1 ); @@ -1086,15 +1458,17 @@ async fn grading_upsert_and_own_result() { // Teacher sees the full list (one row). assert_eq!( - common::items(&send( - &app, - "GET", - &format!("/exams/{exam_id}/results"), - Some(&teacher), - None + common::items( + &send( + &app, + "GET", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + None + ) + .await + .body ) - .await - .body) .len(), 1 ); @@ -1693,15 +2067,17 @@ async fn exam_creation_lives_under_courses() { StatusCode::OK ); assert_eq!( - common::items(&send( - &app, - "GET", - &format!("/courses/{course_id}/exams"), - Some(&alice), - None + common::items( + &send( + &app, + "GET", + &format!("/courses/{course_id}/exams"), + Some(&alice), + None + ) + .await + .body ) - .await - .body) .len(), 1 ); @@ -1769,7 +2145,12 @@ async fn grading_requires_enrollment() { StatusCode::BAD_REQUEST ); assert_eq!( - common::items(&send(&app, "GET", &grade_uri, Some(&teacher), None).await.body).len(), + common::items( + &send(&app, "GET", &grade_uri, Some(&teacher), None) + .await + .body + ) + .len(), 1 ); assert_eq!( @@ -3027,15 +3408,17 @@ async fn graders_cannot_grade_themselves() { // And the rejected attempts wrote nothing. assert_eq!( - common::items(&send( - &app, - "GET", - &format!("/exams/{exam_id}/results"), - Some(&teacher), - None + common::items( + &send( + &app, + "GET", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + None + ) + .await + .body ) - .await - .body) .len(), 0 ); @@ -3122,7 +3505,12 @@ async fn promotion_out_of_student_freezes_the_seat() { None, ) .await; - assert_eq!(res.status, StatusCode::CREATED, "student sits: {}", res.body); + assert_eq!( + res.status, + StatusCode::CREATED, + "student sits: {}", + res.body + ); // Promote the enrolled student to teacher; the enrollment row survives. set_role(&db, "veli", "teacher").await; @@ -3336,6 +3724,7 @@ async fn session_cookie_secure_attribute_follows_config() { let db = database::init_mem().await.unwrap(); let app = build_router(AppState { db, + files_path: common::files_dir(), cookie_secure: true, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), exam_presence: Default::default(), @@ -6129,7 +6518,13 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { None, ) .await; - assert_eq!(common::items(&res.body)[0]["choices"].as_array().unwrap().len(), 2); + assert_eq!( + common::items(&res.body)[0]["choices"] + .as_array() + .unwrap() + .len(), + 2 + ); assert_eq!(common::items(&res.body)[0]["correct"], 1); } diff --git a/tests/pagination.rs b/tests/pagination.rs index 3c07d31..aa6bb5c 100644 --- a/tests/pagination.rs +++ b/tests/pagination.rs @@ -60,7 +60,14 @@ async fn envelope_windows_and_total_is_stable() { assert_eq!(total(&res.body), 25); // Past the end — an empty page, not an error, and `total` stays honest. - let res = send(&app, "GET", "/users?limit=10&offset=999", Some(&admin), None).await; + let res = send( + &app, + "GET", + "/users?limit=10&offset=999", + Some(&admin), + None, + ) + .await; assert_eq!(res.status, StatusCode::OK); assert!(items(&res.body).is_empty(), "offset past the end is empty"); assert_eq!(total(&res.body), 25); @@ -140,7 +147,11 @@ async fn user_search_is_paged_not_capped() { // Unpaged: every match comes back — no 10-row ceiling. let res = send(&app, "GET", "/users/search?q=grp", Some(&teacher), None).await; assert_eq!(res.status, StatusCode::OK); - assert_eq!(total(&res.body), 12, "all matches counted, not capped at 10"); + assert_eq!( + total(&res.body), + 12, + "all matches counted, not capped at 10" + ); assert_eq!(items(&res.body).len(), 12); // Windowed like any other list — the tail is the remainder. @@ -156,8 +167,19 @@ async fn user_search_is_paged_not_capped() { assert_eq!(items(&res.body).len(), 2, "offset 10 of 12 leaves 2"); // Paging bounds are enforced, and a blank query is still refused. - let res = send(&app, "GET", "/users/search?q=grp&limit=0", Some(&teacher), None).await; + let res = send( + &app, + "GET", + "/users/search?q=grp&limit=0", + Some(&teacher), + None, + ) + .await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "limit=0 is a 400"); let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await; - assert_eq!(res.status, StatusCode::BAD_REQUEST, "blank q is still a 400"); + assert_eq!( + res.status, + StatusCode::BAD_REQUEST, + "blank q is still a 400" + ); } diff --git a/tests/persistence.rs b/tests/persistence.rs index 8beb7bc..d8a7766 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -36,6 +36,7 @@ fn config_at(dir: &TempDir) -> Config { db_path: dir.path().join("hezarfen.db").to_str().unwrap().to_string(), db_ns: "hezarfen".into(), db_name: "hezarfen".into(), + files_path: dir.path().join("files").to_str().unwrap().to_string(), cookie_secure: false, rate_limit: RateLimitConfig::unlimited(), admin_username: None, @@ -43,9 +44,12 @@ fn config_at(dir: &TempDir) -> Config { } } -fn state(db: Database) -> AppState { +/// Mirror `main`: the blob directory is created at boot, beside the database. +fn state(db: Database, cfg: &Config) -> AppState { + std::fs::create_dir_all(&cfg.files_path).expect("files dir"); AppState { db, + files_path: cfg.files_path.clone().into(), cookie_secure: false, rate_limit: RateLimitConfig::unlimited(), exam_presence: Default::default(), @@ -56,10 +60,9 @@ fn state(db: Database) -> AppState { #[tokio::test] async fn file_engine_runs_full_flow() { let dir = tempfile::tempdir().unwrap(); - let db = database::init(&config_at(&dir)) - .await - .expect("open file db"); - let app = build_router(state(db)); + let cfg = config_at(&dir); + let db = database::init(&cfg).await.expect("open file db"); + let app = build_router(state(db, &cfg)); let creds = json!({ "username": "ali", "password": "secret1" }); assert_eq!( @@ -83,12 +86,7 @@ async fn file_engine_runs_full_flow() { .await; assert_eq!(note.status, StatusCode::CREATED); assert_eq!( - common::items( - &send(&app, "GET", "/notes", Some(&cookie), None) - .await - .body, - ) - .len(), + common::items(&send(&app, "GET", "/notes", Some(&cookie), None).await.body,).len(), 1 ); } @@ -104,7 +102,7 @@ async fn data_survives_reopen() { // First boot: create a user and a note, then drop the handle. { let db = database::init(&cfg).await.expect("first open"); - let app = build_router(state(db)); + let app = build_router(state(db, &cfg)); assert_eq!( send(&app, "POST", "/auth/register", None, Some(creds.clone())) .await @@ -132,7 +130,7 @@ async fn data_survives_reopen() { // Second boot from the same path: the user and note are still there. { let db = reopen(&cfg).await; - let app = build_router(state(db)); + let app = build_router(state(db, &cfg)); let login = send(&app, "POST", "/auth/login", None, Some(creds)).await; assert_eq!(login.status, StatusCode::OK, "user survived reopen"); let cookie = login.cookie.unwrap(); @@ -149,6 +147,63 @@ async fn data_survives_reopen() { } } +/// A note's uploaded file — its metadata row in the database and its blob on +/// disk — comes back after a close + reopen, byte for byte. +#[tokio::test] +async fn note_files_survive_reopen() { + let dir = tempfile::tempdir().unwrap(); + let cfg = config_at(&dir); + let creds = json!({ "username": "ali", "password": "secret1" }); + let bytes = b"%PDF-1.4 persisted".to_vec(); + let file_uri; + + // First boot: create a note and upload a file onto it. + { + let db = database::init(&cfg).await.expect("first open"); + let app = build_router(state(db, &cfg)); + send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; + let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) + .await + .cookie + .unwrap(); + let note = send( + &app, + "POST", + "/notes", + Some(&cookie), + Some(json!({ "title": "with attachment" })), + ) + .await; + let note_id = note.body["id"].as_str().unwrap().to_string(); + let up = common::upload_file( + &app, + &cookie, + ¬e_id, + "plan.pdf", + "application/pdf", + &bytes, + ) + .await; + assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); + file_uri = format!("/notes/{note_id}/files/{}", up.body["id"].as_str().unwrap()); + } + + // Second boot: metadata and bytes are both still there. + { + let db = reopen(&cfg).await; + let app = build_router(state(db, &cfg)); + let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) + .await + .cookie + .unwrap(); + let (status, headers, body) = + common::send_raw(&app, "GET", &file_uri, Some(&cookie), None, Vec::new()).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, bytes, "blob bytes survived reopen"); + assert_eq!(headers["content-type"], "application/pdf"); + } +} + /// Personal info written through `PATCH /users/me` is still on the account /// after a close + reopen. #[tokio::test] @@ -160,7 +215,7 @@ async fn profile_survives_reopen() { // First boot: register and fill in the profile. { let db = database::init(&cfg).await.expect("first open"); - let app = build_router(state(db)); + let app = build_router(state(db, &cfg)); assert_eq!( send(&app, "POST", "/auth/register", None, Some(creds.clone())) .await @@ -191,7 +246,7 @@ async fn profile_survives_reopen() { // Second boot: the info comes back from disk. { let db = reopen(&cfg).await; - let app = build_router(state(db)); + let app = build_router(state(db, &cfg)); let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) .await .cookie @@ -220,7 +275,7 @@ async fn course_marks_survive_reopen() { // course, enrolls the student, grades 80. { let db = database::init(&cfg).await.expect("first open"); - let app = build_router(state(db.clone())); + let app = build_router(state(db.clone(), &cfg)); for creds in [&teacher_creds, &student_creds] { assert_eq!( send(&app, "POST", "/auth/register", None, Some((*creds).clone())) @@ -288,7 +343,7 @@ async fn course_marks_survive_reopen() { // are all rebuilt from disk. { let db = reopen(&cfg).await; - let app = build_router(state(db)); + let app = build_router(state(db, &cfg)); let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) .await .cookie @@ -330,7 +385,7 @@ async fn settings_and_terms_survive_reopen() { let term; { let db = database::init(&cfg).await.expect("open file db"); - let app = build_router(state(db.clone())); + let app = build_router(state(db.clone(), &cfg)); let creds = json!({ "username": "boss", "password": "secret1" }); send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; @@ -380,7 +435,7 @@ async fn settings_and_terms_survive_reopen() { // New handle at the same path — a fresh boot, migration re-applied. let db = reopen(&cfg).await; - let app = build_router(state(db)); + let app = build_router(state(db, &cfg)); let creds = json!({ "username": "boss", "password": "secret1" }); let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) .await diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index 4e22fba..0ed1f7e 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -21,6 +21,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router { let db = database::init_mem().await.expect("in-memory db"); build_router(AppState { db, + files_path: tempfile::tempdir().expect("files dir").keep(), cookie_secure: false, rate_limit, exam_presence: Default::default(), @@ -311,6 +312,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String { let db = database::init_mem().await.expect("in-memory db"); let app = build_router(AppState { db, + files_path: tempfile::tempdir().expect("files dir").keep(), cookie_secure: false, rate_limit, exam_presence: Default::default(),