diff --git a/README.md b/README.md index a2fad9c..9eddb9a 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,11 @@ given, lessons held and question-pool approvals for a teacher — and the revokes one, and permanent once earned even if the counter later falls. 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"). +linked students' only. The two blocks inside it are cut to what the *reader* +already reaches elsewhere: courses to the ones they would pass +`GET /courses/{id}` on, classes to nothing at all unless they are teacher+, a +linked parent, or the owner — the bar `GET /classes/user/{id}` holds (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 @@ -646,7 +650,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 | +| 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. The profile's `classes` block is empty unless the reader is teacher+, a parent linked to that student, or the owner | | 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 | @@ -795,7 +799,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username; ties whose student was promoted out are left out) · 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}/profile` | student | Any user's public profile — a `parent` reads only their own and their linked students' (`403`); the `courses` block is cut to what the reader may read directly and the `classes` block is empty below teacher+/linked parent | | 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 | @@ -1234,6 +1238,19 @@ 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. +**The class block is cut the same way, at the same bar `GET /classes/user/{id}` +holds**: teacher+, a parent linked to that student, or the owner reading their +own profile. Every other reader — a fellow student included — gets an empty +`classes` array, not a `403`: the rest of the profile stays public to them, but +a class name and grade are exactly what the `/classes` routes withhold below +teacher+ (`GET /classes/{id}` is teacher+, `GET /classes/user/{id}` is +teacher-or-linked-parent), and a profile must not be the way around them. The +gate is all-or-nothing rather than per class, which is the one way this block +differs from the courses one: there is no "the class we share", so a reader +either sees the owner's section list or sees none of it. `stats.classes`, like +`stats.courses`, stays the owner's true total for every reader — a magnitude +names no class. + **`stats` holds sixteen numbers of two different kinds, and the difference is worth knowing.** `pomodoro_sessions`, `pomodoro_focus_ms`, `courses` and `classes` are **computed at read**: they are recounted from the live rows on diff --git a/src/web/users.rs b/src/web/users.rs index 03067df..52c039a 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -829,10 +829,21 @@ struct ProfileStatsResponse { /// 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. +/// serves. Reading your own profile, or reading as manager+, needs no +/// intersection: both already see the whole list. +/// +/// The class block answers to [`ensure_can_observe`], the gate +/// `GET /classes/user/{id}` holds — teacher+, or a parent linked to the target +/// — because every other `/classes` read is teacher+ and a class name and grade +/// are exactly what those routes withhold. That gate is all-or-nothing rather +/// than per class, so a viewer who fails it gets an empty block, not a 403: the +/// rest of the profile is still public to them. +/// +/// So no *named* thing here crosses a gate the viewer would fail directly. The +/// two magnitudes deliberately do: `stats.courses` and `stats.classes` stay the +/// owner's true totals for every reader — they are the motivational counters, a +/// per-reader number would be meaningless, and a magnitude names no course and +/// no class. async fn profile_of( st: &AppState, user: &User, @@ -869,8 +880,14 @@ async fn profile_of( courses.retain(|course| readable.contains(course.get_id())); } courses.truncate(MAX_PROFILE_COURSES); - let (members, class_total) = + let (mut members, class_total) = ClassMember::list_for_user(id, Some(MAX_PROFILE_CLASSES as i64), 0, &st.db).await?; + // The window is safe to take from the database here: the class gate is + // all-or-nothing, so it drops the whole page or none of it — never a row + // out of the middle of one. + if viewer.get_id() != id && ensure_can_observe(viewer, id, &st.db).await.is_err() { + members.clear(); + } 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 @@ -1021,8 +1038,11 @@ async fn my_profile( /// 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. +/// would pass `GET /courses/{id}` on. The class block holds the same bar as +/// `GET /classes/user/{id}` — teacher+, a parent linked to this student, or the +/// owner themselves; every other reader gets an empty `classes` array rather +/// than a 403. `stats.courses` and `stats.classes` stay the owner's true totals +/// either way. #[utoipa::path( get, path = "/{id}/profile", diff --git a/tests/regress_profile.rs b/tests/regress_profile.rs index 0f0f11b..1d3386c 100644 --- a/tests/regress_profile.rs +++ b/tests/regress_profile.rs @@ -14,7 +14,7 @@ use axum::Router; use axum::http::StatusCode; use common::{ app_and_db, create_course, create_exam_with, create_homework, create_subject, enroll, id_of, - login, login_as, me_id, send, set_role, + items, login, login_as, me_id, send, set_role, }; use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN}; use hezarfen_backend::database::Database; @@ -779,6 +779,233 @@ async fn stats_courses_stays_the_owners_true_total() { assert_eq!(peer.body["stats"]["courses"], 2); } +// --- The class block ------------------------------------------------------ +// +// `GET /classes/{id}` is teacher+ and `GET /classes/user/{id}` is teacher-or- +// linked-parent, so a class's name and grade are not school-wide reads. The +// profile's class block used to hand both to any authenticated peer — a plain +// student sufficed. It now holds the same bar, all-or-nothing (there is no +// "the class we share"), and the drift guard at the end compares the two +// surfaces reader by reader rather than trusting either alone. + +/// A manager, a teacher, a linked parent, the student who is in the class, and +/// a nosy fellow student who is in nothing. +struct Section { + app: Router, + manager: String, + teacher: String, + parent: String, + peer: String, + student: String, + student_id: String, +} + +async fn section() -> Section { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "chief", "admin").await; + let manager = login_as(&app, &db, "boss", "manager").await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + let parent = login_as(&app, &db, "mom", "parent").await; + let parent_id = me_id(&app, &parent).await; + let peer = login(&app, "nosy").await; + let student = login(&app, "kid").await; + let student_id = me_id(&app, &student).await; + + let class = create_class(&app, &manager, "9-A", "9").await; + add_member(&app, &manager, &class, &student_id).await; + link_student(&app, &admin, &parent_id, &student_id).await; + + Section { + app, + manager, + teacher, + parent, + peer, + student, + student_id, + } +} + +async fn create_class(app: &Router, manager: &str, name: &str, grade: &str) -> String { + let res = send( + app, + "POST", + "/classes", + Some(manager), + Some(json!({ "name": name, "grade": grade })), + ) + .await; + assert_eq!( + res.status, + StatusCode::CREATED, + "create class: {}", + res.body + ); + id_of(&res.body["class"]) +} + +async fn add_member(app: &Router, manager: &str, class: &str, user_id: &str) { + let res = send( + app, + "POST", + &format!("/classes/{class}/members"), + Some(manager), + Some(json!({ "user_id": user_id })), + ) + .await; + assert!(res.status.is_success(), "add member: {}", res.body); +} + +/// The class names a profile's class block hands `cookie`. +async fn class_names(app: &Router, cookie: &str, id: &str) -> Vec { + let res = profile(app, cookie, id).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + res.body["classes"] + .as_array() + .expect("classes array") + .iter() + .map(|class| class["name"].as_str().expect("name").to_string()) + .collect() +} + +/// The class ids off the same block, sorted — the drift guard's left half. +async fn profile_class_ids(app: &Router, cookie: &str, id: &str) -> Vec { + let res = profile(app, cookie, id).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let mut ids: Vec = res.body["classes"] + .as_array() + .expect("classes array") + .iter() + .map(id_of) + .collect(); + ids.sort(); + ids +} + +/// The class ids the *dedicated* routes hand that same reader for that same +/// subject — `None` when they are refused outright. Your own classes are +/// `GET /classes/me`; anybody else's are `GET /classes/user/{id}`. +async fn route_class_ids(app: &Router, cookie: &str, id: &str, own: bool) -> Option> { + let path = match own { + true => "/classes/me".to_string(), + false => format!("/classes/user/{id}"), + }; + let res = send(app, "GET", &path, Some(cookie), None).await; + if res.status == StatusCode::FORBIDDEN { + return None; + } + assert_eq!(res.status, StatusCode::OK, "GET {path}: {}", res.body); + let mut ids: Vec = items(&res.body).iter().map(id_of).collect(); + ids.sort(); + Some(ids) +} + +/// The leak this closes: a class a reader is `403`'d from at +/// `GET /classes/user/{id}` used to arrive off that student's profile, name and +/// grade and all, for any authenticated account. 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_class_the_reader_is_403d_from() { + let s = section().await; + + let direct = send( + &s.app, + "GET", + &format!("/classes/user/{}", s.student_id), + Some(&s.peer), + None, + ) + .await; + assert_eq!(direct.status, StatusCode::FORBIDDEN, "{}", direct.body); + + let seen = profile(&s.app, &s.peer, &s.student_id).await; + assert_eq!(seen.status, StatusCode::OK, "{}", seen.body); + assert_eq!(seen.body["classes"], json!([])); + assert!( + !seen.body.to_string().contains("9-A"), + "the profile leaked a class the reader cannot read: {}", + seen.body + ); +} + +/// The half that proves the gate is the gate and not a broken read: everyone +/// who may ask the class routes directly still gets the block. +#[tokio::test] +async fn teacher_parent_manager_and_the_owner_still_read_the_class_block() { + let s = section().await; + + assert_eq!( + class_names(&s.app, &s.teacher, &s.student_id).await, + ["9-A"] + ); + assert_eq!( + class_names(&s.app, &s.manager, &s.student_id).await, + ["9-A"] + ); + assert_eq!(class_names(&s.app, &s.parent, &s.student_id).await, ["9-A"]); + assert_eq!( + class_names(&s.app, &s.student, &s.student_id).await, + ["9-A"] + ); + + let mine = send(&s.app, "GET", "/users/me/profile", Some(&s.student), None).await; + assert_eq!(mine.status, StatusCode::OK, "{}", mine.body); + assert_eq!(mine.body["classes"][0]["name"], "9-A"); + assert_eq!(mine.body["classes"][0]["grade"], "9"); +} + +/// `stats.classes` is the owner's true total, deliberately *not* the length of +/// the gated block — the same call already made for `stats.courses`: it is the +/// motivational counter, and a magnitude names no class. +#[tokio::test] +async fn stats_classes_stays_the_owners_true_total() { + let s = section().await; + + let peer = profile(&s.app, &s.peer, &s.student_id).await; + assert_eq!(peer.body["classes"], json!([])); + assert_eq!(peer.body["stats"]["classes"], 1); + + let teacher = profile(&s.app, &s.teacher, &s.student_id).await; + assert_eq!(teacher.body["stats"]["classes"], 1); +} + +/// The forcing function: for every reader, the profile's class block must say +/// exactly what the dedicated class route says to that same reader — an empty +/// block where the route is a `403`, the identical id set where it is a `200`. +/// Whichever surface moves first, this fails. (One class, so the block's +/// `max_profile_classes` truncation cannot make the two disagree honestly.) +#[tokio::test] +async fn the_profile_class_block_agrees_with_the_class_route() { + let s = section().await; + let readers = [ + ("peer", &s.peer, false), + ("teacher", &s.teacher, false), + ("manager", &s.manager, false), + ("parent", &s.parent, false), + ("owner", &s.student, true), + ]; + + let mut refused = 0; + let mut served = 0; + for (who, cookie, own) in readers { + let route = route_class_ids(&s.app, cookie, &s.student_id, own).await; + let block = profile_class_ids(&s.app, cookie, &s.student_id).await; + match &route { + None => refused += 1, + Some(ids) if !ids.is_empty() => served += 1, + Some(_) => {} + } + assert_eq!( + route.unwrap_or_default(), + block, + "{who}: the profile's class block and the class route disagree" + ); + } + // Neither half may pass vacuously: somebody was refused, somebody was served. + assert_eq!(refused, 1, "exactly the peer is refused the class route"); + assert_eq!(served, 4, "the other four are served a non-empty list"); +} + // --- Badges --------------------------------------------------------------- // // Badges are *permanent*: an award row is stamped once and nothing ever moves