//! The drive driven the way a browser drives it: real router, real store, //! real session cookie, fake im. //! //! Auth in tests: the OIDC dance cannot run against a live im, so each test //! spins a fake one — a bare TCP server answering `POST /introspect` — and //! signs users in with `in_client::mint_session_cookie` (feature //! `test-seam`). The token<->claims map is per-test, so one test's session //! is meaningless to the next. //! //! New HTTP tests belong in this file rather than a new `tests/*.rs`: one //! test binary links and runs once. use http::{HeaderValue, Request, StatusCode, header}; use http_body_util::BodyExt; use in_core::{Config, OidcConfig}; use std::collections::HashMap; use std::path::PathBuf; use std::process::Command; use std::sync::{Arc, Mutex}; use in_core::store::{ShareKind, Store, TursoStore}; use in_web::server::App; use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; use topcoat::context::Cx; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{Body, BodyLimit, Router, RouterBuilderDiscoverExt, to_bytes}; use topcoat::runtime::RouterBuilderRuntimeExt; use ulid::Ulid; /// The bundle `cargo build -p in-web` + `topcoat asset bundle --bin in-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" )) } /// Photos by file id: raw bytes plus mime, answered to `GET /photo/{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, directory: Arc>>, family: Arc>>, } 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 directory: Arc>> = Arc::new(Mutex::new(Vec::new())); let family: Arc>> = Arc::new(Mutex::new(Vec::new())); let map = tokens.clone(); let pmap = photos.clone(); let dmap = directory.clone(); let fmap = family.clone(); tokio::spawn(async move { loop { let Ok((socket, _)) = listener.accept().await else { return; }; let map = map.clone(); let pmap = pmap.clone(); let dmap = dmap.clone(); let fmap = fmap.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 directory_answer(&dmap, &head, &first) { Some(members) => members, None => match family_answer(&fmap, &head, &first) { Some(list) => list, None => match answer_for(&map, &first, &body) { Some(answer) => ( "200 OK", "application/json".to_string(), serde_json::to_vec(&answer).unwrap(), ), // Anything but the photo, directory // and family routes 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, directory, family, } } fn url(&self) -> String { format!("http://{}", self.addr) } /// Stages the list `GET /family` answers with — the suite im keeps. /// Unset, the route is simply not there, as for an app im has not /// registered. fn set_family(&self, list: Vec) { *self.family.lock().unwrap() = list; } /// 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() .unwrap() .insert(user_id.to_string(), (bytes, mime.to_string())); } /// Stages the members `GET /directory` answers with — the people im /// knows. Unset, the route is simply not there, as for an app im has /// not registered. fn set_directory(&self, members: &[serde_json::Value]) { *self.directory.lock().unwrap() = members.to_vec(); } } /// The Basic credential the app presents for `GET /photo/*` and /// `GET /directory`: `in-test:s3cr3t`. const APP_BASIC: &str = "Basic aW4tdGVzdDpzM2NyM3Q="; /// 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() == APP_BASIC }); if !authed { return Some(("404 Not Found", "text/plain".to_string(), Vec::new())); } match photos.lock().unwrap().get(id) { Some((bytes, mime)) => Some(("200 OK", mime.clone(), bytes.clone())), None => Some(("404 Not Found", "text/plain".to_string(), Vec::new())), } } /// Answers `GET /directory` with the staged members — the app's Basic /// credential or nothing, and with nothing staged no route at all. `None` /// for anything else, which stays the introspection JSON. fn directory_answer( directory: &Arc>>, 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); if path != "/directory" { return None; } let authed = head .lines() .filter_map(|line| line.split_once(':')) .any(|(name, value)| { name.trim().eq_ignore_ascii_case("authorization") && value.trim() == APP_BASIC }); if !authed { return Some(("404 Not Found", "text/plain".to_string(), Vec::new())); } let members = directory.lock().unwrap(); if members.is_empty() { return Some(("404 Not Found", "text/plain".to_string(), Vec::new())); } Some(( "200 OK", "application/json".to_string(), serde_json::to_vec(&*members).unwrap(), )) } /// Answers `GET /family` with the staged suite — the app's Basic credential /// or nothing, and with nothing staged no route at all. `None` for anything /// else, which falls through to the introspection JSON. fn family_answer( family: &Arc>>, 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); if path != "/family" { return None; } let authed = head .lines() .filter_map(|line| line.split_once(':')) .any(|(name, value)| { name.trim().eq_ignore_ascii_case("authorization") && value.trim() == APP_BASIC }); if !authed { return Some(("404 Not Found", "text/plain".to_string(), Vec::new())); } let list = family.lock().unwrap(); if list.is_empty() { return Some(("404 Not Found", "text/plain".to_string(), Vec::new())); } Some(( "200 OK", "application/json".to_string(), serde_json::to_vec(&*list).unwrap(), )) } 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(in_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().unwrap().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 TestApp { dir: PathBuf, router: Router, store: Arc, config: Config, client: in_client::Config, fake: FakeIm, health: in_web::server::DirectoryHealth, stop: tokio::sync::watch::Sender, } impl TestApp { async fn build() -> Self { Self::build_with(None, &[]).await } /// The same workspace with a config `base_url` set — the key that /// decides where the public links are told to point — and an optional /// family list, the suite the topbar's switcher links to, seeded the /// way the background fetch files it: one JSON row in the `setting` /// store under `family`. async fn build_with(base_url: Option<&str>, family: &[(&str, &str, &str)]) -> Self { let dir = std::env::temp_dir().join(format!("in-http-{}", Ulid::generate())); std::fs::create_dir_all(&dir).unwrap(); let db = dir.join("in.db"); let storage = dir.join("storage"); let store: Arc = Arc::new( TursoStore::open(db.to_str().unwrap(), Some(storage.as_path())) .await .unwrap(), ); if !family.is_empty() { let list: Vec = family .iter() .map(|(key, name, url)| in_client::ServiceJson { key: key.to_string(), name: name.to_string(), url: url.to_string(), limit_bytes: None, }) .collect(); store .set_setting("family", &serde_json::to_string(&list).unwrap()) .await .unwrap(); } let fake = FakeIm::spawn().await; let client = in_client::Config { issuer: fake.url(), client_id: "in-test".to_string(), client_secret: "s3cr3t".to_string(), redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), cookie_name: "in_session".to_string(), cookie_key: [7u8; 32], logout_back: "http://127.0.0.1:7655".to_string(), }; let config = Config { database: db.to_str().unwrap().to_string(), storage, listen: "127.0.0.1:7655".parse().unwrap(), live_seconds: 300, purge_after_days: 30, default_quota_bytes: 10 * 1024 * 1024 * 1024, base_url: base_url.map(str::to_string), r2: None, oidc: OidcConfig { issuer: fake.url(), client_id: "in-test".to_string(), client_secret: "s3cr3t".to_string(), redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), }, ignored: Vec::new(), defaulted: false, }; let (stop, stopping) = tokio::sync::watch::channel(false); let health = in_web::server::DirectoryHealth::new(); let router = in_client::mount( Router::builder() .discover() .runtime() .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload")) .layer(BodyLimit::max(512 * 1024 * 1024).at("/api/service/files")) .cookies() .assets( AssetBundle::load_dir(asset_dir()) .expect("run `topcoat asset bundle` before the http suite"), ) .trusted_proxies(in_web::server::trusted_proxies()), client.clone(), ) .app_context(App { store: store.clone(), config: config.clone(), shutdown: in_web::live::Shutdown(stopping), // Deliberately not the cookie key: the sealing helpers must // reach for `link_key`, not for whatever key sits nearest. link_key: [11u8; 32], directory: im_client::directory::DirectoryClient::new( fake.url(), "in-test".to_string(), "s3cr3t".to_string(), ), health: health.clone(), }) .app_context(in_client::LogoutBack(Arc::new(|cx: &Cx| { Box::pin(async move { Some(in_web::server::share_origin(cx).await) }) }))) .build(); Self { dir, router, store, config, client, fake, health, stop, } } /// Provisions the row and mints a session for it, returning the `Cookie` /// header value to send. async fn sign_in(&self, sub: &str, email: &str, name: &str) -> String { let user = self .store .provision_user(sub, email, name, None, 0, self.config.default_quota_bytes) .await .unwrap(); let token = format!("tok-{}", Ulid::generate()); let exp = time::OffsetDateTime::now_utc() + time::Duration::hours(1); self.fake.tokens.lock().unwrap().insert( token.clone(), serde_json::json!({ "active": true, "sub": user.oidc_sub, "email": user.email, "name": user.display_name, "exp": exp.unix_timestamp(), }), ); let value = in_client::mint_session_cookie(&self.client, &token, exp); format!("in_session={value}") } /// 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. async fn post(&self, path: &str, cookie: Option<&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, "application/json") .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); if let Some(cookie) = cookie { request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap()); } let response = self .router .handle(request.body(Body::from(body)).unwrap()) .await; Answer::from_response(response).await } /// Posts JSON the way the upload script does. async fn post_json( &self, path: &str, cookie: Option<&str>, value: serde_json::Value, ) -> Answer { let mut request = Request::builder() .method("POST") .uri(path) .header(header::ACCEPT, "application/json") .header(header::CONTENT_TYPE, "application/json"); if let Some(cookie) = cookie { request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap()); } let response = self .router .handle(request.body(Body::from(value.to_string())).unwrap()) .await; Answer::from_response(response).await } /// Puts raw bytes the way the upload script sends one chunk. async fn put_bytes(&self, path: &str, cookie: Option<&str>, bytes: &[u8]) -> Answer { let mut request = Request::builder() .method("PUT") .uri(path) .header(header::ACCEPT, "application/json") .header(header::CONTENT_TYPE, "application/octet-stream"); if let Some(cookie) = cookie { request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap()); } let response = self .router .handle(request.body(Body::from(bytes.to_vec())).unwrap()) .await; Answer::from_response(response).await } /// Posts a multipart form the way the drive's upload control does, /// hand-built rather than pulling in a client crate for it: the fields /// first, in the order given, then one `file` part per file. async fn post_multipart( &self, path: &str, cookie: Option<&str>, fields: &[(&str, &str)], files: &[(&str, &str, &[u8])], ) -> Answer { const BOUNDARY: &str = "in-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(), ); } for (filename, content_type, bytes) in files { 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(cookie).unwrap()); } let response = self .router .handle(request.body(Body::from(body)).unwrap()) .await; Answer::from_response(response).await } /// Posts a multipart form with a bearer key, the way iz's storage client /// pushes an attachment. Raw bytes back — the machine answer is JSON the /// caller parses itself. async fn post_service_multipart( &self, path: &str, token: Option<&str>, fields: &[(&str, &str)], file: Option<(&str, &[u8])>, ) -> Raw { const BOUNDARY: &str = "in-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, bytes)) = file { body.extend_from_slice( format!( "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: application/octet-stream\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(token) = token { request = request.header(header::AUTHORIZATION, format!("Bearer {token}")); } let response = self .router .handle(request.body(Body::from(body)).unwrap()) .await; Raw::from_response(response).await } /// A machine GET with (maybe) a bearer key. async fn get_bearer(&self, path: &str, token: Option<&str>) -> Raw { let mut request = Request::builder().method("GET").uri(path); if let Some(token) = token { request = request.header(header::AUTHORIZATION, format!("Bearer {token}")); } let response = self .router .handle(request.body(Body::empty()).unwrap()) .await; Raw::from_response(response).await } /// A machine DELETE with (maybe) a bearer key. async fn delete_bearer(&self, path: &str, token: Option<&str>) -> Raw { let mut request = Request::builder().method("DELETE").uri(path); if let Some(token) = token { request = request.header(header::AUTHORIZATION, format!("Bearer {token}")); } let response = self .router .handle(request.body(Body::empty()).unwrap()) .await; Raw::from_response(response).await } /// Gets a page or a download the way a browser does, 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(path, cookie, None, None).await } /// Like `get`, but with a `Range` header, for the partial-content path. async fn get_with_range(&self, path: &str, cookie: Option<&str>, range: &str) -> Raw { self.get_with(path, cookie, Some(range), None).await } /// Like `get`, but with `If-None-Match`, for the thumbnail 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)).await } async fn get_with( &self, path: &str, cookie: Option<&str>, range: Option<&str>, if_none_match: 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(cookie).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 headers = response.headers().clone(); let header = |name| { headers .get(name) .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: header(header::CONTENT_TYPE), disposition: header(header::CONTENT_DISPOSITION), content_range: header(header::CONTENT_RANGE), accept_ranges: header(header::ACCEPT_RANGES), cache_control: header(header::CACHE_CONTROL), etag: header(header::ETAG), location: header(header::LOCATION), bytes, } } } impl Drop for TestApp { fn drop(&mut self) { let _ = self.stop.send(true); let _ = std::fs::remove_dir_all(&self.dir); } } /// A mutating call's answer: always a 303, carrying the refusal (or its /// absence) as JSON — the same body a hydrated caller reads. struct Answer { status: StatusCode, body: String, location: Option, set_cookie: 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 set_cookie = response .headers() .get(header::SET_COOKIE) .and_then(|value| value.to_str().ok()) .map(str::to_string); let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); Answer { status, location, set_cookie, body: String::from_utf8(bytes.to_vec()).unwrap(), } } fn json(&self) -> serde_json::Value { serde_json::from_str(&self.body).unwrap() } fn refused(&self, code: &str, call: &str) -> bool { self.status == StatusCode::SEE_OTHER && self.location.as_deref().is_some_and(|location| { location.contains(&format!("refusal={code}")) && location.contains(&format!("on={call}")) }) } fn accepted(&self) -> bool { self.status == StatusCode::SEE_OTHER && self .location .as_deref() .is_some_and(|location| !location.contains("refusal=")) } } /// A GET answer kept as raw bytes: a page's HTML or a download's file. struct Raw { status: StatusCode, content_type: Option, disposition: Option, content_range: Option, accept_ranges: Option, cache_control: Option, etag: Option, location: Option, bytes: Vec, } impl Raw { async fn from_response(response: topcoat::router::response::Response) -> Self { let status = response.status(); let headers = response.headers().clone(); let header = |name| { headers .get(name) .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: header(header::CONTENT_TYPE), disposition: header(header::CONTENT_DISPOSITION), content_range: header(header::CONTENT_RANGE), accept_ranges: header(header::ACCEPT_RANGES), cache_control: header(header::CACHE_CONTROL), etag: header(header::ETAG), location: header(header::LOCATION), bytes, } } } impl Raw { fn text(&self) -> String { String::from_utf8(self.bytes.clone()).unwrap() } fn json(&self) -> serde_json::Value { serde_json::from_str(&self.text()).unwrap() } } /// Form encoding, enough for the names 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 } /// The 1x1 transparent PNG: the smallest thing the thumbnailer must accept. fn tiny_png() -> Vec { vec![ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, ] } /// The newest live folder with this name under this parent, read straight /// off the store. async fn folder_id(app: &TestApp, owner: &str, parent: Option<&str>, name: &str) -> String { app.store .list_children(owner, parent) .await .unwrap() .folders .iter() .find(|folder| folder.name == name) .expect("folder was not created") .id .clone() } /// The token off a creation redirect's `?created=` pair. fn created_token(location: &str) -> String { let query = location .split_once('?') .map(|(_, query)| query) .unwrap_or(""); query .split('&') .filter_map(|pair| pair.split_once('=')) .find(|(name, _)| *name == "created") .map(|(_, value)| value.to_string()) .expect("creation set no token") } async fn file_id(app: &TestApp, owner: &str, name: &str, bytes: &[u8]) -> String { app.store .insert_file(owner, None, name, bytes) .await .unwrap() .id } async fn owner_of(app: &TestApp, sub: &str) -> String { app.store .provision_user(sub, "x@y.z", "X", None, 0, app.config.default_quota_bytes) .await .unwrap() .id } #[tokio::test] async fn drive_redirects_without_session() { let app = TestApp::build().await; let page = app.get("/drive", None).await; assert_eq!(page.status, StatusCode::SEE_OTHER); assert_eq!(page.location.as_deref(), Some("/")); } #[tokio::test] async fn folder_crud_and_cycle_is_refused() { let app = TestApp::build().await; let cookie = app.sign_in("sub-crud", "crud@in.test", "Crud").await; let user = app .store .user_by_oidc_sub("sub-crud") .await .unwrap() .unwrap(); let answer = app .post( "/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "projects")], ) .await; assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body); assert_eq!(answer.body, "null", "creating was refused"); let projects = folder_id(&app, &user.id, None, "projects").await; let answer = app .post( "/api/folder/create", Some(&cookie), &[("parent_id", &projects), ("name", "sub")], ) .await; assert_eq!(answer.body, "null", "creating was refused"); let sub = folder_id(&app, &user.id, Some(&projects), "sub").await; // Nesting `projects` inside its own descendant is refused, not looped. let answer = app .post( "/api/folder/move", Some(&cookie), &[("id", &projects), ("parent_id", &sub)], ) .await; assert_eq!(answer.status, StatusCode::SEE_OTHER); assert!( answer.body.contains("Forbidden"), "cycle was not refused: {}", answer.body ); // A legal move, a rename and a delete all land clean. let answer = app .post( "/api/folder/move", Some(&cookie), &[("id", &sub), ("parent_id", "")], ) .await; assert_eq!(answer.body, "null", "moving was refused: {}", answer.body); let answer = app .post( "/api/folder/rename", Some(&cookie), &[("id", &sub), ("name", "moved")], ) .await; assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body); let answer = app .post("/api/folder/delete", Some(&cookie), &[("id", &sub)]) .await; assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body); // The drive page names what is left. let page = app.get("/drive", Some(&cookie)).await; assert_eq!(page.status, StatusCode::OK); assert!(page.text().contains("projects"), "drive hides the folder"); } #[tokio::test] async fn small_upload_round_trip() { let app = TestApp::build().await; let cookie = app.sign_in("sub-small", "small@in.test", "Small").await; let user = app .store .user_by_oidc_sub("sub-small") .await .unwrap() .unwrap(); let bytes = b"hello in"; let answer = app .post_multipart( "/files", Some(&cookie), &[("folder_id", "")], &[("hello.txt", "text/plain", bytes)], ) .await; assert_eq!( answer.status, StatusCode::SEE_OTHER, "{}", answer.location.unwrap_or_default() ); assert!( !answer .location .as_deref() .unwrap_or("") .contains("refusal="), "upload was refused: {}", answer.location.unwrap_or_default() ); let file = app .store .list_children(&user.id, None) .await .unwrap() .files .into_iter() .find(|file| file.name == "hello.txt") .expect("file was not stored"); assert_eq!(file.mime, "text/plain"); let got = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; assert_eq!(got.status, StatusCode::OK); assert_eq!(got.bytes, bytes); assert_eq!(got.accept_ranges.as_deref(), Some("bytes")); assert!( got.cache_control .as_deref() .unwrap_or("") .contains("immutable"), "missing immutable cache directive" ); } #[tokio::test] async fn chunked_upload_round_trip() { let app = TestApp::build().await; let cookie = app.sign_in("sub-chunk", "chunk@in.test", "Chunk").await; let user = app .store .user_by_oidc_sub("sub-chunk") .await .unwrap() .unwrap(); // Two chunks: the 8 MiB server size plus a tail, so the finish assembles // more than one staged piece. let total = 8 * 1024 * 1024 + 100; let mut bytes = Vec::with_capacity(total); for i in 0..total { bytes.push((i % 251) as u8); } let answer = app .post_json( "/api/upload/start", Some(&cookie), serde_json::json!({"folder_id": null, "name": "big.bin", "size_bytes": total}), ) .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); let started = answer.json(); let session = started["ok"]["id"] .as_str() .expect("start was refused") .to_string(); assert_eq!(started["ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024)); let answer = app .put_bytes( &format!("/api/upload/{session}/0"), Some(&cookie), &bytes[..8 * 1024 * 1024], ) .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); assert_eq!( answer.json()["ok"]["received_bytes"].as_u64(), Some(8 * 1024 * 1024) ); let answer = app .put_bytes( &format!("/api/upload/{session}/1"), Some(&cookie), &bytes[8 * 1024 * 1024..], ) .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); assert_eq!( answer.json()["ok"]["received_bytes"].as_u64(), Some(total as u64) ); let answer = app .post_json( &format!("/api/upload/{session}/finish"), Some(&cookie), serde_json::json!({}), ) .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); let file_id = answer.json()["ok"] .as_str() .expect("finish was refused") .to_string(); let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await; assert_eq!(got.status, StatusCode::OK); assert_eq!(got.bytes, bytes); let row = app.store.file(&file_id).await.unwrap().unwrap(); assert_eq!(row.owner_id, user.id); } #[tokio::test] async fn an_interrupted_upload_resumes_from_its_staged_chunks() { let app = TestApp::build().await; let cookie = app.sign_in("sub-resume", "resume@in.test", "Resume").await; // Two chunks: stage the first, ask the status what a resume may skip, // then land the second and finish. let total = 8 * 1024 * 1024 + 100; let mut bytes = Vec::with_capacity(total); for i in 0..total { bytes.push((i % 251) as u8); } let answer = app .post_json( "/api/upload/start", Some(&cookie), serde_json::json!({"folder_id": null, "name": "resume.bin", "size_bytes": total}), ) .await; let session = answer.json()["ok"]["id"] .as_str() .expect("start was refused") .to_string(); app.put_bytes( &format!("/api/upload/{session}/0"), Some(&cookie), &bytes[..8 * 1024 * 1024], ) .await; let status = app .get(&format!("/api/upload/{session}"), Some(&cookie)) .await; assert_eq!(status.status, StatusCode::OK, "{}", status.text()); let body = status.json(); assert_eq!(body["ok"]["size_bytes"].as_u64(), Some(total as u64)); assert_eq!(body["ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024)); assert_eq!(body["ok"]["name"].as_str(), Some("resume.bin")); assert_eq!(body["ok"]["uploaded"], serde_json::json!([0])); // Another owner's probe of the same id is not found, not forbidden. let other = app.sign_in("sub-nosey", "nosey@in.test", "Nosey").await; let status = app .get(&format!("/api/upload/{session}"), Some(&other)) .await; assert_eq!(status.json()["err"].as_str(), Some("NotFound")); app.put_bytes( &format!("/api/upload/{session}/1"), Some(&cookie), &bytes[8 * 1024 * 1024..], ) .await; let answer = app .post_json( &format!("/api/upload/{session}/finish"), Some(&cookie), serde_json::json!({}), ) .await; let file_id = answer.json()["ok"] .as_str() .expect("finish was refused") .to_string(); let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await; assert_eq!(got.bytes, bytes); } #[tokio::test] async fn range_request_serves_a_slice() { let app = TestApp::build().await; let cookie = app.sign_in("sub-range", "range@in.test", "Range").await; let user = app .store .user_by_oidc_sub("sub-range") .await .unwrap() .unwrap(); let bytes = b"hello in"; app.post_multipart( "/files", Some(&cookie), &[("folder_id", "")], &[("hello.txt", "text/plain", bytes)], ) .await; let file = app .store .list_children(&user.id, None) .await .unwrap() .files .into_iter() .next() .unwrap(); let slice = app .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=0-4") .await; assert_eq!(slice.status, StatusCode::PARTIAL_CONTENT); assert_eq!(slice.bytes, b"hello"); assert_eq!(slice.content_range.as_deref(), Some("bytes 0-4/8")); let past_end = app .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=99-") .await; assert_eq!(past_end.status, StatusCode::RANGE_NOT_SATISFIABLE); } #[tokio::test] async fn quota_is_refused_before_and_during_upload() { let app = TestApp::build().await; let cookie = app.sign_in("sub-quota", "quota@in.test", "Quota").await; let user = app .store .user_by_oidc_sub("sub-quota") .await .unwrap() .unwrap(); app.store.set_user_quota(&user.id, 10).await.unwrap(); let answer = app .post_json( "/api/upload/start", Some(&cookie), serde_json::json!({"folder_id": null, "name": "too-big.bin", "size_bytes": 100}), ) .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); assert_eq!( answer.json()["err"].as_str(), Some("QuotaExceeded"), "start was not refused: {}", answer.body ); let answer = app .post_multipart( "/files", Some(&cookie), &[("folder_id", "")], &[("twenty.txt", "text/plain", b"12345678901234567890")], ) .await; assert_eq!(answer.status, StatusCode::SEE_OTHER); let location = answer.location.unwrap_or_default(); assert!( location.contains("quota-exceeded"), "small upload was not refused: {location}" ); } #[tokio::test] async fn thumbnail_is_served_after_image_upload() { let app = TestApp::build().await; let cookie = app.sign_in("sub-thumb", "thumb@in.test", "Thumb").await; let user = app .store .user_by_oidc_sub("sub-thumb") .await .unwrap() .unwrap(); let png = tiny_png(); let answer = app .post_multipart( "/files", Some(&cookie), &[("folder_id", "")], &[("dot.png", "image/png", &png)], ) .await; assert!( !answer .location .as_deref() .unwrap_or("") .contains("refusal="), "image upload was refused: {}", answer.location.unwrap_or_default() ); let file = app .store .list_children(&user.id, None) .await .unwrap() .files .into_iter() .find(|file| file.name == "dot.png") .expect("image was not stored"); assert_eq!(file.mime, "image/png"); let thumb = app.get(&format!("/thumb/{}", file.id), Some(&cookie)).await; assert_eq!(thumb.status, StatusCode::OK, "no thumbnail served"); assert_eq!(thumb.content_type.as_deref(), Some("image/webp")); assert_eq!(&thumb.bytes[0..4], b"RIFF"); assert_eq!(&thumb.bytes[8..12], b"WEBP"); let etag = thumb.etag.clone().expect("no etag on the thumbnail"); let cached = app .get_with_if_none_match(&format!("/thumb/{}", file.id), Some(&cookie), &etag) .await; assert_eq!(cached.status, StatusCode::NOT_MODIFIED); } #[tokio::test] async fn cross_owner_answers_not_found() { let app = TestApp::build().await; let alice = app.sign_in("sub-alice", "alice@in.test", "Alice").await; let alice_user = app .store .user_by_oidc_sub("sub-alice") .await .unwrap() .unwrap(); let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; app.post( "/api/folder/create", Some(&alice), &[("parent_id", ""), ("name", "hers")], ) .await; let hers = folder_id(&app, &alice_user.id, None, "hers").await; app.post_multipart( "/files", Some(&alice), &[("folder_id", "")], &[("hers.txt", "text/plain", b"hers")], ) .await; let file = app .store .list_children(&alice_user.id, None) .await .unwrap() .files .into_iter() .next() .unwrap(); let bytes = app.get(&format!("/file/{}", file.id), Some(&bob)).await; assert_eq!(bytes.status, StatusCode::NOT_FOUND); let thumb = app.get(&format!("/thumb/{}", file.id), Some(&bob)).await; assert_eq!(thumb.status, StatusCode::NOT_FOUND); let page = app.get(&format!("/drive?folder={hers}"), Some(&bob)).await; assert_eq!(page.status, StatusCode::NOT_FOUND); let answer = app .post( "/api/folder/rename", Some(&bob), &[("id", &hers), ("name", "theirs")], ) .await; assert!( answer.body.contains("NotFound"), "cross-owner write was not refused as not-found: {}", answer.body ); let answer = app .post("/api/file/delete", Some(&bob), &[("id", &file.id)]) .await; assert!( answer.body.contains("NotFound"), "cross-owner delete was not refused as not-found: {}", answer.body ); } #[tokio::test] async fn file_rename_move_and_delete() { let app = TestApp::build().await; let cookie = app.sign_in("sub-fops", "fops@in.test", "Fops").await; let user = app .store .user_by_oidc_sub("sub-fops") .await .unwrap() .unwrap(); app.post( "/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "box")], ) .await; let boxed = folder_id(&app, &user.id, None, "box").await; app.post_multipart( "/files", Some(&cookie), &[("folder_id", "")], &[("note.txt", "text/plain", b"note")], ) .await; let file = app .store .list_children(&user.id, None) .await .unwrap() .files .into_iter() .next() .unwrap(); let answer = app .post( "/api/file/rename", Some(&cookie), &[("id", &file.id), ("name", "renamed.txt")], ) .await; assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body); let answer = app .post( "/api/file/move", Some(&cookie), &[("id", &file.id), ("folder_id", &boxed)], ) .await; assert_eq!(answer.body, "null", "moving was refused: {}", answer.body); let moved = app.store.file(&file.id).await.unwrap().unwrap(); assert_eq!(moved.name, "renamed.txt"); assert_eq!(moved.folder_id.as_deref(), Some(boxed.as_str())); let answer = app .post("/api/file/delete", Some(&cookie), &[("id", &file.id)]) .await; assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body); let trashed = app.store.file(&file.id).await.unwrap().unwrap(); assert!( trashed.deleted_at.is_some(), "delete did not trash the file" ); // Trashed bytes still serve the owner's preview inline — only the // taking is dead until the row is restored. let preview = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; assert_eq!(preview.status, StatusCode::OK); let forced = app .get(&format!("/file/{}?dl=1", file.id), Some(&cookie)) .await; assert_eq!(forced.status, StatusCode::NOT_FOUND); } /// A trashed file previews for its owner: the trash's row opens the /// viewer, the back link names the trash, the bytes serve inline while /// `?dl=1` stays dead — and a stranger, grant or no grant, sees nothing. #[tokio::test] async fn trashed_file_previews_for_its_owner() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "gone.png", b"\x89PNG\r\n\x1a\n gone").await; let answer = app .post("/api/file/delete", Some(&admin), &[("id", &file)]) .await; assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body); // The trash's file row opens the preview; the folder rows beside it // stay facts. let shelf = app.get("/trash", Some(&admin)).await; assert_eq!(shelf.status, StatusCode::OK, "{}", shelf.text()); assert!( shelf.text().contains(&format!("/view/{file}")), "{}", shelf.text() ); // The viewer names the trash as the way back and shows the media, // but offers no download for a trashed row. let page = app.get(&format!("/view/{file}"), Some(&admin)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("Back to trash"), "{}", page.text()); assert!(page.text().contains("viewer-media"), "{}", page.text()); assert!(!page.text().contains("?dl=1"), "{}", page.text()); // Inline bytes serve the owner's preview, taking stays dead, and a // stranger sees the same nothing a missing id would show. let inline = app.get(&format!("/file/{file}"), Some(&admin)).await; assert_eq!(inline.status, StatusCode::OK, "{}", inline.text()); let forced = app.get(&format!("/file/{file}?dl=1"), Some(&admin)).await; assert_eq!(forced.status, StatusCode::NOT_FOUND); let stranger = app.get(&format!("/view/{file}"), Some(&bob)).await; assert_eq!(stranger.status, StatusCode::NOT_FOUND); } #[tokio::test] async fn upload_abort_and_bad_chunk() { let app = TestApp::build().await; let cookie = app.sign_in("sub-abort", "abort@in.test", "Abort").await; let answer = app .post_json( "/api/upload/start", Some(&cookie), serde_json::json!({"folder_id": null, "name": "never.bin", "size_bytes": 100}), ) .await; let session = answer.json()["ok"]["id"].as_str().unwrap().to_string(); // A short piece is a bad chunk, not a short file. let answer = app .put_bytes(&format!("/api/upload/{session}/0"), Some(&cookie), b"short") .await; assert_eq!( answer.json()["err"].as_str(), Some("BadChunk"), "short chunk was not refused: {}", answer.body ); let answer = app .post_json( &format!("/api/upload/{session}/abort"), Some(&cookie), serde_json::json!({}), ) .await; assert_eq!( answer.json()["ok"], serde_json::Value::Null, "{}", answer.body ); // The finish after the abort finds an expired session, with the chunks // still staged for nothing. let answer = app .post_json( &format!("/api/upload/{session}/finish"), Some(&cookie), serde_json::json!({}), ) .await; assert_eq!( answer.json()["err"].as_str(), Some("UploadExpired"), "finish after abort was not refused: {}", answer.body ); } #[tokio::test] async fn forced_download_is_attachment() { let app = TestApp::build().await; let cookie = app.sign_in("sub-dl", "dl@in.test", "Dl").await; let user = app.store.user_by_oidc_sub("sub-dl").await.unwrap().unwrap(); app.post_multipart( "/files", Some(&cookie), &[("folder_id", "")], &[("readme.txt", "text/plain", b"read me")], ) .await; let file = app .store .list_children(&user.id, None) .await .unwrap() .files .into_iter() .next() .unwrap(); let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; assert!( inline .disposition .as_deref() .unwrap_or("") .starts_with("inline"), "text should render inline: {:?}", inline.disposition ); let forced = app .get(&format!("/file/{}?dl=1", file.id), Some(&cookie)) .await; assert_eq!(forced.status, StatusCode::OK); assert!( forced .disposition .as_deref() .unwrap_or("") .starts_with("attachment"), "?dl=1 did not force attachment: {:?}", forced.disposition ); assert_eq!(forced.bytes, b"read me"); } /// Looking is not downloading: the viewer's inline serves — the plain GET /// and a media element's range probe from byte 0 — never move the counter; /// only the `?dl=1` disposition does, once per download. #[tokio::test] async fn previews_do_not_count_as_downloads() { let app = TestApp::build().await; let cookie = app.sign_in("sub-prev", "prev@in.test", "Prev").await; let user = app .store .user_by_oidc_sub("sub-prev") .await .unwrap() .unwrap(); app.post_multipart( "/files", Some(&cookie), &[("folder_id", "")], &[("clip.txt", "text/plain", b"counted only when taken")], ) .await; let file = app .store .list_children(&user.id, None) .await .unwrap() .files .into_iter() .next() .unwrap(); let count = || async { app.store .file(&file.id) .await .unwrap() .unwrap() .download_count }; let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; assert_eq!(inline.status, StatusCode::OK); let probe = app .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=0-3") .await; assert_eq!(probe.status, StatusCode::PARTIAL_CONTENT); assert_eq!( count().await, 0, "previews counted: inline and range serves" ); let taken = app .get(&format!("/file/{}?dl=1", file.id), Some(&cookie)) .await; assert_eq!(taken.status, StatusCode::OK); assert_eq!(count().await, 1, "a forced download did not count"); // A mid-file chunk of a download is the same download going on. let resumed = app .get_with_range( &format!("/file/{}?dl=1", file.id), Some(&cookie), "bytes=4-", ) .await; assert_eq!(resumed.status, StatusCode::PARTIAL_CONTENT); assert_eq!(count().await, 1, "a resumed chunk counted again"); } // -- public links (merged from http_d2.rs; one binary per crate) ------------ #[tokio::test] async fn link_create_public_view_revoke_gone() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "notes.txt", b"hello in").await; let answer = app .post( "/api/share/link/create", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("can_download", "1"), ], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let token = created_token(answer.location.as_deref().unwrap()); // Public: no cookie, the card renders. let page = app.get(&format!("/s/{token}"), None).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("notes.txt"), "{}", page.text()); // Public download carries the bytes. let bytes = app.get(&format!("/s/{token}?dl=1"), None).await; assert_eq!(bytes.status, StatusCode::OK); assert_eq!(bytes.bytes, b"hello in"); // Revoke: only the id travels; look it up straight off the store. let id = app.store.share_links(&owner).await.unwrap()[0].id.clone(); let answer = app .post("/api/share/link/revoke", Some(&admin), &[("id", &id)]) .await; assert!(answer.accepted(), "revoke refused: {:?}", answer.location); let gone = app.get(&format!("/s/{token}"), None).await; assert_eq!(gone.status, StatusCode::OK); assert!( gone.text().contains("no longer works"), "revoked link showed: {}", gone.text() ); } #[tokio::test] async fn expired_link_is_dead() { let app = TestApp::build().await; let _ = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "old.txt", b"old").await; let past = time::OffsetDateTime::now_utc() - time::Duration::days(1); let created = app .store .create_share_link(&owner, ShareKind::File, &file, true, Some(past), None) .await .unwrap(); let page = app.get(&format!("/s/{}", created.token), None).await; assert_eq!(page.status, StatusCode::OK); assert!( page.text().contains("no longer works"), "expired link showed: {}", page.text() ); } #[tokio::test] async fn view_only_link_download_is_dead_card() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "secret.txt", b"eyes only").await; let answer = app .post( "/api/share/link/create", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("can_download", "0"), ], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let token = created_token(answer.location.as_deref().unwrap()); let page = app.get(&format!("/s/{token}"), None).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("secret.txt"), "{}", page.text()); let blocked = app.get(&format!("/s/{token}?dl=1"), None).await; assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text()); assert!( blocked.text().contains("no longer works"), "view-only download showed: {}", blocked.text() ); } /// A tiny VP9+AAC Matroska, made by the system `ffmpeg` the way the /// thumbnailer drives it: a test pattern and a tone, half a second. Small, /// but exactly the file a browser refuses to play as a webm — VP9 video /// with AAC audio. `None` skips the tests where ffmpeg is not installed. fn vp9_aac_matroska() -> Option> { if !in_core::thumbs::ffmpeg_available() { eprintln!("skipping matroska preview tests: no ffmpeg on PATH"); return None; } let dir = std::env::temp_dir().join(format!("in-mkv-{}", Ulid::generate())); std::fs::create_dir_all(&dir).unwrap(); let out = dir.join("clip.mkv"); let status = Command::new("ffmpeg") .args([ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=duration=0.5:size=128x96:rate=10", "-f", "lavfi", "-i", "sine=frequency=440:duration=0.5", "-c:v", "libvpx-vp9", "-c:a", "aac", ]) .arg(&out) .status() .ok()?; let bytes = if status.success() { std::fs::read(&out).ok() } else { None }; let _ = std::fs::remove_dir_all(&dir); bytes } /// A VP9+AAC mkv is stored under its honest Matroska name, the inline media /// route serves the stored bytes as they sit under that mime, and `?dl=1` /// still hands over the original, byte for byte. #[tokio::test] async fn a_webm_illegal_matroska_serves_original_bytes_inline_and_on_download() { let Some(mkv) = vp9_aac_matroska() else { return; }; let app = TestApp::build().await; let cookie = app .sign_in("sub-matroska", "matroska@in.test", "Matroska") .await; let user = app .store .user_by_oidc_sub("sub-matroska") .await .unwrap() .unwrap(); app.post_multipart( "/files", Some(&cookie), &[("folder_id", "")], &[("clip.mkv", "video/x-matroska", &mkv)], ) .await; let file = app .store .list_children(&user.id, None) .await .unwrap() .files .into_iter() .next() .unwrap(); // The sniffer no longer calls these tracks a webm. let stored = app.store.file(&file.id).await.unwrap().unwrap(); assert_eq!(stored.mime, "video/x-matroska"); // The inline serve is the stored bytes under the honest sniffed mime — // no derivative stands in, whatever the browser makes of the tracks. let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; assert_eq!(inline.status, StatusCode::OK); assert_eq!(inline.content_type.as_deref(), Some("video/x-matroska")); assert_eq!(inline.bytes, mkv, "the inline serve was not the original"); // The download is the original too, byte for byte. let taken = app .get(&format!("/file/{}?dl=1", file.id), Some(&cookie)) .await; assert_eq!(taken.status, StatusCode::OK); assert_eq!(taken.bytes, mkv); assert_eq!(taken.bytes.len(), mkv.len()); assert_eq!(taken.content_type.as_deref(), Some("video/x-matroska")); assert!( taken .disposition .as_deref() .unwrap_or("") .starts_with("attachment") ); } /// A view-only public link previews the stored bytes — that is what the /// media stream is for — and still cannot be downloaded: `?dl=1` stays the /// dead card. #[tokio::test] async fn view_only_link_previews_a_matroska_but_cannot_download() { let Some(mkv) = vp9_aac_matroska() else { return; }; let app = TestApp::build().await; let owner = owner_of(&app, "sub-admin").await; let file = app .store .insert_file(&owner, None, "clip.mkv", &mkv) .await .unwrap() .id; let created = app .store .create_share_link(&owner, ShareKind::File, &file, false, None, None) .await .unwrap(); let media = app .get(&format!("/s/{}?media=1", created.token), None) .await; assert_eq!(media.status, StatusCode::OK); assert_eq!(media.content_type.as_deref(), Some("video/x-matroska")); assert_eq!(media.bytes, mkv, "the media stream was not the original"); let blocked = app.get(&format!("/s/{}?dl=1", created.token), None).await; assert!( blocked.text().contains("no longer works"), "view-only download showed: {}", blocked.text() ); } /// A password-protected link gates everything — card, download bytes — /// until the browser answers the gate once; the proof then lives in the /// link's own cookie. A wrong password answers the gate with the error and /// mints no cookie, a revoked link dead-ends even an unlocked browser, and /// none of the gate pages ever name the file. #[tokio::test] async fn password_link_gates_until_unlocked() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "private.txt", b"behind the gate").await; let answer = app .post( "/api/share/link/create", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("can_download", "1"), ("password", "open sesame"), ], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let token = created_token(answer.location.as_deref().unwrap()); let link = &app.store.share_links(&owner).await.unwrap()[0]; assert!(link.password_hash.is_some()); // The gate: no cookie, no name, no bytes — on the card and on `?dl=1` // both. let gate = app.get(&format!("/s/{token}"), None).await; assert_eq!(gate.status, StatusCode::OK, "{}", gate.text()); assert!( !gate.text().contains("private.txt"), "gate leaked the file name: {}", gate.text() ); assert!(gate.text().contains("type=\"password\""), "{}", gate.text()); let gated_bytes = app.get(&format!("/s/{token}?dl=1"), None).await; assert_eq!(gated_bytes.status, StatusCode::OK); assert!( !gated_bytes.text().contains("behind the gate"), "gate leaked the bytes: {}", gated_bytes.text() ); // A wrong password: back to the gate with the error on the query, and // no cookie minted. let wrong = app .post(&format!("/s/{token}"), None, &[("password", "wrong one")]) .await; assert_eq!(wrong.status, StatusCode::SEE_OTHER); assert_eq!( wrong.location.as_deref(), Some(&format!("/s/{token}?wrong=1")[..]) ); assert!( wrong.set_cookie.is_none(), "a wrong password minted a cookie: {:?}", wrong.set_cookie ); let wrong_gate = app.get(&format!("/s/{token}?wrong=1"), None).await; assert_eq!(wrong_gate.status, StatusCode::OK); assert!( wrong_gate.text().contains("Wrong password."), "the gate did not say what went wrong: {}", wrong_gate.text() ); // The right password: a 303 back to the page, carrying the proof cookie // named for the link, scoped to /s, not marked Secure on a plain-http // rehearsal. let right = app .post(&format!("/s/{token}"), None, &[("password", "open sesame")]) .await; assert_eq!(right.status, StatusCode::SEE_OTHER); assert_eq!( right.location.as_deref(), Some(format!("/s/{token}").as_str()) ); let proof = in_core::link_unlock_proof(&token, link.password_hash.as_deref().unwrap()); let cookie_pair = format!("in_link_{}={proof}", link.id); let set_cookie = right.set_cookie.as_deref().expect("unlock set no cookie"); assert!( set_cookie.contains(&cookie_pair), "cookie did not carry the proof: {set_cookie}" ); assert!(set_cookie.contains("Path=/s"), "{set_cookie}"); assert!(set_cookie.contains("HttpOnly"), "{set_cookie}"); assert!(set_cookie.contains("SameSite=Lax"), "{set_cookie}"); assert!(!set_cookie.contains("Secure"), "{set_cookie}"); // The unlocked browser sees the card, and the download serves bytes. let unlocked = app.get(&format!("/s/{token}"), Some(&cookie_pair)).await; assert_eq!(unlocked.status, StatusCode::OK, "{}", unlocked.text()); assert!( unlocked.text().contains("private.txt"), "unlocked card showed nothing: {}", unlocked.text() ); let served = app .get(&format!("/s/{token}?dl=1"), Some(&cookie_pair)) .await; assert_eq!(served.bytes, b"behind the gate"); // Revocation dead-ends even the unlocked browser. let id = link.id.clone(); let answer = app .post("/api/share/link/revoke", Some(&admin), &[("id", &id)]) .await; assert!(answer.accepted(), "revoke refused: {:?}", answer.location); let gone = app.get(&format!("/s/{token}"), Some(&cookie_pair)).await; assert_eq!(gone.status, StatusCode::OK); assert!( gone.text().contains("no longer works"), "revoked link showed: {}", gone.text() ); } /// An unchecked `can_download` box posts nothing at all, and nothing posted /// must never mint a download: the absent flag reads view-only, the way an /// explicitly refused one does — while the checked box still opens the bytes. #[tokio::test] async fn link_create_without_the_flag_is_view_only() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "plain.txt", b"plain bytes").await; // No can_download pair — what an unchecked checkbox posts. let answer = app .post( "/api/share/link/create", Some(&admin), &[("kind", "file"), ("target_id", &file)], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let token = created_token(answer.location.as_deref().unwrap()); let page = app.get(&format!("/s/{token}"), None).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("plain.txt"), "{}", page.text()); let blocked = app.get(&format!("/s/{token}?dl=1"), None).await; assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text()); assert!( blocked.text().contains("no longer works"), "absent-flag download showed: {}", blocked.text() ); // Both share surfaces print the target's name, never its raw id. let named = app .get(&format!("/drive?share=file:{file}"), Some(&admin)) .await; assert_eq!(named.status, StatusCode::OK, "{}", named.text()); assert!( named.text().contains("plain.txt") && named.text().contains("modal-scrim"), "share modal showed no name: {}", named.text() ); let settings = app.get("/settings?section=links", Some(&admin)).await; assert_eq!(settings.status, StatusCode::OK, "{}", settings.text()); assert!( settings.text().contains("plain.txt"), "settings panel showed no name: {}", settings.text() ); // The checked box still opens the bytes. let answer = app .post( "/api/share/link/create", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("can_download", "1"), ], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let token = created_token(answer.location.as_deref().unwrap()); let bytes = app.get(&format!("/s/{token}?dl=1"), None).await; assert_eq!(bytes.status, StatusCode::OK); assert_eq!(bytes.bytes, b"plain bytes"); } #[tokio::test] async fn folder_link_lists_and_serves_children() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let folder = app .store .create_folder(&owner, None, "shared") .await .unwrap(); app.store .insert_file(&owner, Some(&folder.id), "child.txt", b"child bytes") .await .unwrap(); let answer = app .post( "/api/share/link/create", Some(&admin), &[ ("kind", "folder"), ("target_id", &folder.id), ("can_download", "1"), ], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let token = created_token(answer.location.as_deref().unwrap()); let page = app.get(&format!("/s/{token}"), None).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("child.txt"), "{}", page.text()); let child = app .store .list_children(&owner, Some(&folder.id)) .await .unwrap() .files[0] .id .clone(); let bytes = app .get( &format!("/s/{token}?folder={}&file={child}&dl=1", folder.id), None, ) .await; assert_eq!(bytes.status, StatusCode::OK, "{}", bytes.text()); assert_eq!(bytes.bytes, b"child bytes"); } #[tokio::test] async fn cross_owner_link_create_is_not_found() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let _ = app.sign_in("sub-bob", "bob@in.test", "Bob").await; let bob = owner_of(&app, "sub-bob").await; let file = file_id(&app, &bob, "bobs.txt", b"bob").await; // Ada names Bob's file: answered as not-found, never forbidden. let answer = app .post( "/api/share/link/create", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("can_download", "1"), ], ) .await; assert!( answer.refused("not-found", "create"), "{:?}", answer.location ); } // -- per-user shares -------------------------------------------------------- #[tokio::test] async fn per_user_share_lands_in_shared_with_me() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; let cara = app.sign_in("sub-cara", "cara@in.test", "Cara").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "joint.txt", b"joint").await; let answer = app .post( "/api/share/user/add", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("email", "BOB@in.test"), ("can_download", "1"), ], ) .await; assert!(answer.accepted(), "add refused: {:?}", answer.location); let bobs = app.get("/shared", Some(&bob)).await; assert_eq!(bobs.status, StatusCode::OK, "{}", bobs.text()); assert!(bobs.text().contains("joint.txt"), "{}", bobs.text()); // The row opens the viewer marked with its origin, so the back link // can name the shared page. assert!( bobs.text().contains(&format!("/view/{file}?from=shared")), "{}", bobs.text() ); let caras = app.get("/shared", Some(&cara)).await; assert_eq!(caras.status, StatusCode::OK, "{}", caras.text()); assert!(!caras.text().contains("joint.txt"), "{}", caras.text()); // Unknown addresses are not-found, not a stack. let answer = app .post( "/api/share/user/add", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("email", "ghost@in.test"), ("can_download", "1"), ], ) .await; assert!(answer.refused("not-found", "add"), "{:?}", answer.location); // Unshare and it leaves Bob's page. let answer = app .post( "/api/share/user/remove", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("email", "bob@in.test"), ], ) .await; assert!(answer.accepted(), "remove refused: {:?}", answer.location); let bobs = app.get("/shared", Some(&bob)).await; assert!(!bobs.text().contains("joint.txt"), "{}", bobs.text()); } /// The share modal picks people from im's directory: a member who has /// never signed in here is offered — the render itself mirrors her into a /// local row — the owner is not, and granting the picked address lands her /// under Who has access. #[tokio::test] async fn share_modal_offers_the_im_directory() { let app = TestApp::build().await; app.fake.set_directory(&[ serde_json::json!({"sub": "sub-ember", "email": "ember@in.test", "name": "Ember", "admin": false}), serde_json::json!({"sub": "sub-bora", "email": "bora@in.test", "name": "Bora", "admin": false}), // The owner as im knows her: never offered to share with herself. serde_json::json!({"sub": "sub-admin", "email": "ada@in.test", "name": "Ada", "admin": true}), // Valid in im but disabled here: sharing with her is sharing with // nobody, so the picker never offers her. serde_json::json!({"sub": "sub-gonca", "email": "gonca@in.test", "name": "Gonca", "admin": false}), ]); let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; app.sign_in("sub-gonca", "gonca@in.test", "Gonca").await; let gonca = app .store .user_by_email("gonca@in.test") .await .unwrap() .unwrap(); app.store.set_user_disabled(&gonca.id, true).await.unwrap(); let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "pick.txt", b"pick").await; let page = app .get(&format!("/drive?share=file:{file}"), Some(&admin)) .await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let text = page.text(); assert!( text.contains("
{url}

")), "no full url in the modal: {text}" ); assert!( text.contains("class=\"quiet share-copy\""), "no copy button in the modal: {text}" ); assert!( !text.contains("/s/…"), "masked value on a re-visible link: {text}" ); // The settings panel's row carries the same. let page = app.get("/settings?section=links", Some(&ada)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let text = page.text(); assert!( text.contains(&format!("\">{url}

")), "no full url in settings: {text}" ); assert!( text.contains("class=\"quiet share-copy\""), "no copy button in settings: {text}" ); assert!( text.contains("__inShareCopy"), "no copy script on the links panel: {text}" ); } /// Revoking deletes the sealed row too — it is part of the revoke, so a /// mint-and-revoke round trip leaves no orphan setting behind. #[tokio::test] async fn revoke_deletes_the_sealed_token_row() { let app = TestApp::build().await; let ada = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "sealed.txt", b"sealed").await; for round in 0..2 { let answer = app .post( "/api/share/link/create", Some(&ada), &[("kind", "file"), ("target_id", &file)], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let id = app.store.share_links(&owner).await.unwrap()[0].id.clone(); let key = format!("share_token:{id}"); assert!( app.store.get_setting(&key).await.unwrap().is_some(), "no sealed row after mint {round}" ); let answer = app .post("/api/share/link/revoke", Some(&ada), &[("id", &id)]) .await; assert!(answer.accepted(), "revoke refused: {:?}", answer.location); assert!( app.store.get_setting(&key).await.unwrap().is_none(), "sealed row survived the revoke {round}" ); } } /// A link minted before the sealing has no row to open: the modal and the /// settings panel state the carry-forward fact and offer the one-click /// mint — no masked value, nothing that reads as an address. #[tokio::test] async fn legacy_link_states_the_carry_forward_note_and_offers_the_mint() { let app = TestApp::build().await; let ada = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "legacy.txt", b"legacy").await; // Minted through the store alone, as the pre-sealing code did it: no // setting row ever comes to be. app.store .create_share_link(&owner, ShareKind::File, &file, false, None, None) .await .unwrap(); let page = app .get(&format!("/drive?share=file:{file}"), Some(&ada)) .await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let text = page.text(); assert!( !text.contains("/s/…"), "masked value on a legacy link: {text}" ); assert!( text.contains("action=\"/api/share/link/remint\""), "no mint action on a legacy link: {text}" ); assert!(text.contains("Mint a new link"), "no mint button: {text}"); assert!( text.contains("predates re-viewable addresses"), "no carry-forward note: {text}" ); assert!( !text.contains("class=\"quiet share-copy\""), "copy button on a link with no re-derivable address: {text}" ); let page = app.get("/settings?section=links", Some(&ada)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let text = page.text(); assert!( !text.contains("/s/…"), "masked value on a legacy link: {text}" ); assert!( text.contains("action=\"/api/share/link/remint\""), "no mint action on a legacy link: {text}" ); assert!( text.contains("predates re-viewable addresses"), "no carry-forward note: {text}" ); assert!( !text.contains("class=\"quiet share-copy\""), "copy button on a link with no re-derivable address: {text}" ); } /// Reminting carries a legacy link forward: the fresh token opens the same /// target with the carried rights, the old token is dead, the old row and /// its seal are gone, and the settings panel shows the new full address /// with its copy button. #[tokio::test] async fn remint_carries_a_legacy_link_forward() { let app = TestApp::build().await; let ada = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "carried.txt", b"carried").await; let answer = app .post( "/api/share/link/create", Some(&ada), &[ ("kind", "file"), ("target_id", &file), ("can_download", "1"), ("expires_in_days", "30"), ], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let old_token = created_token(answer.location.as_deref().unwrap()); let old_id = app.store.share_links(&owner).await.unwrap()[0].id.clone(); // Lose the seal: the address is unrecoverable, the link reads legacy. app.store .delete_setting(&format!("share_token:{old_id}")) .await .unwrap(); let answer = app .post("/api/share/link/remint", Some(&ada), &[("id", &old_id)]) .await; assert_eq!( answer.status, StatusCode::SEE_OTHER, "{:?}", answer.location ); let location = answer.location.as_deref().expect("remint set no location"); let new_token = created_token(location); assert!(!new_token.is_empty(), "remint minted no token: {location}"); // The fresh token opens the same file; the old one is dead. let card = app.get(&format!("/s/{new_token}"), None).await; assert_eq!(card.status, StatusCode::OK, "{}", card.text()); assert!( card.text().contains("carried.txt"), "the fresh token did not open the file: {}", card.text() ); let dead = app.get(&format!("/s/{old_token}"), None).await; assert!( dead.text().contains("no longer works"), "the old token still opens: {}", dead.text() ); // The old row died with its seal; the carried rights ride the new row. let links = app.store.share_links(&owner).await.unwrap(); assert_ne!(links[0].id, old_id, "the old row survived the remint"); assert!(links[0].can_download, "remint dropped the download right"); assert!(links[0].expires_at.is_some(), "remint dropped the expiry"); assert!( app.store .get_setting(&format!("share_token:{}", links[0].id)) .await .unwrap() .is_some(), "the fresh token came unsealed" ); assert!( app.store .get_setting(&format!("share_token:{old_id}")) .await .unwrap() .is_none(), "the old seal survived the remint" ); // The settings panel shows the new full address with its copy button — // no masked placeholder, no legacy row left to carry forward. let page = app .get( &format!("/settings?section=links&created={new_token}"), Some(&ada), ) .await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let text = page.text(); assert!( text.contains(&format!("\">http://127.0.0.1:7655/s/{new_token}

")), "no full new url row in settings: {text}" ); assert!( text.contains("class=\"quiet share-copy\""), "no copy button in settings: {text}" ); assert!(!text.contains("/s/…"), "masked value after remint: {text}"); assert!( !text.contains("predates re-viewable addresses"), "a legacy row survived the remint: {text}" ); } /// Live public links and grants to other people mark their drive rows with /// the Shared chip; unmarked siblings carry nothing, and no row carries two. #[tokio::test] async fn drive_marks_shared_rows() { let app = TestApp::build().await; let ada = app.sign_in("sub-admin", "ada@in.test", "Ada").await; app.sign_in("sub-ember", "ember@in.test", "Ember").await; let owner = owner_of(&app, "sub-admin").await; let linked = file_id(&app, &owner, "linked.txt", b"linked").await; let _plain = file_id(&app, &owner, "plain.txt", b"plain").await; let granted = file_id(&app, &owner, "granted.txt", b"granted").await; let answer = app .post( "/api/folder/create", Some(&ada), &[("parent_id", ""), ("name", "Dossier")], ) .await; assert!( answer.accepted(), "folder create refused: {:?}", answer.location ); let folder = folder_id(&app, &owner, None, "Dossier").await; // A live public link onto the file, another onto the folder. for (kind, target) in [("file", linked.as_str()), ("folder", folder.as_str())] { let answer = app .post( "/api/share/link/create", Some(&ada), &[("kind", kind), ("target_id", target)], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); } // A grant onto the third file. let ember = app .store .user_by_email("ember@in.test") .await .unwrap() .unwrap(); app.store .add_share_user(&owner, ShareKind::File, &granted, &ember.id, true) .await .unwrap(); let page = app.get("/drive", Some(&ada)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let text = page.text(); let chips = text.matches("chip chip-shared").count(); assert_eq!(chips, 3, "expected three marked rows: {text}"); assert!( text.contains("Shared"), "chip markup changed: {text}" ); // The unshared sibling is on the page, but its row carries no mark. assert!(text.contains("plain.txt"), "sibling missing: {text}"); let plain_row = text .split("
") .find(|row| row.contains("plain.txt")) .expect("no drive row for the unshared sibling"); assert!( !plain_row.contains("chip-shared"), "unshared sibling marked: {plain_row}" ); } /// View only means preview, no download: the reader sees the media inline /// on the viewer page and reads the inline bytes, while `?dl=1` stays dead /// and the page never offers the Download link. #[tokio::test] async fn view_only_reader_previews_media_but_cannot_download() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id( &app, &owner, "photo.png", b"\x89PNG\r\n\x1a\n preview bytes", ) .await; let answer = app .post( "/api/share/user/add", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("email", "bob@in.test"), ("can_download", "0"), ], ) .await; assert!(answer.accepted(), "add refused: {:?}", answer.location); // The viewer page renders the media, not the unavailable note, and // offers no download. let page = app.get(&format!("/view/{file}"), Some(&bob)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("viewer-media"), "{}", page.text()); assert!(!page.text().contains("No preview"), "{}", page.text()); assert!(!page.text().contains("?dl=1"), "{}", page.text()); // The chrome names the grant honestly — viewing in the browser, // anything viewable savable — and the retired "no downloads" claim // is gone. assert!( page.text().contains("anything viewable can be saved"), "{}", page.text() ); assert!( !page.text().contains("preview, no downloads"), "{}", page.text() ); // The owner's own viewer names no grant: the note is for the reader // the grant limits. let own = app.get(&format!("/view/{file}"), Some(&admin)).await; assert_eq!(own.status, StatusCode::OK, "{}", own.text()); assert!( !own.text().contains("anything viewable can be saved"), "{}", own.text() ); assert!(own.text().contains("?dl=1"), "{}", own.text()); // The back link names the origin: opened from the shared page (the // `from=shared` its rows carry) it returns there, a plain opening to // the drive. let from_shared = app .get(&format!("/view/{file}?from=shared"), Some(&bob)) .await; assert_eq!(from_shared.status, StatusCode::OK, "{}", from_shared.text()); assert!( from_shared.text().contains("Back to shared"), "{}", from_shared.text() ); assert!( !from_shared.text().contains("Back to the drive"), "{}", from_shared.text() ); assert!(page.text().contains("Back to the drive"), "{}", page.text()); // The inline bytes serve for the preview... let inline = app.get(&format!("/file/{file}"), Some(&bob)).await; assert_eq!(inline.status, StatusCode::OK, "{}", inline.text()); assert_eq!(inline.bytes, b"\x89PNG\r\n\x1a\n preview bytes"); // ...and taking the file away stays the stranger's answer. let taken = app.get(&format!("/file/{file}?dl=1"), Some(&bob)).await; assert_eq!(taken.status, StatusCode::NOT_FOUND, "{}", taken.text()); // A preview is not a download: the counter never moves. assert_eq!( app.store.file(&file).await.unwrap().unwrap().download_count, 0 ); } // -- trash ------------------------------------------------------------------ #[tokio::test] async fn trash_restore_purge_empty_flows() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let one = file_id(&app, &owner, "one.txt", b"one").await; let two = file_id(&app, &owner, "two.txt", b"two").await; app.store.delete_file(&one).await.unwrap(); app.store.delete_file(&two).await.unwrap(); let page = app.get("/trash", Some(&admin)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("one.txt"), "{}", page.text()); assert!(page.text().contains("two.txt"), "{}", page.text()); // Restore one: it leaves the trash and keeps its bytes. let answer = app .post( "/api/trash/restore", Some(&admin), &[("kind", "file"), ("id", &one)], ) .await; assert!(answer.accepted(), "restore refused: {:?}", answer.location); assert!( app.store .file(&one) .await .unwrap() .unwrap() .deleted_at .is_none() ); // Purge the other: the row and its bytes go. let answer = app .post( "/api/trash/purge", Some(&admin), &[("kind", "file"), ("id", &two)], ) .await; assert!(answer.accepted(), "purge refused: {:?}", answer.location); assert!(app.store.file(&two).await.unwrap().is_none()); // Empty takes the rest. let three = file_id(&app, &owner, "three.txt", b"three").await; app.store.delete_file(&three).await.unwrap(); let answer = app.post("/api/trash/empty", Some(&admin), &[]).await; assert!(answer.accepted(), "empty refused: {:?}", answer.location); assert!(app.store.list_trash(&owner).await.unwrap().files.is_empty()); } #[tokio::test] async fn restore_under_trashed_ancestor_is_refused() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let folder = app.store.create_folder(&owner, None, "box").await.unwrap(); let file = app .store .insert_file(&owner, Some(&folder.id), "inbox.txt", b"in") .await .unwrap(); app.store.delete_folder(&folder.id).await.unwrap(); let answer = app .post( "/api/trash/restore", Some(&admin), &[("kind", "file"), ("id", &file.id)], ) .await; assert!( answer.refused("ancestor-trashed", "restore"), "{:?}", answer.location ); // The folder itself restores with its child. let answer = app .post( "/api/trash/restore", Some(&admin), &[("kind", "folder"), ("id", &folder.id)], ) .await; assert!(answer.accepted(), "restore refused: {:?}", answer.location); } #[tokio::test] async fn folder_purge_destroys_its_tree() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let folder = app .store .create_folder(&owner, None, "doomed") .await .unwrap(); let file = app .store .insert_file(&owner, Some(&folder.id), "gone.txt", b"gone") .await .unwrap(); app.store.delete_folder(&folder.id).await.unwrap(); let answer = app .post( "/api/trash/purge", Some(&admin), &[("kind", "folder"), ("id", &folder.id)], ) .await; assert!(answer.accepted(), "purge refused: {:?}", answer.location); assert!(app.store.folder(&folder.id).await.unwrap().is_none()); assert!(app.store.file(&file.id).await.unwrap().is_none()); } // -- search ----------------------------------------------------------------- #[tokio::test] async fn search_scopes_to_owner_and_hides_trashed() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; let ada = owner_of(&app, "sub-admin").await; let bob_id = owner_of(&app, "sub-bob").await; let mine = file_id(&app, &ada, "quarterly report.txt", b"a").await; let _ = file_id(&app, &bob_id, "quarterly notes.txt", b"b").await; let buried = file_id(&app, &ada, "quarterly draft.txt", b"c").await; app.store.delete_file(&buried).await.unwrap(); // Empty query is the folder view, not the whole library under a new // name: the upload control renders, no results caption does. let page = app.get("/drive", Some(&admin)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!( page.text().contains("id=\"upload-form\""), "{}", page.text() ); assert!(!page.text().contains("Search results"), "{}", page.text()); let page = app.get("/drive?q=quarterly", Some(&admin)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!( page.text().contains("quarterly report.txt"), "{}", page.text() ); assert!( !page.text().contains("quarterly notes.txt"), "{}", page.text() ); assert!( !page.text().contains("quarterly draft.txt"), "{}", page.text() ); assert!(app.store.file(&mine).await.unwrap().is_some()); let page = app.get("/drive?q=quarterly", Some(&bob)).await; assert!( page.text().contains("quarterly notes.txt"), "{}", page.text() ); assert!( !page.text().contains("quarterly report.txt"), "{}", page.text() ); } #[tokio::test] async fn drive_search_results_merge_into_one_panel() { let app = TestApp::build().await; let cookie = app .sign_in("sub-search-in-place", "inplace@in.test", "InPlace") .await; let owner = owner_of(&app, "sub-search-in-place").await; let answer = app .post( "/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "holiday photos")], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let folder = folder_id(&app, &owner, None, "holiday photos").await; let file = file_id(&app, &owner, "holiday report.txt", b"sun").await; let page = app.get("/drive?q=holiday", Some(&cookie)).await; let body = page.text(); // Both hits render in one shared list, folders first, wired to their surfaces. assert!(body.contains("holiday photos"), "{body}"); assert!(body.contains("holiday report.txt"), "{body}"); assert!(body.contains(&format!("/drive?folder={folder}")), "{body}"); assert!(body.contains(&format!("/view/{file}")), "{body}"); // Drive rows stay unmarked: only the shared page names an origin. assert!(!body.contains("from=shared"), "{body}"); let folder_at = body.find("holiday photos").expect("no folder hit"); let file_at = body.find("holiday report.txt").expect("no file hit"); assert!(folder_at < file_at, "file hit precedes folder hit: {body}"); // One panel, no heads or chips. assert_eq!( body.matches("
") .count(), 1, "{body}" ); assert!(!body.contains("panel-head"), "{body}"); assert!(!body.contains("class=\"chip\""), "{body}"); assert!(!body.contains(">Folders"), "{body}"); assert!(!body.contains(">Files"), "{body}"); // The caption names the query and the box keeps it. assert!(body.contains("Search results"), "{body}"); assert!(body.contains("holiday"), "{body}"); assert!(body.contains("value=\"holiday\""), "{body}"); assert!(body.contains("name=\"q\""), "{body}"); // The upload control stays in the DOM for the + menu and the drop handler. assert!(body.contains("id=\"upload-form\""), "{body}"); assert!(body.contains("id=\"drive-upload-input\""), "{body}"); // The folder view is gone: no crumbs, no row mutations. assert!(!body.contains("detail-crumbs"), "{body}"); assert!(!body.contains("action=\"/api/folder/rename\""), "{body}"); } #[tokio::test] async fn drive_search_never_shows_other_owners_hits() { let app = TestApp::build().await; let ada = app.sign_in("sub-search-ada", "ada2@in.test", "Ada").await; let bob = app.sign_in("sub-search-bob", "bob2@in.test", "Bob").await; let bob_id = owner_of(&app, "sub-search-bob").await; let _ = file_id(&app, &bob_id, "secret ledger.txt", b"b").await; let answer = app .post( "/api/folder/create", Some(&bob), &[("parent_id", ""), ("name", "secret drawer")], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); // Ada's library-wide search stays hers: Bob's file and folder hits never // appear, and the quiet note says so. let page = app.get("/drive?q=secret", Some(&ada)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let body = page.text(); assert!(!body.contains("secret ledger.txt"), "{body}"); assert!(!body.contains("secret drawer"), "{body}"); assert!(body.contains("Nothing found."), "{body}"); // Sanity: the same query finds them for their owner. let page = app.get("/drive?q=secret", Some(&bob)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("secret ledger.txt"), "{}", page.text()); assert!(page.text().contains("secret drawer"), "{}", page.text()); } #[tokio::test] async fn drive_search_empty_query_is_the_folder_view() { let app = TestApp::build().await; let cookie = app .sign_in("sub-search-empty", "empty@in.test", "Empty") .await; let owner = owner_of(&app, "sub-search-empty").await; let _ = file_id(&app, &owner, "plain.txt", b"p").await; for path in ["/drive?q=", "/drive?q=%20%20"] { let page = app.get(path, Some(&cookie)).await; assert_eq!(page.status, StatusCode::OK, "{}: {}", path, page.text()); let body = page.text(); // The folder listing renders as usual — the file is there through // its directory, not through a result — with the box held empty. assert!(body.contains("plain.txt"), "{path}: {body}"); assert!(body.contains("id=\"upload-form\""), "{path}: {body}"); assert!(body.contains("name=\"q\""), "{path}: {body}"); assert!(!body.contains("Search results"), "{path}: {body}"); } } #[tokio::test] async fn old_search_address_redirects_to_drive() { let app = TestApp::build().await; let cookie = app.sign_in("sub-search-old", "old@in.test", "Old").await; let page = app.get("/search?q=quarterly", Some(&cookie)).await; assert_eq!(page.status, StatusCode::SEE_OTHER, "{}", page.text()); assert_eq!(page.location.as_deref(), Some("/drive?q=quarterly")); // The raw pair rides through untouched, so encoded queries survive. let page = app.get("/search?q=holiday+report", Some(&cookie)).await; assert_eq!(page.status, StatusCode::SEE_OTHER, "{}", page.text()); assert_eq!(page.location.as_deref(), Some("/drive?q=holiday+report")); // No query is the plain drive; no session still redirects, never 401s. let page = app.get("/search", Some(&cookie)).await; assert_eq!(page.status, StatusCode::SEE_OTHER, "{}", page.text()); assert_eq!(page.location.as_deref(), Some("/drive")); let page = app.get("/search?q=quarterly", None).await; assert_eq!(page.status, StatusCode::SEE_OTHER, "{}", page.text()); assert_eq!(page.location.as_deref(), Some("/drive?q=quarterly")); } #[tokio::test] async fn topbar_nav_has_no_search_link() { let app = TestApp::build().await; let cookie = app.sign_in("sub-search-nav", "nav@in.test", "Nav").await; let page = app.get("/drive", Some(&cookie)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let body = page.text(); let nav_start = body.find("topbar-nav-links").expect("no nav"); let nav_end = body[nav_start..].find("").expect("nav never closes"); let nav = &body[nav_start..nav_start + nav_end]; // Drive, Shared, Trash — and nothing else. assert!(nav.contains("href=\"/drive\""), "{nav}"); assert!(nav.contains("href=\"/shared\""), "{nav}"); assert!(nav.contains("href=\"/trash\""), "{nav}"); assert!( !nav.contains("/search"), "search leaked into the nav: {nav}" ); assert!(!nav.contains("Search"), "search leaked into the nav: {nav}"); } #[tokio::test] async fn the_family_flyout_holds_the_siblings_when_the_family_is_mirrored() { // No mirrored family: no switcher — the chrome as it always was. let bare = TestApp::build().await; let cookie = bare .sign_in("sub-switch0", "switch0@in.test", "Switch0") .await; let page = bare.get("/drive", Some(&cookie)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(!page.text().contains("app-switcher"), "{}", page.text()); let app = TestApp::build_with( None, &[ ("in", "Files", "https://files.example.com"), ("im", "Account", "https://id.example.com"), ("iz", "Board", "https://board.example.com"), ], ) .await; let cookie = app.sign_in("sub-switch", "switch@in.test", "Switch").await; let page = app.get("/drive", Some(&cookie)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let body = page.text(); let nav_start = body.find("app-switcher").expect("no switcher"); let nav_end = body[nav_start..] .find("") .expect("switcher never closes"); let nav = &body[nav_start..nav_start + nav_end]; // Only the siblings hang in the flyout — this app's own row is the mark // the flyout hangs from, not an entry in it. assert!( !nav.contains("href=\"https://files.example.com/\""), "{nav}" ); assert!(nav.contains("href=\"https://id.example.com/\""), "{nav}"); assert!(nav.contains("href=\"https://board.example.com/\""), "{nav}"); assert!(nav.contains("title=\"Account\""), "{nav}"); assert_eq!(nav.matches("app-switcher-mark").count(), 2, "{nav}"); assert_eq!(nav.matches("app-switcher-sep").count(), 1, "{nav}"); // Both siblings sit at example.com addresses nothing answers — the // probes fail inside their two-second ceiling, concurrently — so both // read Off. The flyout carries dots only, one per mark. assert!(nav.contains("health-dot health-off"), "{nav}"); assert!(!nav.contains("health-on"), "{nav}"); assert_eq!(nav.matches("health-dot").count(), 2, "{nav}"); // The flyout hangs off the monogram, not the page nav. assert!(body.contains("wordmark-family"), "{body}"); } /// The flyout marks each sibling with its probe's reading: a sibling /// answering `ok` renders `health-on`, a dark port `health-off`, dots /// only — no probe body, no latency — and in's own row stays out. The /// markup itself is pinned router-free in /// `the_family_flyout_marks_pure_html` below. #[tokio::test] async fn the_family_flyout_marks_siblings_with_health_dots() { use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; // A live sibling answering the deploy body, and a dark one. let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let live_url = format!("http://{}", listener.local_addr().unwrap()); let dark = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let dark_url = format!("http://{}", dark.local_addr().unwrap()); drop(dark); // `in` gets a row too — one the flyout must leave out. let app = TestApp::build_with( None, &[ ("in", "Files", "https://files.example.com"), ("iz", "Board", &live_url), ("im", "Account", &dark_url), ], ) .await; let cookie = app .sign_in("sub-switch-dot", "switchdot@in.test", "SwitchDot") .await; let talker = tokio::spawn(async move { let (mut sock, _) = listener.accept().await.unwrap(); let mut buf = [0u8; 1024]; let _ = sock.read(&mut buf).await; sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 6\r\n\r\nok dev") .await .unwrap(); }); let page = app.get("/drive", Some(&cookie)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); talker.await.unwrap(); let body = page.text(); let nav_start = body.find("app-switcher").expect("no switcher"); let nav_end = body[nav_start..] .find("") .expect("switcher never closes"); let nav = &body[nav_start..nav_start + nav_end]; assert!( nav.contains(r#"iz"), "the live sibling renders: {nav}"); assert!( nav.contains("health-dot health-off"), "the dark sibling reads off: {nav}" ); assert!(nav.contains(">im"), "the dark sibling renders: {nav}"); assert!(!nav.contains(">in"), "in's own row stays out: {nav}"); assert!( !body.contains("ok dev"), "the flyout carries dots only: {body}" ); assert!(!nav.contains(" ms"), "the flyout carries no latency: {nav}"); } /// The CI gate for the flyout markup: `switcher_marks` is the exact HTML /// the flyout renders, so the probe-to-dot mapping is pinned without a /// router or an asset bundle — which is where the renders above get /// skipped. Up reads `health-on`, Down `health-off`, the keys stay links /// with their titles, and the probe's body and latency never reach the /// chrome. (The omission of in's own row is `family_mark`'s doing; the /// router renders above pin it.) #[test] fn the_family_flyout_marks_pure_html() { use in_web::health::Probe; let marks = in_web::layout::switcher_marks([ ( "iz", "http://127.0.0.1:9001", "Board", Probe::Up { body: "ok dev".into(), ms: 12, }, ), ("im", "http://127.0.0.1:9002", "Account", Probe::Down), ]); assert!( marks.contains( r#""# ), "the marks stay links: {marks}" ); assert!( marks.contains("health-dot health-on"), "the ok sibling reads on: {marks}" ); assert!( marks.contains(">iz"), "the live sibling renders: {marks}" ); assert!( marks.contains("health-dot health-off"), "the dark sibling reads off: {marks}" ); assert!( marks.contains(">im"), "the dark sibling renders: {marks}" ); assert!( !marks.contains("ok dev"), "the flyout carries dots only: {marks}" ); assert!( !marks.contains(" ms"), "the flyout carries no latency: {marks}" ); assert!( marks.contains(r#"·"#), "the marks join on middots: {marks}" ); } /// The `back` the sign-out hands im is read per sign-out: an origin saved /// on the running install — the `base_url` setting the settings panel /// writes — takes effect on the very next exit, without a restart. Until /// one is saved, the chain falls back to the config origin, which here is /// the address bound. #[tokio::test] async fn logout_back_follows_the_origin_saved_at_runtime() { let app = TestApp::build().await; let cookie = app.sign_in("sub-logout", "logout@in.test", "Logout").await; // Nothing saved: the listen-derived origin carries the back address. let page = app.get("/auth/logout", Some(&cookie)).await; let expected = format!( "{}/logout?back=http%3A%2F%2F127.0.0.1%3A7655%2F", app.client.issuer ); assert_eq!(page.location.as_deref(), Some(expected.as_str())); // The admin saves a public origin; the next sign-out hands im that. let answer = app .post( "/api/settings/base_url", Some(&cookie), &[("base_url", "https://files.example.com")], ) .await; assert!(answer.accepted(), "base_url refused: {:?}", answer.location); let page = app.get("/auth/logout", Some(&cookie)).await; let expected = format!( "{}/logout?back=https%3A%2F%2Ffiles.example.com%2F", app.client.issuer ); assert_eq!(page.location.as_deref(), Some(expected.as_str())); } // -- settings --------------------------------------------------------------- #[tokio::test] async fn settings_quota_and_disable_guards() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; let bob_id = owner_of(&app, "sub-bob").await; let admin_id = owner_of(&app, "sub-admin").await; let page = app.get("/settings", Some(&admin)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("ada@in.test"), "{}", page.text()); // Admin sets Bob's quota in human units: 2 GiB lands as 2147483648 bytes. let answer = app .post( "/api/settings/quota", Some(&admin), &[("user_id", &bob_id), ("quota", "2"), ("quota_unit", "GiB")], ) .await; assert!(answer.accepted(), "quota refused: {:?}", answer.location); assert!( answer .location .as_deref() .is_some_and(|location| location.contains("section=everyone")), "quota left the Everyone section: {:?}", answer.location ); assert_eq!( app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes, 2147483648 ); // A non-admin is refused the same call. let answer = app .post( "/api/settings/quota", Some(&bob), &[ ("user_id", &bob_id), ("quota", "999"), ("quota_unit", "MiB"), ], ) .await; assert!( answer.refused("forbidden", "quota"), "{:?}", answer.location ); // Disabling yourself is refused; disabling Bob signs him out. let answer = app .post( "/api/settings/disable", Some(&admin), &[("user_id", &admin_id), ("disabled", "1")], ) .await; assert!( answer.refused("forbidden", "disable"), "{:?}", answer.location ); let answer = app .post( "/api/settings/disable", Some(&admin), &[("user_id", &bob_id), ("disabled", "1")], ) .await; assert!(answer.accepted(), "disable refused: {:?}", answer.location); assert!( answer .location .as_deref() .is_some_and(|location| location.contains("section=everyone")), "disable left the Everyone section: {:?}", answer.location ); let page = app.get("/settings", Some(&bob)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!( !page.text().contains("bob@in.test"), "disabled account still served: {}", page.text() ); } /// A deployment with a domain tells that domain, never the bind: the /// settings copy-once banner and the drive modal's link rows all carry /// `base_url`. #[tokio::test] async fn share_links_carry_the_configured_base_url() { let app = TestApp::build_with(Some("https://files.example.com"), &[]).await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "notes.txt", b"hello in").await; let answer = app .post( "/api/share/link/create", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("can_download", "1"), ], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let token = created_token(answer.location.as_deref().unwrap()); // The banner the mint redirects back to. let page = app .get( &format!("/settings?section=links&created={token}"), Some(&admin), ) .await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!( page.text() .contains(&format!("https://files.example.com/s/{token}")), "banner showed no domain link: {}", page.text() ); assert!( !page.text().contains("127.0.0.1:7655/s/"), "banner leaked the bind address: {}", page.text() ); // The modal says the same — and a sealed link now carries the full // address, leaving no masked placeholder behind. let page = app .get( &format!("/drive?share=file:{file}&created={token}"), Some(&admin), ) .await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!( page.text() .contains(&format!("https://files.example.com/s/{token}")), "modal showed no domain link: {}", page.text() ); assert!( !page.text().contains("/s/…"), "modal kept a masked placeholder on a sealed link: {}", page.text() ); } #[tokio::test] async fn share_links_follow_the_bind_without_a_base_url() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "notes.txt", b"hello in").await; let answer = app .post( "/api/share/link/create", Some(&admin), &[ ("kind", "file"), ("target_id", &file), ("can_download", "1"), ], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); let token = created_token(answer.location.as_deref().unwrap()); // No `base_url`: the links say the address bound, as they always // have. let page = app .get( &format!("/settings?section=links&created={token}"), Some(&admin), ) .await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!( page.text() .contains(&format!("http://127.0.0.1:7655/s/{token}")), "banner showed no bind link: {}", page.text() ); } /// Mints one link over `file` and returns the plaintext token — and the /// mint must land back on the links section that renders its banner. async fn minted_token(app: &TestApp, cookie: &str, file: &str) -> String { let answer = app .post( "/api/share/link/create", Some(cookie), &[("kind", "file"), ("target_id", file), ("can_download", "1")], ) .await; assert!(answer.accepted(), "create refused: {:?}", answer.location); assert!( answer .location .as_deref() .is_some_and(|location| location.contains("section=links")), "create left the links section: {:?}", answer.location ); created_token(answer.location.as_deref().unwrap()) } /// The rail splits the page: every signed-in reader sees Profile and Share /// links, an admin additionally Everyone and Server — and an admin URL a /// non-admin pastes renders the profile, leaking no rows and no form. #[tokio::test] async fn settings_rail_gates_the_admin_sections() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; // An admin's rail carries all four sections, and the default page is // the profile alone. let page = app.get("/settings", Some(&admin)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let body = page.text(); for section in ["profile", "links", "everyone", "server"] { assert!( body.contains(&format!("/settings?section={section}")), "admin rail lacks {section}: {body}" ); } assert!(body.contains("name=\"ui\""), "{}", body); assert!(!body.contains("member-table"), "{}", body); assert!(!body.contains("/api/settings/base_url"), "{}", body); // A non-admin's rail stops at the reader sections. let page = app.get("/settings", Some(&bob)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let body = page.text(); assert!(body.contains("/settings?section=profile"), "{}", body); assert!(body.contains("/settings?section=links"), "{}", body); assert!(!body.contains("/settings?section=everyone"), "{}", body); assert!(!body.contains("/settings?section=server"), "{}", body); // An admin URL pasted by a non-admin answers the profile: no account // rows, no address form, no origin. for asked in ["everyone", "server"] { let page = app .get(&format!("/settings?section={asked}"), Some(&bob)) .await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let body = page.text(); assert!(body.contains("name=\"ui\""), "not the profile: {body}"); assert!(!body.contains("member-table"), "{body}"); assert!(!body.contains("/api/settings/base_url"), "{body}"); } } /// Each section renders alone on its own `?section=` pair — the profile's /// preferences form, the links panel, the Everyone register, the server /// address form — and never a row or form belonging to another. #[tokio::test] async fn admin_settings_sections_render_alone() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "notes.txt", b"hello in").await; app.store .create_share_link(&owner, ShareKind::File, &file, true, None, None) .await .unwrap(); let body = app .get("/settings?section=profile", Some(&admin)) .await .text(); assert!(body.contains("name=\"ui\""), "{body}"); assert!(!body.contains("/api/share/link/revoke"), "{body}"); assert!(!body.contains("member-table"), "{body}"); assert!(!body.contains("/api/settings/base_url"), "{body}"); let body = app .get("/settings?section=links", Some(&admin)) .await .text(); assert!(body.contains("action=\"/api/share/link/revoke\""), "{body}"); assert!(!body.contains("name=\"ui\""), "{body}"); assert!(!body.contains("member-table"), "{body}"); assert!(!body.contains("/api/settings/base_url"), "{body}"); let body = app .get("/settings?section=everyone", Some(&admin)) .await .text(); assert!(body.contains("member-table"), "{body}"); assert!(body.contains("ada@in.test"), "{body}"); assert!(!body.contains("name=\"ui\""), "{body}"); assert!(!body.contains("/api/share/link/revoke"), "{body}"); assert!(!body.contains("/api/settings/base_url"), "{body}"); let body = app .get("/settings?section=server", Some(&admin)) .await .text(); assert!(body.contains("action=\"/api/settings/base_url\""), "{body}"); // The effective origin shows before anything is stored: the bind. assert!(body.contains("http://127.0.0.1:7655"), "{body}"); assert!(!body.contains("name=\"ui\""), "{body}"); assert!(!body.contains("member-table"), "{body}"); assert!(!body.contains("/api/share/link/revoke"), "{body}"); } /// The admin's server-address form: a valid origin stores the `base_url` /// setting and every newly minted link carries it; a value with no scheme /// or a trailing slash is refused with the setting untouched; saving empty /// clears it and the links fall back to the address bound. A non-admin is /// refused before anything is read. #[tokio::test] async fn server_address_setting_drives_share_links() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "notes.txt", b"hello in").await; let answer = app .post( "/api/settings/base_url", Some(&bob), &[("base_url", "https://bob.example.net")], ) .await; assert!( answer.refused("forbidden", "base_url"), "{:?}", answer.location ); assert_eq!(app.store.get_setting("base_url").await.unwrap(), None); let answer = app .post( "/api/settings/base_url", Some(&admin), &[("base_url", "https://files.example.com")], ) .await; assert!(answer.accepted(), "save refused: {:?}", answer.location); assert!( answer.location.as_deref().is_some_and(|location| { location.contains("section=server") && location.contains("saved=base_url") }), "{:?}", answer.location ); assert_eq!( app.store.get_setting("base_url").await.unwrap().as_deref(), Some("https://files.example.com") ); let token = minted_token(&app, &admin, &file).await; let page = app .get( &format!("/settings?section=links&created={token}"), Some(&admin), ) .await; assert!( page.text() .contains(&format!("https://files.example.com/s/{token}")), "{}", page.text() ); // No scheme, or a trailing slash: refused, the stored value untouched. for bad in ["files.example.com", "https://files.example.com/"] { let answer = app .post("/api/settings/base_url", Some(&admin), &[("base_url", bad)]) .await; assert!( answer.refused("bad-base-url", "base_url"), "{bad}: {:?}", answer.location ); } assert_eq!( app.store.get_setting("base_url").await.unwrap().as_deref(), Some("https://files.example.com"), "a refused save changed the setting" ); // Empty clears: the links fall back to the address bound. let answer = app .post("/api/settings/base_url", Some(&admin), &[("base_url", "")]) .await; assert!(answer.accepted(), "clear refused: {:?}", answer.location); assert_eq!( app.store.get_setting("base_url").await.unwrap().as_deref(), Some("") ); let token = minted_token(&app, &admin, &file).await; let page = app .get( &format!("/settings?section=links&created={token}"), Some(&admin), ) .await; let body = page.text(); assert!( body.contains(&format!("http://127.0.0.1:7655/s/{token}")), "{body}" ); assert!(!body.contains("https://files.example.com"), "{body}"); } /// Clearing a stored origin falls back to the config's `base_url` when the /// file sets one: the setting wins only while it is non-empty. #[tokio::test] async fn cleared_setting_falls_back_to_the_configured_base_url() { let app = TestApp::build_with(Some("https://cfg.example.com"), &[]).await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "notes.txt", b"hello in").await; let answer = app .post( "/api/settings/base_url", Some(&admin), &[("base_url", "https://override.example.com")], ) .await; assert!(answer.accepted(), "save refused: {:?}", answer.location); let token = minted_token(&app, &admin, &file).await; let page = app .get( &format!("/settings?section=links&created={token}"), Some(&admin), ) .await; assert!( page.text() .contains(&format!("https://override.example.com/s/{token}")), "{}", page.text() ); let answer = app .post("/api/settings/base_url", Some(&admin), &[("base_url", "")]) .await; assert!(answer.accepted(), "clear refused: {:?}", answer.location); let token = minted_token(&app, &admin, &file).await; let page = app .get( &format!("/settings?section=links&created={token}"), Some(&admin), ) .await; let body = page.text(); assert!( body.contains(&format!("https://cfg.example.com/s/{token}")), "{body}" ); assert!(!body.contains("override.example.com"), "{body}"); } /// A revoke lands back on the links section that hosts its rows, even for /// a post arriving without a `Referer` to return to. #[tokio::test] async fn revoke_redirects_land_on_the_links_section() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let answer = app .post( "/api/share/link/revoke", Some(&admin), &[("id", "never-real")], ) .await; assert!( answer .location .as_deref() .is_some_and(|location| location.contains("/settings?section=links")), "{:?}", answer.location ); } /// The revoke control is one inline quiet button at the row's end, like /// the modal's remove-access rows — not a full-width block of its own. #[tokio::test] async fn the_settings_revoke_button_sits_inline_in_its_row() { let app = TestApp::build().await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "notes.txt", b"hello in").await; app.store .create_share_link(&owner, ShareKind::File, &file, true, None, None) .await .unwrap(); let body = app .get("/settings?section=links", Some(&admin)) .await .text(); let row_at = body .find("
") .expect("no share-link row"); let form_at = body[row_at..] .find("
") .expect("no revoke form in a member-row"); let form_close = row_at + form_at + body[row_at + form_at..] .find("
") .expect("form never closes"); // The row is still open around the form: its own close is the first // `
` after the form's. let _row_close = form_close + body[form_close..].find("
").expect("row never closes"); let form = &body[row_at + form_at..form_close]; assert!( form.contains("