//! The app driven the way a browser drives it: real router, real handlers, real //! session cookie. //! //! The point of this binary is the guards. A button the UI does not draw proves //! nothing — a Viewer who posts to the mutation endpoint anyway must be refused //! by the handler, and that is what these tests call. //! //! New HTTP tests belong in this file rather than a new `tests/*.rs`: one test //! binary links and runs once. //! //! Ported from the Leptos-era `iz-web`'s `tests/http.rs`. That app answered //! a hydrated caller with `200` and a JSON body; this one is server-rendered //! and every mutating `/api/*` route always answers `303 See Other` (topcoat's //! `see_other`, not the old stack's `302 Found`), carrying the same JSON body //! (`Option` or a domain value) that this file's assertions already //! read off `Answer::body`. `path::()` is gone with the server //! functions themselves — routes are now literal `/api/...` strings, kept as //! `const` items below so a rename shows up once. #![cfg(test)] use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; use parking_lot::Mutex; use http::{HeaderValue, Request, StatusCode, header}; use iz_core::Role; use iz_core::board::Moved; use iz_core::store::{Audience, MailOutcome, SendKind, SendState, Store, Trigger, TursoStore}; use iz_web::directory::{StreamFrame, StreamMember, apply_frame}; use iz_web::server::Mail; use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{Body, BodyLimit, Router, RouterBuilderDiscoverExt, to_bytes}; use topcoat::runtime::RouterBuilderRuntimeExt; use ulid::Ulid; /// The session cookie iz-client seals: the tests mint it directly instead of /// driving a browser through the OIDC round-trip. const SESSION_COOKIE: &str = "iz_session"; /// The bundle `cargo build -p iz-web` + `topcoat asset bundle --bin /// iz-web` write next to the crate's own `target/debug`, not next to the /// test binary (which lives in `target/debug/deps`) — `AssetBundle::load` /// looks beside `current_exe` and would miss it, so the path is given /// explicitly instead. fn asset_dir() -> PathBuf { PathBuf::from(concat!( env!("CARGO_MANIFEST_DIR"), "/../../target/debug/assets" )) } /// A live connection in the suite outlives any test that reads it. The bound /// on a live test is [`live_until`]'s own timeout — waiting for the frame it /// expects — not this window: a window short enough to end the stream promptly /// is also short enough to lose the race on a loaded machine, which is a /// flaky test rather than a fast one. const TEST_LIVE_WINDOW: iz_web::live::LiveWindow = iz_web::live::LiveWindow(std::time::Duration::from_secs(10)); /// Photos the fake im can serve, keyed by person id. type Photos = Arc, String)>>>; /// A fake im: answers `POST /introspect` from its token map, `{"active": /// false}` for anything it does not know. Bare TCP + hand-rolled HTTP/1.1 — /// just enough for the client's form post. struct FakeIm { addr: std::net::SocketAddr, tokens: Arc>>, photos: Photos, } impl FakeIm { async fn spawn() -> Self { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let tokens: Arc>> = Arc::new(Mutex::new(HashMap::new())); let photos: Photos = Arc::new(Mutex::new(HashMap::new())); let map = tokens.clone(); let pmap = photos.clone(); tokio::spawn(async move { loop { let Ok((socket, _)) = listener.accept().await else { return; }; let map = map.clone(); let pmap = pmap.clone(); tokio::spawn(async move { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let mut socket = socket; let mut buf = vec![0u8; 8192]; let mut req = Vec::new(); // One request after another on the same connection: // closing it after every answer races the client's // pool, which may hand out the dead socket for the // next introspection and read that as signed-out. loop { let body_start = loop { let Ok(n) = socket.read(&mut buf).await else { return; }; if n == 0 { return; } req.extend_from_slice(&buf[..n]); if let Some(end) = headers_end(&req) { let head = String::from_utf8_lossy(&req[..end]).to_string(); let len = content_length(&head); if req.len() >= end + len { break end; } } if req.len() > 1_000_000 { return; } }; let head = String::from_utf8_lossy(&req[..body_start]).to_string(); let first = head.lines().next().unwrap_or("").to_string(); // The body may already hold the next pipelined // request's first bytes; take exactly this one. let len = content_length(&head); let body: Vec = req[body_start..body_start + len].to_vec(); req.drain(..body_start + len); let (status, content_type, payload) = match photo_answer(&pmap, &head, &first) { Some(photo) => photo, None => match answer_for(&map, &first, &body) { Some(answer) => ( "200 OK", "application/json".to_string(), serde_json::to_vec(&answer).unwrap(), ), // Anything but the introspection route is // nothing at all, the way the real im 404s // unknown paths rather than answering them. None => ("404 Not Found", "text/plain".to_string(), Vec::new()), }, }; let response = format!( "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n", payload.len() ); if socket.write_all(response.as_bytes()).await.is_err() { return; } if socket.write_all(&payload).await.is_err() { return; } } }); } }); Self { addr, tokens, photos, } } fn url(&self) -> String { format!("http://{}", self.addr) } /// Stores the photo `GET /photo/{user_id}` answers with — the bytes and /// the mime im would serve for this account. fn set_photo(&self, user_id: &str, bytes: Vec, mime: &str) { self.photos .lock() .insert(user_id.to_string(), (bytes, mime.to_string())); } } /// The Basic credential the app presents for `GET /photo/*`: `iz-test:s3cr3t`. const PHOTO_BASIC: &str = "Basic aXotdGVzdDpzM2NyM3Q="; /// Answers `GET /photo/{id}` from the photo map — the app's Basic credential /// or nothing, a missing photo exactly like a missing person. `None` for /// anything else, which stays the introspection JSON. fn photo_answer( photos: &Photos, head: &str, request_line: &str, ) -> Option<(&'static str, String, Vec)> { let mut parts = request_line.split_whitespace(); if parts.next() != Some("GET") { return None; } let target = parts.next().unwrap_or(""); let path = target .split_once('?') .map(|(path, _)| path) .unwrap_or(target); let id = path.strip_prefix("/photo/")?; if id.is_empty() || id.contains('/') { return None; } let authed = head .lines() .filter_map(|line| line.split_once(':')) .any(|(name, value)| { name.trim().eq_ignore_ascii_case("authorization") && value.trim() == PHOTO_BASIC }); if !authed { return Some(("404 Not Found", "text/plain".to_string(), Vec::new())); } match photos.lock().get(id) { Some((bytes, mime)) => Some(("200 OK", mime.clone(), bytes.clone())), None => Some(("404 Not Found", "text/plain".to_string(), Vec::new())), } } fn headers_end(req: &[u8]) -> Option { req.windows(4) .position(|w| w == b"\r\n\r\n") .map(|pos| pos + 4) } fn content_length(head: &str) -> usize { head.lines() .find_map(|line| { let (name, value) = line.split_once(':')?; (name.trim().eq_ignore_ascii_case("content-length")) .then(|| value.trim().parse().ok())? }) .unwrap_or(0) } /// Percent-decoding, enough for the opaque tokens these tests mint. fn decode(raw: &str) -> String { let mut out = String::with_capacity(raw.len()); let mut bytes = raw.as_bytes().iter(); while let Some(&b) = bytes.next() { if b == b'+' { out.push(' '); } else if b == b'%' { let hi = bytes.next().copied().unwrap_or(b'0'); let lo = bytes.next().copied().unwrap_or(b'0'); let hex = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8; out.push((hex(hi) * 16 + hex(lo)) as char); } else { out.push(b as char); } } out } fn answer_for( map: &Arc>>, request_line: &str, body: &[u8], ) -> Option { let mut head = request_line.split_whitespace(); let is_introspect = head.next() == Some("POST") && head.next() == Some(iz_client::introspect_path()); if !is_introspect { return None; } let text = String::from_utf8_lossy(body).to_string(); let token = text .split('&') .filter_map(|pair| pair.split_once('=')) .find(|(name, _)| *name == "token") .map(|(_, value)| decode(value)); match token.and_then(|token| map.lock().get(&token).cloned()) { Some(claims) => Some(claims), None => Some(serde_json::json!({"active": false})), } } /// A throwaway workspace: its own database file, its own fake im, its own /// router. struct App { dir: PathBuf, router: Router, store: Arc, client: iz_client::Config, fake: FakeIm, /// The storage peer's client and health, registered exactly as /// `main.rs` registers them; `storage_cycle` tests run the beat by /// hand over these. storage_client: iz_web::storage::StorageClient, storage_health: iz_web::storage::StorageHealth, /// What the Settings Connection card renders: poked by hand in tests /// the way the mirror task pokes it in the process. health: iz_web::directory::DirectoryHealth, /// Stands in for Ctrl+C. Held so a test can stop this router the way the /// process stops the real one. stop: tokio::sync::watch::Sender, } impl App { async fn build(mail: Mail) -> Self { Self::build_with(mail, None, "", None).await } /// Like `build`, but with the knobs a configured deployment has: the /// family list mirrored from im — passed as the raw JSON the `setting` /// row holds, so a test can also feed it a body that will not parse — /// and the configured `base_url`. Building them in is what lets the /// switcher and the sign-out handoff be asserted over real HTTP. /// /// `storage_in` is the `[storage.in]` token, when the deployment /// under test has one. async fn build_with( mail: Mail, family: Option, base_url: &str, storage_in: Option, ) -> Self { let dir = std::env::temp_dir().join(format!("iz-http-{}", Ulid::generate())); std::fs::create_dir_all(&dir).unwrap(); let db = dir.join("iz.db"); let storage = dir.join("storage"); let store: Arc = Arc::new( TursoStore::open(db.to_str().unwrap(), storage.as_path()) .await .unwrap(), ); // The family list is a mirror, not a config: the test plays the // part of the background beat that stores what im served. if let Some(family) = &family { store .set_setting(iz_web::server::FAMILY_KEY, family) .await .unwrap(); } let storage_client = iz_web::storage::StorageClient::new(storage_in.clone()); let storage_health = iz_web::storage::StorageHealth::new(); let fake = FakeIm::spawn().await; let config = iz_core::Config { database: db, storage, listen: "127.0.0.1:7655".parse().unwrap(), live_seconds: 300, base_url: base_url.to_string(), oidc: iz_core::config::OidcConfig { issuer: fake.url(), client_id: "iz-test".to_string(), client_secret: "s3cr3t".to_string(), redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), }, ignored: Vec::new(), storage_in: storage_in.map(|token| iz_core::config::InStorage { token }), defaulted: false, }; // The fallback half of the chain, built exactly as `main.rs` builds // it: the configured public address, else the address bound. let client = iz_client::Config { issuer: fake.url(), client_id: "iz-test".to_string(), client_secret: "s3cr3t".to_string(), redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), logout_back: config.public_url(), cookie_name: "iz_session".to_string(), cookie_key: [7u8; 32], }; let health = iz_web::directory::DirectoryHealth::new(); let (stop, stopping) = tokio::sync::watch::channel(false); let router = iz_client::mount( Router::builder() .discover() .runtime() .layer( BodyLimit::max(iz_web::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024) .at("/files"), ) .cookies() .assets( AssetBundle::load_dir(asset_dir()) .expect("run `topcoat asset bundle` before the http suite"), ) .trusted_proxies(iz_web::server::trusted_proxies()), client.clone(), ) .app_context(store.clone()) .app_context(im_client::directory::DirectoryClient::new( fake.url(), "iz-test", "s3cr3t", )) .app_context(health.clone()) .app_context(storage_client.clone()) .app_context(storage_health.clone()) .app_context(iz_client::LogoutBack(Arc::new(iz_web::server::logout_back))) .app_context(config.clone()) .app_context(TEST_LIVE_WINDOW) .app_context(iz_web::live::Shutdown(stopping)) .app_context(mail) .build(); Self { dir, router, store, client, fake, storage_client, storage_health, health, stop, } } async fn open() -> Self { Self::build(Mail::silent()).await } /// Like `open`, but with a live mail engine reading the workspace's SMTP /// settings, so a transition actually reaches the ledger instead of the /// silent no-op `open`'s router hands every crossing. async fn open_with_mail() -> Self { let dir = std::env::temp_dir().join(format!("iz-http-{}", Ulid::generate())); std::fs::create_dir_all(&dir).unwrap(); let db = dir.join("iz.db"); let storage = dir.join("storage"); let store: Arc = Arc::new( TursoStore::open(db.to_str().unwrap(), storage.as_path()) .await .unwrap(), ); let engine = Arc::new(iz_core::MailEngine::new( store.clone(), Arc::new(iz_web::smtp::WorkspaceSmtp::new(store.clone())), "https://iz.sh", )); let fake = FakeIm::spawn().await; let config = iz_core::Config { database: db, storage, listen: "127.0.0.1:7655".parse().unwrap(), base_url: String::new(), live_seconds: 300, oidc: iz_core::config::OidcConfig { issuer: fake.url(), client_id: "iz-test".to_string(), client_secret: "s3cr3t".to_string(), redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), }, ignored: Vec::new(), storage_in: None, defaulted: false, }; // The fallback half of the chain, built exactly as `main.rs` builds // it: the configured public address, else the address bound. let client = iz_client::Config { issuer: fake.url(), client_id: "iz-test".to_string(), client_secret: "s3cr3t".to_string(), redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), logout_back: config.public_url(), cookie_name: "iz_session".to_string(), cookie_key: [7u8; 32], }; let health = iz_web::directory::DirectoryHealth::new(); let storage_client = iz_web::storage::StorageClient::new(None); let storage_health = iz_web::storage::StorageHealth::new(); let (stop, stopping) = tokio::sync::watch::channel(false); let router = iz_client::mount( Router::builder() .discover() .runtime() .layer( BodyLimit::max(iz_web::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024) .at("/files"), ) .cookies() .assets( AssetBundle::load_dir(asset_dir()) .expect("run `topcoat asset bundle` before the http suite"), ) .trusted_proxies(iz_web::server::trusted_proxies()), client.clone(), ) .app_context(store.clone()) .app_context(im_client::directory::DirectoryClient::new( fake.url(), "iz-test", "s3cr3t", )) .app_context(health.clone()) .app_context(storage_client.clone()) .app_context(storage_health.clone()) .app_context(iz_client::LogoutBack(Arc::new(iz_web::server::logout_back))) .app_context(config.clone()) .app_context(TEST_LIVE_WINDOW) .app_context(iz_web::live::Shutdown(stopping)) .app_context(Mail::sending(engine)) .build(); Self { dir, router, store, client, fake, storage_client, storage_health, health, stop, } } /// Mints a session cookie for an im identity, registering its claims on /// the fake — exactly what `/auth/callback` seals, without the browser /// dance. The local row is provisioned on the next request, the way a /// real first login provisions it. fn mint(&self, sub: &str, email: &str, name: &str, im_admin: bool) -> String { let token = format!("tok-{}", Ulid::generate()); let exp = time::OffsetDateTime::now_utc() + time::Duration::hours(1); self.fake.tokens.lock().insert( token.clone(), serde_json::json!({ "active": true, "sub": sub, "email": email, "name": name, "admin": im_admin, "exp": exp.unix_timestamp(), }), ); iz_client::mint_session_cookie(&self.client, &token, exp) } /// Opens `/api/live`. The response is returned as soon as the handler has /// subscribed, so a caller writes AFTER this returns and the announcement /// still lands in the feed. async fn live_open(&self, cookie: Option<&str>) -> topcoat::router::response::Response { let mut request = Request::builder().method("GET").uri("/api/live"); if let Some(cookie) = cookie { request = request.header( header::COOKIE, HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(), ); } self.router .handle(request.body(Body::empty()).unwrap()) .await } /// The single workspace's id, read straight off the store: `TursoStore` is /// single-tenant, so there is no id to guess and no JSON endpoint needed /// just to hand it back. async fn workspace_id(&self) -> String { self.store .workspace() .await .unwrap() .expect("no workspace yet") .id } /// Posts a form the way a hydrated caller does: `Accept: application/json`, /// no `Referer`. Every mutating `/api/*` route answers `303 See Other` /// regardless — [`Router::handle`] never follows a redirect, so the answer /// is read straight off this response, same as `oneshot` did before. async fn post(&self, path: &str, cookie: Option<&str>, form: &[(&str, &str)]) -> Answer { self.post_with_extra_cookie(path, cookie, form, None).await } /// Like `post`, but with a second `Cookie` header of the caller's own /// naming — for the `iz_rows_
` page-size cookie, which lives /// beside the session cookie rather than replacing it. async fn post_with_extra_cookie( &self, path: &str, cookie: Option<&str>, form: &[(&str, &str)], extra_cookie: Option<&str>, ) -> Answer { let body = form .iter() .map(|(key, value)| format!("{}={}", encode(key), encode(value))) .collect::>() .join("&"); let mut request = Request::builder() .method("POST") .uri(path) .header(header::ACCEPT, "application/json") .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); if let Some(cookie) = cookie { request = request.header( header::COOKIE, HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(), ); } if let Some(extra) = extra_cookie { request = request.header(header::COOKIE, HeaderValue::from_str(extra).unwrap()); } let response = self .router .handle(request.body(Body::from(body)).unwrap()) .await; Answer::from_response(response).await } /// Posts the same form the way a browser with no script posts it: asking /// for a page back, from a page it names. The answer is a redirect, and the /// redirect is the whole of what the person will be shown. async fn post_without_script( &self, path: &str, cookie: Option<&str>, referer: &str, form: &[(&str, &str)], ) -> Answer { let body = form .iter() .map(|(key, value)| format!("{}={}", encode(key), encode(value))) .collect::>() .join("&"); let mut request = Request::builder() .method("POST") .uri(path) .header(header::ACCEPT, "text/html") .header(header::REFERER, referer) .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); if let Some(cookie) = cookie { request = request.header( header::COOKIE, HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(), ); } let response = self .router .handle(request.body(Body::from(body)).unwrap()) .await; Answer::from_response(response).await } /// Posts a multipart form the way a browser's /// `
` does, hand-built rather than /// pulling in a client crate for it: the fields first, in the order given /// — the upload handler reads `task_id` before it reaches `file` — then /// one `file` part if given. async fn post_multipart( &self, path: &str, cookie: Option<&str>, fields: &[(&str, &str)], file: Option<(&str, &str, &[u8])>, ) -> Answer { const BOUNDARY: &str = "iz-test-boundary"; let mut body = Vec::new(); for (name, value) in fields { body.extend_from_slice( format!( "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n" ) .as_bytes(), ); } if let Some((filename, content_type, bytes)) = file { body.extend_from_slice( format!( "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: {content_type}\r\n\r\n" ) .as_bytes(), ); body.extend_from_slice(bytes); body.extend_from_slice(b"\r\n"); } body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes()); let mut request = Request::builder().method("POST").uri(path).header( header::CONTENT_TYPE, format!("multipart/form-data; boundary={BOUNDARY}"), ); if let Some(cookie) = cookie { request = request.header( header::COOKIE, HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(), ); } let response = self .router .handle(request.body(Body::from(body)).unwrap()) .await; Answer::from_response(response).await } /// Gets a page or a download the way a browser does: no `Accept` header /// forcing JSON, an optional cookie, and the raw bytes back untouched — a /// download's body is not always UTF-8. async fn get(&self, path: &str, cookie: Option<&str>) -> Raw { self.get_with_range(path, cookie, None).await } /// Like `get`, but with a second `Cookie` header of the caller's own /// naming — for the `iz_rows_
` page-size cookie, which /// lives beside the session cookie rather than replacing it. async fn get_with_extra_cookie(&self, path: &str, cookie: Option<&str>, extra: &str) -> Raw { self.get_with(path, cookie, None, None, Some(extra)).await } /// Like `get`, but with a `Range` header, for exercising the /// `/files/{id}` partial-content path. async fn get_with_range(&self, path: &str, cookie: Option<&str>, range: Option<&str>) -> Raw { self.get_with(path, cookie, range, None, None).await } /// Like `get`, but with `If-None-Match`, for the `/photo/{user_id}` /// revalidate path. async fn get_with_if_none_match(&self, path: &str, cookie: Option<&str>, etag: &str) -> Raw { self.get_with(path, cookie, None, Some(etag), None).await } async fn get_with( &self, path: &str, cookie: Option<&str>, range: Option<&str>, if_none_match: Option<&str>, extra_cookie: Option<&str>, ) -> Raw { let mut request = Request::builder().method("GET").uri(path); if let Some(cookie) = cookie { request = request.header( header::COOKIE, HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(), ); } if let Some(extra) = extra_cookie { request = request.header(header::COOKIE, HeaderValue::from_str(extra).unwrap()); } if let Some(range) = range { request = request.header(header::RANGE, range); } if let Some(if_none_match) = if_none_match { request = request.header(header::IF_NONE_MATCH, if_none_match); } let response = self .router .handle(request.body(Body::empty()).unwrap()) .await; let status = response.status(); let content_type = response .headers() .get(header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) .map(str::to_string); let disposition = response .headers() .get(header::CONTENT_DISPOSITION) .and_then(|value| value.to_str().ok()) .map(str::to_string); let content_range = response .headers() .get(header::CONTENT_RANGE) .and_then(|value| value.to_str().ok()) .map(str::to_string); let accept_ranges = response .headers() .get(header::ACCEPT_RANGES) .and_then(|value| value.to_str().ok()) .map(str::to_string); let etag = response .headers() .get(header::ETAG) .and_then(|value| value.to_str().ok()) .map(str::to_string); let cache_control = response .headers() .get(header::CACHE_CONTROL) .and_then(|value| value.to_str().ok()) .map(str::to_string); let location = response .headers() .get(header::LOCATION) .and_then(|value| value.to_str().ok()) .map(str::to_string); let bytes = to_bytes(response.into_body(), usize::MAX) .await .unwrap() .to_vec(); Raw { status, content_type, disposition, content_range, accept_ranges, etag, cache_control, location, bytes, } } } impl Drop for App { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.dir); } } /// A GET answer kept as raw bytes: a page's HTML or a download's file, neither /// of which the JSON-shaped [`Answer`] below is meant for. struct Raw { status: StatusCode, content_type: Option, disposition: Option, content_range: Option, accept_ranges: Option, etag: Option, cache_control: Option, /// Where a 303 sends the browser — the sign-out handoff's whole point. location: Option, bytes: Vec, } struct Answer { status: StatusCode, body: String, /// Where a browser without script is sent next. The only place such a /// browser can be told anything. location: Option, } impl Answer { async fn from_response(response: topcoat::router::response::Response) -> Self { let status = response.status(); let location = response .headers() .get(header::LOCATION) .and_then(|value| value.to_str().ok()) .map(str::to_string); let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); Answer { status, body: String::from_utf8(bytes.to_vec()).unwrap(), location, } } } /// Form encoding, enough for the addresses these tests send. fn encode(raw: &str) -> String { let mut out = String::with_capacity(raw.len()); for byte in raw.bytes() { match byte { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { out.push(byte as char) } b' ' => out.push('+'), other => out.push_str(&format!("%{other:02X}")), } } out } /// What the tests type into the password field. It must never come back out. const SENDER_PASSWORD: &str = "cavalry-battery-hinge-40"; /// Fills in the sender panel the way an admin would, and reports whether the /// server accepted it. /// /// `save_sender` answers with an empty body and carries any refusal on the /// redirect's query instead of in JSON (settings routes have no hydrated /// caller to answer with a value) — accepted is "no `refusal=` on the way /// back". async fn sender_saved(app: &App, admin: &str) -> bool { let answer = app .post( "/api/save_sender", Some(admin), &[ ("host", "smtp.fastmail.com"), ("port", "465"), ("username", "iz"), ("password", SENDER_PASSWORD), ("from_name", "iz"), ("from_address", "iz@iz.sh"), ], ) .await; answer.status == StatusCode::SEE_OTHER && answer .location .as_deref() .is_some_and(|location| !location.contains("refusal=")) } /// Signs in the workspace's first im-admin identity and returns its cookie. /// The first sight of her provisions the local row and claims the workspace /// owner, the way a real first login sets the workspace up. async fn admin(app: &App) -> String { let sub = "im-ada"; let user = app .store .provision_user(sub, "ada@iz.sh", "Ada Lovelace", true) .await .unwrap(); assert_eq!( user.role, Role::Admin, "the first im admin did not claim admin" ); app.mint(sub, "ada@iz.sh", "Ada Lovelace", true) } /// Signs in an im identity as a plain member and returns its cookie. async fn member(app: &App, email: &str, name: &str) -> String { let sub = format!("im-{email}"); app.store .provision_user(&sub, email, name, false) .await .unwrap(); app.mint(&sub, email, name, false) } /// Signs in an im identity as a viewer and returns its cookie: provisioned a /// member by default, then cut down to viewer the way an admin would. async fn viewer(app: &App, email: &str, name: &str) -> String { let sub = format!("im-{email}"); let user = app .store .provision_user(&sub, email, name, false) .await .unwrap(); app.store.set_role(&user.id, Role::Viewer).await.unwrap(); app.mint(&sub, email, name, false) } /// Signs in an im identity in the given role and returns its cookie — the /// old invite-and-redeem flow's replacement at the call sites that only ever /// needed "a member" or "a viewer". An admin comes from im's flag, never /// from this file. async fn invited(app: &App, _admin: &str, email: &str, name: &str, role: Role) -> String { match role { Role::Admin => { let sub = format!("im-{email}"); app.store .provision_user(&sub, email, name, true) .await .unwrap(); app.mint(&sub, email, name, true) } Role::Member => member(app, email, name).await, Role::Viewer => viewer(app, email, name).await, } } /// The id of the board's first column, read straight off the store: there is /// no JSON `CurrentBoard` endpoint left to ask for it (the board is a /// server-rendered shard now), and the id is fixture setup, not the behavior /// under test. async fn first_column(app: &App) -> String { columns_of(app) .await .into_iter() .next() .expect("no columns on a fresh board") } /// Every column id on the board, in order, read straight off the store — see /// [`first_column`] on why this bypasses HTTP. async fn columns_of(app: &App) -> Vec { let workspace_id = app.workspace_id().await; let board = app .store .board(&workspace_id) .await .unwrap() .expect("no board"); app.store .columns(&board.id) .await .unwrap() .into_iter() .map(|c| c.id) .collect() } /// Makes a task and hands back its id, read straight off the store — there is /// no `CurrentBoard` JSON call left to read it from (the board is a /// server-rendered shard now); the mutation itself is still a real HTTP post. async fn a_task(app: &App, cookie: &str, column: &str, title: &str) -> String { let answer = app .post( "/api/create_task", Some(cookie), &[("title", title), ("column_id", column)], ) .await; assert_eq!(answer.body, "", "the task was refused: {}", answer.body); let workspace_id = app.workspace_id().await; let board = iz_core::board::load(app.store.as_ref(), &workspace_id) .await .unwrap() .unwrap(); board .columns .iter() .flat_map(|c| &c.cards) .find(|card| card.title == title) .expect("the new task is not on the board") .id .clone() } #[tokio::test] async fn a_viewer_who_posts_to_create_task_anyway_is_refused() { let app = App::open().await; let admin = admin(&app).await; let viewer = invited(&app, &admin, "quiet@iz.sh", "Quiet Reader", Role::Viewer).await; let column = first_column(&app).await; let answer = app .post( "/api/create_task", Some(&viewer), &[ ("title", "Viewer should not get this"), ("column_id", &column), ], ) .await; assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body); assert_eq!(answer.body, ""); assert!( answer .location .as_deref() .unwrap_or_default() .contains("refusal=forbidden&on=create_task"), "{:?}", answer.location ); // And the refusal is not cosmetic: the board is still empty. let workspace_id = app.workspace_id().await; let board = iz_core::board::load(app.store.as_ref(), &workspace_id) .await .unwrap() .unwrap(); assert!( board .columns .iter() .flat_map(|c| &c.cards) .all(|card| card.title != "Viewer should not get this"), "the refused task was written anyway" ); } #[tokio::test] async fn a_member_may_create_a_task() { let app = App::open().await; let admin = admin(&app).await; let member = invited(&app, &admin, "mo@iz.sh", "Mo Dubois", Role::Member).await; let column = first_column(&app).await; let answer = app .post( "/api/create_task", Some(&member), &[("title", "Wire the deadline chip"), ("column_id", &column)], ) .await; assert_eq!(answer.body, ""); assert!( !answer .location .as_deref() .unwrap_or_default() .contains("refusal="), "a create that worked said it was refused: {:?}", answer.location ); let workspace_id = app.workspace_id().await; let board = iz_core::board::load(app.store.as_ref(), &workspace_id) .await .unwrap() .unwrap(); let card = board .columns .iter() .flat_map(|c| &c.cards) .find(|card| card.title == "Wire the deadline chip") .expect("new task is not on the board"); let tail = card .task_key .strip_prefix("DZ-") .expect("key not shaped like DZ-"); assert!( (5..=7).contains(&tail.len()), "key tail {tail} not 5..=7 chars" ); assert!( tail.chars() .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()), "key tail {tail} not uppercase alnum" ); } // A cross-site form post carries no refusal body — the create simply works — // so `carry_refusal_on_redirect` used to have nothing to rewrite and sent the // browser straight to the attacker's own Referer. The fix sanitizes the // Location on every redirect this layer sees, refusal or not. #[tokio::test] async fn a_successful_create_never_redirects_off_site() { let app = App::open().await; let admin = admin(&app).await; let column = first_column(&app).await; let answer = app .post_without_script( "/api/create_task", Some(&admin), "https://elsewhere.example/steal", &[("title", "Cross-site create"), ("column_id", &column)], ) .await; assert_eq!(answer.status, StatusCode::SEE_OTHER); let location = answer.location.expect("a redirect with nowhere to go"); assert!( !location.contains("elsewhere.example"), "the browser was sent off-site: {location}" ); } #[tokio::test] async fn a_task_cannot_be_dropped_into_another_workspaces_column() { let app = App::open().await; let admin = admin(&app).await; let answer = app .post( "/api/create_task", Some(&admin), &[ ("title", "Wrong column"), ("column_id", "00000000-0000-0000-0000-000000000000"), ], ) .await; assert_eq!(answer.body, ""); assert!( answer .location .as_deref() .unwrap_or_default() .contains("refusal=forbidden&on=create_task"), "{:?}", answer.location ); let workspace_id = app.workspace_id().await; let board = iz_core::board::load(app.store.as_ref(), &workspace_id) .await .unwrap() .unwrap(); assert!( board .columns .iter() .flat_map(|c| &c.cards) .all(|card| card.title != "Wrong column"), "the refused task was written anyway" ); } #[tokio::test] async fn a_card_needs_a_title() { let app = App::open().await; let admin = admin(&app).await; let column = first_column(&app).await; let answer = app .post( "/api/create_task", Some(&admin), &[("title", " "), ("column_id", &column)], ) .await; assert_eq!(answer.body, ""); assert!( answer .location .as_deref() .unwrap_or_default() .contains("refusal=empty-title&on=create_task"), "{:?}", answer.location ); let workspace_id = app.workspace_id().await; let board = iz_core::board::load(app.store.as_ref(), &workspace_id) .await .unwrap() .unwrap(); assert_eq!( board.columns.iter().flat_map(|c| &c.cards).count(), 0, "a blank title was stored anyway" ); } #[tokio::test] async fn the_board_is_not_readable_without_a_session() { let app = App::open().await; let _admin = admin(&app).await; // There is no `CurrentBoard` JSON call any more (see FINDING near // `first_column`); the guard is exercised on a real read instead: the // signed-out board page itself. let raw = app.get("/", None).await; let html = String::from_utf8_lossy(&raw.bytes); assert!( !html.contains("board-stage"), "a signed-out browser was shown the board: {html}" ); } /// The sort control still posts as a plain `