steid

@jamesgill /

steid/tests/http.rs
Rust18.9 KBCode·Blame·History·Raw
1//! The first tests that speak HTTP.
2//!
3//! Everything below is a fact about a *response* — a header, a status, a body — and none
4//! of it was assertable until [`app::build`](steid::infrastructure::app::build) came out
5//! of `main.rs`. Both organisation reviews asked for this; §6 of the second one checked
6//! that `topcoat::serve_until` takes any `Listener` and that `tokio::net::TcpListener`
7//! is one, which is the whole of the mechanism here.
8//!
9//! **`tests/` rather than a `#[cfg(test)]` module inside `web/`**, for two reasons. It
10//! reaches the application exactly the way `main` does — through the public API, with no
11//! access to a private helper that could quietly make a test pass — and it keeps a
12//! server boot, a migration and a pool out of the unit-test binary, which runs 1,300
13//! tests in seven seconds and should keep doing so.
14//!
15//! **It does not replace `web/csrf_scan.rs`,** and could not: this exercises one refused
16//! POST, and the scan's guarantee is about the thirty-odd handlers it has never called.
17//! What it does do is close the scan's own stated gap — that it "has never executed the
18//! 403 page it protects" — so the two are complements. See the note in the CSRF test.
19
20use std::net::SocketAddr;
21
22use steid::{
23 application::{AppConfig, mint_reset_for_handle},
24 domain::SetupToken,
25 infrastructure::{
26 app, database,
27 repository::{SqliteOrgRepo, SqlitePasswordResetRepo, SqliteUserRepo},
28 },
29};
30use tempfile::TempDir;
31use tokio::{net::TcpListener, sync::oneshot, task::JoinHandle};
32use topcoat::asset::AssetBundle;
33
34/// A Steid serving on a port the operating system picked, against a database and a data
35/// directory that vanish with it.
36struct Instance {
37 base: String,
38 /// The claim token, live until the instance is claimed.
39 setup_token: String,
40 /// The configuration it was built from, for the tests that drive a subcommand.
41 config: AppConfig,
42 /// Its database, for the same reason: `steid reset-password` has no HTTP surface.
43 pool: sqlx::SqlitePool,
44 /// Held so the temporary directory outlives the server.
45 _dir: TempDir,
46 stop: Option<oneshot::Sender<()>>,
47 serving: Option<JoinHandle<()>>,
48}
49
50impl Instance {
51 /// A URL on this instance.
52 fn url(&self, path: &str) -> String {
53 format!("{}{path}", self.base)
54 }
55}
56
57impl Drop for Instance {
58 fn drop(&mut self) {
59 // The server holds the pool, which holds an open file in the temp directory the
60 // next line removes. Signalling here rather than in each test keeps every test
61 // to its assertions.
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/// Boots one, unclaimed, and returns once it is accepting connections.
72async fn boot() -> Instance {
73 boot_with(None).await
74}
75
76/// Boots one that was handed an owner in its configuration, exactly as a scripted
77/// install does — so it is claimed before it answers its first request.
78///
79/// Seeds through [`app::seed_owner_on_boot`] rather than calling the use case directly:
80/// that function *is* what `main` calls, so this reaches the application the way the
81/// binary does and a change to the boot policy — the silence on a claimed instance, the
82/// order against the setup token — cannot pass here and fail there.
83async fn boot_with_owner(handle: &str, email: &str) -> Instance {
84 boot_with(Some((handle.to_owned(), email.to_owned()))).await
85}
86
87async 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 // The default, and the one under test: the session cookie is `__Host-` prefixed
96 // and `Secure`. A test that flipped this would be testing the development
97 // fallback rather than what is deployed.
98 insecure_cookies: false,
99 allow_private_webhooks: false,
100 trusted_proxy: false,
101 // Absent, so the operator surface does not exist. `/metrics` answering 404 is the
102 // fact this makes assertable.
103 operator_token: None,
104 setup_token: None,
105 backup_marker: None,
106 smtp_url: None,
107 mail_from: None,
108 // Set together or not at all — the configuration refuses half of an owner, and
109 // that refusal is `AppConfig::owner_seed`'s unit test rather than a boot here.
110 owner_email: owner.as_ref().map(|(_, email)| email.clone()),
111 owner_handle: owner.as_ref().map(|(handle, _)| handle.clone()),
112 owner_org: None,
113 owner_org_name: None,
114 public_url: None,
115 };
116
117 let pool = database::connect(&config.database_url)
118 .await
119 .expect("the database opens");
120
121 // What `main` does, in `main`'s order: the owner is seeded first, because seeding is
122 // what makes the instance claimed, and a claimed instance is handed no setup token.
123 let seeded = app::seed_owner_on_boot(&config, &pool)
124 .await
125 .expect("the configured owner is created");
126 assert_eq!(
127 seeded.is_some(),
128 owner.is_some(),
129 "a configured owner must actually be created"
130 );
131
132 let token = SetupToken::generate();
133 let setup_token = token.reveal().to_owned();
134 let setup = if seeded.is_some() { None } else { Some(token) };
135
136 let router = app::build(config.clone(), pool.clone(), assets(), setup)
137 .await
138 .build();
139
140 // Port zero: the kernel picks, so tests never collide with each other or with a dev
141 // server on 3000.
142 let listener = TcpListener::bind("127.0.0.1:0").await.expect("a port");
143 let addr: SocketAddr = listener.local_addr().expect("the address it got");
144
145 let (stop, stopped) = oneshot::channel();
146 let serving = tokio::spawn(async move {
147 let _ = topcoat::serve_until(listener, router, async {
148 let _ = stopped.await;
149 })
150 .await;
151 });
152
153 Instance {
154 base: format!("http://{addr}"),
155 setup_token,
156 config,
157 pool,
158 _dir: dir,
159 stop: Some(stop),
160 serving: Some(serving),
161 }
162}
163
164/// The asset bundle these tests serve.
165///
166/// Empty, deliberately: nothing asserted here renders a `view!`, so no page reaches
167/// `Asset`'s renderer and the catalog is never consulted. Loading the real bundle would
168/// tie `cargo test` to `topcoat asset bundle` having been run — a build step that is not
169/// part of the test gate — and the failure would be a `NotFound` at boot rather than
170/// anything about the assertion. The day a test here does render a page, this is where
171/// the real bundle goes.
172fn assets() -> AssetBundle {
173 // Leaked rather than held: `load_dir` reads the manifest and keeps only the path,
174 // and the directory has to outlive every instance in the process.
175 let dir = Box::leak(Box::new(tempfile::tempdir().expect("a temp dir")));
176 std::fs::write(
177 dir.path().join("manifest.toml"),
178 "version = 1\nassets = []\n",
179 )
180 .expect("the manifest is written");
181
182 AssetBundle::load_dir(dir.path()).expect("an empty bundle loads")
183}
184
185/// One response, reduced to what these tests ask about.
186struct Answer {
187 status: u16,
188 headers: Vec<(String, String)>,
189 body: String,
190}
191
192impl Answer {
193 /// The first value of a header, case-insensitively.
194 fn header(&self, name: &str) -> Option<&str> {
195 self.headers
196 .iter()
197 .find(|(key, _)| key.eq_ignore_ascii_case(name))
198 .map(|(_, value)| value.as_str())
199 }
200}
201
202/// Makes a request from a blocking thread.
203///
204/// A `body` makes it a POST and a `None` a GET, which is the whole of the verb handling
205/// these tests need.
206///
207/// `ureq` is the client already in the tree, and it is blocking — so it runs on a
208/// blocking thread rather than stalling the runtime worker the server is being polled
209/// on. Without `spawn_blocking` a single-threaded runtime deadlocks here.
210async fn request(url: String, body: Option<(&str, String)>) -> Answer {
211 let body = body.map(|(content_type, body)| (content_type.to_owned(), body));
212
213 tokio::task::spawn_blocking(move || {
214 let agent = ureq::Agent::config_builder()
215 // Every status these tests are about is a 4xx. The default collapses them
216 // into an error variant that carries no headers, which is exactly what is
217 // being asserted.
218 .http_status_as_error(false)
219 .max_redirects(0)
220 .build()
221 .new_agent();
222
223 let mut response = match body {
224 Some((content_type, body)) => agent
225 .post(&url)
226 .header("content-type", &content_type)
227 .send(&body)
228 .expect("the request completes"),
229 None => agent.get(&url).call().expect("the request completes"),
230 };
231
232 let status = response.status().as_u16();
233 let headers = response
234 .headers()
235 .iter()
236 .map(|(name, value)| {
237 (
238 name.as_str().to_owned(),
239 String::from_utf8_lossy(value.as_bytes()).into_owned(),
240 )
241 })
242 .collect();
243 let body = response.body_mut().read_to_string().unwrap_or_default();
244
245 Answer {
246 status,
247 headers,
248 body,
249 }
250 })
251 .await
252 .expect("the blocking thread finishes")
253}
254
255async fn get(instance: &Instance, path: &str) -> Answer {
256 request(instance.url(path), None).await
257}
258
259async fn post_form(instance: &Instance, path: &str, body: &str) -> Answer {
260 request(
261 instance.url(path),
262 Some(("application/x-www-form-urlencoded", body.to_owned())),
263 )
264 .await
265}
266
267async fn post_json(instance: &Instance, path: &str, body: String) -> Answer {
268 request(instance.url(path), Some(("application/json", body))).await
269}
270
271/// Claims the instance headlessly, as `install.sh` does.
272///
273/// Asserted rather than ignored: if this ever stops answering 201 the tests below are
274/// running against an unclaimed instance and would still pass, which is the worst kind
275/// of green.
276async fn claim(instance: &Instance) {
277 let body = format!(
278 r#"{{"setup_token":"{}","email":"ada@example.com","handle":"ada","password":"a-long-enough-password"}}"#,
279 instance.setup_token
280 );
281
282 let answer = post_json(instance, "/api/setup", body).await;
283
284 assert_eq!(answer.status, 201, "the claim was refused: {}", answer.body);
285 assert!(
286 answer.body.contains("\"handle\":\"ada\""),
287 "{}",
288 answer.body
289 );
290}
291
292#[tokio::test]
293async fn an_instance_boots_and_can_be_claimed_without_a_browser() {
294 let instance = boot().await;
295
296 let before = get(&instance, "/api/instance").await;
297 assert_eq!(before.status, 200);
298 assert_eq!(before.body.trim(), r#"{"claimed":false}"#);
299
300 claim(&instance).await;
301
302 let after = get(&instance, "/api/instance").await;
303 assert_eq!(after.status, 200);
304 assert_eq!(after.body.trim(), r#"{"claimed":true}"#);
305}
306
307#[tokio::test]
308async fn an_instance_given_an_owner_in_its_configuration_boots_claimed() {
309 // The whole point of the boot-time owner: there is no window, however short, in
310 // which this instance is unclaimed and reachable.
311 let instance = boot_with_owner("ada", "ada@example.com").await;
312
313 let answer = get(&instance, "/api/instance").await;
314
315 assert_eq!(answer.status, 200);
316 assert_eq!(answer.body.trim(), r#"{"claimed":true}"#);
317}
318
319#[tokio::test]
320async fn a_boot_seeded_instance_cannot_be_claimed_by_anyone() {
321 // A seeded instance holds no setup token at all — `boot_with` withholds it exactly
322 // as `main` does — so both claim surfaces are shut before any credential is read.
323 let instance = boot_with_owner("ada", "ada@example.com").await;
324
325 let over_json = post_json(
326 &instance,
327 "/api/setup",
328 format!(
329 r#"{{"setup_token":"{}","email":"eve@example.com","handle":"eve","password":"a-long-enough-password"}}"#,
330 instance.setup_token
331 ),
332 )
333 .await;
334 assert_ne!(
335 over_json.status, 201,
336 "the claim went through: {}",
337 over_json.body
338 );
339
340 // The form is the other way in. A claimed instance answers it with a 303 to the
341 // root — asserted as it stands today, so a deliberate change has to come through
342 // here rather than silently.
343 let over_form = post_form(
344 &instance,
345 "/auth/setup",
346 &format!(
347 "token={}&handle=eve&email=eve@example.com&password=a-long-enough-password",
348 instance.setup_token
349 ),
350 )
351 .await;
352 assert_eq!(over_form.status, 303);
353 assert_eq!(over_form.header("location"), Some("/"));
354
355 assert_eq!(
356 get(&instance, "/api/instance").await.body.trim(),
357 r#"{"claimed":true}"#,
358 "and nobody became the owner"
359 );
360}
361
362#[tokio::test]
363async fn the_seeded_owner_cannot_sign_in_with_any_password() {
364 // There is no password to guess: the one that was hashed was 32 random bytes, made
365 // at boot and dropped. A wrong password is a 303 back to the form with no session.
366 let instance = boot_with_owner("ada", "ada@example.com").await;
367
368 for guess in ["", "password", "a-long-enough-password"] {
369 let answer = post_form(
370 &instance,
371 "/auth/login",
372 &format!("email=ada@example.com&password={guess}"),
373 )
374 .await;
375
376 assert_eq!(answer.status, 303, "{guess:?} was not refused");
377 assert_eq!(answer.header("location"), Some("/auth/login"));
378 assert!(
379 answer
380 .header("set-cookie")
381 .is_none_or(|cookie| !cookie.to_ascii_lowercase().contains("session")),
382 "{guess:?} produced a session cookie: {:?}",
383 answer.header("set-cookie")
384 );
385 }
386}
387
388#[tokio::test]
389async fn the_seeded_owner_gets_in_through_a_reset_link() {
390 // The only way in, and therefore the one that has to work end to end: what
391 // `steid reset-password ada` mints is spent here, and the new password signs in.
392 let instance = boot_with_owner("ada", "ada@example.com").await;
393
394 let issued = mint_reset_for_handle(
395 "ada",
396 std::time::SystemTime::now(),
397 &SqliteUserRepo::new(instance.pool.clone()),
398 &SqliteOrgRepo::new(instance.pool.clone()),
399 &SqlitePasswordResetRepo::new(instance.pool.clone()),
400 )
401 .await
402 .expect("the query runs")
403 .expect("the seeded owner holds the handle");
404
405 // `steid reset-password` prints exactly this, with STEID_PUBLIC_URL in front; the
406 // instance's own base is that address here.
407 assert!(instance.config.public_url.is_none());
408 let link = issued.link(&instance.base);
409 let path = link
410 .strip_prefix(&instance.base)
411 .expect("the link is on this instance")
412 .to_owned();
413 assert!(path.starts_with("/auth/reset/"), "{link}");
414
415 let spent = post_form(
416 &instance,
417 &path,
418 "password=a-long-enough-password&confirmation=a-long-enough-password",
419 )
420 .await;
421 assert_eq!(spent.status, 303, "the reset was refused");
422 assert_eq!(spent.header("location"), Some("/auth/login?reset"));
423
424 let signed_in = post_form(
425 &instance,
426 "/auth/login",
427 "email=ada@example.com&password=a-long-enough-password",
428 )
429 .await;
430 assert_eq!(signed_in.status, 303);
431 assert_eq!(
432 signed_in.header("location"),
433 Some("/"),
434 "the owner could not sign in with the password they just set"
435 );
436}
437
438#[tokio::test]
439async fn every_response_carries_the_security_headers_including_a_404() {
440 let instance = boot().await;
441
442 // A 404 specifically, because until the layer learned to build the response itself an
443 // error never passed through it: a 404 went out with no CSP, no `X-Frame-Options` and
444 // no `Referrer-Policy` at all. That regression is invisible to every other test.
445 for path in ["/api/instance", "/nothing-is-here"] {
446 let answer = get(&instance, path).await;
447
448 assert!(
449 answer.status == 200 || answer.status == 404,
450 "{path} answered {}",
451 answer.status
452 );
453
454 let policy = answer
455 .header("content-security-policy")
456 .unwrap_or_else(|| panic!("{path} carries no CSP"));
457 assert!(
458 policy.contains("default-src 'none'"),
459 "{path}'s CSP is {policy}"
460 );
461 assert!(
462 policy.contains("frame-ancestors 'none'"),
463 "{path}'s CSP is {policy}"
464 );
465
466 assert_eq!(
467 answer.header("x-content-type-options"),
468 Some("nosniff"),
469 "{path}"
470 );
471 assert_eq!(answer.header("x-frame-options"), Some("DENY"), "{path}");
472 // `no-referrer`, not the usual `strict-origin-when-cross-origin`: a private
473 // repository's URL contains its name, and a README may link anywhere.
474 assert_eq!(
475 answer.header("referrer-policy"),
476 Some("no-referrer"),
477 "{path}"
478 );
479 assert_eq!(
480 answer.header("cache-control"),
481 Some("private, no-cache"),
482 "{path}"
483 );
484 }
485}
486
487#[tokio::test]
488async fn a_post_without_a_csrf_token_is_refused_with_a_403() {
489 let instance = boot().await;
490
491 // `/auth/logout` because it is a guarded POST that needs no session to reach: the
492 // check runs before anything else it does. This is the first time the refusal has
493 // been *executed* — `csrf_scan` asserts that the line is written, which is a
494 // different guarantee and still the one that covers the other thirty handlers.
495 let empty = post_form(&instance, "/auth/logout", "").await;
496 assert_eq!(empty.status, 403, "{}", empty.body);
497 assert!(
498 empty.body.contains("submitted from somewhere else"),
499 "{}",
500 empty.body
501 );
502
503 let wrong = post_form(&instance, "/auth/logout", "csrf_token=not-a-token").await;
504 assert_eq!(wrong.status, 403, "{}", wrong.body);
505
506 // And the refusal is not an exception to the headers: it is built by hand rather than
507 // by the router, so it is exactly the shape of response that could miss them.
508 assert_eq!(empty.header("x-frame-options"), Some("DENY"));
509}
510
511#[tokio::test]
512async fn metrics_without_the_bearer_does_not_exist() {
513 let instance = boot().await;
514
515 // No `operator_token` is configured, so the surface is off. 404 rather than 401, and
516 // byte for byte what an unrouted path answers — a 401 would confirm there is a token
517 // to guess.
518 let metrics = get(&instance, "/metrics").await;
519 let unrouted = get(&instance, "/definitely-not-a-route").await;
520
521 assert_eq!(metrics.status, 404);
522 assert_eq!(metrics.status, unrouted.status);
523 assert_eq!(metrics.body, unrouted.body);
524
525 assert!(
526 !metrics.body.contains("steid_http_requests_total"),
527 "the counters leaked into the refusal: {}",
528 metrics.body
529 );
530}