forge
Explore
Log in

Don't you dare go Hollow

Stop a profile handing out classes the reader is 403'd from

Browse files at this commit

abe75ba3a680c814f9f124b50605e4e6ec8fbd00Ahmet Kaan GümüşParent: c1a0c3b
  • fix
    • stop a profile handing out classes the reader is 403'd from
Show full message
🎟️ fix: stop a profile handing out classes the reader is 403'd from

`profile_of` intersected only the *course* block with what the viewer may
already read; the class block was a bare `ClassMember::list_for_user`. So
`GET /users/{peer}/profile` handed any authenticated non-parent account — a
plain student sufficed — that peer's class ids, names and grades, while both
dedicated reads of exactly that data refuse: `GET /classes/{id}` is teacher+
and `GET /classes/user/{id}` is teacher-or-linked-parent. The module's own doc
comment claimed "nothing here crosses a gate the viewer would fail directly",
which was false for every class it served.

The direction is a product decision, taken deliberately: tighten the profile to
the class routes rather than loosen the class routes to the profile. The block
now runs through `ensure_can_observe`, the same predicate `/classes/user/{id}`
holds, and a viewer who fails it gets an empty `classes` array rather than a
403 — the rest of the profile is still public to them, and the response shape
does not move, so a client degrades instead of failing to parse. The gate is
all-or-nothing (there is no "the class we share"), so it drops the whole
window or none of it and no DB `LIMIT` ends up in front of a Rust filter.

`stats.classes` deliberately stays the owner's true total, like `stats.courses`
one paragraph above: the counters are motivational, a per-reader magnitude
would be meaningless, and a magnitude names no class. The doc comment now says
that instead of claiming the surface is clean of it.

Pinned in `regress_profile`: the peer's empty block asserted next to the 403 it
mirrors, the teacher/manager/parent/owner reads that prove the gate bites
rather than the read being broken, the true total, and a drift guard that
compares the profile's class block against `GET /classes/user/{id}` (or
`/classes/me` for the owner) reader by reader, so the two surfaces cannot
diverge silently again. Three of the four go red without the fix.

The frontend will lose class chips on peers a viewer cannot observe; the
backend defines the contract and the FE aligns.
README.mdmodified+20 -3
@@ -132,7 +132,11 @@ given, lessons held and question-pool approvals for a teacher — and the
132 revokes one, and permanent once earned even if the counter later falls. Contact details are deliberately not part of it — email,132 revokes one, and permanent once earned even if the counter later falls. Contact details are deliberately not part of it — email,
133 phone and birth date keep the gate they already have — and any authenticated133 phone and birth date keep the gate they already have — and any authenticated
134 account reads any profile, except a `parent`, who reads their own and their134 account reads any profile, except a `parent`, who reads their own and their
135-linked students' only (see "User profiles & avatars").135+linked students' only. The two blocks inside it are cut to what the *reader*
136+already reaches elsewhere: courses to the ones they would pass
137+`GET /courses/{id}` on, classes to nothing at all unless they are teacher+, a
138+linked parent, or the owner — the bar `GET /classes/user/{id}` holds (see
139+"User profiles & avatars").
136 The **AI features live in separate projects**, so the backend also opens a140 The **AI features live in separate projects**, so the backend also opens a
137 QUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in,141 QUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in,
138 register the capabilities they serve, and each request rides its own QUIC142 register the capabilities they serve, and each request rides its own QUIC
@@ -646,7 +650,7 @@ still left exactly as they stand.
646 | 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 |650 | 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 |
647 | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields |651 | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields |
648 | Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen — the client then follows the device preference |652 | Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen — the client then follows the device preference |
649-| 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 |653+| 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 |
650 | List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports — a parent changes nothing, anywhere |654 | List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports — a parent changes nothing, anywhere |
651 | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar |655 | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar |
652 | 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 |656 | 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.
795 | GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username; ties whose student was promoted out are left out) · paged |799 | GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username; ties whose student was promoted out are left out) · paged |
796 | GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` — find users by username/name fragment (pickers); refs only, no contact info · paged |800 | GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` — find users by username/name fragment (pickers); refs only, no contact info · paged |
797 | GET | `/users` | admin | List all users · paged |801 | GET | `/users` | admin | List all users · paged |
798-| GET | `/users/{id}/profile` | student | Any user's public profile — a `parent` reads only their own and their linked students' (`403`) |802+| 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 |
799 | GET | `/users/{id}/avatar` | student | The avatar bytes (`nosniff`, `private, no-store`); same reach as the profile |803 | GET | `/users/{id}/avatar` | student | The avatar bytes (`nosniff`, `private, no-store`); same reach as the profile |
800 | DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar — the moderation path |804 | DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar — the moderation path |
801 | GET | `/users/{id}` | admin | Get one user |805 | 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
1234 number would be meaningless, and a magnitude names no course. One consequence,1238 number would be meaningless, and a magnitude names no course. One consequence,
1235 by design: a teacher you share nothing with has an empty `courses` block.1239 by design: a teacher you share nothing with has an empty `courses` block.
1236 1240
1241+**The class block is cut the same way, at the same bar `GET /classes/user/{id}`
1242+holds**: teacher+, a parent linked to that student, or the owner reading their
1243+own profile. Every other reader — a fellow student included — gets an empty
1244+`classes` array, not a `403`: the rest of the profile stays public to them, but
1245+a class name and grade are exactly what the `/classes` routes withhold below
1246+teacher+ (`GET /classes/{id}` is teacher+, `GET /classes/user/{id}` is
1247+teacher-or-linked-parent), and a profile must not be the way around them. The
1248+gate is all-or-nothing rather than per class, which is the one way this block
1249+differs from the courses one: there is no "the class we share", so a reader
1250+either sees the owner's section list or sees none of it. `stats.classes`, like
1251+`stats.courses`, stays the owner's true total for every reader — a magnitude
1252+names no class.
1253+
1237 **`stats` holds sixteen numbers of two different kinds, and the difference is1254 **`stats` holds sixteen numbers of two different kinds, and the difference is
1238 worth knowing.** `pomodoro_sessions`, `pomodoro_focus_ms`, `courses` and1255 worth knowing.** `pomodoro_sessions`, `pomodoro_focus_ms`, `courses` and
1239 `classes` are **computed at read**: they are recounted from the live rows on1256 `classes` are **computed at read**: they are recounted from the live rows on
src/web/users.rsmodified+27 -7
@@ -829,10 +829,21 @@ struct ProfileStatsResponse {
829 /// A course carries a title, and `GET /courses/{id}` hands that title only to829 /// A course carries a title, and `GET /courses/{id}` hands that title only to
830 /// the enrolled, the staff who run it, and manager+ — so the block is830 /// the enrolled, the staff who run it, and manager+ — so the block is
831 /// intersected with [`visible_courses`], the same catalog `GET /courses`831 /// intersected with [`visible_courses`], the same catalog `GET /courses`
832-/// serves. Nothing here crosses a gate the viewer would fail directly. Reading832+/// serves. Reading your own profile, or reading as manager+, needs no
833-/// your own profile, or reading as manager+, needs no intersection: both833+/// intersection: both already see the whole list.
834-/// already see the whole list. `stats.courses` stays the owner's true total —834+///
835-/// it is the motivational counter, and a magnitude names no course.835+/// The class block answers to [`ensure_can_observe`], the gate
836+/// `GET /classes/user/{id}` holds — teacher+, or a parent linked to the target
837+/// — because every other `/classes` read is teacher+ and a class name and grade
838+/// are exactly what those routes withhold. That gate is all-or-nothing rather
839+/// than per class, so a viewer who fails it gets an empty block, not a 403: the
840+/// rest of the profile is still public to them.
841+///
842+/// So no *named* thing here crosses a gate the viewer would fail directly. The
843+/// two magnitudes deliberately do: `stats.courses` and `stats.classes` stay the
844+/// owner's true totals for every reader — they are the motivational counters, a
845+/// per-reader number would be meaningless, and a magnitude names no course and
846+/// no class.
836 async fn profile_of(847 async fn profile_of(
837 st: &AppState,848 st: &AppState,
838 user: &User,849 user: &User,
@@ -869,8 +880,14 @@ async fn profile_of(
869 courses.retain(|course| readable.contains(course.get_id()));880 courses.retain(|course| readable.contains(course.get_id()));
870 }881 }
871 courses.truncate(MAX_PROFILE_COURSES);882 courses.truncate(MAX_PROFILE_COURSES);
872- let (members, class_total) =883+ let (mut members, class_total) =
873 ClassMember::list_for_user(id, Some(MAX_PROFILE_CLASSES as i64), 0, &st.db).await?;884 ClassMember::list_for_user(id, Some(MAX_PROFILE_CLASSES as i64), 0, &st.db).await?;
885+ // The window is safe to take from the database here: the class gate is
886+ // all-or-nothing, so it drops the whole page or none of it — never a row
887+ // out of the middle of one.
888+ if viewer.get_id() != id && ensure_can_observe(viewer, id, &st.db).await.is_err() {
889+ members.clear();
890+ }
874 let class_ids: Vec<ClassGroupId> = members.iter().map(|row| row.get_class().clone()).collect();891 let class_ids: Vec<ClassGroupId> = members.iter().map(|row| row.get_class().clone()).collect();
875 let classes = ClassGroup::list_by_ids(&class_ids, &st.db).await?;892 let classes = ClassGroup::list_by_ids(&class_ids, &st.db).await?;
876 // Both totals are the full counts, not the windowed ones — the blocks are a893 // Both totals are the full counts, not the windowed ones — the blocks are a
@@ -1021,8 +1038,11 @@ async fn my_profile(
1021 /// at `max_profile_classes` / `max_profile_courses` (see `GET /limits`) — the1038 /// at `max_profile_classes` / `max_profile_courses` (see `GET /limits`) — the
1022 /// full paged lists are `GET /classes/me` and `GET /courses/me`. The course1039 /// full paged lists are `GET /classes/me` and `GET /courses/me`. The course
1023 /// block is also cut to what the *reader* may already see: only courses they1040 /// block is also cut to what the *reader* may already see: only courses they
1024-/// would pass `GET /courses/{id}` on. `stats.courses` stays the owner's true1041+/// would pass `GET /courses/{id}` on. The class block holds the same bar as
1025-/// total either way.1042+/// `GET /classes/user/{id}` — teacher+, a parent linked to this student, or the
1043+/// owner themselves; every other reader gets an empty `classes` array rather
1044+/// than a 403. `stats.courses` and `stats.classes` stay the owner's true totals
1045+/// either way.
1026 #[utoipa::path(1046 #[utoipa::path(
1027 get,1047 get,
1028 path = "/{id}/profile",1048 path = "/{id}/profile",
tests/regress_profile.rsmodified+228 -1
@@ -14,7 +14,7 @@ use axum::Router;
14 use axum::http::StatusCode;14 use axum::http::StatusCode;
15 use common::{15 use common::{
16 app_and_db, create_course, create_exam_with, create_homework, create_subject, enroll, id_of,16 app_and_db, create_course, create_exam_with, create_homework, create_subject, enroll, id_of,
17- login, login_as, me_id, send, set_role,17+ items, login, login_as, me_id, send, set_role,
18 };18 };
19 use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN};19 use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN};
20 use hezarfen_backend::database::Database;20 use hezarfen_backend::database::Database;
@@ -779,6 +779,233 @@ async fn stats_courses_stays_the_owners_true_total() {
779 assert_eq!(peer.body["stats"]["courses"], 2);779 assert_eq!(peer.body["stats"]["courses"], 2);
780 }780 }
781 781
782+// --- The class block ------------------------------------------------------
783+//
784+// `GET /classes/{id}` is teacher+ and `GET /classes/user/{id}` is teacher-or-
785+// linked-parent, so a class's name and grade are not school-wide reads. The
786+// profile's class block used to hand both to any authenticated peer — a plain
787+// student sufficed. It now holds the same bar, all-or-nothing (there is no
788+// "the class we share"), and the drift guard at the end compares the two
789+// surfaces reader by reader rather than trusting either alone.
790+
791+/// A manager, a teacher, a linked parent, the student who is in the class, and
792+/// a nosy fellow student who is in nothing.
793+struct Section {
794+ app: Router,
795+ manager: String,
796+ teacher: String,
797+ parent: String,
798+ peer: String,
799+ student: String,
800+ student_id: String,
801+}
802+
803+async fn section() -> Section {
804+ let (app, db) = app_and_db().await;
805+ let admin = login_as(&app, &db, "chief", "admin").await;
806+ let manager = login_as(&app, &db, "boss", "manager").await;
807+ let teacher = login_as(&app, &db, "teach", "teacher").await;
808+ let parent = login_as(&app, &db, "mom", "parent").await;
809+ let parent_id = me_id(&app, &parent).await;
810+ let peer = login(&app, "nosy").await;
811+ let student = login(&app, "kid").await;
812+ let student_id = me_id(&app, &student).await;
813+
814+ let class = create_class(&app, &manager, "9-A", "9").await;
815+ add_member(&app, &manager, &class, &student_id).await;
816+ link_student(&app, &admin, &parent_id, &student_id).await;
817+
818+ Section {
819+ app,
820+ manager,
821+ teacher,
822+ parent,
823+ peer,
824+ student,
825+ student_id,
826+ }
827+}
828+
829+async fn create_class(app: &Router, manager: &str, name: &str, grade: &str) -> String {
830+ let res = send(
831+ app,
832+ "POST",
833+ "/classes",
834+ Some(manager),
835+ Some(json!({ "name": name, "grade": grade })),
836+ )
837+ .await;
838+ assert_eq!(
839+ res.status,
840+ StatusCode::CREATED,
841+ "create class: {}",
842+ res.body
843+ );
844+ id_of(&res.body["class"])
845+}
846+
847+async fn add_member(app: &Router, manager: &str, class: &str, user_id: &str) {
848+ let res = send(
849+ app,
850+ "POST",
851+ &format!("/classes/{class}/members"),
852+ Some(manager),
853+ Some(json!({ "user_id": user_id })),
854+ )
855+ .await;
856+ assert!(res.status.is_success(), "add member: {}", res.body);
857+}
858+
859+/// The class names a profile's class block hands `cookie`.
860+async fn class_names(app: &Router, cookie: &str, id: &str) -> Vec<String> {
861+ let res = profile(app, cookie, id).await;
862+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
863+ res.body["classes"]
864+ .as_array()
865+ .expect("classes array")
866+ .iter()
867+ .map(|class| class["name"].as_str().expect("name").to_string())
868+ .collect()
869+}
870+
871+/// The class ids off the same block, sorted — the drift guard's left half.
872+async fn profile_class_ids(app: &Router, cookie: &str, id: &str) -> Vec<String> {
873+ let res = profile(app, cookie, id).await;
874+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
875+ let mut ids: Vec<String> = res.body["classes"]
876+ .as_array()
877+ .expect("classes array")
878+ .iter()
879+ .map(id_of)
880+ .collect();
881+ ids.sort();
882+ ids
883+}
884+
885+/// The class ids the *dedicated* routes hand that same reader for that same
886+/// subject — `None` when they are refused outright. Your own classes are
887+/// `GET /classes/me`; anybody else's are `GET /classes/user/{id}`.
888+async fn route_class_ids(app: &Router, cookie: &str, id: &str, own: bool) -> Option<Vec<String>> {
889+ let path = match own {
890+ true => "/classes/me".to_string(),
891+ false => format!("/classes/user/{id}"),
892+ };
893+ let res = send(app, "GET", &path, Some(cookie), None).await;
894+ if res.status == StatusCode::FORBIDDEN {
895+ return None;
896+ }
897+ assert_eq!(res.status, StatusCode::OK, "GET {path}: {}", res.body);
898+ let mut ids: Vec<String> = items(&res.body).iter().map(id_of).collect();
899+ ids.sort();
900+ Some(ids)
901+}
902+
903+/// The leak this closes: a class a reader is `403`'d from at
904+/// `GET /classes/user/{id}` used to arrive off that student's profile, name and
905+/// grade and all, for any authenticated account. The 403 is asserted in the
906+/// same test so the two answers cannot drift apart unnoticed.
907+#[tokio::test]
908+async fn a_profile_never_names_a_class_the_reader_is_403d_from() {
909+ let s = section().await;
910+
911+ let direct = send(
912+ &s.app,
913+ "GET",
914+ &format!("/classes/user/{}", s.student_id),
915+ Some(&s.peer),
916+ None,
917+ )
918+ .await;
919+ assert_eq!(direct.status, StatusCode::FORBIDDEN, "{}", direct.body);
920+
921+ let seen = profile(&s.app, &s.peer, &s.student_id).await;
922+ assert_eq!(seen.status, StatusCode::OK, "{}", seen.body);
923+ assert_eq!(seen.body["classes"], json!([]));
924+ assert!(
925+ !seen.body.to_string().contains("9-A"),
926+ "the profile leaked a class the reader cannot read: {}",
927+ seen.body
928+ );
929+}
930+
931+/// The half that proves the gate is the gate and not a broken read: everyone
932+/// who may ask the class routes directly still gets the block.
933+#[tokio::test]
934+async fn teacher_parent_manager_and_the_owner_still_read_the_class_block() {
935+ let s = section().await;
936+
937+ assert_eq!(
938+ class_names(&s.app, &s.teacher, &s.student_id).await,
939+ ["9-A"]
940+ );
941+ assert_eq!(
942+ class_names(&s.app, &s.manager, &s.student_id).await,
943+ ["9-A"]
944+ );
945+ assert_eq!(class_names(&s.app, &s.parent, &s.student_id).await, ["9-A"]);
946+ assert_eq!(
947+ class_names(&s.app, &s.student, &s.student_id).await,
948+ ["9-A"]
949+ );
950+
951+ let mine = send(&s.app, "GET", "/users/me/profile", Some(&s.student), None).await;
952+ assert_eq!(mine.status, StatusCode::OK, "{}", mine.body);
953+ assert_eq!(mine.body["classes"][0]["name"], "9-A");
954+ assert_eq!(mine.body["classes"][0]["grade"], "9");
955+}
956+
957+/// `stats.classes` is the owner's true total, deliberately *not* the length of
958+/// the gated block — the same call already made for `stats.courses`: it is the
959+/// motivational counter, and a magnitude names no class.
960+#[tokio::test]
961+async fn stats_classes_stays_the_owners_true_total() {
962+ let s = section().await;
963+
964+ let peer = profile(&s.app, &s.peer, &s.student_id).await;
965+ assert_eq!(peer.body["classes"], json!([]));
966+ assert_eq!(peer.body["stats"]["classes"], 1);
967+
968+ let teacher = profile(&s.app, &s.teacher, &s.student_id).await;
969+ assert_eq!(teacher.body["stats"]["classes"], 1);
970+}
971+
972+/// The forcing function: for every reader, the profile's class block must say
973+/// exactly what the dedicated class route says to that same reader — an empty
974+/// block where the route is a `403`, the identical id set where it is a `200`.
975+/// Whichever surface moves first, this fails. (One class, so the block's
976+/// `max_profile_classes` truncation cannot make the two disagree honestly.)
977+#[tokio::test]
978+async fn the_profile_class_block_agrees_with_the_class_route() {
979+ let s = section().await;
980+ let readers = [
981+ ("peer", &s.peer, false),
982+ ("teacher", &s.teacher, false),
983+ ("manager", &s.manager, false),
984+ ("parent", &s.parent, false),
985+ ("owner", &s.student, true),
986+ ];
987+
988+ let mut refused = 0;
989+ let mut served = 0;
990+ for (who, cookie, own) in readers {
991+ let route = route_class_ids(&s.app, cookie, &s.student_id, own).await;
992+ let block = profile_class_ids(&s.app, cookie, &s.student_id).await;
993+ match &route {
994+ None => refused += 1,
995+ Some(ids) if !ids.is_empty() => served += 1,
996+ Some(_) => {}
997+ }
998+ assert_eq!(
999+ route.unwrap_or_default(),
1000+ block,
1001+ "{who}: the profile's class block and the class route disagree"
1002+ );
1003+ }
1004+ // Neither half may pass vacuously: somebody was refused, somebody was served.
1005+ assert_eq!(refused, 1, "exactly the peer is refused the class route");
1006+ assert_eq!(served, 4, "the other four are served a non-empty list");
1007+}
1008+
782 // --- Badges ---------------------------------------------------------------1009 // --- Badges ---------------------------------------------------------------
783 //1010 //
784 // Badges are *permanent*: an award row is stamped once and nothing ever moves1011 // Badges are *permanent*: an award row is stamped once and nothing ever moves