mod.rs
⎇
Raw
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
8use std::collections::BTreeMap;
9use std::sync::Arc;
10
11use axum::Router;
12use axum::body::Body;
13use axum::http::{HeaderMap, Method, StatusCode, header};
14use http_body_util::BodyExt;
15use server::db::Db;
16use server::error::AppState;
17use 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/// ```
38pub 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
46impl 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)]
133pub struct Client {
134 app: Router,
135 pub cookie: Option<String>,
136}
137
138pub struct Resp {
139 pub status: StatusCode,
140 pub headers: HeaderMap,
141 pub body: Vec<u8>,
142}
143
144impl 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
166impl 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 // Every real client sends one (HTTP/1.1 requires it), and the
183 // passkey routes need it to know which domain they speak for.
184 // `oneshot` with a relative URI would otherwise send none. A caller
185 // that names its own host wins, so a test can pretend to be on one
186 // WebAuthn cannot use.
187 let mut b = axum::http::Request::builder().method(method).uri(path);
188 if !extra_headers
189 .iter()
190 .any(|(k, _)| k.eq_ignore_ascii_case("host"))
191 {
192 b = b.header(header::HOST, "files.example.com");
193 }
194 for (k, v) in extra_headers {
195 b = b.header(*k, *v);
196 }
197 if let Some(c) = &self.cookie {
198 b = b.header(header::COOKIE, format!("fbng_session={c}"));
199 }
200 let req = b
201 .body(Body::from(body))
202 .unwrap_or_else(|e| panic!("bad request: {e}"));
203 let res = self
204 .app
205 .clone()
206 .oneshot(req)
207 .await
208 .unwrap_or_else(|e| panic!("request failed: {e}"));
209 let status = res.status();
210 let headers = res.headers().clone();
211 let bytes = res.into_body().collect().await.unwrap().to_bytes();
212 Resp {
213 status,
214 headers,
215 body: bytes.to_vec(),
216 }
217 }
218
219 pub async fn get(&self, path: &str) -> Resp {
220 self.raw(Method::GET, path, &[], Vec::new()).await
221 }
222
223 pub async fn delete(&self, path: &str) -> Resp {
224 self.raw(Method::DELETE, path, &[], Vec::new()).await
225 }
226
227 pub async fn post_json(&self, path: &str, v: &serde_json::Value) -> Resp {
228 self.raw(
229 Method::POST,
230 path,
231 &[("content-type", "application/json")],
232 v.to_string().into_bytes(),
233 )
234 .await
235 }
236
237 pub async fn put_json(&self, path: &str, v: &serde_json::Value) -> Resp {
238 self.raw(
239 Method::PUT,
240 path,
241 &[("content-type", "application/json")],
242 v.to_string().into_bytes(),
243 )
244 .await
245 }
246
247 /// `PUT ...?action=content` (editor save).
248 pub async fn put_content(
249 &self,
250 path: &str,
251 content: &[u8],
252 expected_mtime: Option<i64>,
253 ) -> Resp {
254 let mut extra: Vec<(&str, String)> = vec![("content-type", "text/plain".to_string())];
255 if let Some(m) = expected_mtime {
256 extra.push(("x-expected-mtime", format!("{m}")));
257 }
258 let owned: Vec<(String, String)> =
259 extra.into_iter().map(|(k, v)| (k.to_string(), v)).collect();
260 let hdrs: Vec<(&str, &str)> = owned
261 .iter()
262 .map(|(k, v)| (k.as_str(), v.as_str()))
263 .collect();
264 self.raw(Method::PUT, path, &hdrs, content.to_vec()).await
265 }
266
267 /// POST a multipart upload with one file per part name.
268 pub async fn post_multipart(&self, path: &str, parts: &[(&str, &[u8])], query: &str) -> Resp {
269 let boundary = "testboundary123";
270 let (ct, body) = multipart_body(parts, boundary);
271 let full = if query.is_empty() {
272 path.to_string()
273 } else {
274 format!("{path}?{query}")
275 };
276 self.raw(Method::POST, &full, &[("content-type", &ct)], body)
277 .await
278 }
279}
280
281/// Extract the `fbng_session` cookie value from `Set-Cookie` headers.
282pub fn session_cookie(r: &Resp) -> Option<String> {
283 for v in r.headers.get_all(header::SET_COOKIE) {
284 let s = v.to_str().ok()?;
285 let first = s.split(';').next().unwrap_or("");
286 if let Some(tok) = first.strip_prefix("fbng_session=")
287 && !tok.is_empty()
288 {
289 return Some(tok.to_string());
290 }
291 }
292 None
293}
294
295/// POST /api/admin/users helper (used by several test files).
296pub async fn create_user(
297 admin: &Client,
298 name: &str,
299 password: &str,
300 roots: &[(&str, &str)],
301) -> serde_json::Value {
302 let roots_json: Vec<serde_json::Value> = roots
303 .iter()
304 .map(|(p, m)| serde_json::json!({ "path": p, "mode": m }))
305 .collect();
306 let r = admin
307 .post_json(
308 "/api/admin/users",
309 &serde_json::json!({
310 "name": name,
311 "password": password,
312 "is_admin": false,
313 "roots": roots_json,
314 }),
315 )
316 .await;
317 assert_eq!(r.status, StatusCode::OK, "create {name}: {}", r.text());
318 r.json()
319}
320
321/// Log in and return a signed-in client.
322pub async fn login(env: &Env, name: &str, password: &str) -> Client {
323 let c = Client::new(env.app.clone());
324 let r = c
325 .post_json(
326 "/api/auth/login",
327 &serde_json::json!({ "name": name, "password": password }),
328 )
329 .await;
330 assert_eq!(r.status, StatusCode::OK, "login {name}: {}", r.text());
331 let mut c = Client::new(env.app.clone());
332 c.set_cookie(&session_cookie(&r).unwrap());
333 c
334}
335
336/// Find a user id by name via the admin API.
337pub async fn user_id(admin: &Client, name: &str) -> i64 {
338 let r = admin.get("/api/admin/users").await;
339 assert_eq!(r.status, StatusCode::OK);
340 let j = r.json();
341 let users = j.as_array().unwrap();
342 users
343 .iter()
344 .find(|u| u["name"] == name)
345 .unwrap_or_else(|| panic!("user {name} not found"))
346 .as_object()
347 .unwrap()
348 .get("id")
349 .unwrap()
350 .as_i64()
351 .unwrap()
352}
353
354// ---------------------------------------------------------------------------
355// Helpers: multipart + archive readers
356// ---------------------------------------------------------------------------
357
358/// Build a minimal multipart/form-data body. Each part is a file whose
359/// `name` attribute is the (relative) target path — as the web client sends.
360pub fn multipart_body(parts: &[(&str, &[u8])], boundary: &str) -> (String, Vec<u8>) {
361 let mut buf = Vec::new();
362 for (name, content) in parts {
363 buf.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
364 buf.extend_from_slice(
365 format!("Content-Disposition: form-data; name=\"{name}\"\r\n").as_bytes(),
366 );
367 buf.extend_from_slice(b"Content-Type: application/octet-stream\r\n\r\n");
368 buf.extend_from_slice(content);
369 buf.extend_from_slice(b"\r\n");
370 }
371 buf.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
372 (format!("multipart/form-data; boundary={boundary}"), buf)
373}
374
375/// Read a zip into a name → content map (files only).
376pub fn zip_map(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
377 let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("valid zip archive");
378 let mut map = BTreeMap::new();
379 for i in 0..zip.len() {
380 let mut f = zip.by_index(i).unwrap();
381 let name = f.name().unwrap().to_string();
382 if name.ends_with('/') {
383 continue;
384 }
385 let mut buf = Vec::new();
386 std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
387 map.insert(name, buf);
388 }
389 map
390}
391
392/// Read a tar (optionally gz/zst compressed) into a name → content map.
393pub fn tar_map(raw: &[u8], compress: Compress) -> BTreeMap<String, Vec<u8>> {
394 let decompressed: Box<dyn std::io::Read> = match compress {
395 Compress::None => Box::new(std::io::Cursor::new(raw)),
396 Compress::Gz => Box::new(flate2::read::GzDecoder::new(std::io::Cursor::new(raw))),
397 Compress::Zst => {
398 Box::new(zstd::stream::read::Decoder::new(std::io::Cursor::new(raw)).unwrap())
399 }
400 };
401 let mut map = BTreeMap::new();
402 for entry in tar::Archive::new(decompressed).entries().unwrap() {
403 let mut e = entry.unwrap();
404 if !e.header().entry_type().is_file() {
405 continue;
406 }
407 let name = e.path().unwrap().to_string_lossy().into_owned();
408 let mut buf = Vec::new();
409 std::io::Read::read_to_end(&mut e, &mut buf).unwrap();
410 map.insert(name, buf);
411 }
412 map
413}
414
415pub enum Compress {
416 None,
417 Gz,
418 Zst,
419}
420