diff --git a/README.md b/README.md index 61c8c8c..6da6e62 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,13 @@ also carries its own **UI preferences** — theme (`light`/`dark`), language any hex, deliberately not a fixed palette) — self-managed, admin-editable for anyone, `null` until chosen so the client can fall back to the device preference (or, for the accent, its own default). +Every account also has a **public profile** (`/users/{id}/profile`): a +self-chosen `display_name` and `bio`, one **avatar**, the classes and courses +it belongs to, and counters computed at read (finished pomodoro stints, course +and class totals). Contact details are deliberately not part of it — email, +phone and birth date keep the gate they already have — and any authenticated +account reads any profile, except a `parent`, who reads their own and their +linked students' only (see "User profiles & avatars"). The **AI features live in separate projects**, so the backend also opens a QUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in, register the capabilities they serve, and each request rides its own QUIC @@ -318,7 +325,10 @@ response in the same commit. "username_separators": [".", "_", "-"], "reserved_usernames": ["admin", "…"], "min_password_len": 6, "max_password_len": 128, - "max_name_len": 100, "max_email_len": 254, + "max_name_len": 100, "max_display_name_len": 50, + "max_bio_len": 500, + "max_profile_courses": 20, "max_profile_classes": 5, + "max_email_len": 254, "min_phone_digits": 7, "max_phone_digits": 15, "roles": ["parent", "student", "teacher", "manager", "admin"], "themes": ["light", "dark"], "languages": ["tr", "en"], @@ -588,6 +598,7 @@ still left exactly as they stand. | Read another user's homework report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full — statuses/marks/flags, never files | | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields | | Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen — the client then follows the device preference | +| Read any user's **public profile** and avatar; upload/remove **own** avatar | student | A `parent` is the exception: own and linked students' only, the link and the target's live role re-read per call. Removing *another* user's avatar is admin-only moderation | | List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports — a parent changes nothing, anywhere | | 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, the note-file size limit) and the academic calendar are management's call | @@ -721,14 +732,21 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/auth/login` | no | `{username, password}` -> cookie| | POST | `/auth/logout` | no | Clear session (no-op if none) | | GET | `/auth/me` | student | Current user (incl. `role` and personal info) | -| PATCH | `/users/me` | student | Update own personal info (see below) | +| PATCH | `/users/me` | student | Update own personal info, `display_name` and `bio` included (see below) | | PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` — own UI preferences (see below) | +| GET | `/users/me/profile` | student | Own public profile — what everyone else sees of the caller | +| POST | `/users/me/avatar` | student | Upload/replace own avatar: `multipart/form-data`, one `file` part, raster images only, ≤ the school's `max_file_bytes` -> `{content_type, size}` | +| GET | `/users/me/avatar` | student | Own avatar bytes (`404` if there is none) — the self alias of `/users/{id}/avatar` | +| DELETE | `/users/me/avatar` | student | Remove own avatar (`404` if there is none) | | GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) · paged | | GET | `/users/search` | teacher | `?q=&role=` — find users by username/name fragment (pickers); refs only, no contact info · paged | | GET | `/users` | admin | List all users · paged | +| GET | `/users/{id}/profile` | student | Any user's public profile — a `parent` reads only their own and their linked students' (`403`) | +| GET | `/users/{id}/avatar` | student | The avatar bytes (`nosniff`, `private, no-store`); same reach as the profile | +| DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar — the moderation path | | GET | `/users/{id}` | admin | Get one user | | PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll), and a demotion to `parent` also frees their seats on still-open event signup lists | -| PATCH | `/users/{id}/profile` | admin | Update any user's personal info | +| PATCH | `/users/{id}/profile` | admin | Update any user's personal info, `display_name` and `bio` included | | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences | | POST | `/users/{id}/students` | admin | `{user_id}` — tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant | | GET | `/users/{id}/students` | admin | List a parent's linked students · paged | @@ -1068,7 +1086,8 @@ digits plus non-consecutive interior `.`, `_`, `-` separators, starting and ending with a letter or digit (3–32 chars). Staff-looking names (`admin`, `administrator`, `root`, `support`, `system`, `moderator`, `staff`) are rejected at `/auth/register` only — the `ADMIN_USERNAME` bootstrap may still -seed them. +seed them. `display_name` (≤ 50) and `bio` (≤ 500) ride the same two patches +under the same rules, `""` clearing either (see "User profiles & avatars"). UI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`, `palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the same account row and come back on every user response (`/auth/me` included). @@ -1081,6 +1100,101 @@ passes (mixed case in, stored and returned lowercase), so a new frontend palette needs no backend change — `/limits` publishes its pattern rather than a list of colors. +## User profiles & avatars + +The public half of an account: who someone is inside the school, readable by +the school. `GET /users/me/profile` is the caller's own copy of it, +`GET /users/{id}/profile` anyone's, and both return the same document: + +```json +{ + "id": "01J8XZ0K3Q8G7X2M4N5P6R7S8T", + "username": "ada", + "display_name": "Ada Lovelace", + "role": "student", + "bio": "Sınıfın en hızlı pomodorocusu.", + "avatar": { "content_type": "image/png", "size": 20480 }, + "classes": [ { "id": "01J8…", "name": "9-A", "grade": "9" } ], + "courses": [ { "id": "01J8…", "title": "Matematik", "kind": "course" } ], + "stats": { "pomodoro_sessions": 42, "pomodoro_focus_ms": 63000000, + "courses": 7, "classes": 1 } +} +``` + +**Contact fields are absent by design.** `email`, `phone` and `birth_date` are +not on this document at any role — they keep exactly the gate they have today +(`GET /auth/me` for oneself, `GET /users/{id}` for an admin). A school-wide +read surface is not the place to widen where a phone number is reachable. + +**Visibility** is every authenticated account reading every profile, with one +exception: a `parent` reads their own and their currently-linked students', and +nothing else (`403`). Both halves of that grant are re-read on each call — the +link *and* the target's live role — so unlinking a student, or promoting one +out of `student`, stops the reads at once rather than at the next login. + +**`display_name`** resolves in three steps: the stored `display_name`, else the +`"name surname"` join, else `null`. It does **not** replace `name`/`surname` — +those stay the school-office record, and an admin still edits them — and it +deliberately does not enter the user search fold: `/users/search` finds people +by the name the office knows them under, not by a nickname they picked this +morning. `display_name` and `bio` are patched through the ordinary +`PATCH /users/me` (or the admin `PATCH /users/{id}/profile`) with the same +field semantics as the rest: omitted keeps, `""` clears, anything else is +validated. + +**The class and course blocks are a narrowed projection**, not the rows +themselves: id/name/grade for a class, id/title/kind for a course. A class's +`creator` and its homeroom teacher are office data behind the teacher+ +`GET /classes/{id}` and stay there — a profile that carried them would widen +that gate by accident. Both blocks are truncated (20 courses, 5 classes, both +published in `/limits` as `max_profile_courses` / `max_profile_classes`); a +profile is a preview, and `GET /courses/me` and `GET /classes/me` are the full +paged lists. + +**The courses block follows the profile owner's live role**: teacher+ lists the +courses they teach, everyone else the courses they are enrolled in. It is read +off the role, never off the stored `creator`/`teachers` columns, because +ownership here is a live grant and no demotion sweeps those columns — so a +demoted ex-teacher lists what they are enrolled in, like any other student. + +**and it is then cut to what the *reader* may already see**: a course appears +only if the reader would pass the ordinary course-read gate for it +(`GET /courses/{id}` — enrolled, creator, assigned teacher, or manager+). A +course title is not public: a peer who is `403` on the course itself, and gets +an empty `GET /courses`, must not read it off somebody's profile instead. Your +own profile and a manager's read are never cut, since both already see the +whole list, and the 20-course truncation runs *after* the filter, so a reader +gets up to 20 courses they can actually open. `stats.courses` stays the +owner's true total on purpose — it is the motivational counter, a per-reader +number would be meaningless, and a magnitude names no course. One consequence, +by design: a teacher you share nothing with has an empty `courses` block. + +**Stats are computed at read, never stored.** No counter column can drift out +of sync with the rows behind it, and an account with no data reads a true `0` +rather than `null`. Only *finished* pomodoro stints count — a timer left +running is not study time. Exam averages, homework-done rates and attendance +rates are deliberately absent: those tables are indexed for their own reads, so +a per-user aggregate over them is a full table scan, and a profile is far too +cheap a page to pay for one. + +**The avatar** is one picture per account, uploaded as `multipart/form-data` +with the image under a `file` field. Raster types only (`image/png`, +`image/jpeg`, `image/webp`, `image/gif`) — an SVG can carry script, and these +bytes render inline all over the school. The size cap is the school's existing +`max_file_bytes` setting rather than a new knob: one number to raise when a +school wants bigger uploads. Uploading replaces, and the picture it replaced +comes off disk. The owner removes theirs at `DELETE /users/me/avatar`; an admin +removes anyone's at `DELETE /users/{id}/avatar`, the moderation path — an +offensive picture is a school problem. The bytes come back from +`GET /users/{id}/avatar` under the same reach as the profile itself, served +`X-Content-Type-Options: nosniff` and `Cache-Control: private, no-store`; +`GET /users/me/avatar` is the same read for the caller's own picture, so a +client that never learned its own id still has a route. + +There is no `badges` key yet. Auto-earned badges are a planned second pass and +will be added to `stats`' neighborhood additively, so a client written against +today's document keeps working. + ## Appointments Office hours and parent-teacher conferences, booked instead of arranged by diff --git a/src/constant.rs b/src/constant.rs index e6868da..ab942bf 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -29,6 +29,17 @@ pub const MAX_PASSWORD_LEN: usize = 128; pub const MAX_NAME_LEN: usize = 100; +/// Profile fields: the self-chosen name a user is shown under, and the free +/// text under it. +pub const MAX_DISPLAY_NAME_LEN: usize = 50; +pub const MAX_BIO_LEN: usize = 500; + +/// How many course and class references one profile read embeds. A cap on the +/// response, not on membership — the full lists stay at `/courses/me` and +/// `/classes/me`. +pub const MAX_PROFILE_COURSES: usize = 20; +pub const MAX_PROFILE_CLASSES: usize = 5; + /// RFC 5321's practical upper bound for a full address. pub const MAX_EMAIL_LEN: usize = 254; diff --git a/src/domain/course.rs b/src/domain/course.rs index b5cc8bd..05968db 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -244,6 +244,19 @@ impl Course { /// The courses `user` runs — the ones they created plus the ones a manager /// assigned them to. A teacher's slice of the catalog. + /// + /// ponytail: unpaged full table scan, and it stays one — every profile read + /// of a teacher pays it, so the ceiling is the course table's size. It + /// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone + /// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the + /// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is + /// *wrong*, not merely useless — with it, `$usr IN teachers` and + /// `teachers CONTAINS $usr` return **no rows at all**, which is what the + /// integration test `assigned_teacher_manages_course_without_owning_it` + /// catches. A plain `FIELDS teachers` index is correct but unused. The + /// upgrade path is structural: a `course_teacher` link table indexed on + /// `user`, the shape `enrollment` already has, turning this into two + /// index-backed reads. pub async fn list_for_teacher(user: &UserId, db: &Database) -> Result, AppError> { let mut result = db .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC") diff --git a/src/domain/pomodoro.rs b/src/domain/pomodoro.rs index 537e5c2..8fe024c 100644 --- a/src/domain/pomodoro.rs +++ b/src/domain/pomodoro.rs @@ -107,6 +107,15 @@ impl PomodoroSession { /// `CREATE` cannot answer "already exists" on the way back — the table /// carries no `UNIQUE` index and `$closed` is one freshly minted ULID. /// Only the guard's own `THROW` is a decision, and it stays a 409. + /// + /// `finished_at` is floored at the row's own `started_at`. Both stamps come + /// from [`Timestamp::now`], i.e. the wall clock, which an NTP step can move + /// *backwards* mid-stint — so a close can legitimately read earlier than its + /// own start with nothing wrong on the client's side. Refusing it would lose + /// a real study session and leave the open slot wedged for a fault the + /// student did not cause; recording a zero-length stint keeps the session + /// count honest and its duration merely understated. Nothing downstream may + /// then read a negative duration (`ProfileStats::load` sums these). pub async fn finish(user: &UserId, db: &Database) -> Result { let (mut result, mut errors) = transaction_with_retry( db, @@ -116,7 +125,7 @@ impl PomodoroSession { CREATE $closed CONTENT { user: $before[0].user, started_at: $before[0].started_at, - finished_at: $done, + finished_at: math::max([$before[0].started_at, $done]), }; COMMIT TRANSACTION;", &[ @@ -212,4 +221,32 @@ mod tests { let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap(); assert_eq!(sessions.len(), 2); } + + #[tokio::test] + async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() { + let db = database::init_mem().await.unwrap(); + let user = UserId::from_key(&Ulid::new().to_string()); + + PomodoroSession::start(&user, &db).await.unwrap(); + // Stand in for the NTP step: push the running stint's start an hour + // ahead, so the server clock `finish` reads is *behind* it. + db.query("UPDATE $open SET started_at = $future") + .bind(("open", PomodoroSessionId::open_for(&user).record())) + .bind(("future", Timestamp::now().as_millis() + 3_600_000)) + .await + .unwrap() + .check() + .unwrap(); + + let closed = PomodoroSession::finish(&user, &db).await.unwrap(); + let started = closed.get_started_at().as_millis(); + assert_eq!(closed.get_finished_at().unwrap().as_millis(), started); + + // And the stat that sums these stays non-negative. + let stats = crate::domain::profile::ProfileStats::load(&user, 0, 0, &db) + .await + .unwrap(); + assert_eq!(stats.get_pomodoro_sessions(), 1); + assert_eq!(stats.get_pomodoro_focus_ms(), 0); + } } diff --git a/src/domain/profile.rs b/src/domain/profile.rs index 02dd0af..d106c17 100644 --- a/src/domain/profile.rs +++ b/src/domain/profile.rs @@ -3,10 +3,12 @@ use surrealdb::types::SurrealValue; -use crate::constant::MAX_NAME_LEN; +use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN}; +use crate::database::Database; use crate::domain::timestamp::Timestamp; -use crate::error::ValidationError; -use crate::validate::{validate_email, validate_phone, validate_required}; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_email, validate_optional, validate_phone, validate_required}; /// A person's given or family name. One type serves both fields — the `field` /// tag only steers the error message ("name …" vs "surname …"). Stored trimmed; @@ -92,6 +94,122 @@ impl BirthDate { } } +/// The name a profile shows instead of the legal one — a nickname, a shortened +/// form, whatever the person answers to. Stored trimmed; unicode is welcome, +/// same as [`PersonName`] and unlike the ASCII-only username. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct DisplayName(String); + +impl DisplayName { + pub fn try_new(value: &str) -> Result { + validate_required("display_name", value, MAX_DISPLAY_NAME_LEN)?; + Ok(Self(value.trim().to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A short self-description on the public profile. Free text within +/// [`MAX_BIO_LEN`], blank allowed — an empty bio is a written-then-erased one, +/// which is a legitimate state and not an error. Stored trimmed. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct Bio(String); + +impl Bio { + pub fn try_new(value: &str) -> Result { + validate_optional("bio", value, MAX_BIO_LEN)?; + Ok(Self(value.trim().to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// The motivational counters on a public profile. Every field is a derived +/// count, never a settable one: zero rows is a true zero, so these are `i64` +/// and never `Option` — a `null` in this API means "never chose", which a +/// derived number can't be. An account that predates the feature therefore +/// reads exactly like a fresh one. +/// +/// One named struct on purpose: the auto-earned badge rules take a whole +/// `ProfileStats` as their sole input, so a counter added here reaches them +/// without touching a signature. +#[derive(Debug, Clone, SurrealValue)] +pub struct ProfileStats { + pomodoro_sessions: i64, + pomodoro_focus_ms: i64, + courses: i64, + classes: i64, +} + +impl ProfileStats { + pub fn get_pomodoro_sessions(&self) -> i64 { + self.pomodoro_sessions + } + + pub fn get_pomodoro_focus_ms(&self) -> i64 { + self.pomodoro_focus_ms + } + + pub fn get_courses(&self) -> i64 { + self.courses + } + + pub fn get_classes(&self) -> i64 { + self.classes + } + + /// One query, and only one: `courses` and `classes` arrive from the caller, + /// which already holds them as the `total` of the paged class and course + /// readers it ran for the profile's own blocks — re-counting them here + /// would be two extra reads for numbers already in hand. + /// + /// The pomodoro aggregate rides the per-user index, so it is a lookup and + /// not a scan. `finished_at != NONE` is the filter because NONE is falsy: a + /// bare truthiness test would also drop a stint that finished at epoch. An + /// open stint contributes to neither the count nor the sum — unfinished + /// focus has no honest duration to add. + pub async fn load( + user: &UserId, + courses: i64, + classes: i64, + db: &Database, + ) -> Result { + let mut result = db + .query( + "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms + FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL", + ) + .bind(("usr", user.record())) + .await? + .check()?; + // `GROUP ALL` yields no row at all when nothing matched — that is the + // zero case, not a missing one. + let row = result.take::>(0)?.into_iter().next(); + Ok(ProfileStats { + pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions), + // Floored at zero: a stint stamped by a wall clock that stepped + // backwards mid-session sums as negative time, and "you focused for + // minus five seconds" is never the truthful answer. New stints + // cannot go inverted (see [`PomodoroSession::finish`]); rows written + // before that guard still can, and this is what covers them. + pomodoro_focus_ms: row.map_or(0, |totals| totals.focus_ms.max(0)), + courses, + classes, + }) + } +} + +/// The aggregate row of [`ProfileStats::load`]. +#[derive(Debug, SurrealValue)] +struct PomodoroTotals { + sessions: i64, + focus_ms: i64, +} + #[cfg(test)] mod tests { use super::*; @@ -156,4 +274,89 @@ mod tests { let two_days_out = today.succ_opt().unwrap().succ_opt().unwrap(); assert!(BirthDate::try_new(&fmt(two_days_out)).is_err()); } + + #[tokio::test] + async fn display_name_trims_and_validates() { + assert_eq!(DisplayName::try_new(" Ada ").unwrap().as_str(), "Ada"); + // A display name is a name, not a username: unicode passes. + assert_eq!( + DisplayName::try_new("Gümüş 🐢").unwrap().as_str(), + "Gümüş 🐢" + ); + assert!(DisplayName::try_new(" ").is_err()); + assert!(DisplayName::try_new(&"x".repeat(MAX_DISPLAY_NAME_LEN + 1)).is_err()); + } + + #[tokio::test] + async fn bio_trims_and_validates() { + assert_eq!(Bio::try_new(" hello ").unwrap().as_str(), "hello"); + // Blank is a legitimate bio (erased), unlike a blank display name. + assert_eq!(Bio::try_new(" ").unwrap().as_str(), ""); + assert!(Bio::try_new(&"é".repeat(MAX_BIO_LEN)).is_ok()); + assert!(Bio::try_new(&"é".repeat(MAX_BIO_LEN + 1)).is_err()); + } + + #[tokio::test] + async fn stats_are_zero_without_pomodoro_rows() { + let db = crate::database::init_mem().await.unwrap(); + let user = UserId::from_key(&ulid::Ulid::new().to_string()); + + let stats = ProfileStats::load(&user, 3, 1, &db).await.unwrap(); + // Derived counters: no rows is a true zero, never a null. + assert_eq!(stats.get_pomodoro_sessions(), 0); + assert_eq!(stats.get_pomodoro_focus_ms(), 0); + // The passed-in counts survive untouched. + assert_eq!(stats.get_courses(), 3); + assert_eq!(stats.get_classes(), 1); + } + + #[tokio::test] + async fn stats_count_finished_stints_only() { + let db = crate::database::init_mem().await.unwrap(); + let user = UserId::from_key(&ulid::Ulid::new().to_string()); + let other = UserId::from_key(&ulid::Ulid::new().to_string()); + + // Two finished stints (1000 ms + 2500 ms), one still running, and one + // finished stint belonging to somebody else. + db.query( + "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; + CREATE pomodoro_session CONTENT { user: $usr, started_at: 5000, finished_at: 7500 }; + CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000 }; + CREATE pomodoro_session CONTENT { user: $oth, started_at: 0, finished_at: 60000 };", + ) + .bind(("usr", user.record())) + .bind(("oth", other.record())) + .await + .unwrap() + .check() + .unwrap(); + + let stats = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); + assert_eq!(stats.get_pomodoro_sessions(), 2); + assert_eq!(stats.get_pomodoro_focus_ms(), 3500); + } + + #[tokio::test] + async fn focus_time_never_reads_negative() { + let db = crate::database::init_mem().await.unwrap(); + let user = UserId::from_key(&ulid::Ulid::new().to_string()); + + // One honest 1000 ms stint and one inverted row — what a backwards + // clock step left behind before `finish` grew its floor. The raw sum is + // -5000; the profile must still answer a duration, not an accusation. + db.query( + "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; + CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000, finished_at: 3000 };", + ) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + + let stats = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); + // The stints still happened, so the count is honest at 2. + assert_eq!(stats.get_pomodoro_sessions(), 2); + assert_eq!(stats.get_pomodoro_focus_ms(), 0); + } } diff --git a/src/domain/user.rs b/src/domain/user.rs index 7722f85..e4e0a79 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -9,13 +9,14 @@ use crate::constant::{ DECOY_PASSWORD, ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, PARENT_LINK_TABLE, REGISTRATION_COUNT_FIELD, REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE, }; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, transaction_with_retry, write_with_retry}; use crate::domain::board::Board; use crate::domain::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; +use crate::domain::note_file::FileContentType; use crate::domain::page::PagedList; use crate::domain::preferences::{Language, PaletteColor, Theme}; -use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; +use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; use crate::domain::role::Role; use crate::domain::text_fold::{search_fold, search_fold_sql}; use crate::domain::timestamp::Timestamp; @@ -216,6 +217,17 @@ pub struct User { theme: Option, language: Option, palette_color: Option, + // The public profile: what other people see instead of the credentials. + // Optional like everything above — a profile is written after the account + // exists, so rows from before these fields existed read back as `None`, + // which is exactly a fresh account that never filled one in. The avatar is + // a blob on disk (`FILES_PATH`) like every other upload; only its name, + // type and size live on the row. + display_name: Option, + bio: Option, + avatar_file: Option, + avatar_content_type: Option, + avatar_size: Option, } impl User { @@ -267,6 +279,26 @@ impl User { self.palette_color.as_ref() } + pub fn get_display_name(&self) -> Option<&DisplayName> { + self.display_name.as_ref() + } + + pub fn get_bio(&self) -> Option<&Bio> { + self.bio.as_ref() + } + + pub fn get_avatar_file(&self) -> Option<&str> { + self.avatar_file.as_deref() + } + + pub fn get_avatar_content_type(&self) -> Option<&FileContentType> { + self.avatar_content_type.as_ref() + } + + pub fn get_avatar_size(&self) -> Option { + self.avatar_size + } + /// Register a new account. New users always start as [`Role::Student`]; /// elevation is a separate, admin-only action (see [`User::set_role`]). pub async fn create( @@ -308,6 +340,11 @@ impl User { theme: None, language: None, palette_color: None, + display_name: None, + bio: None, + avatar_file: None, + avatar_content_type: None, + avatar_size: None, }; let created: Result, surrealdb::Error> = db.create(user.id.record()).content(user.clone()).await; @@ -594,7 +631,9 @@ impl User { Ok((updated, boards)) } - /// Write the personal-info fields the request actually carried. Every + /// Write the personal-info and public-profile fields the request actually + /// carried — everything a person edits about themselves except the avatar + /// blob, which needs its own writer ([`User::set_avatar`]). Every /// column is nullable, so each argument is an outer/inner `Option`: `None` /// = omitted (not written at all), `Some(None)` = cleared, `Some(Some(v))` /// = set. Merging the request against the current row is the HTTP layer's @@ -605,6 +644,10 @@ impl User { /// for an omitted field would revert a concurrent PATCH of that field — /// two profile edits (a name and a phone) used to lose each other. See /// [`User::set_role`] for why no writer here touches the whole row. + // One argument per nullable column is the point: folding them into a struct + // would just re-spell the HTTP DTO here and cost the compiler's check that + // every column was considered at the call site. + #[allow(clippy::too_many_arguments)] pub async fn set_profile( self, name: Option>, @@ -612,6 +655,8 @@ impl User { email: Option>, phone: Option>, birth_date: Option>, + display_name: Option>, + bio: Option>, db: &Database, ) -> Result { FieldUpdate::new(self.id.record()) @@ -620,10 +665,60 @@ impl User { .set("email", email) .set("phone", phone) .set("birth_date", birth_date) + .set("display_name", display_name) + .set("bio", bio) .run::(db) .await } + /// Point the row at a freshly uploaded avatar blob, returning the row *as + /// it was* — the caller deletes `before.get_avatar_file()` off disk. Losing + /// `RETURN BEFORE` here strands the replaced blob forever: no route ever + /// deletes a user, so nothing else would collect it. + /// + /// Field-scoped for the same reason as [`User::set_profile`]: an avatar + /// upload must not carry a stale snapshot's role back over an admin's + /// change. `None` means the row is gone. + /// + /// Sent through [`write_with_retry`] like every other single-statement row + /// write here, unguarded or not: the user row is contended (preferences, + /// profile, role all write it), and a lost round wrote nothing, so + /// re-sending it is the recovery rather than a 500 in the caller's face. + pub async fn set_avatar( + id: &UserId, + file: &str, + content_type: &FileContentType, + size: i64, + db: &Database, + ) -> Result, AppError> { + let rows: Vec = write_with_retry( + db, + "UPDATE $u SET avatar_file = $file, avatar_content_type = $ct, avatar_size = $size \ + RETURN BEFORE", + &[ + ("u".into(), id.record().into_value()), + ("file".into(), file.to_string().into_value()), + ("ct".into(), content_type.clone().into_value()), + ("size".into(), size.into_value()), + ], + ) + .await?; + Ok(rows.into_iter().next()) + } + + /// Drop the avatar, returning the row as it was so the caller can delete + /// the blob. Same `RETURN BEFORE` contract as [`User::set_avatar`]. + pub async fn clear_avatar(id: &UserId, db: &Database) -> Result, AppError> { + let rows: Vec = write_with_retry( + db, + "UPDATE $u SET avatar_file = NONE, avatar_content_type = NONE, \ + avatar_size = NONE RETURN BEFORE", + &[("u".into(), id.record().into_value())], + ) + .await?; + Ok(rows.into_iter().next()) + } + /// Write the UI-preference fields the request actually carried. Same /// contract as [`User::set_profile`]: `None` = omitted (not written), /// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set. @@ -734,7 +829,16 @@ mod tests { // admin's change. let name = PersonName::try_new("name", "Ayşenur").unwrap(); stale - .set_profile(Some(Some(name.clone())), None, None, None, None, &db) + .set_profile( + Some(Some(name.clone())), + None, + None, + None, + None, + None, + None, + &db, + ) .await .unwrap(); @@ -751,6 +855,121 @@ mod tests { ); } + fn png() -> FileContentType { + FileContentType::try_new("image/png").unwrap() + } + + async fn a_user(username: &str, db: &Database) -> User { + User::create( + Username::try_new(username).unwrap(), + Password::try_new("secret1").unwrap().hash().unwrap(), + db, + ) + .await + .unwrap() + } + + #[tokio::test] + async fn an_avatar_upload_cannot_revert_a_role_change() { + let db = init_mem().await.unwrap(); + let user = a_user("berk", &db).await; + + // The upload handler holds its snapshot (role = student)... + let stale = User::read(user.get_id(), &db).await.unwrap().unwrap(); + + // ...an admin promotes and the person edits their bio, both while the + // blob is still being written... + User::read(user.get_id(), &db) + .await + .unwrap() + .unwrap() + .set_role(Role::Teacher, &db) + .await + .unwrap(); + let display_name = DisplayName::try_new("Berk").unwrap(); + User::read(user.get_id(), &db) + .await + .unwrap() + .unwrap() + .set_profile( + None, + None, + None, + None, + None, + Some(Some(display_name.clone())), + None, + &db, + ) + .await + .unwrap(); + + // ...and only then does the avatar land, from the stale row's id. + User::set_avatar(stale.get_id(), "blob-1", &png(), 42, &db) + .await + .unwrap() + .expect("the row exists"); + + let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); + assert_eq!( + after.get_role(), + Role::Teacher, + "the role change must survive the racing avatar write" + ); + assert_eq!( + after.get_display_name(), + Some(&display_name), + "and so must every other column the avatar write never named" + ); + assert_eq!(after.get_avatar_file(), Some("blob-1")); + assert_eq!(after.get_avatar_content_type(), Some(&png())); + assert_eq!(after.get_avatar_size(), Some(42)); + } + + /// The blob cleanup is built entirely on `RETURN BEFORE`: without the old + /// `avatar_file` coming back, every replace strands a file on disk that no + /// route ever collects. + #[tokio::test] + async fn the_avatar_writers_return_the_replaced_blob() { + let db = init_mem().await.unwrap(); + let user = a_user("ceyda", &db).await; + + let before = User::set_avatar(user.get_id(), "blob-1", &png(), 10, &db) + .await + .unwrap() + .expect("the row exists"); + assert_eq!(before.get_avatar_file(), None, "no blob to collect yet"); + + let before = User::set_avatar(user.get_id(), "blob-2", &png(), 20, &db) + .await + .unwrap() + .expect("the row exists"); + assert_eq!( + before.get_avatar_file(), + Some("blob-1"), + "the replaced blob is what the caller must delete" + ); + + let before = User::clear_avatar(user.get_id(), &db) + .await + .unwrap() + .expect("the row exists"); + assert_eq!(before.get_avatar_file(), Some("blob-2")); + + let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(after.get_avatar_file(), None); + assert_eq!(after.get_avatar_content_type(), None); + assert_eq!(after.get_avatar_size(), None); + + assert!( + User::clear_avatar(&UserId::from_key("yok"), &db) + .await + .unwrap() + .is_none(), + "a missing row is None, not an error" + ); + } + #[tokio::test] async fn username_newtype_validates() { assert_eq!(Username::try_new("ali").unwrap().as_str(), "ali"); diff --git a/src/lib.rs b/src/lib.rs index dcf3449..df487a7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,7 +44,7 @@ use crate::state::AppState; (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is a claimed job rather than an in-process task: whichever backend process holds a `chat.reply` worker picks it up (within ~200ms), dispatches it and stamps the result, so a restart no longer strands an accepted turn and a claim its owner never finishes is retried after 90 seconds. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), - (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"), + (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), and stats computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts; `0`, never `null`). Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter, and `stats.courses` stays the owner's true total either way. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), (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 = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), diff --git a/src/migration_sql.rs b/src/migration_sql.rs index e7e257e..30221ef 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -58,6 +58,11 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS theme ON user TYPE option; DEFINE FIELD IF NOT EXISTS language ON user TYPE option; DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option; + DEFINE FIELD IF NOT EXISTS display_name ON user TYPE option; + DEFINE FIELD IF NOT EXISTS bio ON user TYPE option; + DEFINE FIELD IF NOT EXISTS avatar_file ON user TYPE option; + DEFINE FIELD IF NOT EXISTS avatar_content_type ON user TYPE option; + DEFINE FIELD IF NOT EXISTS avatar_size ON user TYPE option; DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option; DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option; DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; diff --git a/src/web/dto.rs b/src/web/dto.rs index cbe2c6a..2ff241a 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -140,6 +140,14 @@ pub struct UserResponse { /// never chosen — the client should fall back to its default accent. #[schema(example = "#fefae0")] pub palette_color: Option, + /// The name the public profile is shown under, instead of the legal one. + /// `null` = never chosen; unlike [`PersonRef::display_name`] this is the + /// stored column, never a fallback to `"Name Surname"`. + #[schema(example = "Ada")] + pub display_name: Option, + /// Free text under the profile's name; `null` when unset. + #[schema(example = "Sınıfın en hızlı pomodorocusu.")] + pub bio: Option, } impl UserResponse { @@ -156,6 +164,8 @@ impl UserResponse { theme: user.get_theme().map(|v| v.as_str().to_string()), language: user.get_language().map(|v| v.as_str().to_string()), palette_color: user.get_palette_color().map(|v| v.as_str().to_string()), + display_name: user.get_display_name().map(|v| v.as_str().to_string()), + bio: user.get_bio().map(|v| v.as_str().to_string()), } } } diff --git a/src/web/limits.rs b/src/web/limits.rs index a49edbe..aa87ccc 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -39,6 +39,15 @@ struct UserLimits { min_password_len: usize, max_password_len: usize, max_name_len: usize, + /// The self-chosen name a user's profile is shown under. + max_display_name_len: usize, + /// Free text under a profile's name. + max_bio_len: usize, + /// How many course references a profile read embeds — a cap on the + /// response, not on membership. The full list stays at `/courses/me`. + max_profile_courses: usize, + /// Same, for classes; the full list stays at `/classes/me`. + max_profile_classes: usize, max_email_len: usize, /// Digit count, ignoring spaces and punctuation. min_phone_digits: usize, @@ -388,6 +397,10 @@ impl LimitsResponse { min_password_len: MIN_PASSWORD_LEN, max_password_len: MAX_PASSWORD_LEN, max_name_len: MAX_NAME_LEN, + max_display_name_len: MAX_DISPLAY_NAME_LEN, + max_bio_len: MAX_BIO_LEN, + max_profile_courses: MAX_PROFILE_COURSES, + max_profile_classes: MAX_PROFILE_CLASSES, max_email_len: MAX_EMAIL_LEN, min_phone_digits: MIN_PHONE_DIGITS, max_phone_digits: MAX_PHONE_DIGITS, diff --git a/src/web/users.rs b/src/web/users.rs index 1fedee7..27e4a70 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -1,24 +1,34 @@ use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; use axum::http::StatusCode; +use axum::response::Response; use serde::{Deserialize, Serialize}; use serde_json::json; use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +use crate::constant::{ + MAX_MAX_FILE_BYTES, MAX_PROFILE_CLASSES, MAX_PROFILE_COURSES, UPLOAD_BODY_OVERHEAD_BYTES, +}; use crate::database::Database; +use crate::domain::class_group::{ClassGroup, ClassGroupId}; +use crate::domain::class_member::ClassMember; +use crate::domain::course::Course; use crate::domain::parent_link::ParentLink; use crate::domain::preferences::{Language, PaletteColor, Theme}; -use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; +use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats}; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; +use super::courses::visible_courses; use super::dto::Role as RoleSchema; use super::{ - CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UserResponse, paginate, + CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UploadFileForm, + UserResponse, ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob, + store_blob, }; pub fn routes() -> OpenApiRouter { @@ -27,13 +37,26 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(update_my_profile)) .routes(routes!(update_my_preferences)) .routes(routes!(my_students)) + .routes(routes!(my_profile)) .routes(routes!(search_users)) .routes(routes!(get_user)) .routes(routes!(set_role)) - .routes(routes!(update_user_profile)) + .routes(routes!(update_user_profile, get_user_profile)) .routes(routes!(update_user_preferences)) .routes(routes!(link_student, list_parent_students)) .routes(routes!(unlink_student)) + // The avatar routes get their own HTTP body cap, like the note-file and + // question-image ones: the server-wide hard ceiling plus multipart + // framing headroom. It must stay on this sub-router — on the whole + // `/users` router every JSON endpoint would start accepting 25 MB. + .merge( + OpenApiRouter::new() + .routes(routes!(upload_my_avatar, get_my_avatar, delete_my_avatar)) + .routes(routes!(get_avatar, delete_avatar)) + .layer(DefaultBodyLimit::max( + MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, + )), + ) } #[derive(Deserialize, ToSchema)] @@ -61,6 +84,12 @@ struct UpdateProfile { /// Birth date in `YYYY-MM-DD` form. #[schema(example = "1990-01-02")] birth_date: Option, + /// The name the public profile is shown under, instead of the legal one. + #[schema(example = "Ada", max_length = 50)] + display_name: Option, + /// Free text under the profile's name. + #[schema(example = "Sınıfın en hızlı pomodorocusu.", max_length = 500)] + bio: Option, } /// Partial UI-preference update. Same field semantics as [`UpdateProfile`]: @@ -112,8 +141,19 @@ async fn apply_profile( let email = merge_field(req.email.as_deref(), Email::try_new)?; let phone = merge_field(req.phone.as_deref(), Phone::try_new)?; let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?; + let display_name = merge_field(req.display_name.as_deref(), DisplayName::try_new)?; + let bio = merge_field(req.bio.as_deref(), Bio::try_new)?; let updated = user - .set_profile(name, surname, email, phone, birth_date, db) + .set_profile( + name, + surname, + email, + phone, + birth_date, + display_name, + bio, + db, + ) .await?; Ok(UserResponse::new(&updated)) } @@ -222,8 +262,10 @@ async fn list_users( } /// Update the caller's own personal info: name, surname, email, phone, birth -/// date. Any authenticated role. Omitted fields stay as they are; an empty -/// string clears a field. +/// date, plus the public-profile pair `display_name` and `bio` (both readable +/// school-wide at `GET /users/{id}/profile`, unlike the contact fields). Any +/// authenticated role. Omitted fields stay as they are; an empty string clears +/// a field. #[utoipa::path( patch, path = "/me", @@ -615,3 +657,420 @@ async fn my_students( } Ok(Json(students_page(user.get_id(), page, &st.db).await?)) } + +// ---- the public profile ----------------------------------------------------- +// The school-wide read half of a user row: who they are, what they belong to, +// and the counters that motivate. Deliberately *not* `UserResponse` — that one +// carries email, phone, and birth date, which keep exactly the gate they have +// today (self, teacher+, admin). Nothing here widens where they are reachable. + +/// A user's public profile. Contact details are not part of it, at any role. +#[derive(Serialize, ToSchema)] +struct ProfileResponse { + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + id: String, + #[schema(example = "ada")] + username: String, + /// The self-chosen `display_name`, falling back to `"Name Surname"`, then + /// `null` when the row carries neither. + #[schema(example = "Ada Lovelace")] + display_name: Option, + role: RoleSchema, + #[schema(example = "Sınıfın en hızlı pomodorocusu.")] + bio: Option, + /// Present only once a picture is uploaded; the bytes are at + /// `GET /users/{id}/avatar`. + avatar: Option, + /// At most `max_profile_classes` sections — the full list is at + /// `GET /classes/me`. + classes: Vec, + /// At most `max_profile_courses` courses, and only the ones the *reader* + /// may already read at `GET /courses/{id}` — a stranger sees an empty + /// block, the owner and manager+ see it whole. The full list is at + /// `GET /courses/me`. + courses: Vec, + stats: ProfileStatsResponse, +} + +/// What a stored avatar is, without its bytes. +#[derive(Serialize, ToSchema)] +struct ProfileAvatar { + #[schema(example = "image/png")] + content_type: String, + /// Size in bytes. + #[schema(example = 20_480)] + size: i64, +} + +/// A class section as a profile shows it: the label, and nothing about who runs +/// it. The office-side view (creator, homeroom teacher) stays behind +/// `GET /classes/{id}`, which is teacher+. +#[derive(Serialize, ToSchema)] +struct ProfileClassRef { + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + id: String, + #[schema(example = "9-A")] + name: String, + #[schema(example = "9")] + grade: Option, +} + +/// A course as a profile shows it — a label, nothing more. +#[derive(Serialize, ToSchema)] +struct ProfileCourseRef { + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + id: String, + #[schema(example = "Matematik")] + title: String, + /// `course`, `study` (etüt), or `club` (kulüp). + #[schema(example = "course")] + kind: String, +} + +/// The motivational counters. Derived, never settable, and never `null`: an +/// account with no rows behind a counter reads a true `0`. +#[derive(Serialize, ToSchema)] +struct ProfileStatsResponse { + /// Finished pomodoro stints; an open one counts for nothing. + pomodoro_sessions: i64, + /// Total focused milliseconds across those stints. + pomodoro_focus_ms: i64, + /// Every course behind the `courses` block, not just the embedded window. + courses: i64, + /// Every class behind the `classes` block, not just the embedded window. + classes: i64, +} + +/// Build one profile as `viewer` may see it. The course block is chosen off the +/// owner's **live** role, not off the `creator`/`teachers` columns: those are +/// historical and no demotion sweeps them, so a demoted ex-teacher lists what +/// they are enrolled in, like any other student. +/// +/// A course carries a title, and `GET /courses/{id}` hands that title only to +/// the enrolled, the staff who run it, and manager+ — so the block is +/// intersected with [`visible_courses`], the same catalog `GET /courses` +/// serves. Nothing here crosses a gate the viewer would fail directly. Reading +/// your own profile, or reading as manager+, needs no intersection: both +/// already see the whole list. `stats.courses` stays the owner's true total — +/// it is the motivational counter, and a magnitude names no course. +async fn profile_of( + st: &AppState, + user: &User, + viewer: &User, +) -> Result { + let id = user.get_id(); + // One catalog read per request, never one authorization call per course. + let readable = match viewer.get_id() == id || viewer.get_role().at_least(Role::Manager) { + true => None, + false => Some( + visible_courses(viewer, &st.db) + .await? + .iter() + .map(|course| course.get_id().clone()) + .collect::>(), + ), + }; + // The window is cut after the intersection, so a filtered viewer still gets + // up to `MAX_PROFILE_COURSES` courses they can actually see. + let (mut courses, course_total) = match user.get_role().at_least(Role::Teacher) { + // The teacher read is unpaged, so the total is what came back. + true => { + let courses = Course::list_for_teacher(id, &st.db).await?; + let total = courses.len() as i64; + (courses, total) + } + // Unfiltered readers can take the window from the database. + false => { + let window = readable.is_none().then_some(MAX_PROFILE_COURSES as i64); + Course::list_enrolled(id, window, 0, &st.db).await? + } + }; + if let Some(readable) = &readable { + courses.retain(|course| readable.contains(course.get_id())); + } + courses.truncate(MAX_PROFILE_COURSES); + let (members, class_total) = + ClassMember::list_for_user(id, Some(MAX_PROFILE_CLASSES as i64), 0, &st.db).await?; + let class_ids: Vec = members.iter().map(|row| row.get_class().clone()).collect(); + let classes = ClassGroup::list_by_ids(&class_ids, &st.db).await?; + // Both totals are the full counts, not the windowed ones — the blocks are a + // preview, the stats are the truth. + let stats = ProfileStats::load(id, course_total, class_total, &st.db).await?; + Ok(ProfileResponse { + id: id.key().to_string(), + username: user.get_username().as_str().to_string(), + display_name: user + .get_display_name() + .map(|name| name.as_str().to_string()) + // The legal-name join lives in `PersonRef` — one spelling of it. + .or_else(|| PersonRef::new(user).display_name), + role: user.get_role().into(), + bio: user.get_bio().map(|bio| bio.as_str().to_string()), + avatar: user + .get_avatar_content_type() + .map(|content_type| ProfileAvatar { + content_type: content_type.as_str().to_string(), + size: user.get_avatar_size().unwrap_or_default(), + }), + classes: classes + .iter() + .map(|class| ProfileClassRef { + id: class.get_id().key().to_string(), + name: class.get_name().as_str().to_string(), + grade: class.get_grade().map(|grade| grade.as_str().to_string()), + }) + .collect(), + courses: courses + .iter() + .map(|course| ProfileCourseRef { + id: course.get_id().key().to_string(), + title: course.get_title().as_str().to_string(), + kind: course.get_kind().as_str().to_string(), + }) + .collect(), + stats: ProfileStatsResponse { + pomodoro_sessions: stats.get_pomodoro_sessions(), + pomodoro_focus_ms: stats.get_pomodoro_focus_ms(), + courses: stats.get_courses(), + classes: stats.get_classes(), + }, + }) +} + +/// The profile gate: any authenticated account reads any profile — except a +/// parent, who is an observer of their own children and of nobody else. The +/// link alone is not the grant either; [`ensure_can_observe`] re-reads the +/// target's live role, so a student who was promoted out stops being readable. +async fn ensure_may_read_profile( + caller: &User, + target: &UserId, + db: &Database, +) -> Result<(), AppError> { + if caller.get_role() == Role::Parent && caller.get_id() != target { + ensure_can_observe(caller, target, db).await?; + } + Ok(()) +} + +/// The target's row, 404 if it is gone, once the caller is allowed to see it. +async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result { + let target = UserId::from_key(id); + ensure_may_read_profile(caller, &target, &st.db).await?; + User::read(&target, &st.db).await?.ok_or(AppError::NotFound) +} + +/// The caller's own public profile — what everyone else sees of them. +#[utoipa::path( + get, + path = "/me/profile", + tag = "users", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The caller's profile", body = ProfileResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn my_profile( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result, AppError> { + Ok(Json(profile_of(&st, &user, &user).await?)) +} + +/// One user's public profile: display name, bio, avatar meta, their class and +/// course blocks, and the motivational counters. Readable by every +/// authenticated account — except a parent, who reads only their own and their +/// linked students'. Never carries email, phone, or birth date; those stay on +/// `GET /users/{id}` (admin) and `GET /auth/me`. The embedded blocks are capped +/// at `max_profile_classes` / `max_profile_courses` (see `GET /limits`) — the +/// full paged lists are `GET /classes/me` and `GET /courses/me`. The course +/// block is also cut to what the *reader* may already see: only courses they +/// would pass `GET /courses/{id}` on. `stats.courses` stays the owner's true +/// total either way. +#[utoipa::path( + get, + path = "/{id}/profile", + tag = "users", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "User id")), + responses( + (status = 200, description = "The user's profile", body = ProfileResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "A parent without a link to this student", body = ErrorResponse), + (status = 404, description = "User not found", body = ErrorResponse), + ), +)] +async fn get_user_profile( + State(st): State, + CurrentUser(caller): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let target = readable_profile_user(&st, &caller, &id).await?; + Ok(Json(profile_of(&st, &target, &caller).await?)) +} + +// ---- the avatar ------------------------------------------------------------- +// One optional picture per user, the same one-image-on-the-owning-row shape the +// question pool uses: bytes on disk under a server-generated ULID, metadata on +// the user row. Every write here must take the replaced blob off disk — no +// route deletes a user, so nothing else would ever collect it. + +/// Upload (or replace) the caller's own avatar. `multipart/form-data` with the +/// image under a `file` field; the declared content type must be `image/png`, +/// `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the +/// bytes at most the school's `max_file_bytes` (settings). Replacing one drops +/// the previous picture. +#[utoipa::path( + post, + path = "/me/avatar", + tag = "users", + security(("session_cookie" = [])), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "Avatar stored", body = ProfileAvatar), + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "The account no longer exists", body = ErrorResponse), + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), + ), +)] +async fn upload_my_avatar( + State(st): State, + CurrentUser(user): CurrentUser, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let upload = read_image_upload(&st, &mut multipart).await?; + let size = upload.size(); + + let file = ulid::Ulid::new().to_string(); + store_blob(&st, &file, &upload.data, || async { + match User::set_avatar(user.get_id(), &file, &upload.content_type, size, &st.db).await? { + // Row written; the picture this one replaced comes off disk. + Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))), + // The account went away mid-upload — the fresh blob is an orphan. + None => Err(AppError::NotFound), + } + }) + .await?; + Ok(( + StatusCode::CREATED, + Json(ProfileAvatar { + content_type: upload.content_type.as_str().to_string(), + size, + }), + )) +} + +/// The caller's own avatar bytes. The self alias of `GET /{id}/avatar` — the +/// static `/me/avatar` segment wins over `/{id}/avatar` in the router, so +/// without this a client that never learned its own id gets a bodyless `405` +/// on the obvious route. It serves the caller's own row and nothing else, so +/// it asks no gate: the session already proves the reach. +#[utoipa::path( + get, + path = "/me/avatar", + tag = "users", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The image bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "The caller has no avatar", body = ErrorResponse), + ), +)] +async fn get_my_avatar( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result { + serve_avatar(&st, &user).await +} + +/// The avatar bytes. Same reach as the profile itself: every authenticated +/// account, except a parent, who is limited to their own and their linked +/// students'. +#[utoipa::path( + get, + path = "/{id}/avatar", + tag = "users", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "User id")), + responses( + (status = 200, description = "The image bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "A parent without a link to this student", body = ErrorResponse), + (status = 404, description = "No such user, or they have no avatar", body = ErrorResponse), + ), +)] +async fn get_avatar( + State(st): State, + CurrentUser(caller): CurrentUser, + Path(id): Path, +) -> Result { + let target = readable_profile_user(&st, &caller, &id).await?; + serve_avatar(&st, &target).await +} + +/// The shared tail of both avatar reads: the bytes, or a `404` when the row +/// carries none. The caller owns the gate — this one is reached already. +async fn serve_avatar(st: &AppState, user: &User) -> Result { + match (user.get_avatar_file(), user.get_avatar_content_type()) { + (Some(file), Some(content_type)) => { + serve_inline_blob(&st.files_path, file, content_type).await + } + _ => Err(AppError::NotFound), + } +} + +/// Remove the caller's own avatar. +#[utoipa::path( + delete, + path = "/me/avatar", + tag = "users", + security(("session_cookie" = [])), + responses( + (status = 204, description = "Avatar removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "No avatar to remove", body = ErrorResponse), + ), +)] +async fn delete_my_avatar( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result { + drop_avatar(&st, user.get_id()).await +} + +/// Remove any user's avatar. Admin only — the moderation path: an offensive +/// picture is a school problem, and no route deletes the account it hangs on. +#[utoipa::path( + delete, + path = "/{id}/avatar", + tag = "users", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "User id")), + responses( + (status = 204, description = "Avatar removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires admin role", body = ErrorResponse), + (status = 404, description = "No such user, or no avatar to remove", body = ErrorResponse), + ), +)] +async fn delete_avatar( + State(st): State, + _admin: RequireAdmin, + Path(id): Path, +) -> Result { + drop_avatar(&st, &UserId::from_key(&id)).await +} + +/// Clear the row's avatar and take its blob off disk — the shared tail of the +/// self and moderation deletes. A row without one (or no row at all) is a 404. +async fn drop_avatar(st: &AppState, user: &UserId) -> Result { + let before = User::clear_avatar(user, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let Some(file) = before.get_avatar_file() else { + return Err(AppError::NotFound); + }; + remove_blob(&st.files_path, file).await; + Ok(StatusCode::NO_CONTENT) +} diff --git a/tests/regress_profile.rs b/tests/regress_profile.rs new file mode 100644 index 0000000..42abff0 --- /dev/null +++ b/tests/regress_profile.rs @@ -0,0 +1,697 @@ +//! The public-profile surface: who may read a profile, what it may never +//! carry, the display-name fallback, the derived stats, and the avatar's +//! blob discipline. +//! +//! Every gate here is a *read* gate on data that is otherwise school-wide, so +//! each test is written to fail if its guard is deleted: the parent tests +//! assert the 403 *and* the 200 that proves the read would otherwise work, and +//! the blob test counts what is actually on disk rather than trusting the API's +//! own answer. + +mod common; + +use axum::Router; +use axum::http::StatusCode; +use common::{app_and_db, create_course, enroll, login, login_as, me_id, send, set_role}; +use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN}; +use serde_json::{Value, json}; + +const BOUNDARY: &str = "multipart/form-data; boundary=hezarfen-test-boundary"; + +/// Upload `bytes` as the caller's avatar; returns the status and parsed body. +async fn upload_avatar( + app: &Router, + cookie: &str, + content_type: &str, + bytes: &[u8], +) -> (StatusCode, Value) { + let (status, _, body) = common::send_raw( + app, + "POST", + "/users/me/avatar", + Some(cookie), + Some(BOUNDARY), + common::multipart_file("pic.png", content_type, bytes), + ) + .await; + let body = serde_json::from_slice(&body).unwrap_or(Value::Null); + (status, body) +} + +/// How many blobs in the test files dir hold exactly `bytes`. The dir is shared +/// by every app in this binary, so a payload no other test writes is the only +/// concurrency-safe way to count one test's own blobs. +fn blobs_holding(bytes: &[u8]) -> usize { + std::fs::read_dir(common::files_dir()) + .expect("files dir") + .filter_map(|entry| std::fs::read(entry.expect("dir entry").path()).ok()) + .filter(|found| found == bytes) + .count() +} + +/// Tie `student_id` to `parent_id` (admin only), asserting the tie landed. +async fn link_student(app: &Router, admin: &str, parent_id: &str, student_id: &str) { + let res = send( + app, + "POST", + &format!("/users/{parent_id}/students"), + Some(admin), + Some(json!({ "user_id": student_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "link student: {}", res.body); +} + +async fn profile(app: &Router, cookie: &str, id: &str) -> common::Res { + send( + app, + "GET", + &format!("/users/{id}/profile"), + Some(cookie), + None, + ) + .await +} + +/// A profile is the *public* half of a user row: a peer reads it, and the +/// contact fields that `GET /users/{id}` gates behind teacher+ are absent from +/// it entirely. `badges` is pass 2 — no empty key ships early. +#[tokio::test] +async fn a_peer_profile_carries_no_contact_fields() { + let (app, _db) = app_and_db().await; + let ada = login(&app, "ada").await; + let ada_id = me_id(&app, &ada).await; + let peer = login(&app, "peer").await; + + let res = send( + &app, + "PATCH", + "/users/me", + Some(&ada), + Some(json!({ + "name": "Ada", + "surname": "Lovelace", + "email": "ada@example.com", + "phone": "+90 555 123 45 67", + "birth_date": "1990-01-02", + })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let seen = profile(&app, &peer, &ada_id).await; + assert_eq!(seen.status, StatusCode::OK, "{}", seen.body); + assert_eq!(seen.body["username"], "ada"); + for private in ["email", "phone", "birth_date", "badges"] { + assert!( + seen.body.get(private).is_none(), + "{private} must not ride on a profile: {}", + seen.body + ); + } +} + +/// A parent is an observer of their own children and of nobody else: the +/// unlinked student is a 403, the linked one a 200, and their own row a 200. +/// The 200s are the half that proves the 403 is the gate biting, not the read +/// being broken for everyone. +#[tokio::test] +async fn a_parent_reads_only_their_own_and_their_linked_students() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "boss", "admin").await; + let parent = login_as(&app, &db, "mom", "parent").await; + let parent_id = me_id(&app, &parent).await; + let mine = login(&app, "kid").await; + let mine_id = me_id(&app, &mine).await; + let stranger = login(&app, "stranger").await; + let stranger_id = me_id(&app, &stranger).await; + + link_student(&app, &admin, &parent_id, &mine_id).await; + + let blocked = profile(&app, &parent, &stranger_id).await; + assert_eq!( + blocked.status, + StatusCode::FORBIDDEN, + "an unlinked student: {}", + blocked.body + ); + let linked = profile(&app, &parent, &mine_id).await; + assert_eq!(linked.status, StatusCode::OK, "{}", linked.body); + let own = profile(&app, &parent, &parent_id).await; + assert_eq!(own.status, StatusCode::OK, "{}", own.body); + let own_me = send(&app, "GET", "/users/me/profile", Some(&parent), None).await; + assert_eq!(own_me.status, StatusCode::OK, "{}", own_me.body); + + // The avatar bytes ride the same gate as the profile they hang on. + let (status, _, _) = common::send_raw( + &app, + "GET", + &format!("/users/{stranger_id}/avatar"), + Some(&parent), + None, + Vec::new(), + ) + .await; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "avatar of an unlinked student" + ); +} + +/// The link row alone is not the grant: the target's live role is re-read per +/// call, so a linked student promoted out of the student role stops being +/// readable — a stale link cannot leave a colleague's profile open to a parent. +#[tokio::test] +async fn promoting_a_linked_student_closes_the_parent_read() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "boss", "admin").await; + let parent = login_as(&app, &db, "mom", "parent").await; + let parent_id = me_id(&app, &parent).await; + let kid = login(&app, "kid").await; + let kid_id = me_id(&app, &kid).await; + + link_student(&app, &admin, &parent_id, &kid_id).await; + let before = profile(&app, &parent, &kid_id).await; + assert_eq!(before.status, StatusCode::OK, "{}", before.body); + + set_role(&db, "kid", "teacher").await; + + let after = profile(&app, &parent, &kid_id).await; + assert_eq!( + after.status, + StatusCode::FORBIDDEN, + "a promoted-out student must stop being readable: {}", + after.body + ); +} + +/// `display_name` is the self-chosen label, the joined legal name is the +/// fallback, and an account carrying neither reads `null` — never the username, +/// never an empty string. +#[tokio::test] +async fn display_name_falls_back_to_the_legal_name_then_null() { + let (app, _db) = app_and_db().await; + let ada = login(&app, "ada").await; + + let res = send( + &app, + "PATCH", + "/users/me", + Some(&ada), + Some(json!({ "name": "Ada", "surname": "Lovelace", "display_name": "Countess" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; + assert_eq!( + mine.body["display_name"], "Countess", + "the chosen name wins" + ); + + let res = send( + &app, + "PATCH", + "/users/me", + Some(&ada), + Some(json!({ "display_name": "" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; + assert_eq!(mine.body["display_name"], "Ada Lovelace", "the legal name"); + + let res = send( + &app, + "PATCH", + "/users/me", + Some(&ada), + Some(json!({ "name": "", "surname": "" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; + assert!( + mine.body["display_name"].is_null(), + "nothing to show: {}", + mine.body + ); +} + +/// The counters are derived, so a fresh account reads a true `0` on all four — +/// never `null`, never an absent key a client would have to guard. +#[tokio::test] +async fn fresh_stats_read_zero_on_every_field() { + let (app, _db) = app_and_db().await; + let fresh = login(&app, "fresh").await; + + let mine = send(&app, "GET", "/users/me/profile", Some(&fresh), None).await; + assert_eq!(mine.status, StatusCode::OK, "{}", mine.body); + let stats = mine.body["stats"].as_object().expect("stats object"); + for field in [ + "pomodoro_sessions", + "pomodoro_focus_ms", + "courses", + "classes", + ] { + assert_eq!( + stats.get(field).and_then(Value::as_i64), + Some(0), + "stats.{field} must be a numeric 0: {:?}", + stats.get(field) + ); + } + assert_eq!(stats.len(), 4, "no fifth counter shipped: {stats:?}"); + assert!(mine.body["avatar"].is_null()); + assert_eq!(mine.body["classes"], json!([])); + assert_eq!(mine.body["courses"], json!([])); +} + +/// Upload, read back the exact bytes and the declared type, delete, gone. +#[tokio::test] +async fn an_avatar_round_trips_and_delete_makes_it_a_404() { + let (app, db) = app_and_db().await; + let ada = login(&app, "ada").await; + let ada_id = me_id(&app, &ada).await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + let bytes = b"ROUNDTRIP-\x89PNG"; + + let (status, _, _) = common::send_raw( + &app, + "DELETE", + "/users/me/avatar", + Some(&ada), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "nothing to delete yet"); + + let (status, body) = upload_avatar(&app, &ada, "image/png", bytes).await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + assert_eq!(body["content_type"], "image/png"); + assert_eq!(body["size"], bytes.len()); + + let meta = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; + assert_eq!(meta.body["avatar"]["content_type"], "image/png"); + assert_eq!(meta.body["avatar"]["size"], bytes.len()); + + let (status, headers, served) = common::send_raw( + &app, + "GET", + &format!("/users/{ada_id}/avatar"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers["content-type"], "image/png"); + assert_eq!(served, bytes, "the exact bytes come back"); + + let (status, _, _) = common::send_raw( + &app, + "DELETE", + "/users/me/avatar", + Some(&ada), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + + let (status, _, _) = common::send_raw( + &app, + "GET", + &format!("/users/{ada_id}/avatar"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "the picture is gone"); + let meta = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; + assert!(meta.body["avatar"].is_null()); + assert_eq!(blobs_holding(bytes), 0, "the blob left disk too"); +} + +/// The self alias reads the caller's own picture. `/me/avatar` is a static +/// segment, so it beats `/{id}/avatar` in the router: without an explicit `GET` +/// the obvious route answers a bodyless `405` and a client is forced to learn +/// its own id first. +#[tokio::test] +async fn the_caller_reads_their_own_avatar_without_knowing_their_id() { + let (app, _db) = app_and_db().await; + let ada = login(&app, "ada").await; + let bytes = b"SELFALIAS-\x89PNG"; + + let (status, _, _) = common::send_raw( + &app, + "GET", + "/users/me/avatar", + Some(&ada), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "no picture yet, not a 405"); + + let (status, body) = upload_avatar(&app, &ada, "image/png", bytes).await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + + let (status, headers, served) = common::send_raw( + &app, + "GET", + "/users/me/avatar", + Some(&ada), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers["content-type"], "image/png"); + assert_eq!(served, bytes, "the exact bytes, same as the id route"); +} + +/// SVG is not a raster: it scripts, and an avatar renders inline to the whole +/// school. The allowlist keeps it out. +#[tokio::test] +async fn an_svg_avatar_is_rejected() { + let (app, _db) = app_and_db().await; + let ada = login(&app, "ada").await; + let svg = b"SVGREJECT"; + + let (status, body) = upload_avatar(&app, &ada, "image/svg+xml", svg).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; + assert!(mine.body["avatar"].is_null(), "{}", mine.body); + assert_eq!(blobs_holding(svg), 0, "nothing reached disk"); +} + +/// Deleting someone else's picture is moderation, so it is admin-only; the +/// admin's delete succeeding is what proves the 403 is the role gate and not a +/// broken route. +#[tokio::test] +async fn only_an_admin_deletes_someone_elses_avatar() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "boss", "admin").await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + let ada = login(&app, "ada").await; + let ada_id = me_id(&app, &ada).await; + let bytes = b"MODERATION-\x89PNG"; + + let (status, body) = upload_avatar(&app, &ada, "image/png", bytes).await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + + for (who, label) in [(&teacher, "teacher"), (&ada, "the owner via /{id}")] { + let (status, _, _) = common::send_raw( + &app, + "DELETE", + &format!("/users/{ada_id}/avatar"), + Some(who), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{label} is not an admin"); + } + + let (status, _, _) = common::send_raw( + &app, + "DELETE", + &format!("/users/{ada_id}/avatar"), + Some(&admin), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; + assert!(mine.body["avatar"].is_null(), "{}", mine.body); + assert_eq!(blobs_holding(bytes), 0); +} + +/// Replacing an avatar takes the old blob off disk. No route deletes a user, so +/// a blob stranded here is stranded forever — this counts what is actually on +/// disk, not what the API claims. +#[tokio::test] +async fn replacing_an_avatar_leaves_exactly_one_blob() { + let (app, _db) = app_and_db().await; + let ada = login(&app, "ada").await; + let first = b"HYGIENE-FIRST-BLOB"; + let second = b"HYGIENE-SECOND-BLOB"; + + let (status, body) = upload_avatar(&app, &ada, "image/png", first).await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + assert_eq!(blobs_holding(first), 1, "the first picture is on disk"); + + let (status, body) = upload_avatar(&app, &ada, "image/jpeg", second).await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + assert_eq!( + blobs_holding(first), + 0, + "the replaced picture must leave disk — nothing ever collects it" + ); + assert_eq!(blobs_holding(second), 1, "and exactly one replaces it"); + + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; + assert_eq!(mine.body["avatar"]["content_type"], "image/jpeg"); + assert_eq!(mine.body["avatar"]["size"], second.len()); +} + +/// The course block follows the owner's **live** role, not the `creator` / +/// `teachers` columns: those are historical and no demotion sweeps them, so a +/// demoted ex-teacher lists what they are enrolled in, like any other student. +#[tokio::test] +async fn a_demoted_teacher_lists_enrolled_courses_not_created_ones() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "boss", "admin").await; + let ex = login_as(&app, &db, "exteach", "teacher").await; + let staff = login_as(&app, &db, "coach", "teacher").await; + let ex_id = me_id(&app, &ex).await; + + create_course(&app, &ex, "Owned").await; + let joined = create_course(&app, &staff, "Joined").await; + + let as_teacher = send(&app, "GET", "/users/me/profile", Some(&ex), None).await; + assert_eq!(as_teacher.body["courses"][0]["title"], "Owned"); + assert_eq!(as_teacher.body["stats"]["courses"], 1); + + set_role(&db, "exteach", "student").await; + enroll(&app, &staff, &joined, &ex_id).await; + + let after = profile(&app, &admin, &ex_id).await; + assert_eq!(after.status, StatusCode::OK, "{}", after.body); + let titles: Vec<&str> = after.body["courses"] + .as_array() + .expect("courses array") + .iter() + .map(|course| course["title"].as_str().expect("title")) + .collect(); + assert_eq!(titles, ["Joined"], "the course they created is not theirs"); + assert_eq!(after.body["stats"]["courses"], 1); + assert_eq!(after.body["role"], "student"); +} + +/// `""` clears either public field; both are length-bounded, and the bound is +/// the one `GET /limits` publishes. +#[tokio::test] +async fn display_name_and_bio_clear_on_blank_and_are_bounded() { + let (app, _db) = app_and_db().await; + let ada = login(&app, "ada").await; + + let res = send( + &app, + "PATCH", + "/users/me", + Some(&ada), + Some(json!({ "display_name": "Countess", "bio": "hi" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + // The same pair rides every user-shaped response, not just the profile. + assert_eq!(res.body["display_name"], "Countess"); + assert_eq!(res.body["bio"], "hi"); + + let res = send( + &app, + "PATCH", + "/users/me", + Some(&ada), + Some(json!({ "display_name": "", "bio": "" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; + assert!(mine.body["display_name"].is_null(), "{}", mine.body); + assert!(mine.body["bio"].is_null(), "{}", mine.body); + + let over = send( + &app, + "PATCH", + "/users/me", + Some(&ada), + Some(json!({ "display_name": "x".repeat(MAX_DISPLAY_NAME_LEN + 1) })), + ) + .await; + assert_eq!(over.status, StatusCode::BAD_REQUEST, "{}", over.body); + + let over = send( + &app, + "PATCH", + "/users/me", + Some(&ada), + Some(json!({ "bio": "x".repeat(MAX_BIO_LEN + 1) })), + ) + .await; + assert_eq!(over.status, StatusCode::BAD_REQUEST, "{}", over.body); + + // The bound holds exactly at the limit, so the reject above is the bound + // and not an off-by-one that also refuses a legal value. + let ok = send( + &app, + "PATCH", + "/users/me", + Some(&ada), + Some(json!({ "display_name": "x".repeat(MAX_DISPLAY_NAME_LEN) })), + ) + .await; + assert_eq!(ok.status, StatusCode::OK, "{}", ok.body); +} + +/// A teacher who runs two courses, a student enrolled in one of them, a +/// student enrolled in neither, and a manager — the cast every course-block +/// test needs. +struct School { + app: Router, + teacher: String, + teacher_id: String, + peer: String, + stranger: String, + manager: String, + secret: String, +} + +async fn school() -> School { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "boss", "manager").await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + let peer = login(&app, "peer").await; + let peer_id = me_id(&app, &peer).await; + let stranger = login(&app, "nosy").await; + + let secret = create_course(&app, &teacher, "Secret Club").await; + let shared = create_course(&app, &teacher, "Shared Math").await; + enroll(&app, &teacher, &shared, &peer_id).await; + + School { + app, + teacher, + teacher_id, + peer, + stranger, + manager, + secret, + } +} + +/// The titles a profile's course block hands `cookie`. +async fn course_titles(app: &Router, cookie: &str, id: &str) -> Vec { + let res = profile(app, cookie, id).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + res.body["courses"] + .as_array() + .expect("courses array") + .iter() + .map(|course| course["title"].as_str().expect("title").to_string()) + .collect() +} + +/// The leak this filter closes: a course a reader is 403'd from at +/// `GET /courses/{id}` used to arrive, title and all, off any teacher's +/// profile. The 403 is asserted in the same test so the two answers cannot +/// drift apart unnoticed. +#[tokio::test] +async fn a_profile_never_names_a_course_the_reader_is_403d_from() { + let s = school().await; + + let direct = send( + &s.app, + "GET", + &format!("/courses/{}", s.secret), + Some(&s.stranger), + None, + ) + .await; + assert_eq!(direct.status, StatusCode::FORBIDDEN, "{}", direct.body); + + let seen = profile(&s.app, &s.stranger, &s.teacher_id).await; + assert_eq!(seen.status, StatusCode::OK, "{}", seen.body); + assert_eq!(seen.body["courses"], json!([])); + assert!( + !seen.body.to_string().contains("Secret Club"), + "the profile leaked a course title the reader cannot read: {}", + seen.body + ); +} + +/// The intersection is per course, not all-or-nothing: sharing one course +/// reveals that one and nothing else. +#[tokio::test] +async fn a_peer_sees_only_the_course_they_share() { + let s = school().await; + assert_eq!( + course_titles(&s.app, &s.peer, &s.teacher_id).await, + ["Shared Math"] + ); +} + +/// Manager+ reads any course directly, so the filter has nothing to withhold. +#[tokio::test] +async fn a_manager_reads_the_course_block_unfiltered() { + let s = school().await; + let mut titles = course_titles(&s.app, &s.manager, &s.teacher_id).await; + titles.sort(); + assert_eq!(titles, ["Secret Club", "Shared Math"]); +} + +/// Your own profile is never cut — both routes onto it. +#[tokio::test] +async fn your_own_profile_shows_your_whole_course_list() { + let s = school().await; + let mut titles = course_titles(&s.app, &s.teacher, &s.teacher_id).await; + titles.sort(); + assert_eq!(titles, ["Secret Club", "Shared Math"]); + + let mine = send(&s.app, "GET", "/users/me/profile", Some(&s.teacher), None).await; + assert_eq!(mine.body["courses"].as_array().expect("courses").len(), 2); +} + +/// `stats.courses` is the owner's true total, deliberately *not* the length of +/// the filtered block: it is the motivational counter, and a per-reader number +/// would be meaningless. A magnitude names no course. +#[tokio::test] +async fn stats_courses_stays_the_owners_true_total() { + let s = school().await; + + let stranger = profile(&s.app, &s.stranger, &s.teacher_id).await; + assert_eq!(stranger.body["courses"], json!([])); + assert_eq!(stranger.body["stats"]["courses"], 2); + + let peer = profile(&s.app, &s.peer, &s.teacher_id).await; + assert_eq!(peer.body["courses"].as_array().expect("courses").len(), 1); + assert_eq!(peer.body["stats"]["courses"], 2); +} + +/// A profile that was never there is a 404, at any role — the id is not an +/// existence oracle wearing a 403. +#[tokio::test] +async fn an_unknown_user_profile_is_a_404() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + + let gone = profile(&app, &teacher, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await; + assert_eq!(gone.status, StatusCode::NOT_FOUND, "{}", gone.body); +} diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index ffa96f5..d73986d 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -86,6 +86,13 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64), ("UpdateProfile", "surname", "maxLength", MAX_NAME_LEN as i64), ("UpdateProfile", "email", "maxLength", MAX_EMAIL_LEN as i64), + ( + "UpdateProfile", + "display_name", + "maxLength", + MAX_DISPLAY_NAME_LEN as i64, + ), + ("UpdateProfile", "bio", "maxLength", MAX_BIO_LEN as i64), ( "CreateNote", "title", @@ -1070,7 +1077,7 @@ async fn the_image_meta_bodies_stay_the_same_shape() { }; let want = shape("ImageMetaResponse"); - for other in ["BankImageMeta", "PoolImageMeta"] { + for other in ["BankImageMeta", "PoolImageMeta", "ProfileAvatar"] { assert_eq!( want, shape(other),