mod.rs
| 1 | //! Shared integration-test harness: drives the real router with |
| 2 | //! `tower::ServiceExt::oneshot` — no ports, no network, fully parallel. |
| 3 | // |
| 4 | // Every test binary compiles this module privately, so helpers unused by a |
| 5 | // particular binary would warn as dead code. |
| 6 | #![allow(dead_code)] |
| 7 | |
| 8 | use std::collections::BTreeMap; |
| 9 | use std::sync::Arc; |
| 10 | |
| 11 | use axum::Router; |
| 12 | use axum::body::Body; |
| 13 | use axum::http::{HeaderMap, Method, StatusCode, header}; |
| 14 | use http_body_util::BodyExt; |
| 15 | use server::db::Db; |
| 16 | use server::error::AppState; |
| 17 | use tower::ServiceExt; |
| 18 | |
| 19 | // --------------------------------------------------------------------------- |
| 20 | // Environment |
| 21 | // --------------------------------------------------------------------------- |
| 22 | |
| 23 | /// A server with a small fixture tree: |
| 24 | /// |
| 25 | /// ```text |
| 26 | /// root/ |
| 27 | /// docs/ |
| 28 | /// inner/ |
| 29 | /// hello.txt ("hello world") |
| 30 | /// a.txt ("file a") |
| 31 | /// src/ |
| 32 | /// main.rs |
| 33 | /// config.json |
| 34 | /// notes.md |
| 35 | /// editme.txt ("v1") |
| 36 | /// blob.bin (64 bytes) |
| 37 | /// ``` |
| 38 | pub struct Env { |
| 39 | pub root: tempfile::TempDir, |
| 40 | pub state: Arc<AppState>, |
| 41 | pub app: Router, |
| 42 | /// Kept alive so the thumbnail cache folder outlives the server. |
| 43 | pub cache: Option<tempfile::TempDir>, |
| 44 | } |
| 45 | |
| 46 | impl Env { |
| 47 | pub async fn new() -> Self { |
| 48 | Self::build(false, true).await |
| 49 | } |
| 50 | |
| 51 | /// Same fixtures, plus a thumbnail cache in a temp folder. |
| 52 | pub async fn with_thumbs() -> Self { |
| 53 | Self::build(true, true).await |
| 54 | } |
| 55 | |
| 56 | /// A thumbnail cache with ffmpeg reported as missing, so the no-video |
| 57 | /// branch can be exercised on a machine that has it. |
| 58 | pub async fn without_ffmpeg() -> Self { |
| 59 | Self::build(true, false).await |
| 60 | } |
| 61 | |
| 62 | async fn build(thumbs: bool, ffmpeg: bool) -> Self { |
| 63 | let root = tempfile::tempdir().unwrap(); |
| 64 | let p = root.path(); |
| 65 | std::fs::create_dir_all(p.join("docs/inner")).unwrap(); |
| 66 | std::fs::create_dir_all(p.join("src")).unwrap(); |
| 67 | std::fs::write(p.join("docs/inner/hello.txt"), "hello world").unwrap(); |
| 68 | std::fs::write(p.join("docs/a.txt"), "file a").unwrap(); |
| 69 | std::fs::write(p.join("src/main.rs"), "fn main() {}").unwrap(); |
| 70 | std::fs::write(p.join("config.json"), "{\"k\": 1}").unwrap(); |
| 71 | std::fs::write(p.join("notes.md"), "# notes").unwrap(); |
| 72 | std::fs::write(p.join("editme.txt"), "v1").unwrap(); |
| 73 | std::fs::write(p.join("blob.bin"), (0..64u8).collect::<Vec<_>>()).unwrap(); |
| 74 | |
| 75 | // In-memory SQLite: no temp files, no WAL, faster than file-backed. |
| 76 | let db = Db::open_in_memory().await.unwrap(); |
| 77 | let cache = match thumbs { |
| 78 | true => Some(tempfile::tempdir().unwrap()), |
| 79 | false => None, |
| 80 | }; |
| 81 | let thumbs = match &cache { |
| 82 | Some(d) => Some(Arc::new( |
| 83 | server::thumb::Thumbs::with_ffmpeg(d.path().to_path_buf(), ffmpeg) |
| 84 | .await |
| 85 | .unwrap(), |
| 86 | )), |
| 87 | None => None, |
| 88 | }; |
| 89 | let state = Arc::new(AppState { |
| 90 | db, |
| 91 | root: p.canonicalize().unwrap(), |
| 92 | root_name: server::root_file_name(p), |
| 93 | https: false, |
| 94 | public_url: None, |
| 95 | thumbs, |
| 96 | }); |
| 97 | let app = server::api::router(state.clone()); |
| 98 | Self { |
| 99 | root, |
| 100 | state, |
| 101 | app, |
| 102 | cache, |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | /// Absolute path of a fixture file inside the root. |
| 107 | pub fn file(&self, rel: &str) -> std::path::PathBuf { |
| 108 | self.root.path().join(rel) |
| 109 | } |
| 110 | |
| 111 | /// Create an admin account (first boot) and return a signed-in client. |
| 112 | pub async fn admin(&self) -> Client { |
| 113 | let c = Client::new(self.app.clone()); |
| 114 | let r = c |
| 115 | .post_json( |
| 116 | "/api/auth/setup", |
| 117 | &serde_json::json!({ "name": "admin", "password": "admin1234" }), |
| 118 | ) |
| 119 | .await; |
| 120 | assert_eq!(r.status, StatusCode::OK, "setup failed: {}", r.text()); |
| 121 | let token = session_cookie(&r).expect("setup must set a session cookie"); |
| 122 | let mut c = Client::new(self.app.clone()); |
| 123 | c.set_cookie(&token); |
| 124 | c |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | // --------------------------------------------------------------------------- |
| 129 | // Client |
| 130 | // --------------------------------------------------------------------------- |
| 131 | |
| 132 | #[derive(Clone)] |
| 133 | pub struct Client { |
| 134 | app: Router, |
| 135 | pub cookie: Option<String>, |
| 136 | } |
| 137 | |
| 138 | pub struct Resp { |
| 139 | pub status: StatusCode, |
| 140 | pub headers: HeaderMap, |
| 141 | pub body: Vec<u8>, |
| 142 | } |
| 143 | |
| 144 | impl Resp { |
| 145 | pub fn json(&self) -> serde_json::Value { |
| 146 | serde_json::from_slice(&self.body).unwrap_or_else(|e| { |
| 147 | panic!( |
| 148 | "body is not JSON ({e}):\n{}", |
| 149 | String::from_utf8_lossy(&self.body) |
| 150 | ) |
| 151 | }) |
| 152 | } |
| 153 | |
| 154 | pub fn text(&self) -> String { |
| 155 | String::from_utf8_lossy(&self.body).into_owned() |
| 156 | } |
| 157 | |
| 158 | pub fn header(&self, name: &str) -> Option<String> { |
| 159 | self.headers |
| 160 | .get(name) |
| 161 | .and_then(|v| v.to_str().ok()) |
| 162 | .map(str::to_string) |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | impl Client { |
| 167 | pub fn new(app: Router) -> Self { |
| 168 | Self { app, cookie: None } |
| 169 | } |
| 170 | |
| 171 | pub fn set_cookie(&mut self, token: &str) { |
| 172 | self.cookie = Some(token.to_string()); |
| 173 | } |
| 174 | |
| 175 | pub async fn raw( |
| 176 | &self, |
| 177 | method: Method, |
| 178 | path: &str, |
| 179 | extra_headers: &[(&str, &str)], |
| 180 | body: Vec<u8>, |
| 181 | ) -> Resp { |
| 182 | let mut b = axum::http::Request::builder().method(method).uri(path); |
| 183 | for (k, v) in extra_headers { |
| 184 | b = b.header(*k, *v); |
| 185 | } |
| 186 | if let Some(c) = &self.cookie { |
| 187 | b = b.header(header::COOKIE, format!("fbng_session={c}")); |
| 188 | } |
| 189 | let req = b |
| 190 | .body(Body::from(body)) |
| 191 | .unwrap_or_else(|e| panic!("bad request: {e}")); |
| 192 | let res = self |
| 193 | .app |
| 194 | .clone() |
| 195 | .oneshot(req) |
| 196 | .await |
| 197 | .unwrap_or_else(|e| panic!("request failed: {e}")); |
| 198 | let status = res.status(); |
| 199 | let headers = res.headers().clone(); |
| 200 | let bytes = res.into_body().collect().await.unwrap().to_bytes(); |
| 201 | Resp { |
| 202 | status, |
| 203 | headers, |
| 204 | body: bytes.to_vec(), |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | pub async fn get(&self, path: &str) -> Resp { |
| 209 | self.raw(Method::GET, path, &[], Vec::new()).await |
| 210 | } |
| 211 | |
| 212 | pub async fn delete(&self, path: &str) -> Resp { |
| 213 | self.raw(Method::DELETE, path, &[], Vec::new()).await |
| 214 | } |
| 215 | |
| 216 | pub async fn post_json(&self, path: &str, v: &serde_json::Value) -> Resp { |
| 217 | self.raw( |
| 218 | Method::POST, |
| 219 | path, |
| 220 | &[("content-type", "application/json")], |
| 221 | v.to_string().into_bytes(), |
| 222 | ) |
| 223 | .await |
| 224 | } |
| 225 | |
| 226 | pub async fn put_json(&self, path: &str, v: &serde_json::Value) -> Resp { |
| 227 | self.raw( |
| 228 | Method::PUT, |
| 229 | path, |
| 230 | &[("content-type", "application/json")], |
| 231 | v.to_string().into_bytes(), |
| 232 | ) |
| 233 | .await |
| 234 | } |
| 235 | |
| 236 | /// `PUT ...?action=content` (editor save). |
| 237 | pub async fn put_content( |
| 238 | &self, |
| 239 | path: &str, |
| 240 | content: &[u8], |
| 241 | expected_mtime: Option<i64>, |
| 242 | ) -> Resp { |
| 243 | let mut extra: Vec<(&str, String)> = vec![("content-type", "text/plain".to_string())]; |
| 244 | if let Some(m) = expected_mtime { |
| 245 | extra.push(("x-expected-mtime", format!("{m}"))); |
| 246 | } |
| 247 | let owned: Vec<(String, String)> = |
| 248 | extra.into_iter().map(|(k, v)| (k.to_string(), v)).collect(); |
| 249 | let hdrs: Vec<(&str, &str)> = owned |
| 250 | .iter() |
| 251 | .map(|(k, v)| (k.as_str(), v.as_str())) |
| 252 | .collect(); |
| 253 | self.raw(Method::PUT, path, &hdrs, content.to_vec()).await |
| 254 | } |
| 255 | |
| 256 | /// POST a multipart upload with one file per part name. |
| 257 | pub async fn post_multipart(&self, path: &str, parts: &[(&str, &[u8])], query: &str) -> Resp { |
| 258 | let boundary = "testboundary123"; |
| 259 | let (ct, body) = multipart_body(parts, boundary); |
| 260 | let full = if query.is_empty() { |
| 261 | path.to_string() |
| 262 | } else { |
| 263 | format!("{path}?{query}") |
| 264 | }; |
| 265 | self.raw(Method::POST, &full, &[("content-type", &ct)], body) |
| 266 | .await |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | /// Extract the `fbng_session` cookie value from `Set-Cookie` headers. |
| 271 | pub fn session_cookie(r: &Resp) -> Option<String> { |
| 272 | for v in r.headers.get_all(header::SET_COOKIE) { |
| 273 | let s = v.to_str().ok()?; |
| 274 | let first = s.split(';').next().unwrap_or(""); |
| 275 | if let Some(tok) = first.strip_prefix("fbng_session=") |
| 276 | && !tok.is_empty() |
| 277 | { |
| 278 | return Some(tok.to_string()); |
| 279 | } |
| 280 | } |
| 281 | None |
| 282 | } |
| 283 | |
| 284 | /// POST /api/admin/users helper (used by several test files). |
| 285 | pub async fn create_user( |
| 286 | admin: &Client, |
| 287 | name: &str, |
| 288 | password: &str, |
| 289 | roots: &[(&str, &str)], |
| 290 | ) -> serde_json::Value { |
| 291 | let roots_json: Vec<serde_json::Value> = roots |
| 292 | .iter() |
| 293 | .map(|(p, m)| serde_json::json!({ "path": p, "mode": m })) |
| 294 | .collect(); |
| 295 | let r = admin |
| 296 | .post_json( |
| 297 | "/api/admin/users", |
| 298 | &serde_json::json!({ |
| 299 | "name": name, |
| 300 | "password": password, |
| 301 | "is_admin": false, |
| 302 | "roots": roots_json, |
| 303 | }), |
| 304 | ) |
| 305 | .await; |
| 306 | assert_eq!(r.status, StatusCode::OK, "create {name}: {}", r.text()); |
| 307 | r.json() |
| 308 | } |
| 309 | |
| 310 | /// Log in and return a signed-in client. |
| 311 | pub async fn login(env: &Env, name: &str, password: &str) -> Client { |
| 312 | let c = Client::new(env.app.clone()); |
| 313 | let r = c |
| 314 | .post_json( |
| 315 | "/api/auth/login", |
| 316 | &serde_json::json!({ "name": name, "password": password }), |
| 317 | ) |
| 318 | .await; |
| 319 | assert_eq!(r.status, StatusCode::OK, "login {name}: {}", r.text()); |
| 320 | let mut c = Client::new(env.app.clone()); |
| 321 | c.set_cookie(&session_cookie(&r).unwrap()); |
| 322 | c |
| 323 | } |
| 324 | |
| 325 | /// Find a user id by name via the admin API. |
| 326 | pub async fn user_id(admin: &Client, name: &str) -> i64 { |
| 327 | let r = admin.get("/api/admin/users").await; |
| 328 | assert_eq!(r.status, StatusCode::OK); |
| 329 | let j = r.json(); |
| 330 | let users = j.as_array().unwrap(); |
| 331 | users |
| 332 | .iter() |
| 333 | .find(|u| u["name"] == name) |
| 334 | .unwrap_or_else(|| panic!("user {name} not found")) |
| 335 | .as_object() |
| 336 | .unwrap() |
| 337 | .get("id") |
| 338 | .unwrap() |
| 339 | .as_i64() |
| 340 | .unwrap() |
| 341 | } |
| 342 | |
| 343 | // --------------------------------------------------------------------------- |
| 344 | // Helpers: multipart + archive readers |
| 345 | // --------------------------------------------------------------------------- |
| 346 | |
| 347 | /// Build a minimal multipart/form-data body. Each part is a file whose |
| 348 | /// `name` attribute is the (relative) target path — as the web client sends. |
| 349 | pub fn multipart_body(parts: &[(&str, &[u8])], boundary: &str) -> (String, Vec<u8>) { |
| 350 | let mut buf = Vec::new(); |
| 351 | for (name, content) in parts { |
| 352 | buf.extend_from_slice(format!("--{boundary}\r\n").as_bytes()); |
| 353 | buf.extend_from_slice( |
| 354 | format!("Content-Disposition: form-data; name=\"{name}\"\r\n").as_bytes(), |
| 355 | ); |
| 356 | buf.extend_from_slice(b"Content-Type: application/octet-stream\r\n\r\n"); |
| 357 | buf.extend_from_slice(content); |
| 358 | buf.extend_from_slice(b"\r\n"); |
| 359 | } |
| 360 | buf.extend_from_slice(format!("--{boundary}--\r\n").as_bytes()); |
| 361 | (format!("multipart/form-data; boundary={boundary}"), buf) |
| 362 | } |
| 363 | |
| 364 | /// Read a zip into a name → content map (files only). |
| 365 | pub fn zip_map(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> { |
| 366 | let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("valid zip archive"); |
| 367 | let mut map = BTreeMap::new(); |
| 368 | for i in 0..zip.len() { |
| 369 | let mut f = zip.by_index(i).unwrap(); |
| 370 | let name = f.name().unwrap().to_string(); |
| 371 | if name.ends_with('/') { |
| 372 | continue; |
| 373 | } |
| 374 | let mut buf = Vec::new(); |
| 375 | std::io::Read::read_to_end(&mut f, &mut buf).unwrap(); |
| 376 | map.insert(name, buf); |
| 377 | } |
| 378 | map |
| 379 | } |
| 380 | |
| 381 | /// Read a tar (optionally gz/zst compressed) into a name → content map. |
| 382 | pub fn tar_map(raw: &[u8], compress: Compress) -> BTreeMap<String, Vec<u8>> { |
| 383 | let decompressed: Box<dyn std::io::Read> = match compress { |
| 384 | Compress::None => Box::new(std::io::Cursor::new(raw)), |
| 385 | Compress::Gz => Box::new(flate2::read::GzDecoder::new(std::io::Cursor::new(raw))), |
| 386 | Compress::Zst => { |
| 387 | Box::new(zstd::stream::read::Decoder::new(std::io::Cursor::new(raw)).unwrap()) |
| 388 | } |
| 389 | }; |
| 390 | let mut map = BTreeMap::new(); |
| 391 | for entry in tar::Archive::new(decompressed).entries().unwrap() { |
| 392 | let mut e = entry.unwrap(); |
| 393 | if !e.header().entry_type().is_file() { |
| 394 | continue; |
| 395 | } |
| 396 | let name = e.path().unwrap().to_string_lossy().into_owned(); |
| 397 | let mut buf = Vec::new(); |
| 398 | std::io::Read::read_to_end(&mut e, &mut buf).unwrap(); |
| 399 | map.insert(name, buf); |
| 400 | } |
| 401 | map |
| 402 | } |
| 403 | |
| 404 | pub enum Compress { |
| 405 | None, |
| 406 | Gz, |
| 407 | Zst, |
| 408 | } |
| 409 |