forge
Explore
Log in

Don't you dare go Hollow

in_old

Clone
★ 0

0 watching0 forksRustGPL-3.01.1 MiB218b775Tahinli2 months ago90 commits

http.rs6555 lines, 228.1 KiBHistoryRawDownload
1//! The drive driven the way a browser drives it: real router, real store,
2//! real session cookie, fake im.
3//!
4//! Auth in tests: the OIDC dance cannot run against a live im, so each test
5//! spins a fake one — a bare TCP server answering `POST /introspect` — and
6//! signs users in with `in_client::mint_session_cookie` (feature
7//! `test-seam`). The token<->claims map is per-test, so one test's session
8//! is meaningless to the next.
9//!
10//! New HTTP tests belong in this file rather than a new `tests/*.rs`: one
11//! test binary links and runs once.
12use http::{HeaderValue, Request, StatusCode, header};
13use http_body_util::BodyExt;
14use in_core::{Config, OidcConfig};
15use std::collections::HashMap;
16use std::path::PathBuf;
17use std::process::Command;
18use std::sync::{Arc, Mutex};
19
20use in_core::store::{ShareKind, Store, TursoStore};
21use in_web::server::App;
22use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};
23use topcoat::context::Cx;
24use topcoat::cookie::RouterBuilderCookieExt;
25use topcoat::router::{Body, BodyLimit, Router, RouterBuilderDiscoverExt, to_bytes};
26use topcoat::runtime::RouterBuilderRuntimeExt;
27use ulid::Ulid;
28
29/// The bundle `cargo build -p in-web` + `topcoat asset bundle --bin in-web`
30/// write next to the crate's own `target/debug`, not next to the test
31/// binary (which lives in `target/debug/deps`) — `AssetBundle::load` looks
32/// beside `current_exe` and would miss it, so the path is given explicitly
33/// instead.
34fn asset_dir() -> PathBuf {
35 PathBuf::from(concat!(
36 env!("CARGO_MANIFEST_DIR"),
37 "/../../target/debug/assets"
38 ))
39}
40
41/// Photos by file id: raw bytes plus mime, answered to `GET /photo/{id}`.
42type Photos = Arc<Mutex<HashMap<String, (Vec<u8>, String)>>>;
43
44/// A fake im: answers `POST /introspect` from its token map, `{"active":
45/// false}` for anything it does not know. Bare TCP + hand-rolled HTTP/1.1 —
46/// just enough for the client's form post.
47struct FakeIm {
48 addr: std::net::SocketAddr,
49 tokens: Arc<Mutex<HashMap<String, serde_json::Value>>>,
50 photos: Photos,
51 directory: Arc<Mutex<Vec<serde_json::Value>>>,
52 family: Arc<Mutex<Vec<serde_json::Value>>>,
53}
54
55impl FakeIm {
56 async fn spawn() -> Self {
57 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
58 let addr = listener.local_addr().unwrap();
59 let tokens: Arc<Mutex<HashMap<String, serde_json::Value>>> =
60 Arc::new(Mutex::new(HashMap::new()));
61 let photos: Photos = Arc::new(Mutex::new(HashMap::new()));
62 let directory: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
63 let family: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
64 let map = tokens.clone();
65 let pmap = photos.clone();
66 let dmap = directory.clone();
67 let fmap = family.clone();
68 tokio::spawn(async move {
69 loop {
70 let Ok((socket, _)) = listener.accept().await else {
71 return;
72 };
73 let map = map.clone();
74 let pmap = pmap.clone();
75 let dmap = dmap.clone();
76 let fmap = fmap.clone();
77 tokio::spawn(async move {
78 use tokio::io::{AsyncReadExt, AsyncWriteExt};
79 let mut socket = socket;
80 let mut buf = vec![0u8; 8192];
81 let mut req = Vec::new();
82 // One request after another on the same connection:
83 // closing it after every answer races the client's
84 // pool, which may hand out the dead socket for the
85 // next introspection and read that as signed-out.
86 loop {
87 let body_start = loop {
88 let Ok(n) = socket.read(&mut buf).await else {
89 return;
90 };
91 if n == 0 {
92 return;
93 }
94 req.extend_from_slice(&buf[..n]);
95 if let Some(end) = headers_end(&req) {
96 let head = String::from_utf8_lossy(&req[..end]).to_string();
97 let len = content_length(&head);
98 if req.len() >= end + len {
99 break end;
100 }
101 }
102 if req.len() > 1_000_000 {
103 return;
104 }
105 };
106 let head = String::from_utf8_lossy(&req[..body_start]).to_string();
107 let first = head.lines().next().unwrap_or("").to_string();
108 // The body may already hold the next pipelined
109 // request's first bytes; take exactly this one.
110 let len = content_length(&head);
111 let body: Vec<u8> = req[body_start..body_start + len].to_vec();
112 req.drain(..body_start + len);
113 let (status, content_type, payload) =
114 match photo_answer(&pmap, &head, &first) {
115 Some(photo) => photo,
116 None => match directory_answer(&dmap, &head, &first) {
117 Some(members) => members,
118 None => match family_answer(&fmap, &head, &first) {
119 Some(list) => list,
120 None => match answer_for(&map, &first, &body) {
121 Some(answer) => (
122 "200 OK",
123 "application/json".to_string(),
124 serde_json::to_vec(&answer).unwrap(),
125 ),
126 // Anything but the photo, directory
127 // and family routes is nothing at
128 // all, the way the real im 404s
129 // unknown paths rather than
130 // answering them.
131 None => (
132 "404 Not Found",
133 "text/plain".to_string(),
134 Vec::new(),
135 ),
136 },
137 },
138 },
139 };
140 let response = format!(
141 "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n",
142 payload.len()
143 );
144 if socket.write_all(response.as_bytes()).await.is_err() {
145 return;
146 }
147 if socket.write_all(&payload).await.is_err() {
148 return;
149 }
150 }
151 });
152 }
153 });
154 Self {
155 addr,
156 tokens,
157 photos,
158 directory,
159 family,
160 }
161 }
162
163 fn url(&self) -> String {
164 format!("http://{}", self.addr)
165 }
166
167 /// Stages the list `GET /family` answers with — the suite im keeps.
168 /// Unset, the route is simply not there, as for an app im has not
169 /// registered.
170 fn set_family(&self, list: Vec<serde_json::Value>) {
171 *self.family.lock().unwrap() = list;
172 }
173
174 /// Stores the photo `GET /photo/{user_id}` answers with — the bytes and
175 /// the mime im would serve for this account.
176 fn set_photo(&self, user_id: &str, bytes: Vec<u8>, mime: &str) {
177 self.photos
178 .lock()
179 .unwrap()
180 .insert(user_id.to_string(), (bytes, mime.to_string()));
181 }
182
183 /// Stages the members `GET /directory` answers with — the people im
184 /// knows. Unset, the route is simply not there, as for an app im has
185 /// not registered.
186 fn set_directory(&self, members: &[serde_json::Value]) {
187 *self.directory.lock().unwrap() = members.to_vec();
188 }
189}
190
191/// The Basic credential the app presents for `GET /photo/*` and
192/// `GET /directory`: `in-test:s3cr3t`.
193const APP_BASIC: &str = "Basic aW4tdGVzdDpzM2NyM3Q=";
194
195/// Answers `GET /photo/{id}` from the photo map — the app's Basic credential
196/// or nothing, a missing photo exactly like a missing person. `None` for
197/// anything else, which stays the introspection JSON.
198fn photo_answer(
199 photos: &Photos,
200 head: &str,
201 request_line: &str,
202) -> Option<(&'static str, String, Vec<u8>)> {
203 let mut parts = request_line.split_whitespace();
204 if parts.next() != Some("GET") {
205 return None;
206 }
207 let target = parts.next().unwrap_or("");
208 let path = target
209 .split_once('?')
210 .map(|(path, _)| path)
211 .unwrap_or(target);
212 let id = path.strip_prefix("/photo/")?;
213 if id.is_empty() || id.contains('/') {
214 return None;
215 }
216 let authed = head
217 .lines()
218 .filter_map(|line| line.split_once(':'))
219 .any(|(name, value)| {
220 name.trim().eq_ignore_ascii_case("authorization") && value.trim() == APP_BASIC
221 });
222 if !authed {
223 return Some(("404 Not Found", "text/plain".to_string(), Vec::new()));
224 }
225 match photos.lock().unwrap().get(id) {
226 Some((bytes, mime)) => Some(("200 OK", mime.clone(), bytes.clone())),
227 None => Some(("404 Not Found", "text/plain".to_string(), Vec::new())),
228 }
229}
230
231/// Answers `GET /directory` with the staged members — the app's Basic
232/// credential or nothing, and with nothing staged no route at all. `None`
233/// for anything else, which stays the introspection JSON.
234fn directory_answer(
235 directory: &Arc<Mutex<Vec<serde_json::Value>>>,
236 head: &str,
237 request_line: &str,
238) -> Option<(&'static str, String, Vec<u8>)> {
239 let mut parts = request_line.split_whitespace();
240 if parts.next() != Some("GET") {
241 return None;
242 }
243 let target = parts.next().unwrap_or("");
244 let path = target
245 .split_once('?')
246 .map(|(path, _)| path)
247 .unwrap_or(target);
248 if path != "/directory" {
249 return None;
250 }
251 let authed = head
252 .lines()
253 .filter_map(|line| line.split_once(':'))
254 .any(|(name, value)| {
255 name.trim().eq_ignore_ascii_case("authorization") && value.trim() == APP_BASIC
256 });
257 if !authed {
258 return Some(("404 Not Found", "text/plain".to_string(), Vec::new()));
259 }
260 let members = directory.lock().unwrap();
261 if members.is_empty() {
262 return Some(("404 Not Found", "text/plain".to_string(), Vec::new()));
263 }
264 Some((
265 "200 OK",
266 "application/json".to_string(),
267 serde_json::to_vec(&*members).unwrap(),
268 ))
269}
270
271/// Answers `GET /family` with the staged suite — the app's Basic credential
272/// or nothing, and with nothing staged no route at all. `None` for anything
273/// else, which falls through to the introspection JSON.
274fn family_answer(
275 family: &Arc<Mutex<Vec<serde_json::Value>>>,
276 head: &str,
277 request_line: &str,
278) -> Option<(&'static str, String, Vec<u8>)> {
279 let mut parts = request_line.split_whitespace();
280 if parts.next() != Some("GET") {
281 return None;
282 }
283 let target = parts.next().unwrap_or("");
284 let path = target
285 .split_once('?')
286 .map(|(path, _)| path)
287 .unwrap_or(target);
288 if path != "/family" {
289 return None;
290 }
291 let authed = head
292 .lines()
293 .filter_map(|line| line.split_once(':'))
294 .any(|(name, value)| {
295 name.trim().eq_ignore_ascii_case("authorization") && value.trim() == APP_BASIC
296 });
297 if !authed {
298 return Some(("404 Not Found", "text/plain".to_string(), Vec::new()));
299 }
300 let list = family.lock().unwrap();
301 if list.is_empty() {
302 return Some(("404 Not Found", "text/plain".to_string(), Vec::new()));
303 }
304 Some((
305 "200 OK",
306 "application/json".to_string(),
307 serde_json::to_vec(&*list).unwrap(),
308 ))
309}
310
311fn headers_end(req: &[u8]) -> Option<usize> {
312 req.windows(4)
313 .position(|w| w == b"\r\n\r\n")
314 .map(|pos| pos + 4)
315}
316
317fn content_length(head: &str) -> usize {
318 head.lines()
319 .find_map(|line| {
320 let (name, value) = line.split_once(':')?;
321 (name.trim().eq_ignore_ascii_case("content-length"))
322 .then(|| value.trim().parse().ok())?
323 })
324 .unwrap_or(0)
325}
326
327/// Percent-decoding, enough for the opaque tokens these tests mint.
328fn decode(raw: &str) -> String {
329 let mut out = String::with_capacity(raw.len());
330 let mut bytes = raw.as_bytes().iter();
331 while let Some(&b) = bytes.next() {
332 if b == b'+' {
333 out.push(' ');
334 } else if b == b'%' {
335 let hi = bytes.next().copied().unwrap_or(b'0');
336 let lo = bytes.next().copied().unwrap_or(b'0');
337 let hex = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8;
338 out.push((hex(hi) * 16 + hex(lo)) as char);
339 } else {
340 out.push(b as char);
341 }
342 }
343 out
344}
345fn answer_for(
346 map: &Arc<Mutex<HashMap<String, serde_json::Value>>>,
347 request_line: &str,
348 body: &[u8],
349) -> Option<serde_json::Value> {
350 let mut head = request_line.split_whitespace();
351 let is_introspect =
352 head.next() == Some("POST") && head.next() == Some(in_client::introspect_path());
353 if !is_introspect {
354 return None;
355 }
356 let text = String::from_utf8_lossy(body).to_string();
357 let token = text
358 .split('&')
359 .filter_map(|pair| pair.split_once('='))
360 .find(|(name, _)| *name == "token")
361 .map(|(_, value)| decode(value));
362 match token.and_then(|token| map.lock().unwrap().get(&token).cloned()) {
363 Some(claims) => Some(claims),
364 None => Some(serde_json::json!({"active": false})),
365 }
366}
367
368/// A throwaway workspace: its own database file, its own fake im, its own
369/// router.
370struct TestApp {
371 dir: PathBuf,
372 router: Router,
373 store: Arc<dyn Store>,
374 config: Config,
375 client: in_client::Config,
376 fake: FakeIm,
377 health: in_web::server::DirectoryHealth,
378 stop: tokio::sync::watch::Sender<bool>,
379}
380
381impl TestApp {
382 async fn build() -> Self {
383 Self::build_with(None, &[]).await
384 }
385
386 /// The same workspace with a config `base_url` set — the key that
387 /// decides where the public links are told to point — and an optional
388 /// family list, the suite the topbar's switcher links to, seeded the
389 /// way the background fetch files it: one JSON row in the `setting`
390 /// store under `family`.
391 async fn build_with(base_url: Option<&str>, family: &[(&str, &str, &str)]) -> Self {
392 let dir = std::env::temp_dir().join(format!("in-http-{}", Ulid::generate()));
393 std::fs::create_dir_all(&dir).unwrap();
394 let db = dir.join("in.db");
395 let storage = dir.join("storage");
396 let store: Arc<dyn Store> = Arc::new(
397 TursoStore::open(db.to_str().unwrap(), Some(storage.as_path()))
398 .await
399 .unwrap(),
400 );
401 if !family.is_empty() {
402 let list: Vec<in_client::ServiceJson> = family
403 .iter()
404 .map(|(key, name, url)| in_client::ServiceJson {
405 key: key.to_string(),
406 name: name.to_string(),
407 url: url.to_string(),
408 limit_bytes: None,
409 })
410 .collect();
411 store
412 .set_setting("family", &serde_json::to_string(&list).unwrap())
413 .await
414 .unwrap();
415 }
416 let fake = FakeIm::spawn().await;
417 let client = in_client::Config {
418 issuer: fake.url(),
419 client_id: "in-test".to_string(),
420 client_secret: "s3cr3t".to_string(),
421 redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
422 cookie_name: "in_session".to_string(),
423 cookie_key: [7u8; 32],
424 logout_back: "http://127.0.0.1:7655".to_string(),
425 };
426 let config = Config {
427 database: db.to_str().unwrap().to_string(),
428 storage,
429 listen: "127.0.0.1:7655".parse().unwrap(),
430 live_seconds: 300,
431 purge_after_days: 30,
432 default_quota_bytes: 10 * 1024 * 1024 * 1024,
433 base_url: base_url.map(str::to_string),
434 r2: None,
435 oidc: OidcConfig {
436 issuer: fake.url(),
437 client_id: "in-test".to_string(),
438 client_secret: "s3cr3t".to_string(),
439 redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
440 },
441 ignored: Vec::new(),
442 defaulted: false,
443 };
444 let (stop, stopping) = tokio::sync::watch::channel(false);
445 let health = in_web::server::DirectoryHealth::new();
446 let router = in_client::mount(
447 Router::builder()
448 .discover()
449 .runtime()
450 .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload"))
451 .layer(BodyLimit::max(512 * 1024 * 1024).at("/api/service/files"))
452 .cookies()
453 .assets(
454 AssetBundle::load_dir(asset_dir())
455 .expect("run `topcoat asset bundle` before the http suite"),
456 )
457 .trusted_proxies(in_web::server::trusted_proxies()),
458 client.clone(),
459 )
460 .app_context(App {
461 store: store.clone(),
462 config: config.clone(),
463 shutdown: in_web::live::Shutdown(stopping),
464 // Deliberately not the cookie key: the sealing helpers must
465 // reach for `link_key`, not for whatever key sits nearest.
466 link_key: [11u8; 32],
467 directory: im_client::directory::DirectoryClient::new(
468 fake.url(),
469 "in-test".to_string(),
470 "s3cr3t".to_string(),
471 ),
472 health: health.clone(),
473 })
474 .app_context(in_client::LogoutBack(Arc::new(|cx: &Cx| {
475 Box::pin(async move { Some(in_web::server::share_origin(cx).await) })
476 })))
477 .build();
478 Self {
479 dir,
480 router,
481 store,
482 config,
483 client,
484 fake,
485 health,
486 stop,
487 }
488 }
489
490 /// Provisions the row and mints a session for it, returning the `Cookie`
491 /// header value to send.
492 async fn sign_in(&self, sub: &str, email: &str, name: &str) -> String {
493 let user = self
494 .store
495 .provision_user(sub, email, name, None, 0, self.config.default_quota_bytes)
496 .await
497 .unwrap();
498 let token = format!("tok-{}", Ulid::generate());
499 let exp = time::OffsetDateTime::now_utc() + time::Duration::hours(1);
500 self.fake.tokens.lock().unwrap().insert(
501 token.clone(),
502 serde_json::json!({
503 "active": true,
504 "sub": user.oidc_sub,
505 "email": user.email,
506 "name": user.display_name,
507 "exp": exp.unix_timestamp(),
508 }),
509 );
510 let value = in_client::mint_session_cookie(&self.client, &token, exp);
511 format!("in_session={value}")
512 }
513
514 /// Posts a form the way a hydrated caller does: `Accept:
515 /// application/json`, no `Referer`. Every mutating `/api/*` route
516 /// answers `303 See Other` regardless — [`Router::handle`] never follows
517 /// a redirect, so the answer is read straight off this response.
518 async fn post(&self, path: &str, cookie: Option<&str>, form: &[(&str, &str)]) -> Answer {
519 let body = form
520 .iter()
521 .map(|(key, value)| format!("{}={}", encode(key), encode(value)))
522 .collect::<Vec<_>>()
523 .join("&");
524 let mut request = Request::builder()
525 .method("POST")
526 .uri(path)
527 .header(header::ACCEPT, "application/json")
528 .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
529 if let Some(cookie) = cookie {
530 request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
531 }
532 let response = self
533 .router
534 .handle(request.body(Body::from(body)).unwrap())
535 .await;
536 Answer::from_response(response).await
537 }
538
539 /// Posts JSON the way the upload script does.
540 async fn post_json(
541 &self,
542 path: &str,
543 cookie: Option<&str>,
544 value: serde_json::Value,
545 ) -> Answer {
546 let mut request = Request::builder()
547 .method("POST")
548 .uri(path)
549 .header(header::ACCEPT, "application/json")
550 .header(header::CONTENT_TYPE, "application/json");
551 if let Some(cookie) = cookie {
552 request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
553 }
554 let response = self
555 .router
556 .handle(request.body(Body::from(value.to_string())).unwrap())
557 .await;
558 Answer::from_response(response).await
559 }
560
561 /// Puts raw bytes the way the upload script sends one chunk.
562 async fn put_bytes(&self, path: &str, cookie: Option<&str>, bytes: &[u8]) -> Answer {
563 let mut request = Request::builder()
564 .method("PUT")
565 .uri(path)
566 .header(header::ACCEPT, "application/json")
567 .header(header::CONTENT_TYPE, "application/octet-stream");
568 if let Some(cookie) = cookie {
569 request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
570 }
571 let response = self
572 .router
573 .handle(request.body(Body::from(bytes.to_vec())).unwrap())
574 .await;
575 Answer::from_response(response).await
576 }
577
578 /// Posts a multipart form the way the drive's upload control does,
579 /// hand-built rather than pulling in a client crate for it: the fields
580 /// first, in the order given, then one `file` part per file.
581 async fn post_multipart(
582 &self,
583 path: &str,
584 cookie: Option<&str>,
585 fields: &[(&str, &str)],
586 files: &[(&str, &str, &[u8])],
587 ) -> Answer {
588 const BOUNDARY: &str = "in-test-boundary";
589 let mut body = Vec::new();
590 for (name, value) in fields {
591 body.extend_from_slice(
592 format!(
593 "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
594 )
595 .as_bytes(),
596 );
597 }
598 for (filename, content_type, bytes) in files {
599 body.extend_from_slice(
600 format!(
601 "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: {content_type}\r\n\r\n"
602 )
603 .as_bytes(),
604 );
605 body.extend_from_slice(bytes);
606 body.extend_from_slice(b"\r\n");
607 }
608 body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
609
610 let mut request = Request::builder().method("POST").uri(path).header(
611 header::CONTENT_TYPE,
612 format!("multipart/form-data; boundary={BOUNDARY}"),
613 );
614 if let Some(cookie) = cookie {
615 request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
616 }
617 let response = self
618 .router
619 .handle(request.body(Body::from(body)).unwrap())
620 .await;
621 Answer::from_response(response).await
622 }
623
624 /// Posts a multipart form with a bearer key, the way iz's storage client
625 /// pushes an attachment. Raw bytes back — the machine answer is JSON the
626 /// caller parses itself.
627 async fn post_service_multipart(
628 &self,
629 path: &str,
630 token: Option<&str>,
631 fields: &[(&str, &str)],
632 file: Option<(&str, &[u8])>,
633 ) -> Raw {
634 const BOUNDARY: &str = "in-test-boundary";
635 let mut body = Vec::new();
636 for (name, value) in fields {
637 body.extend_from_slice(
638 format!(
639 "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
640 )
641 .as_bytes(),
642 );
643 }
644 if let Some((filename, bytes)) = file {
645 body.extend_from_slice(
646 format!(
647 "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: application/octet-stream\r\n\r\n"
648 )
649 .as_bytes(),
650 );
651 body.extend_from_slice(bytes);
652 body.extend_from_slice(b"\r\n");
653 }
654 body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
655 let mut request = Request::builder().method("POST").uri(path).header(
656 header::CONTENT_TYPE,
657 format!("multipart/form-data; boundary={BOUNDARY}"),
658 );
659 if let Some(token) = token {
660 request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
661 }
662 let response = self
663 .router
664 .handle(request.body(Body::from(body)).unwrap())
665 .await;
666 Raw::from_response(response).await
667 }
668
669 /// A machine GET with (maybe) a bearer key.
670 async fn get_bearer(&self, path: &str, token: Option<&str>) -> Raw {
671 let mut request = Request::builder().method("GET").uri(path);
672 if let Some(token) = token {
673 request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
674 }
675 let response = self
676 .router
677 .handle(request.body(Body::empty()).unwrap())
678 .await;
679 Raw::from_response(response).await
680 }
681
682 /// A machine DELETE with (maybe) a bearer key.
683 async fn delete_bearer(&self, path: &str, token: Option<&str>) -> Raw {
684 let mut request = Request::builder().method("DELETE").uri(path);
685 if let Some(token) = token {
686 request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
687 }
688 let response = self
689 .router
690 .handle(request.body(Body::empty()).unwrap())
691 .await;
692 Raw::from_response(response).await
693 }
694
695 /// Gets a page or a download the way a browser does, raw bytes back
696 /// untouched — a download's body is not always UTF-8.
697 async fn get(&self, path: &str, cookie: Option<&str>) -> Raw {
698 self.get_with(path, cookie, None, None).await
699 }
700
701 /// Like `get`, but with a `Range` header, for the partial-content path.
702 async fn get_with_range(&self, path: &str, cookie: Option<&str>, range: &str) -> Raw {
703 self.get_with(path, cookie, Some(range), None).await
704 }
705
706 /// Like `get`, but with `If-None-Match`, for the thumbnail revalidate
707 /// path.
708 async fn get_with_if_none_match(&self, path: &str, cookie: Option<&str>, etag: &str) -> Raw {
709 self.get_with(path, cookie, None, Some(etag)).await
710 }
711
712 async fn get_with(
713 &self,
714 path: &str,
715 cookie: Option<&str>,
716 range: Option<&str>,
717 if_none_match: Option<&str>,
718 ) -> Raw {
719 let mut request = Request::builder().method("GET").uri(path);
720 if let Some(cookie) = cookie {
721 request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
722 }
723 if let Some(range) = range {
724 request = request.header(header::RANGE, range);
725 }
726 if let Some(if_none_match) = if_none_match {
727 request = request.header(header::IF_NONE_MATCH, if_none_match);
728 }
729 let response = self
730 .router
731 .handle(request.body(Body::empty()).unwrap())
732 .await;
733 let status = response.status();
734 let headers = response.headers().clone();
735 let header = |name| {
736 headers
737 .get(name)
738 .and_then(|value| value.to_str().ok())
739 .map(str::to_string)
740 };
741 let bytes = to_bytes(response.into_body(), usize::MAX)
742 .await
743 .unwrap()
744 .to_vec();
745 Raw {
746 status,
747 content_type: header(header::CONTENT_TYPE),
748 disposition: header(header::CONTENT_DISPOSITION),
749 content_range: header(header::CONTENT_RANGE),
750 accept_ranges: header(header::ACCEPT_RANGES),
751 cache_control: header(header::CACHE_CONTROL),
752 etag: header(header::ETAG),
753 location: header(header::LOCATION),
754 bytes,
755 }
756 }
757}
758
759impl Drop for TestApp {
760 fn drop(&mut self) {
761 let _ = self.stop.send(true);
762 let _ = std::fs::remove_dir_all(&self.dir);
763 }
764}
765/// A mutating call's answer: always a 303, carrying the refusal (or its
766/// absence) as JSON — the same body a hydrated caller reads.
767struct Answer {
768 status: StatusCode,
769 body: String,
770 location: Option<String>,
771 set_cookie: Option<String>,
772}
773
774impl Answer {
775 async fn from_response(response: topcoat::router::response::Response) -> Self {
776 let status = response.status();
777 let location = response
778 .headers()
779 .get(header::LOCATION)
780 .and_then(|value| value.to_str().ok())
781 .map(str::to_string);
782 let set_cookie = response
783 .headers()
784 .get(header::SET_COOKIE)
785 .and_then(|value| value.to_str().ok())
786 .map(str::to_string);
787 let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
788 Answer {
789 status,
790 location,
791 set_cookie,
792 body: String::from_utf8(bytes.to_vec()).unwrap(),
793 }
794 }
795
796 fn json(&self) -> serde_json::Value {
797 serde_json::from_str(&self.body).unwrap()
798 }
799
800 fn refused(&self, code: &str, call: &str) -> bool {
801 self.status == StatusCode::SEE_OTHER
802 && self.location.as_deref().is_some_and(|location| {
803 location.contains(&format!("refusal={code}"))
804 && location.contains(&format!("on={call}"))
805 })
806 }
807
808 fn accepted(&self) -> bool {
809 self.status == StatusCode::SEE_OTHER
810 && self
811 .location
812 .as_deref()
813 .is_some_and(|location| !location.contains("refusal="))
814 }
815}
816
817/// A GET answer kept as raw bytes: a page's HTML or a download's file.
818struct Raw {
819 status: StatusCode,
820 content_type: Option<String>,
821 disposition: Option<String>,
822 content_range: Option<String>,
823 accept_ranges: Option<String>,
824 cache_control: Option<String>,
825 etag: Option<String>,
826 location: Option<String>,
827 bytes: Vec<u8>,
828}
829
830impl Raw {
831 async fn from_response(response: topcoat::router::response::Response) -> Self {
832 let status = response.status();
833 let headers = response.headers().clone();
834 let header = |name| {
835 headers
836 .get(name)
837 .and_then(|value| value.to_str().ok())
838 .map(str::to_string)
839 };
840 let bytes = to_bytes(response.into_body(), usize::MAX)
841 .await
842 .unwrap()
843 .to_vec();
844 Raw {
845 status,
846 content_type: header(header::CONTENT_TYPE),
847 disposition: header(header::CONTENT_DISPOSITION),
848 content_range: header(header::CONTENT_RANGE),
849 accept_ranges: header(header::ACCEPT_RANGES),
850 cache_control: header(header::CACHE_CONTROL),
851 etag: header(header::ETAG),
852 location: header(header::LOCATION),
853 bytes,
854 }
855 }
856}
857impl Raw {
858 fn text(&self) -> String {
859 String::from_utf8(self.bytes.clone()).unwrap()
860 }
861
862 fn json(&self) -> serde_json::Value {
863 serde_json::from_str(&self.text()).unwrap()
864 }
865}
866
867/// Form encoding, enough for the names these tests send.
868fn encode(raw: &str) -> String {
869 let mut out = String::with_capacity(raw.len());
870 for byte in raw.bytes() {
871 match byte {
872 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
873 out.push(byte as char)
874 }
875 b' ' => out.push('+'),
876 other => out.push_str(&format!("%{other:02X}")),
877 }
878 }
879 out
880}
881
882/// The 1x1 transparent PNG: the smallest thing the thumbnailer must accept.
883fn tiny_png() -> Vec<u8> {
884 vec![
885 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44,
886 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F,
887 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00,
888 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49,
889 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
890 ]
891}
892
893/// The newest live folder with this name under this parent, read straight
894/// off the store.
895async fn folder_id(app: &TestApp, owner: &str, parent: Option<&str>, name: &str) -> String {
896 app.store
897 .list_children(owner, parent)
898 .await
899 .unwrap()
900 .folders
901 .iter()
902 .find(|folder| folder.name == name)
903 .expect("folder was not created")
904 .id
905 .clone()
906}
907/// The token off a creation redirect's `?created=` pair.
908fn created_token(location: &str) -> String {
909 let query = location
910 .split_once('?')
911 .map(|(_, query)| query)
912 .unwrap_or("");
913 query
914 .split('&')
915 .filter_map(|pair| pair.split_once('='))
916 .find(|(name, _)| *name == "created")
917 .map(|(_, value)| value.to_string())
918 .expect("creation set no token")
919}
920
921async fn file_id(app: &TestApp, owner: &str, name: &str, bytes: &[u8]) -> String {
922 app.store
923 .insert_file(owner, None, name, bytes)
924 .await
925 .unwrap()
926 .id
927}
928
929async fn owner_of(app: &TestApp, sub: &str) -> String {
930 app.store
931 .provision_user(sub, "x@y.z", "X", None, 0, app.config.default_quota_bytes)
932 .await
933 .unwrap()
934 .id
935}
936
937#[tokio::test]
938async fn drive_redirects_without_session() {
939 let app = TestApp::build().await;
940 let page = app.get("/drive", None).await;
941 assert_eq!(page.status, StatusCode::SEE_OTHER);
942 assert_eq!(page.location.as_deref(), Some("/"));
943}
944
945#[tokio::test]
946async fn folder_crud_and_cycle_is_refused() {
947 let app = TestApp::build().await;
948 let cookie = app.sign_in("sub-crud", "crud@in.test", "Crud").await;
949 let user = app
950 .store
951 .user_by_oidc_sub("sub-crud")
952 .await
953 .unwrap()
954 .unwrap();
955
956 let answer = app
957 .post(
958 "/api/folder/create",
959 Some(&cookie),
960 &[("parent_id", ""), ("name", "projects")],
961 )
962 .await;
963 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
964 assert_eq!(answer.body, "null", "creating was refused");
965
966 let projects = folder_id(&app, &user.id, None, "projects").await;
967 let answer = app
968 .post(
969 "/api/folder/create",
970 Some(&cookie),
971 &[("parent_id", &projects), ("name", "sub")],
972 )
973 .await;
974 assert_eq!(answer.body, "null", "creating was refused");
975 let sub = folder_id(&app, &user.id, Some(&projects), "sub").await;
976
977 // Nesting `projects` inside its own descendant is refused, not looped.
978 let answer = app
979 .post(
980 "/api/folder/move",
981 Some(&cookie),
982 &[("id", &projects), ("parent_id", &sub)],
983 )
984 .await;
985 assert_eq!(answer.status, StatusCode::SEE_OTHER);
986 assert!(
987 answer.body.contains("Forbidden"),
988 "cycle was not refused: {}",
989 answer.body
990 );
991
992 // A legal move, a rename and a delete all land clean.
993 let answer = app
994 .post(
995 "/api/folder/move",
996 Some(&cookie),
997 &[("id", &sub), ("parent_id", "")],
998 )
999 .await;
1000 assert_eq!(answer.body, "null", "moving was refused: {}", answer.body);
1001 let answer = app
1002 .post(
1003 "/api/folder/rename",
1004 Some(&cookie),
1005 &[("id", &sub), ("name", "moved")],
1006 )
1007 .await;
1008 assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body);
1009 let answer = app
1010 .post("/api/folder/delete", Some(&cookie), &[("id", &sub)])
1011 .await;
1012 assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body);
1013
1014 // The drive page names what is left.
1015 let page = app.get("/drive", Some(&cookie)).await;
1016 assert_eq!(page.status, StatusCode::OK);
1017 assert!(page.text().contains("projects"), "drive hides the folder");
1018}
1019
1020#[tokio::test]
1021async fn small_upload_round_trip() {
1022 let app = TestApp::build().await;
1023 let cookie = app.sign_in("sub-small", "small@in.test", "Small").await;
1024 let user = app
1025 .store
1026 .user_by_oidc_sub("sub-small")
1027 .await
1028 .unwrap()
1029 .unwrap();
1030
1031 let bytes = b"hello in";
1032 let answer = app
1033 .post_multipart(
1034 "/files",
1035 Some(&cookie),
1036 &[("folder_id", "")],
1037 &[("hello.txt", "text/plain", bytes)],
1038 )
1039 .await;
1040 assert_eq!(
1041 answer.status,
1042 StatusCode::SEE_OTHER,
1043 "{}",
1044 answer.location.unwrap_or_default()
1045 );
1046 assert!(
1047 !answer
1048 .location
1049 .as_deref()
1050 .unwrap_or("")
1051 .contains("refusal="),
1052 "upload was refused: {}",
1053 answer.location.unwrap_or_default()
1054 );
1055
1056 let file = app
1057 .store
1058 .list_children(&user.id, None)
1059 .await
1060 .unwrap()
1061 .files
1062 .into_iter()
1063 .find(|file| file.name == "hello.txt")
1064 .expect("file was not stored");
1065 assert_eq!(file.mime, "text/plain");
1066
1067 let got = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1068 assert_eq!(got.status, StatusCode::OK);
1069 assert_eq!(got.bytes, bytes);
1070 assert_eq!(got.accept_ranges.as_deref(), Some("bytes"));
1071 assert!(
1072 got.cache_control
1073 .as_deref()
1074 .unwrap_or("")
1075 .contains("immutable"),
1076 "missing immutable cache directive"
1077 );
1078}
1079
1080#[tokio::test]
1081async fn chunked_upload_round_trip() {
1082 let app = TestApp::build().await;
1083 let cookie = app.sign_in("sub-chunk", "chunk@in.test", "Chunk").await;
1084 let user = app
1085 .store
1086 .user_by_oidc_sub("sub-chunk")
1087 .await
1088 .unwrap()
1089 .unwrap();
1090
1091 // Two chunks: the 8 MiB server size plus a tail, so the finish assembles
1092 // more than one staged piece.
1093 let total = 8 * 1024 * 1024 + 100;
1094 let mut bytes = Vec::with_capacity(total);
1095 for i in 0..total {
1096 bytes.push((i % 251) as u8);
1097 }
1098
1099 let answer = app
1100 .post_json(
1101 "/api/upload/start",
1102 Some(&cookie),
1103 serde_json::json!({"folder_id": null, "name": "big.bin", "size_bytes": total}),
1104 )
1105 .await;
1106 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
1107 let started = answer.json();
1108 let session = started["ok"]["id"]
1109 .as_str()
1110 .expect("start was refused")
1111 .to_string();
1112 assert_eq!(started["ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024));
1113
1114 let answer = app
1115 .put_bytes(
1116 &format!("/api/upload/{session}/0"),
1117 Some(&cookie),
1118 &bytes[..8 * 1024 * 1024],
1119 )
1120 .await;
1121 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
1122 assert_eq!(
1123 answer.json()["ok"]["received_bytes"].as_u64(),
1124 Some(8 * 1024 * 1024)
1125 );
1126
1127 let answer = app
1128 .put_bytes(
1129 &format!("/api/upload/{session}/1"),
1130 Some(&cookie),
1131 &bytes[8 * 1024 * 1024..],
1132 )
1133 .await;
1134 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
1135 assert_eq!(
1136 answer.json()["ok"]["received_bytes"].as_u64(),
1137 Some(total as u64)
1138 );
1139
1140 let answer = app
1141 .post_json(
1142 &format!("/api/upload/{session}/finish"),
1143 Some(&cookie),
1144 serde_json::json!({}),
1145 )
1146 .await;
1147 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
1148 let file_id = answer.json()["ok"]
1149 .as_str()
1150 .expect("finish was refused")
1151 .to_string();
1152
1153 let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await;
1154 assert_eq!(got.status, StatusCode::OK);
1155 assert_eq!(got.bytes, bytes);
1156
1157 let row = app.store.file(&file_id).await.unwrap().unwrap();
1158 assert_eq!(row.owner_id, user.id);
1159}
1160
1161#[tokio::test]
1162async fn an_interrupted_upload_resumes_from_its_staged_chunks() {
1163 let app = TestApp::build().await;
1164 let cookie = app.sign_in("sub-resume", "resume@in.test", "Resume").await;
1165
1166 // Two chunks: stage the first, ask the status what a resume may skip,
1167 // then land the second and finish.
1168 let total = 8 * 1024 * 1024 + 100;
1169 let mut bytes = Vec::with_capacity(total);
1170 for i in 0..total {
1171 bytes.push((i % 251) as u8);
1172 }
1173 let answer = app
1174 .post_json(
1175 "/api/upload/start",
1176 Some(&cookie),
1177 serde_json::json!({"folder_id": null, "name": "resume.bin", "size_bytes": total}),
1178 )
1179 .await;
1180 let session = answer.json()["ok"]["id"]
1181 .as_str()
1182 .expect("start was refused")
1183 .to_string();
1184
1185 app.put_bytes(
1186 &format!("/api/upload/{session}/0"),
1187 Some(&cookie),
1188 &bytes[..8 * 1024 * 1024],
1189 )
1190 .await;
1191
1192 let status = app
1193 .get(&format!("/api/upload/{session}"), Some(&cookie))
1194 .await;
1195 assert_eq!(status.status, StatusCode::OK, "{}", status.text());
1196 let body = status.json();
1197 assert_eq!(body["ok"]["size_bytes"].as_u64(), Some(total as u64));
1198 assert_eq!(body["ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024));
1199 assert_eq!(body["ok"]["name"].as_str(), Some("resume.bin"));
1200 assert_eq!(body["ok"]["uploaded"], serde_json::json!([0]));
1201
1202 // Another owner's probe of the same id is not found, not forbidden.
1203 let other = app.sign_in("sub-nosey", "nosey@in.test", "Nosey").await;
1204 let status = app
1205 .get(&format!("/api/upload/{session}"), Some(&other))
1206 .await;
1207 assert_eq!(status.json()["err"].as_str(), Some("NotFound"));
1208
1209 app.put_bytes(
1210 &format!("/api/upload/{session}/1"),
1211 Some(&cookie),
1212 &bytes[8 * 1024 * 1024..],
1213 )
1214 .await;
1215 let answer = app
1216 .post_json(
1217 &format!("/api/upload/{session}/finish"),
1218 Some(&cookie),
1219 serde_json::json!({}),
1220 )
1221 .await;
1222 let file_id = answer.json()["ok"]
1223 .as_str()
1224 .expect("finish was refused")
1225 .to_string();
1226 let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await;
1227 assert_eq!(got.bytes, bytes);
1228}
1229#[tokio::test]
1230async fn range_request_serves_a_slice() {
1231 let app = TestApp::build().await;
1232 let cookie = app.sign_in("sub-range", "range@in.test", "Range").await;
1233 let user = app
1234 .store
1235 .user_by_oidc_sub("sub-range")
1236 .await
1237 .unwrap()
1238 .unwrap();
1239
1240 let bytes = b"hello in";
1241 app.post_multipart(
1242 "/files",
1243 Some(&cookie),
1244 &[("folder_id", "")],
1245 &[("hello.txt", "text/plain", bytes)],
1246 )
1247 .await;
1248 let file = app
1249 .store
1250 .list_children(&user.id, None)
1251 .await
1252 .unwrap()
1253 .files
1254 .into_iter()
1255 .next()
1256 .unwrap();
1257
1258 let slice = app
1259 .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=0-4")
1260 .await;
1261 assert_eq!(slice.status, StatusCode::PARTIAL_CONTENT);
1262 assert_eq!(slice.bytes, b"hello");
1263 assert_eq!(slice.content_range.as_deref(), Some("bytes 0-4/8"));
1264
1265 let past_end = app
1266 .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=99-")
1267 .await;
1268 assert_eq!(past_end.status, StatusCode::RANGE_NOT_SATISFIABLE);
1269}
1270
1271#[tokio::test]
1272async fn quota_is_refused_before_and_during_upload() {
1273 let app = TestApp::build().await;
1274 let cookie = app.sign_in("sub-quota", "quota@in.test", "Quota").await;
1275 let user = app
1276 .store
1277 .user_by_oidc_sub("sub-quota")
1278 .await
1279 .unwrap()
1280 .unwrap();
1281 app.store.set_user_quota(&user.id, 10).await.unwrap();
1282
1283 let answer = app
1284 .post_json(
1285 "/api/upload/start",
1286 Some(&cookie),
1287 serde_json::json!({"folder_id": null, "name": "too-big.bin", "size_bytes": 100}),
1288 )
1289 .await;
1290 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
1291 assert_eq!(
1292 answer.json()["err"].as_str(),
1293 Some("QuotaExceeded"),
1294 "start was not refused: {}",
1295 answer.body
1296 );
1297
1298 let answer = app
1299 .post_multipart(
1300 "/files",
1301 Some(&cookie),
1302 &[("folder_id", "")],
1303 &[("twenty.txt", "text/plain", b"12345678901234567890")],
1304 )
1305 .await;
1306 assert_eq!(answer.status, StatusCode::SEE_OTHER);
1307 let location = answer.location.unwrap_or_default();
1308 assert!(
1309 location.contains("quota-exceeded"),
1310 "small upload was not refused: {location}"
1311 );
1312}
1313
1314#[tokio::test]
1315async fn thumbnail_is_served_after_image_upload() {
1316 let app = TestApp::build().await;
1317 let cookie = app.sign_in("sub-thumb", "thumb@in.test", "Thumb").await;
1318 let user = app
1319 .store
1320 .user_by_oidc_sub("sub-thumb")
1321 .await
1322 .unwrap()
1323 .unwrap();
1324
1325 let png = tiny_png();
1326 let answer = app
1327 .post_multipart(
1328 "/files",
1329 Some(&cookie),
1330 &[("folder_id", "")],
1331 &[("dot.png", "image/png", &png)],
1332 )
1333 .await;
1334 assert!(
1335 !answer
1336 .location
1337 .as_deref()
1338 .unwrap_or("")
1339 .contains("refusal="),
1340 "image upload was refused: {}",
1341 answer.location.unwrap_or_default()
1342 );
1343 let file = app
1344 .store
1345 .list_children(&user.id, None)
1346 .await
1347 .unwrap()
1348 .files
1349 .into_iter()
1350 .find(|file| file.name == "dot.png")
1351 .expect("image was not stored");
1352 assert_eq!(file.mime, "image/png");
1353
1354 let thumb = app.get(&format!("/thumb/{}", file.id), Some(&cookie)).await;
1355 assert_eq!(thumb.status, StatusCode::OK, "no thumbnail served");
1356 assert_eq!(thumb.content_type.as_deref(), Some("image/webp"));
1357 assert_eq!(&thumb.bytes[0..4], b"RIFF");
1358 assert_eq!(&thumb.bytes[8..12], b"WEBP");
1359
1360 let etag = thumb.etag.clone().expect("no etag on the thumbnail");
1361 let cached = app
1362 .get_with_if_none_match(&format!("/thumb/{}", file.id), Some(&cookie), &etag)
1363 .await;
1364 assert_eq!(cached.status, StatusCode::NOT_MODIFIED);
1365}
1366
1367#[tokio::test]
1368async fn cross_owner_answers_not_found() {
1369 let app = TestApp::build().await;
1370 let alice = app.sign_in("sub-alice", "alice@in.test", "Alice").await;
1371 let alice_user = app
1372 .store
1373 .user_by_oidc_sub("sub-alice")
1374 .await
1375 .unwrap()
1376 .unwrap();
1377 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
1378
1379 app.post(
1380 "/api/folder/create",
1381 Some(&alice),
1382 &[("parent_id", ""), ("name", "hers")],
1383 )
1384 .await;
1385 let hers = folder_id(&app, &alice_user.id, None, "hers").await;
1386 app.post_multipart(
1387 "/files",
1388 Some(&alice),
1389 &[("folder_id", "")],
1390 &[("hers.txt", "text/plain", b"hers")],
1391 )
1392 .await;
1393 let file = app
1394 .store
1395 .list_children(&alice_user.id, None)
1396 .await
1397 .unwrap()
1398 .files
1399 .into_iter()
1400 .next()
1401 .unwrap();
1402
1403 let bytes = app.get(&format!("/file/{}", file.id), Some(&bob)).await;
1404 assert_eq!(bytes.status, StatusCode::NOT_FOUND);
1405 let thumb = app.get(&format!("/thumb/{}", file.id), Some(&bob)).await;
1406 assert_eq!(thumb.status, StatusCode::NOT_FOUND);
1407 let page = app.get(&format!("/drive?folder={hers}"), Some(&bob)).await;
1408 assert_eq!(page.status, StatusCode::NOT_FOUND);
1409
1410 let answer = app
1411 .post(
1412 "/api/folder/rename",
1413 Some(&bob),
1414 &[("id", &hers), ("name", "theirs")],
1415 )
1416 .await;
1417 assert!(
1418 answer.body.contains("NotFound"),
1419 "cross-owner write was not refused as not-found: {}",
1420 answer.body
1421 );
1422 let answer = app
1423 .post("/api/file/delete", Some(&bob), &[("id", &file.id)])
1424 .await;
1425 assert!(
1426 answer.body.contains("NotFound"),
1427 "cross-owner delete was not refused as not-found: {}",
1428 answer.body
1429 );
1430}
1431
1432#[tokio::test]
1433async fn file_rename_move_and_delete() {
1434 let app = TestApp::build().await;
1435 let cookie = app.sign_in("sub-fops", "fops@in.test", "Fops").await;
1436 let user = app
1437 .store
1438 .user_by_oidc_sub("sub-fops")
1439 .await
1440 .unwrap()
1441 .unwrap();
1442
1443 app.post(
1444 "/api/folder/create",
1445 Some(&cookie),
1446 &[("parent_id", ""), ("name", "box")],
1447 )
1448 .await;
1449 let boxed = folder_id(&app, &user.id, None, "box").await;
1450 app.post_multipart(
1451 "/files",
1452 Some(&cookie),
1453 &[("folder_id", "")],
1454 &[("note.txt", "text/plain", b"note")],
1455 )
1456 .await;
1457 let file = app
1458 .store
1459 .list_children(&user.id, None)
1460 .await
1461 .unwrap()
1462 .files
1463 .into_iter()
1464 .next()
1465 .unwrap();
1466
1467 let answer = app
1468 .post(
1469 "/api/file/rename",
1470 Some(&cookie),
1471 &[("id", &file.id), ("name", "renamed.txt")],
1472 )
1473 .await;
1474 assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body);
1475 let answer = app
1476 .post(
1477 "/api/file/move",
1478 Some(&cookie),
1479 &[("id", &file.id), ("folder_id", &boxed)],
1480 )
1481 .await;
1482 assert_eq!(answer.body, "null", "moving was refused: {}", answer.body);
1483 let moved = app.store.file(&file.id).await.unwrap().unwrap();
1484 assert_eq!(moved.name, "renamed.txt");
1485 assert_eq!(moved.folder_id.as_deref(), Some(boxed.as_str()));
1486
1487 let answer = app
1488 .post("/api/file/delete", Some(&cookie), &[("id", &file.id)])
1489 .await;
1490 assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body);
1491 let trashed = app.store.file(&file.id).await.unwrap().unwrap();
1492 assert!(
1493 trashed.deleted_at.is_some(),
1494 "delete did not trash the file"
1495 );
1496 // Trashed bytes still serve the owner's preview inline — only the
1497 // taking is dead until the row is restored.
1498 let preview = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1499 assert_eq!(preview.status, StatusCode::OK);
1500 let forced = app
1501 .get(&format!("/file/{}?dl=1", file.id), Some(&cookie))
1502 .await;
1503 assert_eq!(forced.status, StatusCode::NOT_FOUND);
1504}
1505
1506/// A trashed file previews for its owner: the trash's row opens the
1507/// viewer, the back link names the trash, the bytes serve inline while
1508/// `?dl=1` stays dead — and a stranger, grant or no grant, sees nothing.
1509#[tokio::test]
1510async fn trashed_file_previews_for_its_owner() {
1511 let app = TestApp::build().await;
1512 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1513 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
1514 let owner = owner_of(&app, "sub-admin").await;
1515 let file = file_id(&app, &owner, "gone.png", b"\x89PNG\r\n\x1a\n gone").await;
1516
1517 let answer = app
1518 .post("/api/file/delete", Some(&admin), &[("id", &file)])
1519 .await;
1520 assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body);
1521
1522 // The trash's file row opens the preview; the folder rows beside it
1523 // stay facts.
1524 let shelf = app.get("/trash", Some(&admin)).await;
1525 assert_eq!(shelf.status, StatusCode::OK, "{}", shelf.text());
1526 assert!(
1527 shelf.text().contains(&format!("/view/{file}")),
1528 "{}",
1529 shelf.text()
1530 );
1531
1532 // The viewer names the trash as the way back and shows the media,
1533 // but offers no download for a trashed row.
1534 let page = app.get(&format!("/view/{file}"), Some(&admin)).await;
1535 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1536 assert!(page.text().contains("Back to trash"), "{}", page.text());
1537 assert!(page.text().contains("viewer-media"), "{}", page.text());
1538 assert!(!page.text().contains("?dl=1"), "{}", page.text());
1539
1540 // Inline bytes serve the owner's preview, taking stays dead, and a
1541 // stranger sees the same nothing a missing id would show.
1542 let inline = app.get(&format!("/file/{file}"), Some(&admin)).await;
1543 assert_eq!(inline.status, StatusCode::OK, "{}", inline.text());
1544 let forced = app.get(&format!("/file/{file}?dl=1"), Some(&admin)).await;
1545 assert_eq!(forced.status, StatusCode::NOT_FOUND);
1546 let stranger = app.get(&format!("/view/{file}"), Some(&bob)).await;
1547 assert_eq!(stranger.status, StatusCode::NOT_FOUND);
1548}
1549
1550#[tokio::test]
1551async fn upload_abort_and_bad_chunk() {
1552 let app = TestApp::build().await;
1553 let cookie = app.sign_in("sub-abort", "abort@in.test", "Abort").await;
1554
1555 let answer = app
1556 .post_json(
1557 "/api/upload/start",
1558 Some(&cookie),
1559 serde_json::json!({"folder_id": null, "name": "never.bin", "size_bytes": 100}),
1560 )
1561 .await;
1562 let session = answer.json()["ok"]["id"].as_str().unwrap().to_string();
1563
1564 // A short piece is a bad chunk, not a short file.
1565 let answer = app
1566 .put_bytes(&format!("/api/upload/{session}/0"), Some(&cookie), b"short")
1567 .await;
1568 assert_eq!(
1569 answer.json()["err"].as_str(),
1570 Some("BadChunk"),
1571 "short chunk was not refused: {}",
1572 answer.body
1573 );
1574
1575 let answer = app
1576 .post_json(
1577 &format!("/api/upload/{session}/abort"),
1578 Some(&cookie),
1579 serde_json::json!({}),
1580 )
1581 .await;
1582 assert_eq!(
1583 answer.json()["ok"],
1584 serde_json::Value::Null,
1585 "{}",
1586 answer.body
1587 );
1588
1589 // The finish after the abort finds an expired session, with the chunks
1590 // still staged for nothing.
1591 let answer = app
1592 .post_json(
1593 &format!("/api/upload/{session}/finish"),
1594 Some(&cookie),
1595 serde_json::json!({}),
1596 )
1597 .await;
1598 assert_eq!(
1599 answer.json()["err"].as_str(),
1600 Some("UploadExpired"),
1601 "finish after abort was not refused: {}",
1602 answer.body
1603 );
1604}
1605
1606#[tokio::test]
1607async fn forced_download_is_attachment() {
1608 let app = TestApp::build().await;
1609 let cookie = app.sign_in("sub-dl", "dl@in.test", "Dl").await;
1610 let user = app.store.user_by_oidc_sub("sub-dl").await.unwrap().unwrap();
1611
1612 app.post_multipart(
1613 "/files",
1614 Some(&cookie),
1615 &[("folder_id", "")],
1616 &[("readme.txt", "text/plain", b"read me")],
1617 )
1618 .await;
1619 let file = app
1620 .store
1621 .list_children(&user.id, None)
1622 .await
1623 .unwrap()
1624 .files
1625 .into_iter()
1626 .next()
1627 .unwrap();
1628
1629 let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1630 assert!(
1631 inline
1632 .disposition
1633 .as_deref()
1634 .unwrap_or("")
1635 .starts_with("inline"),
1636 "text should render inline: {:?}",
1637 inline.disposition
1638 );
1639 let forced = app
1640 .get(&format!("/file/{}?dl=1", file.id), Some(&cookie))
1641 .await;
1642 assert_eq!(forced.status, StatusCode::OK);
1643 assert!(
1644 forced
1645 .disposition
1646 .as_deref()
1647 .unwrap_or("")
1648 .starts_with("attachment"),
1649 "?dl=1 did not force attachment: {:?}",
1650 forced.disposition
1651 );
1652 assert_eq!(forced.bytes, b"read me");
1653}
1654
1655/// Looking is not downloading: the viewer's inline serves — the plain GET
1656/// and a media element's range probe from byte 0 — never move the counter;
1657/// only the `?dl=1` disposition does, once per download.
1658#[tokio::test]
1659async fn previews_do_not_count_as_downloads() {
1660 let app = TestApp::build().await;
1661 let cookie = app.sign_in("sub-prev", "prev@in.test", "Prev").await;
1662 let user = app
1663 .store
1664 .user_by_oidc_sub("sub-prev")
1665 .await
1666 .unwrap()
1667 .unwrap();
1668
1669 app.post_multipart(
1670 "/files",
1671 Some(&cookie),
1672 &[("folder_id", "")],
1673 &[("clip.txt", "text/plain", b"counted only when taken")],
1674 )
1675 .await;
1676 let file = app
1677 .store
1678 .list_children(&user.id, None)
1679 .await
1680 .unwrap()
1681 .files
1682 .into_iter()
1683 .next()
1684 .unwrap();
1685 let count = || async {
1686 app.store
1687 .file(&file.id)
1688 .await
1689 .unwrap()
1690 .unwrap()
1691 .download_count
1692 };
1693
1694 let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1695 assert_eq!(inline.status, StatusCode::OK);
1696 let probe = app
1697 .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=0-3")
1698 .await;
1699 assert_eq!(probe.status, StatusCode::PARTIAL_CONTENT);
1700 assert_eq!(
1701 count().await,
1702 0,
1703 "previews counted: inline and range serves"
1704 );
1705
1706 let taken = app
1707 .get(&format!("/file/{}?dl=1", file.id), Some(&cookie))
1708 .await;
1709 assert_eq!(taken.status, StatusCode::OK);
1710 assert_eq!(count().await, 1, "a forced download did not count");
1711 // A mid-file chunk of a download is the same download going on.
1712 let resumed = app
1713 .get_with_range(
1714 &format!("/file/{}?dl=1", file.id),
1715 Some(&cookie),
1716 "bytes=4-",
1717 )
1718 .await;
1719 assert_eq!(resumed.status, StatusCode::PARTIAL_CONTENT);
1720 assert_eq!(count().await, 1, "a resumed chunk counted again");
1721}
1722
1723// -- public links (merged from http_d2.rs; one binary per crate) ------------
1724
1725#[tokio::test]
1726async fn link_create_public_view_revoke_gone() {
1727 let app = TestApp::build().await;
1728 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1729 let owner = owner_of(&app, "sub-admin").await;
1730 let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
1731
1732 let answer = app
1733 .post(
1734 "/api/share/link/create",
1735 Some(&admin),
1736 &[
1737 ("kind", "file"),
1738 ("target_id", &file),
1739 ("can_download", "1"),
1740 ],
1741 )
1742 .await;
1743 assert!(answer.accepted(), "create refused: {:?}", answer.location);
1744 let token = created_token(answer.location.as_deref().unwrap());
1745
1746 // Public: no cookie, the card renders.
1747 let page = app.get(&format!("/s/{token}"), None).await;
1748 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1749 assert!(page.text().contains("notes.txt"), "{}", page.text());
1750
1751 // Public download carries the bytes.
1752 let bytes = app.get(&format!("/s/{token}?dl=1"), None).await;
1753 assert_eq!(bytes.status, StatusCode::OK);
1754 assert_eq!(bytes.bytes, b"hello in");
1755
1756 // Revoke: only the id travels; look it up straight off the store.
1757 let id = app.store.share_links(&owner).await.unwrap()[0].id.clone();
1758 let answer = app
1759 .post("/api/share/link/revoke", Some(&admin), &[("id", &id)])
1760 .await;
1761 assert!(answer.accepted(), "revoke refused: {:?}", answer.location);
1762
1763 let gone = app.get(&format!("/s/{token}"), None).await;
1764 assert_eq!(gone.status, StatusCode::OK);
1765 assert!(
1766 gone.text().contains("no longer works"),
1767 "revoked link showed: {}",
1768 gone.text()
1769 );
1770}
1771
1772#[tokio::test]
1773async fn expired_link_is_dead() {
1774 let app = TestApp::build().await;
1775 let _ = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1776 let owner = owner_of(&app, "sub-admin").await;
1777 let file = file_id(&app, &owner, "old.txt", b"old").await;
1778 let past = time::OffsetDateTime::now_utc() - time::Duration::days(1);
1779 let created = app
1780 .store
1781 .create_share_link(&owner, ShareKind::File, &file, true, Some(past), None)
1782 .await
1783 .unwrap();
1784 let page = app.get(&format!("/s/{}", created.token), None).await;
1785 assert_eq!(page.status, StatusCode::OK);
1786 assert!(
1787 page.text().contains("no longer works"),
1788 "expired link showed: {}",
1789 page.text()
1790 );
1791}
1792
1793#[tokio::test]
1794async fn view_only_link_download_is_dead_card() {
1795 let app = TestApp::build().await;
1796 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1797 let owner = owner_of(&app, "sub-admin").await;
1798 let file = file_id(&app, &owner, "secret.txt", b"eyes only").await;
1799 let answer = app
1800 .post(
1801 "/api/share/link/create",
1802 Some(&admin),
1803 &[
1804 ("kind", "file"),
1805 ("target_id", &file),
1806 ("can_download", "0"),
1807 ],
1808 )
1809 .await;
1810 assert!(answer.accepted(), "create refused: {:?}", answer.location);
1811 let token = created_token(answer.location.as_deref().unwrap());
1812
1813 let page = app.get(&format!("/s/{token}"), None).await;
1814 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1815 assert!(page.text().contains("secret.txt"), "{}", page.text());
1816
1817 let blocked = app.get(&format!("/s/{token}?dl=1"), None).await;
1818 assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text());
1819 assert!(
1820 blocked.text().contains("no longer works"),
1821 "view-only download showed: {}",
1822 blocked.text()
1823 );
1824}
1825
1826/// A tiny VP9+AAC Matroska, made by the system `ffmpeg` the way the
1827/// thumbnailer drives it: a test pattern and a tone, half a second. Small,
1828/// but exactly the file a browser refuses to play as a webm — VP9 video
1829/// with AAC audio. `None` skips the tests where ffmpeg is not installed.
1830fn vp9_aac_matroska() -> Option<Vec<u8>> {
1831 if !in_core::thumbs::ffmpeg_available() {
1832 eprintln!("skipping matroska preview tests: no ffmpeg on PATH");
1833 return None;
1834 }
1835 let dir = std::env::temp_dir().join(format!("in-mkv-{}", Ulid::generate()));
1836 std::fs::create_dir_all(&dir).unwrap();
1837 let out = dir.join("clip.mkv");
1838 let status = Command::new("ffmpeg")
1839 .args([
1840 "-v",
1841 "error",
1842 "-y",
1843 "-f",
1844 "lavfi",
1845 "-i",
1846 "testsrc=duration=0.5:size=128x96:rate=10",
1847 "-f",
1848 "lavfi",
1849 "-i",
1850 "sine=frequency=440:duration=0.5",
1851 "-c:v",
1852 "libvpx-vp9",
1853 "-c:a",
1854 "aac",
1855 ])
1856 .arg(&out)
1857 .status()
1858 .ok()?;
1859 let bytes = if status.success() {
1860 std::fs::read(&out).ok()
1861 } else {
1862 None
1863 };
1864 let _ = std::fs::remove_dir_all(&dir);
1865 bytes
1866}
1867
1868/// A VP9+AAC mkv is stored under its honest Matroska name, the inline media
1869/// route serves the stored bytes as they sit under that mime, and `?dl=1`
1870/// still hands over the original, byte for byte.
1871#[tokio::test]
1872async fn a_webm_illegal_matroska_serves_original_bytes_inline_and_on_download() {
1873 let Some(mkv) = vp9_aac_matroska() else {
1874 return;
1875 };
1876 let app = TestApp::build().await;
1877 let cookie = app
1878 .sign_in("sub-matroska", "matroska@in.test", "Matroska")
1879 .await;
1880 let user = app
1881 .store
1882 .user_by_oidc_sub("sub-matroska")
1883 .await
1884 .unwrap()
1885 .unwrap();
1886
1887 app.post_multipart(
1888 "/files",
1889 Some(&cookie),
1890 &[("folder_id", "")],
1891 &[("clip.mkv", "video/x-matroska", &mkv)],
1892 )
1893 .await;
1894 let file = app
1895 .store
1896 .list_children(&user.id, None)
1897 .await
1898 .unwrap()
1899 .files
1900 .into_iter()
1901 .next()
1902 .unwrap();
1903 // The sniffer no longer calls these tracks a webm.
1904 let stored = app.store.file(&file.id).await.unwrap().unwrap();
1905 assert_eq!(stored.mime, "video/x-matroska");
1906
1907 // The inline serve is the stored bytes under the honest sniffed mime —
1908 // no derivative stands in, whatever the browser makes of the tracks.
1909 let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1910 assert_eq!(inline.status, StatusCode::OK);
1911 assert_eq!(inline.content_type.as_deref(), Some("video/x-matroska"));
1912 assert_eq!(inline.bytes, mkv, "the inline serve was not the original");
1913
1914 // The download is the original too, byte for byte.
1915 let taken = app
1916 .get(&format!("/file/{}?dl=1", file.id), Some(&cookie))
1917 .await;
1918 assert_eq!(taken.status, StatusCode::OK);
1919 assert_eq!(taken.bytes, mkv);
1920 assert_eq!(taken.bytes.len(), mkv.len());
1921 assert_eq!(taken.content_type.as_deref(), Some("video/x-matroska"));
1922 assert!(
1923 taken
1924 .disposition
1925 .as_deref()
1926 .unwrap_or("")
1927 .starts_with("attachment")
1928 );
1929}
1930
1931/// A view-only public link previews the stored bytes — that is what the
1932/// media stream is for — and still cannot be downloaded: `?dl=1` stays the
1933/// dead card.
1934#[tokio::test]
1935async fn view_only_link_previews_a_matroska_but_cannot_download() {
1936 let Some(mkv) = vp9_aac_matroska() else {
1937 return;
1938 };
1939 let app = TestApp::build().await;
1940 let owner = owner_of(&app, "sub-admin").await;
1941 let file = app
1942 .store
1943 .insert_file(&owner, None, "clip.mkv", &mkv)
1944 .await
1945 .unwrap()
1946 .id;
1947 let created = app
1948 .store
1949 .create_share_link(&owner, ShareKind::File, &file, false, None, None)
1950 .await
1951 .unwrap();
1952
1953 let media = app
1954 .get(&format!("/s/{}?media=1", created.token), None)
1955 .await;
1956 assert_eq!(media.status, StatusCode::OK);
1957 assert_eq!(media.content_type.as_deref(), Some("video/x-matroska"));
1958 assert_eq!(media.bytes, mkv, "the media stream was not the original");
1959
1960 let blocked = app.get(&format!("/s/{}?dl=1", created.token), None).await;
1961 assert!(
1962 blocked.text().contains("no longer works"),
1963 "view-only download showed: {}",
1964 blocked.text()
1965 );
1966}
1967
1968/// A password-protected link gates everything — card, download bytes —
1969/// until the browser answers the gate once; the proof then lives in the
1970/// link's own cookie. A wrong password answers the gate with the error and
1971/// mints no cookie, a revoked link dead-ends even an unlocked browser, and
1972/// none of the gate pages ever name the file.
1973#[tokio::test]
1974async fn password_link_gates_until_unlocked() {
1975 let app = TestApp::build().await;
1976 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1977 let owner = owner_of(&app, "sub-admin").await;
1978 let file = file_id(&app, &owner, "private.txt", b"behind the gate").await;
1979 let answer = app
1980 .post(
1981 "/api/share/link/create",
1982 Some(&admin),
1983 &[
1984 ("kind", "file"),
1985 ("target_id", &file),
1986 ("can_download", "1"),
1987 ("password", "open sesame"),
1988 ],
1989 )
1990 .await;
1991 assert!(answer.accepted(), "create refused: {:?}", answer.location);
1992 let token = created_token(answer.location.as_deref().unwrap());
1993 let link = &app.store.share_links(&owner).await.unwrap()[0];
1994 assert!(link.password_hash.is_some());
1995
1996 // The gate: no cookie, no name, no bytes — on the card and on `?dl=1`
1997 // both.
1998 let gate = app.get(&format!("/s/{token}"), None).await;
1999 assert_eq!(gate.status, StatusCode::OK, "{}", gate.text());
2000 assert!(
2001 !gate.text().contains("private.txt"),
2002 "gate leaked the file name: {}",
2003 gate.text()
2004 );
2005 assert!(gate.text().contains("type=\"password\""), "{}", gate.text());
2006 let gated_bytes = app.get(&format!("/s/{token}?dl=1"), None).await;
2007 assert_eq!(gated_bytes.status, StatusCode::OK);
2008 assert!(
2009 !gated_bytes.text().contains("behind the gate"),
2010 "gate leaked the bytes: {}",
2011 gated_bytes.text()
2012 );
2013
2014 // A wrong password: back to the gate with the error on the query, and
2015 // no cookie minted.
2016 let wrong = app
2017 .post(&format!("/s/{token}"), None, &[("password", "wrong one")])
2018 .await;
2019 assert_eq!(wrong.status, StatusCode::SEE_OTHER);
2020 assert_eq!(
2021 wrong.location.as_deref(),
2022 Some(&format!("/s/{token}?wrong=1")[..])
2023 );
2024 assert!(
2025 wrong.set_cookie.is_none(),
2026 "a wrong password minted a cookie: {:?}",
2027 wrong.set_cookie
2028 );
2029 let wrong_gate = app.get(&format!("/s/{token}?wrong=1"), None).await;
2030 assert_eq!(wrong_gate.status, StatusCode::OK);
2031 assert!(
2032 wrong_gate.text().contains("Wrong password."),
2033 "the gate did not say what went wrong: {}",
2034 wrong_gate.text()
2035 );
2036
2037 // The right password: a 303 back to the page, carrying the proof cookie
2038 // named for the link, scoped to /s, not marked Secure on a plain-http
2039 // rehearsal.
2040 let right = app
2041 .post(&format!("/s/{token}"), None, &[("password", "open sesame")])
2042 .await;
2043 assert_eq!(right.status, StatusCode::SEE_OTHER);
2044 assert_eq!(
2045 right.location.as_deref(),
2046 Some(format!("/s/{token}").as_str())
2047 );
2048 let proof = in_core::link_unlock_proof(&token, link.password_hash.as_deref().unwrap());
2049 let cookie_pair = format!("in_link_{}={proof}", link.id);
2050 let set_cookie = right.set_cookie.as_deref().expect("unlock set no cookie");
2051 assert!(
2052 set_cookie.contains(&cookie_pair),
2053 "cookie did not carry the proof: {set_cookie}"
2054 );
2055 assert!(set_cookie.contains("Path=/s"), "{set_cookie}");
2056 assert!(set_cookie.contains("HttpOnly"), "{set_cookie}");
2057 assert!(set_cookie.contains("SameSite=Lax"), "{set_cookie}");
2058 assert!(!set_cookie.contains("Secure"), "{set_cookie}");
2059
2060 // The unlocked browser sees the card, and the download serves bytes.
2061 let unlocked = app.get(&format!("/s/{token}"), Some(&cookie_pair)).await;
2062 assert_eq!(unlocked.status, StatusCode::OK, "{}", unlocked.text());
2063 assert!(
2064 unlocked.text().contains("private.txt"),
2065 "unlocked card showed nothing: {}",
2066 unlocked.text()
2067 );
2068 let served = app
2069 .get(&format!("/s/{token}?dl=1"), Some(&cookie_pair))
2070 .await;
2071 assert_eq!(served.bytes, b"behind the gate");
2072
2073 // Revocation dead-ends even the unlocked browser.
2074 let id = link.id.clone();
2075 let answer = app
2076 .post("/api/share/link/revoke", Some(&admin), &[("id", &id)])
2077 .await;
2078 assert!(answer.accepted(), "revoke refused: {:?}", answer.location);
2079 let gone = app.get(&format!("/s/{token}"), Some(&cookie_pair)).await;
2080 assert_eq!(gone.status, StatusCode::OK);
2081 assert!(
2082 gone.text().contains("no longer works"),
2083 "revoked link showed: {}",
2084 gone.text()
2085 );
2086}
2087
2088/// An unchecked `can_download` box posts nothing at all, and nothing posted
2089/// must never mint a download: the absent flag reads view-only, the way an
2090/// explicitly refused one does — while the checked box still opens the bytes.
2091#[tokio::test]
2092async fn link_create_without_the_flag_is_view_only() {
2093 let app = TestApp::build().await;
2094 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2095 let owner = owner_of(&app, "sub-admin").await;
2096 let file = file_id(&app, &owner, "plain.txt", b"plain bytes").await;
2097 // No can_download pair — what an unchecked checkbox posts.
2098 let answer = app
2099 .post(
2100 "/api/share/link/create",
2101 Some(&admin),
2102 &[("kind", "file"), ("target_id", &file)],
2103 )
2104 .await;
2105 assert!(answer.accepted(), "create refused: {:?}", answer.location);
2106 let token = created_token(answer.location.as_deref().unwrap());
2107 let page = app.get(&format!("/s/{token}"), None).await;
2108 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2109 assert!(page.text().contains("plain.txt"), "{}", page.text());
2110 let blocked = app.get(&format!("/s/{token}?dl=1"), None).await;
2111 assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text());
2112 assert!(
2113 blocked.text().contains("no longer works"),
2114 "absent-flag download showed: {}",
2115 blocked.text()
2116 );
2117 // Both share surfaces print the target's name, never its raw id.
2118 let named = app
2119 .get(&format!("/drive?share=file:{file}"), Some(&admin))
2120 .await;
2121 assert_eq!(named.status, StatusCode::OK, "{}", named.text());
2122 assert!(
2123 named.text().contains("plain.txt") && named.text().contains("modal-scrim"),
2124 "share modal showed no name: {}",
2125 named.text()
2126 );
2127 let settings = app.get("/settings?section=links", Some(&admin)).await;
2128 assert_eq!(settings.status, StatusCode::OK, "{}", settings.text());
2129 assert!(
2130 settings.text().contains("plain.txt"),
2131 "settings panel showed no name: {}",
2132 settings.text()
2133 );
2134 // The checked box still opens the bytes.
2135 let answer = app
2136 .post(
2137 "/api/share/link/create",
2138 Some(&admin),
2139 &[
2140 ("kind", "file"),
2141 ("target_id", &file),
2142 ("can_download", "1"),
2143 ],
2144 )
2145 .await;
2146 assert!(answer.accepted(), "create refused: {:?}", answer.location);
2147 let token = created_token(answer.location.as_deref().unwrap());
2148 let bytes = app.get(&format!("/s/{token}?dl=1"), None).await;
2149 assert_eq!(bytes.status, StatusCode::OK);
2150 assert_eq!(bytes.bytes, b"plain bytes");
2151}
2152
2153#[tokio::test]
2154async fn folder_link_lists_and_serves_children() {
2155 let app = TestApp::build().await;
2156 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2157 let owner = owner_of(&app, "sub-admin").await;
2158 let folder = app
2159 .store
2160 .create_folder(&owner, None, "shared")
2161 .await
2162 .unwrap();
2163 app.store
2164 .insert_file(&owner, Some(&folder.id), "child.txt", b"child bytes")
2165 .await
2166 .unwrap();
2167 let answer = app
2168 .post(
2169 "/api/share/link/create",
2170 Some(&admin),
2171 &[
2172 ("kind", "folder"),
2173 ("target_id", &folder.id),
2174 ("can_download", "1"),
2175 ],
2176 )
2177 .await;
2178 assert!(answer.accepted(), "create refused: {:?}", answer.location);
2179 let token = created_token(answer.location.as_deref().unwrap());
2180
2181 let page = app.get(&format!("/s/{token}"), None).await;
2182 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2183 assert!(page.text().contains("child.txt"), "{}", page.text());
2184
2185 let child = app
2186 .store
2187 .list_children(&owner, Some(&folder.id))
2188 .await
2189 .unwrap()
2190 .files[0]
2191 .id
2192 .clone();
2193 let bytes = app
2194 .get(
2195 &format!("/s/{token}?folder={}&file={child}&dl=1", folder.id),
2196 None,
2197 )
2198 .await;
2199 assert_eq!(bytes.status, StatusCode::OK, "{}", bytes.text());
2200 assert_eq!(bytes.bytes, b"child bytes");
2201}
2202
2203#[tokio::test]
2204async fn cross_owner_link_create_is_not_found() {
2205 let app = TestApp::build().await;
2206 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2207 let _ = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
2208 let bob = owner_of(&app, "sub-bob").await;
2209 let file = file_id(&app, &bob, "bobs.txt", b"bob").await;
2210 // Ada names Bob's file: answered as not-found, never forbidden.
2211 let answer = app
2212 .post(
2213 "/api/share/link/create",
2214 Some(&admin),
2215 &[
2216 ("kind", "file"),
2217 ("target_id", &file),
2218 ("can_download", "1"),
2219 ],
2220 )
2221 .await;
2222 assert!(
2223 answer.refused("not-found", "create"),
2224 "{:?}",
2225 answer.location
2226 );
2227}
2228
2229// -- per-user shares --------------------------------------------------------
2230
2231#[tokio::test]
2232async fn per_user_share_lands_in_shared_with_me() {
2233 let app = TestApp::build().await;
2234 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2235 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
2236 let cara = app.sign_in("sub-cara", "cara@in.test", "Cara").await;
2237 let owner = owner_of(&app, "sub-admin").await;
2238 let file = file_id(&app, &owner, "joint.txt", b"joint").await;
2239
2240 let answer = app
2241 .post(
2242 "/api/share/user/add",
2243 Some(&admin),
2244 &[
2245 ("kind", "file"),
2246 ("target_id", &file),
2247 ("email", "BOB@in.test"),
2248 ("can_download", "1"),
2249 ],
2250 )
2251 .await;
2252 assert!(answer.accepted(), "add refused: {:?}", answer.location);
2253
2254 let bobs = app.get("/shared", Some(&bob)).await;
2255 assert_eq!(bobs.status, StatusCode::OK, "{}", bobs.text());
2256 assert!(bobs.text().contains("joint.txt"), "{}", bobs.text());
2257 // The row opens the viewer marked with its origin, so the back link
2258 // can name the shared page.
2259 assert!(
2260 bobs.text().contains(&format!("/view/{file}?from=shared")),
2261 "{}",
2262 bobs.text()
2263 );
2264
2265 let caras = app.get("/shared", Some(&cara)).await;
2266 assert_eq!(caras.status, StatusCode::OK, "{}", caras.text());
2267 assert!(!caras.text().contains("joint.txt"), "{}", caras.text());
2268
2269 // Unknown addresses are not-found, not a stack.
2270 let answer = app
2271 .post(
2272 "/api/share/user/add",
2273 Some(&admin),
2274 &[
2275 ("kind", "file"),
2276 ("target_id", &file),
2277 ("email", "ghost@in.test"),
2278 ("can_download", "1"),
2279 ],
2280 )
2281 .await;
2282 assert!(answer.refused("not-found", "add"), "{:?}", answer.location);
2283
2284 // Unshare and it leaves Bob's page.
2285 let answer = app
2286 .post(
2287 "/api/share/user/remove",
2288 Some(&admin),
2289 &[
2290 ("kind", "file"),
2291 ("target_id", &file),
2292 ("email", "bob@in.test"),
2293 ],
2294 )
2295 .await;
2296 assert!(answer.accepted(), "remove refused: {:?}", answer.location);
2297 let bobs = app.get("/shared", Some(&bob)).await;
2298 assert!(!bobs.text().contains("joint.txt"), "{}", bobs.text());
2299}
2300
2301/// The share modal picks people from im's directory: a member who has
2302/// never signed in here is offered — the render itself mirrors her into a
2303/// local row — the owner is not, and granting the picked address lands her
2304/// under Who has access.
2305#[tokio::test]
2306async fn share_modal_offers_the_im_directory() {
2307 let app = TestApp::build().await;
2308 app.fake.set_directory(&[
2309 serde_json::json!({"sub": "sub-ember", "email": "ember@in.test", "name": "Ember", "admin": false}),
2310 serde_json::json!({"sub": "sub-bora", "email": "bora@in.test", "name": "Bora", "admin": false}),
2311 // The owner as im knows her: never offered to share with herself.
2312 serde_json::json!({"sub": "sub-admin", "email": "ada@in.test", "name": "Ada", "admin": true}),
2313 // Valid in im but disabled here: sharing with her is sharing with
2314 // nobody, so the picker never offers her.
2315 serde_json::json!({"sub": "sub-gonca", "email": "gonca@in.test", "name": "Gonca", "admin": false}),
2316 ]);
2317 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2318 app.sign_in("sub-gonca", "gonca@in.test", "Gonca").await;
2319 let gonca = app
2320 .store
2321 .user_by_email("gonca@in.test")
2322 .await
2323 .unwrap()
2324 .unwrap();
2325 app.store.set_user_disabled(&gonca.id, true).await.unwrap();
2326 let owner = owner_of(&app, "sub-admin").await;
2327 let file = file_id(&app, &owner, "pick.txt", b"pick").await;
2328
2329 let page = app
2330 .get(&format!("/drive?share=file:{file}"), Some(&admin))
2331 .await;
2332 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2333 let text = page.text();
2334 assert!(
2335 text.contains("<div class=\"share-picker pop-panel\""),
2336 "picker panel missing: {text}"
2337 );
2338 assert!(
2339 text.contains("aria-label=\"Pick a person\""),
2340 "no picker group label: {text}"
2341 );
2342 assert!(
2343 text.contains(
2344 "<input class=\"field-input share-pick-filter\" type=\"email\" name=\"email\"",
2345 ),
2346 "picker filter (and typed-address fallback) missing: {text}"
2347 );
2348 assert!(
2349 text.contains("class=\"pop-row share-pick-row\""),
2350 "candidate rows not drawn as the control: {text}"
2351 );
2352 assert!(
2353 text.contains("class=\"field-note share-pick-none share-pick-off\""),
2354 "no-match note not shipped hidden: {text}"
2355 );
2356 assert!(
2357 text.contains("type=\"checkbox\" name=\"email\" value=\"ember@in.test\""),
2358 "Ember not offered as a checkable row: {text}"
2359 );
2360 assert!(
2361 text.contains("type=\"checkbox\" name=\"email\" value=\"bora@in.test\""),
2362 "Bora not offered as a checkable row: {text}"
2363 );
2364 assert!(
2365 text.find("Bora").unwrap() < text.find("Ember").unwrap(),
2366 "directory not offered by name: {text}"
2367 );
2368 assert!(
2369 !text.contains("value=\"ada@in.test\""),
2370 "owner offered: {text}"
2371 );
2372 assert!(
2373 !text.contains("value=\"gonca@in.test\""),
2374 "disabled account offered: {text}"
2375 );
2376
2377 // The grant posts the picked address; Ember never signed in here.
2378 let answer = app
2379 .post(
2380 "/api/share/user/add",
2381 Some(&admin),
2382 &[
2383 ("kind", "file"),
2384 ("target_id", &file),
2385 ("email", "ember@in.test"),
2386 ("can_download", "1"),
2387 ],
2388 )
2389 .await;
2390 assert!(answer.accepted(), "add refused: {:?}", answer.location);
2391 let page = app
2392 .get(&format!("/drive?share=file:{file}"), Some(&admin))
2393 .await;
2394 assert!(page.text().contains("Ember"), "{}", page.text());
2395}
2396
2397/// One submit, several people: the picker posts one `email` field per
2398/// checked row, and every address lands under Who has access carrying the
2399/// one `can_download` the submit chose.
2400#[tokio::test]
2401async fn share_modal_grants_every_posted_address() {
2402 let app = TestApp::build().await;
2403 app.fake.set_directory(&[
2404 serde_json::json!({"sub": "sub-ember", "email": "ember@in.test", "name": "Ember", "admin": false}),
2405 serde_json::json!({"sub": "sub-bora", "email": "bora@in.test", "name": "Bora", "admin": false}),
2406 ]);
2407 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2408 let owner = owner_of(&app, "sub-admin").await;
2409 let file = file_id(&app, &owner, "crowd.txt", b"crowd").await;
2410
2411 // The picker exists only on a rendered modal, and the render is what
2412 // provisions im's directory into the store; the post below is the
2413 // picker's own submit, so it opens the modal first.
2414 let page = app
2415 .get(&format!("/drive?share=file:{file}"), Some(&admin))
2416 .await;
2417 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2418
2419 let answer = app
2420 .post(
2421 "/api/share/user/add",
2422 Some(&admin),
2423 &[
2424 ("kind", "file"),
2425 ("target_id", &file),
2426 ("email", "ember@in.test"),
2427 ("email", "bora@in.test"),
2428 ("can_download", "0"),
2429 ],
2430 )
2431 .await;
2432 assert!(answer.accepted(), "add refused: {:?}", answer.location);
2433
2434 let grants = app
2435 .store
2436 .shares_for_target(&owner, ShareKind::File, &file)
2437 .await
2438 .unwrap();
2439 assert_eq!(grants.len(), 2, "not every posted address granted");
2440 assert!(
2441 grants.iter().all(|grant| !grant.can_download),
2442 "view-only not applied to every grant"
2443 );
2444
2445 let page = app
2446 .get(&format!("/drive?share=file:{file}"), Some(&admin))
2447 .await;
2448 let text = page.text();
2449 assert!(text.contains("Ember"), "{}", text);
2450 assert!(text.contains("Bora"), "{}", text);
2451}
2452
2453/// A directory that does not answer — im without the route, the way an
2454/// unregistered or unreachable im behaves — leaves the modal exactly as
2455/// it was: the typed address.
2456#[tokio::test]
2457async fn share_modal_without_a_directory_keeps_the_typed_address() {
2458 let app = TestApp::build().await;
2459 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2460 let owner = owner_of(&app, "sub-admin").await;
2461 let file = file_id(&app, &owner, "typed.txt", b"typed").await;
2462
2463 let page = app
2464 .get(&format!("/drive?share=file:{file}"), Some(&admin))
2465 .await;
2466 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2467 let text = page.text();
2468 assert!(
2469 text.contains("type=\"email\" name=\"email\""),
2470 "typed address lost: {text}"
2471 );
2472 assert!(
2473 !text.contains("<select class=\"field-input share-add-email\""),
2474 "dropdown rendered without a directory: {text}"
2475 );
2476}
2477
2478/// The link a person just minted stays visible: creation seals the token
2479/// onto its setting row, and the modal's live row and the settings panel's
2480/// row both re-derive the full address from it — copy buttons included,
2481/// masked value nowhere.
2482#[tokio::test]
2483async fn created_link_is_revisible_and_copyable_everywhere() {
2484 let app = TestApp::build().await;
2485 let ada = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2486 let owner = owner_of(&app, "sub-admin").await;
2487 let file = file_id(&app, &owner, "visible.txt", b"visible").await;
2488
2489 let answer = app
2490 .post(
2491 "/api/share/link/create",
2492 Some(&ada),
2493 &[
2494 ("kind", "file"),
2495 ("target_id", &file),
2496 ("can_download", "1"),
2497 ],
2498 )
2499 .await;
2500 assert!(answer.accepted(), "create refused: {:?}", answer.location);
2501 let token = created_token(answer.location.as_deref().unwrap());
2502 let url = format!("http://127.0.0.1:7655/s/{token}");
2503
2504 // The mint stored the sealed token — ciphertext, not the plaintext —
2505 // and the app's link key is what opens it.
2506 let link = &app.store.share_links(&owner).await.unwrap()[0];
2507 let sealed = app
2508 .store
2509 .get_setting(&format!("share_token:{}", link.id))
2510 .await
2511 .unwrap()
2512 .expect("no sealed token row after mint");
2513 assert_ne!(sealed, token);
2514 assert_eq!(
2515 in_core::store::secret::open(&[11u8; 32], &sealed).as_deref(),
2516 Some(token.as_str())
2517 );
2518
2519 // The modal's live row carries the full address with its copy button.
2520 let page = app
2521 .get(
2522 &format!("/drive?share=file:{file}&created={token}"),
2523 Some(&ada),
2524 )
2525 .await;
2526 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2527 let text = page.text();
2528 assert!(
2529 text.contains(&format!("\">{url}</p>")),
2530 "no full url in the modal: {text}"
2531 );
2532 assert!(
2533 text.contains("class=\"quiet share-copy\""),
2534 "no copy button in the modal: {text}"
2535 );
2536 assert!(
2537 !text.contains("/s/…"),
2538 "masked value on a re-visible link: {text}"
2539 );
2540
2541 // The settings panel's row carries the same.
2542 let page = app.get("/settings?section=links", Some(&ada)).await;
2543 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2544 let text = page.text();
2545 assert!(
2546 text.contains(&format!("\">{url}</p>")),
2547 "no full url in settings: {text}"
2548 );
2549 assert!(
2550 text.contains("class=\"quiet share-copy\""),
2551 "no copy button in settings: {text}"
2552 );
2553 assert!(
2554 text.contains("__inShareCopy"),
2555 "no copy script on the links panel: {text}"
2556 );
2557}
2558
2559/// Revoking deletes the sealed row too — it is part of the revoke, so a
2560/// mint-and-revoke round trip leaves no orphan setting behind.
2561#[tokio::test]
2562async fn revoke_deletes_the_sealed_token_row() {
2563 let app = TestApp::build().await;
2564 let ada = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2565 let owner = owner_of(&app, "sub-admin").await;
2566 let file = file_id(&app, &owner, "sealed.txt", b"sealed").await;
2567
2568 for round in 0..2 {
2569 let answer = app
2570 .post(
2571 "/api/share/link/create",
2572 Some(&ada),
2573 &[("kind", "file"), ("target_id", &file)],
2574 )
2575 .await;
2576 assert!(answer.accepted(), "create refused: {:?}", answer.location);
2577 let id = app.store.share_links(&owner).await.unwrap()[0].id.clone();
2578 let key = format!("share_token:{id}");
2579 assert!(
2580 app.store.get_setting(&key).await.unwrap().is_some(),
2581 "no sealed row after mint {round}"
2582 );
2583
2584 let answer = app
2585 .post("/api/share/link/revoke", Some(&ada), &[("id", &id)])
2586 .await;
2587 assert!(answer.accepted(), "revoke refused: {:?}", answer.location);
2588 assert!(
2589 app.store.get_setting(&key).await.unwrap().is_none(),
2590 "sealed row survived the revoke {round}"
2591 );
2592 }
2593}
2594
2595/// A link minted before the sealing has no row to open: the modal and the
2596/// settings panel state the carry-forward fact and offer the one-click
2597/// mint — no masked value, nothing that reads as an address.
2598#[tokio::test]
2599async fn legacy_link_states_the_carry_forward_note_and_offers_the_mint() {
2600 let app = TestApp::build().await;
2601 let ada = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2602 let owner = owner_of(&app, "sub-admin").await;
2603 let file = file_id(&app, &owner, "legacy.txt", b"legacy").await;
2604 // Minted through the store alone, as the pre-sealing code did it: no
2605 // setting row ever comes to be.
2606 app.store
2607 .create_share_link(&owner, ShareKind::File, &file, false, None, None)
2608 .await
2609 .unwrap();
2610
2611 let page = app
2612 .get(&format!("/drive?share=file:{file}"), Some(&ada))
2613 .await;
2614 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2615 let text = page.text();
2616 assert!(
2617 !text.contains("/s/…"),
2618 "masked value on a legacy link: {text}"
2619 );
2620 assert!(
2621 text.contains("action=\"/api/share/link/remint\""),
2622 "no mint action on a legacy link: {text}"
2623 );
2624 assert!(text.contains("Mint a new link"), "no mint button: {text}");
2625 assert!(
2626 text.contains("predates re-viewable addresses"),
2627 "no carry-forward note: {text}"
2628 );
2629 assert!(
2630 !text.contains("class=\"quiet share-copy\""),
2631 "copy button on a link with no re-derivable address: {text}"
2632 );
2633
2634 let page = app.get("/settings?section=links", Some(&ada)).await;
2635 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2636 let text = page.text();
2637 assert!(
2638 !text.contains("/s/…"),
2639 "masked value on a legacy link: {text}"
2640 );
2641 assert!(
2642 text.contains("action=\"/api/share/link/remint\""),
2643 "no mint action on a legacy link: {text}"
2644 );
2645 assert!(
2646 text.contains("predates re-viewable addresses"),
2647 "no carry-forward note: {text}"
2648 );
2649 assert!(
2650 !text.contains("class=\"quiet share-copy\""),
2651 "copy button on a link with no re-derivable address: {text}"
2652 );
2653}
2654
2655/// Reminting carries a legacy link forward: the fresh token opens the same
2656/// target with the carried rights, the old token is dead, the old row and
2657/// its seal are gone, and the settings panel shows the new full address
2658/// with its copy button.
2659#[tokio::test]
2660async fn remint_carries_a_legacy_link_forward() {
2661 let app = TestApp::build().await;
2662 let ada = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2663 let owner = owner_of(&app, "sub-admin").await;
2664 let file = file_id(&app, &owner, "carried.txt", b"carried").await;
2665 let answer = app
2666 .post(
2667 "/api/share/link/create",
2668 Some(&ada),
2669 &[
2670 ("kind", "file"),
2671 ("target_id", &file),
2672 ("can_download", "1"),
2673 ("expires_in_days", "30"),
2674 ],
2675 )
2676 .await;
2677 assert!(answer.accepted(), "create refused: {:?}", answer.location);
2678 let old_token = created_token(answer.location.as_deref().unwrap());
2679 let old_id = app.store.share_links(&owner).await.unwrap()[0].id.clone();
2680 // Lose the seal: the address is unrecoverable, the link reads legacy.
2681 app.store
2682 .delete_setting(&format!("share_token:{old_id}"))
2683 .await
2684 .unwrap();
2685
2686 let answer = app
2687 .post("/api/share/link/remint", Some(&ada), &[("id", &old_id)])
2688 .await;
2689 assert_eq!(
2690 answer.status,
2691 StatusCode::SEE_OTHER,
2692 "{:?}",
2693 answer.location
2694 );
2695 let location = answer.location.as_deref().expect("remint set no location");
2696 let new_token = created_token(location);
2697 assert!(!new_token.is_empty(), "remint minted no token: {location}");
2698
2699 // The fresh token opens the same file; the old one is dead.
2700 let card = app.get(&format!("/s/{new_token}"), None).await;
2701 assert_eq!(card.status, StatusCode::OK, "{}", card.text());
2702 assert!(
2703 card.text().contains("carried.txt"),
2704 "the fresh token did not open the file: {}",
2705 card.text()
2706 );
2707 let dead = app.get(&format!("/s/{old_token}"), None).await;
2708 assert!(
2709 dead.text().contains("no longer works"),
2710 "the old token still opens: {}",
2711 dead.text()
2712 );
2713
2714 // The old row died with its seal; the carried rights ride the new row.
2715 let links = app.store.share_links(&owner).await.unwrap();
2716 assert_ne!(links[0].id, old_id, "the old row survived the remint");
2717 assert!(links[0].can_download, "remint dropped the download right");
2718 assert!(links[0].expires_at.is_some(), "remint dropped the expiry");
2719 assert!(
2720 app.store
2721 .get_setting(&format!("share_token:{}", links[0].id))
2722 .await
2723 .unwrap()
2724 .is_some(),
2725 "the fresh token came unsealed"
2726 );
2727 assert!(
2728 app.store
2729 .get_setting(&format!("share_token:{old_id}"))
2730 .await
2731 .unwrap()
2732 .is_none(),
2733 "the old seal survived the remint"
2734 );
2735
2736 // The settings panel shows the new full address with its copy button —
2737 // no masked placeholder, no legacy row left to carry forward.
2738 let page = app
2739 .get(
2740 &format!("/settings?section=links&created={new_token}"),
2741 Some(&ada),
2742 )
2743 .await;
2744 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2745 let text = page.text();
2746 assert!(
2747 text.contains(&format!("\">http://127.0.0.1:7655/s/{new_token}</p>")),
2748 "no full new url row in settings: {text}"
2749 );
2750 assert!(
2751 text.contains("class=\"quiet share-copy\""),
2752 "no copy button in settings: {text}"
2753 );
2754 assert!(!text.contains("/s/…"), "masked value after remint: {text}");
2755 assert!(
2756 !text.contains("predates re-viewable addresses"),
2757 "a legacy row survived the remint: {text}"
2758 );
2759}
2760
2761/// Live public links and grants to other people mark their drive rows with
2762/// the Shared chip; unmarked siblings carry nothing, and no row carries two.
2763#[tokio::test]
2764async fn drive_marks_shared_rows() {
2765 let app = TestApp::build().await;
2766 let ada = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2767 app.sign_in("sub-ember", "ember@in.test", "Ember").await;
2768 let owner = owner_of(&app, "sub-admin").await;
2769 let linked = file_id(&app, &owner, "linked.txt", b"linked").await;
2770 let _plain = file_id(&app, &owner, "plain.txt", b"plain").await;
2771 let granted = file_id(&app, &owner, "granted.txt", b"granted").await;
2772 let answer = app
2773 .post(
2774 "/api/folder/create",
2775 Some(&ada),
2776 &[("parent_id", ""), ("name", "Dossier")],
2777 )
2778 .await;
2779 assert!(
2780 answer.accepted(),
2781 "folder create refused: {:?}",
2782 answer.location
2783 );
2784 let folder = folder_id(&app, &owner, None, "Dossier").await;
2785
2786 // A live public link onto the file, another onto the folder.
2787 for (kind, target) in [("file", linked.as_str()), ("folder", folder.as_str())] {
2788 let answer = app
2789 .post(
2790 "/api/share/link/create",
2791 Some(&ada),
2792 &[("kind", kind), ("target_id", target)],
2793 )
2794 .await;
2795 assert!(answer.accepted(), "create refused: {:?}", answer.location);
2796 }
2797 // A grant onto the third file.
2798 let ember = app
2799 .store
2800 .user_by_email("ember@in.test")
2801 .await
2802 .unwrap()
2803 .unwrap();
2804 app.store
2805 .add_share_user(&owner, ShareKind::File, &granted, &ember.id, true)
2806 .await
2807 .unwrap();
2808
2809 let page = app.get("/drive", Some(&ada)).await;
2810 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2811 let text = page.text();
2812 let chips = text.matches("chip chip-shared").count();
2813 assert_eq!(chips, 3, "expected three marked rows: {text}");
2814 assert!(
2815 text.contains("<span class=\"chip chip-shared\">Shared</span>"),
2816 "chip markup changed: {text}"
2817 );
2818 // The unshared sibling is on the page, but its row carries no mark.
2819 assert!(text.contains("plain.txt"), "sibling missing: {text}");
2820 let plain_row = text
2821 .split("<div class=\"drive-row\">")
2822 .find(|row| row.contains("plain.txt"))
2823 .expect("no drive row for the unshared sibling");
2824 assert!(
2825 !plain_row.contains("chip-shared"),
2826 "unshared sibling marked: {plain_row}"
2827 );
2828}
2829
2830/// View only means preview, no download: the reader sees the media inline
2831/// on the viewer page and reads the inline bytes, while `?dl=1` stays dead
2832/// and the page never offers the Download link.
2833#[tokio::test]
2834async fn view_only_reader_previews_media_but_cannot_download() {
2835 let app = TestApp::build().await;
2836 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2837 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
2838 let owner = owner_of(&app, "sub-admin").await;
2839 let file = file_id(
2840 &app,
2841 &owner,
2842 "photo.png",
2843 b"\x89PNG\r\n\x1a\n preview bytes",
2844 )
2845 .await;
2846
2847 let answer = app
2848 .post(
2849 "/api/share/user/add",
2850 Some(&admin),
2851 &[
2852 ("kind", "file"),
2853 ("target_id", &file),
2854 ("email", "bob@in.test"),
2855 ("can_download", "0"),
2856 ],
2857 )
2858 .await;
2859 assert!(answer.accepted(), "add refused: {:?}", answer.location);
2860
2861 // The viewer page renders the media, not the unavailable note, and
2862 // offers no download.
2863 let page = app.get(&format!("/view/{file}"), Some(&bob)).await;
2864 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2865 assert!(page.text().contains("viewer-media"), "{}", page.text());
2866 assert!(!page.text().contains("No preview"), "{}", page.text());
2867 assert!(!page.text().contains("?dl=1"), "{}", page.text());
2868 // The chrome names the grant honestly — viewing in the browser,
2869 // anything viewable savable — and the retired "no downloads" claim
2870 // is gone.
2871 assert!(
2872 page.text().contains("anything viewable can be saved"),
2873 "{}",
2874 page.text()
2875 );
2876 assert!(
2877 !page.text().contains("preview, no downloads"),
2878 "{}",
2879 page.text()
2880 );
2881 // The owner's own viewer names no grant: the note is for the reader
2882 // the grant limits.
2883 let own = app.get(&format!("/view/{file}"), Some(&admin)).await;
2884 assert_eq!(own.status, StatusCode::OK, "{}", own.text());
2885 assert!(
2886 !own.text().contains("anything viewable can be saved"),
2887 "{}",
2888 own.text()
2889 );
2890 assert!(own.text().contains("?dl=1"), "{}", own.text());
2891 // The back link names the origin: opened from the shared page (the
2892 // `from=shared` its rows carry) it returns there, a plain opening to
2893 // the drive.
2894 let from_shared = app
2895 .get(&format!("/view/{file}?from=shared"), Some(&bob))
2896 .await;
2897 assert_eq!(from_shared.status, StatusCode::OK, "{}", from_shared.text());
2898 assert!(
2899 from_shared.text().contains("Back to shared"),
2900 "{}",
2901 from_shared.text()
2902 );
2903 assert!(
2904 !from_shared.text().contains("Back to the drive"),
2905 "{}",
2906 from_shared.text()
2907 );
2908 assert!(page.text().contains("Back to the drive"), "{}", page.text());
2909
2910 // The inline bytes serve for the preview...
2911 let inline = app.get(&format!("/file/{file}"), Some(&bob)).await;
2912 assert_eq!(inline.status, StatusCode::OK, "{}", inline.text());
2913 assert_eq!(inline.bytes, b"\x89PNG\r\n\x1a\n preview bytes");
2914 // ...and taking the file away stays the stranger's answer.
2915 let taken = app.get(&format!("/file/{file}?dl=1"), Some(&bob)).await;
2916 assert_eq!(taken.status, StatusCode::NOT_FOUND, "{}", taken.text());
2917
2918 // A preview is not a download: the counter never moves.
2919 assert_eq!(
2920 app.store.file(&file).await.unwrap().unwrap().download_count,
2921 0
2922 );
2923}
2924
2925// -- trash ------------------------------------------------------------------
2926
2927#[tokio::test]
2928async fn trash_restore_purge_empty_flows() {
2929 let app = TestApp::build().await;
2930 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2931 let owner = owner_of(&app, "sub-admin").await;
2932 let one = file_id(&app, &owner, "one.txt", b"one").await;
2933 let two = file_id(&app, &owner, "two.txt", b"two").await;
2934 app.store.delete_file(&one).await.unwrap();
2935 app.store.delete_file(&two).await.unwrap();
2936
2937 let page = app.get("/trash", Some(&admin)).await;
2938 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2939 assert!(page.text().contains("one.txt"), "{}", page.text());
2940 assert!(page.text().contains("two.txt"), "{}", page.text());
2941
2942 // Restore one: it leaves the trash and keeps its bytes.
2943 let answer = app
2944 .post(
2945 "/api/trash/restore",
2946 Some(&admin),
2947 &[("kind", "file"), ("id", &one)],
2948 )
2949 .await;
2950 assert!(answer.accepted(), "restore refused: {:?}", answer.location);
2951 assert!(
2952 app.store
2953 .file(&one)
2954 .await
2955 .unwrap()
2956 .unwrap()
2957 .deleted_at
2958 .is_none()
2959 );
2960
2961 // Purge the other: the row and its bytes go.
2962 let answer = app
2963 .post(
2964 "/api/trash/purge",
2965 Some(&admin),
2966 &[("kind", "file"), ("id", &two)],
2967 )
2968 .await;
2969 assert!(answer.accepted(), "purge refused: {:?}", answer.location);
2970 assert!(app.store.file(&two).await.unwrap().is_none());
2971
2972 // Empty takes the rest.
2973 let three = file_id(&app, &owner, "three.txt", b"three").await;
2974 app.store.delete_file(&three).await.unwrap();
2975 let answer = app.post("/api/trash/empty", Some(&admin), &[]).await;
2976 assert!(answer.accepted(), "empty refused: {:?}", answer.location);
2977 assert!(app.store.list_trash(&owner).await.unwrap().files.is_empty());
2978}
2979
2980#[tokio::test]
2981async fn restore_under_trashed_ancestor_is_refused() {
2982 let app = TestApp::build().await;
2983 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2984 let owner = owner_of(&app, "sub-admin").await;
2985 let folder = app.store.create_folder(&owner, None, "box").await.unwrap();
2986 let file = app
2987 .store
2988 .insert_file(&owner, Some(&folder.id), "inbox.txt", b"in")
2989 .await
2990 .unwrap();
2991 app.store.delete_folder(&folder.id).await.unwrap();
2992
2993 let answer = app
2994 .post(
2995 "/api/trash/restore",
2996 Some(&admin),
2997 &[("kind", "file"), ("id", &file.id)],
2998 )
2999 .await;
3000 assert!(
3001 answer.refused("ancestor-trashed", "restore"),
3002 "{:?}",
3003 answer.location
3004 );
3005
3006 // The folder itself restores with its child.
3007 let answer = app
3008 .post(
3009 "/api/trash/restore",
3010 Some(&admin),
3011 &[("kind", "folder"), ("id", &folder.id)],
3012 )
3013 .await;
3014 assert!(answer.accepted(), "restore refused: {:?}", answer.location);
3015}
3016
3017#[tokio::test]
3018async fn folder_purge_destroys_its_tree() {
3019 let app = TestApp::build().await;
3020 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3021 let owner = owner_of(&app, "sub-admin").await;
3022 let folder = app
3023 .store
3024 .create_folder(&owner, None, "doomed")
3025 .await
3026 .unwrap();
3027 let file = app
3028 .store
3029 .insert_file(&owner, Some(&folder.id), "gone.txt", b"gone")
3030 .await
3031 .unwrap();
3032 app.store.delete_folder(&folder.id).await.unwrap();
3033
3034 let answer = app
3035 .post(
3036 "/api/trash/purge",
3037 Some(&admin),
3038 &[("kind", "folder"), ("id", &folder.id)],
3039 )
3040 .await;
3041 assert!(answer.accepted(), "purge refused: {:?}", answer.location);
3042 assert!(app.store.folder(&folder.id).await.unwrap().is_none());
3043 assert!(app.store.file(&file.id).await.unwrap().is_none());
3044}
3045
3046// -- search -----------------------------------------------------------------
3047
3048#[tokio::test]
3049async fn search_scopes_to_owner_and_hides_trashed() {
3050 let app = TestApp::build().await;
3051 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3052 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
3053 let ada = owner_of(&app, "sub-admin").await;
3054 let bob_id = owner_of(&app, "sub-bob").await;
3055 let mine = file_id(&app, &ada, "quarterly report.txt", b"a").await;
3056 let _ = file_id(&app, &bob_id, "quarterly notes.txt", b"b").await;
3057 let buried = file_id(&app, &ada, "quarterly draft.txt", b"c").await;
3058 app.store.delete_file(&buried).await.unwrap();
3059
3060 // Empty query is the folder view, not the whole library under a new
3061 // name: the upload control renders, no results caption does.
3062 let page = app.get("/drive", Some(&admin)).await;
3063 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3064 assert!(
3065 page.text().contains("id=\"upload-form\""),
3066 "{}",
3067 page.text()
3068 );
3069 assert!(!page.text().contains("Search results"), "{}", page.text());
3070
3071 let page = app.get("/drive?q=quarterly", Some(&admin)).await;
3072 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3073 assert!(
3074 page.text().contains("quarterly report.txt"),
3075 "{}",
3076 page.text()
3077 );
3078 assert!(
3079 !page.text().contains("quarterly notes.txt"),
3080 "{}",
3081 page.text()
3082 );
3083 assert!(
3084 !page.text().contains("quarterly draft.txt"),
3085 "{}",
3086 page.text()
3087 );
3088 assert!(app.store.file(&mine).await.unwrap().is_some());
3089
3090 let page = app.get("/drive?q=quarterly", Some(&bob)).await;
3091 assert!(
3092 page.text().contains("quarterly notes.txt"),
3093 "{}",
3094 page.text()
3095 );
3096 assert!(
3097 !page.text().contains("quarterly report.txt"),
3098 "{}",
3099 page.text()
3100 );
3101}
3102
3103#[tokio::test]
3104async fn drive_search_results_merge_into_one_panel() {
3105 let app = TestApp::build().await;
3106 let cookie = app
3107 .sign_in("sub-search-in-place", "inplace@in.test", "InPlace")
3108 .await;
3109 let owner = owner_of(&app, "sub-search-in-place").await;
3110 let answer = app
3111 .post(
3112 "/api/folder/create",
3113 Some(&cookie),
3114 &[("parent_id", ""), ("name", "holiday photos")],
3115 )
3116 .await;
3117 assert!(answer.accepted(), "create refused: {:?}", answer.location);
3118 let folder = folder_id(&app, &owner, None, "holiday photos").await;
3119 let file = file_id(&app, &owner, "holiday report.txt", b"sun").await;
3120
3121 let page = app.get("/drive?q=holiday", Some(&cookie)).await;
3122 let body = page.text();
3123 // Both hits render in one shared list, folders first, wired to their surfaces.
3124 assert!(body.contains("holiday photos"), "{body}");
3125 assert!(body.contains("holiday report.txt"), "{body}");
3126 assert!(body.contains(&format!("/drive?folder={folder}")), "{body}");
3127 assert!(body.contains(&format!("/view/{file}")), "{body}");
3128 // Drive rows stay unmarked: only the shared page names an origin.
3129 assert!(!body.contains("from=shared"), "{body}");
3130 let folder_at = body.find("holiday photos").expect("no folder hit");
3131 let file_at = body.find("holiday report.txt").expect("no file hit");
3132 assert!(folder_at < file_at, "file hit precedes folder hit: {body}");
3133 // One panel, no heads or chips.
3134 assert_eq!(
3135 body.matches("<section class=\"panel drive-panel\">")
3136 .count(),
3137 1,
3138 "{body}"
3139 );
3140 assert!(!body.contains("panel-head"), "{body}");
3141 assert!(!body.contains("class=\"chip\""), "{body}");
3142 assert!(!body.contains(">Folders</h2>"), "{body}");
3143 assert!(!body.contains(">Files</h2>"), "{body}");
3144 // The caption names the query and the box keeps it.
3145 assert!(body.contains("Search results"), "{body}");
3146 assert!(body.contains("holiday"), "{body}");
3147 assert!(body.contains("value=\"holiday\""), "{body}");
3148 assert!(body.contains("name=\"q\""), "{body}");
3149 // The upload control stays in the DOM for the + menu and the drop handler.
3150 assert!(body.contains("id=\"upload-form\""), "{body}");
3151 assert!(body.contains("id=\"drive-upload-input\""), "{body}");
3152 // The folder view is gone: no crumbs, no row mutations.
3153 assert!(!body.contains("detail-crumbs"), "{body}");
3154 assert!(!body.contains("action=\"/api/folder/rename\""), "{body}");
3155}
3156
3157#[tokio::test]
3158async fn drive_search_never_shows_other_owners_hits() {
3159 let app = TestApp::build().await;
3160 let ada = app.sign_in("sub-search-ada", "ada2@in.test", "Ada").await;
3161 let bob = app.sign_in("sub-search-bob", "bob2@in.test", "Bob").await;
3162 let bob_id = owner_of(&app, "sub-search-bob").await;
3163 let _ = file_id(&app, &bob_id, "secret ledger.txt", b"b").await;
3164 let answer = app
3165 .post(
3166 "/api/folder/create",
3167 Some(&bob),
3168 &[("parent_id", ""), ("name", "secret drawer")],
3169 )
3170 .await;
3171 assert!(answer.accepted(), "create refused: {:?}", answer.location);
3172
3173 // Ada's library-wide search stays hers: Bob's file and folder hits never
3174 // appear, and the quiet note says so.
3175 let page = app.get("/drive?q=secret", Some(&ada)).await;
3176 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3177 let body = page.text();
3178 assert!(!body.contains("secret ledger.txt"), "{body}");
3179 assert!(!body.contains("secret drawer"), "{body}");
3180 assert!(body.contains("Nothing found."), "{body}");
3181
3182 // Sanity: the same query finds them for their owner.
3183 let page = app.get("/drive?q=secret", Some(&bob)).await;
3184 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3185 assert!(page.text().contains("secret ledger.txt"), "{}", page.text());
3186 assert!(page.text().contains("secret drawer"), "{}", page.text());
3187}
3188
3189#[tokio::test]
3190async fn drive_search_empty_query_is_the_folder_view() {
3191 let app = TestApp::build().await;
3192 let cookie = app
3193 .sign_in("sub-search-empty", "empty@in.test", "Empty")
3194 .await;
3195 let owner = owner_of(&app, "sub-search-empty").await;
3196 let _ = file_id(&app, &owner, "plain.txt", b"p").await;
3197
3198 for path in ["/drive?q=", "/drive?q=%20%20"] {
3199 let page = app.get(path, Some(&cookie)).await;
3200 assert_eq!(page.status, StatusCode::OK, "{}: {}", path, page.text());
3201 let body = page.text();
3202 // The folder listing renders as usual — the file is there through
3203 // its directory, not through a result — with the box held empty.
3204 assert!(body.contains("plain.txt"), "{path}: {body}");
3205 assert!(body.contains("id=\"upload-form\""), "{path}: {body}");
3206 assert!(body.contains("name=\"q\""), "{path}: {body}");
3207 assert!(!body.contains("Search results"), "{path}: {body}");
3208 }
3209}
3210
3211#[tokio::test]
3212async fn old_search_address_redirects_to_drive() {
3213 let app = TestApp::build().await;
3214 let cookie = app.sign_in("sub-search-old", "old@in.test", "Old").await;
3215
3216 let page = app.get("/search?q=quarterly", Some(&cookie)).await;
3217 assert_eq!(page.status, StatusCode::SEE_OTHER, "{}", page.text());
3218 assert_eq!(page.location.as_deref(), Some("/drive?q=quarterly"));
3219
3220 // The raw pair rides through untouched, so encoded queries survive.
3221 let page = app.get("/search?q=holiday+report", Some(&cookie)).await;
3222 assert_eq!(page.status, StatusCode::SEE_OTHER, "{}", page.text());
3223 assert_eq!(page.location.as_deref(), Some("/drive?q=holiday+report"));
3224
3225 // No query is the plain drive; no session still redirects, never 401s.
3226 let page = app.get("/search", Some(&cookie)).await;
3227 assert_eq!(page.status, StatusCode::SEE_OTHER, "{}", page.text());
3228 assert_eq!(page.location.as_deref(), Some("/drive"));
3229 let page = app.get("/search?q=quarterly", None).await;
3230 assert_eq!(page.status, StatusCode::SEE_OTHER, "{}", page.text());
3231 assert_eq!(page.location.as_deref(), Some("/drive?q=quarterly"));
3232}
3233
3234#[tokio::test]
3235async fn topbar_nav_has_no_search_link() {
3236 let app = TestApp::build().await;
3237 let cookie = app.sign_in("sub-search-nav", "nav@in.test", "Nav").await;
3238 let page = app.get("/drive", Some(&cookie)).await;
3239 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3240 let body = page.text();
3241 let nav_start = body.find("topbar-nav-links").expect("no nav");
3242 let nav_end = body[nav_start..].find("</nav>").expect("nav never closes");
3243 let nav = &body[nav_start..nav_start + nav_end];
3244 // Drive, Shared, Trash — and nothing else.
3245 assert!(nav.contains("href=\"/drive\""), "{nav}");
3246 assert!(nav.contains("href=\"/shared\""), "{nav}");
3247 assert!(nav.contains("href=\"/trash\""), "{nav}");
3248 assert!(
3249 !nav.contains("/search"),
3250 "search leaked into the nav: {nav}"
3251 );
3252 assert!(!nav.contains("Search"), "search leaked into the nav: {nav}");
3253}
3254
3255#[tokio::test]
3256async fn the_family_flyout_holds_the_siblings_when_the_family_is_mirrored() {
3257 // No mirrored family: no switcher — the chrome as it always was.
3258 let bare = TestApp::build().await;
3259 let cookie = bare
3260 .sign_in("sub-switch0", "switch0@in.test", "Switch0")
3261 .await;
3262 let page = bare.get("/drive", Some(&cookie)).await;
3263 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3264 assert!(!page.text().contains("app-switcher"), "{}", page.text());
3265
3266 let app = TestApp::build_with(
3267 None,
3268 &[
3269 ("in", "Files", "https://files.example.com"),
3270 ("im", "Account", "https://id.example.com"),
3271 ("iz", "Board", "https://board.example.com"),
3272 ],
3273 )
3274 .await;
3275 let cookie = app.sign_in("sub-switch", "switch@in.test", "Switch").await;
3276 let page = app.get("/drive", Some(&cookie)).await;
3277 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3278 let body = page.text();
3279 let nav_start = body.find("app-switcher").expect("no switcher");
3280 let nav_end = body[nav_start..]
3281 .find("</nav>")
3282 .expect("switcher never closes");
3283 let nav = &body[nav_start..nav_start + nav_end];
3284 // Only the siblings hang in the flyout — this app's own row is the mark
3285 // the flyout hangs from, not an entry in it.
3286 assert!(
3287 !nav.contains("href=\"https://files.example.com/\""),
3288 "{nav}"
3289 );
3290 assert!(nav.contains("href=\"https://id.example.com/\""), "{nav}");
3291 assert!(nav.contains("href=\"https://board.example.com/\""), "{nav}");
3292 assert!(nav.contains("title=\"Account\""), "{nav}");
3293 assert_eq!(nav.matches("app-switcher-mark").count(), 2, "{nav}");
3294 assert_eq!(nav.matches("app-switcher-sep").count(), 1, "{nav}");
3295 // Both siblings sit at example.com addresses nothing answers — the
3296 // probes fail inside their two-second ceiling, concurrently — so both
3297 // read Off. The flyout carries dots only, one per mark.
3298 assert!(nav.contains("health-dot health-off"), "{nav}");
3299 assert!(!nav.contains("health-on"), "{nav}");
3300 assert_eq!(nav.matches("health-dot").count(), 2, "{nav}");
3301 // The flyout hangs off the monogram, not the page nav.
3302 assert!(body.contains("wordmark-family"), "{body}");
3303}
3304
3305/// The flyout marks each sibling with its probe's reading: a sibling
3306/// answering `ok` renders `health-on`, a dark port `health-off`, dots
3307/// only — no probe body, no latency — and in's own row stays out. The
3308/// markup itself is pinned router-free in
3309/// `the_family_flyout_marks_pure_html` below.
3310#[tokio::test]
3311async fn the_family_flyout_marks_siblings_with_health_dots() {
3312 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
3313
3314 // A live sibling answering the deploy body, and a dark one.
3315 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3316 let live_url = format!("http://{}", listener.local_addr().unwrap());
3317 let dark = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3318 let dark_url = format!("http://{}", dark.local_addr().unwrap());
3319 drop(dark);
3320 // `in` gets a row too — one the flyout must leave out.
3321 let app = TestApp::build_with(
3322 None,
3323 &[
3324 ("in", "Files", "https://files.example.com"),
3325 ("iz", "Board", &live_url),
3326 ("im", "Account", &dark_url),
3327 ],
3328 )
3329 .await;
3330 let cookie = app
3331 .sign_in("sub-switch-dot", "switchdot@in.test", "SwitchDot")
3332 .await;
3333 let talker = tokio::spawn(async move {
3334 let (mut sock, _) = listener.accept().await.unwrap();
3335 let mut buf = [0u8; 1024];
3336 let _ = sock.read(&mut buf).await;
3337 sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 6\r\n\r\nok dev")
3338 .await
3339 .unwrap();
3340 });
3341 let page = app.get("/drive", Some(&cookie)).await;
3342 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3343 talker.await.unwrap();
3344 let body = page.text();
3345 let nav_start = body.find("app-switcher").expect("no switcher");
3346 let nav_end = body[nav_start..]
3347 .find("</nav>")
3348 .expect("switcher never closes");
3349 let nav = &body[nav_start..nav_start + nav_end];
3350 assert!(
3351 nav.contains(r#"<a class="app-switcher-mark" href="http://127.0.0.1:"#),
3352 "the marks stay links: {nav}"
3353 );
3354 assert!(
3355 nav.contains("health-dot health-on"),
3356 "the ok sibling reads on: {nav}"
3357 );
3358 assert!(nav.contains(">iz</a>"), "the live sibling renders: {nav}");
3359 assert!(
3360 nav.contains("health-dot health-off"),
3361 "the dark sibling reads off: {nav}"
3362 );
3363 assert!(nav.contains(">im</a>"), "the dark sibling renders: {nav}");
3364 assert!(!nav.contains(">in</a>"), "in's own row stays out: {nav}");
3365 assert!(
3366 !body.contains("ok dev"),
3367 "the flyout carries dots only: {body}"
3368 );
3369 assert!(!nav.contains(" ms"), "the flyout carries no latency: {nav}");
3370}
3371
3372/// The CI gate for the flyout markup: `switcher_marks` is the exact HTML
3373/// the flyout renders, so the probe-to-dot mapping is pinned without a
3374/// router or an asset bundle — which is where the renders above get
3375/// skipped. Up reads `health-on`, Down `health-off`, the keys stay links
3376/// with their titles, and the probe's body and latency never reach the
3377/// chrome. (The omission of in's own row is `family_mark`'s doing; the
3378/// router renders above pin it.)
3379#[test]
3380fn the_family_flyout_marks_pure_html() {
3381 use in_web::health::Probe;
3382
3383 let marks = in_web::layout::switcher_marks([
3384 (
3385 "iz",
3386 "http://127.0.0.1:9001",
3387 "Board",
3388 Probe::Up {
3389 body: "ok dev".into(),
3390 ms: 12,
3391 },
3392 ),
3393 ("im", "http://127.0.0.1:9002", "Account", Probe::Down),
3394 ]);
3395 assert!(
3396 marks.contains(
3397 r#"<a class="app-switcher-mark" href="http://127.0.0.1:9001/" title="Board">"#
3398 ),
3399 "the marks stay links: {marks}"
3400 );
3401 assert!(
3402 marks.contains("health-dot health-on"),
3403 "the ok sibling reads on: {marks}"
3404 );
3405 assert!(
3406 marks.contains(">iz</a>"),
3407 "the live sibling renders: {marks}"
3408 );
3409 assert!(
3410 marks.contains("health-dot health-off"),
3411 "the dark sibling reads off: {marks}"
3412 );
3413 assert!(
3414 marks.contains(">im</a>"),
3415 "the dark sibling renders: {marks}"
3416 );
3417 assert!(
3418 !marks.contains("ok dev"),
3419 "the flyout carries dots only: {marks}"
3420 );
3421 assert!(
3422 !marks.contains(" ms"),
3423 "the flyout carries no latency: {marks}"
3424 );
3425 assert!(
3426 marks.contains(r#"<span class="app-switcher-sep">·</span>"#),
3427 "the marks join on middots: {marks}"
3428 );
3429}
3430
3431/// The `back` the sign-out hands im is read per sign-out: an origin saved
3432/// on the running install — the `base_url` setting the settings panel
3433/// writes — takes effect on the very next exit, without a restart. Until
3434/// one is saved, the chain falls back to the config origin, which here is
3435/// the address bound.
3436#[tokio::test]
3437async fn logout_back_follows_the_origin_saved_at_runtime() {
3438 let app = TestApp::build().await;
3439 let cookie = app.sign_in("sub-logout", "logout@in.test", "Logout").await;
3440
3441 // Nothing saved: the listen-derived origin carries the back address.
3442 let page = app.get("/auth/logout", Some(&cookie)).await;
3443 let expected = format!(
3444 "{}/logout?back=http%3A%2F%2F127.0.0.1%3A7655%2F",
3445 app.client.issuer
3446 );
3447 assert_eq!(page.location.as_deref(), Some(expected.as_str()));
3448
3449 // The admin saves a public origin; the next sign-out hands im that.
3450 let answer = app
3451 .post(
3452 "/api/settings/base_url",
3453 Some(&cookie),
3454 &[("base_url", "https://files.example.com")],
3455 )
3456 .await;
3457 assert!(answer.accepted(), "base_url refused: {:?}", answer.location);
3458 let page = app.get("/auth/logout", Some(&cookie)).await;
3459 let expected = format!(
3460 "{}/logout?back=https%3A%2F%2Ffiles.example.com%2F",
3461 app.client.issuer
3462 );
3463 assert_eq!(page.location.as_deref(), Some(expected.as_str()));
3464}
3465
3466// -- settings ---------------------------------------------------------------
3467
3468#[tokio::test]
3469async fn settings_quota_and_disable_guards() {
3470 let app = TestApp::build().await;
3471 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3472 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
3473 let bob_id = owner_of(&app, "sub-bob").await;
3474 let admin_id = owner_of(&app, "sub-admin").await;
3475
3476 let page = app.get("/settings", Some(&admin)).await;
3477 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3478 assert!(page.text().contains("ada@in.test"), "{}", page.text());
3479
3480 // Admin sets Bob's quota in human units: 2 GiB lands as 2147483648 bytes.
3481 let answer = app
3482 .post(
3483 "/api/settings/quota",
3484 Some(&admin),
3485 &[("user_id", &bob_id), ("quota", "2"), ("quota_unit", "GiB")],
3486 )
3487 .await;
3488 assert!(answer.accepted(), "quota refused: {:?}", answer.location);
3489 assert!(
3490 answer
3491 .location
3492 .as_deref()
3493 .is_some_and(|location| location.contains("section=everyone")),
3494 "quota left the Everyone section: {:?}",
3495 answer.location
3496 );
3497 assert_eq!(
3498 app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes,
3499 2147483648
3500 );
3501
3502 // A non-admin is refused the same call.
3503 let answer = app
3504 .post(
3505 "/api/settings/quota",
3506 Some(&bob),
3507 &[
3508 ("user_id", &bob_id),
3509 ("quota", "999"),
3510 ("quota_unit", "MiB"),
3511 ],
3512 )
3513 .await;
3514 assert!(
3515 answer.refused("forbidden", "quota"),
3516 "{:?}",
3517 answer.location
3518 );
3519
3520 // Disabling yourself is refused; disabling Bob signs him out.
3521 let answer = app
3522 .post(
3523 "/api/settings/disable",
3524 Some(&admin),
3525 &[("user_id", &admin_id), ("disabled", "1")],
3526 )
3527 .await;
3528 assert!(
3529 answer.refused("forbidden", "disable"),
3530 "{:?}",
3531 answer.location
3532 );
3533
3534 let answer = app
3535 .post(
3536 "/api/settings/disable",
3537 Some(&admin),
3538 &[("user_id", &bob_id), ("disabled", "1")],
3539 )
3540 .await;
3541 assert!(answer.accepted(), "disable refused: {:?}", answer.location);
3542 assert!(
3543 answer
3544 .location
3545 .as_deref()
3546 .is_some_and(|location| location.contains("section=everyone")),
3547 "disable left the Everyone section: {:?}",
3548 answer.location
3549 );
3550 let page = app.get("/settings", Some(&bob)).await;
3551 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3552 assert!(
3553 !page.text().contains("bob@in.test"),
3554 "disabled account still served: {}",
3555 page.text()
3556 );
3557}
3558
3559/// A deployment with a domain tells that domain, never the bind: the
3560/// settings copy-once banner and the drive modal's link rows all carry
3561/// `base_url`.
3562#[tokio::test]
3563async fn share_links_carry_the_configured_base_url() {
3564 let app = TestApp::build_with(Some("https://files.example.com"), &[]).await;
3565 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3566 let owner = owner_of(&app, "sub-admin").await;
3567 let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
3568
3569 let answer = app
3570 .post(
3571 "/api/share/link/create",
3572 Some(&admin),
3573 &[
3574 ("kind", "file"),
3575 ("target_id", &file),
3576 ("can_download", "1"),
3577 ],
3578 )
3579 .await;
3580 assert!(answer.accepted(), "create refused: {:?}", answer.location);
3581 let token = created_token(answer.location.as_deref().unwrap());
3582
3583 // The banner the mint redirects back to.
3584 let page = app
3585 .get(
3586 &format!("/settings?section=links&created={token}"),
3587 Some(&admin),
3588 )
3589 .await;
3590 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3591 assert!(
3592 page.text()
3593 .contains(&format!("https://files.example.com/s/{token}")),
3594 "banner showed no domain link: {}",
3595 page.text()
3596 );
3597 assert!(
3598 !page.text().contains("127.0.0.1:7655/s/"),
3599 "banner leaked the bind address: {}",
3600 page.text()
3601 );
3602
3603 // The modal says the same — and a sealed link now carries the full
3604 // address, leaving no masked placeholder behind.
3605 let page = app
3606 .get(
3607 &format!("/drive?share=file:{file}&created={token}"),
3608 Some(&admin),
3609 )
3610 .await;
3611 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3612 assert!(
3613 page.text()
3614 .contains(&format!("https://files.example.com/s/{token}")),
3615 "modal showed no domain link: {}",
3616 page.text()
3617 );
3618 assert!(
3619 !page.text().contains("/s/…"),
3620 "modal kept a masked placeholder on a sealed link: {}",
3621 page.text()
3622 );
3623}
3624
3625#[tokio::test]
3626async fn share_links_follow_the_bind_without_a_base_url() {
3627 let app = TestApp::build().await;
3628 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3629 let owner = owner_of(&app, "sub-admin").await;
3630 let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
3631
3632 let answer = app
3633 .post(
3634 "/api/share/link/create",
3635 Some(&admin),
3636 &[
3637 ("kind", "file"),
3638 ("target_id", &file),
3639 ("can_download", "1"),
3640 ],
3641 )
3642 .await;
3643 assert!(answer.accepted(), "create refused: {:?}", answer.location);
3644 let token = created_token(answer.location.as_deref().unwrap());
3645
3646 // No `base_url`: the links say the address bound, as they always
3647 // have.
3648 let page = app
3649 .get(
3650 &format!("/settings?section=links&created={token}"),
3651 Some(&admin),
3652 )
3653 .await;
3654 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3655 assert!(
3656 page.text()
3657 .contains(&format!("http://127.0.0.1:7655/s/{token}")),
3658 "banner showed no bind link: {}",
3659 page.text()
3660 );
3661}
3662
3663/// Mints one link over `file` and returns the plaintext token — and the
3664/// mint must land back on the links section that renders its banner.
3665async fn minted_token(app: &TestApp, cookie: &str, file: &str) -> String {
3666 let answer = app
3667 .post(
3668 "/api/share/link/create",
3669 Some(cookie),
3670 &[("kind", "file"), ("target_id", file), ("can_download", "1")],
3671 )
3672 .await;
3673 assert!(answer.accepted(), "create refused: {:?}", answer.location);
3674 assert!(
3675 answer
3676 .location
3677 .as_deref()
3678 .is_some_and(|location| location.contains("section=links")),
3679 "create left the links section: {:?}",
3680 answer.location
3681 );
3682 created_token(answer.location.as_deref().unwrap())
3683}
3684
3685/// The rail splits the page: every signed-in reader sees Profile and Share
3686/// links, an admin additionally Everyone and Server — and an admin URL a
3687/// non-admin pastes renders the profile, leaking no rows and no form.
3688#[tokio::test]
3689async fn settings_rail_gates_the_admin_sections() {
3690 let app = TestApp::build().await;
3691 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3692 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
3693
3694 // An admin's rail carries all four sections, and the default page is
3695 // the profile alone.
3696 let page = app.get("/settings", Some(&admin)).await;
3697 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3698 let body = page.text();
3699 for section in ["profile", "links", "everyone", "server"] {
3700 assert!(
3701 body.contains(&format!("/settings?section={section}")),
3702 "admin rail lacks {section}: {body}"
3703 );
3704 }
3705 assert!(body.contains("name=\"ui\""), "{}", body);
3706 assert!(!body.contains("member-table"), "{}", body);
3707 assert!(!body.contains("/api/settings/base_url"), "{}", body);
3708
3709 // A non-admin's rail stops at the reader sections.
3710 let page = app.get("/settings", Some(&bob)).await;
3711 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3712 let body = page.text();
3713 assert!(body.contains("/settings?section=profile"), "{}", body);
3714 assert!(body.contains("/settings?section=links"), "{}", body);
3715 assert!(!body.contains("/settings?section=everyone"), "{}", body);
3716 assert!(!body.contains("/settings?section=server"), "{}", body);
3717
3718 // An admin URL pasted by a non-admin answers the profile: no account
3719 // rows, no address form, no origin.
3720 for asked in ["everyone", "server"] {
3721 let page = app
3722 .get(&format!("/settings?section={asked}"), Some(&bob))
3723 .await;
3724 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
3725 let body = page.text();
3726 assert!(body.contains("name=\"ui\""), "not the profile: {body}");
3727 assert!(!body.contains("member-table"), "{body}");
3728 assert!(!body.contains("/api/settings/base_url"), "{body}");
3729 }
3730}
3731
3732/// Each section renders alone on its own `?section=` pair — the profile's
3733/// preferences form, the links panel, the Everyone register, the server
3734/// address form — and never a row or form belonging to another.
3735#[tokio::test]
3736async fn admin_settings_sections_render_alone() {
3737 let app = TestApp::build().await;
3738 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3739 let owner = owner_of(&app, "sub-admin").await;
3740 let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
3741 app.store
3742 .create_share_link(&owner, ShareKind::File, &file, true, None, None)
3743 .await
3744 .unwrap();
3745
3746 let body = app
3747 .get("/settings?section=profile", Some(&admin))
3748 .await
3749 .text();
3750 assert!(body.contains("name=\"ui\""), "{body}");
3751 assert!(!body.contains("/api/share/link/revoke"), "{body}");
3752 assert!(!body.contains("member-table"), "{body}");
3753 assert!(!body.contains("/api/settings/base_url"), "{body}");
3754
3755 let body = app
3756 .get("/settings?section=links", Some(&admin))
3757 .await
3758 .text();
3759 assert!(body.contains("action=\"/api/share/link/revoke\""), "{body}");
3760 assert!(!body.contains("name=\"ui\""), "{body}");
3761 assert!(!body.contains("member-table"), "{body}");
3762 assert!(!body.contains("/api/settings/base_url"), "{body}");
3763
3764 let body = app
3765 .get("/settings?section=everyone", Some(&admin))
3766 .await
3767 .text();
3768 assert!(body.contains("member-table"), "{body}");
3769 assert!(body.contains("ada@in.test"), "{body}");
3770 assert!(!body.contains("name=\"ui\""), "{body}");
3771 assert!(!body.contains("/api/share/link/revoke"), "{body}");
3772 assert!(!body.contains("/api/settings/base_url"), "{body}");
3773
3774 let body = app
3775 .get("/settings?section=server", Some(&admin))
3776 .await
3777 .text();
3778 assert!(body.contains("action=\"/api/settings/base_url\""), "{body}");
3779 // The effective origin shows before anything is stored: the bind.
3780 assert!(body.contains("http://127.0.0.1:7655"), "{body}");
3781 assert!(!body.contains("name=\"ui\""), "{body}");
3782 assert!(!body.contains("member-table"), "{body}");
3783 assert!(!body.contains("/api/share/link/revoke"), "{body}");
3784}
3785
3786/// The admin's server-address form: a valid origin stores the `base_url`
3787/// setting and every newly minted link carries it; a value with no scheme
3788/// or a trailing slash is refused with the setting untouched; saving empty
3789/// clears it and the links fall back to the address bound. A non-admin is
3790/// refused before anything is read.
3791#[tokio::test]
3792async fn server_address_setting_drives_share_links() {
3793 let app = TestApp::build().await;
3794 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3795 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
3796 let owner = owner_of(&app, "sub-admin").await;
3797 let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
3798
3799 let answer = app
3800 .post(
3801 "/api/settings/base_url",
3802 Some(&bob),
3803 &[("base_url", "https://bob.example.net")],
3804 )
3805 .await;
3806 assert!(
3807 answer.refused("forbidden", "base_url"),
3808 "{:?}",
3809 answer.location
3810 );
3811 assert_eq!(app.store.get_setting("base_url").await.unwrap(), None);
3812
3813 let answer = app
3814 .post(
3815 "/api/settings/base_url",
3816 Some(&admin),
3817 &[("base_url", "https://files.example.com")],
3818 )
3819 .await;
3820 assert!(answer.accepted(), "save refused: {:?}", answer.location);
3821 assert!(
3822 answer.location.as_deref().is_some_and(|location| {
3823 location.contains("section=server") && location.contains("saved=base_url")
3824 }),
3825 "{:?}",
3826 answer.location
3827 );
3828 assert_eq!(
3829 app.store.get_setting("base_url").await.unwrap().as_deref(),
3830 Some("https://files.example.com")
3831 );
3832 let token = minted_token(&app, &admin, &file).await;
3833 let page = app
3834 .get(
3835 &format!("/settings?section=links&created={token}"),
3836 Some(&admin),
3837 )
3838 .await;
3839 assert!(
3840 page.text()
3841 .contains(&format!("https://files.example.com/s/{token}")),
3842 "{}",
3843 page.text()
3844 );
3845
3846 // No scheme, or a trailing slash: refused, the stored value untouched.
3847 for bad in ["files.example.com", "https://files.example.com/"] {
3848 let answer = app
3849 .post("/api/settings/base_url", Some(&admin), &[("base_url", bad)])
3850 .await;
3851 assert!(
3852 answer.refused("bad-base-url", "base_url"),
3853 "{bad}: {:?}",
3854 answer.location
3855 );
3856 }
3857 assert_eq!(
3858 app.store.get_setting("base_url").await.unwrap().as_deref(),
3859 Some("https://files.example.com"),
3860 "a refused save changed the setting"
3861 );
3862
3863 // Empty clears: the links fall back to the address bound.
3864 let answer = app
3865 .post("/api/settings/base_url", Some(&admin), &[("base_url", "")])
3866 .await;
3867 assert!(answer.accepted(), "clear refused: {:?}", answer.location);
3868 assert_eq!(
3869 app.store.get_setting("base_url").await.unwrap().as_deref(),
3870 Some("")
3871 );
3872 let token = minted_token(&app, &admin, &file).await;
3873 let page = app
3874 .get(
3875 &format!("/settings?section=links&created={token}"),
3876 Some(&admin),
3877 )
3878 .await;
3879 let body = page.text();
3880 assert!(
3881 body.contains(&format!("http://127.0.0.1:7655/s/{token}")),
3882 "{body}"
3883 );
3884 assert!(!body.contains("https://files.example.com"), "{body}");
3885}
3886
3887/// Clearing a stored origin falls back to the config's `base_url` when the
3888/// file sets one: the setting wins only while it is non-empty.
3889#[tokio::test]
3890async fn cleared_setting_falls_back_to_the_configured_base_url() {
3891 let app = TestApp::build_with(Some("https://cfg.example.com"), &[]).await;
3892 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3893 let owner = owner_of(&app, "sub-admin").await;
3894 let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
3895
3896 let answer = app
3897 .post(
3898 "/api/settings/base_url",
3899 Some(&admin),
3900 &[("base_url", "https://override.example.com")],
3901 )
3902 .await;
3903 assert!(answer.accepted(), "save refused: {:?}", answer.location);
3904 let token = minted_token(&app, &admin, &file).await;
3905 let page = app
3906 .get(
3907 &format!("/settings?section=links&created={token}"),
3908 Some(&admin),
3909 )
3910 .await;
3911 assert!(
3912 page.text()
3913 .contains(&format!("https://override.example.com/s/{token}")),
3914 "{}",
3915 page.text()
3916 );
3917
3918 let answer = app
3919 .post("/api/settings/base_url", Some(&admin), &[("base_url", "")])
3920 .await;
3921 assert!(answer.accepted(), "clear refused: {:?}", answer.location);
3922 let token = minted_token(&app, &admin, &file).await;
3923 let page = app
3924 .get(
3925 &format!("/settings?section=links&created={token}"),
3926 Some(&admin),
3927 )
3928 .await;
3929 let body = page.text();
3930 assert!(
3931 body.contains(&format!("https://cfg.example.com/s/{token}")),
3932 "{body}"
3933 );
3934 assert!(!body.contains("override.example.com"), "{body}");
3935}
3936
3937/// A revoke lands back on the links section that hosts its rows, even for
3938/// a post arriving without a `Referer` to return to.
3939#[tokio::test]
3940async fn revoke_redirects_land_on_the_links_section() {
3941 let app = TestApp::build().await;
3942 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3943 let answer = app
3944 .post(
3945 "/api/share/link/revoke",
3946 Some(&admin),
3947 &[("id", "never-real")],
3948 )
3949 .await;
3950 assert!(
3951 answer
3952 .location
3953 .as_deref()
3954 .is_some_and(|location| location.contains("/settings?section=links")),
3955 "{:?}",
3956 answer.location
3957 );
3958}
3959
3960/// The revoke control is one inline quiet button at the row's end, like
3961/// the modal's remove-access rows — not a full-width block of its own.
3962#[tokio::test]
3963async fn the_settings_revoke_button_sits_inline_in_its_row() {
3964 let app = TestApp::build().await;
3965 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
3966 let owner = owner_of(&app, "sub-admin").await;
3967 let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
3968 app.store
3969 .create_share_link(&owner, ShareKind::File, &file, true, None, None)
3970 .await
3971 .unwrap();
3972
3973 let body = app
3974 .get("/settings?section=links", Some(&admin))
3975 .await
3976 .text();
3977 let row_at = body
3978 .find("<div class=\"member-row\">")
3979 .expect("no share-link row");
3980 let form_at = body[row_at..]
3981 .find("<form class=\"pop-row-form\" method=\"post\" action=\"/api/share/link/revoke\">")
3982 .expect("no revoke form in a member-row");
3983 let form_close = row_at
3984 + form_at
3985 + body[row_at + form_at..]
3986 .find("</form>")
3987 .expect("form never closes");
3988 // The row is still open around the form: its own close is the first
3989 // `</div>` after the form's.
3990 let _row_close = form_close + body[form_close..].find("</div>").expect("row never closes");
3991 let form = &body[row_at + form_at..form_close];
3992 assert!(
3993 form.contains("<button class=\"quiet quiet-danger\" type=\"submit\">"),
3994 "revoke is not the inline quiet button: {form}"
3995 );
3996 assert!(
3997 !form.contains("div"),
3998 "the revoke control is wrapped or outside its row: {form}"
3999 );
4000}
4001
4002#[tokio::test]
4003async fn signed_out_mutations_ask_to_sign_in() {
4004 let app = TestApp::build().await;
4005 for (path, call, form) in [
4006 (
4007 "/api/share/link/create",
4008 "create",
4009 &[("kind", "file"), ("target_id", "x"), ("can_download", "1")][..],
4010 ),
4011 ("/api/share/link/revoke", "revoke", &[("id", "x")][..]),
4012 (
4013 "/api/share/user/add",
4014 "add",
4015 &[("kind", "file"), ("target_id", "x"), ("email", "a@b.c")][..],
4016 ),
4017 (
4018 "/api/trash/restore",
4019 "restore",
4020 &[("kind", "file"), ("id", "x")][..],
4021 ),
4022 ("/api/trash/empty", "empty", &[][..]),
4023 (
4024 "/api/settings/quota",
4025 "quota",
4026 &[("user_id", "x"), ("quota", "1"), ("quota_unit", "GiB")][..],
4027 ),
4028 ] {
4029 let answer = app.post(path, None, form).await;
4030 assert!(
4031 answer.refused("sign-in-first", call),
4032 "{path}: {:?}",
4033 answer.location
4034 );
4035 }
4036 // A never-real token is the dead card, not a stack.
4037 let page = app.get("/s/never-real-token", None).await;
4038 assert_eq!(page.status, StatusCode::OK);
4039 assert!(page.text().contains("no longer works"), "{}", page.text());
4040}
4041
4042#[tokio::test]
4043async fn empty_file_upload_round_trip() {
4044 let app = TestApp::build().await;
4045 let cookie = app.sign_in("sub-empty", "empty@in.test", "Empty").await;
4046 let user = app
4047 .store
4048 .user_by_oidc_sub("sub-empty")
4049 .await
4050 .unwrap()
4051 .unwrap();
4052
4053 let answer = app
4054 .post_multipart(
4055 "/files",
4056 Some(&cookie),
4057 &[("folder_id", "")],
4058 &[("empty.txt", "text/plain", &[])],
4059 )
4060 .await;
4061 assert_eq!(
4062 answer.status,
4063 StatusCode::SEE_OTHER,
4064 "{}",
4065 answer.location.clone().unwrap_or_default()
4066 );
4067 assert!(
4068 !answer
4069 .location
4070 .as_deref()
4071 .unwrap_or("")
4072 .contains("refusal="),
4073 "empty upload was refused: {}",
4074 answer.location.clone().unwrap_or_default()
4075 );
4076
4077 let file = app
4078 .store
4079 .list_children(&user.id, None)
4080 .await
4081 .unwrap()
4082 .files
4083 .into_iter()
4084 .find(|file| file.name == "empty.txt")
4085 .expect("empty file was not stored");
4086 assert_eq!(file.size_bytes, 0);
4087
4088 let got = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
4089 assert_eq!(got.status, StatusCode::OK);
4090 assert!(
4091 got.bytes.is_empty(),
4092 "expected 0 bytes, got {}",
4093 got.bytes.len()
4094 );
4095}
4096
4097/// The 16-byte ISO-BMFF header the mime sniffer reads as `video/mp4`.
4098const CLIP: &[u8] = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00";
4099
4100/// The shell every public /s page must wear: a full document — DOCTYPE and
4101/// the compiled stylesheet — carrying none of the session-gated machinery:
4102/// a stranger's page opens no `/api/live` stream.
4103fn assert_public_shell(page: &Raw, what: &str) {
4104 let body = page.text();
4105 assert!(
4106 body.contains("<!DOCTYPE html>"),
4107 "{what} carried no doctype: {body}"
4108 );
4109 assert!(
4110 body.contains("assets/main-"),
4111 "{what} carried no stylesheet: {body}"
4112 );
4113 assert!(
4114 !body.contains("/api/live") && !body.contains("__inLive"),
4115 "{what} leaked the session-gated live stream: {body}"
4116 );
4117}
4118
4119/// Every public /s answer — card, folder listing, password gate, dead card —
4120/// is a full styled document now, not a bare fragment; none of them opens
4121/// the signed-in live stream at a stranger.
4122#[tokio::test]
4123async fn public_link_pages_wear_the_document_shell() {
4124 let app = TestApp::build().await;
4125 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
4126 let owner = owner_of(&app, "sub-admin").await;
4127 let file = file_id(&app, &owner, "shelled.txt", b"shelled bytes").await;
4128 let answer = app
4129 .post(
4130 "/api/share/link/create",
4131 Some(&admin),
4132 &[
4133 ("kind", "file"),
4134 ("target_id", &file),
4135 ("can_download", "1"),
4136 ("password", "open sesame"),
4137 ],
4138 )
4139 .await;
4140 assert!(answer.accepted(), "create refused: {:?}", answer.location);
4141 let token = created_token(answer.location.as_deref().unwrap());
4142 let link = &app.store.share_links(&owner).await.unwrap()[0];
4143 let proof = in_core::link_unlock_proof(&token, link.password_hash.as_deref().unwrap());
4144 let unlocked = format!("in_link_{}={proof}", link.id);
4145
4146 // The gate: styled, and still saying nothing about the target.
4147 let gate = app.get(&format!("/s/{token}"), None).await;
4148 assert_eq!(gate.status, StatusCode::OK, "{}", gate.text());
4149 assert_public_shell(&gate, "the gate");
4150 assert!(gate.text().contains("type=\"password\""), "{}", gate.text());
4151 assert!(!gate.text().contains("shelled.txt"), "{}", gate.text());
4152
4153 // The unlocked card: the same document shell around the name.
4154 let card = app.get(&format!("/s/{token}"), Some(&unlocked)).await;
4155 assert_eq!(card.status, StatusCode::OK, "{}", card.text());
4156 assert_public_shell(&card, "the card");
4157 assert!(card.text().contains("shelled.txt"), "{}", card.text());
4158
4159 // The dead card: same.
4160 let dead = app.get("/s/never-real-token", None).await;
4161 assert_eq!(dead.status, StatusCode::OK, "{}", dead.text());
4162 assert_public_shell(&dead, "the dead card");
4163
4164 // So is a folder listing.
4165 let folder = app
4166 .store
4167 .create_folder(&owner, None, "shelled folder")
4168 .await
4169 .unwrap();
4170 let created = app
4171 .store
4172 .create_share_link(&owner, ShareKind::Folder, &folder.id, true, None, None)
4173 .await
4174 .unwrap();
4175 let listing = app.get(&format!("/s/{}", created.token), None).await;
4176 assert_eq!(listing.status, StatusCode::OK, "{}", listing.text());
4177 assert_public_shell(&listing, "the folder card");
4178 assert!(
4179 listing.text().contains("shelled folder"),
4180 "{}",
4181 listing.text()
4182 );
4183}
4184
4185/// A video link plays inline through the house player itself — the same
4186/// markup, controls bar and wiring script the signed-in viewer renders, no
4187/// native controls — streaming `?media=1`, ranges included, even on a
4188/// view-only link, while `?dl=1` stays dead and a view never counts as a
4189/// download. A text link draws no player at all.
4190#[tokio::test]
4191async fn video_link_plays_inline_without_download_rights() {
4192 let app = TestApp::build().await;
4193 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
4194 let owner = owner_of(&app, "sub-admin").await;
4195 let clip = file_id(&app, &owner, "clip.mp4", CLIP).await;
4196 let answer = app
4197 .post(
4198 "/api/share/link/create",
4199 Some(&admin),
4200 &[("kind", "file"), ("target_id", &clip)],
4201 )
4202 .await;
4203 assert!(answer.accepted(), "create refused: {:?}", answer.location);
4204 let token = created_token(answer.location.as_deref().unwrap());
4205
4206 // The card: the viewer's player, fed by the public media stream, and no
4207 // download on a view-only link.
4208 let page = app.get(&format!("/s/{token}"), None).await;
4209 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4210 let body = page.text();
4211 assert!(
4212 body.contains("<div class=\"media-player media-player-video\">"),
4213 "no video player: {body}"
4214 );
4215 assert!(
4216 body.contains("<video class=\"media-el viewer-video\""),
4217 "player lost the viewer's classes: {body}"
4218 );
4219 assert!(
4220 body.contains(&format!("<video class=\"media-el viewer-video\" src=\"/s/{token}?media=1\" preload=\"metadata\">")),
4221 "player not fed by ?media=1: {body}"
4222 );
4223 // The house bar and its wiring script — the browser's own controls
4224 // never appear on the element.
4225 assert!(
4226 body.contains("<div class=\"media-controls\">"),
4227 "no house controls bar: {body}"
4228 );
4229 assert!(
4230 body.contains("class=\"media-play\""),
4231 "no play toggle: {body}"
4232 );
4233 assert!(
4234 body.contains("class=\"media-full\""),
4235 "no fullscreen toggle: {body}"
4236 );
4237 assert!(
4238 body.contains("__inMediaWired"),
4239 "house wiring script missing: {body}"
4240 );
4241 assert!(
4242 !body.contains(" controls="),
4243 "native controls leaked onto the card: {body}"
4244 );
4245 assert!(
4246 !body.contains("?dl=1"),
4247 "view-only card offered a download: {body}"
4248 );
4249
4250 // The stream serves ranges: a mid-file probe reads only its span, 206,
4251 // under the stored video mime.
4252 let probe = app
4253 .get_with_range(&format!("/s/{token}?media=1"), None, "bytes=0-3")
4254 .await;
4255 assert_eq!(
4256 probe.status,
4257 StatusCode::PARTIAL_CONTENT,
4258 "{}",
4259 probe.text()
4260 );
4261 assert_eq!(probe.content_type.as_deref(), Some("video/mp4"));
4262 assert_eq!(probe.bytes, &CLIP[0..4]);
4263 assert_eq!(probe.content_range.as_deref(), Some("bytes 0-3/16"));
4264
4265 // A whole fetch is the whole clip, offered inline, and never counted as
4266 // a download — preview is what a view-only link grants.
4267 let full = app.get(&format!("/s/{token}?media=1"), None).await;
4268 assert_eq!(full.status, StatusCode::OK, "{}", full.text());
4269 assert_eq!(full.bytes, CLIP);
4270 assert!(
4271 full.disposition
4272 .as_deref()
4273 .is_some_and(|disposition| disposition.starts_with("inline")),
4274 "the stream was an attachment: {:?}",
4275 full.disposition
4276 );
4277 let stored = app.store.file(&clip).await.unwrap().unwrap();
4278 assert_eq!(stored.download_count, 0, "a media view counted a download");
4279
4280 // The forced download stays dead — the stream is a preview, not the
4281 // grant.
4282 let blocked = app.get(&format!("/s/{token}?dl=1"), None).await;
4283 assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text());
4284 assert!(
4285 blocked.text().contains("no longer works"),
4286 "{}",
4287 blocked.text()
4288 );
4289
4290 // A text link draws no player.
4291 let doc = file_id(&app, &owner, "plain.txt", b"plain").await;
4292 let answer = app
4293 .post(
4294 "/api/share/link/create",
4295 Some(&admin),
4296 &[("kind", "file"), ("target_id", &doc)],
4297 )
4298 .await;
4299 assert!(answer.accepted(), "create refused: {:?}", answer.location);
4300 let text_token = created_token(answer.location.as_deref().unwrap());
4301 let text_card = app.get(&format!("/s/{text_token}"), None).await;
4302 assert_eq!(text_card.status, StatusCode::OK, "{}", text_card.text());
4303 let text_body = text_card.text();
4304 assert!(
4305 !text_body.contains("<video") && !text_body.contains("<audio"),
4306 "a text card drew a player: {text_body}"
4307 );
4308}
4309
4310/// An audio link wears the same house player — bar above the element,
4311/// wiring script included, no native controls, no fullscreen button (that
4312/// is the video variant's) — fed by the public `?media=1` stream.
4313#[tokio::test]
4314async fn audio_link_card_draws_the_house_player() {
4315 let app = TestApp::build().await;
4316 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
4317 let owner = owner_of(&app, "sub-admin").await;
4318 let tone = file_id(&app, &owner, "tone.ogg", b"OggS\x00\x00\x00\x00").await;
4319 let answer = app
4320 .post(
4321 "/api/share/link/create",
4322 Some(&admin),
4323 &[("kind", "file"), ("target_id", &tone)],
4324 )
4325 .await;
4326 assert!(answer.accepted(), "create refused: {:?}", answer.location);
4327 let token = created_token(answer.location.as_deref().unwrap());
4328
4329 let page = app.get(&format!("/s/{token}"), None).await;
4330 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4331 let body = page.text();
4332 assert!(
4333 body.contains("<div class=\"media-player\">"),
4334 "no audio player: {body}"
4335 );
4336 assert!(
4337 body.contains(&format!(
4338 "<audio class=\"media-el\" src=\"/s/{token}?media=1\" preload=\"metadata\">"
4339 )),
4340 "audio element not fed by ?media=1: {body}"
4341 );
4342 // The audio variant draws the bar straight into `.media-player` — no
4343 // `.media-controls` wrapper; that is the video layout's.
4344 assert!(body.contains("class=\"media-seek\""), "no seek bar: {body}");
4345 assert!(
4346 body.contains("class=\"media-play\""),
4347 "no play toggle: {body}"
4348 );
4349 assert!(
4350 body.contains("__inMediaWired"),
4351 "house wiring script missing: {body}"
4352 );
4353 // The button itself stays video-only; the wiring script's `.media-full`
4354 // query is on every player page regardless.
4355 assert!(
4356 !body.contains("class=\"media-full\""),
4357 "audio card drew the fullscreen button: {body}"
4358 );
4359}
4360
4361/// The password gate covers the media stream too: a locked browser is
4362/// answered with the gate, never the bytes, and an unlocked one streams —
4363/// ranges included.
4364#[tokio::test]
4365async fn password_link_gates_the_media_stream() {
4366 let app = TestApp::build().await;
4367 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
4368 let owner = owner_of(&app, "sub-admin").await;
4369 let clip = file_id(&app, &owner, "clip.mp4", CLIP).await;
4370 let answer = app
4371 .post(
4372 "/api/share/link/create",
4373 Some(&admin),
4374 &[
4375 ("kind", "file"),
4376 ("target_id", &clip),
4377 ("password", "open sesame"),
4378 ],
4379 )
4380 .await;
4381 assert!(answer.accepted(), "create refused: {:?}", answer.location);
4382 let token = created_token(answer.location.as_deref().unwrap());
4383
4384 // Locked: the gate, not the clip.
4385 let gated = app.get(&format!("/s/{token}?media=1"), None).await;
4386 assert_eq!(gated.status, StatusCode::OK);
4387 assert!(
4388 gated.text().contains("type=\"password\""),
4389 "the gate did not gate the stream: {}",
4390 gated.text()
4391 );
4392 assert_ne!(
4393 gated.content_type.as_deref(),
4394 Some("video/mp4"),
4395 "the gate leaked the media mime"
4396 );
4397
4398 // Unlocked: the stream serves, ranges included.
4399 let link = &app.store.share_links(&owner).await.unwrap()[0];
4400 let proof = in_core::link_unlock_proof(&token, link.password_hash.as_deref().unwrap());
4401 let unlocked = format!("in_link_{}={proof}", link.id);
4402 let served = app
4403 .get(&format!("/s/{token}?media=1"), Some(&unlocked))
4404 .await;
4405 assert_eq!(served.status, StatusCode::OK, "{}", served.text());
4406 assert_eq!(served.content_type.as_deref(), Some("video/mp4"));
4407 assert_eq!(served.bytes, CLIP);
4408 let span = app
4409 .get_with_range(&format!("/s/{token}?media=1"), Some(&unlocked), "bytes=4-")
4410 .await;
4411 assert_eq!(span.status, StatusCode::PARTIAL_CONTENT);
4412 assert_eq!(span.bytes, &CLIP[4..]);
4413 assert_eq!(span.content_range.as_deref(), Some("bytes 4-15/16"));
4414}
4415
4416// -- share review regressions (FullSilkworm) ------------------------------------
4417
4418#[tokio::test]
4419async fn view_only_download_matches_dead_token() {
4420 let app = TestApp::build().await;
4421 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
4422 let owner = owner_of(&app, "sub-admin").await;
4423 let file = file_id(&app, &owner, "quiet.txt", b"quiet").await;
4424 let answer = app
4425 .post(
4426 "/api/share/link/create",
4427 Some(&admin),
4428 &[
4429 ("kind", "file"),
4430 ("target_id", &file),
4431 ("can_download", "0"),
4432 ],
4433 )
4434 .await;
4435 assert!(answer.accepted(), "create refused: {:?}", answer.location);
4436 let token = created_token(answer.location.as_deref().unwrap());
4437
4438 // A view-only download attempt is the dead card — the same answer as a
4439 // token that never existed, so the surface never says which tokens exist.
4440 let blocked = app.get(&format!("/s/{token}?dl=1"), None).await;
4441 let dead = app.get("/s/never-real-token", None).await;
4442 assert_eq!(blocked.status, dead.status, "{}", blocked.text());
4443 assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text());
4444 assert!(
4445 blocked.text().contains("no longer works"),
4446 "view-only download showed: {}",
4447 blocked.text()
4448 );
4449 assert!(
4450 dead.text().contains("no longer works"),
4451 "dead token showed: {}",
4452 dead.text()
4453 );
4454}
4455
4456#[tokio::test]
4457async fn malformed_expiry_is_forbidden() {
4458 let app = TestApp::build().await;
4459 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
4460 let owner = owner_of(&app, "sub-admin").await;
4461 let file = file_id(&app, &owner, "lease.txt", b"lease").await;
4462 // Non-numeric, zero and negative values must not mint a link — and must
4463 // never silently mint a never-expiring one.
4464 for raw in ["not-a-number", "0", "-2", "1.5"] {
4465 let answer = app
4466 .post(
4467 "/api/share/link/create",
4468 Some(&admin),
4469 &[
4470 ("kind", "file"),
4471 ("target_id", &file),
4472 ("can_download", "1"),
4473 ("expires_in_days", raw),
4474 ],
4475 )
4476 .await;
4477 assert!(
4478 answer.refused("forbidden", "create"),
4479 "{raw:?}: {:?}",
4480 answer.location
4481 );
4482 }
4483 assert!(
4484 app.store.share_links(&owner).await.unwrap().is_empty(),
4485 "a refused mint left a link behind"
4486 );
4487 // A positive value still mints an expiring link; an empty one still means
4488 // no expiry.
4489 let answer = app
4490 .post(
4491 "/api/share/link/create",
4492 Some(&admin),
4493 &[
4494 ("kind", "file"),
4495 ("target_id", &file),
4496 ("can_download", "1"),
4497 ("expires_in_days", "30"),
4498 ],
4499 )
4500 .await;
4501 assert!(
4502 answer.accepted(),
4503 "good expiry refused: {:?}",
4504 answer.location
4505 );
4506 let links = app.store.share_links(&owner).await.unwrap();
4507 assert_eq!(links.len(), 1);
4508 assert!(
4509 links[0].expires_at.is_some(),
4510 "a 30-day link carries no expiry"
4511 );
4512 let answer = app
4513 .post(
4514 "/api/share/link/create",
4515 Some(&admin),
4516 &[
4517 ("kind", "file"),
4518 ("target_id", &file),
4519 ("can_download", "1"),
4520 ("expires_in_days", ""),
4521 ],
4522 )
4523 .await;
4524 assert!(
4525 answer.accepted(),
4526 "empty expiry refused: {:?}",
4527 answer.location
4528 );
4529 let links = app.store.share_links(&owner).await.unwrap();
4530 assert_eq!(links.len(), 2);
4531 assert!(
4532 links.iter().any(|link| link.expires_at.is_none()),
4533 "an empty expiry should mean no expiry"
4534 );
4535}
4536
4537#[tokio::test]
4538async fn unshare_trashed_target_still_revokes() {
4539 let app = TestApp::build().await;
4540 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
4541 let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
4542 let owner = owner_of(&app, "sub-admin").await;
4543 let file = file_id(&app, &owner, "doomed.txt", b"doomed").await;
4544 let answer = app
4545 .post(
4546 "/api/share/user/add",
4547 Some(&admin),
4548 &[
4549 ("kind", "file"),
4550 ("target_id", &file),
4551 ("email", "bob@in.test"),
4552 ("can_download", "1"),
4553 ],
4554 )
4555 .await;
4556 assert!(answer.accepted(), "add refused: {:?}", answer.location);
4557 let bobs = app.get("/shared", Some(&bob)).await;
4558 assert!(bobs.text().contains("doomed.txt"), "{}", bobs.text());
4559
4560 // Trash the target: unsharing must still go through for the owner.
4561 app.store.delete_file(&file).await.unwrap();
4562 let answer = app
4563 .post(
4564 "/api/share/user/remove",
4565 Some(&admin),
4566 &[
4567 ("kind", "file"),
4568 ("target_id", &file),
4569 ("email", "bob@in.test"),
4570 ],
4571 )
4572 .await;
4573 assert!(answer.accepted(), "remove refused: {:?}", answer.location);
4574 // The grant row is really gone: restoring the file does not bring the
4575 // share back to Bob's page.
4576 app.store.restore_file(&file).await.unwrap();
4577 let bobs = app.get("/shared", Some(&bob)).await;
4578 assert!(!bobs.text().contains("doomed.txt"), "{}", bobs.text());
4579}
4580
4581#[tokio::test]
4582async fn view_only_public_thumb_serves_webp() {
4583 let app = TestApp::build().await;
4584 let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
4585 let owner = owner_of(&app, "sub-admin").await;
4586 let png = tiny_png();
4587 let answer = app
4588 .post_multipart(
4589 "/files",
4590 Some(&admin),
4591 &[("folder_id", "")],
4592 &[("dot.png", "image/png", &png)],
4593 )
4594 .await;
4595 assert!(
4596 !answer
4597 .location
4598 .as_deref()
4599 .unwrap_or("")
4600 .contains("refusal="),
4601 "image upload was refused: {}",
4602 answer.location.unwrap_or_default()
4603 );
4604 let file = app
4605 .store
4606 .list_children(&owner, None)
4607 .await
4608 .unwrap()
4609 .files
4610 .into_iter()
4611 .find(|file| file.name == "dot.png")
4612 .expect("image was not stored");
4613 let answer = app
4614 .post(
4615 "/api/share/link/create",
4616 Some(&admin),
4617 &[
4618 ("kind", "file"),
4619 ("target_id", &file.id),
4620 ("can_download", "0"),
4621 ],
4622 )
4623 .await;
4624 assert!(answer.accepted(), "create refused: {:?}", answer.location);
4625 let token = created_token(answer.location.as_deref().unwrap());
4626 // The card previews through the thumb route, never the raw bytes.
4627 let page = app.get(&format!("/s/{token}"), None).await;
4628 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4629 assert!(
4630 page.text().contains("?thumb=1"),
4631 "card previews off nothing public: {}",
4632 page.text()
4633 );
4634 assert!(
4635 !page.text().contains("?dl=1"),
4636 "card must not point at the raw bytes: {}",
4637 page.text()
4638 );
4639 // The card names the grant honestly: viewing happens in the browser
4640 // and anything viewable can be saved — never a "no downloads" claim.
4641 assert!(
4642 page.text().contains("anything viewable can be saved"),
4643 "{}",
4644 page.text()
4645 );
4646 assert!(
4647 !page.text().contains("preview, no downloads"),
4648 "{}",
4649 page.text()
4650 );
4651
4652 // View-only still grants the 512px preview: webp bytes, etag revalidates.
4653 let thumb = app.get(&format!("/s/{token}?thumb=1"), None).await;
4654 assert_eq!(thumb.status, StatusCode::OK, "{}", thumb.text());
4655 assert_eq!(thumb.content_type.as_deref(), Some("image/webp"));
4656 assert_eq!(&thumb.bytes[0..4], b"RIFF");
4657 assert_eq!(&thumb.bytes[8..12], b"WEBP");
4658 let etag = thumb.etag.clone().expect("no etag on the public thumbnail");
4659 let cached = app
4660 .get_with_if_none_match(&format!("/s/{token}?thumb=1"), None, &etag)
4661 .await;
4662 assert_eq!(cached.status, StatusCode::NOT_MODIFIED);
4663
4664 // The full bytes stay behind the download gate even so.
4665 let blocked = app.get(&format!("/s/{token}?dl=1"), None).await;
4666 assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text());
4667 assert!(
4668 blocked.text().contains("no longer works"),
4669 "view-only download showed: {}",
4670 blocked.text()
4671 );
4672
4673 // A dead token's thumb is the dead card, not a stack.
4674 let dead = app.get("/s/never-real-token?thumb=1", None).await;
4675 assert_eq!(dead.status, StatusCode::OK, "{}", dead.text());
4676 assert!(
4677 dead.text().contains("no longer works"),
4678 "dead thumb showed: {}",
4679 dead.text()
4680 );
4681}
4682
4683#[tokio::test]
4684async fn a_name_collision_upload_lands_postfixed() {
4685 let app = TestApp::build().await;
4686 let cookie = app.sign_in("sub-dupe", "dupe@in.test", "Dupe").await;
4687
4688 // Three uploads under one name: none is refused — the later ones land
4689 // with a postfix before the extension instead of wasting the upload.
4690 for body in [b"first" as &[u8], b"second", b"third"] {
4691 let answer = app
4692 .post_multipart(
4693 "/files",
4694 Some(&cookie),
4695 &[("folder_id", "")],
4696 &[("same.txt", "text/plain", body)],
4697 )
4698 .await;
4699 assert!(answer.accepted(), "upload refused: {:?}", answer.location);
4700 }
4701
4702 let page = app.get("/drive", Some(&cookie)).await;
4703 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4704 assert!(page.text().contains("same.txt"), "{}", page.text());
4705 assert!(page.text().contains("same (2).txt"), "{}", page.text());
4706 assert!(page.text().contains("same (3).txt"), "{}", page.text());
4707}
4708
4709// -- settings preferences ------------------------------------------------------
4710
4711#[tokio::test]
4712async fn settings_preferences_round_trip() {
4713 let app = TestApp::build().await;
4714 let cookie = app.sign_in("sub-prefs", "prefs@in.test", "Prefs").await;
4715 let me = owner_of(&app, "sub-prefs").await;
4716
4717 // Instrument, dark and English are the defaults, worn on `<html>` from
4718 // the first render.
4719 let user = app.store.user(&me).await.unwrap().unwrap();
4720 assert_eq!(user.ui, "instrument");
4721 assert_eq!(user.theme, "dark");
4722 assert_eq!(user.language, "en");
4723 let page = app.get("/settings", Some(&cookie)).await;
4724 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4725 assert!(
4726 page.text().contains("data-ui=\"instrument\""),
4727 "{}",
4728 page.text()
4729 );
4730 assert!(
4731 page.text().contains("data-theme=\"dark\""),
4732 "{}",
4733 page.text()
4734 );
4735 assert!(page.text().contains("lang=\"en\""), "{}", page.text());
4736
4737 // Saving all three writes the row and re-renders the chrome — away from
4738 // the defaults, so the render proves the write.
4739 let answer = app
4740 .post(
4741 "/api/settings/preferences",
4742 Some(&cookie),
4743 &[("ui", "ledger"), ("theme", "light"), ("language", "tr")],
4744 )
4745 .await;
4746 assert!(
4747 answer.accepted(),
4748 "preferences refused: {:?}",
4749 answer.location
4750 );
4751 let user = app.store.user(&me).await.unwrap().unwrap();
4752 assert_eq!(user.ui, "ledger");
4753 assert_eq!(user.theme, "light");
4754 assert_eq!(user.language, "tr");
4755
4756 // The redirect carries the saved chip, rendered in the new language.
4757 let page = app
4758 .get(answer.location.as_deref().unwrap(), Some(&cookie))
4759 .await;
4760 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4761 assert!(page.text().contains("Kaydedildi."), "{}", page.text());
4762
4763 let page = app.get("/settings", Some(&cookie)).await;
4764 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4765 assert!(
4766 page.text().contains("data-ui=\"ledger\""),
4767 "{}",
4768 page.text()
4769 );
4770 // Light means no `data-theme` at all.
4771 assert!(!page.text().contains("data-theme="), "{}", page.text());
4772 assert!(page.text().contains("lang=\"tr\""), "{}", page.text());
4773 for name in ["name=\"ui\"", "name=\"theme\"", "name=\"language\""] {
4774 assert!(page.text().contains(name), "{}", page.text());
4775 }
4776
4777 // And back again, to the defaults.
4778 let answer = app
4779 .post(
4780 "/api/settings/preferences",
4781 Some(&cookie),
4782 &[("ui", "instrument"), ("theme", "dark"), ("language", "en")],
4783 )
4784 .await;
4785 assert!(
4786 answer.accepted(),
4787 "preferences refused: {:?}",
4788 answer.location
4789 );
4790 let user = app.store.user(&me).await.unwrap().unwrap();
4791 assert_eq!(user.ui, "instrument");
4792 assert_eq!(user.theme, "dark");
4793 assert_eq!(user.language, "en");
4794}
4795
4796#[tokio::test]
4797async fn settings_preferences_rejects_unknown_values() {
4798 let app = TestApp::build().await;
4799 let cookie = app
4800 .sign_in("sub-prefs-bad", "prefsbad@in.test", "PrefsBad")
4801 .await;
4802 let me = owner_of(&app, "sub-prefs-bad").await;
4803
4804 // Each field is refused with its own code, and the row keeps the last
4805 // good write.
4806 let answer = app
4807 .post(
4808 "/api/settings/preferences",
4809 Some(&cookie),
4810 &[("ui", "mosaic"), ("theme", "light"), ("language", "en")],
4811 )
4812 .await;
4813 assert!(
4814 answer.refused("bad-ui", "preferences"),
4815 "{:?}",
4816 answer.location
4817 );
4818 let answer = app
4819 .post(
4820 "/api/settings/preferences",
4821 Some(&cookie),
4822 &[("ui", "ledger"), ("theme", "dim"), ("language", "en")],
4823 )
4824 .await;
4825 assert!(
4826 answer.refused("bad-theme", "preferences"),
4827 "{:?}",
4828 answer.location
4829 );
4830 let answer = app
4831 .post(
4832 "/api/settings/preferences",
4833 Some(&cookie),
4834 &[("ui", "ledger"), ("theme", "light"), ("language", "xx")],
4835 )
4836 .await;
4837 assert!(
4838 answer.refused("bad-language", "preferences"),
4839 "{:?}",
4840 answer.location
4841 );
4842 let user = app.store.user(&me).await.unwrap().unwrap();
4843 assert_eq!(user.ui, "instrument");
4844 assert_eq!(user.theme, "dark");
4845 assert_eq!(user.language, "en");
4846 let page = app
4847 .get(answer.location.as_deref().unwrap(), Some(&cookie))
4848 .await;
4849 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4850 assert!(
4851 page.text().contains("That is not a language."),
4852 "{}",
4853 page.text()
4854 );
4855
4856 // Signed out, the same post asks to sign in first.
4857 let answer = app
4858 .post(
4859 "/api/settings/preferences",
4860 None,
4861 &[("ui", "instrument"), ("theme", "dark"), ("language", "tr")],
4862 )
4863 .await;
4864 assert!(
4865 answer.refused("sign-in-first", "preferences"),
4866 "{:?}",
4867 answer.location
4868 );
4869}
4870
4871impl TestApp {
4872 /// Like `get`, but carrying an `Accept-Language` header, for the
4873 /// signed-out language fallback.
4874 async fn get_with_lang(&self, path: &str, cookie: Option<&str>, lang: &str) -> Raw {
4875 let mut request = Request::builder()
4876 .method("GET")
4877 .uri(path)
4878 .header(header::ACCEPT_LANGUAGE, lang);
4879 if let Some(cookie) = cookie {
4880 request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
4881 }
4882 let response = self
4883 .router
4884 .handle(request.body(Body::empty()).unwrap())
4885 .await;
4886 let status = response.status();
4887 let bytes = to_bytes(response.into_body(), usize::MAX)
4888 .await
4889 .unwrap()
4890 .to_vec();
4891 Raw {
4892 status,
4893 content_type: None,
4894 disposition: None,
4895 content_range: None,
4896 accept_ranges: None,
4897 cache_control: None,
4898 etag: None,
4899 location: None,
4900 bytes,
4901 }
4902 }
4903}
4904
4905#[tokio::test]
4906async fn signed_out_settings_falls_back_to_accept_language() {
4907 let app = TestApp::build().await;
4908 // No header: English chrome on a light instrument shell.
4909 let page = app.get("/settings", None).await;
4910 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4911 assert!(page.text().contains("lang=\"en\""), "{}", page.text());
4912 // Signed-out wears the family default: a light instrument shell.
4913 assert!(
4914 !page.text().contains("data-theme=\"dark\""),
4915 "{}",
4916 page.text()
4917 );
4918 assert!(
4919 page.text().contains("data-ui=\"instrument\""),
4920 "{}",
4921 page.text()
4922 );
4923 assert!(page.text().contains("Sign in first."), "{}", page.text());
4924 // A Turkish browser is answered in Turkish.
4925 let page = app
4926 .get_with_lang("/settings", None, "tr-TR,tr;q=0.9,en;q=0.8")
4927 .await;
4928 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4929 assert!(page.text().contains("lang=\"tr\""), "{}", page.text());
4930 assert!(page.text().contains("Önce oturum aç."), "{}", page.text());
4931 assert!(page.text().contains("Sürücüye dön"), "{}", page.text());
4932}
4933
4934#[tokio::test]
4935async fn settings_panels_nest_inside_the_stage() {
4936 let app = TestApp::build().await;
4937 let admin = app.sign_in("sub-stage", "stage@in.test", "Stage").await;
4938 let page = app.get("/settings", Some(&admin)).await;
4939 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4940 let body = page.text();
4941 let stage = body
4942 .find("<main class=\"settings-stage")
4943 .expect("no settings-stage");
4944 let close = body.find("</main>").expect("no main close");
4945 for marker in ["panel-head", "name=\"ui\""] {
4946 let at = body.find(marker).unwrap_or_else(|| panic!("no {marker}"));
4947 assert!(stage < at && at < close, "{marker} escapes the stage");
4948 }
4949 // The admin register keeps its named columns, on its own section.
4950 let page = app.get("/settings?section=everyone", Some(&admin)).await;
4951 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
4952 let body = page.text();
4953 let stage = body
4954 .find("<main class=\"settings-stage")
4955 .expect("no settings-stage");
4956 let close = body.find("</main>").expect("no main close");
4957 let at = body.find("member-table").expect("no member-table");
4958 assert!(stage < at && at < close, "member-table escapes the stage");
4959 assert!(body.contains("<th class=\"member-col-name\""), "{body}");
4960}
4961
4962// The /shared and /trash strip fix: content belongs in the stage,
4963// never directly in the flex-row shell. Mirrors
4964// settings_panels_nest_inside_the_stage.
4965fn assert_stage_nests(body: &str, markers: &[&str]) {
4966 assert!(
4967 !body.contains("<main class=\"settings-shell\">"),
4968 "content still sits in the shell: {body}"
4969 );
4970 let stage = body
4971 .find("<main class=\"settings-stage")
4972 .expect("no settings-stage");
4973 let close = body.find("</main>").expect("no main close");
4974 assert!(stage < close, "unclosed stage");
4975 for marker in markers {
4976 let at = body.find(marker).unwrap_or_else(|| panic!("no {marker}"));
4977 assert!(stage < at && at < close, "{marker} escapes the stage");
4978 }
4979}
4980
4981#[tokio::test]
4982async fn shared_lists_nest_inside_the_stage() {
4983 let app = TestApp::build().await;
4984 let admin = app
4985 .sign_in("sub-stage-sharer", "sharer@in.test", "Sharer")
4986 .await;
4987 let bob = app
4988 .sign_in("sub-stage-bob", "stagebob@in.test", "StageBob")
4989 .await;
4990 let owner = owner_of(&app, "sub-stage-sharer").await;
4991 let file = file_id(&app, &owner, "staged.txt", b"staged").await;
4992 let answer = app
4993 .post(
4994 "/api/share/user/add",
4995 Some(&admin),
4996 &[
4997 ("kind", "file"),
4998 ("target_id", &file),
4999 ("email", "stagebob@in.test"),
5000 ("can_download", "1"),
5001 ],
5002 )
5003 .await;
5004 assert!(answer.accepted(), "add refused: {:?}", answer.location);
5005 let page = app.get("/shared", Some(&bob)).await;
5006 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
5007 assert_stage_nests(&page.text(), &["drive-panel", "drive-head", "staged.txt"]);
5008}
5009
5010#[tokio::test]
5011async fn trash_panels_nest_inside_the_stage() {
5012 let app = TestApp::build().await;
5013 let admin = app
5014 .sign_in("sub-stage-trash", "stagetrash@in.test", "StageTrash")
5015 .await;
5016 let owner = owner_of(&app, "sub-stage-trash").await;
5017 let one = file_id(&app, &owner, "staged-trash.txt", b"staged").await;
5018 app.store.delete_file(&one).await.unwrap();
5019 let page = app.get("/trash", Some(&admin)).await;
5020 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
5021 assert_stage_nests(
5022 &page.text(),
5023 &[
5024 "drive-panel",
5025 "drive-head",
5026 "staged-trash.txt",
5027 "action=\"/api/trash/restore\"",
5028 "action=\"/api/trash/empty\"",
5029 ],
5030 );
5031}
5032
5033#[tokio::test]
5034async fn drive_search_panel_nests_inside_the_stage() {
5035 let app = TestApp::build().await;
5036 let admin = app
5037 .sign_in("sub-stage-search", "stagesearch@in.test", "StageSearch")
5038 .await;
5039 let owner = owner_of(&app, "sub-stage-search").await;
5040 file_id(&app, &owner, "staged-report.txt", b"staged").await;
5041 let page = app.get("/drive?q=staged-report", Some(&admin)).await;
5042 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
5043 assert_stage_nests(
5044 &page.text(),
5045 &["drive-panel", "name=\"q\"", "staged-report.txt"],
5046 );
5047}
5048
5049#[tokio::test]
5050async fn public_link_dead_card_survives_the_reskin() {
5051 let app = TestApp::build().await;
5052 // A never-real token is the dead card, not a stack.
5053 let page = app.get("/s/never-real-token", None).await;
5054 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
5055 assert!(page.text().contains("no longer works"), "{}", page.text());
5056 assert!(
5057 page.text().contains("class=\"scaffold-note\""),
5058 "{}",
5059 page.text()
5060 );
5061}
5062
5063#[tokio::test]
5064async fn drive_root_hides_crumbs_while_a_subfolder_shows_them() {
5065 let app = TestApp::build().await;
5066 let cookie = app.sign_in("sub-crumbs", "crumbs@in.test", "Crumbs").await;
5067 let owner = owner_of(&app, "sub-crumbs").await;
5068
5069 // At the root the crumbs nav is pointless chrome: no self-link.
5070 let page = app.get("/drive", Some(&cookie)).await;
5071 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
5072 assert!(!page.text().contains("detail-crumbs"), "{}", page.text());
5073 // The filterbar itself stays, holding the search box and the create form.
5074 assert!(
5075 page.text().contains("class=\"filterbar drive-bar\""),
5076 "{}",
5077 page.text()
5078 );
5079 assert!(page.text().contains("name=\"q\""), "{}", page.text());
5080 assert!(
5081 page.text().contains("action=\"/api/folder/create\""),
5082 "{}",
5083 page.text()
5084 );
5085
5086 // Inside a folder the way back renders.
5087 let answer = app
5088 .post(
5089 "/api/folder/create",
5090 Some(&cookie),
5091 &[("parent_id", ""), ("name", "inside")],
5092 )
5093 .await;
5094 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
5095 let folder = folder_id(&app, &owner, None, "inside").await;
5096 let page = app
5097 .get(&format!("/drive?folder={folder}"), Some(&cookie))
5098 .await;
5099 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
5100 assert!(page.text().contains("detail-crumbs"), "{}", page.text());
5101 assert!(page.text().contains("inside"), "{}", page.text());
5102}
5103
5104#[tokio::test]
5105async fn settings_quota_button_wears_the_quiet_class() {
5106 let app = TestApp::build().await;
5107 let admin = app
5108 .sign_in("sub-quota-btn", "quotabtn@in.test", "QuotaBtn")
5109 .await;
5110 let page = app.get("/settings?section=everyone", Some(&admin)).await;
5111 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
5112 let body = page.text();
5113 // The Set-the-quota submit is a house button in a field row, not a
5114 // native gray one.
5115 assert!(
5116 body.contains("<form class=\"pop-row-form member-quota\""),
5117 "{body}"
5118 );
5119 let quota_at = body
5120 .find("action=\"/api/settings/quota\"")
5121 .expect("no quota form");
5122 let button_at = body[quota_at..]
5123 .find("<button class=\"quiet\" type=\"submit\">")
5124 .expect("quota submit is not quiet");
5125 let form_end = body[quota_at..]
5126 .find("</form>")
5127 .expect("quota form never closes");
5128 assert!(
5129 button_at < form_end,
5130 "quiet button escapes the quota form: {body}"
5131 );
5132}
5133
5134#[tokio::test]
5135async fn settings_lives_in_the_user_menu_not_the_topbar() {
5136 let app = TestApp::build().await;
5137 let cookie = app.sign_in("sub-menu", "menu@in.test", "Menu").await;
5138 let page = app.get("/drive", Some(&cookie)).await;
5139 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
5140 let body = page.text();
5141
5142 // The page nav carries no settings link…
5143 let nav_start = body.find("topbar-nav-links").expect("no nav");
5144 let nav_end = body[nav_start..].find("</nav>").expect("nav never closes");
5145 let nav = &body[nav_start..nav_start + nav_end];
5146 assert!(
5147 !nav.contains("/settings"),
5148 "settings leaked into the nav: {nav}"
5149 );
5150
5151 // …the user menu carries it, plus the profile link out to im.
5152 let menu_start = body.find("user-menu-panel").expect("no user menu");
5153 let menu = &body[menu_start..];
5154 assert!(menu.contains("href=\"/settings\""), "{menu}");
5155 let profile = format!("href=\"{}/people/{}\"", app.config.oidc.issuer, "sub-menu");
5156 assert!(
5157 menu.contains(&profile),
5158 "no profile deep link to im's people page: {menu}"
5159 );
5160}
5161
5162#[tokio::test]
5163async fn avatar_serves_photo_with_a_version_etag() {
5164 let app = TestApp::build().await;
5165 let cookie = app.sign_in("sub-face", "face@in.test", "Face").await;
5166 let me = owner_of(&app, "sub-face").await;
5167 app.fake.set_photo("sub-face", tiny_png(), "image/png");
5168
5169 // Unstamped, the route answers and revalidates: no-cache, the etag the
5170 // row's photo_version spells, a 304 on a matching If-None-Match.
5171 let face = app.get(&format!("/avatar/{me}"), Some(&cookie)).await;
5172 assert_eq!(face.status, StatusCode::OK);
5173 assert_eq!(face.content_type.as_deref(), Some("image/png"));
5174 assert_eq!(
5175 face.cache_control.as_deref(),
5176 Some("private, no-cache"),
5177 "unstamped avatar must revalidate: {:?}",
5178 face.cache_control
5179 );
5180 assert_eq!(face.etag.as_deref(), Some("\"p0\""));
5181 assert_eq!(face.bytes, tiny_png());
5182
5183 let cached = app
5184 .get_with_if_none_match(&format!("/avatar/{me}"), Some(&cookie), "\"p0\"")
5185 .await;
5186 assert_eq!(cached.status, StatusCode::NOT_MODIFIED);
5187 assert!(cached.bytes.is_empty());
5188
5189 // The user menu wears the photo over the initials, stamped with the
5190 // row's version so a changed photo is a changed URL.
5191 let page = app.get("/drive", Some(&cookie)).await;
5192 assert_eq!(page.status, StatusCode::OK);
5193 let body = page.text();
5194 assert!(
5195 body.contains(&format!("src=\"/avatar/{me}?v=0\"")),
5196 "menu wears no versioned photo img"
5197 );
5198 assert!(
5199 body.contains("avatar-stack"),
5200 "no initials stack under the photo"
5201 );
5202 assert!(body.contains("__inAvatar"), "no avatar fallback script");
5203}
5204
5205#[tokio::test]
5206async fn avatar_version_stamped_url_caches_immutable() {
5207 let app = TestApp::build().await;
5208 let cookie = app.sign_in("sub-stamp", "stamp@in.test", "Stamp").await;
5209 let me = owner_of(&app, "sub-stamp").await;
5210 app.fake.set_photo("sub-stamp", tiny_png(), "image/png");
5211
5212 // `?v` equal to the row's version: a year of immutable, no revalidation.
5213 let fresh = app.get(&format!("/avatar/{me}?v=0"), Some(&cookie)).await;
5214 assert_eq!(fresh.status, StatusCode::OK);
5215 assert_eq!(
5216 fresh.cache_control.as_deref(),
5217 Some("private, max-age=31536000, immutable")
5218 );
5219 // A stale stamp — the browser holds a face the row has moved past —
5220 // falls back to revalidate, so the next answer is the truth.
5221 let stale = app.get(&format!("/avatar/{me}?v=7"), Some(&cookie)).await;
5222 assert_eq!(stale.status, StatusCode::OK);
5223 assert_eq!(stale.cache_control.as_deref(), Some("private, no-cache"));
5224 assert_eq!(stale.etag.as_deref(), Some("\"p0\""));
5225}
5226
5227#[tokio::test]
5228async fn avatar_serves_any_member_to_any_signed_in_user() {
5229 let app = TestApp::build().await;
5230 let alice = app
5231 .sign_in("sub-alice-face", "alice@in.test", "Alice")
5232 .await;
5233 let bob = app.sign_in("sub-bob-face", "bob@in.test", "Bob").await;
5234 let bob_id = owner_of(&app, "sub-bob-face").await;
5235 app.fake.set_photo("sub-bob-face", tiny_png(), "image/png");
5236
5237 // Bob's face through Alice's session: a coworker's face renders in her
5238 // topbar too, so the gate is the session, not the id.
5239 let face = app.get(&format!("/avatar/{bob_id}"), Some(&alice)).await;
5240 assert_eq!(face.status, StatusCode::OK);
5241 assert_eq!(face.bytes, tiny_png());
5242
5243 // An id that names nobody provisioned stays the empty answer.
5244 let ghost = app
5245 .get("/avatar/00000000000000000000000000", Some(&alice))
5246 .await;
5247 assert_eq!(ghost.status, StatusCode::NOT_FOUND);
5248
5249 // Bob himself still sees his own.
5250 let own = app.get(&format!("/avatar/{bob_id}"), Some(&bob)).await;
5251 assert_eq!(own.status, StatusCode::OK);
5252 assert_eq!(own.bytes, tiny_png());
5253}
5254
5255#[tokio::test]
5256async fn avatar_without_session_is_unauthorized() {
5257 let app = TestApp::build().await;
5258 let face = app.get("/avatar/anyone", None).await;
5259 assert_eq!(face.status, StatusCode::UNAUTHORIZED);
5260}
5261
5262#[tokio::test]
5263async fn avatar_resolves_local_id_to_oidc_sub() {
5264 // im keys photos by the OIDC sub, while `/avatar/{id}` carries the
5265 // local row id — the two are never equal (ULID vs `sub-*`), so a photo
5266 // map keyed by the sub 404'd before the handler translated the id.
5267 let app = TestApp::build().await;
5268 let cookie = app.sign_in("sub-looks", "looks@in.test", "Looks").await;
5269 let me = owner_of(&app, "sub-looks").await;
5270 assert_ne!(me, "sub-looks", "local id collides with the sub");
5271 app.fake.set_photo("sub-looks", tiny_png(), "image/png");
5272
5273 let face = app.get(&format!("/avatar/{me}"), Some(&cookie)).await;
5274 assert_eq!(face.status, StatusCode::OK);
5275 assert_eq!(face.bytes, tiny_png());
5276}
5277
5278#[tokio::test]
5279async fn drive_add_menu_has_two_items() {
5280 let app = TestApp::build().await;
5281 let cookie = app
5282 .sign_in("sub-addmenu", "addmenu@in.test", "AddMenu")
5283 .await;
5284
5285 let page = app.get("/drive", Some(&cookie)).await;
5286 assert_eq!(page.status, StatusCode::OK);
5287 let body = page.text();
5288
5289 // The filterbar carries one + menu, not the old confirm modal.
5290 assert!(
5291 !body.contains("confirm-details"),
5292 "confirm modal still rendered"
5293 );
5294 assert!(
5295 !body.contains("new-folder-form"),
5296 "modal form still rendered"
5297 );
5298 let details_at = body.find("drive-add").expect("no + menu on the drive");
5299 let details_end = body[details_at..]
5300 .find("</details>")
5301 .expect("menu never closes");
5302 let details = &body[details_at..details_at + details_end];
5303 // New folder: a button-only quick form posting just the parent.
5304 assert!(
5305 details.contains("action=\"/api/folder/create\""),
5306 "quick form escapes the menu: {details}"
5307 );
5308 assert!(
5309 details.contains("name=\"parent_id\""),
5310 "no parent field: {details}"
5311 );
5312 assert!(
5313 !details.contains("name=\"name\""),
5314 "quick form asks for a name: {details}"
5315 );
5316 assert!(
5317 details.contains("New folder"),
5318 "no New folder item: {details}"
5319 );
5320 // Upload files: a label for the panel's own picker, no script needed.
5321 assert!(
5322 details.contains("for=\"drive-upload-input\""),
5323 "no upload label in the menu: {details}"
5324 );
5325 assert!(
5326 details.contains("Upload files"),
5327 "no Upload files item: {details}"
5328 );
5329 assert!(
5330 body.contains("id=\"drive-upload-input\""),
5331 "upload input carries no id for the label"
5332 );
5333}
5334
5335#[tokio::test]
5336async fn drive_quick_create_names_and_edits() {
5337 let app = TestApp::build().await;
5338 let cookie = app.sign_in("sub-quick", "quick@in.test", "Quick").await;
5339 let me = owner_of(&app, "sub-quick").await;
5340
5341 // The + menu posts no name: generic name, 303 into that row's edit mode.
5342 let answer = app
5343 .post("/api/folder/create", Some(&cookie), &[("parent_id", "")])
5344 .await;
5345 assert_eq!(answer.status, StatusCode::SEE_OTHER);
5346 let location = answer
5347 .location
5348 .clone()
5349 .expect("quick create redirects nowhere");
5350 assert!(
5351 location.starts_with("/drive?"),
5352 "quick create leaves the drive: {location}"
5353 );
5354 assert!(
5355 location.contains("edit="),
5356 "quick create skips edit mode: {location}"
5357 );
5358 let edit = location
5359 .split("edit=")
5360 .nth(1)
5361 .expect("no edit id")
5362 .split('&')
5363 .next()
5364 .unwrap();
5365 assert_eq!(folder_id(&app, &me, None, "New folder").await, edit);
5366
5367 // A second quick create never refuses: the store postfixes the generic
5368 // name instead of duplicating it.
5369 let answer = app
5370 .post("/api/folder/create", Some(&cookie), &[("parent_id", "")])
5371 .await;
5372 let location = answer
5373 .location
5374 .clone()
5375 .expect("second quick create redirects nowhere");
5376 let edit2 = location
5377 .split("edit=")
5378 .nth(1)
5379 .expect("no edit id")
5380 .split('&')
5381 .next()
5382 .unwrap();
5383 assert_ne!(edit, edit2, "second quick create reused the row");
5384 let root = app.store.list_children(&me, None).await.unwrap();
5385 let names: Vec<&str> = root
5386 .folders
5387 .iter()
5388 .map(|folder| folder.name.as_str())
5389 .collect();
5390 assert!(
5391 names.contains(&"New folder") && names.contains(&"New folder (2)"),
5392 "second quick create did not postfix the generic name: {names:?}"
5393 );
5394
5395 // A typed name keeps the old answer: back to the page, no edit mode.
5396 let answer = app
5397 .post(
5398 "/api/folder/create",
5399 Some(&cookie),
5400 &[("parent_id", ""), ("name", "typed")],
5401 )
5402 .await;
5403 assert!(
5404 answer.accepted(),
5405 "typed create refused: {:?}",
5406 answer.location
5407 );
5408 assert!(
5409 answer
5410 .location
5411 .as_deref()
5412 .is_some_and(|location| !location.contains("edit=")),
5413 "typed create enters edit mode: {:?}",
5414 answer.location
5415 );
5416 folder_id(&app, &me, None, "typed").await;
5417
5418 let answer = app
5419 .post(
5420 "/api/folder/create",
5421 Some(&cookie),
5422 &[("parent_id", ""), ("name", "typed")],
5423 )
5424 .await;
5425 assert!(
5426 answer.accepted(),
5427 "typed dupe refused: {:?}",
5428 answer.location
5429 );
5430 let root = app.store.list_children(&me, None).await.unwrap();
5431 let names: Vec<&str> = root
5432 .folders
5433 .iter()
5434 .map(|folder| folder.name.as_str())
5435 .collect();
5436 assert!(
5437 names.contains(&"typed") && names.contains(&"typed (2)"),
5438 "typed dupe did not land postfixed: {names:?}"
5439 );
5440}
5441
5442#[tokio::test]
5443async fn drive_edit_row_renders_the_rename_form() {
5444 let app = TestApp::build().await;
5445 let cookie = app
5446 .sign_in("sub-editrow", "editrow@in.test", "EditRow")
5447 .await;
5448 let me = owner_of(&app, "sub-editrow").await;
5449
5450 let answer = app
5451 .post(
5452 "/api/folder/create",
5453 Some(&cookie),
5454 &[("parent_id", ""), ("name", "plans")],
5455 )
5456 .await;
5457 assert!(
5458 answer.accepted(),
5459 "setup create refused: {:?}",
5460 answer.location
5461 );
5462 let id = folder_id(&app, &me, None, "plans").await;
5463
5464 // Plain view: the row is a link with an edit entry, no rename input.
5465 let page = app.get("/drive", Some(&cookie)).await;
5466 let body = page.text();
5467 assert!(
5468 body.contains(&format!("/drive?folder={id}")),
5469 "row links nowhere"
5470 );
5471 assert!(
5472 body.contains(&format!("/drive?edit={id}")),
5473 "row has no edit entry"
5474 );
5475
5476 // Edit view: that row — and only that row — is the rename form, pre-filled.
5477 let page = app.get(&format!("/drive?edit={id}"), Some(&cookie)).await;
5478 assert_eq!(page.status, StatusCode::OK);
5479 let body = page.text();
5480 assert!(
5481 body.contains("action=\"/api/folder/rename\""),
5482 "edit view renders no rename form"
5483 );
5484 assert!(
5485 body.contains("data-edit-focus"),
5486 "rename input carries no focus hook"
5487 );
5488 assert!(
5489 body.contains("value=\"plans\""),
5490 "rename input is not pre-filled"
5491 );
5492 assert!(body.contains("__inEditFocus"), "no edit focus script");
5493}
5494
5495#[tokio::test]
5496async fn drive_lists_folders_before_files_in_one_panel() {
5497 let app = TestApp::build().await;
5498 let cookie = app.sign_in("sub-merged", "merged@in.test", "Merged").await;
5499 let owner = owner_of(&app, "sub-merged").await;
5500 // The file's name sorts first alphabetically, so order proves folders lead.
5501 let file_id = file_id(&app, &owner, "aaa file.txt", b"a").await;
5502 let answer = app
5503 .post(
5504 "/api/folder/create",
5505 Some(&cookie),
5506 &[("parent_id", ""), ("name", "mmm folder")],
5507 )
5508 .await;
5509 assert!(
5510 answer.accepted(),
5511 "setup create refused: {:?}",
5512 answer.location
5513 );
5514
5515 let page = app.get("/drive", Some(&cookie)).await;
5516 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
5517 let body = page.text();
5518 // One panel, no heads or chips — just the merged list.
5519 assert_eq!(
5520 body.matches("<section class=\"panel drive-panel\">")
5521 .count(),
5522 1,
5523 "{body}"
5524 );
5525 assert!(!body.contains("panel-head"), "{body}");
5526 assert!(!body.contains("class=\"chip\""), "{body}");
5527 assert!(!body.contains(">Folders</h2>"), "{body}");
5528 assert!(!body.contains(">Files</h2>"), "{body}");
5529 // Folders first, then files, each wired to its surface.
5530 let folder_at = body.find("mmm folder").expect("no folder row");
5531 let file_at = body.find("aaa file.txt").expect("no file row");
5532 assert!(folder_at < file_at, "file row precedes folder row: {body}");
5533 // Move is a picker modal now: the row's menu links to it, and the modal
5534 // carries the destination rows that post the move.
5535 let folder_id = {
5536 let at = body.find("/drive?folder=").expect("no folder link");
5537 let rest = &body[at + "/drive?folder=".len()..];
5538 let end = rest.find('"').expect("unterminated folder link");
5539 rest[..end].to_string()
5540 };
5541 assert!(
5542 body.contains(&format!("move=folder:{folder_id}")),
5543 "folder row has no move entry: {body}"
5544 );
5545 assert!(
5546 body.contains(&format!("move=file:{file_id}")),
5547 "file row has no move entry: {body}"
5548 );
5549 let picker = app
5550 .get(&format!("/drive?move=folder:{folder_id}"), Some(&cookie))
5551 .await;
5552 let picker_body = picker.text();
5553 assert!(
5554 picker_body.contains("action=\"/api/folder/move\""),
5555 "{picker_body}"
5556 );
5557 // A folder never offers its own subtree as a destination: with only the
5558 // target folder in the tree, the drive root is the one row left.
5559 assert_eq!(
5560 picker_body.matches("class=\"move-pick\"").count(),
5561 1,
5562 "{picker_body}"
5563 );
5564 // File rename follows the folder pattern: an edit link on the plain
5565 // view, the form only on the edit view.
5566 assert!(
5567 body.contains(&format!("/drive?edit={file_id}")),
5568 "file row has no edit entry: {body}"
5569 );
5570 let edit_page = app
5571 .get(&format!("/drive?edit={file_id}"), Some(&cookie))
5572 .await;
5573 assert!(
5574 edit_page.text().contains("action=\"/api/file/rename\""),
5575 "{}",
5576 edit_page.text()
5577 );
5578 // A non-empty list carries no empty state.
5579 assert!(!body.contains("This folder is empty"), "{body}");
5580}
5581
5582#[tokio::test]
5583async fn an_empty_folder_says_how_to_fill_it() {
5584 let app = TestApp::build().await;
5585 let cookie = app.sign_in("sub-empty", "empty@in.test", "Empty").await;
5586 let page = app.get("/drive", Some(&cookie)).await;
5587 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
5588 let body = page.text();
5589 // The single empty state names both ways to fill the folder.
5590 assert!(
5591 body.contains(
5592 "This folder is empty. Press + to create or upload, or drop files on this page."
5593 ),
5594 "no empty-state hint: {body}"
5595 );
5596 assert_eq!(
5597 body.matches("<section class=\"panel drive-panel\">")
5598 .count(),
5599 1,
5600 "{body}"
5601 );
5602 assert!(!body.contains("panel-head"), "{body}");
5603 // And the upload control plus the drop handler the hint promises are on the page.
5604 assert!(body.contains("id=\"upload-form\""), "{body}");
5605 assert!(body.contains("__inDrop"), "{body}");
5606}
5607
5608/// The settings Connection card reads the shared health the sync task
5609/// writes: the issuer and the client id straight from the config, the
5610/// stream wording from the state atomics, and never the client secret —
5611/// the one value the card must not carry onto any page.
5612#[tokio::test]
5613async fn connection_card_shows_issuer_client_id_and_stream_state() {
5614 let app = TestApp::build().await;
5615 let cookie = app.sign_in("sub-conn", "conn@in.test", "Conn").await;
5616
5617 // A fresh process has never opened the stream: the card is amber.
5618 let page = app.get("/settings", Some(&cookie)).await;
5619 assert_eq!(page.status, StatusCode::OK);
5620 let body = page.text();
5621 assert!(body.contains("Connection"), "no card title: {body}");
5622 assert!(
5623 body.contains(app.config.oidc.issuer.as_str()),
5624 "no issuer: {body}"
5625 );
5626 assert!(body.contains("in-test"), "no client id: {body}");
5627 assert!(body.contains("Reconnecting"), "no amber wording: {body}");
5628 assert!(body.contains("connection-wait"), "no amber dot: {body}");
5629 // Before the first occurrences both ages read never — the row is
5630 // there, the number is not.
5631 assert!(body.contains("Last roster event"), "no event row: {body}");
5632 assert!(body.contains("Last full pass"), "no pass row: {body}");
5633 assert!(
5634 body.matches("<dd>never</dd>").count() >= 2,
5635 "both ages must read never: {body}"
5636 );
5637 assert!(
5638 !body.contains("s3cr3t"),
5639 "the client secret reached the page: {body}"
5640 );
5641
5642 // The sync task opens the stream and a full pass heals the mirror:
5643 // green, and both age lines carry numbers now.
5644 app.health.connected();
5645 app.health.note_pass();
5646 app.health.note_event();
5647 let page = app.get("/settings", Some(&cookie)).await;
5648 let body = page.text();
5649 assert!(body.contains("Connected"), "no green wording: {body}");
5650 assert!(body.contains("connection-on"), "no green dot: {body}");
5651 // An age, not never — the number itself races the second boundary
5652 // between the stamp and this render, so only the sentence shape is
5653 // asserted.
5654 assert!(
5655 !body.contains("<dd>never</dd>"),
5656 "ages still read never after both stamps: {body}"
5657 );
5658 assert!(
5659 body.matches(" ago</dd>").count() >= 2,
5660 "ages not sentenced: {body}"
5661 );
5662 // The stream ends: amber again, no event line retraction needed — the
5663 // last event stays but the wording names the truth.
5664 app.health.reconnecting();
5665 let page = app.get("/settings", Some(&cookie)).await;
5666 let body = page.text();
5667 assert!(body.contains("Reconnecting"), "no amber return: {body}");
5668 assert!(!body.contains("connection-on"), "green lingered: {body}");
5669}
5670
5671// ---------------------------------------------------------------------------
5672// The service storage API: bearer keys, machine answers, im's ceilings.
5673// ---------------------------------------------------------------------------
5674
5675/// A minted service account's bearer key, straight off the store.
5676async fn service_key(store: &Arc<dyn Store>, service: &str, name: &str) -> (String, String) {
5677 let token = store
5678 .create_service_account(service, name, 1024 * 1024)
5679 .await
5680 .unwrap();
5681 let account = store.list_service_accounts().await.unwrap();
5682 let user_id = account
5683 .iter()
5684 .find(|account| account.service == service)
5685 .unwrap()
5686 .user_id
5687 .clone();
5688 (token, user_id)
5689}
5690
5691#[tokio::test]
5692async fn service_routes_refuse_a_missing_or_wrong_key() {
5693 let app = TestApp::build().await;
5694 for path in ["/api/service/status", "/api/service/file/some-id"] {
5695 let raw = app.get_bearer(path, None).await;
5696 assert_eq!(raw.status, StatusCode::UNAUTHORIZED, "{path}");
5697 let raw = app.get_bearer(path, None).await;
5698 assert_eq!(
5699 raw.status,
5700 StatusCode::UNAUTHORIZED,
5701 "{path}: {} {:?}",
5702 raw.text(),
5703 raw.cache_control
5704 );
5705 assert_eq!(raw.status, StatusCode::UNAUTHORIZED, "{path}");
5706 }
5707 let raw = app.delete_bearer("/api/service/file/some-id", None).await;
5708 assert_eq!(raw.status, StatusCode::UNAUTHORIZED);
5709 let raw = app
5710 .post_service_multipart("/api/service/files", None, &[], None)
5711 .await;
5712 assert_eq!(raw.status, StatusCode::UNAUTHORIZED);
5713}
5714
5715#[tokio::test]
5716async fn the_service_happy_path_pushes_fetches_counts_and_takes_away() {
5717 let app = TestApp::build().await;
5718 let (token, user_id) = service_key(&app.store, "iz", "İz").await;
5719
5720 // Push: the answer is the file id, and the bytes are the account's.
5721 let raw = app
5722 .post_service_multipart(
5723 "/api/service/files",
5724 Some(&token),
5725 &[("external_id", "att-1"), ("name", "notes.txt")],
5726 Some(("notes.txt", b"hello iz".as_slice())),
5727 )
5728 .await;
5729 assert_eq!(raw.status, StatusCode::OK, "{:?}", raw.text());
5730 let pushed: serde_json::Value = serde_json::from_str(&raw.text()).unwrap();
5731 let file_id = pushed["ok"].as_str().unwrap().to_string();
5732
5733 // Status: the account's ceiling and what it now holds.
5734 let raw = app.get_bearer("/api/service/status", Some(&token)).await;
5735 assert_eq!(raw.status, StatusCode::OK);
5736 let status: serde_json::Value = serde_json::from_str(&raw.text()).unwrap();
5737 assert_eq!(status["ok"], serde_json::Value::Bool(true));
5738 assert_eq!(status["quota_bytes"], 1024 * 1024);
5739 assert_eq!(status["used_bytes"], 8);
5740
5741 // Fetch: the same bytes, the attachment disposition, a year immutable.
5742 let raw = app
5743 .get_bearer("/api/service/file/att-1", Some(&token))
5744 .await;
5745 assert_eq!(raw.status, StatusCode::OK, "GET file: {}", raw.text());
5746 assert_eq!(raw.bytes, b"hello iz".as_slice());
5747 assert_eq!(
5748 raw.cache_control.as_deref(),
5749 Some("private, max-age=31536000, immutable")
5750 );
5751 assert!(raw.disposition.unwrap().contains("notes.txt"));
5752
5753 // The account row agrees with the status: mime sniffed, no thumbnail,
5754 // usage recomputed from the row.
5755 let file = app.store.file(&file_id).await.unwrap().unwrap();
5756 assert_eq!(file.owner_id, user_id);
5757 assert_eq!(file.mime, "text/plain");
5758 assert_eq!(file.thumb_state, in_core::store::ThumbState::None);
5759 let holder = app.store.user(&user_id).await.unwrap().unwrap();
5760 assert_eq!(holder.used_bytes, 8);
5761
5762 // Delete: the row and the bytes are gone, the usage follows.
5763 let raw = app
5764 .delete_bearer("/api/service/file/att-1", Some(&token))
5765 .await;
5766 assert_eq!(raw.status, StatusCode::OK);
5767 assert!(raw.text().contains("\"ok\":true"), "{}", raw.text());
5768 let raw = app
5769 .get_bearer("/api/service/file/att-1", Some(&token))
5770 .await;
5771 assert_eq!(raw.status, StatusCode::NOT_FOUND);
5772 let holder = app.store.user(&user_id).await.unwrap().unwrap();
5773 assert_eq!(holder.used_bytes, 0);
5774}
5775
5776#[tokio::test]
5777async fn a_repush_of_a_known_handle_replaces_bytes_without_a_second_row() {
5778 let app = TestApp::build().await;
5779 let (token, user_id) = service_key(&app.store, "iz", "İz").await;
5780 for payload in [b"first".as_slice(), b"second-and-longer".as_slice()] {
5781 let raw = app
5782 .post_service_multipart(
5783 "/api/service/files",
5784 Some(&token),
5785 &[("external_id", "att-1"), ("name", "notes.txt")],
5786 Some(("notes.txt", payload)),
5787 )
5788 .await;
5789 assert_eq!(raw.status, StatusCode::OK, "{:?}", raw.text());
5790 }
5791 let raw = app
5792 .get_bearer("/api/service/file/att-1", Some(&token))
5793 .await;
5794 assert_eq!(raw.bytes, b"second-and-longer".as_slice());
5795 let holder = app.store.user(&user_id).await.unwrap().unwrap();
5796 // Recomputed from the one row, never incremented past it.
5797 assert_eq!(holder.used_bytes, 17);
5798}
5799
5800#[tokio::test]
5801async fn the_service_quota_is_the_ceiling_the_word_names() {
5802 let app = TestApp::build().await;
5803 // One mebibyte of headroom, then a push past it.
5804 let (token, _) = service_key(&app.store, "iz", "İz").await;
5805 let big = vec![0u8; 2 * 1024 * 1024];
5806 let raw = app
5807 .post_service_multipart(
5808 "/api/service/files",
5809 Some(&token),
5810 &[("external_id", "big"), ("name", "big.bin")],
5811 Some(("big.bin", big.as_slice())),
5812 )
5813 .await;
5814 assert_eq!(raw.status, StatusCode::OK);
5815 assert!(raw.text().contains("QuotaExceeded"), "{}", raw.text());
5816 // A re-push that would not fit over the row it replaces is refused too,
5817 // and the old bytes stay exactly as they were.
5818 let raw = app
5819 .post_service_multipart(
5820 "/api/service/files",
5821 Some(&token),
5822 &[("external_id", "small"), ("name", "small.txt")],
5823 Some(("small.txt", b"tiny".as_slice())),
5824 )
5825 .await;
5826 assert_eq!(raw.status, StatusCode::OK);
5827 // One byte past the ceiling, over the row it replaces: refused.
5828 let overflow = vec![b'a'; 1024 * 1024 + 1];
5829 let raw = app
5830 .post_service_multipart(
5831 "/api/service/files",
5832 Some(&token),
5833 &[("external_id", "small"), ("name", "small.txt")],
5834 Some(("small.txt", overflow.as_slice())),
5835 )
5836 .await;
5837 assert!(raw.text().contains("QuotaExceeded"), "{}", raw.text());
5838 let raw = app
5839 .get_bearer("/api/service/file/small", Some(&token))
5840 .await;
5841 assert_eq!(raw.bytes, b"tiny".as_slice());
5842}
5843
5844#[tokio::test]
5845async fn a_human_browser_is_a_stranger_on_the_machine_routes() {
5846 let app = TestApp::build().await;
5847 let (token, _) = service_key(&app.store, "iz", "İz").await;
5848 let admin = app.sign_in("sub-admin", "admin@example.com", "Admin").await;
5849 // The admin's session cookie buys nothing here.
5850 let raw = app.get("/api/service/status", Some(&admin)).await;
5851 assert_eq!(raw.status, StatusCode::UNAUTHORIZED);
5852 // And the bearer key buys nothing on the human drive.
5853 let raw = app.get_bearer("/drive", Some(&token)).await;
5854 assert!(raw.status.is_redirection() || raw.status == StatusCode::UNAUTHORIZED);
5855}
5856
5857#[tokio::test]
5858async fn the_everyone_quota_write_refuses_a_service_account() {
5859 let app = TestApp::build().await;
5860 // The admin signs in first: the first human sight is the admin, and a
5861 // service row must not claim that.
5862 let admin = app.sign_in("sub-admin", "admin@example.com", "Admin").await;
5863 let (_, user_id) = service_key(&app.store, "iz", "İz").await;
5864 let answer = app
5865 .post(
5866 "/api/settings/quota",
5867 Some(&admin),
5868 &[
5869 ("user_id", user_id.as_str()),
5870 ("quota", "5"),
5871 ("quota_unit", "GiB"),
5872 ],
5873 )
5874 .await;
5875 assert!(
5876 answer.refused("service-quota", "quota"),
5877 "{} {}",
5878 answer.location.as_deref().unwrap_or(""),
5879 answer.body
5880 );
5881 // The ceiling is untouched.
5882 let holder = app.store.user(&user_id).await.unwrap().unwrap();
5883 assert_eq!(holder.quota_bytes, 1024 * 1024);
5884}
5885
5886#[tokio::test]
5887async fn the_mint_shows_its_key_once_and_refuses_a_stranger() {
5888 let app = TestApp::build().await;
5889 app.store
5890 .set_setting(
5891 "family",
5892 r#"[{"key":"iz","name":"İz","url":"http://127.0.0.1:7654","limit_bytes":5368709120}]"#,
5893 )
5894 .await
5895 .unwrap();
5896 let admin = app.sign_in("sub-admin", "admin@example.com", "Admin").await;
5897 let plain = app.sign_in("sub-plain", "plain@example.com", "Plain").await;
5898
5899 // Non-admin: the section reads as the profile, the mint refuses.
5900 let page = app.get("/settings?section=service", Some(&plain)).await;
5901 assert!(
5902 !page.text().contains("Service keys"),
5903 "rail leaked: {}",
5904 page.text()
5905 );
5906 let answer = app
5907 .post(
5908 "/api/settings/service_add",
5909 Some(&plain),
5910 &[("service", "iz"), ("name", "İz")],
5911 )
5912 .await;
5913 assert!(
5914 answer.refused("forbidden", "service_add"),
5915 "{} {}",
5916 answer.location.as_deref().unwrap_or(""),
5917 answer.body
5918 );
5919
5920 // The admin mints; the redirect carries a ticket, not the key.
5921 let answer = app
5922 .post(
5923 "/api/settings/service_add",
5924 Some(&admin),
5925 &[("service", "iz"), ("name", "İz")],
5926 )
5927 .await;
5928 assert!(
5929 answer.accepted(),
5930 "{} {}",
5931 answer.location.as_deref().unwrap_or(""),
5932 answer.body
5933 );
5934 let location = answer.location.unwrap();
5935 let ticket = location
5936 .split("shown=")
5937 .nth(1)
5938 .unwrap()
5939 .split('&')
5940 .next()
5941 .unwrap()
5942 .to_string();
5943 assert!(!ticket.is_empty());
5944
5945 // First render: the key stands in the banner. Second: nothing.
5946 let page = app
5947 .get(
5948 &format!("/settings?section=service&shown={ticket}"),
5949 Some(&admin),
5950 )
5951 .await;
5952 let body = page.text();
5953 assert!(body.contains("service-secret"), "no banner: {body}");
5954 assert!(body.contains("Copy it now"), "{body}");
5955 let start = body.split("service-secret\"").nth(1).unwrap();
5956 let key = start
5957 .split('>')
5958 .nth(1)
5959 .unwrap()
5960 .split('<')
5961 .next()
5962 .unwrap()
5963 .to_string();
5964 assert!(!key.is_empty());
5965 // The store opened the account, and the account opens by that key.
5966 let account = app
5967 .store
5968 .service_account_by_token(&key)
5969 .await
5970 .unwrap()
5971 .expect("the shown key opens");
5972 assert_eq!(account.oidc_sub, "service:iz");
5973 // The replayed URL — the live tick, a reload — renders no banner.
5974 let page = app
5975 .get(
5976 &format!("/settings?section=service&shown={ticket}"),
5977 Some(&admin),
5978 )
5979 .await;
5980 assert!(!page.text().contains("service-secret\""));
5981 let page = app
5982 .get(
5983 "/settings?section=service&shown=forged-ticket",
5984 Some(&admin),
5985 )
5986 .await;
5987 assert!(!page.text().contains("service-secret\""));
5988
5989 // Rotate replaces the key; revoke kills it, the account stays.
5990 let answer = app
5991 .post(
5992 "/api/settings/service_rotate",
5993 Some(&admin),
5994 &[("service", "iz")],
5995 )
5996 .await;
5997 assert!(
5998 answer.accepted(),
5999 "{} {}",
6000 answer.location.as_deref().unwrap_or(""),
6001 answer.body
6002 );
6003 let ticket = answer
6004 .location
6005 .unwrap()
6006 .split("shown=")
6007 .nth(1)
6008 .unwrap()
6009 .to_string();
6010 let page = app
6011 .get(
6012 &format!("/settings?section=service&shown={ticket}"),
6013 Some(&admin),
6014 )
6015 .await;
6016 let rotated = page
6017 .text()
6018 .split("service-secret\"")
6019 .nth(1)
6020 .unwrap()
6021 .split('>')
6022 .nth(1)
6023 .unwrap()
6024 .split('<')
6025 .next()
6026 .unwrap()
6027 .to_string();
6028 assert_ne!(rotated, key);
6029 assert!(
6030 app.store
6031 .service_account_by_token(&key)
6032 .await
6033 .unwrap()
6034 .is_none()
6035 );
6036 let answer = app
6037 .post(
6038 "/api/settings/service_revoke",
6039 Some(&admin),
6040 &[("service", "iz")],
6041 )
6042 .await;
6043 assert!(
6044 answer.accepted(),
6045 "{} {}",
6046 answer.location.as_deref().unwrap_or(""),
6047 answer.body
6048 );
6049 assert!(
6050 app.store
6051 .service_account_by_token(&rotated)
6052 .await
6053 .unwrap()
6054 .is_none()
6055 );
6056 let accounts = app.store.list_service_accounts().await.unwrap();
6057 assert!(
6058 accounts.is_empty(),
6059 "revoke took the row, not the account: the account row stays"
6060 );
6061}
6062
6063#[tokio::test]
6064async fn the_family_limit_lands_on_the_account() {
6065 let app = TestApp::build().await;
6066 // im names a 5 GiB ceiling for iz; the beat carries it.
6067 app.fake.set_family(vec![serde_json::json!({
6068 "key": "iz",
6069 "name": "İz",
6070 "url": "http://127.0.0.1:7654",
6071 "limit_bytes": 5 * 1024 * 1024 * 1024u64,
6072 })]);
6073 let client = in_client::InClient::new(app.client.clone());
6074 let family = client.family().await.expect("the fake answered");
6075 assert_eq!(family[0].limit_bytes, Some(5 * 1024 * 1024 * 1024));
6076 in_web::service::apply_family_limits(&app.store, &family, 1024 * 1024)
6077 .await
6078 .unwrap();
6079 let accounts = app.store.list_service_accounts().await.unwrap();
6080 assert!(accounts.is_empty(), "no key, no account to ceiling");
6081 let (token, user_id) = service_key(&app.store, "iz", "İz").await;
6082 let _ = token;
6083 // Before a beat the account sits at the default; im's word moves it.
6084 in_web::service::apply_family_limits(&app.store, &family, 1024 * 1024)
6085 .await
6086 .unwrap();
6087 let holder = app.store.user(&user_id).await.unwrap().unwrap();
6088 assert_eq!(holder.quota_bytes, 5 * 1024 * 1024 * 1024);
6089 // No limit named: the house default.
6090 app.fake.set_family(vec![serde_json::json!({
6091 "key": "iz",
6092 "name": "İz",
6093 "url": "http://127.0.0.1:7654",
6094 })]);
6095 let family = client.family().await.unwrap();
6096 assert_eq!(family[0].limit_bytes, None);
6097 in_web::service::apply_family_limits(&app.store, &family, 1024 * 1024)
6098 .await
6099 .unwrap();
6100 let holder = app.store.user(&user_id).await.unwrap().unwrap();
6101 assert_eq!(holder.quota_bytes, 1024 * 1024);
6102}
6103
6104/// How long one wait for a live frame may run before the test fails
6105/// loudly. A stream that never speaks is a hang, not an answer.
6106const FRAME_PATIENCE: std::time::Duration = std::time::Duration::from_secs(5);
6107
6108/// One open `/api/live` connection, held the way a browser holds it: the
6109/// frames are read as they arrive, and the end of the body is itself
6110/// news — a stream the server closed behind its last word.
6111struct LiveStream {
6112 status: StatusCode,
6113 content_type: Option<String>,
6114 body: Body,
6115 /// Bytes read but not yet through a blank-line frame boundary; an
6116 /// SSE event may straddle two body chunks.
6117 buffer: String,
6118}
6119
6120impl LiveStream {
6121 /// The next complete SSE frame, or `None` when the stream ended. A
6122 /// frame that never arrives fails the test rather than outlasting it.
6123 async fn next_frame(&mut self) -> Option<String> {
6124 loop {
6125 if let Some(at) = self.buffer.find("\n\n") {
6126 return Some(self.buffer.drain(..at + 2).collect::<String>());
6127 }
6128 let polled = tokio::time::timeout(FRAME_PATIENCE, self.body.frame())
6129 .await
6130 .expect("no frame arrived in time");
6131 // `None` is the body running out — the stream's end, which is
6132 // the caller's news. Anything else is a frame to buffer.
6133 let Some(polled) = polled else {
6134 return None;
6135 };
6136 let frame = polled.expect("the live body failed");
6137 let chunk = frame.into_data().expect("a frame with no data");
6138 self.buffer.push_str(&String::from_utf8_lossy(&chunk));
6139 }
6140 }
6141}
6142
6143impl TestApp {
6144 /// Opens the signed-in live stream and keeps it, unread — the frame
6145 /// reader works on the body [`LiveStream`] holds.
6146 async fn open_live(&self, cookie: &str) -> LiveStream {
6147 let response = self
6148 .router
6149 .handle(
6150 Request::builder()
6151 .method("GET")
6152 .uri("/api/live")
6153 .header(header::COOKIE, HeaderValue::from_str(cookie).unwrap())
6154 .body(Body::empty())
6155 .unwrap(),
6156 )
6157 .await;
6158 let status = response.status();
6159 let content_type = response
6160 .headers()
6161 .get(header::CONTENT_TYPE)
6162 .and_then(|value| value.to_str().ok())
6163 .map(str::to_string);
6164 LiveStream {
6165 status,
6166 content_type,
6167 body: response.into_body(),
6168 buffer: String::new(),
6169 }
6170 }
6171}
6172
6173/// The sign-in probe the live channel's error path polls: 204 while the
6174/// session stands, 401 the moment it does not. A locally disabled
6175/// account reads as signed out even though im's introspection would
6176/// still vouch for the very same cookie — the local flag outranks it.
6177#[tokio::test]
6178async fn the_me_probe_answers_204_while_signed_in_and_401_the_moment_not() {
6179 let app = TestApp::build().await;
6180 let out = app.get("/api/me", None).await;
6181 assert_eq!(out.status, StatusCode::UNAUTHORIZED);
6182 assert!(out.bytes.is_empty(), "no body: {:?}", out.text());
6183
6184 let cookie = app.sign_in("sub-probe", "probe@in.test", "Probe").await;
6185 let in_answer = app.get("/api/me", Some(&cookie)).await;
6186 assert_eq!(in_answer.status, StatusCode::NO_CONTENT);
6187 assert!(in_answer.bytes.is_empty(), "no body on 204 either");
6188
6189 let user = app
6190 .store
6191 .user_by_oidc_sub("sub-probe")
6192 .await
6193 .unwrap()
6194 .unwrap();
6195 app.store.set_user_disabled(&user.id, true).await.unwrap();
6196 let disabled = app.get("/api/me", Some(&cookie)).await;
6197 assert_eq!(disabled.status, StatusCode::UNAUTHORIZED);
6198}
6199
6200/// A user-level kill — the disabled flag mirrored from im — rides the
6201/// ordinary topic bus, but its frame goes to exactly one listener: the
6202/// killed account's own open tabs, each answered with the bare revoked
6203/// frame and then an ended stream. Everybody else hears an ordinary
6204/// profile move and keeps their stream.
6205#[tokio::test]
6206async fn a_user_level_kill_orders_its_own_tabs_out_and_nobody_else() {
6207 let app = TestApp::build().await;
6208 let alice_cookie = app.sign_in("sub-alice", "alice@in.test", "Alice").await;
6209 let bob_cookie = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
6210 let mut alice = app.open_live(&alice_cookie).await;
6211 let mut bob = app.open_live(&bob_cookie).await;
6212 assert_eq!(alice.status, StatusCode::OK);
6213 assert_eq!(
6214 alice.content_type.as_deref(),
6215 Some("text/event-stream"),
6216 "the live channel is an event stream"
6217 );
6218
6219 // The kill: im's mirror flips the local flag; the store announces.
6220 let alice_id = app
6221 .store
6222 .user_by_oidc_sub("sub-alice")
6223 .await
6224 .unwrap()
6225 .unwrap()
6226 .id;
6227 app.store.set_user_disabled(&alice_id, true).await.unwrap();
6228
6229 // Bob hears the profile move — and only that. The revoked frame is
6230 // an order no bystander ever receives.
6231 let heard = bob.next_frame().await.unwrap();
6232 assert!(
6233 heard.contains("\"topic\":\"profile\""),
6234 "bob heard: {heard}"
6235 );
6236
6237 // Alice hears her own kill as the bare frame, and the stream ends
6238 // behind it — nothing on a dead account's connection lingers.
6239 loop {
6240 let heard = alice.next_frame().await.unwrap();
6241 if heard.contains("\"topic\":\"revoked\"") {
6242 break;
6243 }
6244 }
6245 assert!(
6246 alice.next_frame().await.is_none(),
6247 "the killed tab's stream must end behind the revoked frame"
6248 );
6249
6250 // Bob's stream survived Alice's kill: his own kill reaches it.
6251 let bob_id = app
6252 .store
6253 .user_by_oidc_sub("sub-bob")
6254 .await
6255 .unwrap()
6256 .unwrap()
6257 .id;
6258 app.store.set_user_disabled(&bob_id, true).await.unwrap();
6259 loop {
6260 let heard = bob.next_frame().await.unwrap();
6261 if heard.contains("\"topic\":\"revoked\"") {
6262 break;
6263 }
6264 }
6265 assert!(bob.next_frame().await.is_none(), "bob's stream ends too");
6266}
6267/// The finding's surface, end to end: a folder grant turns the shared
6268/// page's `/drive?folder=` link into a read-only browse — the listing with
6269/// its subfolder and file rows, descent into the subtree, the honest
6270/// access tell — with no write affordance anywhere, no sibling named, the
6271/// owner's own page for the same folder untouched, and a 404 the moment
6272/// the grant is gone.
6273#[tokio::test]
6274async fn granted_folder_browses_read_only() {
6275 let app = TestApp::build().await;
6276 let ada = app.sign_in("sub-ada", "ada-grant@in.test", "Ada").await;
6277 let bob = app.sign_in("sub-bob", "bob-grant@in.test", "Bob").await;
6278 let cara = app.sign_in("sub-cara", "cara-grant@in.test", "Cara").await;
6279 let owner = owner_of(&app, "sub-ada").await;
6280
6281 // Ada's tree: `trip` holding `inner` and a note, `secret` beside it.
6282 let answer = app
6283 .post(
6284 "/api/folder/create",
6285 Some(&ada),
6286 &[("parent_id", ""), ("name", "trip")],
6287 )
6288 .await;
6289 assert!(answer.accepted(), "create refused: {:?}", answer.location);
6290 let trip = folder_id(&app, &owner, None, "trip").await;
6291 let answer = app
6292 .post(
6293 "/api/folder/create",
6294 Some(&ada),
6295 &[("parent_id", &trip), ("name", "inner")],
6296 )
6297 .await;
6298 assert!(answer.accepted(), "create refused: {:?}", answer.location);
6299 let inner = folder_id(&app, &owner, Some(&trip), "inner").await;
6300 let note = app
6301 .store
6302 .insert_file(&owner, Some(&trip), "note.txt", b"note bytes")
6303 .await
6304 .unwrap()
6305 .id;
6306 app.post(
6307 "/api/folder/create",
6308 Some(&ada),
6309 &[("parent_id", ""), ("name", "secret")],
6310 )
6311 .await;
6312 let secret = folder_id(&app, &owner, None, "secret").await;
6313
6314 let answer = app
6315 .post(
6316 "/api/share/user/add",
6317 Some(&ada),
6318 &[
6319 ("kind", "folder"),
6320 ("target_id", &trip),
6321 ("email", "bob-grant@in.test"),
6322 ("can_download", "1"),
6323 ],
6324 )
6325 .await;
6326 assert!(answer.accepted(), "grant refused: {:?}", answer.location);
6327
6328 // The grant opens the browse where a stranger's tree would 404.
6329 let page = app.get(&format!("/drive?folder={trip}"), Some(&bob)).await;
6330 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
6331 let body = page.text();
6332 assert!(body.contains("inner"), "{body}");
6333 assert!(body.contains("note.txt"), "{body}");
6334 assert!(body.contains(&format!("/drive?folder={inner}")), "{body}");
6335 assert!(body.contains(&format!("/view/{note}")), "{body}");
6336 // The honest tell names the grant's reach.
6337 assert!(body.contains("Shared with you"), "{body}");
6338 assert!(body.contains("May download"), "{body}");
6339 // And the page offers nothing to write with: no + menu, no upload, no
6340 // row options, no rename, move, share, or delete anywhere on it.
6341 for absent in [
6342 "/api/folder/create",
6343 "/api/folder/rename",
6344 "/api/folder/delete",
6345 "/api/file/rename",
6346 "/api/file/delete",
6347 "share=folder:",
6348 "share=file:",
6349 "move=folder:",
6350 "move=file:",
6351 "&edit=",
6352 "?dl=1",
6353 "upload-form",
6354 "drive-upload-input",
6355 "drop-overlay",
6356 "drive-add",
6357 "entry-options",
6358 ] {
6359 assert!(
6360 !body.contains(absent),
6361 "grantee page offers {absent}: {body}"
6362 );
6363 }
6364 // Nothing beside the grant is named, let alone linked.
6365 assert!(
6366 !body.contains(&format!("/drive?folder={secret}")),
6367 "grantee page links the ungranted sibling: {body}"
6368 );
6369 assert!(
6370 !body.contains(">secret</span>"),
6371 "grantee page renders the ungranted sibling: {body}"
6372 );
6373
6374 // Descent into the granted subtree is the same read-only browse one
6375 // level down, and the trail stops at the granted folder: `trip` is
6376 // named, the drive root above it never is.
6377 let deep = app
6378 .store
6379 .insert_file(&owner, Some(&inner), "deep.txt", b"deep")
6380 .await
6381 .unwrap()
6382 .id;
6383 let page = app.get(&format!("/drive?folder={inner}"), Some(&bob)).await;
6384 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
6385 let body = page.text();
6386 assert!(body.contains("deep.txt"), "{body}");
6387 assert!(body.contains(&format!("/view/{deep}")), "{body}");
6388 assert!(body.contains(&format!("/drive?folder={trip}")), "{body}");
6389 assert!(
6390 !body.contains("detail-crumb\" href=\"/drive\""),
6391 "grantee trail climbs out of the grant: {body}"
6392 );
6393
6394 // The owner's own page for the same folder is exactly what it was.
6395 let page = app.get(&format!("/drive?folder={trip}"), Some(&ada)).await;
6396 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
6397 assert!(page.text().contains("upload-form"), "{}", page.text());
6398
6399 // A bystander without the grant sees nothing at all.
6400 let page = app.get(&format!("/drive?folder={trip}"), Some(&cara)).await;
6401 assert_eq!(page.status, StatusCode::NOT_FOUND, "{}", page.text());
6402 let page = app
6403 .get(&format!("/drive?folder={secret}"), Some(&bob))
6404 .await;
6405 assert_eq!(page.status, StatusCode::NOT_FOUND, "{}", page.text());
6406
6407 // Revoke and the same address is the plain not-found again.
6408 let answer = app
6409 .post(
6410 "/api/share/user/remove",
6411 Some(&ada),
6412 &[
6413 ("kind", "folder"),
6414 ("target_id", &trip),
6415 ("email", "bob-grant@in.test"),
6416 ],
6417 )
6418 .await;
6419 assert!(answer.accepted(), "remove refused: {:?}", answer.location);
6420 let page = app.get(&format!("/drive?folder={trip}"), Some(&bob)).await;
6421 assert_eq!(page.status, StatusCode::NOT_FOUND, "{}", page.text());
6422}
6423
6424/// The grant's edge is exactly the granted subtree: a folder granted deeper
6425/// opens while its parent and siblings do not, the trail never climbs out,
6426/// a view-only grant says so while its files preview but stay download-dead,
6427/// and a trashed branch closes the path until the owner restores it.
6428#[tokio::test]
6429async fn grant_edges_close_the_browse() {
6430 let app = TestApp::build().await;
6431 let ada = app.sign_in("sub-ada", "ada-edges@in.test", "Ada").await;
6432 let bob = app.sign_in("sub-bob", "bob-edges@in.test", "Bob").await;
6433 let owner = owner_of(&app, "sub-ada").await;
6434
6435 // outer/inner with `beside` off the path; only `inner` is granted.
6436 let answer = app
6437 .post(
6438 "/api/folder/create",
6439 Some(&ada),
6440 &[("parent_id", ""), ("name", "outer")],
6441 )
6442 .await;
6443 assert!(answer.accepted(), "create refused: {:?}", answer.location);
6444 let outer = folder_id(&app, &owner, None, "outer").await;
6445 let answer = app
6446 .post(
6447 "/api/folder/create",
6448 Some(&ada),
6449 &[("parent_id", &outer), ("name", "inner")],
6450 )
6451 .await;
6452 assert!(answer.accepted(), "create refused: {:?}", answer.location);
6453 let inner = folder_id(&app, &owner, Some(&outer), "inner").await;
6454 app.post(
6455 "/api/folder/create",
6456 Some(&ada),
6457 &[("parent_id", ""), ("name", "beside")],
6458 )
6459 .await;
6460 let beside = folder_id(&app, &owner, None, "beside").await;
6461 let pic = app
6462 .store
6463 .insert_file(&owner, Some(&inner), "pic.png", &tiny_png())
6464 .await
6465 .unwrap()
6466 .id;
6467
6468 let answer = app
6469 .post(
6470 "/api/share/user/add",
6471 Some(&ada),
6472 &[
6473 ("kind", "folder"),
6474 ("target_id", &inner),
6475 ("email", "bob-edges@in.test"),
6476 ("can_download", "0"),
6477 ],
6478 )
6479 .await;
6480 assert!(answer.accepted(), "grant refused: {:?}", answer.location);
6481
6482 // The granted folder opens, view-only on its face; the parent, a
6483 // sibling, and the trail above the grant all stay closed.
6484 let page = app.get(&format!("/drive?folder={inner}"), Some(&bob)).await;
6485 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
6486 let body = page.text();
6487 assert!(body.contains("View only"), "{body}");
6488 assert!(!body.contains("May download"), "{body}");
6489 assert!(
6490 !body.contains(&format!("/drive?folder={outer}")),
6491 "trail names the ungranted parent: {body}"
6492 );
6493 let page = app.get(&format!("/drive?folder={outer}"), Some(&bob)).await;
6494 assert_eq!(page.status, StatusCode::NOT_FOUND, "{}", page.text());
6495 let page = app
6496 .get(&format!("/drive?folder={beside}"), Some(&bob))
6497 .await;
6498 assert_eq!(page.status, StatusCode::NOT_FOUND, "{}", page.text());
6499
6500 // The file previews through the folder grant, but taking it away is
6501 // refused — the view-only grant opens the page, not the bytes.
6502 let view = app.get(&format!("/view/{pic}"), Some(&bob)).await;
6503 assert_eq!(view.status, StatusCode::OK, "{}", view.text());
6504 assert!(
6505 !view.text().contains("?dl=1"),
6506 "view-only viewer offers a download: {}",
6507 view.text()
6508 );
6509 let bytes = app.get(&format!("/file/{pic}?dl=1"), Some(&bob)).await;
6510 assert_eq!(bytes.status, StatusCode::NOT_FOUND);
6511 let preview = app.get(&format!("/file/{pic}"), Some(&bob)).await;
6512 assert_eq!(preview.status, StatusCode::OK);
6513
6514 // The same grant refreshed with download opens the bytes too.
6515 let answer = app
6516 .post(
6517 "/api/share/user/add",
6518 Some(&ada),
6519 &[
6520 ("kind", "folder"),
6521 ("target_id", &inner),
6522 ("email", "bob-edges@in.test"),
6523 ("can_download", "1"),
6524 ],
6525 )
6526 .await;
6527 assert!(answer.accepted(), "re-grant refused: {:?}", answer.location);
6528 let page = app.get(&format!("/drive?folder={inner}"), Some(&bob)).await;
6529 assert!(page.text().contains("May download"), "{}", page.text());
6530 let bytes = app.get(&format!("/file/{pic}?dl=1"), Some(&bob)).await;
6531 assert_eq!(bytes.status, StatusCode::OK);
6532 assert!(
6533 bytes
6534 .disposition
6535 .as_deref()
6536 .is_some_and(|value| value.starts_with("attachment")),
6537 "download did not land as a file: {:?}",
6538 bytes.disposition
6539 );
6540
6541 // Trashing the granted folder closes the whole path — the grant row
6542 // survives, but trash is unreachable — and restoring reopens it.
6543 let answer = app
6544 .post("/api/folder/delete", Some(&ada), &[("id", &inner)])
6545 .await;
6546 assert!(answer.accepted(), "delete refused: {:?}", answer.location);
6547 let page = app.get(&format!("/drive?folder={inner}"), Some(&bob)).await;
6548 assert_eq!(page.status, StatusCode::NOT_FOUND, "{}", page.text());
6549 let view = app.get(&format!("/view/{pic}"), Some(&bob)).await;
6550 assert_eq!(view.status, StatusCode::NOT_FOUND, "{}", view.text());
6551 app.store.restore_folder(&inner).await.unwrap();
6552 let page = app.get(&format!("/drive?folder={inner}"), Some(&bob)).await;
6553 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
6554 assert!(page.text().contains("pic.png"), "{}", page.text());
6555}