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

tenant_state.rs379 lines, 14.4 KiBHistoryRawDownload
1//! The school-scoped replacement for `axum::extract::State`.
2//!
3//! [`State`] is named to **shadow** `axum::extract::State` on purpose: a
4//! handler file swaps one import and every `State(st)` in it starts working in
5//! the caller's school instead of the control database, with no handler body
6//! touched. That is the whole design — there is no `st.db` a handler could
7//! forget to scope, because the only `st` it can name is already scoped.
8//!
9//! Three files keep the real `axum::extract::State` because they legitimately
10//! see the control database: `web::auth` (it resolves the school itself, and
11//! its rate limiter is deployment-wide), `web::limits` (constants, no rows) and
12//! `web::ai` (bridge certificate, no rows).
13
14use std::path::PathBuf;
15
16use axum::extract::{FromRef, FromRequestParts};
17use axum::http::request::Parts;
18use axum_extra::extract::CookieJar;
19
20use crate::database::Database;
21use crate::error::AppError;
22use crate::module::ModuleSet;
23use crate::state::AppState;
24use crate::tenant::{ResolvedTenant, SchoolId};
25
26/// The school a request has already been resolved into, injected as a request
27/// extension by an in-process caller that has no cookie — today only the AI
28/// bridge. Extensions cannot be set from outside the process, so this is
29/// unforgeable over HTTP, exactly like
30/// [`crate::web::extractor::AiPrincipal`].
31#[derive(Clone)]
32pub struct TenantExt {
33 pub id: SchoolId,
34 pub db: Database,
35 pub modules: ModuleSet,
36}
37
38/// Split a `session` cookie into its school part and its token. `builder` in
39/// the first position is the deployment operator; anything else is a school
40/// uuid. Splits at the **first** dot, so a token can never be mistaken for
41/// the school no matter what it contains.
42pub fn split_cookie(value: &str) -> Option<(&str, &str)> {
43 let (prefix, token) = value.split_once('.')?;
44 (!prefix.is_empty() && !token.is_empty()).then_some((prefix, token))
45}
46
47/// The school behind this request: the `TenantExt` extension if one was
48/// injected, else the `session` cookie's prefix.
49///
50/// Shared with [`crate::web::extractor`] so the two can never disagree about
51/// which school a request belongs to — the authenticated user and the rows
52/// they read must come from the same database.
53pub(crate) async fn resolve_tenant<S>(
54 parts: &mut Parts,
55 state: &S,
56) -> Result<ResolvedTenant, AppError>
57where
58 S: Send + Sync,
59 AppState: FromRef<S>,
60{
61 if let Some(tenant) = parts.extensions.get::<ResolvedTenant>() {
62 return Ok(tenant.clone());
63 }
64 if let Some(tenant) = parts.extensions.get::<TenantExt>() {
65 return Ok(ResolvedTenant {
66 id: tenant.id,
67 db: tenant.db.clone(),
68 modules: tenant.modules.clone(),
69 });
70 }
71 let jar = CookieJar::from_request_parts(parts, state)
72 .await
73 .map_err(|_| AppError::Unauthorized)?;
74 let cookie = jar.get("session").ok_or(AppError::Unauthorized)?;
75 // A builder cookie names no school, and a cookie with no dot names nothing
76 // at all. Both are `401` here: the builder surface is a different extractor
77 // (`RequireBuilder`), and this one must never let it in.
78 let (prefix, _) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?;
79 let id = SchoolId::try_parse(prefix).map_err(|_| AppError::Unauthorized)?;
80
81 let app = AppState::from_ref(state);
82 let resolved = app.tenants.resolve(&id).await?;
83 // The one caller-derived label telemetry is allowed to carry: which school,
84 // never which user. The span field and the metric slot are set together so
85 // a trace and its latency sample agree. Field name stays `school`.
86 let label = id.as_str();
87 tracing::Span::current().record("school", label.as_str());
88 if let Some(slot) = parts.extensions.get::<crate::telemetry::SchoolSlot>() {
89 slot.set(&label);
90 }
91 // Memoized on the request, not just returned: the next extractor on this
92 // same request (and the module gate ahead of both) reuses this verdict
93 // instead of re-reading the registry row.
94 parts.extensions.insert(resolved.clone());
95 Ok(resolved)
96}
97
98/// The application state, narrowed to the caller's school. Drop-in for
99/// `axum::extract::State<AppState>` in every handler that reads school data.
100///
101/// Unauthenticated callers are refused *here*, before the handler runs — which
102/// is correct for every route that uses it, since all of them already require a
103/// session to do anything.
104pub struct State<T>(pub T);
105
106impl<S> FromRequestParts<S> for State<AppState>
107where
108 S: Send + Sync,
109 AppState: FromRef<S>,
110{
111 type Rejection = AppError;
112
113 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
114 let tenant = resolve_tenant(parts, state).await?;
115 let app = AppState::from_ref(state);
116 Ok(State(AppState {
117 db: tenant.db,
118 files_path: school_files_path(&app.files_path, &tenant.id),
119 ..app
120 }))
121 }
122}
123
124/// The resolved school itself, for a handler that must carry it somewhere the
125/// request does not reach — today the chatbot's detached answer task, which
126/// hands it back to the bridge as a [`TenantExt`].
127impl<S> FromRequestParts<S> for ResolvedTenant
128where
129 S: Send + Sync,
130 AppState: FromRef<S>,
131{
132 type Rejection = AppError;
133
134 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
135 resolve_tenant(parts, state).await
136 }
137}
138
139/// Just the school, for the handlers that need it as a key prefix (the exam
140/// presence map, the whiteboard hub) rather than as a database handle.
141pub struct SchoolIdCookie(pub SchoolId);
142
143impl<S> FromRequestParts<S> for SchoolIdCookie
144where
145 S: Send + Sync,
146 AppState: FromRef<S>,
147{
148 type Rejection = AppError;
149
150 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
151 Ok(SchoolIdCookie(resolve_tenant(parts, state).await?.id))
152 }
153}
154
155/// Where a school's uploaded blobs live: one directory per school under the
156/// deployment's `FILES_PATH`. The id's hyphenated form contains no separator
157/// and no `..`, so this is a plain `join`.
158pub fn school_files_path(root: &std::path::Path, id: &SchoolId) -> PathBuf {
159 root.join(id.as_str())
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165
166 use axum::http::StatusCode;
167 use axum::routing::get;
168 use axum::{Router, body::Body, http::Request};
169 use tower::ServiceExt;
170
171 use crate::database::init_test_tenants;
172 use crate::db::session;
173 use crate::domain::user::{Password, Username};
174 use crate::tenant::DEMO_SCHOOL_ID;
175 use crate::web::{CurrentUser, RequireBuilder};
176
177 async fn school_surface(State(_): State<AppState>, CurrentUser(_): CurrentUser) -> StatusCode {
178 StatusCode::OK
179 }
180
181 async fn builder_surface(RequireBuilder(_): RequireBuilder) -> StatusCode {
182 StatusCode::OK
183 }
184
185 /// A two-route app, one live cookie of each kind, and the registry behind
186 /// them.
187 async fn harness() -> (Router, String, String, crate::tenant::Tenants) {
188 let tenants = init_test_tenants().await;
189 let school = tenants
190 .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap())
191 .await
192 .expect("the demo school");
193
194 let user = crate::service::user::create(&school, Username::try_new("ada").unwrap(), None)
195 .await
196 .unwrap();
197 let session = session::create(&school, user.get_id()).await.unwrap();
198 let school_cookie = format!("session={DEMO_SCHOOL_ID}.{}", session.token().as_str());
199
200 crate::service::builder::ensure(
201 tenants.control(),
202 Username::try_new("operator").unwrap(),
203 Password::try_new("secret1").unwrap(),
204 )
205 .await
206 .unwrap();
207 let builder = crate::service::builder::find_by_username(tenants.control(), "operator")
208 .await
209 .unwrap()
210 .unwrap();
211 let builder_session =
212 crate::service::builder::create_session(tenants.control(), builder.get_id())
213 .await
214 .unwrap();
215 let builder_cookie = format!("session=builder.{}", builder_session.token().as_str());
216
217 let state = AppState {
218 db: tenants.control().clone(),
219 tenants: tenants.clone(),
220 files_path: std::env::temp_dir(),
221 cookie_secure: false,
222 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
223 chatbot_limit: Default::default(),
224 rag_limit: Default::default(),
225 exam_presence: Default::default(),
226 board_hub: Default::default(),
227 ai: None,
228 metrics: crate::telemetry::Metrics::noop(),
229 };
230 let app = Router::new()
231 .route("/school", get(school_surface))
232 .route("/builder", get(builder_surface))
233 .with_state(state);
234 (app, school_cookie, builder_cookie, tenants)
235 }
236
237 async fn status(app: &Router, uri: &str, cookie: Option<&str>) -> StatusCode {
238 let mut builder = Request::builder().uri(uri);
239 if let Some(cookie) = cookie {
240 builder = builder.header("cookie", cookie);
241 }
242 app.clone()
243 .oneshot(builder.body(Body::empty()).unwrap())
244 .await
245 .unwrap()
246 .status()
247 }
248
249 /// The two principals share a cookie name and nothing else. Neither may
250 /// ever be accepted where the other belongs — a builder holding school
251 /// power, or a student reaching the school-management surface, is the one
252 /// failure this whole split exists to prevent.
253 #[tokio::test]
254 async fn neither_cookie_works_on_the_others_surface() {
255 let (app, school, builder, _) = harness().await;
256
257 assert_eq!(status(&app, "/school", Some(&school)).await, StatusCode::OK);
258 assert_eq!(
259 status(&app, "/builder", Some(&builder)).await,
260 StatusCode::OK
261 );
262
263 assert_eq!(
264 status(&app, "/school", Some(&builder)).await,
265 StatusCode::UNAUTHORIZED,
266 "a builder cookie must not pass a school extractor"
267 );
268 assert_eq!(
269 status(&app, "/builder", Some(&school)).await,
270 StatusCode::UNAUTHORIZED,
271 "a school cookie must not pass RequireBuilder"
272 );
273
274 // A cookie with no school part names nothing resolvable — including the
275 // pre-tenancy shape, which is deliberately not accepted anywhere.
276 let bare = school.replace(&format!("{DEMO_SCHOOL_ID}."), "");
277 for uri in ["/school", "/builder"] {
278 assert_eq!(
279 status(&app, uri, Some(&bare)).await,
280 StatusCode::UNAUTHORIZED,
281 "{uri} accepted a cookie with no school"
282 );
283 assert_eq!(
284 status(&app, uri, None).await,
285 StatusCode::UNAUTHORIZED,
286 "{uri} accepted no cookie at all"
287 );
288 }
289 }
290
291 /// A suspended school is refused at the edge, before any handler — with a
292 /// session that was perfectly good a moment earlier, and through a handle
293 /// the registry had already cached.
294 #[tokio::test]
295 async fn a_suspension_refuses_a_live_session() {
296 let (app, school, _, tenants) = harness().await;
297 let demo = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
298 assert_eq!(status(&app, "/school", Some(&school)).await, StatusCode::OK);
299
300 tenants
301 .set_status(&demo, crate::tenant::SchoolStatus::Suspended)
302 .await
303 .unwrap();
304 assert_eq!(
305 status(&app, "/school", Some(&school)).await,
306 StatusCode::FORBIDDEN,
307 "a suspended school must be refused immediately, cached handle or not"
308 );
309
310 tenants
311 .set_status(&demo, crate::tenant::SchoolStatus::Active)
312 .await
313 .unwrap();
314 assert_eq!(
315 status(&app, "/school", Some(&school)).await,
316 StatusCode::OK,
317 "un-suspending must restore the very same session"
318 );
319 }
320
321 /// One request, one registry read. Measured by making the registry answer
322 /// *differently* the second time: the school is suspended between the two
323 /// extractor calls on the same request, so a second read would refuse. It
324 /// still passes — the verdict came from the memoized extension.
325 #[tokio::test]
326 async fn a_request_resolves_its_school_exactly_once() {
327 let tenants = init_test_tenants().await;
328 let demo = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
329 let state = AppState {
330 db: tenants.control().clone(),
331 tenants: tenants.clone(),
332 files_path: std::env::temp_dir(),
333 cookie_secure: false,
334 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
335 chatbot_limit: Default::default(),
336 rag_limit: Default::default(),
337 exam_presence: Default::default(),
338 board_hub: Default::default(),
339 ai: None,
340 metrics: crate::telemetry::Metrics::noop(),
341 };
342 let request = Request::builder()
343 .uri("/school")
344 .header("cookie", format!("session={DEMO_SCHOOL_ID}.whatever"))
345 .body(Body::empty())
346 .unwrap();
347 let (mut parts, _) = request.into_parts();
348
349 resolve_tenant(&mut parts, &state)
350 .await
351 .expect("the first resolve reads the registry");
352 assert!(
353 parts.extensions.get::<ResolvedTenant>().is_some(),
354 "the first resolve must memoize its verdict on the request"
355 );
356
357 tenants
358 .set_status(&demo, crate::tenant::SchoolStatus::Suspended)
359 .await
360 .unwrap();
361 let second = resolve_tenant(&mut parts, &state)
362 .await
363 .expect("a second read would have seen the suspension and refused");
364 assert_eq!(second.id, demo);
365 }
366
367 #[test]
368 fn a_cookie_splits_at_its_first_dot_or_not_at_all() {
369 assert_eq!(split_cookie("demo.abc123"), Some(("demo", "abc123")));
370 assert_eq!(split_cookie("builder.abc123"), Some(("builder", "abc123")));
371 // First dot, so a dotted token still yields the school it named.
372 assert_eq!(split_cookie("demo.a.b"), Some(("demo", "a.b")));
373 // A pre-tenancy cookie, an empty half, or nothing at all names no
374 // school — every one of these must be refused, not guessed at.
375 for bad in ["abc123", "", ".", "demo.", ".abc123"] {
376 assert_eq!(split_cookie(bad), None, "{bad:?}");
377 }
378 }
379}