| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::path::PathBuf; |
| 15 | |
| 16 | use axum::extract::{FromRef, FromRequestParts}; |
| 17 | use axum::http::request::Parts; |
| 18 | use axum_extra::extract::CookieJar; |
| 19 | |
| 20 | use crate::database::Database; |
| 21 | use crate::error::AppError; |
| 22 | use crate::module::ModuleSet; |
| 23 | use crate::state::AppState; |
| 24 | use crate::tenant::{ResolvedTenant, SchoolId}; |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | #[derive(Clone)] |
| 32 | pub struct TenantExt { |
| 33 | pub id: SchoolId, |
| 34 | pub db: Database, |
| 35 | pub modules: ModuleSet, |
| 36 | } |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | pub 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 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | pub(crate) async fn resolve_tenant<S>( |
| 54 | parts: &mut Parts, |
| 55 | state: &S, |
| 56 | ) -> Result<ResolvedTenant, AppError> |
| 57 | where |
| 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 | |
| 76 | |
| 77 | |
| 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 | |
| 84 | |
| 85 | |
| 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 | |
| 92 | |
| 93 | |
| 94 | parts.extensions.insert(resolved.clone()); |
| 95 | Ok(resolved) |
| 96 | } |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | pub struct State<T>(pub T); |
| 105 | |
| 106 | impl<S> FromRequestParts<S> for State<AppState> |
| 107 | where |
| 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 | |
| 125 | |
| 126 | |
| 127 | impl<S> FromRequestParts<S> for ResolvedTenant |
| 128 | where |
| 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 | |
| 140 | |
| 141 | pub struct SchoolIdCookie(pub SchoolId); |
| 142 | |
| 143 | impl<S> FromRequestParts<S> for SchoolIdCookie |
| 144 | where |
| 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 | |
| 156 | |
| 157 | |
| 158 | pub fn school_files_path(root: &std::path::Path, id: &SchoolId) -> PathBuf { |
| 159 | root.join(id.as_str()) |
| 160 | } |
| 161 | |
| 162 | #[cfg(test)] |
| 163 | mod 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 | |
| 186 | |
| 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 | |
| 250 | |
| 251 | |
| 252 | |
| 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 | |
| 275 | |
| 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 | |
| 292 | |
| 293 | |
| 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 | |
| 322 | |
| 323 | |
| 324 | |
| 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 | |
| 372 | assert_eq!(split_cookie("demo.a.b"), Some(("demo", "a.b"))); |
| 373 | |
| 374 | |
| 375 | for bad in ["abc123", "", ".", "demo.", ".abc123"] { |
| 376 | assert_eq!(split_cookie(bad), None, "{bad:?}"); |
| 377 | } |
| 378 | } |
| 379 | } |