diff --git a/README.md b/README.md index 34b8380..9f8b092 100644 --- a/README.md +++ b/README.md @@ -286,7 +286,7 @@ their existing shapes: the student exam-room reads | 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}` | admin | Get one user | -| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role | +| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) | | PATCH | `/users/{id}/profile` | admin | Update any user's personal info | | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences | | POST | `/notes` | student | `{title, content?}` | diff --git a/src/database.rs b/src/database.rs index 9eda9fc..07925a5 100644 --- a/src/database.rs +++ b/src/database.rs @@ -245,6 +245,11 @@ const BACKFILL: &str = " }; UPDATE $ev.id SET audience = { kind: 'registration' }; }; + + -- Promotion out of student now deletes the user's enrollments (2026-07-18); + -- this sweeps rows promoted before that fix. A deleted user reads as + -- `user.role = NONE`, which is also != 'student' — those rows go too. + DELETE enrollment WHERE user.role != 'student'; "; /// Open the file-backed database and apply the schema. diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index 7a0641a..07eae29 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -109,6 +109,16 @@ impl Enrollment { Ok(result.take::>(0)?) } + /// Drop every enrollment `user` holds, across all courses. Only students + /// enroll, so promotion out of `student` calls this to clear the rosters. + pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> { + db.query("DELETE enrollment WHERE user = $usr") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(()) + } + pub async fn remove( course: &CourseId, user: &UserId, diff --git a/src/web/users.rs b/src/web/users.rs index 02cf7f9..57f1745 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -6,6 +6,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; +use crate::domain::enrollment::Enrollment; use crate::domain::preferences::{Language, Theme}; use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; use crate::domain::role::Role; @@ -358,6 +359,8 @@ async fn update_user_preferences( /// Set a user's role. Admin only. An admin cannot change their own role — that /// guard keeps a sole admin from accidentally locking everyone out of role /// management (recover such a lockout with the SurrealQL in the README). +/// Setting any non-`student` role also drops the user's course enrollments — +/// only students enroll, so a promoted user leaves every roster. #[utoipa::path( patch, path = "/{id}/role", @@ -388,5 +391,11 @@ async fn set_role( .await? .ok_or(AppError::NotFound)?; let updated = user.set_role(role, &st.db).await?; + // Roster hygiene: only students enroll, so a non-student sheds all their + // enrollment rows (security checks re-read the live role and never + // trusted these; this just stops them polluting rosters and counts). + if role != Role::Student { + Enrollment::delete_for_user(&target, &st.db).await?; + } Ok(Json(UserResponse::new(&updated))) } diff --git a/tests/integration.rs b/tests/integration.rs index da83816..5473e74 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -4556,10 +4556,11 @@ async fn only_students_can_be_enrolled() { } /// The student-only rule is enforced on the *live* role, not merely at enroll -/// time. A student enrolled mid-course, then promoted to staff, keeps the -/// enrollment row — but it goes inert: they can no longer sit the exam, save -/// answers, be graded, or be marked present. This is the "stale rows stay -/// inert" decision, made airtight by the action-time checks. +/// time. This flips the role directly in the DB (bypassing the admin endpoint, +/// which also sweeps enrollments — and boot sweeps rows like this one), so the +/// enrollment row is still present — but inert: they can no longer sit the +/// exam, save answers, be graded, or be marked present. The action-time checks +/// alone hold, with no help from roster hygiene. #[tokio::test] async fn promotion_out_of_student_freezes_the_seat() { let (app, db) = app_and_db().await; @@ -4659,6 +4660,65 @@ async fn promotion_out_of_student_freezes_the_seat() { ); } +/// Promotion through the admin role endpoint doesn't just freeze the seat — +/// it deletes the user's enrollment rows outright, so a promoted user drops +/// off course rosters and live-monitor counts instead of lingering. +#[tokio::test] +async fn promotion_via_role_endpoint_sweeps_enrollments() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "boss", "admin").await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let student = login(&app, "veli").await; + let student_id = me_id(&app, &student).await; + + let course = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course, &student_id).await; + let roster = send( + &app, + "GET", + &format!("/courses/{course}/enrollments"), + Some(&teacher), + None, + ) + .await; + assert_eq!(common::total(&roster.body), 1); + + let res = send( + &app, + "PATCH", + &format!("/users/{student_id}/role"), + Some(&admin), + Some(json!({ "role": "teacher" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let roster = send( + &app, + "GET", + &format!("/courses/{course}/enrollments"), + Some(&teacher), + None, + ) + .await; + assert_eq!( + common::total(&roster.body), + 0, + "promoted user left the roster: {}", + roster.body + ); + + // Really deleted, not merely filtered out of the listing. + let mut result = db + .query("SELECT VALUE id FROM enrollment") + .await + .expect("count enrollments") + .check() + .expect("count enrollments check"); + let rows: Vec = result.take(0).expect("enrollment rows"); + assert!(rows.is_empty(), "enrollment rows deleted from the DB"); +} + /// Regression: `User::create` pre-checks the username and then inserts, so two /// concurrent registrations of the same name could both pass the check; the /// loser then hit the unique index and surfaced as a raw 500. A lost race must diff --git a/tests/persistence.rs b/tests/persistence.rs index 2e68d9e..4ea4cb5 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -843,3 +843,89 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() { let answers: Vec = result.take(0).expect("answer rows"); assert!(answers.is_empty(), "orphaned answers destroyed"); } + +/// Enrollment rows whose user is no longer a student — promoted before the +/// role endpoint swept enrollments (2026-07-18), or deleted outright — are +/// removed by the boot backfill. A real student's row survives. +#[tokio::test] +async fn stale_staff_enrollments_are_swept_on_boot() { + let dir = tempfile::tempdir().unwrap(); + let cfg = config_at(&dir); + let creds = json!({ "username": "ali", "password": "secret1" }); + let course; + let keeper_id; + + // First boot: a course with three enrolled students, then age two rows the + // way a pre-fix binary could have — flip one student to teacher directly + // in the DB, and delete the other's user record entirely. + { + let db = database::init(&cfg).await.expect("first open"); + let app = build_router(state(db.clone(), &cfg)); + assert_eq!( + send(&app, "POST", "/auth/register", None, Some(creds.clone())) + .await + .status, + StatusCode::CREATED + ); + set_role(&db, "ali", "teacher").await; + let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) + .await + .cookie + .unwrap(); + course = create_course(&app, &cookie, "algebra").await; + + let mut ids = Vec::new(); + for name in ["veli", "ayse", "can"] { + let student = json!({ "username": name, "password": "secret1" }); + assert_eq!( + send(&app, "POST", "/auth/register", None, Some(student.clone())) + .await + .status, + StatusCode::CREATED + ); + let student_cookie = send(&app, "POST", "/auth/login", None, Some(student)) + .await + .cookie + .unwrap(); + let id = me_id(&app, &student_cookie).await; + enroll(&app, &cookie, &course, &id).await; + ids.push(id); + } + keeper_id = ids[1].clone(); + set_role(&db, "veli", "teacher").await; + db.query("DELETE user WHERE username = 'can'") + .await + .expect("delete user") + .check() + .expect("delete user check"); + } + + // Second boot: the backfill swept the promoted user's row and the deleted + // user's dangling row; the remaining student's enrollment is intact. + let db = reopen(&cfg).await; + let app = build_router(state(db, &cfg)); + let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) + .await + .cookie + .unwrap(); + let roster = send( + &app, + "GET", + &format!("/courses/{course}/enrollments"), + Some(&cookie), + None, + ) + .await; + assert_eq!(roster.status, StatusCode::OK, "{}", roster.body); + assert_eq!( + common::total(&roster.body), + 1, + "stale rows swept: {}", + roster.body + ); + assert_eq!( + common::items(&roster.body)[0]["user"]["id"], + keeper_id.as_str(), + "the real student's row survives" + ); +}