| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | use std::net::SocketAddr; |
| 21 | |
| 22 | use steid::{ |
| 23 | application::{AppConfig, mint_reset_for_handle}, |
| 24 | domain::SetupToken, |
| 25 | infrastructure::{ |
| 26 | app, database, |
| 27 | repository::{SqliteOrgRepo, SqlitePasswordResetRepo, SqliteUserRepo}, |
| 28 | }, |
| 29 | }; |
| 30 | use tempfile::TempDir; |
| 31 | use tokio::{net::TcpListener, sync::oneshot, task::JoinHandle}; |
| 32 | use topcoat::asset::AssetBundle; |
| 33 | |
| 34 | |
| 35 | |
| 36 | struct Instance { |
| 37 | base: String, |
| 38 | |
| 39 | setup_token: String, |
| 40 | |
| 41 | config: AppConfig, |
| 42 | |
| 43 | pool: sqlx::SqlitePool, |
| 44 | |
| 45 | _dir: TempDir, |
| 46 | stop: Option<oneshot::Sender<()>>, |
| 47 | serving: Option<JoinHandle<()>>, |
| 48 | } |
| 49 | |
| 50 | impl Instance { |
| 51 | |
| 52 | fn url(&self, path: &str) -> String { |
| 53 | format!("{}{path}", self.base) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | impl Drop for Instance { |
| 58 | fn drop(&mut self) { |
| 59 | |
| 60 | |
| 61 | |
| 62 | if let Some(stop) = self.stop.take() { |
| 63 | let _ = stop.send(()); |
| 64 | } |
| 65 | if let Some(serving) = self.serving.take() { |
| 66 | serving.abort(); |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | |
| 72 | async fn boot() -> Instance { |
| 73 | boot_with(None).await |
| 74 | } |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | async fn boot_with_owner(handle: &str, email: &str) -> Instance { |
| 84 | boot_with(Some((handle.to_owned(), email.to_owned()))).await |
| 85 | } |
| 86 | |
| 87 | async fn boot_with(owner: Option<(String, String)>) -> Instance { |
| 88 | let dir = tempfile::tempdir().expect("a temp dir"); |
| 89 | let data_dir = dir.path().join("data"); |
| 90 | std::fs::create_dir_all(&data_dir).expect("mkdir"); |
| 91 | |
| 92 | let config = AppConfig { |
| 93 | database_url: format!("sqlite:{}?mode=rwc", dir.path().join("steid.db").display()), |
| 94 | data_dir, |
| 95 | |
| 96 | |
| 97 | |
| 98 | insecure_cookies: false, |
| 99 | allow_private_webhooks: false, |
| 100 | trusted_proxy: false, |
| 101 | |
| 102 | |
| 103 | operator_token: None, |
| 104 | setup_token: None, |
| 105 | backup_marker: None, |
| 106 | smtp_url: None, |
| 107 | mail_from: None, |
| 108 | |
| 109 | |
| 110 | owner_email: owner.as_ref().map(|(_, email)| email.clone()), |
| 111 | owner_handle: owner.as_ref().map(|(handle, _)| handle.clone()), |
| 112 | public_url: None, |
| 113 | }; |
| 114 | |
| 115 | let pool = database::connect(&config.database_url) |
| 116 | .await |
| 117 | .expect("the database opens"); |
| 118 | |
| 119 | |
| 120 | |
| 121 | let seeded = app::seed_owner_on_boot(&config, &pool) |
| 122 | .await |
| 123 | .expect("the configured owner is created"); |
| 124 | assert_eq!( |
| 125 | seeded.is_some(), |
| 126 | owner.is_some(), |
| 127 | "a configured owner must actually be created" |
| 128 | ); |
| 129 | |
| 130 | let token = SetupToken::generate(); |
| 131 | let setup_token = token.reveal().to_owned(); |
| 132 | let setup = if seeded.is_some() { None } else { Some(token) }; |
| 133 | |
| 134 | let router = app::build(config.clone(), pool.clone(), assets(), setup) |
| 135 | .await |
| 136 | .build(); |
| 137 | |
| 138 | |
| 139 | |
| 140 | let listener = TcpListener::bind("127.0.0.1:0").await.expect("a port"); |
| 141 | let addr: SocketAddr = listener.local_addr().expect("the address it got"); |
| 142 | |
| 143 | let (stop, stopped) = oneshot::channel(); |
| 144 | let serving = tokio::spawn(async move { |
| 145 | let _ = topcoat::serve_until(listener, router, async { |
| 146 | let _ = stopped.await; |
| 147 | }) |
| 148 | .await; |
| 149 | }); |
| 150 | |
| 151 | Instance { |
| 152 | base: format!("http://{addr}"), |
| 153 | setup_token, |
| 154 | config, |
| 155 | pool, |
| 156 | _dir: dir, |
| 157 | stop: Some(stop), |
| 158 | serving: Some(serving), |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | fn assets() -> AssetBundle { |
| 171 | |
| 172 | |
| 173 | let dir = Box::leak(Box::new(tempfile::tempdir().expect("a temp dir"))); |
| 174 | std::fs::write( |
| 175 | dir.path().join("manifest.toml"), |
| 176 | "version = 1\nassets = []\n", |
| 177 | ) |
| 178 | .expect("the manifest is written"); |
| 179 | |
| 180 | AssetBundle::load_dir(dir.path()).expect("an empty bundle loads") |
| 181 | } |
| 182 | |
| 183 | |
| 184 | struct Answer { |
| 185 | status: u16, |
| 186 | headers: Vec<(String, String)>, |
| 187 | body: String, |
| 188 | } |
| 189 | |
| 190 | impl Answer { |
| 191 | |
| 192 | fn header(&self, name: &str) -> Option<&str> { |
| 193 | self.headers |
| 194 | .iter() |
| 195 | .find(|(key, _)| key.eq_ignore_ascii_case(name)) |
| 196 | .map(|(_, value)| value.as_str()) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | async fn request(url: String, body: Option<(&str, String)>) -> Answer { |
| 209 | let body = body.map(|(content_type, body)| (content_type.to_owned(), body)); |
| 210 | |
| 211 | tokio::task::spawn_blocking(move || { |
| 212 | let agent = ureq::Agent::config_builder() |
| 213 | |
| 214 | |
| 215 | |
| 216 | .http_status_as_error(false) |
| 217 | .max_redirects(0) |
| 218 | .build() |
| 219 | .new_agent(); |
| 220 | |
| 221 | let mut response = match body { |
| 222 | Some((content_type, body)) => agent |
| 223 | .post(&url) |
| 224 | .header("content-type", &content_type) |
| 225 | .send(&body) |
| 226 | .expect("the request completes"), |
| 227 | None => agent.get(&url).call().expect("the request completes"), |
| 228 | }; |
| 229 | |
| 230 | let status = response.status().as_u16(); |
| 231 | let headers = response |
| 232 | .headers() |
| 233 | .iter() |
| 234 | .map(|(name, value)| { |
| 235 | ( |
| 236 | name.as_str().to_owned(), |
| 237 | String::from_utf8_lossy(value.as_bytes()).into_owned(), |
| 238 | ) |
| 239 | }) |
| 240 | .collect(); |
| 241 | let body = response.body_mut().read_to_string().unwrap_or_default(); |
| 242 | |
| 243 | Answer { |
| 244 | status, |
| 245 | headers, |
| 246 | body, |
| 247 | } |
| 248 | }) |
| 249 | .await |
| 250 | .expect("the blocking thread finishes") |
| 251 | } |
| 252 | |
| 253 | async fn get(instance: &Instance, path: &str) -> Answer { |
| 254 | request(instance.url(path), None).await |
| 255 | } |
| 256 | |
| 257 | async fn post_form(instance: &Instance, path: &str, body: &str) -> Answer { |
| 258 | request( |
| 259 | instance.url(path), |
| 260 | Some(("application/x-www-form-urlencoded", body.to_owned())), |
| 261 | ) |
| 262 | .await |
| 263 | } |
| 264 | |
| 265 | async fn post_json(instance: &Instance, path: &str, body: String) -> Answer { |
| 266 | request(instance.url(path), Some(("application/json", body))).await |
| 267 | } |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | async fn claim(instance: &Instance) { |
| 275 | let body = format!( |
| 276 | r#"{{"setup_token":"{}","email":"ada@example.com","handle":"ada","password":"a-long-enough-password"}}"#, |
| 277 | instance.setup_token |
| 278 | ); |
| 279 | |
| 280 | let answer = post_json(instance, "/api/setup", body).await; |
| 281 | |
| 282 | assert_eq!(answer.status, 201, "the claim was refused: {}", answer.body); |
| 283 | assert!( |
| 284 | answer.body.contains("\"handle\":\"ada\""), |
| 285 | "{}", |
| 286 | answer.body |
| 287 | ); |
| 288 | } |
| 289 | |
| 290 | #[tokio::test] |
| 291 | async fn an_instance_boots_and_can_be_claimed_without_a_browser() { |
| 292 | let instance = boot().await; |
| 293 | |
| 294 | let before = get(&instance, "/api/instance").await; |
| 295 | assert_eq!(before.status, 200); |
| 296 | assert_eq!(before.body.trim(), r#"{"claimed":false}"#); |
| 297 | |
| 298 | claim(&instance).await; |
| 299 | |
| 300 | let after = get(&instance, "/api/instance").await; |
| 301 | assert_eq!(after.status, 200); |
| 302 | assert_eq!(after.body.trim(), r#"{"claimed":true}"#); |
| 303 | } |
| 304 | |
| 305 | #[tokio::test] |
| 306 | async fn an_instance_given_an_owner_in_its_configuration_boots_claimed() { |
| 307 | |
| 308 | |
| 309 | let instance = boot_with_owner("ada", "ada@example.com").await; |
| 310 | |
| 311 | let answer = get(&instance, "/api/instance").await; |
| 312 | |
| 313 | assert_eq!(answer.status, 200); |
| 314 | assert_eq!(answer.body.trim(), r#"{"claimed":true}"#); |
| 315 | } |
| 316 | |
| 317 | #[tokio::test] |
| 318 | async fn a_boot_seeded_instance_cannot_be_claimed_by_anyone() { |
| 319 | |
| 320 | |
| 321 | let instance = boot_with_owner("ada", "ada@example.com").await; |
| 322 | |
| 323 | let over_json = post_json( |
| 324 | &instance, |
| 325 | "/api/setup", |
| 326 | format!( |
| 327 | r#"{{"setup_token":"{}","email":"eve@example.com","handle":"eve","password":"a-long-enough-password"}}"#, |
| 328 | instance.setup_token |
| 329 | ), |
| 330 | ) |
| 331 | .await; |
| 332 | assert_ne!( |
| 333 | over_json.status, 201, |
| 334 | "the claim went through: {}", |
| 335 | over_json.body |
| 336 | ); |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | let over_form = post_form( |
| 342 | &instance, |
| 343 | "/auth/setup", |
| 344 | &format!( |
| 345 | "token={}&handle=eve&email=eve@example.com&password=a-long-enough-password", |
| 346 | instance.setup_token |
| 347 | ), |
| 348 | ) |
| 349 | .await; |
| 350 | assert_eq!(over_form.status, 303); |
| 351 | assert_eq!(over_form.header("location"), Some("/")); |
| 352 | |
| 353 | assert_eq!( |
| 354 | get(&instance, "/api/instance").await.body.trim(), |
| 355 | r#"{"claimed":true}"#, |
| 356 | "and nobody became the owner" |
| 357 | ); |
| 358 | } |
| 359 | |
| 360 | #[tokio::test] |
| 361 | async fn the_seeded_owner_cannot_sign_in_with_any_password() { |
| 362 | |
| 363 | |
| 364 | let instance = boot_with_owner("ada", "ada@example.com").await; |
| 365 | |
| 366 | for guess in ["", "password", "a-long-enough-password"] { |
| 367 | let answer = post_form( |
| 368 | &instance, |
| 369 | "/auth/login", |
| 370 | &format!("email=ada@example.com&password={guess}"), |
| 371 | ) |
| 372 | .await; |
| 373 | |
| 374 | assert_eq!(answer.status, 303, "{guess:?} was not refused"); |
| 375 | assert_eq!(answer.header("location"), Some("/auth/login")); |
| 376 | assert!( |
| 377 | answer |
| 378 | .header("set-cookie") |
| 379 | .is_none_or(|cookie| !cookie.to_ascii_lowercase().contains("session")), |
| 380 | "{guess:?} produced a session cookie: {:?}", |
| 381 | answer.header("set-cookie") |
| 382 | ); |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | #[tokio::test] |
| 387 | async fn the_seeded_owner_gets_in_through_a_reset_link() { |
| 388 | |
| 389 | |
| 390 | let instance = boot_with_owner("ada", "ada@example.com").await; |
| 391 | |
| 392 | let issued = mint_reset_for_handle( |
| 393 | "ada", |
| 394 | std::time::SystemTime::now(), |
| 395 | &SqliteUserRepo::new(instance.pool.clone()), |
| 396 | &SqliteOrgRepo::new(instance.pool.clone()), |
| 397 | &SqlitePasswordResetRepo::new(instance.pool.clone()), |
| 398 | ) |
| 399 | .await |
| 400 | .expect("the query runs") |
| 401 | .expect("the seeded owner holds the handle"); |
| 402 | |
| 403 | |
| 404 | |
| 405 | assert!(instance.config.public_url.is_none()); |
| 406 | let link = issued.link(&instance.base); |
| 407 | let path = link |
| 408 | .strip_prefix(&instance.base) |
| 409 | .expect("the link is on this instance") |
| 410 | .to_owned(); |
| 411 | assert!(path.starts_with("/auth/reset/"), "{link}"); |
| 412 | |
| 413 | let spent = post_form( |
| 414 | &instance, |
| 415 | &path, |
| 416 | "password=a-long-enough-password&confirmation=a-long-enough-password", |
| 417 | ) |
| 418 | .await; |
| 419 | assert_eq!(spent.status, 303, "the reset was refused"); |
| 420 | assert_eq!(spent.header("location"), Some("/auth/login?reset")); |
| 421 | |
| 422 | let signed_in = post_form( |
| 423 | &instance, |
| 424 | "/auth/login", |
| 425 | "email=ada@example.com&password=a-long-enough-password", |
| 426 | ) |
| 427 | .await; |
| 428 | assert_eq!(signed_in.status, 303); |
| 429 | assert_eq!( |
| 430 | signed_in.header("location"), |
| 431 | Some("/"), |
| 432 | "the owner could not sign in with the password they just set" |
| 433 | ); |
| 434 | } |
| 435 | |
| 436 | #[tokio::test] |
| 437 | async fn every_response_carries_the_security_headers_including_a_404() { |
| 438 | let instance = boot().await; |
| 439 | |
| 440 | |
| 441 | |
| 442 | |
| 443 | for path in ["/api/instance", "/nothing-is-here"] { |
| 444 | let answer = get(&instance, path).await; |
| 445 | |
| 446 | assert!( |
| 447 | answer.status == 200 || answer.status == 404, |
| 448 | "{path} answered {}", |
| 449 | answer.status |
| 450 | ); |
| 451 | |
| 452 | let policy = answer |
| 453 | .header("content-security-policy") |
| 454 | .unwrap_or_else(|| panic!("{path} carries no CSP")); |
| 455 | assert!( |
| 456 | policy.contains("default-src 'none'"), |
| 457 | "{path}'s CSP is {policy}" |
| 458 | ); |
| 459 | assert!( |
| 460 | policy.contains("frame-ancestors 'none'"), |
| 461 | "{path}'s CSP is {policy}" |
| 462 | ); |
| 463 | |
| 464 | assert_eq!( |
| 465 | answer.header("x-content-type-options"), |
| 466 | Some("nosniff"), |
| 467 | "{path}" |
| 468 | ); |
| 469 | assert_eq!(answer.header("x-frame-options"), Some("DENY"), "{path}"); |
| 470 | |
| 471 | |
| 472 | assert_eq!( |
| 473 | answer.header("referrer-policy"), |
| 474 | Some("no-referrer"), |
| 475 | "{path}" |
| 476 | ); |
| 477 | assert_eq!( |
| 478 | answer.header("cache-control"), |
| 479 | Some("private, no-cache"), |
| 480 | "{path}" |
| 481 | ); |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | #[tokio::test] |
| 486 | async fn a_post_without_a_csrf_token_is_refused_with_a_403() { |
| 487 | let instance = boot().await; |
| 488 | |
| 489 | |
| 490 | |
| 491 | |
| 492 | |
| 493 | let empty = post_form(&instance, "/auth/logout", "").await; |
| 494 | assert_eq!(empty.status, 403, "{}", empty.body); |
| 495 | assert!( |
| 496 | empty.body.contains("submitted from somewhere else"), |
| 497 | "{}", |
| 498 | empty.body |
| 499 | ); |
| 500 | |
| 501 | let wrong = post_form(&instance, "/auth/logout", "csrf_token=not-a-token").await; |
| 502 | assert_eq!(wrong.status, 403, "{}", wrong.body); |
| 503 | |
| 504 | |
| 505 | |
| 506 | assert_eq!(empty.header("x-frame-options"), Some("DENY")); |
| 507 | } |
| 508 | |
| 509 | #[tokio::test] |
| 510 | async fn metrics_without_the_bearer_does_not_exist() { |
| 511 | let instance = boot().await; |
| 512 | |
| 513 | |
| 514 | |
| 515 | |
| 516 | let metrics = get(&instance, "/metrics").await; |
| 517 | let unrouted = get(&instance, "/definitely-not-a-route").await; |
| 518 | |
| 519 | assert_eq!(metrics.status, 404); |
| 520 | assert_eq!(metrics.status, unrouted.status); |
| 521 | assert_eq!(metrics.body, unrouted.body); |
| 522 | |
| 523 | assert!( |
| 524 | !metrics.body.contains("steid_http_requests_total"), |
| 525 | "the counters leaked into the refusal: {}", |
| 526 | metrics.body |
| 527 | ); |
| 528 | } |