forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

regress_admin_floor.rs189 lines, 6.7 KiBHistoryRawDownload
1//! Regressions for the two holes the 2026-08-05 hunt left standing on the
2//! role/parent-link surface: two admins demoting each other could empty the
3//! admin set for good, and a parent's student list named accounts that had
4//! since been promoted out of `student`.
5//!
6//! Every assertion re-reads the *store*. The in-memory engine forges wins under
7//! concurrency (src/domain/cap.rs), so the race below is judged on how many
8//! admins survive, never on which request answered what.
9
10mod common;
11
12use axum::http::StatusCode;
13use common::{app_and_db, login_as, me_id, send};
14use hezarfen_backend::database::Database;
15use hezarfen_backend::domain::role::Role;
16use hezarfen_backend::domain::user::UserId;
17use serde_json::json;
18
19/// How many accounts hold `admin` right now, out of the store.
20async fn admin_count(db: &Database) -> usize {
21 sqlx::query_scalar::<_, i64>("SELECT count(*) FROM app_user WHERE role = 'admin'")
22 .fetch_one(db)
23 .await
24 .unwrap() as usize
25}
26
27/// Two admins demote each other at the same instant. Both `RequireAdmin`
28/// extractors resolve against the live rows before either write lands, so
29/// before the floor guard both writes committed and the school was left with
30/// **zero** admins — unrecoverable, since the boot seed refuses to promote an
31/// existing non-admin row.
32#[tokio::test]
33async fn two_admins_demoting_each_other_leave_one() {
34 let (app, db) = app_and_db().await;
35 let ada = login_as(&app, &db, "ada", "admin").await;
36 let bora = login_as(&app, &db, "bora", "admin").await;
37 let ada_id = me_id(&app, &ada).await;
38 let bora_id = me_id(&app, &bora).await;
39 assert_eq!(admin_count(&db).await, 2);
40
41 let (one, two) = {
42 let (app_a, app_b) = (app.clone(), app.clone());
43 let demote = |app: axum::Router, cookie: String, target: String| async move {
44 send(
45 &app,
46 "PATCH",
47 &format!("/users/{target}/role"),
48 Some(&cookie),
49 Some(json!({ "role": "student" })),
50 )
51 .await
52 .status
53 };
54 tokio::join!(
55 tokio::spawn(demote(app_a, ada.clone(), bora_id)),
56 tokio::spawn(demote(app_b, bora.clone(), ada_id)),
57 )
58 };
59 let (one, two) = (one.unwrap(), two.unwrap());
60
61 // The stored state is the invariant — not who was told they won.
62 assert!(
63 admin_count(&db).await >= 1,
64 "both demotions landed and the school has no admin left ({one}, {two})"
65 );
66}
67
68/// The floor itself, driven where it is deterministic. Over HTTP the `409` is
69/// reachable only through the race above (demoting an admin needs a *second*
70/// admin logged in, so sequentially the target is never the last one), which is
71/// exactly why the guard has to live in the writer rather than the handler.
72#[tokio::test]
73async fn set_role_refuses_the_last_admin() {
74 let (app, db) = app_and_db().await;
75 let ada = login_as(&app, &db, "ada", "admin").await;
76 let ada_id = UserId::from_key(&me_id(&app, &ada).await);
77
78 hezarfen_backend::db::user::read(&db, &ada_id).await.unwrap().unwrap();
79 let refused = hezarfen_backend::service::user::set_role(&db, &ada_id, Role::Student).await;
80 assert!(refused.is_err(), "the sole admin was demoted");
81 assert_eq!(admin_count(&db).await, 1, "the admin row was still lowered");
82
83 // Promotion is never refused, and the floor lifts once a second admin is in
84 // place: the guard is "keep one", not "freeze the set".
85 let bora = login_as(&app, &db, "bora", "student").await;
86 let bora_id = me_id(&app, &bora).await;
87 let res = send(
88 &app,
89 "PATCH",
90 &format!("/users/{bora_id}/role"),
91 Some(&ada),
92 Some(json!({ "role": "admin" })),
93 )
94 .await;
95 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
96 hezarfen_backend::db::user::read(&db, &ada_id).await.unwrap().unwrap();
97 assert!(
98 hezarfen_backend::service::user::set_role(&db, &ada_id, Role::Student)
99 .await
100 .is_ok()
101 );
102 assert_eq!(admin_count(&db).await, 1);
103}
104
105/// The self-demotion door, which the floor does not replace: an admin never
106/// changes their own role, whether or not others exist.
107#[tokio::test]
108async fn admin_cannot_demote_themselves() {
109 let (app, db) = app_and_db().await;
110 let ada = login_as(&app, &db, "ada", "admin").await;
111 login_as(&app, &db, "bora", "admin").await;
112 let ada_id = me_id(&app, &ada).await;
113
114 let res = send(
115 &app,
116 "PATCH",
117 &format!("/users/{ada_id}/role"),
118 Some(&ada),
119 Some(json!({ "role": "student" })),
120 )
121 .await;
122 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
123 assert_eq!(admin_count(&db).await, 2);
124}
125
126/// A `parent_link` whose student was promoted out — the row a lost sweep race
127/// leaves behind, and the row an older build may already have on disk. Written
128/// straight into the store (the role change is applied without `set_role`'s
129/// sweep, which is precisely the state the race produces) and then read back
130/// through both list handlers.
131#[tokio::test]
132async fn a_promoted_student_leaves_the_parent_list() {
133 let (app, db) = app_and_db().await;
134 let ada = login_as(&app, &db, "ada", "admin").await;
135 let veli = login_as(&app, &db, "veli", "parent").await;
136 let can = login_as(&app, &db, "can", "student").await;
137 let veli_id = me_id(&app, &veli).await;
138 let can_id = me_id(&app, &can).await;
139
140 let res = send(
141 &app,
142 "POST",
143 &format!("/users/{veli_id}/students"),
144 Some(&ada),
145 Some(json!({ "user_id": can_id })),
146 )
147 .await;
148 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
149 let listed = send(
150 &app,
151 "GET",
152 &format!("/users/{veli_id}/students"),
153 Some(&ada),
154 None,
155 )
156 .await;
157 assert_eq!(listed.body["total"], 1, "{}", listed.body);
158
159 common::set_role(&db, "can", "teacher").await;
160 assert_eq!(
161 rows("SELECT parent FROM parent_link", &db).await,
162 1,
163 "the stale link is the premise of this test"
164 );
165
166 for (uri, cookie) in [
167 (format!("/users/{veli_id}/students"), &ada),
168 ("/users/me/students".to_string(), &veli),
169 ] {
170 let res = send(&app, "GET", &uri, Some(cookie), None).await;
171 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
172 assert_eq!(res.body["total"], 0, "{uri}: {}", res.body);
173 assert_eq!(
174 res.body["items"].as_array().unwrap().len(),
175 0,
176 "{uri}: {}",
177 res.body
178 );
179 }
180}
181
182/// Ids `sql` selects.
183async fn rows(sql: &'static str, db: &Database) -> usize {
184 sqlx::query_as::<_, (uuid::Uuid,)>(sql)
185 .fetch_all(db)
186 .await
187 .unwrap()
188 .len()
189}