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 public_url: None,
113 };
114
115 let pool = database::connect(&config.database_url)
116 .await
117 .expect("the database opens");
118
119 // What `main` does, in `main`'s order: the owner is seeded first, because seeding is
120 // what makes the instance claimed, and a claimed instance is handed no setup token.
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 // Port zero: the kernel picks, so tests never collide with each other or with a dev
139 // server on 3000.
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/// The asset bundle these tests serve.
163///
164/// Empty, deliberately: nothing asserted here renders a `view!`, so no page reaches
165/// `Asset`'s renderer and the catalog is never consulted. Loading the real bundle would
166/// tie `cargo test` to `topcoat asset bundle` having been run — a build step that is not
167/// part of the test gate — and the failure would be a `NotFound` at boot rather than
168/// anything about the assertion. The day a test here does render a page, this is where
169/// the real bundle goes.
170fn assets() -> AssetBundle {
171 // Leaked rather than held: `load_dir` reads the manifest and keeps only the path,
172 // and the directory has to outlive every instance in the process.
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/// One response, reduced to what these tests ask about.
184struct Answer {
185 status: u16,
186 headers: Vec<(String, String)>,
187 body: String,
188}
189
190impl Answer {
191 /// The first value of a header, case-insensitively.
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/// Makes a request from a blocking thread.
201///
202/// A `body` makes it a POST and a `None` a GET, which is the whole of the verb handling
203/// these tests need.
204///
205/// `ureq` is the client already in the tree, and it is blocking — so it runs on a
206/// blocking thread rather than stalling the runtime worker the server is being polled
207/// on. Without `spawn_blocking` a single-threaded runtime deadlocks here.
208async 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 // Every status these tests are about is a 4xx. The default collapses them
214 // into an error variant that carries no headers, which is exactly what is
215 // being asserted.
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
253async fn get(instance: &Instance, path: &str) -> Answer {
254 request(instance.url(path), None).await
255}
256
257async 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
265async fn post_json(instance: &Instance, path: &str, body: String) -> Answer {
266 request(instance.url(path), Some(("application/json", body))).await
267}
268
269/// Claims the instance headlessly, as `install.sh` does.
270///
271/// Asserted rather than ignored: if this ever stops answering 201 the tests below are
272/// running against an unclaimed instance and would still pass, which is the worst kind
273/// of green.
274async 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]
291async 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]
306async fn an_instance_given_an_owner_in_its_configuration_boots_claimed() {
307 // The whole point of the boot-time owner: there is no window, however short, in
308 // which this instance is unclaimed and reachable.
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]
318async fn a_boot_seeded_instance_cannot_be_claimed_by_anyone() {
319 // A seeded instance holds no setup token at all — `boot_with` withholds it exactly
320 // as `main` does — so both claim surfaces are shut before any credential is read.
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 // The form is the other way in. A claimed instance answers it with a 303 to the
339 // root — asserted as it stands today, so a deliberate change has to come through
340 // here rather than silently.
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]
361async fn the_seeded_owner_cannot_sign_in_with_any_password() {
362 // There is no password to guess: the one that was hashed was 32 random bytes, made
363 // at boot and dropped. A wrong password is a 303 back to the form with no session.
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]
387async fn the_seeded_owner_gets_in_through_a_reset_link() {
388 // The only way in, and therefore the one that has to work end to end: what
389 // `steid reset-password ada` mints is spent here, and the new password signs in.
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 // `steid reset-password` prints exactly this, with STEID_PUBLIC_URL in front; the
404 // instance's own base is that address here.
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]
437async fn every_response_carries_the_security_headers_including_a_404() {
438 let instance = boot().await;
439
440 // A 404 specifically, because until the layer learned to build the response itself an
441 // error never passed through it: a 404 went out with no CSP, no `X-Frame-Options` and
442 // no `Referrer-Policy` at all. That regression is invisible to every other test.
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 // `no-referrer`, not the usual `strict-origin-when-cross-origin`: a private
471 // repository's URL contains its name, and a README may link anywhere.
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]
486async fn a_post_without_a_csrf_token_is_refused_with_a_403() {
487 let instance = boot().await;
488
489 // `/auth/logout` because it is a guarded POST that needs no session to reach: the
490 // check runs before anything else it does. This is the first time the refusal has
491 // been *executed* — `csrf_scan` asserts that the line is written, which is a
492 // different guarantee and still the one that covers the other thirty handlers.
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 // And the refusal is not an exception to the headers: it is built by hand rather than
505 // by the router, so it is exactly the shape of response that could miss them.
506 assert_eq!(empty.header("x-frame-options"), Some("DENY"));
507}
508
509#[tokio::test]
510async fn metrics_without_the_bearer_does_not_exist() {
511 let instance = boot().await;
512
513 // No `operator_token` is configured, so the surface is off. 404 rather than 401, and
514 // byte for byte what an unrouted path answers — a 401 would confirm there is a token
515 // to guess.
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}