forge
Explore
Log in

Don't you dare go Hollow

Drop enrollments when a user leaves the student role

Browse files at this commit

6917977a0456668d0f800aab3c4bebe812f7064eAhmet Kaan GümüşParent: 05cfa93
  • fix
    • drop enrollments when a user leaves the student role
Show full message
🐛 fix(users): drop enrollments when a user leaves the student role

Enrollment is student-only, but promotion left the rows behind: the
ex-student stayed on course rosters, inflated the live monitor's
enrolled/absent counts, and kept course view access. Security paths
always re-checked the live role — this is roster hygiene, not a hole.

PATCH /users/{id}/role to any non-student role now sweeps the target's
enrollments, and a boot backfill deletes rows already stale on disk
(including rows whose user record is gone: user.role = NONE).
README.mdmodified+1 -1
@@ -286,7 +286,7 @@ their existing shapes: the student exam-room reads
286 | GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` — find users by username/name fragment (pickers); refs only, no contact info · paged |286 | GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` — find users by username/name fragment (pickers); refs only, no contact info · paged |
287 | GET | `/users` | admin | List all users · paged |287 | GET | `/users` | admin | List all users · paged |
288 | GET | `/users/{id}` | admin | Get one user |288 | GET | `/users/{id}` | admin | Get one user |
289-| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role |289+| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |
290 | PATCH | `/users/{id}/profile` | admin | Update any user's personal info |290 | PATCH | `/users/{id}/profile` | admin | Update any user's personal info |
291 | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |291 | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |
292 | POST | `/notes` | student | `{title, content?}` |292 | POST | `/notes` | student | `{title, content?}` |
src/database.rsmodified+5 -0
@@ -245,6 +245,11 @@ const BACKFILL: &str = "
245 };245 };
246 UPDATE $ev.id SET audience = { kind: 'registration' };246 UPDATE $ev.id SET audience = { kind: 'registration' };
247 };247 };
248+
249+ -- Promotion out of student now deletes the user's enrollments (2026-07-18);
250+ -- this sweeps rows promoted before that fix. A deleted user reads as
251+ -- `user.role = NONE`, which is also != 'student' — those rows go too.
252+ DELETE enrollment WHERE user.role != 'student';
248 ";253 ";
249 254
250 /// Open the file-backed database and apply the schema.255 /// Open the file-backed database and apply the schema.
src/domain/enrollment.rsmodified+10 -0
@@ -109,6 +109,16 @@ impl Enrollment {
109 Ok(result.take::<Vec<Enrollment>>(0)?)109 Ok(result.take::<Vec<Enrollment>>(0)?)
110 }110 }
111 111
112+ /// Drop every enrollment `user` holds, across all courses. Only students
113+ /// enroll, so promotion out of `student` calls this to clear the rosters.
114+ pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> {
115+ db.query("DELETE enrollment WHERE user = $usr")
116+ .bind(("usr", user.record()))
117+ .await?
118+ .check()?;
119+ Ok(())
120+ }
121+
112 pub async fn remove(122 pub async fn remove(
113 course: &CourseId,123 course: &CourseId,
114 user: &UserId,124 user: &UserId,
src/web/users.rsmodified+9 -0
@@ -6,6 +6,7 @@ use utoipa_axum::router::OpenApiRouter;
6 use utoipa_axum::routes;6 use utoipa_axum::routes;
7 7
8 use crate::database::Database;8 use crate::database::Database;
9+use crate::domain::enrollment::Enrollment;
9 use crate::domain::preferences::{Language, Theme};10 use crate::domain::preferences::{Language, Theme};
10 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};11 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};
11 use crate::domain::role::Role;12 use crate::domain::role::Role;
@@ -358,6 +359,8 @@ async fn update_user_preferences(
358 /// Set a user's role. Admin only. An admin cannot change their own role — that359 /// Set a user's role. Admin only. An admin cannot change their own role — that
359 /// guard keeps a sole admin from accidentally locking everyone out of role360 /// guard keeps a sole admin from accidentally locking everyone out of role
360 /// management (recover such a lockout with the SurrealQL in the README).361 /// management (recover such a lockout with the SurrealQL in the README).
362+/// Setting any non-`student` role also drops the user's course enrollments —
363+/// only students enroll, so a promoted user leaves every roster.
361 #[utoipa::path(364 #[utoipa::path(
362 patch,365 patch,
363 path = "/{id}/role",366 path = "/{id}/role",
@@ -388,5 +391,11 @@ async fn set_role(
388 .await?391 .await?
389 .ok_or(AppError::NotFound)?;392 .ok_or(AppError::NotFound)?;
390 let updated = user.set_role(role, &st.db).await?;393 let updated = user.set_role(role, &st.db).await?;
394+ // Roster hygiene: only students enroll, so a non-student sheds all their
395+ // enrollment rows (security checks re-read the live role and never
396+ // trusted these; this just stops them polluting rosters and counts).
397+ if role != Role::Student {
398+ Enrollment::delete_for_user(&target, &st.db).await?;
399+ }
391 Ok(Json(UserResponse::new(&updated)))400 Ok(Json(UserResponse::new(&updated)))
392 }401 }
tests/integration.rsmodified+64 -4
@@ -4556,10 +4556,11 @@ async fn only_students_can_be_enrolled() {
4556 }4556 }
4557 4557
4558 /// The student-only rule is enforced on the *live* role, not merely at enroll4558 /// The student-only rule is enforced on the *live* role, not merely at enroll
4559-/// time. A student enrolled mid-course, then promoted to staff, keeps the4559+/// time. This flips the role directly in the DB (bypassing the admin endpoint,
4560-/// enrollment row — but it goes inert: they can no longer sit the exam, save4560+/// which also sweeps enrollments — and boot sweeps rows like this one), so the
4561-/// answers, be graded, or be marked present. This is the "stale rows stay4561+/// enrollment row is still present — but inert: they can no longer sit the
4562-/// inert" decision, made airtight by the action-time checks.4562+/// exam, save answers, be graded, or be marked present. The action-time checks
4563+/// alone hold, with no help from roster hygiene.
4563 #[tokio::test]4564 #[tokio::test]
4564 async fn promotion_out_of_student_freezes_the_seat() {4565 async fn promotion_out_of_student_freezes_the_seat() {
4565 let (app, db) = app_and_db().await;4566 let (app, db) = app_and_db().await;
@@ -4659,6 +4660,65 @@ async fn promotion_out_of_student_freezes_the_seat() {
4659 );4660 );
4660 }4661 }
4661 4662
4663+/// Promotion through the admin role endpoint doesn't just freeze the seat —
4664+/// it deletes the user's enrollment rows outright, so a promoted user drops
4665+/// off course rosters and live-monitor counts instead of lingering.
4666+#[tokio::test]
4667+async fn promotion_via_role_endpoint_sweeps_enrollments() {
4668+ let (app, db) = app_and_db().await;
4669+ let admin = login_as(&app, &db, "boss", "admin").await;
4670+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
4671+ let student = login(&app, "veli").await;
4672+ let student_id = me_id(&app, &student).await;
4673+
4674+ let course = create_course(&app, &teacher, "algebra").await;
4675+ enroll(&app, &teacher, &course, &student_id).await;
4676+ let roster = send(
4677+ &app,
4678+ "GET",
4679+ &format!("/courses/{course}/enrollments"),
4680+ Some(&teacher),
4681+ None,
4682+ )
4683+ .await;
4684+ assert_eq!(common::total(&roster.body), 1);
4685+
4686+ let res = send(
4687+ &app,
4688+ "PATCH",
4689+ &format!("/users/{student_id}/role"),
4690+ Some(&admin),
4691+ Some(json!({ "role": "teacher" })),
4692+ )
4693+ .await;
4694+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
4695+
4696+ let roster = send(
4697+ &app,
4698+ "GET",
4699+ &format!("/courses/{course}/enrollments"),
4700+ Some(&teacher),
4701+ None,
4702+ )
4703+ .await;
4704+ assert_eq!(
4705+ common::total(&roster.body),
4706+ 0,
4707+ "promoted user left the roster: {}",
4708+ roster.body
4709+ );
4710+
4711+ // Really deleted, not merely filtered out of the listing.
4712+ let mut result = db
4713+ .query("SELECT VALUE id FROM enrollment")
4714+ .await
4715+ .expect("count enrollments")
4716+ .check()
4717+ .expect("count enrollments check");
4718+ let rows: Vec<surrealdb::types::RecordId> = result.take(0).expect("enrollment rows");
4719+ assert!(rows.is_empty(), "enrollment rows deleted from the DB");
4720+}
4721+
4662 /// Regression: `User::create` pre-checks the username and then inserts, so two4722 /// Regression: `User::create` pre-checks the username and then inserts, so two
4663 /// concurrent registrations of the same name could both pass the check; the4723 /// concurrent registrations of the same name could both pass the check; the
4664 /// loser then hit the unique index and surfaced as a raw 500. A lost race must4724 /// loser then hit the unique index and surfaced as a raw 500. A lost race must
tests/persistence.rsmodified+86 -0
@@ -843,3 +843,89 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() {
843 let answers: Vec<surrealdb::types::RecordId> = result.take(0).expect("answer rows");843 let answers: Vec<surrealdb::types::RecordId> = result.take(0).expect("answer rows");
844 assert!(answers.is_empty(), "orphaned answers destroyed");844 assert!(answers.is_empty(), "orphaned answers destroyed");
845 }845 }
846+
847+/// Enrollment rows whose user is no longer a student — promoted before the
848+/// role endpoint swept enrollments (2026-07-18), or deleted outright — are
849+/// removed by the boot backfill. A real student's row survives.
850+#[tokio::test]
851+async fn stale_staff_enrollments_are_swept_on_boot() {
852+ let dir = tempfile::tempdir().unwrap();
853+ let cfg = config_at(&dir);
854+ let creds = json!({ "username": "ali", "password": "secret1" });
855+ let course;
856+ let keeper_id;
857+
858+ // First boot: a course with three enrolled students, then age two rows the
859+ // way a pre-fix binary could have — flip one student to teacher directly
860+ // in the DB, and delete the other's user record entirely.
861+ {
862+ let db = database::init(&cfg).await.expect("first open");
863+ let app = build_router(state(db.clone(), &cfg));
864+ assert_eq!(
865+ send(&app, "POST", "/auth/register", None, Some(creds.clone()))
866+ .await
867+ .status,
868+ StatusCode::CREATED
869+ );
870+ set_role(&db, "ali", "teacher").await;
871+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone()))
872+ .await
873+ .cookie
874+ .unwrap();
875+ course = create_course(&app, &cookie, "algebra").await;
876+
877+ let mut ids = Vec::new();
878+ for name in ["veli", "ayse", "can"] {
879+ let student = json!({ "username": name, "password": "secret1" });
880+ assert_eq!(
881+ send(&app, "POST", "/auth/register", None, Some(student.clone()))
882+ .await
883+ .status,
884+ StatusCode::CREATED
885+ );
886+ let student_cookie = send(&app, "POST", "/auth/login", None, Some(student))
887+ .await
888+ .cookie
889+ .unwrap();
890+ let id = me_id(&app, &student_cookie).await;
891+ enroll(&app, &cookie, &course, &id).await;
892+ ids.push(id);
893+ }
894+ keeper_id = ids[1].clone();
895+ set_role(&db, "veli", "teacher").await;
896+ db.query("DELETE user WHERE username = 'can'")
897+ .await
898+ .expect("delete user")
899+ .check()
900+ .expect("delete user check");
901+ }
902+
903+ // Second boot: the backfill swept the promoted user's row and the deleted
904+ // user's dangling row; the remaining student's enrollment is intact.
905+ let db = reopen(&cfg).await;
906+ let app = build_router(state(db, &cfg));
907+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds))
908+ .await
909+ .cookie
910+ .unwrap();
911+ let roster = send(
912+ &app,
913+ "GET",
914+ &format!("/courses/{course}/enrollments"),
915+ Some(&cookie),
916+ None,
917+ )
918+ .await;
919+ assert_eq!(roster.status, StatusCode::OK, "{}", roster.body);
920+ assert_eq!(
921+ common::total(&roster.body),
922+ 1,
923+ "stale rows swept: {}",
924+ roster.body
925+ );
926+ assert_eq!(
927+ common::items(&roster.body)[0]["user"]["id"],
928+ keeper_id.as_str(),
929+ "the real student's row survives"
930+ );
931+}