forge
Explore
Log in

Don't you dare go Hollow

iz_old

Clone
★ 0

0 watching0 forksRustGPL-3.02.2 MiB4c154b4Tahinli2 months ago301 commits

http.rs11273 lines, 372.1 KiBHistoryRawDownload
1//! The app driven the way a browser drives it: real router, real handlers, real
2//! session cookie.
3//!
4//! The point of this binary is the guards. A button the UI does not draw proves
5//! nothing — a Viewer who posts to the mutation endpoint anyway must be refused
6//! by the handler, and that is what these tests call.
7//!
8//! New HTTP tests belong in this file rather than a new `tests/*.rs`: one test
9//! binary links and runs once.
10//!
11//! Ported from the Leptos-era `iz-web`'s `tests/http.rs`. That app answered
12//! a hydrated caller with `200` and a JSON body; this one is server-rendered
13//! and every mutating `/api/*` route always answers `303 See Other` (topcoat's
14//! `see_other`, not the old stack's `302 Found`), carrying the same JSON body
15//! (`Option<Refusal>` or a domain value) that this file's assertions already
16//! read off `Answer::body`. `path::<ServerFn>()` is gone with the server
17//! functions themselves — routes are now literal `/api/...` strings, kept as
18//! `const` items below so a rename shows up once.
19#![cfg(test)]
20
21use std::collections::HashMap;
22use std::path::PathBuf;
23use std::sync::Arc;
24
25use parking_lot::Mutex;
26
27use http::{HeaderValue, Request, StatusCode, header};
28use iz_core::Role;
29use iz_core::board::Moved;
30use iz_core::store::{Audience, MailOutcome, SendKind, SendState, Store, Trigger, TursoStore};
31use iz_web::directory::{StreamFrame, StreamMember, apply_frame};
32use iz_web::server::Mail;
33use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};
34use topcoat::cookie::RouterBuilderCookieExt;
35use topcoat::router::{Body, BodyLimit, Router, RouterBuilderDiscoverExt, to_bytes};
36use topcoat::runtime::RouterBuilderRuntimeExt;
37use ulid::Ulid;
38
39/// The session cookie iz-client seals: the tests mint it directly instead of
40/// driving a browser through the OIDC round-trip.
41const SESSION_COOKIE: &str = "iz_session";
42
43/// The bundle `cargo build -p iz-web` + `topcoat asset bundle --bin
44/// iz-web` write next to the crate's own `target/debug`, not next to the
45/// test binary (which lives in `target/debug/deps`) — `AssetBundle::load`
46/// looks beside `current_exe` and would miss it, so the path is given
47/// explicitly instead.
48fn asset_dir() -> PathBuf {
49 PathBuf::from(concat!(
50 env!("CARGO_MANIFEST_DIR"),
51 "/../../target/debug/assets"
52 ))
53}
54
55/// A live connection in the suite outlives any test that reads it. The bound
56/// on a live test is [`live_until`]'s own timeout — waiting for the frame it
57/// expects — not this window: a window short enough to end the stream promptly
58/// is also short enough to lose the race on a loaded machine, which is a
59/// flaky test rather than a fast one.
60const TEST_LIVE_WINDOW: iz_web::live::LiveWindow =
61 iz_web::live::LiveWindow(std::time::Duration::from_secs(10));
62
63/// Photos the fake im can serve, keyed by person id.
64type Photos = Arc<Mutex<HashMap<String, (Vec<u8>, String)>>>;
65
66/// A fake im: answers `POST /introspect` from its token map, `{"active":
67/// false}` for anything it does not know. Bare TCP + hand-rolled HTTP/1.1 —
68/// just enough for the client's form post.
69struct FakeIm {
70 addr: std::net::SocketAddr,
71 tokens: Arc<Mutex<HashMap<String, serde_json::Value>>>,
72 photos: Photos,
73}
74
75impl FakeIm {
76 async fn spawn() -> Self {
77 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
78 let addr = listener.local_addr().unwrap();
79 let tokens: Arc<Mutex<HashMap<String, serde_json::Value>>> =
80 Arc::new(Mutex::new(HashMap::new()));
81 let photos: Photos = Arc::new(Mutex::new(HashMap::new()));
82 let map = tokens.clone();
83 let pmap = photos.clone();
84 tokio::spawn(async move {
85 loop {
86 let Ok((socket, _)) = listener.accept().await else {
87 return;
88 };
89 let map = map.clone();
90 let pmap = pmap.clone();
91 tokio::spawn(async move {
92 use tokio::io::{AsyncReadExt, AsyncWriteExt};
93 let mut socket = socket;
94 let mut buf = vec![0u8; 8192];
95 let mut req = Vec::new();
96 // One request after another on the same connection:
97 // closing it after every answer races the client's
98 // pool, which may hand out the dead socket for the
99 // next introspection and read that as signed-out.
100 loop {
101 let body_start = loop {
102 let Ok(n) = socket.read(&mut buf).await else {
103 return;
104 };
105 if n == 0 {
106 return;
107 }
108 req.extend_from_slice(&buf[..n]);
109 if let Some(end) = headers_end(&req) {
110 let head = String::from_utf8_lossy(&req[..end]).to_string();
111 let len = content_length(&head);
112 if req.len() >= end + len {
113 break end;
114 }
115 }
116 if req.len() > 1_000_000 {
117 return;
118 }
119 };
120 let head = String::from_utf8_lossy(&req[..body_start]).to_string();
121 let first = head.lines().next().unwrap_or("").to_string();
122 // The body may already hold the next pipelined
123 // request's first bytes; take exactly this one.
124 let len = content_length(&head);
125 let body: Vec<u8> = req[body_start..body_start + len].to_vec();
126 req.drain(..body_start + len);
127 let (status, content_type, payload) =
128 match photo_answer(&pmap, &head, &first) {
129 Some(photo) => photo,
130 None => match answer_for(&map, &first, &body) {
131 Some(answer) => (
132 "200 OK",
133 "application/json".to_string(),
134 serde_json::to_vec(&answer).unwrap(),
135 ),
136 // Anything but the introspection route is
137 // nothing at all, the way the real im 404s
138 // unknown paths rather than answering them.
139 None => ("404 Not Found", "text/plain".to_string(), Vec::new()),
140 },
141 };
142 let response = format!(
143 "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n",
144 payload.len()
145 );
146 if socket.write_all(response.as_bytes()).await.is_err() {
147 return;
148 }
149 if socket.write_all(&payload).await.is_err() {
150 return;
151 }
152 }
153 });
154 }
155 });
156 Self {
157 addr,
158 tokens,
159 photos,
160 }
161 }
162
163 fn url(&self) -> String {
164 format!("http://{}", self.addr)
165 }
166
167 /// Stores the photo `GET /photo/{user_id}` answers with — the bytes and
168 /// the mime im would serve for this account.
169 fn set_photo(&self, user_id: &str, bytes: Vec<u8>, mime: &str) {
170 self.photos
171 .lock()
172 .insert(user_id.to_string(), (bytes, mime.to_string()));
173 }
174}
175
176/// The Basic credential the app presents for `GET /photo/*`: `iz-test:s3cr3t`.
177const PHOTO_BASIC: &str = "Basic aXotdGVzdDpzM2NyM3Q=";
178
179/// Answers `GET /photo/{id}` from the photo map — the app's Basic credential
180/// or nothing, a missing photo exactly like a missing person. `None` for
181/// anything else, which stays the introspection JSON.
182fn photo_answer(
183 photos: &Photos,
184 head: &str,
185 request_line: &str,
186) -> Option<(&'static str, String, Vec<u8>)> {
187 let mut parts = request_line.split_whitespace();
188 if parts.next() != Some("GET") {
189 return None;
190 }
191 let target = parts.next().unwrap_or("");
192 let path = target
193 .split_once('?')
194 .map(|(path, _)| path)
195 .unwrap_or(target);
196 let id = path.strip_prefix("/photo/")?;
197 if id.is_empty() || id.contains('/') {
198 return None;
199 }
200 let authed = head
201 .lines()
202 .filter_map(|line| line.split_once(':'))
203 .any(|(name, value)| {
204 name.trim().eq_ignore_ascii_case("authorization") && value.trim() == PHOTO_BASIC
205 });
206 if !authed {
207 return Some(("404 Not Found", "text/plain".to_string(), Vec::new()));
208 }
209 match photos.lock().get(id) {
210 Some((bytes, mime)) => Some(("200 OK", mime.clone(), bytes.clone())),
211 None => Some(("404 Not Found", "text/plain".to_string(), Vec::new())),
212 }
213}
214
215fn headers_end(req: &[u8]) -> Option<usize> {
216 req.windows(4)
217 .position(|w| w == b"\r\n\r\n")
218 .map(|pos| pos + 4)
219}
220
221fn content_length(head: &str) -> usize {
222 head.lines()
223 .find_map(|line| {
224 let (name, value) = line.split_once(':')?;
225 (name.trim().eq_ignore_ascii_case("content-length"))
226 .then(|| value.trim().parse().ok())?
227 })
228 .unwrap_or(0)
229}
230
231/// Percent-decoding, enough for the opaque tokens these tests mint.
232fn decode(raw: &str) -> String {
233 let mut out = String::with_capacity(raw.len());
234 let mut bytes = raw.as_bytes().iter();
235 while let Some(&b) = bytes.next() {
236 if b == b'+' {
237 out.push(' ');
238 } else if b == b'%' {
239 let hi = bytes.next().copied().unwrap_or(b'0');
240 let lo = bytes.next().copied().unwrap_or(b'0');
241 let hex = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8;
242 out.push((hex(hi) * 16 + hex(lo)) as char);
243 } else {
244 out.push(b as char);
245 }
246 }
247 out
248}
249fn answer_for(
250 map: &Arc<Mutex<HashMap<String, serde_json::Value>>>,
251 request_line: &str,
252 body: &[u8],
253) -> Option<serde_json::Value> {
254 let mut head = request_line.split_whitespace();
255 let is_introspect =
256 head.next() == Some("POST") && head.next() == Some(iz_client::introspect_path());
257 if !is_introspect {
258 return None;
259 }
260 let text = String::from_utf8_lossy(body).to_string();
261 let token = text
262 .split('&')
263 .filter_map(|pair| pair.split_once('='))
264 .find(|(name, _)| *name == "token")
265 .map(|(_, value)| decode(value));
266 match token.and_then(|token| map.lock().get(&token).cloned()) {
267 Some(claims) => Some(claims),
268 None => Some(serde_json::json!({"active": false})),
269 }
270}
271
272/// A throwaway workspace: its own database file, its own fake im, its own
273/// router.
274struct App {
275 dir: PathBuf,
276 router: Router,
277 store: Arc<dyn Store>,
278 client: iz_client::Config,
279 fake: FakeIm,
280 /// The storage peer's client and health, registered exactly as
281 /// `main.rs` registers them; `storage_cycle` tests run the beat by
282 /// hand over these.
283 storage_client: iz_web::storage::StorageClient,
284 storage_health: iz_web::storage::StorageHealth,
285 /// What the Settings Connection card renders: poked by hand in tests
286 /// the way the mirror task pokes it in the process.
287 health: iz_web::directory::DirectoryHealth,
288 /// Stands in for Ctrl+C. Held so a test can stop this router the way the
289 /// process stops the real one.
290 stop: tokio::sync::watch::Sender<bool>,
291}
292
293impl App {
294 async fn build(mail: Mail) -> Self {
295 Self::build_with(mail, None, "", None).await
296 }
297
298 /// Like `build`, but with the knobs a configured deployment has: the
299 /// family list mirrored from im — passed as the raw JSON the `setting`
300 /// row holds, so a test can also feed it a body that will not parse —
301 /// and the configured `base_url`. Building them in is what lets the
302 /// switcher and the sign-out handoff be asserted over real HTTP.
303 ///
304 /// `storage_in` is the `[storage.in]` token, when the deployment
305 /// under test has one.
306 async fn build_with(
307 mail: Mail,
308 family: Option<String>,
309 base_url: &str,
310 storage_in: Option<String>,
311 ) -> Self {
312 let dir = std::env::temp_dir().join(format!("iz-http-{}", Ulid::generate()));
313 std::fs::create_dir_all(&dir).unwrap();
314 let db = dir.join("iz.db");
315 let storage = dir.join("storage");
316 let store: Arc<dyn Store> = Arc::new(
317 TursoStore::open(db.to_str().unwrap(), storage.as_path())
318 .await
319 .unwrap(),
320 );
321 // The family list is a mirror, not a config: the test plays the
322 // part of the background beat that stores what im served.
323 if let Some(family) = &family {
324 store
325 .set_setting(iz_web::server::FAMILY_KEY, family)
326 .await
327 .unwrap();
328 }
329 let storage_client = iz_web::storage::StorageClient::new(storage_in.clone());
330 let storage_health = iz_web::storage::StorageHealth::new();
331 let fake = FakeIm::spawn().await;
332 let config = iz_core::Config {
333 database: db,
334 storage,
335 listen: "127.0.0.1:7655".parse().unwrap(),
336 live_seconds: 300,
337 base_url: base_url.to_string(),
338 oidc: iz_core::config::OidcConfig {
339 issuer: fake.url(),
340 client_id: "iz-test".to_string(),
341 client_secret: "s3cr3t".to_string(),
342 redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
343 },
344 ignored: Vec::new(),
345 storage_in: storage_in.map(|token| iz_core::config::InStorage { token }),
346 defaulted: false,
347 };
348 // The fallback half of the chain, built exactly as `main.rs` builds
349 // it: the configured public address, else the address bound.
350 let client = iz_client::Config {
351 issuer: fake.url(),
352 client_id: "iz-test".to_string(),
353 client_secret: "s3cr3t".to_string(),
354 redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
355 logout_back: config.public_url(),
356 cookie_name: "iz_session".to_string(),
357 cookie_key: [7u8; 32],
358 };
359 let health = iz_web::directory::DirectoryHealth::new();
360 let (stop, stopping) = tokio::sync::watch::channel(false);
361 let router = iz_client::mount(
362 Router::builder()
363 .discover()
364 .runtime()
365 .layer(
366 BodyLimit::max(iz_web::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024)
367 .at("/files"),
368 )
369 .cookies()
370 .assets(
371 AssetBundle::load_dir(asset_dir())
372 .expect("run `topcoat asset bundle` before the http suite"),
373 )
374 .trusted_proxies(iz_web::server::trusted_proxies()),
375 client.clone(),
376 )
377 .app_context(store.clone())
378 .app_context(im_client::directory::DirectoryClient::new(
379 fake.url(),
380 "iz-test",
381 "s3cr3t",
382 ))
383 .app_context(health.clone())
384 .app_context(storage_client.clone())
385 .app_context(storage_health.clone())
386 .app_context(iz_client::LogoutBack(Arc::new(iz_web::server::logout_back)))
387 .app_context(config.clone())
388 .app_context(TEST_LIVE_WINDOW)
389 .app_context(iz_web::live::Shutdown(stopping))
390 .app_context(mail)
391 .build();
392 Self {
393 dir,
394 router,
395 store,
396 client,
397 fake,
398 storage_client,
399 storage_health,
400 health,
401 stop,
402 }
403 }
404
405 async fn open() -> Self {
406 Self::build(Mail::silent()).await
407 }
408
409 /// Like `open`, but with a live mail engine reading the workspace's SMTP
410 /// settings, so a transition actually reaches the ledger instead of the
411 /// silent no-op `open`'s router hands every crossing.
412 async fn open_with_mail() -> Self {
413 let dir = std::env::temp_dir().join(format!("iz-http-{}", Ulid::generate()));
414 std::fs::create_dir_all(&dir).unwrap();
415 let db = dir.join("iz.db");
416 let storage = dir.join("storage");
417 let store: Arc<dyn Store> = Arc::new(
418 TursoStore::open(db.to_str().unwrap(), storage.as_path())
419 .await
420 .unwrap(),
421 );
422 let engine = Arc::new(iz_core::MailEngine::new(
423 store.clone(),
424 Arc::new(iz_web::smtp::WorkspaceSmtp::new(store.clone())),
425 "https://iz.sh",
426 ));
427 let fake = FakeIm::spawn().await;
428 let config = iz_core::Config {
429 database: db,
430 storage,
431 listen: "127.0.0.1:7655".parse().unwrap(),
432 base_url: String::new(),
433 live_seconds: 300,
434 oidc: iz_core::config::OidcConfig {
435 issuer: fake.url(),
436 client_id: "iz-test".to_string(),
437 client_secret: "s3cr3t".to_string(),
438 redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
439 },
440 ignored: Vec::new(),
441 storage_in: None,
442 defaulted: false,
443 };
444 // The fallback half of the chain, built exactly as `main.rs` builds
445 // it: the configured public address, else the address bound.
446 let client = iz_client::Config {
447 issuer: fake.url(),
448 client_id: "iz-test".to_string(),
449 client_secret: "s3cr3t".to_string(),
450 redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
451 logout_back: config.public_url(),
452 cookie_name: "iz_session".to_string(),
453 cookie_key: [7u8; 32],
454 };
455 let health = iz_web::directory::DirectoryHealth::new();
456 let storage_client = iz_web::storage::StorageClient::new(None);
457 let storage_health = iz_web::storage::StorageHealth::new();
458 let (stop, stopping) = tokio::sync::watch::channel(false);
459 let router = iz_client::mount(
460 Router::builder()
461 .discover()
462 .runtime()
463 .layer(
464 BodyLimit::max(iz_web::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024)
465 .at("/files"),
466 )
467 .cookies()
468 .assets(
469 AssetBundle::load_dir(asset_dir())
470 .expect("run `topcoat asset bundle` before the http suite"),
471 )
472 .trusted_proxies(iz_web::server::trusted_proxies()),
473 client.clone(),
474 )
475 .app_context(store.clone())
476 .app_context(im_client::directory::DirectoryClient::new(
477 fake.url(),
478 "iz-test",
479 "s3cr3t",
480 ))
481 .app_context(health.clone())
482 .app_context(storage_client.clone())
483 .app_context(storage_health.clone())
484 .app_context(iz_client::LogoutBack(Arc::new(iz_web::server::logout_back)))
485 .app_context(config.clone())
486 .app_context(TEST_LIVE_WINDOW)
487 .app_context(iz_web::live::Shutdown(stopping))
488 .app_context(Mail::sending(engine))
489 .build();
490 Self {
491 dir,
492 router,
493 store,
494 client,
495 fake,
496 storage_client,
497 storage_health,
498 health,
499 stop,
500 }
501 }
502 /// Mints a session cookie for an im identity, registering its claims on
503 /// the fake — exactly what `/auth/callback` seals, without the browser
504 /// dance. The local row is provisioned on the next request, the way a
505 /// real first login provisions it.
506 fn mint(&self, sub: &str, email: &str, name: &str, im_admin: bool) -> String {
507 let token = format!("tok-{}", Ulid::generate());
508 let exp = time::OffsetDateTime::now_utc() + time::Duration::hours(1);
509 self.fake.tokens.lock().insert(
510 token.clone(),
511 serde_json::json!({
512 "active": true,
513 "sub": sub,
514 "email": email,
515 "name": name,
516 "admin": im_admin,
517 "exp": exp.unix_timestamp(),
518 }),
519 );
520 iz_client::mint_session_cookie(&self.client, &token, exp)
521 }
522
523 /// Opens `/api/live`. The response is returned as soon as the handler has
524 /// subscribed, so a caller writes AFTER this returns and the announcement
525 /// still lands in the feed.
526 async fn live_open(&self, cookie: Option<&str>) -> topcoat::router::response::Response<Body> {
527 let mut request = Request::builder().method("GET").uri("/api/live");
528 if let Some(cookie) = cookie {
529 request = request.header(
530 header::COOKIE,
531 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
532 );
533 }
534 self.router
535 .handle(request.body(Body::empty()).unwrap())
536 .await
537 }
538
539 /// The single workspace's id, read straight off the store: `TursoStore` is
540 /// single-tenant, so there is no id to guess and no JSON endpoint needed
541 /// just to hand it back.
542 async fn workspace_id(&self) -> String {
543 self.store
544 .workspace()
545 .await
546 .unwrap()
547 .expect("no workspace yet")
548 .id
549 }
550
551 /// Posts a form the way a hydrated caller does: `Accept: application/json`,
552 /// no `Referer`. Every mutating `/api/*` route answers `303 See Other`
553 /// regardless — [`Router::handle`] never follows a redirect, so the answer
554 /// is read straight off this response, same as `oneshot` did before.
555 async fn post(&self, path: &str, cookie: Option<&str>, form: &[(&str, &str)]) -> Answer {
556 self.post_with_extra_cookie(path, cookie, form, None).await
557 }
558
559 /// Like `post`, but with a second `Cookie` header of the caller's own
560 /// naming — for the `iz_rows_<section>` page-size cookie, which lives
561 /// beside the session cookie rather than replacing it.
562 async fn post_with_extra_cookie(
563 &self,
564 path: &str,
565 cookie: Option<&str>,
566 form: &[(&str, &str)],
567 extra_cookie: Option<&str>,
568 ) -> Answer {
569 let body = form
570 .iter()
571 .map(|(key, value)| format!("{}={}", encode(key), encode(value)))
572 .collect::<Vec<_>>()
573 .join("&");
574 let mut request = Request::builder()
575 .method("POST")
576 .uri(path)
577 .header(header::ACCEPT, "application/json")
578 .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
579 if let Some(cookie) = cookie {
580 request = request.header(
581 header::COOKIE,
582 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
583 );
584 }
585 if let Some(extra) = extra_cookie {
586 request = request.header(header::COOKIE, HeaderValue::from_str(extra).unwrap());
587 }
588 let response = self
589 .router
590 .handle(request.body(Body::from(body)).unwrap())
591 .await;
592 Answer::from_response(response).await
593 }
594
595 /// Posts the same form the way a browser with no script posts it: asking
596 /// for a page back, from a page it names. The answer is a redirect, and the
597 /// redirect is the whole of what the person will be shown.
598 async fn post_without_script(
599 &self,
600 path: &str,
601 cookie: Option<&str>,
602 referer: &str,
603 form: &[(&str, &str)],
604 ) -> Answer {
605 let body = form
606 .iter()
607 .map(|(key, value)| format!("{}={}", encode(key), encode(value)))
608 .collect::<Vec<_>>()
609 .join("&");
610 let mut request = Request::builder()
611 .method("POST")
612 .uri(path)
613 .header(header::ACCEPT, "text/html")
614 .header(header::REFERER, referer)
615 .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
616 if let Some(cookie) = cookie {
617 request = request.header(
618 header::COOKIE,
619 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
620 );
621 }
622 let response = self
623 .router
624 .handle(request.body(Body::from(body)).unwrap())
625 .await;
626 Answer::from_response(response).await
627 }
628
629 /// Posts a multipart form the way a browser's
630 /// `<form enctype="multipart/form-data">` does, hand-built rather than
631 /// pulling in a client crate for it: the fields first, in the order given
632 /// — the upload handler reads `task_id` before it reaches `file` — then
633 /// one `file` part if given.
634 async fn post_multipart(
635 &self,
636 path: &str,
637 cookie: Option<&str>,
638 fields: &[(&str, &str)],
639 file: Option<(&str, &str, &[u8])>,
640 ) -> Answer {
641 const BOUNDARY: &str = "iz-test-boundary";
642 let mut body = Vec::new();
643 for (name, value) in fields {
644 body.extend_from_slice(
645 format!(
646 "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
647 )
648 .as_bytes(),
649 );
650 }
651 if let Some((filename, content_type, bytes)) = file {
652 body.extend_from_slice(
653 format!(
654 "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: {content_type}\r\n\r\n"
655 )
656 .as_bytes(),
657 );
658 body.extend_from_slice(bytes);
659 body.extend_from_slice(b"\r\n");
660 }
661 body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
662
663 let mut request = Request::builder().method("POST").uri(path).header(
664 header::CONTENT_TYPE,
665 format!("multipart/form-data; boundary={BOUNDARY}"),
666 );
667 if let Some(cookie) = cookie {
668 request = request.header(
669 header::COOKIE,
670 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
671 );
672 }
673 let response = self
674 .router
675 .handle(request.body(Body::from(body)).unwrap())
676 .await;
677 Answer::from_response(response).await
678 }
679
680 /// Gets a page or a download the way a browser does: no `Accept` header
681 /// forcing JSON, an optional cookie, and the raw bytes back untouched — a
682 /// download's body is not always UTF-8.
683 async fn get(&self, path: &str, cookie: Option<&str>) -> Raw {
684 self.get_with_range(path, cookie, None).await
685 }
686
687 /// Like `get`, but with a second `Cookie` header of the caller's own
688 /// naming — for the `iz_rows_<section>` page-size cookie, which
689 /// lives beside the session cookie rather than replacing it.
690 async fn get_with_extra_cookie(&self, path: &str, cookie: Option<&str>, extra: &str) -> Raw {
691 self.get_with(path, cookie, None, None, Some(extra)).await
692 }
693
694 /// Like `get`, but with a `Range` header, for exercising the
695 /// `/files/{id}` partial-content path.
696 async fn get_with_range(&self, path: &str, cookie: Option<&str>, range: Option<&str>) -> Raw {
697 self.get_with(path, cookie, range, None, None).await
698 }
699
700 /// Like `get`, but with `If-None-Match`, for the `/photo/{user_id}`
701 /// revalidate path.
702 async fn get_with_if_none_match(&self, path: &str, cookie: Option<&str>, etag: &str) -> Raw {
703 self.get_with(path, cookie, None, Some(etag), None).await
704 }
705
706 async fn get_with(
707 &self,
708 path: &str,
709 cookie: Option<&str>,
710 range: Option<&str>,
711 if_none_match: Option<&str>,
712 extra_cookie: Option<&str>,
713 ) -> Raw {
714 let mut request = Request::builder().method("GET").uri(path);
715 if let Some(cookie) = cookie {
716 request = request.header(
717 header::COOKIE,
718 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
719 );
720 }
721 if let Some(extra) = extra_cookie {
722 request = request.header(header::COOKIE, HeaderValue::from_str(extra).unwrap());
723 }
724 if let Some(range) = range {
725 request = request.header(header::RANGE, range);
726 }
727 if let Some(if_none_match) = if_none_match {
728 request = request.header(header::IF_NONE_MATCH, if_none_match);
729 }
730 let response = self
731 .router
732 .handle(request.body(Body::empty()).unwrap())
733 .await;
734 let status = response.status();
735 let content_type = response
736 .headers()
737 .get(header::CONTENT_TYPE)
738 .and_then(|value| value.to_str().ok())
739 .map(str::to_string);
740 let disposition = response
741 .headers()
742 .get(header::CONTENT_DISPOSITION)
743 .and_then(|value| value.to_str().ok())
744 .map(str::to_string);
745 let content_range = response
746 .headers()
747 .get(header::CONTENT_RANGE)
748 .and_then(|value| value.to_str().ok())
749 .map(str::to_string);
750 let accept_ranges = response
751 .headers()
752 .get(header::ACCEPT_RANGES)
753 .and_then(|value| value.to_str().ok())
754 .map(str::to_string);
755 let etag = response
756 .headers()
757 .get(header::ETAG)
758 .and_then(|value| value.to_str().ok())
759 .map(str::to_string);
760 let cache_control = response
761 .headers()
762 .get(header::CACHE_CONTROL)
763 .and_then(|value| value.to_str().ok())
764 .map(str::to_string);
765 let location = response
766 .headers()
767 .get(header::LOCATION)
768 .and_then(|value| value.to_str().ok())
769 .map(str::to_string);
770 let bytes = to_bytes(response.into_body(), usize::MAX)
771 .await
772 .unwrap()
773 .to_vec();
774 Raw {
775 status,
776 content_type,
777 disposition,
778 content_range,
779 accept_ranges,
780 etag,
781 cache_control,
782 location,
783 bytes,
784 }
785 }
786}
787
788impl Drop for App {
789 fn drop(&mut self) {
790 let _ = std::fs::remove_dir_all(&self.dir);
791 }
792}
793
794/// A GET answer kept as raw bytes: a page's HTML or a download's file, neither
795/// of which the JSON-shaped [`Answer`] below is meant for.
796struct Raw {
797 status: StatusCode,
798 content_type: Option<String>,
799 disposition: Option<String>,
800 content_range: Option<String>,
801 accept_ranges: Option<String>,
802 etag: Option<String>,
803 cache_control: Option<String>,
804 /// Where a 303 sends the browser — the sign-out handoff's whole point.
805 location: Option<String>,
806 bytes: Vec<u8>,
807}
808
809struct Answer {
810 status: StatusCode,
811 body: String,
812 /// Where a browser without script is sent next. The only place such a
813 /// browser can be told anything.
814 location: Option<String>,
815}
816
817impl Answer {
818 async fn from_response(response: topcoat::router::response::Response) -> Self {
819 let status = response.status();
820 let location = response
821 .headers()
822 .get(header::LOCATION)
823 .and_then(|value| value.to_str().ok())
824 .map(str::to_string);
825 let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
826 Answer {
827 status,
828 body: String::from_utf8(bytes.to_vec()).unwrap(),
829 location,
830 }
831 }
832}
833
834/// Form encoding, enough for the addresses these tests send.
835fn encode(raw: &str) -> String {
836 let mut out = String::with_capacity(raw.len());
837 for byte in raw.bytes() {
838 match byte {
839 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
840 out.push(byte as char)
841 }
842 b' ' => out.push('+'),
843 other => out.push_str(&format!("%{other:02X}")),
844 }
845 }
846 out
847}
848
849/// What the tests type into the password field. It must never come back out.
850const SENDER_PASSWORD: &str = "cavalry-battery-hinge-40";
851
852/// Fills in the sender panel the way an admin would, and reports whether the
853/// server accepted it.
854///
855/// `save_sender` answers with an empty body and carries any refusal on the
856/// redirect's query instead of in JSON (settings routes have no hydrated
857/// caller to answer with a value) — accepted is "no `refusal=` on the way
858/// back".
859async fn sender_saved(app: &App, admin: &str) -> bool {
860 let answer = app
861 .post(
862 "/api/save_sender",
863 Some(admin),
864 &[
865 ("host", "smtp.fastmail.com"),
866 ("port", "465"),
867 ("username", "iz"),
868 ("password", SENDER_PASSWORD),
869 ("from_name", "iz"),
870 ("from_address", "iz@iz.sh"),
871 ],
872 )
873 .await;
874 answer.status == StatusCode::SEE_OTHER
875 && answer
876 .location
877 .as_deref()
878 .is_some_and(|location| !location.contains("refusal="))
879}
880
881/// Signs in the workspace's first im-admin identity and returns its cookie.
882/// The first sight of her provisions the local row and claims the workspace
883/// owner, the way a real first login sets the workspace up.
884async fn admin(app: &App) -> String {
885 let sub = "im-ada";
886 let user = app
887 .store
888 .provision_user(sub, "ada@iz.sh", "Ada Lovelace", true)
889 .await
890 .unwrap();
891 assert_eq!(
892 user.role,
893 Role::Admin,
894 "the first im admin did not claim admin"
895 );
896 app.mint(sub, "ada@iz.sh", "Ada Lovelace", true)
897}
898
899/// Signs in an im identity as a plain member and returns its cookie.
900async fn member(app: &App, email: &str, name: &str) -> String {
901 let sub = format!("im-{email}");
902 app.store
903 .provision_user(&sub, email, name, false)
904 .await
905 .unwrap();
906 app.mint(&sub, email, name, false)
907}
908
909/// Signs in an im identity as a viewer and returns its cookie: provisioned a
910/// member by default, then cut down to viewer the way an admin would.
911async fn viewer(app: &App, email: &str, name: &str) -> String {
912 let sub = format!("im-{email}");
913 let user = app
914 .store
915 .provision_user(&sub, email, name, false)
916 .await
917 .unwrap();
918 app.store.set_role(&user.id, Role::Viewer).await.unwrap();
919 app.mint(&sub, email, name, false)
920}
921/// Signs in an im identity in the given role and returns its cookie — the
922/// old invite-and-redeem flow's replacement at the call sites that only ever
923/// needed "a member" or "a viewer". An admin comes from im's flag, never
924/// from this file.
925async fn invited(app: &App, _admin: &str, email: &str, name: &str, role: Role) -> String {
926 match role {
927 Role::Admin => {
928 let sub = format!("im-{email}");
929 app.store
930 .provision_user(&sub, email, name, true)
931 .await
932 .unwrap();
933 app.mint(&sub, email, name, true)
934 }
935 Role::Member => member(app, email, name).await,
936 Role::Viewer => viewer(app, email, name).await,
937 }
938}
939
940/// The id of the board's first column, read straight off the store: there is
941/// no JSON `CurrentBoard` endpoint left to ask for it (the board is a
942/// server-rendered shard now), and the id is fixture setup, not the behavior
943/// under test.
944async fn first_column(app: &App) -> String {
945 columns_of(app)
946 .await
947 .into_iter()
948 .next()
949 .expect("no columns on a fresh board")
950}
951
952/// Every column id on the board, in order, read straight off the store — see
953/// [`first_column`] on why this bypasses HTTP.
954async fn columns_of(app: &App) -> Vec<String> {
955 let workspace_id = app.workspace_id().await;
956 let board = app
957 .store
958 .board(&workspace_id)
959 .await
960 .unwrap()
961 .expect("no board");
962 app.store
963 .columns(&board.id)
964 .await
965 .unwrap()
966 .into_iter()
967 .map(|c| c.id)
968 .collect()
969}
970
971/// Makes a task and hands back its id, read straight off the store — there is
972/// no `CurrentBoard` JSON call left to read it from (the board is a
973/// server-rendered shard now); the mutation itself is still a real HTTP post.
974async fn a_task(app: &App, cookie: &str, column: &str, title: &str) -> String {
975 let answer = app
976 .post(
977 "/api/create_task",
978 Some(cookie),
979 &[("title", title), ("column_id", column)],
980 )
981 .await;
982 assert_eq!(answer.body, "", "the task was refused: {}", answer.body);
983
984 let workspace_id = app.workspace_id().await;
985 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
986 .await
987 .unwrap()
988 .unwrap();
989 board
990 .columns
991 .iter()
992 .flat_map(|c| &c.cards)
993 .find(|card| card.title == title)
994 .expect("the new task is not on the board")
995 .id
996 .clone()
997}
998
999#[tokio::test]
1000async fn a_viewer_who_posts_to_create_task_anyway_is_refused() {
1001 let app = App::open().await;
1002 let admin = admin(&app).await;
1003 let viewer = invited(&app, &admin, "quiet@iz.sh", "Quiet Reader", Role::Viewer).await;
1004 let column = first_column(&app).await;
1005
1006 let answer = app
1007 .post(
1008 "/api/create_task",
1009 Some(&viewer),
1010 &[
1011 ("title", "Viewer should not get this"),
1012 ("column_id", &column),
1013 ],
1014 )
1015 .await;
1016
1017 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
1018 assert_eq!(answer.body, "");
1019 assert!(
1020 answer
1021 .location
1022 .as_deref()
1023 .unwrap_or_default()
1024 .contains("refusal=forbidden&on=create_task"),
1025 "{:?}",
1026 answer.location
1027 );
1028
1029 // And the refusal is not cosmetic: the board is still empty.
1030 let workspace_id = app.workspace_id().await;
1031 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1032 .await
1033 .unwrap()
1034 .unwrap();
1035 assert!(
1036 board
1037 .columns
1038 .iter()
1039 .flat_map(|c| &c.cards)
1040 .all(|card| card.title != "Viewer should not get this"),
1041 "the refused task was written anyway"
1042 );
1043}
1044
1045#[tokio::test]
1046async fn a_member_may_create_a_task() {
1047 let app = App::open().await;
1048 let admin = admin(&app).await;
1049 let member = invited(&app, &admin, "mo@iz.sh", "Mo Dubois", Role::Member).await;
1050 let column = first_column(&app).await;
1051
1052 let answer = app
1053 .post(
1054 "/api/create_task",
1055 Some(&member),
1056 &[("title", "Wire the deadline chip"), ("column_id", &column)],
1057 )
1058 .await;
1059 assert_eq!(answer.body, "");
1060 assert!(
1061 !answer
1062 .location
1063 .as_deref()
1064 .unwrap_or_default()
1065 .contains("refusal="),
1066 "a create that worked said it was refused: {:?}",
1067 answer.location
1068 );
1069
1070 let workspace_id = app.workspace_id().await;
1071 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1072 .await
1073 .unwrap()
1074 .unwrap();
1075 let card = board
1076 .columns
1077 .iter()
1078 .flat_map(|c| &c.cards)
1079 .find(|card| card.title == "Wire the deadline chip")
1080 .expect("new task is not on the board");
1081 let tail = card
1082 .task_key
1083 .strip_prefix("DZ-")
1084 .expect("key not shaped like DZ-<tail>");
1085 assert!(
1086 (5..=7).contains(&tail.len()),
1087 "key tail {tail} not 5..=7 chars"
1088 );
1089 assert!(
1090 tail.chars()
1091 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()),
1092 "key tail {tail} not uppercase alnum"
1093 );
1094}
1095
1096// A cross-site form post carries no refusal body — the create simply works —
1097// so `carry_refusal_on_redirect` used to have nothing to rewrite and sent the
1098// browser straight to the attacker's own Referer. The fix sanitizes the
1099// Location on every redirect this layer sees, refusal or not.
1100#[tokio::test]
1101async fn a_successful_create_never_redirects_off_site() {
1102 let app = App::open().await;
1103 let admin = admin(&app).await;
1104 let column = first_column(&app).await;
1105
1106 let answer = app
1107 .post_without_script(
1108 "/api/create_task",
1109 Some(&admin),
1110 "https://elsewhere.example/steal",
1111 &[("title", "Cross-site create"), ("column_id", &column)],
1112 )
1113 .await;
1114 assert_eq!(answer.status, StatusCode::SEE_OTHER);
1115 let location = answer.location.expect("a redirect with nowhere to go");
1116 assert!(
1117 !location.contains("elsewhere.example"),
1118 "the browser was sent off-site: {location}"
1119 );
1120}
1121
1122#[tokio::test]
1123async fn a_task_cannot_be_dropped_into_another_workspaces_column() {
1124 let app = App::open().await;
1125 let admin = admin(&app).await;
1126
1127 let answer = app
1128 .post(
1129 "/api/create_task",
1130 Some(&admin),
1131 &[
1132 ("title", "Wrong column"),
1133 ("column_id", "00000000-0000-0000-0000-000000000000"),
1134 ],
1135 )
1136 .await;
1137 assert_eq!(answer.body, "");
1138 assert!(
1139 answer
1140 .location
1141 .as_deref()
1142 .unwrap_or_default()
1143 .contains("refusal=forbidden&on=create_task"),
1144 "{:?}",
1145 answer.location
1146 );
1147 let workspace_id = app.workspace_id().await;
1148 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1149 .await
1150 .unwrap()
1151 .unwrap();
1152 assert!(
1153 board
1154 .columns
1155 .iter()
1156 .flat_map(|c| &c.cards)
1157 .all(|card| card.title != "Wrong column"),
1158 "the refused task was written anyway"
1159 );
1160}
1161
1162#[tokio::test]
1163async fn a_card_needs_a_title() {
1164 let app = App::open().await;
1165 let admin = admin(&app).await;
1166 let column = first_column(&app).await;
1167
1168 let answer = app
1169 .post(
1170 "/api/create_task",
1171 Some(&admin),
1172 &[("title", " "), ("column_id", &column)],
1173 )
1174 .await;
1175 assert_eq!(answer.body, "");
1176 assert!(
1177 answer
1178 .location
1179 .as_deref()
1180 .unwrap_or_default()
1181 .contains("refusal=empty-title&on=create_task"),
1182 "{:?}",
1183 answer.location
1184 );
1185 let workspace_id = app.workspace_id().await;
1186 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1187 .await
1188 .unwrap()
1189 .unwrap();
1190 assert_eq!(
1191 board.columns.iter().flat_map(|c| &c.cards).count(),
1192 0,
1193 "a blank title was stored anyway"
1194 );
1195}
1196
1197#[tokio::test]
1198async fn the_board_is_not_readable_without_a_session() {
1199 let app = App::open().await;
1200 let _admin = admin(&app).await;
1201
1202 // There is no `CurrentBoard` JSON call any more (see FINDING near
1203 // `first_column`); the guard is exercised on a real read instead: the
1204 // signed-out board page itself.
1205 let raw = app.get("/", None).await;
1206 let html = String::from_utf8_lossy(&raw.bytes);
1207 assert!(
1208 !html.contains("board-stage"),
1209 "a signed-out browser was shown the board: {html}"
1210 );
1211}
1212
1213/// The sort control still posts as a plain `<select name=sort>` — `dropdown.rs`
1214/// only hides it and stands a trigger button in front, it never renames or
1215/// drops the form field a `GET /?sort=` relies on.
1216#[tokio::test]
1217async fn the_board_sort_control_keeps_its_hidden_select_and_gets_a_dropdown_trigger() {
1218 let app = App::open().await;
1219 let admin = admin(&app).await;
1220
1221 let page = app.get("/", Some(&admin)).await;
1222 let html = String::from_utf8_lossy(&page.bytes);
1223 assert!(
1224 html.contains("select class=\"status-select\" name=\"sort\""),
1225 "{html}"
1226 );
1227 // `dropdown.rs`'s script is what turns that hidden select into the
1228 // house trigger + panel client-side; its presence is the page's only
1229 // server-rendered proof the shell is wired in.
1230 assert!(
1231 html.contains("dd-trigger"),
1232 "no dropdown script on the board page: {html}"
1233 );
1234 // `root_layout` emits `layout.rs`'s Escape manager on every page; the
1235 // registration below is proof the topbar `.user-menu` gets its close
1236 // path on the board page too.
1237 assert!(
1238 html.contains("window.__izEsc"),
1239 "no escape manager on the board page: {html}"
1240 );
1241 assert!(
1242 html.contains("__izEsc.register(40"),
1243 "no escape script on the board page: {html}"
1244 );
1245 assert!(
1246 html.contains("closest('.user-menu')"),
1247 "no user-menu close path on the board page: {html}"
1248 );
1249}
1250
1251#[tokio::test]
1252async fn a_viewer_who_posts_a_comment_anyway_is_refused() {
1253 let app = App::open().await;
1254 let admin = admin(&app).await;
1255 let viewer = invited(&app, &admin, "eyes@iz.sh", "Ida Eyes", Role::Viewer).await;
1256 let column = first_column(&app).await;
1257 let task = a_task(&app, &admin, &column, "Ship the detail modal").await;
1258
1259 let answer = app
1260 .post(
1261 "/api/post_comment",
1262 Some(&viewer),
1263 &[("task_id", &task), ("body", "Viewers cannot say this")],
1264 )
1265 .await;
1266 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
1267 assert_eq!(answer.body, "\"Forbidden\"");
1268
1269 // The refusal is not cosmetic: nothing was written.
1270 let answer = app
1271 .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
1272 .await;
1273 assert!(
1274 !answer.body.contains("Viewers cannot say this"),
1275 "the refused comment was written anyway: {}",
1276 answer.body
1277 );
1278}
1279
1280#[tokio::test]
1281async fn a_member_may_comment_and_the_author_is_the_session() {
1282 let app = App::open().await;
1283 let admin = admin(&app).await;
1284 let member = invited(&app, &admin, "kai@iz.sh", "Kai Renner", Role::Member).await;
1285 let column = first_column(&app).await;
1286 let task = a_task(&app, &admin, &column, "Wire the picker").await;
1287
1288 let answer = app
1289 .post(
1290 "/api/post_comment",
1291 Some(&member),
1292 &[("task_id", &task), ("body", "Picker is narrow on purpose")],
1293 )
1294 .await;
1295 assert_eq!(answer.body, "null", "a member was refused: {}", answer.body);
1296
1297 let answer = app
1298 .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
1299 .await;
1300 assert!(answer.body.contains("Picker is narrow on purpose"));
1301 assert!(
1302 answer.body.contains("Kai Renner"),
1303 "the comment is not attributed to the session's user: {}",
1304 answer.body
1305 );
1306}
1307
1308#[tokio::test]
1309async fn a_link_that_would_close_a_circle_is_refused_at_the_endpoint() {
1310 let app = App::open().await;
1311 let admin = admin(&app).await;
1312 let column = first_column(&app).await;
1313 let first = a_task(&app, &admin, &column, "Lay the cable").await;
1314 let second = a_task(&app, &admin, &column, "Light the cable").await;
1315
1316 let answer = app
1317 .post(
1318 "/api/link_tasks",
1319 Some(&admin),
1320 &[
1321 ("task_id", &second),
1322 ("other_id", &first),
1323 ("direction", "blocked_by"),
1324 ],
1325 )
1326 .await;
1327 assert_eq!(
1328 answer.body, "null",
1329 "the first link was refused: {}",
1330 answer.body
1331 );
1332
1333 let answer = app
1334 .post(
1335 "/api/link_tasks",
1336 Some(&admin),
1337 &[
1338 ("task_id", &first),
1339 ("other_id", &second),
1340 ("direction", "blocked_by"),
1341 ],
1342 )
1343 .await;
1344 assert_eq!(answer.body, "\"Cycle\"");
1345}
1346
1347#[tokio::test]
1348async fn a_refusal_reaches_a_browser_with_no_script() {
1349 let app = App::open().await;
1350 let admin = admin(&app).await;
1351 let column = first_column(&app).await;
1352 let first = a_task(&app, &admin, &column, "Lay the cable").await;
1353 let second = a_task(&app, &admin, &column, "Light the cable").await;
1354
1355 app.post(
1356 "/api/link_tasks",
1357 Some(&admin),
1358 &[
1359 ("task_id", &second),
1360 ("other_id", &first),
1361 ("direction", "blocked_by"),
1362 ],
1363 )
1364 .await;
1365
1366 // The same link back the other way, asked for by a browser that has no way
1367 // to read the answer's body.
1368 let answer = app
1369 .post_without_script(
1370 "/api/link_tasks",
1371 Some(&admin),
1372 &format!("http://iz.test/?task={first}"),
1373 &[
1374 ("task_id", &first),
1375 ("other_id", &second),
1376 ("direction", "blocked_by"),
1377 ],
1378 )
1379 .await;
1380 assert_eq!(answer.status, StatusCode::SEE_OTHER);
1381 let location = answer.location.expect("a redirect with nowhere to go");
1382 assert!(
1383 location.contains("refusal=cycle") && location.contains("on=link_tasks"),
1384 "the refusal did not ride back on the redirect: {location}"
1385 );
1386 assert!(
1387 location.contains(&format!("task={first}")),
1388 "the modal was closed on the way back: {location}"
1389 );
1390}
1391
1392#[tokio::test]
1393async fn a_call_that_was_not_refused_carries_nothing_back() {
1394 let app = App::open().await;
1395 let admin = admin(&app).await;
1396 let column = first_column(&app).await;
1397 let first = a_task(&app, &admin, &column, "Lay the cable").await;
1398 let second = a_task(&app, &admin, &column, "Light the cable").await;
1399
1400 let answer = app
1401 .post_without_script(
1402 "/api/link_tasks",
1403 Some(&admin),
1404 "http://iz.test/",
1405 &[
1406 ("task_id", &second),
1407 ("other_id", &first),
1408 ("direction", "blocked_by"),
1409 ],
1410 )
1411 .await;
1412 assert_eq!(answer.status, StatusCode::SEE_OTHER);
1413 let location = answer.location.expect("a redirect with nowhere to go");
1414 assert!(
1415 !location.contains("refusal="),
1416 "a link that was made said it was refused: {location}"
1417 );
1418}
1419
1420#[tokio::test]
1421async fn a_task_id_from_nowhere_is_not_found() {
1422 let app = App::open().await;
1423 let admin = admin(&app).await;
1424
1425 let answer = app
1426 .post(
1427 "/api/fetch_task",
1428 Some(&admin),
1429 &[("task_id", "00000000-0000-0000-0000-000000000000")],
1430 )
1431 .await;
1432 assert_eq!(answer.body, "{\"Err\":\"NotFound\"}");
1433}
1434
1435#[tokio::test]
1436async fn a_viewer_who_posts_a_delete_anyway_is_refused() {
1437 let app = App::open().await;
1438 let admin = admin(&app).await;
1439 let viewer = invited(&app, &admin, "wren@iz.sh", "Wren Ash", Role::Viewer).await;
1440 let column = first_column(&app).await;
1441 let task = a_task(&app, &admin, &column, "Viewers cannot remove this").await;
1442
1443 let answer = app
1444 .post("/api/delete_task", Some(&viewer), &[("task_id", &task)])
1445 .await;
1446 assert_eq!(answer.body, "\"Forbidden\"");
1447
1448 let workspace_id = app.workspace_id().await;
1449 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1450 .await
1451 .unwrap()
1452 .unwrap();
1453 assert!(
1454 board
1455 .columns
1456 .iter()
1457 .flat_map(|c| &c.cards)
1458 .any(|card| card.title == "Viewers cannot remove this"),
1459 "the refused delete happened anyway"
1460 );
1461}
1462
1463#[tokio::test]
1464async fn deleting_the_task_the_modal_came_from_lands_on_the_board_not_the_dead_modal() {
1465 let app = App::open().await;
1466 let admin = admin(&app).await;
1467 let column = first_column(&app).await;
1468 let task = a_task(&app, &admin, &column, "Delete me from my own modal").await;
1469
1470 let answer = app
1471 .post_without_script(
1472 "/api/delete_task",
1473 Some(&admin),
1474 &format!("http://iz.test/?task={task}"),
1475 &[("task_id", &task)],
1476 )
1477 .await;
1478 assert_eq!(answer.status, StatusCode::SEE_OTHER);
1479 assert_eq!(
1480 answer.location.as_deref(),
1481 Some("/"),
1482 "a deleted task's modal should not reopen"
1483 );
1484}
1485
1486#[tokio::test]
1487async fn a_member_may_delete_and_the_delete_is_soft() {
1488 let app = App::open().await;
1489 let admin = admin(&app).await;
1490 let member = invited(&app, &admin, "rae@iz.sh", "Rae Okonkwo", Role::Member).await;
1491 let column = first_column(&app).await;
1492 let task = a_task(&app, &admin, &column, "Mistyped in a hurry").await;
1493
1494 // What it would cost is a read: it says so and writes nothing.
1495 let answer = app
1496 .post(
1497 "/api/what_delete_costs",
1498 Some(&member),
1499 &[("task_id", &task)],
1500 )
1501 .await;
1502 assert!(
1503 answer.body.contains("Mistyped in a hurry"),
1504 "{}",
1505 answer.body
1506 );
1507 let workspace_id = app.workspace_id().await;
1508 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1509 .await
1510 .unwrap()
1511 .unwrap();
1512 assert!(
1513 board
1514 .columns
1515 .iter()
1516 .flat_map(|c| &c.cards)
1517 .any(|card| card.title == "Mistyped in a hurry"),
1518 "asking cost deleted it"
1519 );
1520
1521 let answer = app
1522 .post("/api/delete_task", Some(&member), &[("task_id", &task)])
1523 .await;
1524 assert_eq!(answer.body, "null", "a member was refused: {}", answer.body);
1525
1526 // Gone from the board, and gone from the detail: soft is not visible.
1527 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1528 .await
1529 .unwrap()
1530 .unwrap();
1531 assert!(
1532 board
1533 .columns
1534 .iter()
1535 .flat_map(|c| &c.cards)
1536 .all(|card| card.title != "Mistyped in a hurry"),
1537 "the task is still on the board"
1538 );
1539 let answer = app
1540 .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
1541 .await;
1542 assert_eq!(answer.body, "{\"Err\":\"NotFound\"}");
1543}
1544
1545#[tokio::test]
1546async fn a_viewer_who_posts_a_move_anyway_is_refused() {
1547 let app = App::open().await;
1548 let admin = admin(&app).await;
1549 let viewer = invited(&app, &admin, "quiet@iz.sh", "Quiet Reader", Role::Viewer).await;
1550 let columns = columns_of(&app).await;
1551 let task = a_task(&app, &admin, &columns[0], "Stays in Backlog").await;
1552
1553 let answer = app
1554 .post(
1555 "/api/move_card",
1556 Some(&viewer),
1557 &[
1558 ("task_id", &task),
1559 ("from_column_id", &columns[0]),
1560 ("to_column_id", &columns[1]),
1561 ],
1562 )
1563 .await;
1564
1565 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
1566 assert_eq!(answer.body, "");
1567 assert!(
1568 answer
1569 .location
1570 .as_deref()
1571 .unwrap_or_default()
1572 .contains("refusal=forbidden&on=move_card"),
1573 "{:?}",
1574 answer.location
1575 );
1576
1577 // And nothing moved: the refusal is in the handler, not in the drawing.
1578 let answer = app
1579 .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
1580 .await;
1581 assert!(
1582 answer.body.contains(&columns[0]),
1583 "the refused move happened anyway: {}",
1584 answer.body
1585 );
1586}
1587
1588#[tokio::test]
1589async fn a_member_may_move_a_card() {
1590 let app = App::open().await;
1591 let admin = admin(&app).await;
1592 let member = invited(&app, &admin, "mo@iz.sh", "Mo Dubois", Role::Member).await;
1593 let columns = columns_of(&app).await;
1594 let task = a_task(&app, &admin, &columns[0], "Gets picked up").await;
1595
1596 let answer = app
1597 .post(
1598 "/api/move_card",
1599 Some(&member),
1600 &[
1601 ("task_id", &task),
1602 ("from_column_id", &columns[0]),
1603 ("to_column_id", &columns[1]),
1604 ],
1605 )
1606 .await;
1607 assert_eq!(answer.body, "");
1608 assert!(
1609 !answer
1610 .location
1611 .as_deref()
1612 .unwrap_or_default()
1613 .contains("refusal="),
1614 "a move that worked said it was refused: {:?}",
1615 answer.location
1616 );
1617
1618 let answer = app
1619 .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
1620 .await;
1621 assert!(answer.body.contains("\"moved\""), "no move in the activity");
1622}
1623
1624// Same open-redirect shape as create_task's: an empty (successful) body left
1625// the Referer's host untouched before the fix.
1626#[tokio::test]
1627async fn a_successful_move_never_redirects_off_site() {
1628 let app = App::open().await;
1629 let admin = admin(&app).await;
1630 let columns = columns_of(&app).await;
1631 let task = a_task(&app, &admin, &columns[0], "Cross-site move").await;
1632
1633 let answer = app
1634 .post_without_script(
1635 "/api/move_card",
1636 Some(&admin),
1637 "https://elsewhere.example/steal",
1638 &[
1639 ("task_id", &task),
1640 ("from_column_id", &columns[0]),
1641 ("to_column_id", &columns[1]),
1642 ],
1643 )
1644 .await;
1645 assert_eq!(answer.status, StatusCode::SEE_OTHER);
1646 let location = answer.location.expect("a redirect with nowhere to go");
1647 assert!(
1648 !location.contains("elsewhere.example"),
1649 "the browser was sent off-site: {location}"
1650 );
1651}
1652
1653#[tokio::test]
1654async fn a_card_with_open_subtasks_is_refused_the_done_column() {
1655 let app = App::open().await;
1656 let admin = admin(&app).await;
1657 let columns = columns_of(&app).await;
1658 let parent = a_task(&app, &admin, &columns[0], "Ship the exporter").await;
1659 let child = a_task(&app, &admin, &columns[0], "Write the CSV writer").await;
1660 app.store.set_parent(&child, Some(&parent)).await.unwrap();
1661
1662 // The last column is the done one; both the board drag and the detail
1663 // page's status control post here.
1664 let done = columns.last().unwrap();
1665 let held = app
1666 .post(
1667 "/api/move_card",
1668 Some(&admin),
1669 &[
1670 ("task_id", &parent),
1671 ("from_column_id", &columns[0]),
1672 ("to_column_id", done),
1673 ],
1674 )
1675 .await;
1676 assert!(
1677 held.location
1678 .as_deref()
1679 .unwrap_or_default()
1680 .contains("refusal=subtasks-open&on=move_card"),
1681 "{:?}",
1682 held.location
1683 );
1684
1685 // The card did not move, so the board still shows it where it was.
1686 let workspace_id = app.workspace_id().await;
1687 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1688 .await
1689 .unwrap()
1690 .unwrap();
1691 let held_card = board
1692 .columns
1693 .iter()
1694 .flat_map(|c| &c.cards)
1695 .find(|card| card.id == parent)
1696 .expect("the parent left the board");
1697 assert_eq!(held_card.column_id, columns[0]);
1698 assert!(!held_card.is_done());
1699
1700 // Finishing the subtask is what lets it through.
1701 let finished = app
1702 .post(
1703 "/api/move_card",
1704 Some(&admin),
1705 &[
1706 ("task_id", &child),
1707 ("from_column_id", &columns[0]),
1708 ("to_column_id", done),
1709 ],
1710 )
1711 .await;
1712 assert_eq!(finished.body, "");
1713 let through = app
1714 .post(
1715 "/api/move_card",
1716 Some(&admin),
1717 &[
1718 ("task_id", &parent),
1719 ("from_column_id", &columns[0]),
1720 ("to_column_id", done),
1721 ],
1722 )
1723 .await;
1724 assert_eq!(through.body, "");
1725 assert!(
1726 !through
1727 .location
1728 .as_deref()
1729 .unwrap_or_default()
1730 .contains("refusal="),
1731 "{:?}",
1732 through.location
1733 );
1734}
1735
1736#[tokio::test]
1737async fn a_subtask_is_opened_from_its_parents_page_and_shows_up_there() {
1738 let app = App::open().await;
1739 let admin = admin(&app).await;
1740 let columns = columns_of(&app).await;
1741 let parent = a_task(&app, &admin, &columns[0], "Ship the exporter").await;
1742
1743 let made = app
1744 .post(
1745 "/api/create_subtask",
1746 Some(&admin),
1747 &[("parent_id", &parent), ("title", "Write the CSV writer")],
1748 )
1749 .await;
1750 assert_eq!(made.body, "null", "the subtask was refused: {}", made.body);
1751
1752 // The parts live on their own tab; the board does not card them.
1753 let page = app
1754 .get(&format!("/?task={parent}&tab=subtasks"), Some(&admin))
1755 .await;
1756 let page = String::from_utf8_lossy(&page.bytes);
1757 assert!(
1758 page.contains("Write the CSV writer"),
1759 "the subtask is not on its parent's Subtasks tab"
1760 );
1761
1762 let workspace_id = app.workspace_id().await;
1763 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1764 .await
1765 .unwrap()
1766 .unwrap();
1767 let cards: Vec<_> = board.columns.iter().flat_map(|c| &c.cards).collect();
1768 assert_eq!(cards.len(), 1, "the subtask took a card of its own");
1769 assert_eq!(cards[0].subtask_label().as_deref(), Some("0/1"));
1770}
1771
1772#[tokio::test]
1773async fn a_subtask_with_nothing_in_its_title_is_refused() {
1774 let app = App::open().await;
1775 let admin = admin(&app).await;
1776 let columns = columns_of(&app).await;
1777 let parent = a_task(&app, &admin, &columns[0], "Ship the exporter").await;
1778
1779 // Posted the way a browser without script does, so the refusal has to
1780 // survive the round trip through the address bar.
1781 let empty = app
1782 .post_without_script(
1783 "/api/create_subtask",
1784 Some(&admin),
1785 &format!("http://iz.sh/?task={parent}"),
1786 &[("parent_id", &parent), ("title", " ")],
1787 )
1788 .await;
1789 assert!(
1790 empty
1791 .location
1792 .as_deref()
1793 .unwrap_or_default()
1794 .contains("refusal=empty-title&on=create_subtask"),
1795 "{:?}",
1796 empty.location
1797 );
1798}
1799
1800#[tokio::test]
1801async fn taking_a_task_in_and_letting_it_out_are_the_same_form() {
1802 let app = App::open().await;
1803 let admin = admin(&app).await;
1804 let columns = columns_of(&app).await;
1805 let parent = a_task(&app, &admin, &columns[0], "Ship the exporter").await;
1806 let loose = a_task(&app, &admin, &columns[1], "Write the CSV writer").await;
1807
1808 let taken = app
1809 .post(
1810 "/api/set_parent",
1811 Some(&admin),
1812 &[("task_id", &loose), ("parent_id", &parent)],
1813 )
1814 .await;
1815 assert_eq!(
1816 taken.body, "null",
1817 "taking it in was refused: {}",
1818 taken.body
1819 );
1820 let workspace_id = app.workspace_id().await;
1821 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1822 .await
1823 .unwrap()
1824 .unwrap();
1825 assert_eq!(board.columns.iter().flat_map(|c| &c.cards).count(), 1);
1826
1827 // The subtask kept its column: being taken in is not a move.
1828 let page = app.get(&format!("/?task={loose}"), Some(&admin)).await;
1829 let page = String::from_utf8_lossy(&page.bytes);
1830 // The way back up: a link that names the whole, not a caption.
1831 assert!(
1832 page.contains("detail-crumb-up") && page.contains(&format!("/?task={parent}")),
1833 "the part does not link back to its whole"
1834 );
1835 assert!(
1836 page.contains("Ship the exporter"),
1837 "the link back does not name the task it goes to"
1838 );
1839
1840 let released = app
1841 .post(
1842 "/api/set_parent",
1843 Some(&admin),
1844 &[("task_id", &loose), ("parent_id", "")],
1845 )
1846 .await;
1847 assert_eq!(
1848 released.body, "null",
1849 "letting it out was refused: {}",
1850 released.body
1851 );
1852 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
1853 .await
1854 .unwrap()
1855 .unwrap();
1856 assert_eq!(
1857 board.columns.iter().flat_map(|c| &c.cards).count(),
1858 2,
1859 "the released task did not come back to the board"
1860 );
1861}
1862
1863#[tokio::test]
1864async fn a_second_level_of_subtask_is_refused_at_the_door() {
1865 let app = App::open().await;
1866 let admin = admin(&app).await;
1867 let columns = columns_of(&app).await;
1868 let parent = a_task(&app, &admin, &columns[0], "Ship the exporter").await;
1869 let child = a_task(&app, &admin, &columns[0], "Write the CSV writer").await;
1870 let loose = a_task(&app, &admin, &columns[0], "Loose").await;
1871 app.store.set_parent(&child, Some(&parent)).await.unwrap();
1872
1873 let refused = app
1874 .post_without_script(
1875 "/api/create_subtask",
1876 Some(&admin),
1877 &format!("http://iz.sh/?task={child}"),
1878 &[("parent_id", &child), ("title", "Deeper")],
1879 )
1880 .await;
1881 assert!(
1882 refused
1883 .location
1884 .as_deref()
1885 .unwrap_or_default()
1886 .contains("refusal=not-nestable&on=create_subtask"),
1887 "{:?}",
1888 refused.location
1889 );
1890
1891 let also_refused = app
1892 .post_without_script(
1893 "/api/set_parent",
1894 Some(&admin),
1895 &format!("http://iz.sh/?task={child}"),
1896 &[("task_id", &loose), ("parent_id", &child)],
1897 )
1898 .await;
1899 assert!(
1900 also_refused
1901 .location
1902 .as_deref()
1903 .unwrap_or_default()
1904 .contains("refusal=not-nestable&on=set_parent"),
1905 "{:?}",
1906 also_refused.location
1907 );
1908}
1909
1910#[tokio::test]
1911async fn a_viewer_may_not_open_or_move_a_subtask() {
1912 let app = App::open().await;
1913 let admin = admin(&app).await;
1914 let watcher = invited(&app, &admin, "kay@iz.sh", "Kay Watcher", Role::Viewer).await;
1915 let columns = columns_of(&app).await;
1916 let parent = a_task(&app, &admin, &columns[0], "Ship the exporter").await;
1917
1918 let refused = app
1919 .post_without_script(
1920 "/api/create_subtask",
1921 Some(&watcher),
1922 &format!("http://iz.sh/?task={parent}"),
1923 &[("parent_id", &parent), ("title", "Not yours")],
1924 )
1925 .await;
1926 assert!(
1927 refused
1928 .location
1929 .as_deref()
1930 .unwrap_or_default()
1931 .contains("refusal=forbidden"),
1932 "{:?}",
1933 refused.location
1934 );
1935
1936 let also = app
1937 .post_without_script(
1938 "/api/set_parent",
1939 Some(&watcher),
1940 &format!("http://iz.sh/?task={parent}"),
1941 &[("task_id", &parent), ("parent_id", "")],
1942 )
1943 .await;
1944 assert!(
1945 also.location
1946 .as_deref()
1947 .unwrap_or_default()
1948 .contains("refusal=forbidden"),
1949 "{:?}",
1950 also.location
1951 );
1952}
1953
1954#[tokio::test]
1955async fn a_card_wears_its_conditional_classes() {
1956 // `class:foo=(cond)` renders as a literal attribute in this view macro
1957 // rather than merging into `class`, so every state that used it — a done
1958 // card, an overdue chip, a dateless chip, an open-parts chip — was
1959 // invisible. They are built with `class!` now; this holds that.
1960 let app = App::open().await;
1961 let admin = admin(&app).await;
1962 let columns = columns_of(&app).await;
1963 let task = a_task(&app, &admin, &columns[0], "Undated").await;
1964
1965 let page = app.get("/", Some(&admin)).await;
1966 let page = String::from_utf8_lossy(&page.bytes);
1967 assert!(
1968 !page.contains("class:"),
1969 "a conditional class rendered as a literal attribute"
1970 );
1971 assert!(
1972 page.contains("card-deadline card-deadline-none"),
1973 "the dateless chip lost its class"
1974 );
1975
1976 // A card in a done column carries card-done, which is what greys it.
1977 let done = columns.last().unwrap();
1978 app.post(
1979 "/api/move_card",
1980 Some(&admin),
1981 &[
1982 ("task_id", &task),
1983 ("from_column_id", &columns[0]),
1984 ("to_column_id", done),
1985 ],
1986 )
1987 .await;
1988 let page = app.get("/", Some(&admin)).await;
1989 let page = String::from_utf8_lossy(&page.bytes);
1990 assert!(
1991 page.contains("card card-done"),
1992 "a finished card is not marked"
1993 );
1994}
1995
1996#[tokio::test]
1997async fn a_parents_own_part_is_not_offered_as_a_blocker() {
1998 let app = App::open().await;
1999 let admin = admin(&app).await;
2000 let columns = columns_of(&app).await;
2001 let parent = a_task(&app, &admin, &columns[0], "Ship the exporter").await;
2002 let child = a_task(&app, &admin, &columns[0], "Write the CSV writer").await;
2003 let stranger = a_task(&app, &admin, &columns[0], "Unrelated work").await;
2004 app.store.set_parent(&child, Some(&parent)).await.unwrap();
2005
2006 // The store refuses a parent-to-part edge, so the picker must not offer
2007 // one: an option that is always refused is a worse control than no option.
2008 let page = app.get(&format!("/?task={parent}"), Some(&admin)).await;
2009 let page = String::from_utf8_lossy(&page.bytes);
2010 let picker = page
2011 .split_once("link-pop")
2012 .map(|(_, rest)| rest.split_once("</div>").map(|(p, _)| p).unwrap_or(rest))
2013 .unwrap_or_default()
2014 .to_string();
2015 assert!(
2016 !picker.contains(&child),
2017 "the picker offered the task's own part"
2018 );
2019 assert!(
2020 page.contains(&stranger),
2021 "an unrelated task vanished from the page"
2022 );
2023}
2024
2025#[tokio::test]
2026async fn the_whole_control_box_opens_its_dropdown() {
2027 // A status control is a box holding a dot, the trigger and a chevron.
2028 // Listening on the trigger alone leaves every other part of the box dead
2029 // where it looks clickable. The delegated listener walks up to whatever
2030 // *directly* contains a single trigger, which pins the hit area to the
2031 // visual box and needs no markup to opt in.
2032 let app = App::open().await;
2033 let admin = admin(&app).await;
2034 let columns = columns_of(&app).await;
2035 let task = a_task(&app, &admin, &columns[0], "Anything").await;
2036 let page = app.get(&format!("/?task={task}"), Some(&admin)).await;
2037 let page = String::from_utf8_lossy(&page.bytes);
2038
2039 assert!(
2040 page.contains("found[0].parentNode === box"),
2041 "the dropdown hit area is back to the button alone"
2042 );
2043 assert!(
2044 page.contains("trigger.__ddPanel = panel"),
2045 "a delegated click can no longer reach the panel"
2046 );
2047 // The box really is a box with siblings around the select — which is the
2048 // shape that made the button-only listener wrong in the first place.
2049 assert!(
2050 page.contains("status-dot") && page.contains("status-select"),
2051 "the status control changed shape"
2052 );
2053}
2054
2055#[tokio::test]
2056async fn the_morph_keeps_what_the_client_owns_and_names_none_of_it() {
2057 // The live refresh morphs the server's HTML over the live DOM. The server
2058 // knows nothing about the trigger the dropdown built or the class hiding
2059 // the select underneath it, so a morph that trusted the server's
2060 // attributes wholesale unhid every select under its own trigger — one
2061 // dropdown drawn twice, per field, after a single save.
2062 //
2063 // The fix is not a longer exemption list. A node declares what belongs to
2064 // the client at the moment the client takes it, and the morph reads only
2065 // that. These assertions are the guard on that shape: reintroducing a
2066 // name into the morph is what makes them fail.
2067 let app = App::open().await;
2068 let admin = admin(&app).await;
2069 let page = app.get("/settings", Some(&admin)).await;
2070 let page = String::from_utf8_lossy(&page.bytes);
2071
2072 assert!(
2073 page.contains("window.__izOwn = function (node, classes, attrs)"),
2074 "there is no way left for an enhancement to declare what it owns"
2075 );
2076 assert!(
2077 page.contains("window.__izAdded = function (node)"),
2078 "a client-built node can no longer say it is not a stray"
2079 );
2080 // The morph asks the node, never a list of names it was told to remember.
2081 assert!(
2082 page.contains("function clientMade(node) { return node.__izAdded === true; }"),
2083 "the stray test is back to sniffing class names"
2084 );
2085 assert!(
2086 page.contains("var own = from.__izMine"),
2087 "the attribute sweep no longer reads what the node owns"
2088 );
2089 // class is merged, not overwritten. This is the exact line the bug was.
2090 assert!(
2091 page.contains("syncClass(from, to, own)") && page.contains("own.c.forEach"),
2092 "the server's class list is overwriting the client's again"
2093 );
2094
2095 // And the dropdown declares, rather than relying on the morph to know.
2096 assert!(
2097 page.contains("window.__izOwn(select, ['dd-native'], [])"),
2098 "the select's hidden state is no longer declared as the client's"
2099 );
2100 assert!(
2101 page.contains("window.__izAdded(trigger)") && page.contains("window.__izAdded(panel)"),
2102 "the trigger and panel no longer say they are the client's"
2103 );
2104}
2105
2106#[tokio::test]
2107async fn a_rewired_dropdown_repairs_itself_instead_of_being_skipped() {
2108 // Ownership stops the morph from breaking the enhancement. It does not
2109 // make the enhancement follow the data: the trigger's label is drawn from
2110 // the select, so when a live refresh moves the selection the trigger has
2111 // to re-read it. An already-enhanced select is therefore repaired on
2112 // `iz:wire`, not skipped.
2113 let app = App::open().await;
2114 let admin = admin(&app).await;
2115 let page = app.get("/settings", Some(&admin)).await;
2116 let page = String::from_utf8_lossy(&page.bytes);
2117
2118 assert!(
2119 page.contains("if (select.dataset.ddDone) { resync(select); return; }"),
2120 "an already-enhanced select is skipped again instead of repaired"
2121 );
2122 assert!(
2123 page.contains("if (!rowsMatch(panel, select)) { fillRows(panel, select); }"),
2124 "the panel no longer follows the select's option list"
2125 );
2126 // Repairing under an open panel would move the rows out from under the
2127 // pointer; stale for that moment is the better failure.
2128 assert!(
2129 page.contains("if (panel.classList.contains('dd-open')) { return; }"),
2130 "the repair now runs under an open panel"
2131 );
2132}
2133
2134#[tokio::test]
2135async fn the_parts_have_a_tab_and_a_subtask_is_not_offered_one() {
2136 let app = App::open().await;
2137 let admin = admin(&app).await;
2138 let columns = columns_of(&app).await;
2139 let parent = a_task(&app, &admin, &columns[0], "Ship the exporter").await;
2140 let child = a_task(&app, &admin, &columns[0], "Write the CSV writer").await;
2141 app.store.set_parent(&child, Some(&parent)).await.unwrap();
2142
2143 // The whole gets the tab, with the ratio on it.
2144 let whole = app.get(&format!("/?task={parent}"), Some(&admin)).await;
2145 let whole = String::from_utf8_lossy(&whole.bytes);
2146 assert!(
2147 whole.contains(&format!("/?task={parent}&amp;tab=subtasks")),
2148 "the parent has no Subtasks tab"
2149 );
2150 assert!(whole.contains("0/1"), "the tab does not carry the ratio");
2151 // ...and the parts are not on the Task tab any more.
2152 assert!(
2153 !whole.contains("subtask-list"),
2154 "the parts are still rendered under the task itself"
2155 );
2156
2157 // The part is not offered a tab it can never fill.
2158 let part = app.get(&format!("/?task={child}"), Some(&admin)).await;
2159 let part = String::from_utf8_lossy(&part.bytes);
2160 assert!(
2161 !part.contains("tab=subtasks"),
2162 "a subtask was offered a Subtasks tab"
2163 );
2164
2165 // And an address that names it anyway lands on the task, not on an empty
2166 // panel with no tab lit.
2167 let forced = app
2168 .get(&format!("/?task={child}&tab=subtasks"), Some(&admin))
2169 .await;
2170 let forced = String::from_utf8_lossy(&forced.bytes);
2171 assert!(
2172 !forced.contains("subtask-new"),
2173 "a subtask rendered the Subtasks tab"
2174 );
2175 assert!(
2176 forced.contains("detail-crumb-up"),
2177 "the fallback did not render the task itself"
2178 );
2179}
2180
2181#[tokio::test]
2182async fn a_drop_decided_against_a_stale_board_is_refused() {
2183 let app = App::open().await;
2184 let admin = admin(&app).await;
2185 let member = invited(&app, &admin, "mo@iz.sh", "Mo Dubois", Role::Member).await;
2186 let columns = columns_of(&app).await;
2187 let task = a_task(&app, &admin, &columns[0], "Contested").await;
2188
2189 // Two people picked the same card up out of the first column.
2190 let first = app
2191 .post(
2192 "/api/move_card",
2193 Some(&admin),
2194 &[
2195 ("task_id", &task),
2196 ("from_column_id", &columns[0]),
2197 ("to_column_id", &columns[1]),
2198 ],
2199 )
2200 .await;
2201 assert_eq!(first.body, "");
2202
2203 let second = app
2204 .post(
2205 "/api/move_card",
2206 Some(&member),
2207 &[
2208 ("task_id", &task),
2209 ("from_column_id", &columns[0]),
2210 ("to_column_id", &columns[2]),
2211 ],
2212 )
2213 .await;
2214 assert_eq!(second.body, "");
2215 assert!(
2216 second
2217 .location
2218 .as_deref()
2219 .unwrap_or_default()
2220 .contains("refusal=moved-already&on=move_card"),
2221 "{:?}",
2222 second.location
2223 );
2224
2225 // The winner's move stands, and there is exactly one crossing.
2226 let answer = app
2227 .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
2228 .await;
2229 assert_eq!(
2230 answer.body.matches("\"moved\"").count(),
2231 1,
2232 "the second drop wrote a crossing too: {}",
2233 answer.body
2234 );
2235}
2236
2237#[tokio::test]
2238async fn a_card_cannot_be_moved_into_another_boards_column() {
2239 let app = App::open().await;
2240 let admin = admin(&app).await;
2241 let columns = columns_of(&app).await;
2242 let task = a_task(&app, &admin, &columns[0], "Stays put").await;
2243
2244 let answer = app
2245 .post(
2246 "/api/move_card",
2247 Some(&admin),
2248 &[
2249 ("task_id", &task),
2250 ("from_column_id", &columns[0]),
2251 ("to_column_id", "00000000-0000-0000-0000-000000000000"),
2252 ],
2253 )
2254 .await;
2255 assert_eq!(answer.body, "");
2256 assert!(
2257 answer
2258 .location
2259 .as_deref()
2260 .unwrap_or_default()
2261 .contains("refusal=forbidden&on=move_card"),
2262 "{:?}",
2263 answer.location
2264 );
2265 let answer = app
2266 .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
2267 .await;
2268 assert!(
2269 answer.body.contains(&columns[0]),
2270 "the forbidden move happened anyway"
2271 );
2272}
2273
2274// ---------------------------------------------------------------------------
2275// Settings: sign-out, profile, limits, sender, test mail, resend
2276// ---------------------------------------------------------------------------
2277
2278/// Settings has three `select.field-input`s (timezone, theme, language) plus
2279/// a member-role `select.status-select` once there are members — the page
2280/// carries no board.rs, so it has to wire `dropdown.rs`'s script in for
2281/// itself; this proves it did, and that the theme select still posts as a
2282/// plain named field.
2283#[tokio::test]
2284async fn settings_selects_keep_their_hidden_form_fields_and_get_a_dropdown_trigger() {
2285 let app = App::open().await;
2286 let cookie = admin(&app).await;
2287
2288 let page = app.get("/settings", Some(&cookie)).await;
2289 let html = String::from_utf8_lossy(&page.bytes);
2290 assert!(
2291 html.contains("select class=\"field-input\" name=\"theme\""),
2292 "{html}"
2293 );
2294 assert!(
2295 html.contains("dd-trigger"),
2296 "no dropdown script on the settings page: {html}"
2297 );
2298 assert!(
2299 html.contains("__izEsc.register(40"),
2300 "no escape script on the settings page: {html}"
2301 );
2302 assert!(
2303 html.contains("closest('.user-menu')"),
2304 "no user-menu close path on the settings page: {html}"
2305 );
2306}
2307
2308/// The rules and logs pages carry no `board.rs`, so like settings they wire
2309/// `layout.rs`'s shared Escape script in for themselves — rules also closes
2310/// its `<details class="rule-new">` composer on the same press.
2311#[tokio::test]
2312async fn the_rules_and_logs_pages_get_the_shared_escape_script() {
2313 let app = App::open().await;
2314 let cookie = admin(&app).await;
2315
2316 let rules_page = app.get("/rules", Some(&cookie)).await;
2317 let rules_html = String::from_utf8_lossy(&rules_page.bytes);
2318 assert!(
2319 rules_html.contains("__izEsc.register(40"),
2320 "no escape script on the rules page: {rules_html}"
2321 );
2322 assert!(
2323 rules_html.contains("details.rule-new[open]"),
2324 "escape script does not close the rule composer: {rules_html}"
2325 );
2326
2327 let logs_page = app.get("/logs", Some(&cookie)).await;
2328 let logs_html = String::from_utf8_lossy(&logs_page.bytes);
2329 assert!(
2330 logs_html.contains("__izEsc.register(40"),
2331 "no escape script on the logs page: {logs_html}"
2332 );
2333}
2334
2335/// The soft swap settles the address bar before it runs the swapped-in
2336/// page's scripts, never after. `logs.rs`'s fit script reloads through
2337/// `location.replace(location.href)`; while the link handler pushed the
2338/// new URL only after `swap()` had re-executed scripts, that read the
2339/// page the browser had just left, so clicking Logs painted the page and
2340/// hard-navigated back to the board a few hundred milliseconds later.
2341/// Ordering inside `swap` is the whole fix, so ordering is what is
2342/// asserted, together with the hazard that makes it matter.
2343#[tokio::test]
2344async fn the_soft_swap_rewrites_the_url_before_the_new_pages_scripts_run() {
2345 let app = App::open().await;
2346 let cookie = admin(&app).await;
2347
2348 let page = app.get("/", Some(&cookie)).await;
2349 let html = String::from_utf8_lossy(&page.bytes);
2350 let (_, after) = html
2351 .split_once("function swap(html, url, fresh, push, morphing)")
2352 .unwrap_or_else(|| panic!("no soft-nav swap on the board page: {html}"));
2353 let body = after
2354 .split_once("window.__izGo")
2355 .unwrap_or_else(|| panic!("swap runs past the end of the script: {after}"))
2356 .0;
2357 let rewrite = body
2358 .find("history[")
2359 .unwrap_or_else(|| panic!("swap no longer rewrites history: {body}"));
2360 let run = body
2361 .find("document.body.replaceChildren()")
2362 .unwrap_or_else(|| panic!("swap no longer replaces the body: {body}"));
2363 assert!(
2364 rewrite < run,
2365 "swap runs the new page's scripts before the URL is settled: {body}"
2366 );
2367
2368 // Every caller hands `swap` the response URL. A `null` here is the
2369 // old shape: the address bar lagged the body by one navigation.
2370 assert!(
2371 html.contains("swap(t, r.url, true, true)"),
2372 "the link handler no longer pushes through swap: {html}"
2373 );
2374 assert!(
2375 !html.contains("swap(t, null"),
2376 "a swap still runs the new page's scripts under the old URL: {html}"
2377 );
2378
2379 // The hazard itself: a swapped-in script that reads `location.href`
2380 // on load. Were this to go, the ordering above would still be right
2381 // but would guard nothing.
2382 let logs = app.get("/logs", Some(&cookie)).await;
2383 let logs_html = String::from_utf8_lossy(&logs.bytes);
2384 assert!(
2385 logs_html.contains("location.replace(location.href)"),
2386 "the log-fit reload is gone: {logs_html}"
2387 );
2388}
2389
2390#[tokio::test]
2391async fn a_member_who_posts_new_limits_anyway_is_refused() {
2392 let app = App::open().await;
2393 let admin_cookie = admin(&app).await;
2394 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
2395
2396 let answer = app
2397 .post(
2398 "/api/save_limits",
2399 Some(&member),
2400 &[
2401 ("attachment_limit_mb", "400"),
2402 ("allowed_file_types", "png"),
2403 ("mail_batch_minutes", "5"),
2404 ],
2405 )
2406 .await;
2407 assert!(
2408 answer
2409 .location
2410 .as_deref()
2411 .unwrap_or_default()
2412 .contains("refusal=forbidden&on=save_limits"),
2413 "{:?}",
2414 answer.location
2415 );
2416
2417 // The refusal is not cosmetic: the limits are where they were.
2418 let workspace = app.store.workspace().await.unwrap().unwrap();
2419 assert_eq!(workspace.attachment_limit_bytes, 25 * 1024 * 1024);
2420}
2421
2422#[tokio::test]
2423async fn an_admin_changes_the_limits_and_they_stay_changed() {
2424 let app = App::open().await;
2425 let admin_cookie = admin(&app).await;
2426
2427 let answer = app
2428 .post(
2429 "/api/save_limits",
2430 Some(&admin_cookie),
2431 &[
2432 ("attachment_limit_mb", "10"),
2433 ("allowed_file_types", ".PNG, png, pdf"),
2434 ("mail_batch_minutes", "5"),
2435 ],
2436 )
2437 .await;
2438 assert!(
2439 answer
2440 .location
2441 .as_deref()
2442 .unwrap_or_default()
2443 .contains("saved=save_limits"),
2444 "{:?}",
2445 answer.location
2446 );
2447
2448 let workspace = app.store.workspace().await.unwrap().unwrap();
2449 assert_eq!(workspace.attachment_limit_bytes, 10 * 1024 * 1024);
2450 assert_eq!(
2451 workspace.allowed_file_types,
2452 vec!["png".to_string(), "pdf".to_string()]
2453 );
2454}
2455
2456#[tokio::test]
2457async fn a_limit_outside_what_the_disk_should_promise_is_refused() {
2458 let app = App::open().await;
2459 let admin_cookie = admin(&app).await;
2460
2461 for attachment in ["5000", "0"] {
2462 let answer = app
2463 .post(
2464 "/api/save_limits",
2465 Some(&admin_cookie),
2466 &[
2467 ("attachment_limit_mb", attachment),
2468 ("allowed_file_types", ""),
2469 ("mail_batch_minutes", "5"),
2470 ],
2471 )
2472 .await;
2473 let location = answer.location.as_deref().unwrap_or_default();
2474 assert!(
2475 location.contains("refusal=bad-limit&on=save_limits"),
2476 "{attachment}: {location}"
2477 );
2478
2479 let page = app.get(location, Some(&admin_cookie)).await;
2480 let html = String::from_utf8_lossy(&page.bytes);
2481 assert!(
2482 html.contains("A limit has to be at least 1 MB, and no wider than 500 MB per file."),
2483 "{attachment}: {html}"
2484 );
2485 }
2486}
2487
2488/// The security section, end to end: an admin sees the rail link and the
2489/// panel, a member sees neither — including by asking for the section by URL
2490/// — a member's post to the save endpoint is refused by the handler, an
2491/// out-of-range number is refused by name and stores nothing, and a save in
2492/// range lands in the row and renders back into the fields.
2493
2494#[tokio::test]
2495async fn a_file_type_that_is_not_an_extension_is_refused() {
2496 let app = App::open().await;
2497 let admin_cookie = admin(&app).await;
2498
2499 let answer = app
2500 .post(
2501 "/api/save_limits",
2502 Some(&admin_cookie),
2503 &[
2504 ("attachment_limit_mb", "25"),
2505 ("allowed_file_types", "../etc/passwd"),
2506 ("mail_batch_minutes", "5"),
2507 ],
2508 )
2509 .await;
2510 let location = answer.location.as_deref().unwrap_or_default();
2511 assert!(
2512 location.contains("refusal=bad-file-type&on=save_limits"),
2513 "{location}"
2514 );
2515
2516 let page = app.get(location, Some(&admin_cookie)).await;
2517 let html = String::from_utf8_lossy(&page.bytes);
2518 assert!(html.contains("File types are extensions"), "{html}");
2519}
2520
2521#[tokio::test]
2522async fn only_an_admin_may_write_the_sender() {
2523 let app = App::open().await;
2524 let admin_cookie = admin(&app).await;
2525 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
2526
2527 let answer = app
2528 .post(
2529 "/api/save_sender",
2530 Some(&member),
2531 &[
2532 ("host", "smtp.attacker.example"),
2533 ("port", "587"),
2534 ("username", "emre"),
2535 ("password", "let-me-in"),
2536 ("from_name", "iz"),
2537 ("from_address", "emre@iz.sh"),
2538 ],
2539 )
2540 .await;
2541 assert!(
2542 answer
2543 .location
2544 .as_deref()
2545 .unwrap_or_default()
2546 .contains("refusal=forbidden&on=save_sender"),
2547 "{:?}",
2548 answer.location
2549 );
2550
2551 // And nothing was written.
2552 let workspace = app.store.workspace().await.unwrap();
2553 assert!(
2554 workspace.and_then(|ws| ws.smtp_host).unwrap_or_default() != "smtp.attacker.example",
2555 "the attacker's host was stored"
2556 );
2557}
2558
2559#[tokio::test]
2560async fn a_signed_out_browser_may_not_write_the_sender() {
2561 let app = App::open().await;
2562 let _admin_cookie = admin(&app).await;
2563
2564 let answer = app
2565 .post(
2566 "/api/save_sender",
2567 None,
2568 &[
2569 ("host", "smtp.attacker.example"),
2570 ("port", "587"),
2571 ("username", "nobody"),
2572 ("password", "let-me-in"),
2573 ("from_name", "iz"),
2574 ("from_address", "nobody@iz.sh"),
2575 ],
2576 )
2577 .await;
2578 assert!(
2579 answer
2580 .location
2581 .as_deref()
2582 .unwrap_or_default()
2583 .contains("refusal=sign-in-first&on=save_sender"),
2584 "{:?}",
2585 answer.location
2586 );
2587
2588 let workspace = app.store.workspace().await.unwrap();
2589 assert!(workspace.and_then(|ws| ws.smtp_host).unwrap_or_default() != "smtp.attacker.example");
2590}
2591
2592#[tokio::test]
2593async fn an_edit_with_no_password_typed_keeps_the_stored_one() {
2594 let app = App::open().await;
2595 let admin_cookie = admin(&app).await;
2596 assert!(sender_saved(&app, &admin_cookie).await);
2597
2598 let answer = app
2599 .post(
2600 "/api/save_sender",
2601 Some(&admin_cookie),
2602 &[
2603 ("host", "smtp.fastmail.com"),
2604 ("port", "587"),
2605 ("username", "iz"),
2606 ("password", ""),
2607 ("from_name", "iz"),
2608 ("from_address", "iz@iz.sh"),
2609 ],
2610 )
2611 .await;
2612 assert!(
2613 !answer
2614 .location
2615 .as_deref()
2616 .unwrap_or_default()
2617 .contains("refusal="),
2618 "an empty password field was refused: {:?}",
2619 answer.location
2620 );
2621
2622 let workspace = app.store.workspace().await.unwrap().unwrap();
2623 assert_eq!(workspace.smtp_port, Some(587));
2624 assert!(
2625 workspace.smtp_password_set,
2626 "an empty field blanked the password"
2627 );
2628}
2629
2630#[tokio::test]
2631async fn a_first_sender_with_no_password_is_refused_and_says_why() {
2632 let app = App::open().await;
2633 let admin_cookie = admin(&app).await;
2634
2635 let answer = app
2636 .post(
2637 "/api/save_sender",
2638 Some(&admin_cookie),
2639 &[
2640 ("host", "smtp.fastmail.com"),
2641 ("port", "587"),
2642 ("username", "iz"),
2643 ("password", ""),
2644 ("from_name", "iz"),
2645 ("from_address", "iz@iz.sh"),
2646 ],
2647 )
2648 .await;
2649 let location = answer.location.as_deref().unwrap_or_default();
2650 assert!(
2651 location.contains("refusal=bad-sender&on=save_sender"),
2652 "{location}"
2653 );
2654
2655 let page = app.get(location, Some(&admin_cookie)).await;
2656 let html = String::from_utf8_lossy(&page.bytes);
2657 assert!(
2658 html.contains("A password is needed the first time."),
2659 "{html}"
2660 );
2661}
2662
2663#[tokio::test]
2664async fn a_sender_field_that_cannot_work_is_refused_by_name() {
2665 let app = App::open().await;
2666 let admin_cookie = admin(&app).await;
2667
2668 type BadCase = (
2669 &'static str,
2670 &'static [(&'static str, &'static str)],
2671 &'static str,
2672 );
2673 let bad: &[BadCase] = &[
2674 ("host", &[("host", " ")], "Give the SMTP host."),
2675 (
2676 "host",
2677 &[("host", "smtp.fastmail.com/inbox")],
2678 "The SMTP host is a host name, not an address or a URL.",
2679 ),
2680 (
2681 "port",
2682 &[("port", "0")],
2683 "A port is a number between 1 and 65535.",
2684 ),
2685 (
2686 "port",
2687 &[("port", "99999")],
2688 "A port is a number between 1 and 65535.",
2689 ),
2690 ("username", &[("username", "")], "Give the SMTP username."),
2691 (
2692 "from_address",
2693 &[("from_address", "board-at-iz")],
2694 "That is not a from-address.",
2695 ),
2696 (
2697 "from_address",
2698 &[("from_address", "board@iz")],
2699 "That is not a from-address.",
2700 ),
2701 ];
2702 for (field, overrides, expected) in bad {
2703 let mut form: Vec<(&str, &str)> = vec![
2704 ("host", "smtp.fastmail.com"),
2705 ("port", "587"),
2706 ("username", "iz"),
2707 ("password", SENDER_PASSWORD),
2708 ("from_name", "iz"),
2709 ("from_address", "iz@iz.sh"),
2710 ];
2711 for (key, value) in *overrides {
2712 for slot in form.iter_mut() {
2713 if slot.0 == *key {
2714 slot.1 = value;
2715 }
2716 }
2717 }
2718 let answer = app
2719 .post("/api/save_sender", Some(&admin_cookie), &form)
2720 .await;
2721 let location = answer.location.as_deref().unwrap_or_default();
2722 assert!(
2723 location.contains("refusal=bad-sender&on=save_sender"),
2724 "{field} was accepted with {overrides:?}: {location}"
2725 );
2726
2727 let page = app.get(location, Some(&admin_cookie)).await;
2728 let html = String::from_utf8_lossy(&page.bytes);
2729 assert!(html.contains(*expected), "{field}: {html}");
2730 }
2731}
2732
2733#[tokio::test]
2734async fn a_member_may_not_press_the_test_button() {
2735 let app = App::open().await;
2736 let admin_cookie = admin(&app).await;
2737 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
2738
2739 let answer = app.post("/api/send_test_mail", Some(&member), &[]).await;
2740 assert!(
2741 answer
2742 .location
2743 .as_deref()
2744 .unwrap_or_default()
2745 .contains("refusal=forbidden&on=send_test_mail"),
2746 "{:?}",
2747 answer.location
2748 );
2749}
2750
2751#[tokio::test]
2752async fn a_viewer_may_not_press_the_test_button() {
2753 let app = App::open().await;
2754 let admin_cookie = admin(&app).await;
2755 let viewer = invited(&app, &admin_cookie, "pinar@iz.sh", "Pinar", Role::Viewer).await;
2756
2757 let answer = app.post("/api/send_test_mail", Some(&viewer), &[]).await;
2758 assert!(
2759 answer
2760 .location
2761 .as_deref()
2762 .unwrap_or_default()
2763 .contains("refusal=forbidden&on=send_test_mail"),
2764 "{:?}",
2765 answer.location
2766 );
2767}
2768
2769#[tokio::test]
2770async fn a_signed_out_browser_may_not_press_the_test_button() {
2771 let app = App::open().await;
2772
2773 let answer = app.post("/api/send_test_mail", None, &[]).await;
2774 assert!(
2775 answer
2776 .location
2777 .as_deref()
2778 .unwrap_or_default()
2779 .contains("refusal=sign-in-first&on=send_test_mail"),
2780 "{:?}",
2781 answer.location
2782 );
2783}
2784
2785#[tokio::test]
2786async fn testing_a_sender_that_was_never_filled_in_says_so_rather_than_sending() {
2787 let app = App::open().await;
2788 let admin_cookie = admin(&app).await;
2789
2790 let answer = app
2791 .post("/api/send_test_mail", Some(&admin_cookie), &[])
2792 .await;
2793 assert!(
2794 answer
2795 .location
2796 .as_deref()
2797 .unwrap_or_default()
2798 .contains("refusal=bad-sender&on=send_test_mail"),
2799 "{:?}",
2800 answer.location
2801 );
2802
2803 // Nothing was recorded either: the panel still has no test line to show.
2804 let workspace = app.store.workspace().await.unwrap().unwrap();
2805 assert!(
2806 workspace.sender_test.is_none(),
2807 "a test with no sender recorded a result"
2808 );
2809}
2810
2811#[tokio::test]
2812async fn an_admin_may_change_a_members_role_over_http() {
2813 let app = App::open().await;
2814 let admin_cookie = admin(&app).await;
2815 let _ = invited(&app, &admin_cookie, "mert@iz.sh", "Mert", Role::Member).await;
2816 let workspace_id = app.workspace_id().await;
2817 let mert_id = app
2818 .store
2819 .users(&workspace_id)
2820 .await
2821 .unwrap()
2822 .into_iter()
2823 .find(|user| user.email == "mert@iz.sh")
2824 .expect("no member row for mert")
2825 .id;
2826
2827 let answer = app
2828 .post(
2829 "/api/set_role",
2830 Some(&admin_cookie),
2831 &[("user_id", &mert_id), ("role", "viewer")],
2832 )
2833 .await;
2834 assert!(
2835 answer
2836 .location
2837 .as_deref()
2838 .unwrap_or_default()
2839 .contains("saved=set_role"),
2840 "{:?}",
2841 answer.location
2842 );
2843
2844 let reloaded = app.store.user(&mert_id).await.unwrap().unwrap();
2845 assert_eq!(reloaded.role, Role::Viewer, "role change did not persist");
2846}
2847
2848#[tokio::test]
2849async fn the_owner_cannot_be_retargeted_over_http() {
2850 let app = App::open().await;
2851 let admin_cookie = admin(&app).await;
2852 let owner_id = app
2853 .store
2854 .owner()
2855 .await
2856 .unwrap()
2857 .expect("workspace has no owner")
2858 .id;
2859
2860 let answer = app
2861 .post(
2862 "/api/set_role",
2863 Some(&admin_cookie),
2864 &[("user_id", &owner_id), ("role", "member")],
2865 )
2866 .await;
2867 assert!(
2868 answer
2869 .location
2870 .as_deref()
2871 .unwrap_or_default()
2872 .contains("refusal=forbidden&on=set_role"),
2873 "{:?}",
2874 answer.location
2875 );
2876
2877 let reloaded = app.store.user(&owner_id).await.unwrap().unwrap();
2878 assert_eq!(
2879 reloaded.role,
2880 Role::Admin,
2881 "the owner's role changed anyway"
2882 );
2883}
2884
2885#[tokio::test]
2886async fn a_non_admin_may_not_set_roles_over_http() {
2887 let app = App::open().await;
2888 let admin_cookie = admin(&app).await;
2889 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
2890 let _ = invited(&app, &admin_cookie, "mert@iz.sh", "Mert", Role::Member).await;
2891 let workspace_id = app.workspace_id().await;
2892 let mert_id = app
2893 .store
2894 .users(&workspace_id)
2895 .await
2896 .unwrap()
2897 .into_iter()
2898 .find(|user| user.email == "mert@iz.sh")
2899 .expect("no member row for mert")
2900 .id;
2901
2902 let answer = app
2903 .post(
2904 "/api/set_role",
2905 Some(&member),
2906 &[("user_id", &mert_id), ("role", "admin")],
2907 )
2908 .await;
2909 assert!(
2910 answer
2911 .location
2912 .as_deref()
2913 .unwrap_or_default()
2914 .contains("refusal=forbidden&on=set_role"),
2915 "{:?}",
2916 answer.location
2917 );
2918
2919 let reloaded = app.store.user(&mert_id).await.unwrap().unwrap();
2920 assert_eq!(
2921 reloaded.role,
2922 Role::Member,
2923 "role change was not really refused"
2924 );
2925}
2926
2927// ---------------------------------------------------------------------------
2928// Settings visibility: the sender and the member list are the admin's
2929// ---------------------------------------------------------------------------
2930
2931#[tokio::test]
2932async fn a_signed_out_browser_is_told_nothing_by_the_settings_call() {
2933 let app = App::open().await;
2934 let admin_cookie = admin(&app).await;
2935 assert!(sender_saved(&app, &admin_cookie).await);
2936
2937 let page = app.get("/settings", None).await;
2938 assert_eq!(page.status, StatusCode::OK);
2939 let html = String::from_utf8_lossy(&page.bytes);
2940 assert!(html.contains("Sign in first."), "{html}");
2941 assert!(!html.contains("fastmail"), "{html}");
2942}
2943
2944#[tokio::test]
2945async fn a_member_is_told_nothing_about_the_sender() {
2946 let app = App::open().await;
2947 let admin_cookie = admin(&app).await;
2948 assert!(sender_saved(&app, &admin_cookie).await);
2949 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
2950
2951 let page = app.get("/settings", Some(&member)).await;
2952 assert_eq!(page.status, StatusCode::OK);
2953 let html = String::from_utf8_lossy(&page.bytes);
2954 assert!(!html.contains("Outgoing mail"), "{html}");
2955 assert!(!html.contains("fastmail"), "{html}");
2956}
2957
2958#[tokio::test]
2959async fn an_admin_sees_the_sender_and_never_a_password() {
2960 let app = App::open().await;
2961 let admin_cookie = admin(&app).await;
2962 assert!(sender_saved(&app, &admin_cookie).await);
2963
2964 let page = app
2965 .get("/settings?section=outgoing", Some(&admin_cookie))
2966 .await;
2967 assert_eq!(page.status, StatusCode::OK);
2968 let html = String::from_utf8_lossy(&page.bytes);
2969 assert!(html.contains("smtp.fastmail.com"), "{html}");
2970 assert!(html.contains("iz@iz.sh"), "{html}");
2971 // Saved in full, and nobody has dialled the server — this router has no
2972 // mail engine at all. "Connected" would be a claim about a handshake that
2973 // never happened, which is the whole reason the chip has four states.
2974 assert!(html.contains("Unchecked"), "{html}");
2975 assert!(!html.contains("chip-connected"), "{html}");
2976 assert!(
2977 !html.contains(SENDER_PASSWORD),
2978 "the settings page carried the SMTP password: {html}"
2979 );
2980}
2981
2982#[tokio::test]
2983async fn a_member_is_not_sent_the_member_list() {
2984 let app = App::open().await;
2985 let admin_cookie = admin(&app).await;
2986 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
2987 let _ = invited(&app, &admin_cookie, "quiet@iz.sh", "Quiet", Role::Viewer).await;
2988
2989 let page = app.get("/settings", Some(&member)).await;
2990 let html = String::from_utf8_lossy(&page.bytes);
2991 assert!(!html.contains("member-table"), "{html}");
2992 assert!(!html.contains("quiet@iz.sh"), "{html}");
2993}
2994
2995#[tokio::test]
2996async fn an_admin_sees_the_member_list_with_roles_and_a_disable_control() {
2997 let app = App::open().await;
2998 let admin_cookie = admin(&app).await;
2999 let _ = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
3000
3001 let page = app
3002 .get("/settings?section=members", Some(&admin_cookie))
3003 .await;
3004 assert_eq!(page.status, StatusCode::OK);
3005 let html = String::from_utf8_lossy(&page.bytes);
3006 assert!(html.contains("member-table"), "{html}");
3007 assert!(html.contains("emre@iz.sh"), "{html}");
3008 assert!(html.contains("Ada Lovelace"), "{html}");
3009 // The admin role is im's to grant: the admin's own row wears its badge
3010 // instead of a role form.
3011 assert!(html.contains("chip-role"), "{html}");
3012 // ...and every other row carries the disable control.
3013 assert!(html.contains("/api/set_disabled"), "{html}");
3014}
3015
3016// ---------------------------------------------------------------------------
3017// Mail rules
3018// ---------------------------------------------------------------------------
3019
3020/// Writes one rule as the admin, and reports whether the server took it.
3021async fn rule_written(app: &App, admin: &str, column_id: &str, subject: &str) -> bool {
3022 let answer = app
3023 .post(
3024 "/api/create_rule",
3025 Some(admin),
3026 &[
3027 ("trigger", "status"),
3028 ("column_id", column_id),
3029 ("subject", subject),
3030 ("audience", "assignees"),
3031 ],
3032 )
3033 .await;
3034 answer.status == StatusCode::SEE_OTHER && answer.body == "null"
3035}
3036
3037/// The id of the one rule the workspace has.
3038async fn only_rule(app: &App, admin: &str) -> String {
3039 let answer = app.post("/api/current_rules", Some(admin), &[]).await;
3040 answer
3041 .body
3042 .split("\"rules\":[")
3043 .nth(1)
3044 .and_then(|rest| rest.split("\"id\":\"").nth(1))
3045 .and_then(|rest| rest.split('"').next())
3046 .unwrap_or_else(|| panic!("no rule id in {}", answer.body))
3047 .to_string()
3048}
3049
3050#[tokio::test]
3051async fn an_admin_writes_a_rule_and_reads_it_back_as_a_sentence() {
3052 let app = App::open().await;
3053 let admin_cookie = admin(&app).await;
3054 let column = first_column(&app).await;
3055
3056 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
3057
3058 let answer = app
3059 .post("/api/current_rules", Some(&admin_cookie), &[])
3060 .await;
3061 assert!(
3062 answer.body.contains("\"when\":\"When status becomes\""),
3063 "{}",
3064 answer.body
3065 );
3066 assert!(
3067 answer.body.contains("\"subject\":\"Task completed\""),
3068 "{}",
3069 answer.body
3070 );
3071 assert!(
3072 answer.body.contains("\"audience\":\"assignees\""),
3073 "{}",
3074 answer.body
3075 );
3076 // Nothing has been sent, and the row says so rather than nothing at all.
3077 assert!(
3078 answer.body.contains("\"last_sent\":null"),
3079 "{}",
3080 answer.body
3081 );
3082}
3083
3084#[tokio::test]
3085async fn a_rule_with_no_subject_is_refused_and_says_why() {
3086 let app = App::open().await;
3087 let admin_cookie = admin(&app).await;
3088 let column = first_column(&app).await;
3089
3090 let answer = app
3091 .post(
3092 "/api/create_rule",
3093 Some(&admin_cookie),
3094 &[
3095 ("trigger", "status"),
3096 ("column_id", &column),
3097 ("subject", " "),
3098 ("audience", "assignees"),
3099 ],
3100 )
3101 .await;
3102 assert!(answer.body.contains("EmptySubject"), "{}", answer.body);
3103}
3104
3105#[tokio::test]
3106async fn a_trigger_with_nothing_to_name_prints_no_term_box() {
3107 // "When someone is assigned" names no column, and the sentence used to
3108 // print the term box anyway, with nothing in it — an empty rounded box
3109 // sitting between the words. The absence was carried as an empty string,
3110 // so the renderer could not tell "no term" from "a term that is blank".
3111 let app = App::open().await;
3112 let admin_cookie = admin(&app).await;
3113 let column = first_column(&app).await;
3114
3115 // One rule that has a term, and one that has none.
3116 app.post(
3117 "/api/create_rule",
3118 Some(&admin_cookie),
3119 &[
3120 ("trigger", "status"),
3121 ("column_id", &column),
3122 ("subject", "A card reached the column."),
3123 ("audience", "assignees"),
3124 ],
3125 )
3126 .await;
3127 app.post(
3128 "/api/create_rule",
3129 Some(&admin_cookie),
3130 &[
3131 ("trigger", "assigned"),
3132 ("column_id", ""),
3133 ("subject", "You have been assigned a task."),
3134 ("audience", "assignees"),
3135 ],
3136 )
3137 .await;
3138
3139 let page = app.get("/rules", Some(&admin_cookie)).await;
3140 let page = String::from_utf8_lossy(&page.bytes);
3141 // The rule with no column is on the page at all — without this the
3142 // assertion below passes by having nothing to assert on.
3143 assert!(
3144 page.contains("When someone is assigned"),
3145 "the triggerless rule was never created, so this test proves nothing"
3146 );
3147 assert!(
3148 !page.contains(r#"<span class="rule-term"></span>"#),
3149 "a trigger with no second half still prints an empty term box"
3150 );
3151 // The rule that does name a column still shows it, so this did not fix
3152 // the box by removing it.
3153 assert!(
3154 page.contains(r#"<span class="rule-term">"#),
3155 "the term box is gone from the rule that has a term"
3156 );
3157}
3158
3159#[tokio::test]
3160async fn a_rule_may_not_be_hung_off_a_column_that_is_not_on_this_board() {
3161 let app = App::open().await;
3162 let admin_cookie = admin(&app).await;
3163
3164 let answer = app
3165 .post(
3166 "/api/create_rule",
3167 Some(&admin_cookie),
3168 &[
3169 ("trigger", "status"),
3170 ("column_id", &Ulid::generate().to_string()),
3171 ("subject", "Task completed"),
3172 ("audience", "assignees"),
3173 ],
3174 )
3175 .await;
3176 assert!(answer.body.contains("Forbidden"), "{}", answer.body);
3177
3178 let seen = app
3179 .post("/api/current_rules", Some(&admin_cookie), &[])
3180 .await;
3181 assert!(seen.body.contains("\"rules\":[]"), "{}", seen.body);
3182}
3183
3184#[tokio::test]
3185async fn an_audience_the_screen_never_offers_is_refused() {
3186 let app = App::open().await;
3187 let admin_cookie = admin(&app).await;
3188 let column = first_column(&app).await;
3189
3190 let answer = app
3191 .post(
3192 "/api/create_rule",
3193 Some(&admin_cookie),
3194 &[
3195 ("trigger", "status"),
3196 ("column_id", &column),
3197 ("subject", "Task completed"),
3198 ("audience", "everyone-everywhere"),
3199 ],
3200 )
3201 .await;
3202 assert!(answer.body.contains("Forbidden"), "{}", answer.body);
3203}
3204
3205#[tokio::test]
3206async fn switching_a_rule_off_leaves_it_listed_and_switched_off() {
3207 let app = App::open().await;
3208 let admin_cookie = admin(&app).await;
3209 let column = first_column(&app).await;
3210 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
3211 let rule = only_rule(&app, &admin_cookie).await;
3212
3213 let answer = app
3214 .post(
3215 "/api/set_rule_enabled",
3216 Some(&admin_cookie),
3217 &[("rule_id", &rule), ("enabled", "false")],
3218 )
3219 .await;
3220 assert_eq!(answer.body, "null", "{}", answer.body);
3221
3222 // The screen lists what exists, not what is live.
3223 let seen = app
3224 .post("/api/current_rules", Some(&admin_cookie), &[])
3225 .await;
3226 assert!(seen.body.contains("\"enabled\":false"), "{}", seen.body);
3227 assert!(
3228 seen.body.contains("\"subject\":\"Task completed\""),
3229 "{}",
3230 seen.body
3231 );
3232}
3233
3234#[tokio::test]
3235async fn a_rule_id_this_workspace_does_not_own_is_refused() {
3236 let app = App::open().await;
3237 let admin_cookie = admin(&app).await;
3238 let stranger = Ulid::generate().to_string();
3239
3240 for path in ["/api/set_rule_enabled", "/api/delete_rule"] {
3241 let answer = app
3242 .post(
3243 path,
3244 Some(&admin_cookie),
3245 &[("rule_id", &stranger), ("enabled", "false")],
3246 )
3247 .await;
3248 assert!(answer.body.contains("NotFound"), "{path}: {}", answer.body);
3249 }
3250}
3251
3252#[tokio::test]
3253async fn deleting_a_rule_takes_it_off_the_screen() {
3254 let app = App::open().await;
3255 let admin_cookie = admin(&app).await;
3256 let column = first_column(&app).await;
3257 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
3258 let rule = only_rule(&app, &admin_cookie).await;
3259
3260 let answer = app
3261 .post(
3262 "/api/delete_rule",
3263 Some(&admin_cookie),
3264 &[("rule_id", &rule)],
3265 )
3266 .await;
3267 assert_eq!(answer.body, "null", "{}", answer.body);
3268
3269 let seen = app
3270 .post("/api/current_rules", Some(&admin_cookie), &[])
3271 .await;
3272 assert!(seen.body.contains("\"rules\":[]"), "{}", seen.body);
3273}
3274
3275#[tokio::test]
3276async fn only_an_admin_may_read_or_write_the_rules() {
3277 let app = App::open().await;
3278 let admin_cookie = admin(&app).await;
3279 let column = first_column(&app).await;
3280 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
3281 let rule = only_rule(&app, &admin_cookie).await;
3282
3283 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
3284 let viewer = invited(&app, &admin_cookie, "pinar@iz.sh", "Pinar", Role::Viewer).await;
3285
3286 for who in [&member, &viewer] {
3287 let read = app.post("/api/current_rules", Some(who), &[]).await;
3288 assert!(read.body.contains("Forbidden"), "{}", read.body);
3289
3290 let written = app
3291 .post(
3292 "/api/create_rule",
3293 Some(who),
3294 &[
3295 ("trigger", "status"),
3296 ("column_id", &column),
3297 ("subject", "Mail everyone about me"),
3298 ("audience", "board"),
3299 ],
3300 )
3301 .await;
3302 assert!(written.body.contains("Forbidden"), "{}", written.body);
3303
3304 let switched = app
3305 .post(
3306 "/api/set_rule_enabled",
3307 Some(who),
3308 &[("rule_id", &rule), ("enabled", "false")],
3309 )
3310 .await;
3311 assert!(switched.body.contains("Forbidden"), "{}", switched.body);
3312
3313 let deleted = app
3314 .post("/api/delete_rule", Some(who), &[("rule_id", &rule)])
3315 .await;
3316 assert!(deleted.body.contains("Forbidden"), "{}", deleted.body);
3317 }
3318
3319 // And the rule is untouched: still there, still on.
3320 let seen = app
3321 .post("/api/current_rules", Some(&admin_cookie), &[])
3322 .await;
3323 assert!(seen.body.contains("\"enabled\":true"), "{}", seen.body);
3324 assert!(
3325 !seen.body.contains("Mail everyone about me"),
3326 "{}",
3327 seen.body
3328 );
3329}
3330
3331#[tokio::test]
3332async fn a_signed_out_browser_may_not_touch_the_rules() {
3333 let app = App::open().await;
3334 let admin_cookie = admin(&app).await;
3335 let column = first_column(&app).await;
3336 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
3337 let rule = only_rule(&app, &admin_cookie).await;
3338
3339 for (path, form) in [
3340 ("/api/current_rules", vec![] as Vec<(&str, &str)>),
3341 (
3342 "/api/create_rule",
3343 vec![
3344 ("trigger", "status"),
3345 ("column_id", column.as_str()),
3346 ("subject", "Task completed"),
3347 ("audience", "assignees"),
3348 ],
3349 ),
3350 (
3351 "/api/set_rule_enabled",
3352 vec![("rule_id", rule.as_str()), ("enabled", "false")],
3353 ),
3354 ("/api/delete_rule", vec![("rule_id", rule.as_str())]),
3355 ] {
3356 let answer = app.post(path, None, &form).await;
3357 assert!(
3358 answer.body.contains("SignInFirst"),
3359 "{path}: {}",
3360 answer.body
3361 );
3362 }
3363}
3364
3365// ---------------------------------------------------------------------------
3366// Attachments
3367// ---------------------------------------------------------------------------
3368
3369#[tokio::test]
3370async fn a_download_of_an_unknown_attachment_is_not_found_and_signed_out_is_a_redirect() {
3371 let app = App::open().await;
3372 let admin_cookie = admin(&app).await;
3373
3374 let signed_in = app.get("/files/anything", Some(&admin_cookie)).await;
3375 assert_eq!(signed_in.status, StatusCode::NOT_FOUND);
3376
3377 let signed_out = app.get("/files/anything", None).await;
3378 assert_eq!(signed_out.status, StatusCode::SEE_OTHER);
3379}
3380
3381// A signed-in member's detail page carries the upload form no-script needs: a
3382// real multipart `<form>` posting to `/files`, not a hydrated one — a browser
3383// with no script still has a way to attach a file.
3384#[tokio::test]
3385async fn the_files_section_is_on_the_detail_page() {
3386 let app = App::open().await;
3387 let admin_cookie = admin(&app).await;
3388 let column = first_column(&app).await;
3389 let task = a_task(&app, &admin_cookie, &column, "Attach something to me").await;
3390
3391 let page = app
3392 .get(&format!("/?task={task}&tab=files"), Some(&admin_cookie))
3393 .await;
3394 assert_eq!(page.status, StatusCode::OK);
3395 let html = String::from_utf8_lossy(&page.bytes);
3396 assert!(
3397 html.contains("multipart/form-data"),
3398 "no multipart upload form on the detail page"
3399 );
3400 assert!(
3401 html.contains(r#"action="/files""#),
3402 "the upload form does not post to /files"
3403 );
3404}
3405
3406#[tokio::test]
3407async fn the_datepicker_shell_renders_in_both_task_modals() {
3408 let app = App::open().await;
3409 let admin_cookie = admin(&app).await;
3410 let column = first_column(&app).await;
3411 let task = a_task(&app, &admin_cookie, &column, "Pick a date on me").await;
3412
3413 let detail = app
3414 .get(&format!("/?task={task}"), Some(&admin_cookie))
3415 .await;
3416 let html = String::from_utf8_lossy(&detail.bytes);
3417 assert!(
3418 html.contains("datepick-input"),
3419 "no datepicker shell on the task modal: {html}"
3420 );
3421 assert!(
3422 html.contains("datepick-grid"),
3423 "no datepicker grid on the task modal: {html}"
3424 );
3425
3426 let new_task = app.get("/?new=1", Some(&admin_cookie)).await;
3427 let html = String::from_utf8_lossy(&new_task.bytes);
3428 assert!(
3429 html.contains("datepick-input"),
3430 "no datepicker shell on the new-task modal: {html}"
3431 );
3432 assert!(
3433 html.contains("datepick-grid"),
3434 "no datepicker grid on the new-task modal: {html}"
3435 );
3436}
3437
3438/// The id of the file named `name` in a `/api/fetch_task` snapshot's body,
3439/// read the way the page would: found by its name, then the `id` field that
3440/// comes right before it on the wire.
3441fn attachment_id_named(body: &str, name: &str) -> String {
3442 let needle = format!("\",\"name\":\"{name}\"");
3443 let before = body
3444 .split_once(&needle)
3445 .map(|(head, _)| head)
3446 .unwrap_or_else(|| panic!("no file named {name} in the detail snapshot: {body}"));
3447 before
3448 .rsplit_once("\"id\":\"")
3449 .and_then(|(_, rest)| rest.split('"').next())
3450 .expect("no id before the file name")
3451 .to_string()
3452}
3453
3454#[tokio::test]
3455async fn a_viewer_who_posts_an_upload_anyway_is_refused() {
3456 let app = App::open().await;
3457 let admin_cookie = admin(&app).await;
3458 let viewer = invited(
3459 &app,
3460 &admin_cookie,
3461 "quiet@iz.sh",
3462 "Quiet Reader",
3463 Role::Viewer,
3464 )
3465 .await;
3466 let column = first_column(&app).await;
3467 let task = a_task(&app, &admin_cookie, &column, "Viewers cannot attach").await;
3468
3469 let answer = app
3470 .post_multipart(
3471 "/files",
3472 Some(&viewer),
3473 &[("task_id", &task)],
3474 Some(("note.txt", "text/plain", b"hello")),
3475 )
3476 .await;
3477 assert_eq!(answer.status, StatusCode::SEE_OTHER);
3478 assert_eq!(
3479 answer.location.as_deref(),
3480 Some("/?refusal=forbidden&on=upload_file")
3481 );
3482}
3483
3484#[tokio::test]
3485async fn a_member_uploads_a_file_and_the_chip_comes_back() {
3486 let app = App::open().await;
3487 let admin_cookie = admin(&app).await;
3488 let member = invited(&app, &admin_cookie, "mo@iz.sh", "Mo Dubois", Role::Member).await;
3489 let column = first_column(&app).await;
3490 let task = a_task(&app, &admin_cookie, &column, "Attach the spec").await;
3491
3492 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
3493 let answer = app
3494 .post_multipart(
3495 "/files",
3496 Some(&member),
3497 &[("task_id", &task)],
3498 Some(("spec.png", "image/png", &png)),
3499 )
3500 .await;
3501 assert_eq!(answer.status, StatusCode::SEE_OTHER);
3502 assert_eq!(
3503 answer.location.as_deref(),
3504 Some(format!("/?task={task}&tab=files").as_str())
3505 );
3506
3507 let snapshot = app
3508 .post("/api/fetch_task", Some(&member), &[("task_id", &task)])
3509 .await;
3510 let file_id = attachment_id_named(&snapshot.body, "spec.png");
3511
3512 let page = app
3513 .get(&format!("/?task={task}&tab=files"), Some(&member))
3514 .await;
3515 assert_eq!(page.status, StatusCode::OK);
3516 let html = String::from_utf8_lossy(&page.bytes);
3517 assert!(
3518 html.contains(&format!("task={task}&amp;tab=files&amp;file={file_id}")),
3519 "no viewer href for the new file: {html}"
3520 );
3521 assert!(html.contains("spec.png"));
3522
3523 let download = app.get(&format!("/files/{file_id}"), Some(&member)).await;
3524 assert_eq!(download.status, StatusCode::OK);
3525 assert_eq!(download.bytes, png);
3526}
3527
3528#[tokio::test]
3529async fn an_image_downloads_inline_and_an_unrecognised_type_stays_attachment() {
3530 let app = App::open().await;
3531 let admin_cookie = admin(&app).await;
3532 let column = first_column(&app).await;
3533 let task = a_task(&app, &admin_cookie, &column, "Two kinds of file").await;
3534
3535 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
3536 app.post_multipart(
3537 "/files",
3538 Some(&admin_cookie),
3539 &[("task_id", &task)],
3540 Some(("spec.png", "image/png", &png)),
3541 )
3542 .await;
3543 let unknown = [0x00u8, 0x01, 0xFE, 0xFF, 0x02];
3544 app.post_multipart(
3545 "/files",
3546 Some(&admin_cookie),
3547 &[("task_id", &task)],
3548 Some(("blob.bin", "application/octet-stream", &unknown)),
3549 )
3550 .await;
3551
3552 let snapshot = app
3553 .post(
3554 "/api/fetch_task",
3555 Some(&admin_cookie),
3556 &[("task_id", &task)],
3557 )
3558 .await;
3559 let png_id = attachment_id_named(&snapshot.body, "spec.png");
3560 let blob_id = attachment_id_named(&snapshot.body, "blob.bin");
3561
3562 let png_download = app
3563 .get(&format!("/files/{png_id}"), Some(&admin_cookie))
3564 .await;
3565 assert_eq!(png_download.content_type.as_deref(), Some("image/png"));
3566 assert!(
3567 png_download
3568 .disposition
3569 .as_deref()
3570 .unwrap_or_default()
3571 .starts_with("inline;"),
3572 "{:?}",
3573 png_download.disposition
3574 );
3575
3576 let blob_download = app
3577 .get(&format!("/files/{blob_id}"), Some(&admin_cookie))
3578 .await;
3579 assert!(
3580 blob_download
3581 .disposition
3582 .as_deref()
3583 .unwrap_or_default()
3584 .starts_with("attachment;"),
3585 "{:?}",
3586 blob_download.disposition
3587 );
3588}
3589
3590#[tokio::test]
3591async fn dl_forces_a_download_of_an_otherwise_inline_type() {
3592 let app = App::open().await;
3593 let admin_cookie = admin(&app).await;
3594 let column = first_column(&app).await;
3595 let task = a_task(&app, &admin_cookie, &column, "Forced download").await;
3596
3597 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
3598 app.post_multipart(
3599 "/files",
3600 Some(&admin_cookie),
3601 &[("task_id", &task)],
3602 Some(("spec.png", "image/png", &png)),
3603 )
3604 .await;
3605 let snapshot = app
3606 .post(
3607 "/api/fetch_task",
3608 Some(&admin_cookie),
3609 &[("task_id", &task)],
3610 )
3611 .await;
3612 let file_id = attachment_id_named(&snapshot.body, "spec.png");
3613
3614 let forced = app
3615 .get(&format!("/files/{file_id}?dl=1"), Some(&admin_cookie))
3616 .await;
3617 assert!(
3618 forced
3619 .disposition
3620 .as_deref()
3621 .unwrap_or_default()
3622 .starts_with("attachment;"),
3623 "{:?}",
3624 forced.disposition
3625 );
3626}
3627
3628// Safari refuses to play `<video>`/`<audio>` without a `206` answer to its
3629// own `Range` probe on the download route.
3630#[tokio::test]
3631async fn a_range_request_answers_206_with_the_sliced_bytes_and_a_bad_range_answers_416() {
3632 let app = App::open().await;
3633 let admin_cookie = admin(&app).await;
3634 let column = first_column(&app).await;
3635 let task = a_task(&app, &admin_cookie, &column, "Ranged download").await;
3636
3637 let bytes = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
3638 app.post_multipart(
3639 "/files",
3640 Some(&admin_cookie),
3641 &[("task_id", &task)],
3642 Some(("spec.png", "image/png", &bytes)),
3643 )
3644 .await;
3645 let snapshot = app
3646 .post(
3647 "/api/fetch_task",
3648 Some(&admin_cookie),
3649 &[("task_id", &task)],
3650 )
3651 .await;
3652 let file_id = attachment_id_named(&snapshot.body, "spec.png");
3653 let total = bytes.len();
3654
3655 let no_range = app
3656 .get(&format!("/files/{file_id}"), Some(&admin_cookie))
3657 .await;
3658 assert_eq!(no_range.status, StatusCode::OK);
3659 assert_eq!(no_range.accept_ranges.as_deref(), Some("bytes"));
3660 assert_eq!(no_range.bytes, bytes);
3661
3662 let first_four = app
3663 .get_with_range(
3664 &format!("/files/{file_id}"),
3665 Some(&admin_cookie),
3666 Some("bytes=0-3"),
3667 )
3668 .await;
3669 assert_eq!(first_four.status, StatusCode::PARTIAL_CONTENT);
3670 assert_eq!(
3671 first_four.content_range.as_deref(),
3672 Some(format!("bytes 0-3/{total}").as_str())
3673 );
3674 assert_eq!(first_four.bytes, &bytes[0..4]);
3675
3676 let last_two = app
3677 .get_with_range(
3678 &format!("/files/{file_id}"),
3679 Some(&admin_cookie),
3680 Some("bytes=-2"),
3681 )
3682 .await;
3683 assert_eq!(last_two.status, StatusCode::PARTIAL_CONTENT);
3684 assert_eq!(
3685 last_two.content_range.as_deref(),
3686 Some(format!("bytes {}-{}/{total}", total - 2, total - 1).as_str())
3687 );
3688 assert_eq!(last_two.bytes, &bytes[total - 2..]);
3689
3690 let out_of_range = app
3691 .get_with_range(
3692 &format!("/files/{file_id}"),
3693 Some(&admin_cookie),
3694 Some(&format!("bytes={total}-{}", total + 10)),
3695 )
3696 .await;
3697 assert_eq!(out_of_range.status, StatusCode::RANGE_NOT_SATISFIABLE);
3698 assert_eq!(
3699 out_of_range.content_range.as_deref(),
3700 Some(format!("bytes */{total}").as_str())
3701 );
3702}
3703
3704#[tokio::test]
3705async fn the_viewer_renders_in_page_for_a_renderable_file_and_ignores_a_foreign_or_missing_one() {
3706 let app = App::open().await;
3707 let admin_cookie = admin(&app).await;
3708 let column = first_column(&app).await;
3709 let task = a_task(&app, &admin_cookie, &column, "Open it in place").await;
3710 let other_task = a_task(&app, &admin_cookie, &column, "Not this one").await;
3711
3712 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
3713 app.post_multipart(
3714 "/files",
3715 Some(&admin_cookie),
3716 &[("task_id", &task)],
3717 Some(("spec.png", "image/png", &png)),
3718 )
3719 .await;
3720 let snapshot = app
3721 .post(
3722 "/api/fetch_task",
3723 Some(&admin_cookie),
3724 &[("task_id", &task)],
3725 )
3726 .await;
3727 let file_id = attachment_id_named(&snapshot.body, "spec.png");
3728
3729 let page = app
3730 .get(
3731 &format!("/?task={task}&file={file_id}"),
3732 Some(&admin_cookie),
3733 )
3734 .await;
3735 assert_eq!(page.status, StatusCode::OK);
3736 let html = String::from_utf8_lossy(&page.bytes);
3737 // "viewer-body" marks the rendered overlay; the viewer's Escape resolver
3738 // that escape_closes registers (priority 90) also appears here on task
3739 // pages only, not every board page.
3740 assert!(
3741 html.contains("viewer-body"),
3742 "no viewer overlay in the page: {html}"
3743 );
3744 assert!(
3745 html.contains("__izEsc.register(90"),
3746 "no viewer escape resolver in the page: {html}"
3747 );
3748 assert!(
3749 html.contains(&format!("/files/{file_id}")),
3750 "viewer's <img> does not point at the file: {html}"
3751 );
3752
3753 // A file id that exists but belongs to another task is refused the same
3754 // silent way a made-up one is: no overlay, the task modal alone.
3755 let wrong_task_page = app
3756 .get(
3757 &format!("/?task={other_task}&file={file_id}"),
3758 Some(&admin_cookie),
3759 )
3760 .await;
3761 assert!(!String::from_utf8_lossy(&wrong_task_page.bytes).contains("viewer-body"));
3762
3763 let missing_page = app
3764 .get(&format!("/?task={task}&file=anything"), Some(&admin_cookie))
3765 .await;
3766 assert_eq!(missing_page.status, StatusCode::OK);
3767 assert!(!String::from_utf8_lossy(&missing_page.bytes).contains("viewer-body"));
3768}
3769
3770/// The PDF reader is the one viewer with a presentation mode: its overlay
3771/// carries the Present control and the delegated listener that answers it,
3772/// while an image's overlay carries neither.
3773#[tokio::test]
3774async fn the_pdf_viewer_offers_presentation_mode_and_other_viewers_do_not() {
3775 let app = App::open().await;
3776 let admin_cookie = admin(&app).await;
3777 let column = first_column(&app).await;
3778 let task = a_task(&app, &admin_cookie, &column, "Present me").await;
3779
3780 let pdf = b"%PDF-1.4 nothing to see".to_vec();
3781 app.post_multipart(
3782 "/files",
3783 Some(&admin_cookie),
3784 &[("task_id", &task)],
3785 Some(("deck.pdf", "application/pdf", &pdf)),
3786 )
3787 .await;
3788 let snapshot = app
3789 .post(
3790 "/api/fetch_task",
3791 Some(&admin_cookie),
3792 &[("task_id", &task)],
3793 )
3794 .await;
3795 let pdf_id = attachment_id_named(&snapshot.body, "deck.pdf");
3796
3797 let page = app
3798 .get(&format!("/?task={task}&file={pdf_id}"), Some(&admin_cookie))
3799 .await;
3800 let html = String::from_utf8_lossy(&page.bytes);
3801 assert!(
3802 html.contains("viewer-present"),
3803 "no Present control on a PDF: {html}"
3804 );
3805 assert!(
3806 html.contains("requestFullscreen"),
3807 "no presentation wiring on a PDF: {html}"
3808 );
3809
3810 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
3811 app.post_multipart(
3812 "/files",
3813 Some(&admin_cookie),
3814 &[("task_id", &task)],
3815 Some(("spec.png", "image/png", &png)),
3816 )
3817 .await;
3818 let snapshot = app
3819 .post(
3820 "/api/fetch_task",
3821 Some(&admin_cookie),
3822 &[("task_id", &task)],
3823 )
3824 .await;
3825 let png_id = attachment_id_named(&snapshot.body, "spec.png");
3826 let page = app
3827 .get(&format!("/?task={task}&file={png_id}"), Some(&admin_cookie))
3828 .await;
3829 let html = String::from_utf8_lossy(&page.bytes);
3830 assert!(
3831 !html.contains("viewer-present"),
3832 "an image got the PDF's Present control: {html}"
3833 );
3834}
3835
3836/// A file is opened from a section, so closing it lands back on that section:
3837/// the close links carry the tab the viewer was opened over, not the panel's
3838/// default.
3839#[tokio::test]
3840async fn closing_a_file_returns_to_the_tab_it_was_opened_from() {
3841 let app = App::open().await;
3842 let admin_cookie = admin(&app).await;
3843 let column = first_column(&app).await;
3844 let task = a_task(&app, &admin_cookie, &column, "Open it in place").await;
3845 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
3846 app.post_multipart(
3847 "/files",
3848 Some(&admin_cookie),
3849 &[("task_id", &task)],
3850 Some(("spec.png", "image/png", &png)),
3851 )
3852 .await;
3853 let snapshot = app
3854 .post(
3855 "/api/fetch_task",
3856 Some(&admin_cookie),
3857 &[("task_id", &task)],
3858 )
3859 .await;
3860 let file_id = attachment_id_named(&snapshot.body, "spec.png");
3861
3862 let page = app
3863 .get(
3864 &format!("/?task={task}&tab=files&file={file_id}"),
3865 Some(&admin_cookie),
3866 )
3867 .await;
3868 assert_eq!(page.status, StatusCode::OK);
3869 let html = String::from_utf8_lossy(&page.bytes);
3870 assert!(html.contains("viewer-body"), "no viewer overlay: {html}");
3871 // The tab strip behind the overlay carries the same href, so the check
3872 // names the close control itself.
3873 assert!(
3874 html.contains(&format!(
3875 "class=\"viewer-close\" href=\"/?task={task}&amp;tab=files\""
3876 )),
3877 "viewer closes to the bare task, losing the section: {html}"
3878 );
3879}
3880
3881#[tokio::test]
3882async fn a_file_past_the_workspace_limit_is_refused_before_it_is_kept() {
3883 let app = App::open().await;
3884 let admin_cookie = admin(&app).await;
3885 let column = first_column(&app).await;
3886 let task = a_task(&app, &admin_cookie, &column, "Too big to keep").await;
3887
3888 let answer = app
3889 .post(
3890 "/api/save_limits",
3891 Some(&admin_cookie),
3892 &[
3893 ("attachment_limit_mb", "1"),
3894 ("allowed_file_types", ""),
3895 ("mail_batch_minutes", "5"),
3896 ],
3897 )
3898 .await;
3899 assert!(
3900 !answer
3901 .location
3902 .as_deref()
3903 .unwrap_or_default()
3904 .contains("refusal="),
3905 "{:?}",
3906 answer.location
3907 );
3908
3909 let big = vec![0u8; 2 * 1024 * 1024];
3910 let answer = app
3911 .post_multipart(
3912 "/files",
3913 Some(&admin_cookie),
3914 &[("task_id", &task)],
3915 Some(("big.bin", "application/octet-stream", &big)),
3916 )
3917 .await;
3918 assert_eq!(answer.status, StatusCode::SEE_OTHER);
3919 assert_eq!(
3920 answer.location.as_deref(),
3921 Some(format!("/?task={task}&tab=files&refusal=file-too-big&on=upload_file").as_str())
3922 );
3923
3924 let snapshot = app
3925 .post(
3926 "/api/fetch_task",
3927 Some(&admin_cookie),
3928 &[("task_id", &task)],
3929 )
3930 .await;
3931 assert!(snapshot.body.contains("\"files\":[]"), "{}", snapshot.body);
3932}
3933
3934#[tokio::test]
3935async fn a_file_type_off_the_list_is_refused() {
3936 let app = App::open().await;
3937 let admin_cookie = admin(&app).await;
3938 let column = first_column(&app).await;
3939 let task = a_task(&app, &admin_cookie, &column, "No executables here").await;
3940
3941 let answer = app
3942 .post(
3943 "/api/save_limits",
3944 Some(&admin_cookie),
3945 &[
3946 ("attachment_limit_mb", "25"),
3947 ("allowed_file_types", "png"),
3948 ("mail_batch_minutes", "5"),
3949 ],
3950 )
3951 .await;
3952 assert!(
3953 !answer
3954 .location
3955 .as_deref()
3956 .unwrap_or_default()
3957 .contains("refusal="),
3958 "{:?}",
3959 answer.location
3960 );
3961
3962 let answer = app
3963 .post_multipart(
3964 "/files",
3965 Some(&admin_cookie),
3966 &[("task_id", &task)],
3967 Some(("evil.exe", "application/octet-stream", b"MZ\x90\x00")),
3968 )
3969 .await;
3970 assert_eq!(answer.status, StatusCode::SEE_OTHER);
3971 assert_eq!(
3972 answer.location.as_deref(),
3973 Some(format!("/?task={task}&tab=files&refusal=file-type&on=upload_file").as_str())
3974 );
3975}
3976
3977#[tokio::test]
3978async fn an_empty_allowed_list_lets_anything_through() {
3979 let app = App::open().await;
3980 let admin_cookie = admin(&app).await;
3981 let column = first_column(&app).await;
3982 let task = a_task(&app, &admin_cookie, &column, "Whatever shows up").await;
3983
3984 let answer = app
3985 .post_multipart(
3986 "/files",
3987 Some(&admin_cookie),
3988 &[("task_id", &task)],
3989 Some((
3990 "anything.bin",
3991 "application/octet-stream",
3992 &[0x00, 0x01, 0x02],
3993 )),
3994 )
3995 .await;
3996 assert_eq!(answer.status, StatusCode::SEE_OTHER);
3997 assert_eq!(
3998 answer.location.as_deref(),
3999 Some(format!("/?task={task}&tab=files").as_str())
4000 );
4001}
4002
4003#[tokio::test]
4004async fn the_stored_type_is_what_the_bytes_are_not_what_the_upload_claimed() {
4005 let app = App::open().await;
4006 let admin_cookie = admin(&app).await;
4007 let column = first_column(&app).await;
4008 let task = a_task(&app, &admin_cookie, &column, "Mislabeled on the way in").await;
4009
4010 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
4011 let answer = app
4012 .post_multipart(
4013 "/files",
4014 Some(&admin_cookie),
4015 &[("task_id", &task)],
4016 Some(("liar.pdf", "application/pdf", &png)),
4017 )
4018 .await;
4019 assert_eq!(answer.status, StatusCode::SEE_OTHER);
4020
4021 let snapshot = app
4022 .post(
4023 "/api/fetch_task",
4024 Some(&admin_cookie),
4025 &[("task_id", &task)],
4026 )
4027 .await;
4028 let file_id = attachment_id_named(&snapshot.body, "liar.pdf");
4029
4030 let download = app
4031 .get(&format!("/files/{file_id}"), Some(&admin_cookie))
4032 .await;
4033 assert_eq!(download.content_type.as_deref(), Some("image/png"));
4034}
4035
4036#[tokio::test]
4037async fn a_file_name_that_is_a_path_is_kept_as_a_label() {
4038 let app = App::open().await;
4039 let admin_cookie = admin(&app).await;
4040 let column = first_column(&app).await;
4041 let task = a_task(&app, &admin_cookie, &column, "Filename tries to escape").await;
4042
4043 let answer = app
4044 .post_multipart(
4045 "/files",
4046 Some(&admin_cookie),
4047 &[("task_id", &task)],
4048 Some(("../../etc/passwd", "text/plain", b"root:x:0:0")),
4049 )
4050 .await;
4051 assert_eq!(answer.status, StatusCode::SEE_OTHER);
4052
4053 let snapshot = app
4054 .post(
4055 "/api/fetch_task",
4056 Some(&admin_cookie),
4057 &[("task_id", &task)],
4058 )
4059 .await;
4060 assert!(
4061 snapshot.body.contains("\"name\":\"passwd\""),
4062 "the stored name still has a path in it: {}",
4063 snapshot.body
4064 );
4065 let file_id = attachment_id_named(&snapshot.body, "passwd");
4066
4067 let page = app
4068 .get(&format!("/?task={task}"), Some(&admin_cookie))
4069 .await;
4070 let html = String::from_utf8_lossy(&page.bytes);
4071 assert!(
4072 !html.contains("../../etc/passwd"),
4073 "the raw path leaked onto the chip: {html}"
4074 );
4075
4076 let download = app
4077 .get(&format!("/files/{file_id}"), Some(&admin_cookie))
4078 .await;
4079 let disposition = download
4080 .disposition
4081 .expect("no content-disposition on the download");
4082 assert!(!disposition.contains('\r'), "{disposition}");
4083 assert!(!disposition.contains('\n'), "{disposition}");
4084 assert!(!disposition.contains('/'), "{disposition}");
4085}
4086
4087/// A second workspace is a second database in this harness — there is no way
4088/// to build two workspaces sharing one store to prove sibling-workspace
4089/// isolation directly. What this proves instead: an attachment id that is
4090/// real, just not in *this* store, gets the same 404 an id from nowhere gets.
4091#[tokio::test]
4092async fn a_file_from_another_workspace_is_not_found() {
4093 let app_a = App::open().await;
4094 let admin_a = admin(&app_a).await;
4095
4096 let app_b = App::open().await;
4097 let admin_b = admin(&app_b).await;
4098 let column_b = first_column(&app_b).await;
4099 let task_b = a_task(&app_b, &admin_b, &column_b, "Lives in the other workspace").await;
4100 let answer = app_b
4101 .post_multipart(
4102 "/files",
4103 Some(&admin_b),
4104 &[("task_id", &task_b)],
4105 Some(("theirs.png", "image/png", &[0x89, 0x50, 0x4E, 0x47])),
4106 )
4107 .await;
4108 assert_eq!(answer.status, StatusCode::SEE_OTHER);
4109 let snapshot = app_b
4110 .post("/api/fetch_task", Some(&admin_b), &[("task_id", &task_b)])
4111 .await;
4112 let file_id = attachment_id_named(&snapshot.body, "theirs.png");
4113
4114 let answer = app_a
4115 .get(&format!("/files/{file_id}"), Some(&admin_a))
4116 .await;
4117 assert_eq!(answer.status, StatusCode::NOT_FOUND);
4118}
4119
4120#[tokio::test]
4121async fn an_upload_without_a_file_is_refused() {
4122 let app = App::open().await;
4123 let admin_cookie = admin(&app).await;
4124 let column = first_column(&app).await;
4125 let task = a_task(&app, &admin_cookie, &column, "Nothing was chosen").await;
4126
4127 let answer = app
4128 .post_multipart("/files", Some(&admin_cookie), &[("task_id", &task)], None)
4129 .await;
4130 assert_eq!(answer.status, StatusCode::SEE_OTHER);
4131 assert_eq!(
4132 answer.location.as_deref(),
4133 Some(format!("/?task={task}&tab=files&refusal=no-file&on=upload_file").as_str())
4134 );
4135}
4136
4137#[tokio::test]
4138async fn only_the_uploader_or_an_admin_may_delete_a_file() {
4139 let app = App::open().await;
4140 let admin_cookie = admin(&app).await;
4141 let member_a = invited(&app, &admin_cookie, "asha@iz.sh", "Asha", Role::Member).await;
4142 let member_b = invited(&app, &admin_cookie, "beau@iz.sh", "Beau", Role::Member).await;
4143 let column = first_column(&app).await;
4144 let task = a_task(&app, &admin_cookie, &column, "Two uploaders, one task").await;
4145
4146 let answer = app
4147 .post_multipart(
4148 "/files",
4149 Some(&member_a),
4150 &[("task_id", &task)],
4151 Some(("mine.png", "image/png", &[0x89, 0x50, 0x4E, 0x47])),
4152 )
4153 .await;
4154 assert_eq!(answer.status, StatusCode::SEE_OTHER);
4155 let answer = app
4156 .post_multipart(
4157 "/files",
4158 Some(&member_b),
4159 &[("task_id", &task)],
4160 Some(("theirs.png", "image/png", &[0x89, 0x50, 0x4E, 0x47])),
4161 )
4162 .await;
4163 assert_eq!(answer.status, StatusCode::SEE_OTHER);
4164
4165 let snapshot = app
4166 .post(
4167 "/api/fetch_task",
4168 Some(&admin_cookie),
4169 &[("task_id", &task)],
4170 )
4171 .await;
4172 let file_a = attachment_id_named(&snapshot.body, "mine.png");
4173 let file_b = attachment_id_named(&snapshot.body, "theirs.png");
4174
4175 let answer = app
4176 .post("/api/delete_file", Some(&member_b), &[("file_id", &file_a)])
4177 .await;
4178 assert_eq!(answer.body, "\"Forbidden\"", "{}", answer.body);
4179
4180 let answer = app
4181 .post("/api/delete_file", Some(&member_a), &[("file_id", &file_a)])
4182 .await;
4183 assert_eq!(
4184 answer.body, "null",
4185 "the uploader was refused: {}",
4186 answer.body
4187 );
4188
4189 let answer = app
4190 .post(
4191 "/api/delete_file",
4192 Some(&admin_cookie),
4193 &[("file_id", &file_b)],
4194 )
4195 .await;
4196 assert_eq!(
4197 answer.body, "null",
4198 "the admin was refused: {}",
4199 answer.body
4200 );
4201
4202 let snapshot = app
4203 .post(
4204 "/api/fetch_task",
4205 Some(&admin_cookie),
4206 &[("task_id", &task)],
4207 )
4208 .await;
4209 assert!(snapshot.body.contains("\"files\":[]"), "{}", snapshot.body);
4210}
4211
4212// ---------------------------------------------------------------------------
4213// Logs
4214// ---------------------------------------------------------------------------
4215
4216/// The id of the assignable person on a task whose display name matches.
4217async fn person_id(app: &App, cookie: &str, task_id: &str, name: &str) -> String {
4218 let answer = app
4219 .post("/api/fetch_task", Some(cookie), &[("task_id", task_id)])
4220 .await;
4221 let needle = format!("\"display_name\":\"{name}\"");
4222 let before = answer
4223 .body
4224 .split_once(&needle)
4225 .map(|(head, _)| head)
4226 .unwrap_or_else(|| panic!("no such person in {}", answer.body));
4227 before
4228 .rsplit_once("\"id\":\"")
4229 .and_then(|(_, rest)| rest.split('"').next())
4230 .expect("no id before the display name")
4231 .to_string()
4232}
4233
4234/// Reads the admin's logs until the snapshot contains `needle`, since the
4235/// engine runs off the request in a spawned task. Bounded so a snapshot that
4236/// never arrives fails the test instead of hanging it.
4237async fn until_logs_contains(app: &App, admin: &str, needle: &str) -> String {
4238 for _ in 0..100 {
4239 let answer = app.post("/api/current_logs", Some(admin), &[]).await;
4240 if answer.body.contains(needle) {
4241 return answer.body;
4242 }
4243 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
4244 }
4245 panic!("the logs never showed {needle:?}");
4246}
4247
4248#[tokio::test]
4249async fn only_an_admin_may_read_the_logs() {
4250 let app = App::open().await;
4251 let admin_cookie = admin(&app).await;
4252 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
4253 let viewer = invited(&app, &admin_cookie, "pinar@iz.sh", "Pinar", Role::Viewer).await;
4254
4255 for who in [&member, &viewer] {
4256 let read = app.post("/api/current_logs", Some(who), &[]).await;
4257 assert!(read.body.contains("Forbidden"), "{}", read.body);
4258 }
4259
4260 let out = app.post("/api/current_logs", None, &[]).await;
4261 assert!(out.body.contains("SignInFirst"), "{}", out.body);
4262}
4263
4264#[tokio::test]
4265async fn an_admin_reads_the_logs() {
4266 let app = App::open_with_mail().await;
4267 let admin_cookie = admin(&app).await;
4268 let mate = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
4269 let columns = columns_of(&app).await;
4270 let task = a_task(&app, &admin_cookie, &columns[0], "Ship it").await;
4271 let mate_id = person_id(&app, &admin_cookie, &task, "Emre").await;
4272
4273 let assigned = app
4274 .post(
4275 "/api/assign",
4276 Some(&admin_cookie),
4277 &[("task_id", &task), ("user_id", &mate_id)],
4278 )
4279 .await;
4280 assert_eq!(assigned.body, "null", "{}", assigned.body);
4281 assert!(rule_written(&app, &admin_cookie, &columns[1], "Task completed").await);
4282 // No batch window: the rule's send falls due the moment it is owed, so
4283 // the engine attempts it right away instead of holding it pending.
4284 let limits = app
4285 .post(
4286 "/api/save_limits",
4287 Some(&admin_cookie),
4288 &[
4289 ("attachment_limit_mb", "10"),
4290 ("allowed_file_types", ""),
4291 ("mail_batch_minutes", "0"),
4292 ],
4293 )
4294 .await;
4295 assert!(
4296 limits
4297 .location
4298 .as_deref()
4299 .unwrap_or_default()
4300 .contains("saved=save_limits"),
4301 "{:?}",
4302 limits.location
4303 );
4304
4305 // Emre is the only assignee and Emre moves the card himself: the rule
4306 // owes him the mail all the same. With no sender configured the send is
4307 // not a failure — it waits in the queue, held with nothing spent.
4308 let moved = app
4309 .post(
4310 "/api/move_card",
4311 Some(&mate),
4312 &[
4313 ("task_id", &task),
4314 ("from_column_id", &columns[0]),
4315 ("to_column_id", &columns[1]),
4316 ],
4317 )
4318 .await;
4319 assert_eq!(moved.body, "");
4320
4321 // The queue row shows up claimed-but-unattempted first; poll for the
4322 // settled "held" verdict instead of the subject alone, or the first
4323 // sighting catches the send mid-attempt.
4324 let snapshot = until_logs_contains(&app, &admin_cookie, "\"state_kind\":\"held\"").await;
4325 assert!(
4326 snapshot.contains("\"subject\":\"Task completed\""),
4327 "{}",
4328 snapshot
4329 );
4330 assert!(
4331 snapshot.contains("\"recipient\":\"emre@iz.sh\""),
4332 "{}",
4333 snapshot
4334 );
4335 assert!(snapshot.contains("\"attempts\":0"), "{}", snapshot);
4336}
4337
4338/// The `"at"` field of the activity row whose `"title"` matches, read out of
4339/// a `/api/current_logs` body the way `person_id` reads an id.
4340fn moment_for(body: &str, title: &str) -> String {
4341 let needle = format!("\"title\":\"{title}\"");
4342 let before = body
4343 .split_once(&needle)
4344 .map(|(head, _)| head)
4345 .unwrap_or_else(|| panic!("no such title in {body}"));
4346 before
4347 .rsplit_once("\"at\":\"")
4348 .and_then(|(_, rest)| rest.split('"').next())
4349 .expect("no at before the title")
4350 .to_string()
4351}
4352
4353/// The hour out of a `moment_label`-shaped stamp like `"Aug 19 11:04:07"`.
4354fn hour_of(moment: &str) -> u32 {
4355 moment
4356 .rsplit(' ')
4357 .next()
4358 .and_then(|hm| hm.split(':').next())
4359 .and_then(|h| h.parse().ok())
4360 .unwrap_or_else(|| panic!("not a moment: {moment}"))
4361}
4362
4363#[tokio::test]
4364async fn a_stamp_shifts_with_the_viewers_stored_timezone() {
4365 let app = App::open().await;
4366 let admin_cookie = admin(&app).await;
4367 let columns = columns_of(&app).await;
4368 let _task = a_task(&app, &admin_cookie, &columns[0], "Ship it").await;
4369
4370 let utc = until_logs_contains(&app, &admin_cookie, "\"title\":\"Ship it\"").await;
4371 let utc_at = moment_for(&utc, "Ship it");
4372
4373 app.store
4374 .sync_member("im-ada", "ada@iz.sh", "Ada Lovelace", true, 0, "UTC+03:00")
4375 .await
4376 .unwrap();
4377
4378 let shifted = app
4379 .post("/api/current_logs", Some(&admin_cookie), &[])
4380 .await;
4381 let shifted_at = moment_for(&shifted.body, "Ship it");
4382
4383 assert_ne!(utc_at, shifted_at, "utc={utc_at} shifted={shifted_at}");
4384 assert_eq!(
4385 hour_of(&shifted_at),
4386 (hour_of(&utc_at) + 3) % 24,
4387 "utc={utc_at} shifted={shifted_at}"
4388 );
4389}
4390
4391/// The first `activity-stamp` span's text out of a task modal's HTML — the
4392/// same shape `moment_for` reads out of a `/api/current_logs` body.
4393fn activity_stamp_of(html: &str) -> &str {
4394 let (_, rest) = html
4395 .split_once(r#"class="activity-stamp">"#)
4396 .unwrap_or_else(|| panic!("no activity stamp in {html}"));
4397 rest.split_once('<')
4398 .map(|(stamp, _)| stamp)
4399 .expect("unterminated activity stamp")
4400}
4401
4402#[tokio::test]
4403async fn a_task_modal_stamp_shifts_with_the_viewers_stored_timezone() {
4404 let app = App::open().await;
4405 let admin_cookie = admin(&app).await;
4406 let column = first_column(&app).await;
4407 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
4408
4409 // Activity lives behind its own tab now, so the stamp is asked for there.
4410 let page = app
4411 .get(&format!("/?task={task}&tab=activity"), Some(&admin_cookie))
4412 .await;
4413 let html = String::from_utf8_lossy(&page.bytes);
4414 let utc_at = activity_stamp_of(&html).to_string();
4415
4416 app.store
4417 .sync_member("im-ada", "ada@iz.sh", "Ada Lovelace", true, 0, "UTC+03:00")
4418 .await
4419 .unwrap();
4420
4421 let shifted_page = app
4422 .get(&format!("/?task={task}&tab=activity"), Some(&admin_cookie))
4423 .await;
4424 let shifted_html = String::from_utf8_lossy(&shifted_page.bytes);
4425 let shifted_at = activity_stamp_of(&shifted_html).to_string();
4426
4427 assert_ne!(utc_at, shifted_at, "utc={utc_at} shifted={shifted_at}");
4428 assert_eq!(
4429 hour_of(&shifted_at),
4430 (hour_of(&utc_at) + 3) % 24,
4431 "utc={utc_at} shifted={shifted_at}"
4432 );
4433}
4434
4435#[tokio::test]
4436async fn a_posted_timezone_is_ignored() {
4437 let app = App::open().await;
4438 let admin_cookie = admin(&app).await;
4439
4440 // im owns the timezone now: a posted one — even an unlisted one — is
4441 // not read, let alone refused or saved. The row keeps the value the
4442 // directory last mirrored while the fields iz owns still save.
4443 let answer = app
4444 .post(
4445 "/api/save_profile",
4446 Some(&admin_cookie),
4447 &[
4448 ("timezone", "Mars/Olympus_Mons"),
4449 ("theme", "dark"),
4450 ("language", "en"),
4451 ("ui", "instrument"),
4452 ],
4453 )
4454 .await;
4455 assert!(
4456 !answer
4457 .location
4458 .as_deref()
4459 .unwrap_or_default()
4460 .contains("refusal="),
4461 "{:?}",
4462 answer.location
4463 );
4464 let admin_id = user_id(&app, "ada@iz.sh").await;
4465 let row = app.store.user(&admin_id).await.unwrap().unwrap();
4466 assert_eq!(row.timezone, "UTC");
4467 assert_eq!(row.theme, "dark");
4468}
4469
4470#[tokio::test]
4471async fn the_dark_theme_is_saved_and_marks_the_page() {
4472 let app = App::open().await;
4473 let admin_cookie = admin(&app).await;
4474
4475 let saved = app
4476 .post(
4477 "/api/save_profile",
4478 Some(&admin_cookie),
4479 &[
4480 ("timezone", "UTC"),
4481 ("theme", "dark"),
4482 ("language", "en"),
4483 ("ui", "instrument"),
4484 ],
4485 )
4486 .await;
4487 assert!(
4488 !saved
4489 .location
4490 .as_deref()
4491 .unwrap_or_default()
4492 .contains("refusal="),
4493 "{:?}",
4494 saved.location
4495 );
4496
4497 let page = app.get("/settings", Some(&admin_cookie)).await;
4498 let html = String::from_utf8_lossy(&page.bytes);
4499 assert!(html.contains(r#"data-theme="dark""#), "{html}");
4500}
4501
4502#[tokio::test]
4503async fn turkish_is_saved_and_the_board_renders_in_turkish() {
4504 let app = App::open().await;
4505 let admin_cookie = admin(&app).await;
4506
4507 let saved = app
4508 .post(
4509 "/api/save_profile",
4510 Some(&admin_cookie),
4511 &[
4512 ("timezone", "UTC"),
4513 ("theme", "light"),
4514 ("language", "tr"),
4515 ("ui", "instrument"),
4516 ],
4517 )
4518 .await;
4519 assert!(
4520 !saved
4521 .location
4522 .as_deref()
4523 .unwrap_or_default()
4524 .contains("refusal="),
4525 "{:?}",
4526 saved.location
4527 );
4528
4529 let page = app.get("/", Some(&admin_cookie)).await;
4530 let html = String::from_utf8_lossy(&page.bytes);
4531 assert!(html.contains(r#"<html lang="tr""#), "{html}");
4532 assert!(html.contains("Ayarlar"), "{html}");
4533
4534 let settings_page = app.get("/settings", Some(&admin_cookie)).await;
4535 let settings_html = String::from_utf8_lossy(&settings_page.bytes);
4536 assert!(settings_html.contains("Profilin"), "{settings_html}");
4537
4538 let rules_page = app.get("/rules", Some(&admin_cookie)).await;
4539 let rules_html = String::from_utf8_lossy(&rules_page.bytes);
4540 assert!(rules_html.contains("Posta kuralları"), "{rules_html}");
4541}
4542
4543#[tokio::test]
4544async fn an_unlisted_language_is_refused() {
4545 let app = App::open().await;
4546 let admin_cookie = admin(&app).await;
4547
4548 let saved = app
4549 .post(
4550 "/api/save_profile",
4551 Some(&admin_cookie),
4552 &[
4553 ("timezone", "UTC"),
4554 ("theme", "light"),
4555 ("language", "fr"),
4556 ("ui", "instrument"),
4557 ],
4558 )
4559 .await;
4560 assert_eq!(
4561 saved.location.as_deref(),
4562 Some("/settings?refusal=bad-language&on=save_profile&section=profile")
4563 );
4564}
4565
4566#[tokio::test]
4567async fn an_unlisted_theme_is_refused() {
4568 let app = App::open().await;
4569 let admin_cookie = admin(&app).await;
4570
4571 let answer = app
4572 .post(
4573 "/api/save_profile",
4574 Some(&admin_cookie),
4575 &[
4576 ("timezone", "UTC"),
4577 ("theme", "neon"),
4578 ("language", "en"),
4579 ("ui", "instrument"),
4580 ],
4581 )
4582 .await;
4583 let location = answer.location.as_deref().unwrap_or_default();
4584 assert!(
4585 location.contains("refusal=bad-theme&on=save_profile"),
4586 "{location}"
4587 );
4588}
4589
4590#[tokio::test]
4591async fn the_ledger_ui_is_saved_and_marks_the_page() {
4592 let app = App::open().await;
4593 let admin_cookie = admin(&app).await;
4594
4595 let saved = app
4596 .post(
4597 "/api/save_profile",
4598 Some(&admin_cookie),
4599 &[
4600 ("timezone", "UTC"),
4601 ("theme", "light"),
4602 ("language", "en"),
4603 ("ui", "ledger"),
4604 ],
4605 )
4606 .await;
4607 assert!(
4608 !saved
4609 .location
4610 .as_deref()
4611 .unwrap_or_default()
4612 .contains("refusal="),
4613 "{:?}",
4614 saved.location
4615 );
4616
4617 let page = app.get("/settings", Some(&admin_cookie)).await;
4618 let html = String::from_utf8_lossy(&page.bytes);
4619 assert!(html.contains(r#"data-ui="ledger""#), "{html}");
4620}
4621
4622#[tokio::test]
4623async fn an_unlisted_ui_is_refused() {
4624 let app = App::open().await;
4625 let admin_cookie = admin(&app).await;
4626
4627 let answer = app
4628 .post(
4629 "/api/save_profile",
4630 Some(&admin_cookie),
4631 &[
4632 ("timezone", "UTC"),
4633 ("theme", "light"),
4634 ("language", "en"),
4635 ("ui", "neon"),
4636 ],
4637 )
4638 .await;
4639 let location = answer.location.as_deref().unwrap_or_default();
4640 assert!(
4641 location.contains("refusal=bad-ui&on=save_profile"),
4642 "{location}"
4643 );
4644
4645 let page = app.get("/settings", Some(&admin_cookie)).await;
4646 let html = String::from_utf8_lossy(&page.bytes);
4647 assert!(html.contains(r#"data-ui="instrument""#), "{html}");
4648}
4649
4650/// Creating a task files its own Created activity, but the column it lands
4651/// in also fires a `Transition` the way a drop does — a `StatusBecomes` rule
4652/// armed on that column must owe mail on creation, not only on a later move.
4653#[tokio::test]
4654async fn creating_a_task_into_a_ruled_column_owes_mail() {
4655 let app = App::open_with_mail().await;
4656 let admin_cookie = admin(&app).await;
4657 let member = invited(&app, &admin_cookie, "deniz@iz.sh", "Deniz", Role::Member).await;
4658 let column = first_column(&app).await;
4659
4660 let written = app
4661 .post(
4662 "/api/create_rule",
4663 Some(&admin_cookie),
4664 &[
4665 ("trigger", "status"),
4666 ("column_id", &column),
4667 ("subject", "New card"),
4668 ("audience", "board"),
4669 ],
4670 )
4671 .await;
4672 assert_eq!(written.body, "null", "{}", written.body);
4673 let rule = only_rule(&app, &admin_cookie).await;
4674
4675 // Deniz creates the card; the board audience is everyone who can write
4676 // on it, so both the admin and Deniz himself are owed a mail.
4677 let created = app
4678 .post(
4679 "/api/create_task",
4680 Some(&member),
4681 &[("title", "Ship it"), ("column_id", &column)],
4682 )
4683 .await;
4684 assert_eq!(created.body, "", "the task was refused: {}", created.body);
4685
4686 let send = until_rule_send_to(&app, &rule, "ada@iz.sh", 0).await;
4687 assert_eq!(send.recipient, "ada@iz.sh");
4688 let own = until_rule_send_to(&app, &rule, "deniz@iz.sh", 0).await;
4689 assert_eq!(own.recipient, "deniz@iz.sh");
4690}
4691
4692#[tokio::test]
4693async fn the_topbar_nav_marks_the_active_page() {
4694 let app = App::open().await;
4695 let admin_cookie = admin(&app).await;
4696
4697 for (path, active) in [
4698 ("/", "/"),
4699 ("/rules", "/rules"),
4700 ("/logs", "/logs"),
4701 ("/settings", "/settings"),
4702 ] {
4703 let page = app.get(path, Some(&admin_cookie)).await;
4704 assert_eq!(page.status, StatusCode::OK);
4705 let html = String::from_utf8_lossy(&page.bytes);
4706 for nav in ["/", "/rules", "/logs", "/settings"] {
4707 let expected = if nav == active {
4708 format!(r#"class="topbar-nav topbar-nav-on" href="{nav}""#)
4709 } else {
4710 format!(r#"class="topbar-nav" href="{nav}""#)
4711 };
4712 assert!(
4713 html.contains(&expected),
4714 "page {path} lacks `{expected}`: {html}"
4715 );
4716 }
4717 }
4718
4719 // The settings rail keeps the panels' admin gating: a member sees only
4720 // the Profile link, and an admin-only section in the query still renders
4721 // Profile rather than the panel it asked for.
4722 let member = invited(&app, &admin_cookie, "deniz@iz.sh", "Deniz", Role::Member).await;
4723 let page = app.get("/settings", Some(&member)).await;
4724 let html = String::from_utf8_lossy(&page.bytes);
4725 assert!(
4726 html.contains(r#"href="/settings?section=profile""#),
4727 "{html}"
4728 );
4729 assert!(
4730 !html.contains("href=\"/settings?section=limits\""),
4731 "{html}"
4732 );
4733 assert!(
4734 !html.contains("href=\"/settings?section=members\""),
4735 "{html}"
4736 );
4737 assert!(html.contains(r#"id="profile""#), "{html}");
4738 assert!(!html.contains(r#"id="limits""#), "{html}");
4739
4740 let page = app.get("/settings?section=limits", Some(&member)).await;
4741 let html = String::from_utf8_lossy(&page.bytes);
4742 assert!(html.contains(r#"id="profile""#), "{html}");
4743 assert!(!html.contains(r#"id="limits""#), "{html}");
4744}
4745
4746// ---------------------------------------------------------------------------
4747// SSO identity: provisioning, roles from im, and the sign-in card
4748// ---------------------------------------------------------------------------
4749
4750/// The first SSO login provisions a member by default — open provisioning,
4751/// no invite needed. Catches a provision that defaults to viewer (or admin).
4752#[tokio::test]
4753async fn a_first_sso_login_provisions_a_member() {
4754 let app = App::open().await;
4755 let cookie = app.mint("im-new", "new@iz.sh", "New Person", false);
4756
4757 let page = app.get("/", Some(&cookie)).await;
4758 assert_eq!(page.status, StatusCode::OK);
4759 let html = String::from_utf8_lossy(&page.bytes);
4760 assert!(html.contains("board-stage"), "{html}");
4761
4762 let user = app
4763 .store
4764 .user_by_email(&app.workspace_id().await, "new@iz.sh")
4765 .await
4766 .unwrap()
4767 .expect("no local row after the first login");
4768 assert_eq!(user.role, Role::Member, "a first login was not a member");
4769 assert_eq!(user.oidc_sub.as_deref(), Some("im-new"));
4770}
4771
4772/// im's admin flag makes the local admin. Catches a provision that ignores
4773/// the flag — every im admin would land a member with no way up.
4774#[tokio::test]
4775async fn the_im_admin_flag_makes_an_admin() {
4776 let app = App::open().await;
4777 let cookie = app.mint("im-boss", "boss@iz.sh", "Boss", true);
4778
4779 // A role-gated route is the proof, not the row alone: only an admin's
4780 // board carries the admin surfaces.
4781 let page = app.get("/", Some(&cookie)).await;
4782 let html = String::from_utf8_lossy(&page.bytes);
4783 assert!(html.contains("href=\"/rules\""), "{html}");
4784
4785 let user = app
4786 .store
4787 .user_by_email(&app.workspace_id().await, "boss@iz.sh")
4788 .await
4789 .unwrap()
4790 .expect("no local row after the first login");
4791 assert_eq!(
4792 user.role,
4793 Role::Admin,
4794 "the im admin flag did not make an admin"
4795 );
4796}
4797
4798/// A first SSO login claims the legacy row by address: the `sub` is stamped
4799/// onto it, keeping its id and its role. Catches a provision that inserts a
4800/// second row and strands the person's history on the old one.
4801#[tokio::test]
4802async fn a_first_sso_login_claims_the_legacy_row_by_address() {
4803 let app = App::open().await;
4804 let legacy = app
4805 .store
4806 .provision_user("im-old", "ada@iz.sh", "Ada Lovelace", false)
4807 .await
4808 .unwrap();
4809 app.store.set_role(&legacy.id, Role::Viewer).await.unwrap();
4810
4811 let cookie = app.mint("im-new", "ada@iz.sh", "Ada Lovelace", false);
4812 let page = app.get("/", Some(&cookie)).await;
4813 assert_eq!(page.status, StatusCode::OK);
4814
4815 let claimed = app
4816 .store
4817 .user_by_email(&app.workspace_id().await, "ada@iz.sh")
4818 .await
4819 .unwrap()
4820 .expect("the address has no row after claiming");
4821 assert_eq!(
4822 claimed.id, legacy.id,
4823 "the login did not claim the legacy row"
4824 );
4825 assert_eq!(
4826 claimed.role,
4827 Role::Viewer,
4828 "claiming did not preserve the role"
4829 );
4830 assert_eq!(claimed.oidc_sub.as_deref(), Some("im-new"));
4831}
4832
4833/// A disabled member reads as signed out everywhere: the board is gone and a
4834/// mutation is refused as if there were no session. Catches a guard that
4835/// checks the cookie but not the flag.
4836#[tokio::test]
4837async fn a_disabled_member_reads_as_signed_out() {
4838 let app = App::open().await;
4839 let admin_cookie = admin(&app).await;
4840 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
4841 let member_id = user_id(&app, "emre@iz.sh").await;
4842 app.store.set_user_disabled(&member_id, true).await.unwrap();
4843
4844 let page = app.get("/", Some(&member)).await;
4845 let html = String::from_utf8_lossy(&page.bytes);
4846 assert!(
4847 !html.contains("board-stage"),
4848 "a disabled member was shown the board: {html}"
4849 );
4850 assert!(html.contains("/auth/login"), "{html}");
4851
4852 let column = first_column(&app).await;
4853 let answer = app
4854 .post(
4855 "/api/create_task",
4856 Some(&member),
4857 &[("title", "Ghost task"), ("column_id", &column)],
4858 )
4859 .await;
4860 assert!(
4861 answer
4862 .location
4863 .as_deref()
4864 .unwrap_or_default()
4865 .contains("refusal=sign-in-first&on=create_task"),
4866 "{:?}",
4867 answer.location
4868 );
4869}
4870
4871/// Disabling yourself is refused — the workspace must never be left with no
4872/// way back in through its only admin. Catches a missing self-check.
4873#[tokio::test]
4874async fn an_admin_cannot_disable_their_own_sign_in() {
4875 let app = App::open().await;
4876 let admin_cookie = admin(&app).await;
4877 let admin_id = user_id(&app, "ada@iz.sh").await;
4878
4879 let answer = app
4880 .post(
4881 "/api/set_disabled",
4882 Some(&admin_cookie),
4883 &[("user_id", &admin_id)],
4884 )
4885 .await;
4886 assert!(
4887 answer
4888 .location
4889 .as_deref()
4890 .unwrap_or_default()
4891 .contains("refusal=forbidden&on=set_disabled"),
4892 "{:?}",
4893 answer.location
4894 );
4895
4896 let page = app.get("/", Some(&admin_cookie)).await;
4897 let html = String::from_utf8_lossy(&page.bytes);
4898 assert!(html.contains("board-stage"), "{html}");
4899}
4900
4901/// `set_role` can move between member and viewer only: admin comes from im,
4902/// never from this route. Catches a role write that trusts the form.
4903#[tokio::test]
4904async fn set_role_cannot_make_an_admin() {
4905 let app = App::open().await;
4906 let admin_cookie = admin(&app).await;
4907 let _ = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
4908 let member_id = user_id(&app, "emre@iz.sh").await;
4909
4910 let answer = app
4911 .post(
4912 "/api/set_role",
4913 Some(&admin_cookie),
4914 &[("user_id", &member_id), ("role", "admin")],
4915 )
4916 .await;
4917 assert!(
4918 answer
4919 .location
4920 .as_deref()
4921 .unwrap_or_default()
4922 .contains("refusal=forbidden&on=set_role"),
4923 "{:?}",
4924 answer.location
4925 );
4926
4927 let reloaded = app.store.user(&member_id).await.unwrap().unwrap();
4928 assert_eq!(reloaded.role, Role::Member, "set_role made an admin anyway");
4929}
4930
4931/// An admin may add a member who has never signed in, and the row is a
4932/// member like any other: a task can be assigned to it straight away.
4933/// Catches a members table that only knows rows SSO wrote.
4934#[tokio::test]
4935async fn an_admin_may_add_a_member_before_their_first_sign_in() {
4936 let app = App::open().await;
4937 let admin_cookie = admin(&app).await;
4938
4939 let answer = app
4940 .post(
4941 "/api/add_member",
4942 Some(&admin_cookie),
4943 &[
4944 ("display_name", "Mert"),
4945 ("email", "mert@iz.sh"),
4946 ("role", "member"),
4947 ],
4948 )
4949 .await;
4950 assert!(
4951 answer
4952 .location
4953 .as_deref()
4954 .unwrap_or_default()
4955 .contains("saved=add_member"),
4956 "{:?}",
4957 answer.location
4958 );
4959
4960 let member_id = user_id(&app, "mert@iz.sh").await;
4961 let row = app.store.user(&member_id).await.unwrap().unwrap();
4962 assert_eq!(row.oidc_sub, None, "an unclaimed row carries no sub");
4963 assert_eq!(row.role, Role::Member);
4964
4965 let column = first_column(&app).await;
4966 let task = a_task(&app, &admin_cookie, &column, "Onboard Mert").await;
4967 app.store.assign_task(&task, &member_id).await.unwrap();
4968}
4969
4970/// A member the directory beat mirrored — born linked, never signed in —
4971/// is a member like any other: in the picker list and assignable straight
4972/// away. Catches a sync that writes rows the board cannot see.
4973#[tokio::test]
4974async fn a_synced_member_is_listed_and_assignable_before_their_first_sign_in() {
4975 let app = App::open().await;
4976 let admin_cookie = admin(&app).await;
4977 let admin_row = app
4978 .store
4979 .user(&user_id(&app, "ada@iz.sh").await)
4980 .await
4981 .unwrap()
4982 .unwrap();
4983
4984 let sync = app
4985 .store
4986 .sync_member("sub-mert", "mert@iz.sh", "Mert", false, 0, "UTC+03:00")
4987 .await
4988 .unwrap();
4989 assert_eq!(sync, iz_core::store::MemberSync::Inserted);
4990
4991 let member_id = user_id(&app, "mert@iz.sh").await;
4992 let row = app.store.user(&member_id).await.unwrap().unwrap();
4993 assert_eq!(row.oidc_sub.as_deref(), Some("sub-mert"));
4994 assert!(row.last_signed_in_at.is_none());
4995
4996 let listed = app.store.users(&admin_row.workspace_id).await.unwrap();
4997 assert!(
4998 listed.iter().any(|user| user.id == member_id),
4999 "the picker's source does not list the synced member"
5000 );
5001
5002 let column = first_column(&app).await;
5003 let task = a_task(&app, &admin_cookie, &column, "Onboard Mert").await;
5004 app.store.assign_task(&task, &member_id).await.unwrap();
5005}
5006
5007/// A member who posts to the add route anyway is refused, and no row is
5008/// written. Catches a handler that trusts the form's being hidden.
5009#[tokio::test]
5010async fn a_non_admin_may_not_add_members_over_http() {
5011 let app = App::open().await;
5012 let admin_cookie = admin(&app).await;
5013 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
5014
5015 let answer = app
5016 .post(
5017 "/api/add_member",
5018 Some(&member),
5019 &[
5020 ("display_name", "Mert"),
5021 ("email", "mert@iz.sh"),
5022 ("role", "member"),
5023 ],
5024 )
5025 .await;
5026 assert!(
5027 answer
5028 .location
5029 .as_deref()
5030 .unwrap_or_default()
5031 .contains("refusal=forbidden&on=add_member"),
5032 "{:?}",
5033 answer.location
5034 );
5035
5036 let workspace_id = app.workspace_id().await;
5037 assert!(
5038 app.store
5039 .user_by_email(&workspace_id, "mert@iz.sh")
5040 .await
5041 .unwrap()
5042 .is_none(),
5043 "a refused add wrote its row anyway"
5044 );
5045}
5046
5047/// The second add of an address is refused, however it is cased. Catches a
5048/// duplicate check that compares what was typed instead of what was folded.
5049#[tokio::test]
5050async fn adding_the_same_address_twice_is_refused_over_http() {
5051 let app = App::open().await;
5052 let admin_cookie = admin(&app).await;
5053
5054 let first = app
5055 .post(
5056 "/api/add_member",
5057 Some(&admin_cookie),
5058 &[
5059 ("display_name", "Mert"),
5060 ("email", "mert@iz.sh"),
5061 ("role", "member"),
5062 ],
5063 )
5064 .await;
5065 assert_eq!(first.status, StatusCode::SEE_OTHER);
5066
5067 let answer = app
5068 .post(
5069 "/api/add_member",
5070 Some(&admin_cookie),
5071 &[
5072 ("display_name", "Mert Again"),
5073 ("email", "MERT@iz.sh"),
5074 ("role", "viewer"),
5075 ],
5076 )
5077 .await;
5078 assert!(
5079 answer
5080 .location
5081 .as_deref()
5082 .unwrap_or_default()
5083 .contains("refusal=already-member&on=add_member"),
5084 "{:?}",
5085 answer.location
5086 );
5087}
5088
5089/// `add_member` writes member or viewer only: admin comes from im, never
5090/// from this route. Catches an add that trusts the form's role value.
5091#[tokio::test]
5092async fn add_member_cannot_make_an_admin() {
5093 let app = App::open().await;
5094 let admin_cookie = admin(&app).await;
5095
5096 let answer = app
5097 .post(
5098 "/api/add_member",
5099 Some(&admin_cookie),
5100 &[
5101 ("display_name", "Boss"),
5102 ("email", "boss@iz.sh"),
5103 ("role", "admin"),
5104 ],
5105 )
5106 .await;
5107 assert!(
5108 answer
5109 .location
5110 .as_deref()
5111 .unwrap_or_default()
5112 .contains("refusal=forbidden&on=add_member"),
5113 "{:?}",
5114 answer.location
5115 );
5116
5117 let workspace_id = app.workspace_id().await;
5118 assert!(
5119 app.store
5120 .user_by_email(&workspace_id, "boss@iz.sh")
5121 .await
5122 .unwrap()
5123 .is_none(),
5124 "a refused add wrote its row anyway"
5125 );
5126}
5127
5128/// Losing im's admin flag drops the role to member on the very next request.
5129/// Catches a provision that grants admin once and never syncs it back down —
5130/// a demoted admin would keep administering forever.
5131#[tokio::test]
5132async fn losing_the_im_admin_flag_drops_the_role_to_member() {
5133 let app = App::open().await;
5134 let token = format!("tok-{}", Ulid::generate());
5135 let exp = time::OffsetDateTime::now_utc() + time::Duration::hours(1);
5136 app.fake.tokens.lock().insert(
5137 token.clone(),
5138 serde_json::json!({
5139 "active": true,
5140 "sub": "im-fickle",
5141 "email": "fickle@iz.sh",
5142 "name": "Fickle",
5143 "admin": true,
5144 "exp": exp.unix_timestamp(),
5145 }),
5146 );
5147 let cookie = iz_client::mint_session_cookie(&app.client, &token, exp);
5148
5149 let page = app.get("/", Some(&cookie)).await;
5150 assert!(String::from_utf8_lossy(&page.bytes).contains("href=\"/rules\""));
5151
5152 // im demotes them; the next request syncs the role down.
5153 app.fake.tokens.lock().insert(
5154 token.clone(),
5155 serde_json::json!({
5156 "active": true,
5157 "sub": "im-fickle",
5158 "email": "fickle@iz.sh",
5159 "name": "Fickle",
5160 "admin": false,
5161 "exp": exp.unix_timestamp(),
5162 }),
5163 );
5164 let answer = app.post("/api/current_rules", Some(&cookie), &[]).await;
5165 assert!(
5166 answer.body.contains("Forbidden"),
5167 "a demoted admin still reads the rules: {}",
5168 answer.body
5169 );
5170 let user = app
5171 .store
5172 .user_by_email(&app.workspace_id().await, "fickle@iz.sh")
5173 .await
5174 .unwrap()
5175 .expect("no local row");
5176 assert_eq!(user.role, Role::Member, "the demotion did not sync down");
5177}
5178
5179/// Signed out, `/` is the sign-in card: one link starting the OIDC
5180/// round-trip, and a failed round-trip names the one-line fact. Catches a
5181/// landing that leaks the board, or swallows the failure it was told about.
5182#[tokio::test]
5183async fn the_sign_in_card_links_the_login_and_names_a_failed_round_trip() {
5184 let app = App::open().await;
5185 let _ = admin(&app).await;
5186
5187 let plain = app.get("/", None).await;
5188 assert_eq!(plain.status, StatusCode::OK);
5189 let html = String::from_utf8_lossy(&plain.bytes);
5190 assert!(html.contains("href=\"/auth/login\""), "{html}");
5191 assert!(!html.contains("board-stage"), "{html}");
5192
5193 let failed = app.get("/?auth_error=1", None).await;
5194 assert_eq!(failed.status, StatusCode::OK);
5195 let html = String::from_utf8_lossy(&failed.bytes);
5196 assert!(html.contains("href=\"/auth/login\""), "{html}");
5197 assert!(html.contains("auth-problem"), "{html}");
5198}
5199
5200// ---------------------------------------------------------------------------
5201// Avatar: the signed-in person's face, proxied from im
5202// ---------------------------------------------------------------------------
5203
5204/// A member's avatar proxies im's photo bytes with the app's credential.
5205/// Catches a proxy that drops the auth or mangles the bytes, and pins the
5206/// versioned caching: the row's `photo_version` is the ETag and the `?v=`
5207/// stamp a page renders.
5208#[tokio::test]
5209async fn a_members_avatar_proxies_the_im_photo() {
5210 let app = App::open().await;
5211 let admin = admin(&app).await;
5212 let admin_id = user_id(&app, "ada@iz.sh").await;
5213 app.fake.set_photo("im-ada", PNG.to_vec(), "image/png");
5214
5215 let photo = app.get(&format!("/avatar/{admin_id}"), Some(&admin)).await;
5216 assert_eq!(photo.status, StatusCode::OK);
5217 assert_eq!(photo.content_type.as_deref(), Some("image/png"));
5218 assert_eq!(photo.bytes, PNG);
5219 // The row has met no photo yet: version zero, and the ETag says so.
5220 assert_eq!(photo.etag.as_deref(), Some("\"p0\""));
5221 // No stamp on the URL: revalidate, never cache hard — the URL a page
5222 // renders always carries the stamp, so this is only the stray fetch.
5223 assert_eq!(photo.cache_control.as_deref(), Some("private, no-cache"));
5224
5225 let cached = app
5226 .get_with_if_none_match(&format!("/avatar/{admin_id}"), Some(&admin), "\"p0\"")
5227 .await;
5228 assert_eq!(cached.status, StatusCode::NOT_MODIFIED);
5229 assert!(cached.bytes.is_empty());
5230}
5231
5232/// The profile section renders no timezone editor: the clock is im's now,
5233/// so the form iz serves carries only the fields iz owns.
5234#[tokio::test]
5235async fn the_profile_section_has_no_timezone_editor() {
5236 let app = App::open().await;
5237 let admin = admin(&app).await;
5238
5239 let page = app.get("/settings", Some(&admin)).await;
5240 assert_eq!(page.status.as_u16(), 200);
5241 let html = String::from_utf8(page.bytes).unwrap();
5242 assert!(
5243 !html.contains("name=\"timezone\""),
5244 "a timezone select is still on the profile: {html}"
5245 );
5246 assert!(
5247 !html.contains("TIMEZONE"),
5248 "a timezone label is still on the profile: {html}"
5249 );
5250}
5251
5252/// The stamp the row carries pins the face: `?v=` agreeing with the row is
5253/// cacheable for a year because the URL itself changes when the face does,
5254/// any other spelling revalidates, and a sync that hears of a new photo
5255/// moves both the stamp and the ETag together.
5256#[tokio::test]
5257async fn a_matching_version_stamp_is_immutable_and_a_new_one_moves_it() {
5258 let app = App::open().await;
5259 let admin_cookie = admin(&app).await;
5260 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
5261 let member_id = user_id(&app, "emre@iz.sh").await;
5262 // The directory pass finds the row by its sub — the same subject the
5263 // sign-in provisions — and reports the face's third revision.
5264 app.store
5265 .sync_member("im-emre@iz.sh", "emre@iz.sh", "Emre", false, 3, "UTC+03:00")
5266 .await
5267 .unwrap();
5268 app.fake
5269 .set_photo("im-emre@iz.sh", PNG.to_vec(), "image/png");
5270
5271 let stamped = app
5272 .get(&format!("/avatar/{member_id}?v=3"), Some(&member))
5273 .await;
5274 assert_eq!(stamped.status, StatusCode::OK);
5275 assert_eq!(
5276 stamped.cache_control.as_deref(),
5277 Some("private, max-age=31536000, immutable")
5278 );
5279 assert_eq!(stamped.etag.as_deref(), Some("\"p3\""));
5280
5281 // Any other spelling — a stale stamp, junk, none — may not be pinned.
5282 for query in ["?v=2", "?v=junk", ""] {
5283 let stray = app
5284 .get(&format!("/avatar/{member_id}{query}"), Some(&member))
5285 .await;
5286 assert_eq!(stray.cache_control.as_deref(), Some("private, no-cache"));
5287 }
5288
5289 // im's count moves; the next sync (the stream's event, or the beat)
5290 // carries it onto the row, and the old stamp stops being true.
5291 app.store
5292 .sync_member("im-emre@iz.sh", "emre@iz.sh", "Emre", false, 4, "UTC+03:00")
5293 .await
5294 .unwrap();
5295 let moved = app
5296 .get(&format!("/avatar/{member_id}?v=4"), Some(&member))
5297 .await;
5298 assert_eq!(moved.etag.as_deref(), Some("\"p4\""));
5299 assert_eq!(
5300 moved.cache_control.as_deref(),
5301 Some("private, max-age=31536000, immutable")
5302 );
5303 let stale = app
5304 .get(&format!("/avatar/{member_id}?v=3"), Some(&member))
5305 .await;
5306 assert_eq!(stale.cache_control.as_deref(), Some("private, no-cache"));
5307}
5308
5309/// Any member's face serves to any signed-in member — the board shows
5310/// assignees' faces, so the bytes must be reachable — while a browser
5311/// without a session is refused outright, the way the live channel is.
5312#[tokio::test]
5313async fn another_members_avatar_serves_but_a_signed_out_browser_does_not() {
5314 let app = App::open().await;
5315 let admin_cookie = admin(&app).await;
5316 let admin_id = user_id(&app, "ada@iz.sh").await;
5317 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
5318 app.fake.set_photo("im-ada", PNG.to_vec(), "image/png");
5319
5320 let photo = app.get(&format!("/avatar/{admin_id}"), Some(&member)).await;
5321 assert_eq!(photo.status, StatusCode::OK);
5322 assert_eq!(photo.bytes, PNG);
5323
5324 let refused = app.get(&format!("/avatar/{admin_id}"), None).await;
5325 assert_eq!(refused.status, StatusCode::UNAUTHORIZED);
5326}
5327
5328/// A row that has not met the provider — invited, never signed in, never
5329/// synced — has no face to fetch, and an id nobody holds reads the same.
5330/// Catches a proxy that fails the page around a missing face.
5331#[tokio::test]
5332async fn the_avatar_is_not_found_without_a_linked_row() {
5333 let app = App::open().await;
5334 let admin_cookie = admin(&app).await;
5335 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
5336 let member_id = user_id(&app, "emre@iz.sh").await;
5337
5338 let photo = app
5339 .get(&format!("/avatar/{member_id}"), Some(&member))
5340 .await;
5341 assert_eq!(photo.status, StatusCode::NOT_FOUND);
5342
5343 let stranger = app
5344 .get(&format!("/avatar/{}", Ulid::generate()), Some(&member))
5345 .await;
5346 assert_eq!(stranger.status, StatusCode::NOT_FOUND);
5347}
5348
5349/// Every page with avatars carries the fallback script: the board's topbar
5350/// and card faces are `<img>`s to 404s without it, and a bare failed `<img>`
5351/// is the broken-image box, not the initials. Catches a page that renders
5352/// `avatar()` without the behavior that hides the failure.
5353#[tokio::test]
5354async fn the_board_carries_the_avatar_fallback_script() {
5355 let app = App::open().await;
5356 let admin = admin(&app).await;
5357
5358 let page = app.get("/", Some(&admin)).await;
5359 assert_eq!(page.status.as_u16(), 200);
5360 let html = String::from_utf8(page.bytes).unwrap();
5361 assert!(
5362 html.contains("avatar-photo"),
5363 "the topbar face is not on the board: {html}"
5364 );
5365 assert!(
5366 html.contains("__izAvatar"),
5367 "avatars without the fallback script show the broken-image box: {html}"
5368 );
5369}
5370
5371// ---------------------------------------------------------------------------
5372// Connection card: the identity mirror's stand, on every member's Settings
5373// ---------------------------------------------------------------------------
5374
5375/// The card names the provider and the app's public id, and says Connected
5376/// while the mirror's health holds an open stream. The client secret is
5377/// nowhere on the page — it must not even be read into the render path.
5378#[tokio::test]
5379async fn the_connection_card_names_its_provider_without_its_secret() {
5380 let app = App::open().await;
5381 let admin = admin(&app).await;
5382 app.health.connected();
5383 app.health.event();
5384 app.health.pass();
5385
5386 let page = app.get("/settings", Some(&admin)).await;
5387 assert_eq!(page.status.as_u16(), 200);
5388 let html = String::from_utf8(page.bytes).unwrap();
5389 assert!(
5390 html.contains("id=\"connection\""),
5391 "no Connection card: {html}"
5392 );
5393 assert!(
5394 !html.contains("iz-test:s3cr3t"),
5395 "the client secret leaked onto the page: {html}"
5396 );
5397 assert!(
5398 !html.contains("s3cr3t"),
5399 "the client secret leaked onto the page: {html}"
5400 );
5401 assert!(
5402 html.contains("iz-test"),
5403 "the client id is the card's public fact: {html}"
5404 );
5405 assert!(
5406 html.contains("Connected"),
5407 "an open stream says Connected: {html}"
5408 );
5409}
5410
5411/// Between passes — before the first stream opens, or after one died —
5412/// the card says Reconnecting, and still carries the public facts without
5413/// the secret.
5414#[tokio::test]
5415async fn the_connection_card_says_reconnecting_while_the_stream_is_down() {
5416 let app = App::open().await;
5417 let admin = admin(&app).await;
5418
5419 let page = app.get("/settings", Some(&admin)).await;
5420 assert_eq!(page.status.as_u16(), 200);
5421 let html = String::from_utf8(page.bytes).unwrap();
5422 assert!(
5423 html.contains("Reconnecting"),
5424 "a stream that never opened says Reconnecting: {html}"
5425 );
5426 assert!(
5427 html.contains("iz-test") && !html.contains("s3cr3t"),
5428 "the card names the client without the secret: {html}"
5429 );
5430}
5431/// Polls the store until a `Rule` send for `rule_id` addressed to `recipient`
5432/// exists beyond the `already` count — the engine runs off the request in a
5433/// spawned task, so the row is not there yet when the triggering call
5434/// returns. Bounded so a send that never arrives fails the test instead of
5435/// hanging it.
5436async fn until_rule_send_to(
5437 app: &App,
5438 rule_id: &str,
5439 recipient: &str,
5440 already: usize,
5441) -> iz_core::store::MailSend {
5442 for _ in 0..500 {
5443 let matching: Vec<_> = app
5444 .store
5445 .mail_queue(50, iz_core::store::FeedPage::Newest)
5446 .await
5447 .unwrap()
5448 .into_iter()
5449 .filter(|send| {
5450 send.kind == SendKind::Rule
5451 && send.rule_id.as_deref() == Some(rule_id)
5452 && send.recipient == recipient
5453 })
5454 .collect();
5455 if matching.len() > already {
5456 return matching.into_iter().next().unwrap();
5457 }
5458 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
5459 }
5460 panic!("no rule send to {recipient} for rule {rule_id} ever queued");
5461}
5462
5463/// One rule rides two different events across its lifetime, and a rewrite in
5464/// place keeps riding the second without becoming a new rule: a comment mails
5465/// the task's creator, not the commenter, and after the rule is rewritten to
5466/// fire on a rename instead, a rename mails the assignee, not the renamer.
5467#[tokio::test]
5468async fn a_rule_rides_every_event_and_can_be_rewritten() {
5469 let app = App::open_with_mail().await;
5470 let admin_cookie = admin(&app).await;
5471 let member = invited(&app, &admin_cookie, "deniz@iz.sh", "Deniz", Role::Member).await;
5472 let column = first_column(&app).await;
5473 let task = a_task(&app, &admin_cookie, &column, "Ship the picker").await;
5474
5475 let created = app
5476 .post(
5477 "/api/create_rule",
5478 Some(&admin_cookie),
5479 &[
5480 ("trigger", "commented"),
5481 ("column_id", ""),
5482 ("subject", "Someone commented"),
5483 ("audience", "creator"),
5484 ],
5485 )
5486 .await;
5487 assert_eq!(created.body, "null", "{}", created.body);
5488 let rule = only_rule(&app, &admin_cookie).await;
5489
5490 // A second member comments; the task's creator is the admin, not them.
5491 let commented = app
5492 .post(
5493 "/api/post_comment",
5494 Some(&member),
5495 &[("task_id", &task), ("body", "Looks good")],
5496 )
5497 .await;
5498 assert_eq!(commented.body, "null", "{}", commented.body);
5499
5500 let send = until_rule_send_to(&app, &rule, "ada@iz.sh", 0).await;
5501 assert_eq!(send.recipient, "ada@iz.sh");
5502 assert!(
5503 app.store
5504 .mail_queue(50, iz_core::store::FeedPage::Newest)
5505 .await
5506 .unwrap()
5507 .iter()
5508 .all(|send| {
5509 !(send.kind == SendKind::Rule
5510 && send.rule_id.as_deref() == Some(rule.as_str())
5511 && send.recipient == "deniz@iz.sh")
5512 }),
5513 "the commenter was mailed instead of the creator"
5514 );
5515 let decisions = app
5516 .store
5517 .recent_mail_decisions(50, iz_core::store::FeedPage::Newest)
5518 .await
5519 .unwrap();
5520 assert!(
5521 decisions.iter().any(|decision| decision.rule_id == rule
5522 && matches!(decision.outcome, iz_core::store::MailOutcome::Owed)),
5523 "the decisions ledger has no matched decision for the rule"
5524 );
5525
5526 // The admin is put on the task so the rewritten rule's assignees audience
5527 // has someone to address once it fires on a rename.
5528 let admin_id = person_id(&app, &admin_cookie, &task, "Ada Lovelace").await;
5529 let assigned = app
5530 .post(
5531 "/api/assign",
5532 Some(&admin_cookie),
5533 &[("task_id", &task), ("user_id", &admin_id)],
5534 )
5535 .await;
5536 assert_eq!(assigned.body, "null", "{}", assigned.body);
5537
5538 // The rule is rewritten in place: same id, new trigger, subject and
5539 // audience.
5540 let updated = app
5541 .post(
5542 "/api/update_rule",
5543 Some(&admin_cookie),
5544 &[
5545 ("rule_id", &rule),
5546 ("trigger", "retitled"),
5547 ("column_id", ""),
5548 ("subject", "Renamed"),
5549 ("audience", "assignees"),
5550 ],
5551 )
5552 .await;
5553 assert_eq!(
5554 updated.body, "null",
5555 "the rewrite was refused: {}",
5556 updated.body
5557 );
5558 assert_eq!(
5559 only_rule(&app, &admin_cookie).await,
5560 rule,
5561 "a new rule was made instead of the old one rewritten"
5562 );
5563
5564 let seen = app
5565 .post("/api/current_rules", Some(&admin_cookie), &[])
5566 .await;
5567 assert!(
5568 seen.body.contains(&format!("\"id\":\"{rule}\"")),
5569 "{}",
5570 seen.body
5571 );
5572 assert!(seen.body.contains("\"enabled\":true"), "{}", seen.body);
5573 assert!(
5574 seen.body.contains("\"trigger_kind\":\"retitled\""),
5575 "{}",
5576 seen.body
5577 );
5578 assert!(
5579 seen.body.contains("\"subject\":\"Renamed\""),
5580 "{}",
5581 seen.body
5582 );
5583
5584 // The second member renames the task; the rule now fires on retitle and
5585 // addresses the assignee — the admin — not the member who renamed it.
5586 let already = app
5587 .store
5588 .mail_queue(50, iz_core::store::FeedPage::Newest)
5589 .await
5590 .unwrap()
5591 .iter()
5592 .filter(|send| {
5593 send.kind == SendKind::Rule
5594 && send.rule_id.as_deref() == Some(rule.as_str())
5595 && send.recipient == "ada@iz.sh"
5596 })
5597 .count();
5598 let renamed = app
5599 .post(
5600 "/api/save_task",
5601 Some(&member),
5602 &[("task_id", &task), ("title", "Ship the redesigned picker")],
5603 )
5604 .await;
5605 assert_eq!(renamed.body, "null", "{}", renamed.body);
5606
5607 until_rule_send_to(&app, &rule, "ada@iz.sh", already).await;
5608 assert!(
5609 app.store
5610 .mail_queue(50, iz_core::store::FeedPage::Newest)
5611 .await
5612 .unwrap()
5613 .iter()
5614 .all(|send| {
5615 !(send.kind == SendKind::Rule
5616 && send.rule_id.as_deref() == Some(rule.as_str())
5617 && send.recipient == "deniz@iz.sh")
5618 }),
5619 "the renamer was mailed though the audience is the assignees"
5620 );
5621
5622 let logs = until_logs_contains(&app, &admin_cookie, "\"subject\":\"Renamed\"").await;
5623 assert!(logs.contains("\"recipient\":\"ada@iz.sh\""), "{}", logs);
5624}
5625
5626// `?task=X&new=1` together used to render both modals at once — two
5627// document-level datepicker listeners double-stepping the month nav.
5628#[tokio::test]
5629async fn task_and_new_together_render_only_the_task_modal() {
5630 let app = App::open().await;
5631 let admin = admin(&app).await;
5632 let column = first_column(&app).await;
5633 let task = a_task(&app, &admin, &column, "Only one modal at a time").await;
5634
5635 let raw = app.get(&format!("/?task={task}&new=1"), Some(&admin)).await;
5636 let html = String::from_utf8_lossy(&raw.bytes);
5637 assert_eq!(html.matches("class=\"modal-scrim\"").count(), 1, "{html}");
5638 assert!(
5639 !html.contains("modal-new-task"),
5640 "the new-task modal rendered too: {html}"
5641 );
5642}
5643
5644#[tokio::test]
5645async fn the_new_task_modal_opens_from_the_board_and_creates_into_the_chosen_column() {
5646 let app = App::open().await;
5647 let admin = admin(&app).await;
5648 let columns = columns_of(&app).await;
5649 let column = columns.last().expect("no columns on a fresh board").clone();
5650
5651 let raw = app.get("/?new=1", Some(&admin)).await;
5652 let html = String::from_utf8_lossy(&raw.bytes);
5653 assert!(
5654 html.contains("modal-new-task"),
5655 "the new-task modal did not render: {html}"
5656 );
5657 assert!(
5658 html.contains(&format!("value=\"{column}\"")),
5659 "the column picker is missing a board column: {html}"
5660 );
5661
5662 let answer = app
5663 .post(
5664 "/api/create_task",
5665 Some(&admin),
5666 &[("title", "Ship the new-task modal"), ("column_id", &column)],
5667 )
5668 .await;
5669 assert_eq!(answer.body, "", "the create was refused: {}", answer.body);
5670
5671 // A browser without script posts from `/?new=1`; a success has to land on
5672 // the board, not reopen the (now stale) new-task modal.
5673 let no_script = app
5674 .post_without_script(
5675 "/api/create_task",
5676 Some(&admin),
5677 "http://iz.test/?new=1",
5678 &[("title", "Ship it, no script"), ("column_id", &column)],
5679 )
5680 .await;
5681 assert_eq!(
5682 no_script.location.as_deref(),
5683 Some("/"),
5684 "{:?}",
5685 no_script.location
5686 );
5687
5688 let workspace_id = app.workspace_id().await;
5689 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
5690 .await
5691 .unwrap()
5692 .unwrap();
5693 let card = board
5694 .columns
5695 .iter()
5696 .find(|c| c.column.id == column)
5697 .and_then(|c| {
5698 c.cards
5699 .iter()
5700 .find(|card| card.title == "Ship the new-task modal")
5701 })
5702 .expect("the created task did not land in the chosen column");
5703 assert_eq!(card.title, "Ship the new-task modal");
5704}
5705
5706/// The new-task modal carries the Task-tab settings at birth: the project
5707/// select, the assignee checkboxes and — once something exists to link —
5708/// the dependency radios. The create form is still one form: no picker may
5709/// smuggle in a post of its own, and no control may create the card before
5710/// the footer's submit.
5711#[tokio::test]
5712async fn the_new_task_modal_carries_the_task_tab_fields() {
5713 let app = App::open().await;
5714 let admin = admin(&app).await;
5715 let column = first_column(&app).await;
5716 a_tag(&app, &admin, "Atlas").await;
5717 a_task(&app, &admin, &column, "Something to link").await;
5718
5719 let raw = app.get("/?new=1", Some(&admin)).await;
5720 let html = String::from_utf8_lossy(&raw.bytes).into_owned();
5721 assert!(
5722 html.contains("modal-new-task"),
5723 "the new-task modal did not render: {html}"
5724 );
5725 // Anchor at the modal div itself — the page's scripts quote `modal-scrim`
5726 // too — and stop at the first script after it: what sits between is the
5727 // modal's own markup.
5728 let start = html.find("modal modal-new-task").expect("no modal scrim");
5729 let modal = &html[start..];
5730 let modal = &modal[..modal.find("<script").unwrap_or(modal.len())];
5731 assert!(
5732 modal.contains("name=\"tag_id\""),
5733 "no project field: {modal}"
5734 );
5735 assert!(
5736 modal.contains("name=\"assignee_id\""),
5737 "no assignee field: {modal}"
5738 );
5739 assert!(modal.contains("dd-search"), "no assignee search: {modal}");
5740 assert!(
5741 modal.contains("name=\"other_id\""),
5742 "no dependency field: {modal}"
5743 );
5744 assert!(
5745 !modal.contains("action=\"/api/assign\"")
5746 && !modal.contains("action=\"/api/link_tasks\"")
5747 && !modal.contains("action=\"/api/set_task_tag\""),
5748 "the modal nests a form of its own: {modal}"
5749 );
5750 assert!(
5751 !modal.contains("data-autosubmit"),
5752 "a create-modal control posts the card by itself: {modal}"
5753 );
5754}
5755
5756/// Project, assignees and one dependency can all be set on the create post
5757/// itself: the card is born wearing the tag, carrying the person and blocking
5758/// the older task.
5759#[tokio::test]
5760async fn creating_a_task_can_set_project_assignees_and_a_dependency() {
5761 let app = App::open().await;
5762 let admin = admin(&app).await;
5763 invited(&app, &admin, "derya@iz.sh", "Derya", Role::Member).await;
5764 let column = first_column(&app).await;
5765 let other = a_task(&app, &admin, &column, "The older card").await;
5766 let atlas = a_tag(&app, &admin, "Atlas").await;
5767 let assignee = user_id(&app, "derya@iz.sh").await;
5768
5769 let answer = app
5770 .post(
5771 "/api/create_task",
5772 Some(&admin),
5773 &[
5774 ("title", "Born dressed"),
5775 ("column_id", &column),
5776 ("tag_id", &atlas.id),
5777 ("assignee_id", &assignee),
5778 ("other_id", &other),
5779 ("direction", "blocks"),
5780 ],
5781 )
5782 .await;
5783 assert_eq!(answer.body, "", "the create was refused: {}", answer.body);
5784
5785 let workspace_id = app.workspace_id().await;
5786 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
5787 .await
5788 .unwrap()
5789 .unwrap();
5790 let older_key = board
5791 .columns
5792 .iter()
5793 .flat_map(|c| &c.cards)
5794 .find(|card| card.id == other)
5795 .map(|card| card.task_key.clone())
5796 .expect("the older card is not on the board");
5797 let card = board
5798 .columns
5799 .iter()
5800 .flat_map(|c| &c.cards)
5801 .find(|card| card.title == "Born dressed")
5802 .expect("the created task is not on the board");
5803 assert_eq!(
5804 card.tag.as_ref().map(|tag| tag.name.as_str()),
5805 Some("Atlas"),
5806 "the card did not wear the chosen tag: {:?}",
5807 card.tag
5808 );
5809 assert!(
5810 card.assignees.iter().any(|person| person.id == assignee),
5811 "the assignee did not land: {:?}",
5812 card.assignees
5813 );
5814 assert!(
5815 card.blocks.iter().any(|key| *key == older_key),
5816 "the new card does not block the older one: {:?}",
5817 card.blocks
5818 );
5819}
5820
5821/// The assign call takes several people in one post: the task picker's
5822/// multi-select lands as repeated `user_id` pairs, same as a single assign.
5823#[tokio::test]
5824async fn assigning_two_people_at_once_puts_both_on_the_card() {
5825 let app = App::open().await;
5826 let admin = admin(&app).await;
5827 invited(&app, &admin, "ayse@iz.sh", "Ayse", Role::Member).await;
5828 invited(&app, &admin, "berk@iz.sh", "Berk", Role::Member).await;
5829 let column = first_column(&app).await;
5830 let task = a_task(&app, &admin, &column, "Two at once").await;
5831 let ayse = user_id(&app, "ayse@iz.sh").await;
5832 let berk = user_id(&app, "berk@iz.sh").await;
5833
5834 let html =
5835 String::from_utf8_lossy(&app.get(&format!("/?task={task}"), Some(&admin)).await.bytes)
5836 .into_owned();
5837 assert!(
5838 html.contains("assignee-pop")
5839 && html.contains("dd-search")
5840 && html.contains("name=\"user_id\""),
5841 "the task picker is not a searchable multi-select: {html}"
5842 );
5843
5844 let answer = app
5845 .post(
5846 "/api/assign",
5847 Some(&admin),
5848 &[("task_id", &task), ("user_id", &ayse), ("user_id", &berk)],
5849 )
5850 .await;
5851 assert_eq!(
5852 answer.body, "null",
5853 "the assign was refused: {}",
5854 answer.body
5855 );
5856
5857 let workspace_id = app.workspace_id().await;
5858 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
5859 .await
5860 .unwrap()
5861 .unwrap();
5862 let card = board
5863 .columns
5864 .iter()
5865 .flat_map(|c| &c.cards)
5866 .find(|card| card.id == task)
5867 .expect("the task is not on the board");
5868 assert!(
5869 card.assignees.iter().any(|person| person.id == ayse)
5870 && card.assignees.iter().any(|person| person.id == berk),
5871 "both people did not land: {:?}",
5872 card.assignees
5873 );
5874}
5875
5876/// A tag from nowhere refuses the whole create: nothing is written, the same
5877/// shape as a create into another workspace's column.
5878#[tokio::test]
5879async fn a_create_with_a_foreign_tag_is_refused_and_writes_nothing() {
5880 let app = App::open().await;
5881 let admin = admin(&app).await;
5882 let column = first_column(&app).await;
5883
5884 let answer = app
5885 .post(
5886 "/api/create_task",
5887 Some(&admin),
5888 &[
5889 ("title", "Wearing a tag from nowhere"),
5890 ("column_id", &column),
5891 ("tag_id", "00000000-0000-0000-0000-000000000000"),
5892 ],
5893 )
5894 .await;
5895 assert_eq!(answer.body, "");
5896 assert!(
5897 answer
5898 .location
5899 .as_deref()
5900 .unwrap_or_default()
5901 .contains("refusal=not-found&on=create_task"),
5902 "{:?}",
5903 answer.location
5904 );
5905 let workspace_id = app.workspace_id().await;
5906 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
5907 .await
5908 .unwrap()
5909 .unwrap();
5910 assert!(
5911 board
5912 .columns
5913 .iter()
5914 .flat_map(|c| &c.cards)
5915 .all(|card| card.title != "Wearing a tag from nowhere"),
5916 "the refused task was written anyway"
5917 );
5918}
5919/// A 1×1 transparent PNG: 67 real bytes, header to checksum, so it sniffs as
5920/// `image/png` and survives a byte-for-byte round trip.
5921const PNG: [u8; 67] = [
5922 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
5923 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4,
5924 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00,
5925 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE,
5926 0x42, 0x60, 0x82,
5927];
5928
5929/// The id of the account behind an email address, read straight off the store:
5930/// fixture setup, not the behavior under test.
5931async fn user_id(app: &App, email: &str) -> String {
5932 app.store
5933 .user_by_email(&app.workspace_id().await, email)
5934 .await
5935 .unwrap()
5936 .expect("no such user")
5937 .id
5938}
5939
5940/// The nav shows a page only to a role that can act on it: an admin's board
5941/// carries all four links, a member's carries neither Rules nor Logs.
5942#[tokio::test]
5943async fn the_nav_hides_rules_and_logs_from_a_member() {
5944 let app = App::open().await;
5945 let admin = admin(&app).await;
5946 let member = invited(&app, &admin, "deniz@iz.sh", "Deniz", Role::Member).await;
5947
5948 let admin_board = app.get("/", Some(&admin)).await;
5949 let admin_html = String::from_utf8_lossy(&admin_board.bytes).into_owned();
5950 assert!(admin_html.contains("href=\"/rules\""));
5951 assert!(admin_html.contains("href=\"/logs\""));
5952
5953 let member_board = app.get("/", Some(&member)).await;
5954 let member_html = String::from_utf8_lossy(&member_board.bytes).into_owned();
5955 assert!(member_html.contains("href=\"/settings\""));
5956 assert!(!member_html.contains("href=\"/rules\""));
5957 assert!(!member_html.contains("href=\"/logs\""));
5958}
5959
5960/// Account events ride the same feed as task events: a role change and a
5961/// profile save show up beside a created task, each on its actor.
5962#[tokio::test]
5963async fn account_events_ride_the_activity_feed() {
5964 let app = App::open().await;
5965 let admin_cookie = admin(&app).await;
5966 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
5967 let columns = columns_of(&app).await;
5968 a_task(&app, &admin_cookie, &columns[0], "Ship it").await;
5969
5970 let member_id = user_id(&app, "emre@iz.sh").await;
5971 let answer = app
5972 .post(
5973 "/api/set_role",
5974 Some(&admin_cookie),
5975 &[("user_id", &member_id), ("role", "viewer")],
5976 )
5977 .await;
5978 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
5979
5980 let prefs = app
5981 .post(
5982 "/api/save_profile",
5983 Some(&member),
5984 &[
5985 ("timezone", "UTC+03:00"),
5986 ("theme", "dark"),
5987 ("language", "en"),
5988 ("ui", "instrument"),
5989 ],
5990 )
5991 .await;
5992 assert_eq!(prefs.status, StatusCode::SEE_OTHER, "{}", prefs.body);
5993
5994 let body = until_logs_contains(&app, &admin_cookie, "made Emre -> viewer").await;
5995 assert!(body.contains("saved the profile"), "{body}");
5996 assert!(body.contains("Ship it"), "{body}");
5997}
5998
5999/// The href the page itself hands back for a link, so the test walks the
6000/// same road a reader would rather than predicting a query string.
6001fn extract_href<'h>(html: &'h str, contains: &str) -> &'h str {
6002 let start = html
6003 .match_indices("href=\"")
6004 .map(|(i, _)| i + "href=\"".len())
6005 .find(|&i| html[i..].starts_with(contains))
6006 .unwrap_or_else(|| panic!("no href containing {contains:?}: {html}"));
6007 let end = html[start..].find('"').unwrap() + start;
6008 &html[start..end]
6009}
6010
6011/// The activity panel truncates at 50 rows. Rows shift under an OFFSET
6012/// reader turning the page; a keyset cursor cannot skip or duplicate one
6013/// because it names the row itself, not a position that can move. A page
6014/// turn here follows the actual `Older`/`Newer` href out of the body —
6015/// never predicts a query string — and a member GET still finds the door
6016/// shut.
6017#[tokio::test]
6018async fn the_logs_page_pages_past_the_truncation() {
6019 let app = App::open().await;
6020 let admin_cookie = admin(&app).await;
6021 let member = invited(&app, &admin_cookie, "deniz@iz.sh", "Deniz", Role::Member).await;
6022
6023 let t0 = time::OffsetDateTime::now_utc();
6024 for i in 0..60 {
6025 app.store
6026 .record_event(
6027 None,
6028 &iz_core::detail::ActivityKind::Other("row".to_string()),
6029 &format!("row {i}"),
6030 t0 + time::Duration::seconds(i),
6031 )
6032 .await
6033 .unwrap();
6034 }
6035
6036 let first = app.get("/logs?section=activity", Some(&admin_cookie)).await;
6037 let first_html = String::from_utf8_lossy(&first.bytes).into_owned();
6038 assert!(first_html.contains("row 59"), "{first_html}");
6039 // Row 10 is the 50th newest — the boundary row this page ends on.
6040 assert!(first_html.contains("row 10<"), "{first_html}");
6041 assert!(!first_html.contains("row 9<"), "{first_html}");
6042 assert!(
6043 !first_html.contains("\">Newer</a>"),
6044 "a Newer link on the newest page: {first_html}"
6045 );
6046 let older_href =
6047 extract_href(&first_html, "/logs?section=activity&amp;before=").replace("&amp;", "&");
6048
6049 let second = app.get(&older_href, Some(&admin_cookie)).await;
6050 let second_html = String::from_utf8_lossy(&second.bytes).into_owned();
6051 // Row 10 shown once, on the first page — not skipped, not repeated here.
6052 assert!(!second_html.contains("row 10<"), "{second_html}");
6053 assert!(second_html.contains("row 9<"), "{second_html}");
6054 assert!(second_html.contains("row 0<"), "{second_html}");
6055 let newer_href =
6056 extract_href(&second_html, "/logs?section=activity&amp;after=").replace("&amp;", "&");
6057 // No Older link left: the second page is the whole remainder.
6058 assert!(
6059 !second_html.contains("\">Older</a>"),
6060 "an Older link past the last row: {second_html}"
6061 );
6062
6063 let back = app.get(&newer_href, Some(&admin_cookie)).await;
6064 let back_html = String::from_utf8_lossy(&back.bytes).into_owned();
6065 assert!(back_html.contains("row 59"), "{back_html}");
6066
6067 let refused = app.get("/logs", Some(&member)).await;
6068 let refused_html = String::from_utf8_lossy(&refused.bytes);
6069 assert!(refused_html.contains("Not permitted."), "{refused_html}");
6070
6071 // A cursor that does not parse falls back to the newest page rather
6072 // than erroring.
6073 let garbage = app
6074 .get("/logs?section=activity&before=zzz", Some(&admin_cookie))
6075 .await;
6076 assert_eq!(garbage.status, 200);
6077 let garbage_html = String::from_utf8_lossy(&garbage.bytes);
6078 assert!(garbage_html.contains("row 59"), "{garbage_html}");
6079}
6080
6081/// The activity filter row narrows the feed by actor, kind, task and day,
6082/// and the pager foot's position note counts against the filtered total —
6083/// not the whole feed.
6084#[tokio::test]
6085async fn the_activity_filter_narrows_and_the_position_note_counts_the_match() {
6086 let app = App::open().await;
6087 let admin_cookie = admin(&app).await;
6088 let admin_id = user_id(&app, "ada@iz.sh").await;
6089 let member = invited(&app, &admin_cookie, "deniz@iz.sh", "Deniz", Role::Member).await;
6090 let member_id = user_id(&app, "deniz@iz.sh").await;
6091
6092 let t0 = time::OffsetDateTime::now_utc();
6093 for i in 0..60 {
6094 let actor = if i % 2 == 0 {
6095 Some(admin_id.as_str())
6096 } else {
6097 Some(member_id.as_str())
6098 };
6099 app.store
6100 .record_event(
6101 actor,
6102 &iz_core::detail::ActivityKind::Other("row".to_string()),
6103 &format!("row {i}"),
6104 t0 + time::Duration::seconds(i),
6105 )
6106 .await
6107 .unwrap();
6108 }
6109
6110 let all = app
6111 .get("/logs?section=activity&kind=row", Some(&admin_cookie))
6112 .await;
6113 let all_html = String::from_utf8_lossy(&all.bytes).into_owned();
6114 assert!(all_html.contains("1\u{2013}"), "{all_html}");
6115 assert!(all_html.contains("/ 60</span>"), "{all_html}");
6116
6117 let by_actor = app
6118 .get(
6119 &format!("/logs?section=activity&kind=row&actor={member_id}"),
6120 Some(&admin_cookie),
6121 )
6122 .await;
6123 let by_actor_html = String::from_utf8_lossy(&by_actor.bytes).into_owned();
6124 assert!(by_actor_html.contains("/ 30</span>"), "{by_actor_html}");
6125
6126 let oldest = app
6127 .get(
6128 "/logs?section=activity&kind=row&dir=oldest",
6129 Some(&admin_cookie),
6130 )
6131 .await;
6132 let oldest_html = String::from_utf8_lossy(&oldest.bytes).into_owned();
6133 assert!(oldest_html.contains("row 0<"), "{oldest_html}");
6134
6135 let garbage = app
6136 .get(
6137 "/logs?section=activity&actor=zz&kind=zz&on=zz",
6138 Some(&admin_cookie),
6139 )
6140 .await;
6141 assert_eq!(garbage.status, 200);
6142
6143 let refused = app
6144 .get("/logs?section=activity&actor=x", Some(&member))
6145 .await;
6146 let refused_html = String::from_utf8_lossy(&refused.bytes);
6147 assert!(refused_html.contains("Not permitted."), "{refused_html}");
6148}
6149
6150/// `kind=` alone narrows the feed to one activity kind, leaving the other
6151/// kind's rows out of the body entirely.
6152#[tokio::test]
6153async fn the_kind_filter_shows_only_that_kinds_rows() {
6154 let app = App::open().await;
6155 let admin_cookie = admin(&app).await;
6156
6157 let t0 = time::OffsetDateTime::now_utc();
6158 for i in 0..5 {
6159 app.store
6160 .record_event(
6161 None,
6162 &iz_core::detail::ActivityKind::Created,
6163 "",
6164 t0 + time::Duration::seconds(i),
6165 )
6166 .await
6167 .unwrap();
6168 }
6169 for i in 0..3 {
6170 app.store
6171 .record_event(
6172 None,
6173 &iz_core::detail::ActivityKind::Commented,
6174 "",
6175 t0 + time::Duration::seconds(100 + i),
6176 )
6177 .await
6178 .unwrap();
6179 }
6180
6181 let narrowed = app
6182 .get("/logs?section=activity&kind=created", Some(&admin_cookie))
6183 .await;
6184 let html = String::from_utf8_lossy(&narrowed.bytes).into_owned();
6185 assert!(html.contains("created this task"), "{html}");
6186 assert!(!html.contains("log-line\">commented<"), "{html}");
6187 assert!(html.contains("/ 5</span>"), "{html}");
6188}
6189
6190/// `task=` narrows the feed to one task's rows, by its key — not any other
6191/// task's, even one created in the same run.
6192#[tokio::test]
6193async fn the_task_filter_shows_only_that_tasks_rows() {
6194 let app = App::open().await;
6195 let admin_cookie = admin(&app).await;
6196 let column = first_column(&app).await;
6197 let alpha = a_task(&app, &admin_cookie, &column, "Task Alpha").await;
6198 let _beta = a_task(&app, &admin_cookie, &column, "Task Beta").await;
6199 let alpha_key = app
6200 .store
6201 .task(&alpha)
6202 .await
6203 .unwrap()
6204 .expect("alpha task gone")
6205 .row
6206 .task_key;
6207
6208 let narrowed = app
6209 .get(
6210 &format!("/logs?section=activity&task={alpha_key}"),
6211 Some(&admin_cookie),
6212 )
6213 .await;
6214 let html = String::from_utf8_lossy(&narrowed.bytes).into_owned();
6215 assert!(html.contains("log-title\">Task Alpha<"), "{html}");
6216 assert!(!html.contains("log-title\">Task Beta<"), "{html}");
6217}
6218
6219/// The task filter is a select listing the workspace's tasks, keyed by
6220/// task_key — not a bare text input.
6221#[tokio::test]
6222async fn the_task_filter_lists_the_workspaces_tasks() {
6223 let app = App::open().await;
6224 let admin_cookie = admin(&app).await;
6225 let column = first_column(&app).await;
6226 let alpha = a_task(&app, &admin_cookie, &column, "Task Alpha").await;
6227 let alpha_key = app
6228 .store
6229 .task(&alpha)
6230 .await
6231 .unwrap()
6232 .expect("alpha task gone")
6233 .row
6234 .task_key;
6235
6236 let page = app.get("/logs?section=activity", Some(&admin_cookie)).await;
6237 let html = String::from_utf8_lossy(&page.bytes).into_owned();
6238 assert!(
6239 html.contains(&format!("<option value=\"{alpha_key}\"")),
6240 "{html}"
6241 );
6242}
6243
6244/// A row for a task-attached event carries the task's key alongside its
6245/// title.
6246#[tokio::test]
6247async fn the_activity_row_shows_the_task_key() {
6248 let app = App::open().await;
6249 let admin_cookie = admin(&app).await;
6250 let column = first_column(&app).await;
6251 let alpha = a_task(&app, &admin_cookie, &column, "Task Alpha").await;
6252 let alpha_key = app
6253 .store
6254 .task(&alpha)
6255 .await
6256 .unwrap()
6257 .expect("alpha task gone")
6258 .row
6259 .task_key;
6260
6261 let page = app.get("/logs?section=activity", Some(&admin_cookie)).await;
6262 let html = String::from_utf8_lossy(&page.bytes).into_owned();
6263 assert!(
6264 html.contains(&format!("log-key\">({alpha_key})<")),
6265 "{html}"
6266 );
6267}
6268
6269/// `on=YYYY-MM-DD` keeps only the rows recorded that day, in the admin's own
6270/// timezone (UTC by default in this fixture).
6271#[tokio::test]
6272async fn the_day_filter_keeps_only_that_days_rows() {
6273 let app = App::open().await;
6274 let admin_cookie = admin(&app).await;
6275
6276 let today = time::OffsetDateTime::now_utc();
6277 let two_days_ago = today - time::Duration::days(2);
6278 for i in 0..5 {
6279 app.store
6280 .record_event(
6281 None,
6282 &iz_core::detail::ActivityKind::Other("row".to_string()),
6283 &format!("today-row {i}"),
6284 today + time::Duration::seconds(i),
6285 )
6286 .await
6287 .unwrap();
6288 }
6289 for i in 0..5 {
6290 app.store
6291 .record_event(
6292 None,
6293 &iz_core::detail::ActivityKind::Other("row".to_string()),
6294 &format!("old-row {i}"),
6295 two_days_ago + time::Duration::seconds(i),
6296 )
6297 .await
6298 .unwrap();
6299 }
6300 let on = format!(
6301 "{:04}-{:02}-{:02}",
6302 today.year(),
6303 today.month() as u8,
6304 today.day()
6305 );
6306
6307 let narrowed = app
6308 .get(
6309 &format!("/logs?section=activity&on={on}"),
6310 Some(&admin_cookie),
6311 )
6312 .await;
6313 let html = String::from_utf8_lossy(&narrowed.bytes).into_owned();
6314 assert!(html.contains("today-row"), "{html}");
6315 assert!(!html.contains("old-row"), "{html}");
6316}
6317
6318/// `from=`/`to=` narrows the feed to an inclusive span of days, in the
6319/// admin's own timezone (UTC by default in this fixture): a row on the `to`
6320/// day itself is kept, not just the days strictly between.
6321#[tokio::test]
6322async fn the_range_filter_keeps_the_inclusive_span() {
6323 let app = App::open().await;
6324 let admin_cookie = admin(&app).await;
6325
6326 let base =
6327 time::OffsetDateTime::now_utc().replace_time(time::Time::from_hms(12, 0, 0).unwrap());
6328 for i in 0..5i64 {
6329 let day = base + time::Duration::days(i);
6330 app.store
6331 .record_event(
6332 None,
6333 &iz_core::detail::ActivityKind::Other("row".to_string()),
6334 &format!("day{i}-row"),
6335 day,
6336 )
6337 .await
6338 .unwrap();
6339 }
6340 let ymd = |dt: time::OffsetDateTime| {
6341 format!("{:04}-{:02}-{:02}", dt.year(), dt.month() as u8, dt.day())
6342 };
6343 let from = ymd(base + time::Duration::days(1));
6344 let to = ymd(base + time::Duration::days(3));
6345
6346 let ranged = app
6347 .get(
6348 &format!("/logs?section=activity&from={from}&to={to}"),
6349 Some(&admin_cookie),
6350 )
6351 .await;
6352 let html = String::from_utf8_lossy(&ranged.bytes).into_owned();
6353 assert!(!html.contains("day0-row"), "{html}");
6354 assert!(html.contains("day1-row"), "{html}");
6355 assert!(html.contains("day2-row"), "{html}");
6356 // The `to` day itself is included — the off-by-one that matters.
6357 assert!(html.contains("day3-row"), "{html}");
6358 assert!(!html.contains("day4-row"), "{html}");
6359
6360 let from_only = app
6361 .get(
6362 &format!("/logs?section=activity&from={from}"),
6363 Some(&admin_cookie),
6364 )
6365 .await;
6366 let from_only_html = String::from_utf8_lossy(&from_only.bytes).into_owned();
6367 assert!(!from_only_html.contains("day0-row"), "{from_only_html}");
6368 assert!(from_only_html.contains("day1-row"), "{from_only_html}");
6369 assert!(from_only_html.contains("day4-row"), "{from_only_html}");
6370
6371 let to_only = app
6372 .get(
6373 &format!("/logs?section=activity&to={to}"),
6374 Some(&admin_cookie),
6375 )
6376 .await;
6377 let to_only_html = String::from_utf8_lossy(&to_only.bytes).into_owned();
6378 assert!(to_only_html.contains("day0-row"), "{to_only_html}");
6379 assert!(to_only_html.contains("day3-row"), "{to_only_html}");
6380 assert!(!to_only_html.contains("day4-row"), "{to_only_html}");
6381
6382 // A reversed range (from later than to) is swapped, not empty: same rows
6383 // as the correctly-ordered range, though the form itself keeps echoing
6384 // the raw (reversed) query values so it does not overrule what the user
6385 // typed.
6386 let reversed = app
6387 .get(
6388 &format!("/logs?section=activity&from={to}&to={from}"),
6389 Some(&admin_cookie),
6390 )
6391 .await;
6392 let reversed_html = String::from_utf8_lossy(&reversed.bytes).into_owned();
6393 for i in 1..=3 {
6394 assert!(
6395 reversed_html.contains(&format!("day{i}-row")),
6396 "{reversed_html}"
6397 );
6398 }
6399 assert!(!reversed_html.contains("day0-row"), "{reversed_html}");
6400 assert!(!reversed_html.contains("day4-row"), "{reversed_html}");
6401
6402 // Garbage bounds narrow nothing rather than 500ing.
6403 let garbage = app
6404 .get("/logs?section=activity&from=zz&to=zz", Some(&admin_cookie))
6405 .await;
6406 assert_eq!(garbage.status, StatusCode::OK);
6407 let garbage_html = String::from_utf8_lossy(&garbage.bytes).into_owned();
6408 for i in 0..5 {
6409 assert!(
6410 garbage_html.contains(&format!("day{i}-row")),
6411 "{garbage_html}"
6412 );
6413 }
6414}
6415
6416/// An Older href on a range-filtered page keeps carrying `from=`/`to=` so
6417/// paging never drops the range.
6418#[tokio::test]
6419async fn the_older_href_round_trips_the_range_filter() {
6420 let app = App::open().await;
6421 let admin_cookie = admin(&app).await;
6422
6423 let t0 = time::OffsetDateTime::now_utc();
6424 for i in 0..60 {
6425 app.store
6426 .record_event(
6427 None,
6428 &iz_core::detail::ActivityKind::Other("row".to_string()),
6429 &format!("row {i}"),
6430 t0 + time::Duration::seconds(i),
6431 )
6432 .await
6433 .unwrap();
6434 }
6435 let from = format!("{:04}-{:02}-{:02}", t0.year(), t0.month() as u8, t0.day());
6436 let to = from.clone();
6437
6438 let first = app
6439 .get(
6440 &format!("/logs?section=activity&from={from}&to={to}"),
6441 Some(&admin_cookie),
6442 )
6443 .await;
6444 let first_html = String::from_utf8_lossy(&first.bytes).into_owned();
6445 let older_href =
6446 extract_href(&first_html, "/logs?section=activity&amp;before=").replace("&amp;", "&");
6447 assert!(older_href.contains(&format!("from={from}")), "{older_href}");
6448 assert!(older_href.contains(&format!("to={to}")), "{older_href}");
6449}
6450
6451/// The `iz_rows_activity` cookie the page's own fit script sets caps the
6452/// page at that many rows, no more.
6453#[tokio::test]
6454async fn the_rows_cookie_caps_the_page_size() {
6455 let app = App::open().await;
6456 let admin_cookie = admin(&app).await;
6457
6458 let t0 = time::OffsetDateTime::now_utc();
6459 for i in 0..60 {
6460 app.store
6461 .record_event(
6462 None,
6463 &iz_core::detail::ActivityKind::Other("row".to_string()),
6464 &format!("row {i}"),
6465 t0 + time::Duration::seconds(i),
6466 )
6467 .await
6468 .unwrap();
6469 }
6470
6471 let capped = app
6472 .get_with_extra_cookie(
6473 "/logs?section=activity",
6474 Some(&admin_cookie),
6475 "iz_rows_activity=15",
6476 )
6477 .await;
6478 let html = String::from_utf8_lossy(&capped.bytes).into_owned();
6479 assert_eq!(html.matches("class=\"log-row\"").count(), 15, "{html}");
6480 assert!(html.contains("\">Older</a>"), "{html}");
6481}
6482
6483/// The Older href carries an active `kind=`/`dir=oldest` filter along with
6484/// its own cursor, and following it never turns up the other kind's rows.
6485#[tokio::test]
6486async fn the_older_href_round_trips_the_active_filter() {
6487 let app = App::open().await;
6488 let admin_cookie = admin(&app).await;
6489
6490 let t0 = time::OffsetDateTime::now_utc();
6491 for i in 0..60 {
6492 app.store
6493 .record_event(
6494 None,
6495 &iz_core::detail::ActivityKind::Other("target".to_string()),
6496 &format!("target {i}"),
6497 t0 + time::Duration::seconds(i),
6498 )
6499 .await
6500 .unwrap();
6501 }
6502 for i in 0..5 {
6503 app.store
6504 .record_event(
6505 None,
6506 &iz_core::detail::ActivityKind::Other("foreign".to_string()),
6507 &format!("foreign {i}"),
6508 t0 + time::Duration::seconds(1000 + i),
6509 )
6510 .await
6511 .unwrap();
6512 }
6513
6514 let first = app
6515 .get(
6516 "/logs?section=activity&kind=target&dir=oldest",
6517 Some(&admin_cookie),
6518 )
6519 .await;
6520 let first_html = String::from_utf8_lossy(&first.bytes).into_owned();
6521 assert!(!first_html.contains("foreign"), "{first_html}");
6522 let older_href =
6523 extract_href(&first_html, "/logs?section=activity&amp;before=").replace("&amp;", "&");
6524 assert!(older_href.contains("kind=target"), "{older_href}");
6525 assert!(older_href.contains("dir=oldest"), "{older_href}");
6526
6527 let second = app.get(&older_href, Some(&admin_cookie)).await;
6528 let second_html = String::from_utf8_lossy(&second.bytes).into_owned();
6529 assert!(!second_html.contains("foreign"), "{second_html}");
6530}
6531
6532/// `/api/current_logs` keeps reading the unpaged newest page regardless of a
6533/// small `iz_rows_activity` cookie — the JSON route never widened by the
6534/// page's own fit cookie.
6535#[tokio::test]
6536async fn current_logs_json_ignores_the_rows_cookie() {
6537 let app = App::open().await;
6538 let admin_cookie = admin(&app).await;
6539
6540 let t0 = time::OffsetDateTime::now_utc();
6541 for i in 0..60 {
6542 app.store
6543 .record_event(
6544 None,
6545 &iz_core::detail::ActivityKind::Other("row".to_string()),
6546 &format!("row {i}"),
6547 t0 + time::Duration::seconds(i),
6548 )
6549 .await
6550 .unwrap();
6551 }
6552
6553 let answer = app
6554 .post_with_extra_cookie(
6555 "/api/current_logs",
6556 Some(&admin_cookie),
6557 &[],
6558 Some("iz_rows_activity=5"),
6559 )
6560 .await;
6561 assert!(answer.body.contains("\"queue\""), "{}", answer.body);
6562 assert!(answer.body.contains("\"decisions\""), "{}", answer.body);
6563 assert!(answer.body.contains("\"activity\""), "{}", answer.body);
6564 let activity_rows = answer.body.matches("\"sentence\":").count();
6565 assert!(
6566 activity_rows <= 50,
6567 "{} rows: {}",
6568 activity_rows,
6569 answer.body
6570 );
6571}
6572
6573/// Seeds one decision and one accepted send directly on the store — the
6574/// engine's own timing is not what these notification tests are about — and
6575/// hands back the task and the send's id.
6576async fn a_task_with_a_notification(
6577 app: &App,
6578 admin_cookie: &str,
6579 subject: &str,
6580) -> (String, String) {
6581 let columns = columns_of(app).await;
6582 let task = a_task(app, admin_cookie, &columns[0], "Ship it").await;
6583 let admin_id = person_id(app, admin_cookie, &task, "Ada Lovelace").await;
6584 let workspace_id = app.workspace_id().await;
6585 let board = app.store.board(&workspace_id).await.unwrap().unwrap();
6586 let rule = app
6587 .store
6588 .create_mail_rule(
6589 &board.id,
6590 &Trigger::StatusBecomes(Some(columns[1].clone())),
6591 subject,
6592 Audience::Assignees,
6593 time::OffsetDateTime::now_utc(),
6594 false,
6595 )
6596 .await
6597 .unwrap();
6598 let transition = match app
6599 .store
6600 .move_task(
6601 &task,
6602 &columns[0],
6603 &columns[1],
6604 &admin_id,
6605 time::OffsetDateTime::now_utc(),
6606 )
6607 .await
6608 .unwrap()
6609 {
6610 Moved::Recorded(transition) => transition,
6611 other => panic!("the move did not happen: {other:?}"),
6612 };
6613 let now = time::OffsetDateTime::now_utc();
6614 app.store
6615 .record_mail_decision(&rule.id, &transition.id, &task, MailOutcome::Owed, "", now)
6616 .await
6617 .unwrap();
6618 let send = app
6619 .store
6620 .claim_send(&rule.id, &transition.id, &task, "ada@iz.sh", now, now)
6621 .await
6622 .unwrap()
6623 .unwrap();
6624 app.store.record_send_accepted(&send.id, now).await.unwrap();
6625 (task, send.id.clone())
6626}
6627
6628/// A task's detail page shows its notifications: the recipient and a state
6629/// chip for a send its rules made, to anyone who can read the task — but the
6630/// rule's own name only to an admin.
6631#[tokio::test]
6632async fn a_tasks_notifications_show_the_recipient_and_the_rule_name_is_admin_only() {
6633 let app = App::open().await;
6634 let admin_cookie = admin(&app).await;
6635 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
6636 let (task, _send_id) =
6637 a_task_with_a_notification(&app, &admin_cookie, "Wraps up the sprint").await;
6638
6639 let member_page = app
6640 .get(&format!("/?task={task}&tab=mail"), Some(&member))
6641 .await;
6642 let member_html = String::from_utf8_lossy(&member_page.bytes);
6643 assert!(member_html.contains("ada@iz.sh"), "{member_html}");
6644 assert!(
6645 member_html.contains("rule-term-sent"),
6646 "no state chip on the member's page: {member_html}"
6647 );
6648 assert!(
6649 !member_html.contains("Wraps up the sprint"),
6650 "a member was shown the rule's name: {member_html}"
6651 );
6652
6653 let admin_page = app
6654 .get(&format!("/?task={task}&tab=mail"), Some(&admin_cookie))
6655 .await;
6656 let admin_html = String::from_utf8_lossy(&admin_page.bytes);
6657 assert!(admin_html.contains("ada@iz.sh"), "{admin_html}");
6658 assert!(admin_html.contains("Wraps up the sprint"), "{admin_html}");
6659}
6660
6661/// Who a task mailed and whether it arrived belongs to everyone who can read
6662/// the task. Why the mail server refused belongs to the people who can do
6663/// something about it.
6664#[tokio::test]
6665async fn the_mail_servers_own_words_are_admin_only() {
6666 let app = App::open().await;
6667 let admin_cookie = admin(&app).await;
6668 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
6669 let (task, send_id) = a_task_with_a_notification(&app, &admin_cookie, "Sprint wrap").await;
6670
6671 // The send failed, and the server said something about the account it
6672 // failed to authenticate.
6673 let now = time::OffsetDateTime::now_utc();
6674 app.store
6675 .record_send_refused(
6676 &send_id,
6677 "535 5.7.8 Username and Password not accepted for postmaster@dizey.sh",
6678 None,
6679 now,
6680 )
6681 .await
6682 .unwrap();
6683
6684 let member_page = app
6685 .get(&format!("/?task={task}&tab=mail"), Some(&member))
6686 .await;
6687 let member_html = String::from_utf8_lossy(&member_page.bytes);
6688 // The fact of the failure is theirs to see.
6689 assert!(
6690 member_html.contains("ada@iz.sh"),
6691 "the member lost the recipient too: {member_html}"
6692 );
6693 assert!(
6694 !member_html.contains("postmaster@dizey.sh") && !member_html.contains("535"),
6695 "a member was shown what the mail server said: {member_html}"
6696 );
6697
6698 let admin_page = app
6699 .get(&format!("/?task={task}&tab=mail"), Some(&admin_cookie))
6700 .await;
6701 let admin_html = String::from_utf8_lossy(&admin_page.bytes);
6702 assert!(
6703 admin_html.contains("postmaster@dizey.sh"),
6704 "the admin cannot see why it failed either: {admin_html}"
6705 );
6706}
6707
6708/// A task with no mail at all renders the same quiet empty line the other
6709/// blocks use, under the notifications heading.
6710#[tokio::test]
6711async fn a_task_with_no_mail_shows_the_quiet_notifications_line() {
6712 let app = App::open().await;
6713 let admin_cookie = admin(&app).await;
6714 let column = first_column(&app).await;
6715 let task = a_task(&app, &admin_cookie, &column, "Nobody mails me").await;
6716
6717 let page = app
6718 .get(&format!("/?task={task}&tab=mail"), Some(&admin_cookie))
6719 .await;
6720 let html = String::from_utf8_lossy(&page.bytes);
6721 assert!(html.contains("Notifications"), "{html}");
6722 assert!(html.contains("Nothing yet."), "{html}");
6723}
6724
6725/// An admin's retry puts a failed send back in play — pending, due right
6726/// away — and the queue tab picks it back up.
6727#[tokio::test]
6728async fn an_admin_retries_a_failed_send_and_it_rejoins_the_queue() {
6729 let app = App::open().await;
6730 let admin_cookie = admin(&app).await;
6731 let (task, send_id) = a_task_with_a_notification(&app, &admin_cookie, "Never got there").await;
6732 let now = time::OffsetDateTime::now_utc();
6733 app.store
6734 .record_send_refused(&send_id, "timeout", Some(now), now)
6735 .await
6736 .unwrap();
6737
6738 let answer = app
6739 .post(
6740 "/api/retry_send",
6741 Some(&admin_cookie),
6742 &[("send_id", &send_id)],
6743 )
6744 .await;
6745 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
6746 assert_eq!(answer.body, "null", "{}", answer.body);
6747
6748 let sends = app.store.sends_for_task(&task, 10).await.unwrap();
6749 let reread = sends.iter().find(|s| s.id == send_id).unwrap();
6750 assert_eq!(reread.state, SendState::Pending);
6751 assert!(
6752 reread
6753 .next_attempt_at
6754 .is_some_and(|at| at <= time::OffsetDateTime::now_utc()),
6755 "the retry is not due right away: {reread:?}"
6756 );
6757
6758 let logs = app
6759 .post("/api/current_logs", Some(&admin_cookie), &[])
6760 .await;
6761 assert!(
6762 logs.body.contains("\"recipient\":\"ada@iz.sh\""),
6763 "the retried send did not rejoin the queue: {}",
6764 logs.body
6765 );
6766}
6767
6768/// A member cannot retry a send, and the pages a member can reach never draw
6769/// a Retry button in the first place.
6770#[tokio::test]
6771async fn a_member_may_not_retry_a_send() {
6772 let app = App::open().await;
6773 let admin_cookie = admin(&app).await;
6774 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
6775 let (task, send_id) =
6776 a_task_with_a_notification(&app, &admin_cookie, "Member cannot touch this").await;
6777 let now = time::OffsetDateTime::now_utc();
6778 app.store
6779 .record_send_refused(&send_id, "timeout", Some(now), now)
6780 .await
6781 .unwrap();
6782
6783 let answer = app
6784 .post("/api/retry_send", Some(&member), &[("send_id", &send_id)])
6785 .await;
6786 assert!(answer.body.contains("Forbidden"), "{}", answer.body);
6787
6788 let sends = app.store.sends_for_task(&task, 10).await.unwrap();
6789 let reread = sends.iter().find(|s| s.id == send_id).unwrap();
6790 assert_eq!(
6791 reread.state,
6792 SendState::Failed,
6793 "the refused retry moved it anyway"
6794 );
6795
6796 let member_page = app.get(&format!("/?task={task}"), Some(&member)).await;
6797 let member_html = String::from_utf8_lossy(&member_page.bytes);
6798 assert!(!member_html.contains("Retry"), "{member_html}");
6799}
6800
6801/// Retrying a send that already went out changes nothing, and does not 500.
6802#[tokio::test]
6803async fn retrying_an_already_sent_send_changes_nothing() {
6804 let app = App::open().await;
6805 let admin_cookie = admin(&app).await;
6806 let (task, send_id) =
6807 a_task_with_a_notification(&app, &admin_cookie, "Already on its way").await;
6808
6809 let answer = app
6810 .post(
6811 "/api/retry_send",
6812 Some(&admin_cookie),
6813 &[("send_id", &send_id)],
6814 )
6815 .await;
6816 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
6817 assert_eq!(answer.body, "null", "{}", answer.body);
6818
6819 let sends = app.store.sends_for_task(&task, 10).await.unwrap();
6820 let reread = sends.iter().find(|s| s.id == send_id).unwrap();
6821 assert_eq!(
6822 reread.state,
6823 SendState::Sent,
6824 "a sent send was touched by a retry"
6825 );
6826}
6827
6828// ---------------------------------------------------------------------------
6829// Send message
6830// ---------------------------------------------------------------------------
6831
6832#[tokio::test]
6833async fn an_admin_sends_a_message_to_one_member() {
6834 let app = App::open().await;
6835 let admin_cookie = admin(&app).await;
6836 let _ = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
6837 let mert_id = app
6838 .store
6839 .user_by_email(&app.workspace_id().await, "emre@iz.sh")
6840 .await
6841 .unwrap()
6842 .unwrap()
6843 .id;
6844
6845 let answer = app
6846 .post(
6847 "/api/send_message",
6848 Some(&admin_cookie),
6849 &[
6850 ("to", &mert_id),
6851 ("subject", "Heads up"),
6852 ("body", "Standup moved to 10."),
6853 ],
6854 )
6855 .await;
6856 assert!(
6857 answer
6858 .location
6859 .as_deref()
6860 .unwrap_or_default()
6861 .contains("saved=send_message"),
6862 "{:?}",
6863 answer.location
6864 );
6865
6866 let sends = app
6867 .store
6868 .mail_queue(10, iz_core::store::FeedPage::Newest)
6869 .await
6870 .unwrap();
6871 let notices: Vec<_> = sends
6872 .iter()
6873 .filter(|send| send.kind == SendKind::Notice)
6874 .collect();
6875 assert_eq!(notices.len(), 1, "{sends:?}");
6876 let notice = notices[0];
6877 assert_eq!(notice.recipient, "emre@iz.sh");
6878 assert_eq!(notice.subject.as_deref(), Some("Heads up"));
6879 assert_eq!(notice.body.as_deref(), Some("Standup moved to 10."));
6880
6881 let queue = app.get("/logs?section=queue", Some(&admin_cookie)).await;
6882 let html = String::from_utf8_lossy(&queue.bytes);
6883 assert!(html.contains("Heads up"), "{html}");
6884}
6885
6886#[tokio::test]
6887async fn an_admin_sends_a_message_to_everyone_and_not_to_themself() {
6888 let app = App::open().await;
6889 let admin_cookie = admin(&app).await;
6890 let _ = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
6891 let _ = invited(&app, &admin_cookie, "quiet@iz.sh", "Quiet", Role::Viewer).await;
6892
6893 let answer = app
6894 .post(
6895 "/api/send_message",
6896 Some(&admin_cookie),
6897 &[
6898 ("to", "everyone"),
6899 ("subject", "All hands"),
6900 ("body", "Board meeting Friday."),
6901 ],
6902 )
6903 .await;
6904 assert!(
6905 answer
6906 .location
6907 .as_deref()
6908 .unwrap_or_default()
6909 .contains("saved=send_message"),
6910 "{:?}",
6911 answer.location
6912 );
6913
6914 let sends = app
6915 .store
6916 .mail_queue(10, iz_core::store::FeedPage::Newest)
6917 .await
6918 .unwrap();
6919 let notices: Vec<_> = sends
6920 .iter()
6921 .filter(|send| send.kind == SendKind::Notice)
6922 .collect();
6923 assert_eq!(notices.len(), 2, "{sends:?}");
6924 assert!(
6925 notices.iter().all(|send| send.recipient != "ada@iz.sh"),
6926 "{sends:?}"
6927 );
6928}
6929
6930#[tokio::test]
6931async fn a_blank_subject_or_body_refuses_and_queues_nothing() {
6932 let app = App::open().await;
6933 let admin_cookie = admin(&app).await;
6934 let _ = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
6935
6936 let answer = app
6937 .post(
6938 "/api/send_message",
6939 Some(&admin_cookie),
6940 &[
6941 ("to", "everyone"),
6942 ("subject", " "),
6943 ("body", "Something"),
6944 ],
6945 )
6946 .await;
6947 assert!(
6948 answer
6949 .location
6950 .as_deref()
6951 .unwrap_or_default()
6952 .contains("refusal=empty-subject&on=send_message"),
6953 "{:?}",
6954 answer.location
6955 );
6956
6957 let answer = app
6958 .post(
6959 "/api/send_message",
6960 Some(&admin_cookie),
6961 &[("to", "everyone"), ("subject", "Subject"), ("body", " ")],
6962 )
6963 .await;
6964 assert!(
6965 answer
6966 .location
6967 .as_deref()
6968 .unwrap_or_default()
6969 .contains("refusal=empty-body&on=send_message"),
6970 "{:?}",
6971 answer.location
6972 );
6973
6974 let sends = app
6975 .store
6976 .mail_queue(10, iz_core::store::FeedPage::Newest)
6977 .await
6978 .unwrap();
6979 assert!(
6980 sends.iter().all(|send| send.kind != SendKind::Notice),
6981 "{sends:?}"
6982 );
6983
6984 let location = answer.location.expect("no redirect");
6985 let page = app.get(&location, Some(&admin_cookie)).await;
6986 let html = String::from_utf8_lossy(&page.bytes);
6987 assert!(html.contains("field-error"), "{html}");
6988}
6989
6990#[tokio::test]
6991async fn a_member_may_not_send_a_message_and_never_sees_the_panel() {
6992 let app = App::open().await;
6993 let admin_cookie = admin(&app).await;
6994 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
6995
6996 let answer = app
6997 .post(
6998 "/api/send_message",
6999 Some(&member),
7000 &[
7001 ("to", "everyone"),
7002 ("subject", "Sneaky"),
7003 ("body", "Should not send"),
7004 ],
7005 )
7006 .await;
7007 assert!(
7008 answer
7009 .location
7010 .as_deref()
7011 .unwrap_or_default()
7012 .contains("refusal=forbidden&on=send_message"),
7013 "{:?}",
7014 answer.location
7015 );
7016
7017 let sends = app
7018 .store
7019 .mail_queue(10, iz_core::store::FeedPage::Newest)
7020 .await
7021 .unwrap();
7022 assert!(
7023 sends.iter().all(|send| send.kind != SendKind::Notice),
7024 "{sends:?}"
7025 );
7026
7027 let page = app.get("/settings", Some(&member)).await;
7028 let html = String::from_utf8_lossy(&page.bytes);
7029 assert!(!html.contains("section=message"), "{html}");
7030 assert!(!html.contains("id=\"message\""), "{html}");
7031}
7032
7033#[tokio::test]
7034async fn an_unknown_recipient_refuses_and_never_broadcasts() {
7035 let app = App::open().await;
7036 let admin_cookie = admin(&app).await;
7037 let _ = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
7038
7039 let answer = app
7040 .post(
7041 "/api/send_message",
7042 Some(&admin_cookie),
7043 &[
7044 ("to", "not-a-real-id"),
7045 ("subject", "Subject"),
7046 ("body", "Body"),
7047 ],
7048 )
7049 .await;
7050 assert_ne!(
7051 answer.status,
7052 StatusCode::INTERNAL_SERVER_ERROR,
7053 "{}",
7054 answer.body
7055 );
7056 assert!(
7057 answer
7058 .location
7059 .as_deref()
7060 .unwrap_or_default()
7061 .contains("refusal=no-such-member&on=send_message"),
7062 "{:?}",
7063 answer.location
7064 );
7065
7066 let sends = app
7067 .store
7068 .mail_queue(10, iz_core::store::FeedPage::Newest)
7069 .await
7070 .unwrap();
7071 assert!(
7072 sends.iter().all(|send| send.kind != SendKind::Notice),
7073 "{sends:?}"
7074 );
7075}
7076
7077/// The markup inside a single tab anchor: found by its `tab=<slug>` href, up
7078/// to that anchor's own closing tag — for asserting a `detail-tab-count`
7079/// span is (or is not) inside the one tab it belongs to, not just somewhere
7080/// on the page.
7081fn tab_anchor<'a>(html: &'a str, slug: &str) -> &'a str {
7082 let needle = format!("&amp;tab={slug}\">");
7083 let (_, after) = html
7084 .split_once(&needle)
7085 .unwrap_or_else(|| panic!("no {slug} tab anchor: {html}"));
7086 after
7087 .split_once("</a>")
7088 .map(|(inner, _)| inner)
7089 .expect("unterminated tab anchor")
7090}
7091
7092#[tokio::test]
7093async fn opening_the_task_with_no_tab_shows_the_task_region_and_the_strip() {
7094 let app = App::open().await;
7095 let admin_cookie = admin(&app).await;
7096 let column = first_column(&app).await;
7097 let task = a_task(&app, &admin_cookie, &column, "Land on the task tab").await;
7098
7099 let page = app
7100 .get(&format!("/?task={task}"), Some(&admin_cookie))
7101 .await;
7102 assert_eq!(page.status, StatusCode::OK);
7103 let html = String::from_utf8_lossy(&page.bytes);
7104 assert!(
7105 html.contains(r#"class="detail-tabs""#),
7106 "no tab strip: {html}"
7107 );
7108 assert!(
7109 html.contains(r#"class="detail-fields""#),
7110 "no task fields grid: {html}"
7111 );
7112 assert!(
7113 !html.contains("comment-composer"),
7114 "composer shown on the task tab: {html}"
7115 );
7116}
7117
7118#[tokio::test]
7119async fn each_tab_renders_only_its_own_region() {
7120 let app = App::open().await;
7121 let admin_cookie = admin(&app).await;
7122 let column = first_column(&app).await;
7123 let task = a_task(&app, &admin_cookie, &column, "Walk every tab").await;
7124
7125 let files = app
7126 .get(&format!("/?task={task}&tab=files"), Some(&admin_cookie))
7127 .await;
7128 let files_html = String::from_utf8_lossy(&files.bytes);
7129 assert!(
7130 files_html.contains("multipart/form-data"),
7131 "no files region: {files_html}"
7132 );
7133 assert!(
7134 !files_html.contains("comment-composer"),
7135 "composer shown on the files tab: {files_html}"
7136 );
7137
7138 let comments = app
7139 .get(&format!("/?task={task}&tab=comments"), Some(&admin_cookie))
7140 .await;
7141 let comments_html = String::from_utf8_lossy(&comments.bytes);
7142 assert!(
7143 comments_html.contains("comment-composer"),
7144 "no composer on the comments tab: {comments_html}"
7145 );
7146
7147 let activity = app
7148 .get(&format!("/?task={task}&tab=activity"), Some(&admin_cookie))
7149 .await;
7150 let activity_html = String::from_utf8_lossy(&activity.bytes);
7151 assert!(
7152 activity_html.contains("activity-stamp"),
7153 "no activity stamp: {activity_html}"
7154 );
7155
7156 let mail = app
7157 .get(&format!("/?task={task}&tab=mail"), Some(&admin_cookie))
7158 .await;
7159 let mail_html = String::from_utf8_lossy(&mail.bytes);
7160 assert!(
7161 mail_html.contains("Notifications"),
7162 "no notifications heading: {mail_html}"
7163 );
7164}
7165
7166#[tokio::test]
7167async fn a_tab_name_it_does_not_know_falls_back_to_the_task_region() {
7168 let app = App::open().await;
7169 let admin_cookie = admin(&app).await;
7170 let column = first_column(&app).await;
7171 let task = a_task(&app, &admin_cookie, &column, "Land on garbage").await;
7172
7173 let page = app
7174 .get(&format!("/?task={task}&tab=zzz"), Some(&admin_cookie))
7175 .await;
7176 assert_eq!(page.status, StatusCode::OK);
7177 let html = String::from_utf8_lossy(&page.bytes);
7178 assert!(
7179 html.contains(r#"class="detail-fields""#),
7180 "garbage tab did not fall back to the task region: {html}"
7181 );
7182}
7183
7184#[tokio::test]
7185async fn the_tab_strip_counts_files_and_comments_and_is_silent_when_there_are_none() {
7186 let app = App::open().await;
7187 let admin_cookie = admin(&app).await;
7188 let column = first_column(&app).await;
7189 let task = a_task(&app, &admin_cookie, &column, "Nothing attached yet").await;
7190
7191 let page = app
7192 .get(&format!("/?task={task}"), Some(&admin_cookie))
7193 .await;
7194 let html = String::from_utf8_lossy(&page.bytes);
7195 assert!(
7196 !tab_anchor(&html, "files").contains("detail-tab-count"),
7197 "count shown with no files: {html}"
7198 );
7199 assert!(
7200 !tab_anchor(&html, "comments").contains("detail-tab-count"),
7201 "count shown with no comments: {html}"
7202 );
7203
7204 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
7205 app.post_multipart(
7206 "/files",
7207 Some(&admin_cookie),
7208 &[("task_id", &task)],
7209 Some(("spec.png", "image/png", &png)),
7210 )
7211 .await;
7212 app.post(
7213 "/api/post_comment",
7214 Some(&admin_cookie),
7215 &[("task_id", &task), ("body", "One comment")],
7216 )
7217 .await;
7218
7219 let page = app
7220 .get(&format!("/?task={task}"), Some(&admin_cookie))
7221 .await;
7222 let html = String::from_utf8_lossy(&page.bytes);
7223 assert!(
7224 tab_anchor(&html, "files").contains(r#"class="detail-tab-count">1<"#),
7225 "no file count of 1: {html}"
7226 );
7227 assert!(
7228 tab_anchor(&html, "comments").contains(r#"class="detail-tab-count">1<"#),
7229 "no comment count of 1: {html}"
7230 );
7231}
7232
7233#[tokio::test]
7234async fn the_title_renders_on_every_tab() {
7235 let app = App::open().await;
7236 let admin_cookie = admin(&app).await;
7237 let column = first_column(&app).await;
7238 let task = a_task(&app, &admin_cookie, &column, "Carry my title everywhere").await;
7239
7240 for tab in ["task", "files"] {
7241 let page = app
7242 .get(&format!("/?task={task}&tab={tab}"), Some(&admin_cookie))
7243 .await;
7244 let html = String::from_utf8_lossy(&page.bytes);
7245 assert!(
7246 html.contains(r#"class="detail-headline""#),
7247 "no headline on tab={tab}: {html}"
7248 );
7249 assert!(
7250 html.contains("Carry my title everywhere"),
7251 "no title text on tab={tab}: {html}"
7252 );
7253 }
7254}
7255
7256#[tokio::test]
7257async fn a_member_who_may_only_read_still_gets_the_tab_strip() {
7258 let app = App::open().await;
7259 let admin_cookie = admin(&app).await;
7260 let member = invited(
7261 &app,
7262 &admin_cookie,
7263 "reads@iz.sh",
7264 "Reader Only",
7265 Role::Member,
7266 )
7267 .await;
7268 let column = first_column(&app).await;
7269 let task = a_task(&app, &admin_cookie, &column, "A member can still see this").await;
7270
7271 let page = app.get(&format!("/?task={task}"), Some(&member)).await;
7272 assert_eq!(page.status, StatusCode::OK);
7273 let html = String::from_utf8_lossy(&page.bytes);
7274 assert!(
7275 html.contains(r#"class="detail-tabs""#),
7276 "no tab strip for a member: {html}"
7277 );
7278}
7279
7280/// A spreadsheet has no browser element behind it: iz reads the workbook
7281/// itself and lays the sheet out as a table, tab strip and all. The upload is
7282/// a real xlsx, so this covers the sniffer, the reader and the view together.
7283#[tokio::test]
7284async fn a_workbook_opens_as_a_table_and_its_other_sheet_is_one_link_away() {
7285 let app = App::open().await;
7286 let admin_cookie = admin(&app).await;
7287 let column = first_column(&app).await;
7288 let task = a_task(&app, &admin_cookie, &column, "Read the book").await;
7289
7290 let book = include_bytes!("fixtures/book.xlsx");
7291 app.post_multipart(
7292 "/files",
7293 Some(&admin_cookie),
7294 &[("task_id", &task)],
7295 Some((
7296 "costs.xlsx",
7297 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
7298 book,
7299 )),
7300 )
7301 .await;
7302 let snapshot = app
7303 .post(
7304 "/api/fetch_task",
7305 Some(&admin_cookie),
7306 &[("task_id", &task)],
7307 )
7308 .await;
7309 let file_id = attachment_id_named(&snapshot.body, "costs.xlsx");
7310
7311 let page = app
7312 .get(
7313 &format!("/?task={task}&file={file_id}"),
7314 Some(&admin_cookie),
7315 )
7316 .await;
7317 assert_eq!(page.status, StatusCode::OK);
7318 let html = String::from_utf8_lossy(&page.bytes);
7319 assert!(html.contains("sheet-table"), "no sheet table: {html}");
7320 assert!(html.contains("Cable"), "a cell's text is missing: {html}");
7321 assert!(html.contains("1250"), "a number is missing: {html}");
7322 assert!(html.contains("Ledger"), "the sheet tab is missing: {html}");
7323 assert!(
7324 html.contains(&format!("file={file_id}&amp;sheet=1")),
7325 "no link to the second sheet: {html}"
7326 );
7327
7328 // The tab strip is navigation, so the second sheet is a page of its own.
7329 let second = app
7330 .get(
7331 &format!("/?task={task}&file={file_id}&sheet=1"),
7332 Some(&admin_cookie),
7333 )
7334 .await;
7335 let second_html = String::from_utf8_lossy(&second.bytes);
7336 assert!(
7337 second_html.contains("Second sheet cell"),
7338 "the second sheet did not render: {second_html}"
7339 );
7340
7341 // A hand-edited sheet index is the first sheet, not an error.
7342 let past_the_end = app
7343 .get(
7344 &format!("/?task={task}&file={file_id}&sheet=99"),
7345 Some(&admin_cookie),
7346 )
7347 .await;
7348 assert!(String::from_utf8_lossy(&past_the_end.bytes).contains("Cable"));
7349}
7350
7351/// A status rule can watch the whole board: the column select's first option
7352/// sends no column, and the rule reads back as a sentence about status
7353/// changing rather than becoming one named column.
7354#[tokio::test]
7355async fn a_status_rule_may_watch_every_column() {
7356 let app = App::open().await;
7357 let admin_cookie = admin(&app).await;
7358
7359 let answer = app
7360 .post(
7361 "/api/create_rule",
7362 Some(&admin_cookie),
7363 &[
7364 ("trigger", "status"),
7365 ("column_id", ""),
7366 ("subject", "It moved"),
7367 ("audience", "assignees"),
7368 ],
7369 )
7370 .await;
7371 assert_eq!(answer.status, StatusCode::SEE_OTHER);
7372 assert_eq!(answer.body, "null", "the rule was refused: {}", answer.body);
7373
7374 let seen = app
7375 .post("/api/current_rules", Some(&admin_cookie), &[])
7376 .await;
7377 assert!(
7378 seen.body.contains("\"when\":\"When status changes\""),
7379 "{}",
7380 seen.body
7381 );
7382 assert!(
7383 seen.body.contains("\"column_id\":null"),
7384 "the every-column rule names no column: {}",
7385 seen.body
7386 );
7387
7388 // The composer offers it: the column select carries the any option, and
7389 // it is the one selected while the rule names no column.
7390 let page = app.get("/rules", Some(&admin_cookie)).await;
7391 let html = String::from_utf8_lossy(&page.bytes);
7392 assert!(html.contains("Any column"), "no any-column option: {html}");
7393}
7394
7395/// The queue says when a retry fires, not just a bare moment: a stamp in the
7396/// future is labelled as the next try, and one already past says the send is
7397/// due rather than naming a time that has been and gone.
7398#[tokio::test]
7399async fn the_queue_says_when_the_next_try_fires() {
7400 let app = App::open().await;
7401 let admin_cookie = admin(&app).await;
7402 let (_task, send_id) = a_task_with_a_notification(&app, &admin_cookie, "Never got there").await;
7403 let now = time::OffsetDateTime::now_utc();
7404
7405 let later = now + time::Duration::hours(2);
7406 app.store
7407 .record_send_refused(&send_id, "timeout", Some(later), now)
7408 .await
7409 .unwrap();
7410 let logs = app
7411 .post("/api/current_logs", Some(&admin_cookie), &[])
7412 .await;
7413 assert!(
7414 logs.body.contains("next try"),
7415 "the queue does not say when the retry fires: {}",
7416 logs.body
7417 );
7418
7419 // Once the moment has passed the row is waiting on the next sweep.
7420 app.store
7421 .record_send_refused(
7422 &send_id,
7423 "timeout",
7424 Some(now - time::Duration::hours(1)),
7425 now,
7426 )
7427 .await
7428 .unwrap();
7429 let logs = app
7430 .post("/api/current_logs", Some(&admin_cookie), &[])
7431 .await;
7432 assert!(
7433 logs.body.contains("\"next_attempt\":\"due\""),
7434 "a retry already owed does not say so: {}",
7435 logs.body
7436 );
7437}
7438
7439/// An admin can set the address mail links point at — the box answers on
7440/// localhost and is reached through a proxy on a public name. A trailing
7441/// slash is trimmed, something that is not an origin is refused, and an empty
7442/// field puts the configured address back.
7443#[tokio::test]
7444async fn an_admin_sets_the_address_mail_links_point_at() {
7445 let app = App::open().await;
7446 let admin_cookie = admin(&app).await;
7447
7448 async fn sender_with(app: &App, admin: &str, public_url: &str) -> Answer {
7449 app.post(
7450 "/api/save_sender",
7451 Some(admin),
7452 &[
7453 ("host", "smtp.fastmail.com"),
7454 ("port", "465"),
7455 ("username", "iz"),
7456 ("password", SENDER_PASSWORD),
7457 ("from_name", "iz"),
7458 ("from_address", "iz@iz.sh"),
7459 ("public_url", public_url),
7460 ],
7461 )
7462 .await
7463 }
7464
7465 let answer = sender_with(&app, &admin_cookie, "https://board.example/").await;
7466 assert!(
7467 answer
7468 .location
7469 .as_deref()
7470 .is_some_and(|location| !location.contains("refusal=")),
7471 "the address was refused: {:?}",
7472 answer.location
7473 );
7474 assert_eq!(
7475 app.store.workspace().await.unwrap().unwrap().public_url,
7476 Some("https://board.example".to_string()),
7477 "the trailing slash was kept"
7478 );
7479
7480 // The field shows what is stored, so a reload does not blank it.
7481 let page = app
7482 .get("/settings?section=outgoing", Some(&admin_cookie))
7483 .await;
7484 let html = String::from_utf8_lossy(&page.bytes);
7485 assert!(html.contains("https://board.example"), "{html}");
7486
7487 let refused = sender_with(&app, &admin_cookie, "board.example").await;
7488 assert!(
7489 refused
7490 .location
7491 .as_deref()
7492 .is_some_and(|location| location.contains("refusal=")),
7493 "a bare host was taken as an origin: {:?}",
7494 refused.location
7495 );
7496 assert_eq!(
7497 app.store.workspace().await.unwrap().unwrap().public_url,
7498 Some("https://board.example".to_string()),
7499 "the refused save wrote anyway"
7500 );
7501
7502 sender_with(&app, &admin_cookie, "").await;
7503 assert_eq!(
7504 app.store.workspace().await.unwrap().unwrap().public_url,
7505 None,
7506 "an empty field did not clear the stored address"
7507 );
7508}
7509
7510/// A sheet is read one window at a time and the pagers move it: down the rows
7511/// and across the columns, each a link like every other overlay state. The
7512/// window's own numbers and letters label the grid, so a page says where it
7513/// sits without being told.
7514#[tokio::test]
7515async fn a_big_sheet_pages_down_its_rows_and_across_its_columns() {
7516 let app = App::open().await;
7517 let admin_cookie = admin(&app).await;
7518 let column = first_column(&app).await;
7519 let task = a_task(&app, &admin_cookie, &column, "Read the big book").await;
7520
7521 let book = include_bytes!("fixtures/wide.xlsx");
7522 app.post_multipart(
7523 "/files",
7524 Some(&admin_cookie),
7525 &[("task_id", &task)],
7526 Some((
7527 "wide.xlsx",
7528 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
7529 book,
7530 )),
7531 )
7532 .await;
7533 let snapshot = app
7534 .post(
7535 "/api/fetch_task",
7536 Some(&admin_cookie),
7537 &[("task_id", &task)],
7538 )
7539 .await;
7540 let file_id = attachment_id_named(&snapshot.body, "wide.xlsx");
7541
7542 let first = app
7543 .get(
7544 &format!("/?task={task}&file={file_id}"),
7545 Some(&admin_cookie),
7546 )
7547 .await;
7548 let html = String::from_utf8_lossy(&first.bytes);
7549 assert!(
7550 html.contains("Col A"),
7551 "the first column is missing: {html}"
7552 );
7553 assert!(!html.contains("Col M"), "the window is not 12 wide: {html}");
7554 assert!(html.contains("A–L / 40"), "no column count: {html}");
7555 assert!(html.contains("1–8 / 8"), "no row count: {html}");
7556 assert!(
7557 html.contains(&format!("file={file_id}&amp;sheet=0&amp;rows=0&amp;cols=1")),
7558 "no step to the next columns: {html}"
7559 );
7560
7561 // Stepping across lands on the next twelve columns, and the grid labels
7562 // them from where the window sits rather than from A.
7563 let across = app
7564 .get(
7565 &format!("/?task={task}&file={file_id}&sheet=0&rows=0&cols=1"),
7566 Some(&admin_cookie),
7567 )
7568 .await;
7569 let html = String::from_utf8_lossy(&across.bytes);
7570 assert!(html.contains("Col M"), "the second window is wrong: {html}");
7571 assert!(html.contains("M–X / 40"), "the count did not move: {html}");
7572 assert!(
7573 html.contains(&format!("file={file_id}&amp;sheet=0&amp;rows=0&amp;cols=0")),
7574 "no step back to the first columns: {html}"
7575 );
7576
7577 // A window nobody links to is the empty one it names, not a redirect and
7578 // not the first page wearing another page's numbers.
7579 let nowhere = app
7580 .get(
7581 &format!("/?task={task}&file={file_id}&sheet=0&rows=99&cols=0"),
7582 Some(&admin_cookie),
7583 )
7584 .await;
7585 let html = String::from_utf8_lossy(&nowhere.bytes);
7586 assert!(html.contains("sheet-table"), "the grid is gone: {html}");
7587 assert!(!html.contains("Col A"), "row 4951 is not row 1: {html}");
7588}
7589
7590// -- the live channel -------------------------------------------------------
7591
7592/// Reads a live connection until it says `needle`, or until `patience` runs
7593/// out, and hands back everything it said. Bounded by the frame it is waiting
7594/// for rather than by a fixed sleep: the positive assertions return the moment
7595/// the announcement lands, and the negative ones spend their whole patience
7596/// proving the silence.
7597async fn live_until(
7598 response: topcoat::router::response::Response<Body>,
7599 needle: &str,
7600 patience: std::time::Duration,
7601) -> String {
7602 use http_body_util::BodyExt;
7603
7604 let mut body = response.into_body();
7605 let mut heard = String::new();
7606 let deadline = tokio::time::Instant::now() + patience;
7607 loop {
7608 let left = deadline.saturating_duration_since(tokio::time::Instant::now());
7609 if left.is_zero() {
7610 return heard;
7611 }
7612 match tokio::time::timeout(left, body.frame()).await {
7613 Err(_) => return heard,
7614 Ok(None) => return heard,
7615 Ok(Some(Err(_))) => return heard,
7616 Ok(Some(Ok(frame))) => {
7617 if let Some(chunk) = frame.data_ref() {
7618 heard.push_str(&String::from_utf8_lossy(chunk));
7619 if heard.contains(needle) {
7620 return heard;
7621 }
7622 }
7623 }
7624 }
7625 }
7626}
7627
7628/// A browser nobody signed in gets no feed at all.
7629#[tokio::test]
7630async fn the_live_channel_refuses_a_signed_out_caller() {
7631 let app = App::open().await;
7632 admin(&app).await;
7633 let response = app.live_open(None).await;
7634 assert_eq!(response.status(), 401);
7635}
7636
7637/// The role gate reaches the channel: a member is never told that an
7638/// admin-only surface moved, because being told is itself knowing something
7639/// about it. The assertion is on the raw bytes on purpose — the topic name
7640/// must not appear at all, not merely go unrendered.
7641#[tokio::test]
7642async fn the_live_channel_never_names_an_admin_surface_to_a_member() {
7643 let app = App::open().await;
7644 let boss = admin(&app).await;
7645 let member = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await;
7646
7647 let member_feed = app.live_open(Some(&member)).await;
7648 let admin_feed = app.live_open(Some(&boss)).await;
7649
7650 // An admin-only write: a mail rule.
7651 let workspace_id = app.workspace_id().await;
7652 let board = app.store.board(&workspace_id).await.unwrap().unwrap().id;
7653 app.store
7654 .create_mail_rule(
7655 &board,
7656 &iz_core::store::Trigger::Created,
7657 "Something happened",
7658 iz_core::store::Audience::Board,
7659 time::OffsetDateTime::now_utc(),
7660 false,
7661 )
7662 .await
7663 .unwrap();
7664
7665 // The admin's stream is the clock: once it has the announcement, the
7666 // member's has had every chance to receive one too.
7667 let heard_by_admin = live_until(admin_feed, "rules", std::time::Duration::from_secs(10)).await;
7668 let heard_by_member =
7669 live_until(member_feed, "rules", std::time::Duration::from_millis(500)).await;
7670
7671 assert!(
7672 !heard_by_member.contains("rules"),
7673 "a member was told about the rules: {heard_by_member}"
7674 );
7675 assert!(
7676 heard_by_admin.contains("rules"),
7677 "the admin was not told about the rules: {heard_by_admin}"
7678 );
7679}
7680
7681/// A surface everybody can see is announced to everybody.
7682#[tokio::test]
7683async fn the_live_channel_announces_a_shared_surface_to_a_member() {
7684 let app = App::open().await;
7685 let boss = admin(&app).await;
7686 let member = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await;
7687 let column = first_column(&app).await;
7688
7689 let feed = app.live_open(Some(&member)).await;
7690 a_task(&app, &boss, &column, "Ship the exporter").await;
7691 let heard = live_until(feed, "board", std::time::Duration::from_secs(10)).await;
7692
7693 assert!(heard.contains("board"), "no board announcement: {heard}");
7694}
7695
7696/// The guard is what stops a soft navigation stacking a second `EventSource`
7697/// on the tab: `swap()` re-executes every script it swaps in, so the script
7698/// must refuse to run twice. Emitted once, and only once, per page.
7699#[tokio::test]
7700async fn the_live_script_is_emitted_once_and_guarded() {
7701 let app = App::open().await;
7702 let boss = admin(&app).await;
7703 let html = String::from_utf8(app.get("/", Some(&boss)).await.bytes).unwrap();
7704
7705 assert_eq!(
7706 html.matches("__izLive").count(),
7707 2,
7708 "the live script should appear once, as a guard read and a guard set"
7709 );
7710 assert!(
7711 html.contains("EventSource('/api/live')"),
7712 "no live connection"
7713 );
7714}
7715
7716/// A signed-out page opens no stream: `/api/live` refuses it, and a tab on the
7717/// sign-in screen would otherwise reconnect against that refusal forever.
7718#[tokio::test]
7719async fn a_signed_out_page_opens_no_live_connection() {
7720 let app = App::open().await;
7721 admin(&app).await;
7722 let html = String::from_utf8(app.get("/", None).await.bytes).unwrap();
7723 assert!(
7724 !html.contains("__izLive"),
7725 "the sign-in page carries the live script"
7726 );
7727}
7728
7729/// Text that goes stale on the clock rather than on a write carries the mark
7730/// the tick looks for — a queued mail's next-try time is the case that started
7731/// this: nothing writes when the minute changes.
7732#[tokio::test]
7733async fn a_queued_mails_next_try_is_marked_for_the_tick() {
7734 let app = App::open().await;
7735 let boss = admin(&app).await;
7736 app.store
7737 .queue_notice(
7738 "bo@iz.sh",
7739 "Your \u{130}z sign-in link",
7740 "body",
7741 time::OffsetDateTime::now_utc(),
7742 )
7743 .await
7744 .unwrap();
7745 let html = String::from_utf8(app.get("/logs?section=queue", Some(&boss)).await.bytes).unwrap();
7746 assert!(
7747 html.contains("data-tick"),
7748 "the queue's next-try stamp is not marked for the tick"
7749 );
7750}
7751
7752/// The lightweight probe the live script's error path asks. A live session
7753/// gets a bodyless yes; no cookie, or a session im no longer vouches for,
7754/// gets a plain 401 — so a dropped stream can be told apart from a signed-
7755/// out tab without fetching a page of HTML to learn it.
7756#[tokio::test]
7757async fn the_me_probe_answers_yes_only_to_a_live_session() {
7758 let app = App::open().await;
7759 let boss = admin(&app).await;
7760
7761 let live = app.get("/api/me", Some(&boss)).await;
7762 assert_eq!(live.status, StatusCode::NO_CONTENT);
7763 assert!(live.bytes.is_empty(), "the probe answered a body");
7764
7765 let stranger = app.get("/api/me", None).await;
7766 assert_eq!(stranger.status, StatusCode::UNAUTHORIZED);
7767
7768 // The session revoked in im: once the fake stops vouching for the
7769 // token, the probe refuses with no page to fetch first.
7770 app.fake.tokens.lock().clear();
7771 let revoked = app.get("/api/me", Some(&boss)).await;
7772 assert_eq!(revoked.status, StatusCode::UNAUTHORIZED);
7773}
7774
7775/// A session revocation heard off the directory stream is told to the whole
7776/// workspace — which session died is im's knowledge alone, so no connection
7777/// is named and no tab is sent away; every tab's own refetch, which
7778/// re-introspects per request, is what sorts out who is still signed in.
7779/// A tab whose other session survived therefore keeps its place.
7780#[tokio::test]
7781async fn a_session_revocation_announces_the_member_surface_to_everyone() {
7782 let app = App::open().await;
7783 let boss = admin(&app).await;
7784 let bo = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await;
7785
7786 let member_feed = app.live_open(Some(&bo)).await;
7787 let admin_feed = app.live_open(Some(&boss)).await;
7788
7789 apply_frame(
7790 &app.store,
7791 StreamFrame::Revoked {
7792 sub: "im-bo@iz.sh".into(),
7793 },
7794 )
7795 .await;
7796
7797 let heard_by_admin =
7798 live_until(admin_feed, "members", std::time::Duration::from_secs(10)).await;
7799 assert!(
7800 heard_by_admin.contains("members"),
7801 "no members announcement: {heard_by_admin}"
7802 );
7803 let heard_by_member = live_until(
7804 member_feed,
7805 "members",
7806 std::time::Duration::from_millis(500),
7807 )
7808 .await;
7809 assert!(
7810 heard_by_member.contains("members"),
7811 "the member was not told the member surface moved: {heard_by_member}"
7812 );
7813 assert!(
7814 !heard_by_admin.contains("revoked") && !heard_by_member.contains("revoked"),
7815 "a session revocation named a connection: {heard_by_admin} / {heard_by_member}"
7816 );
7817}
7818
7819/// A profile arriving `disabled` is a user-level kill: the local row is
7820/// disabled through the same store path an admin's hand uses, the
7821/// account's own tab is named with the `revoked` topic — and only that
7822/// tab — and the row's next probe reads as signed out, exactly as any
7823/// refetch would find it.
7824#[tokio::test]
7825async fn a_disabled_member_is_named_once_and_signed_out_everywhere() {
7826 let app = App::open().await;
7827 let boss = admin(&app).await;
7828 let bo = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await;
7829
7830 let member_feed = app.live_open(Some(&bo)).await;
7831 let admin_feed = app.live_open(Some(&boss)).await;
7832
7833 apply_frame(
7834 &app.store,
7835 StreamFrame::Profile(StreamMember {
7836 sub: "im-bo@iz.sh".into(),
7837 email: "bo@iz.sh".into(),
7838 name: "Bo".into(),
7839 admin: false,
7840 photo_version: 0,
7841 timezone: "UTC+03:00".into(),
7842 disabled: true,
7843 }),
7844 )
7845 .await;
7846
7847 // The account's own connection is named — the goodbye frame the client
7848 // answers with a hard redirect.
7849 let goodbye = live_until(member_feed, "revoked", std::time::Duration::from_secs(10)).await;
7850 assert!(
7851 goodbye.contains("revoked"),
7852 "the disabled member's tab was not named: {goodbye}"
7853 );
7854
7855 // The workspace heard the member surface move; nobody else was named.
7856 let heard_by_admin =
7857 live_until(admin_feed, "members", std::time::Duration::from_secs(10)).await;
7858 assert!(
7859 heard_by_admin.contains("members"),
7860 "no members announcement: {heard_by_admin}"
7861 );
7862 assert!(
7863 !heard_by_admin.contains("revoked"),
7864 "an uninvolved tab was named: {heard_by_admin}"
7865 );
7866
7867 // The row itself, and the seam every refetch would hit.
7868 let user = app
7869 .store
7870 .user_by_sub("im-bo@iz.sh")
7871 .await
7872 .unwrap()
7873 .expect("the disabled member had no local row");
7874 assert!(user.disabled);
7875 assert_eq!(
7876 app.get("/api/me", Some(&bo)).await.status,
7877 StatusCode::UNAUTHORIZED
7878 );
7879}
7880
7881/// im owns the account's life both ways: the same stream that kills the
7882/// row brings it back. A disable lands, then a re-enable — the local flag
7883/// follows each, and the member's own probe reads signed-in again, with
7884/// no revoked naming on the way back in.
7885#[tokio::test]
7886async fn a_reenabled_member_is_signed_back_in() {
7887 let app = App::open().await;
7888 let _boss = admin(&app).await;
7889 let bo = member(&app, "bo@iz.sh", "Bo").await;
7890
7891 let disabled = StreamMember {
7892 sub: "im-bo@iz.sh".into(),
7893 email: "bo@iz.sh".into(),
7894 name: "Bo".into(),
7895 admin: false,
7896 photo_version: 0,
7897 timezone: "UTC+03:00".into(),
7898 disabled: true,
7899 };
7900 apply_frame(&app.store, StreamFrame::Profile(disabled.clone())).await;
7901 assert!(
7902 app.store
7903 .user_by_sub("im-bo@iz.sh")
7904 .await
7905 .unwrap()
7906 .expect("no local row")
7907 .disabled,
7908 "the stream did not disable the row"
7909 );
7910
7911 let enabled = StreamMember {
7912 disabled: false,
7913 ..disabled
7914 };
7915 apply_frame(&app.store, StreamFrame::Profile(enabled)).await;
7916 assert!(
7917 !app.store
7918 .user_by_sub("im-bo@iz.sh")
7919 .await
7920 .unwrap()
7921 .expect("no local row")
7922 .disabled,
7923 "the stream did not re-enable the row"
7924 );
7925 assert_eq!(
7926 app.get("/api/me", Some(&bo)).await.status,
7927 StatusCode::NO_CONTENT
7928 );
7929}
7930
7931/// A live update changes only what actually changed. It morphs the fetched
7932/// document onto the live one instead of replacing the body, which is what
7933/// leaves an open dropdown open, a caret where it was and a half-typed comment
7934/// intact — not because any of those is special-cased, but because nothing
7935/// touched them. Asserted here so a refactor back to a wholesale replace fails
7936/// loudly rather than quietly making the app unusable while anyone is typing.
7937#[tokio::test]
7938async fn a_live_update_morphs_rather_than_replacing_the_page() {
7939 let app = App::open().await;
7940 let boss = admin(&app).await;
7941 let html = String::from_utf8(app.get("/", Some(&boss)).await.bytes).unwrap();
7942
7943 assert!(
7944 html.contains("function morph("),
7945 "no morph: the live path replaces the page"
7946 );
7947 assert!(
7948 html.contains("swap(t, r.url, false, false, true)"),
7949 "the live refresh does not ask for a morphing swap"
7950 );
7951 // The dropdown's trigger and panel are built by script and are in no
7952 // server response; a morph that did not know that would delete them.
7953 assert!(
7954 html.contains("function clientMade(") && html.contains("dd-panel"),
7955 "the morph would delete the dropdown's own nodes as strays"
7956 );
7957 // Navigations and form posts must still replace: restoring a sent comment
7958 // over the server's cleared box would look like the message never went.
7959 assert!(
7960 html.contains("document.body.replaceChildren()"),
7961 "the full-replace path is gone, so form posts would carry stale state"
7962 );
7963 assert!(
7964 html.contains("captureFields"),
7965 "the swap captures no field state"
7966 );
7967 assert!(
7968 html.contains("restoreFields"),
7969 "the swap restores no field state"
7970 );
7971}
7972
7973/// A promise about the future is shown to the second. A retry that says 16:42
7974/// but fires at 16:42:47 reads as forty-seven seconds of broken clock to
7975/// whoever is watching one; the queue names the second it means.
7976#[tokio::test]
7977async fn the_queues_next_try_is_shown_to_the_second() {
7978 let app = App::open().await;
7979 let boss = admin(&app).await;
7980 app.store
7981 .queue_notice(
7982 "bo@iz.sh",
7983 "Subject",
7984 "body",
7985 time::OffsetDateTime::now_utc() + time::Duration::hours(1),
7986 )
7987 .await
7988 .unwrap();
7989
7990 let html = String::from_utf8(app.get("/logs?section=queue", Some(&boss)).await.bytes).unwrap();
7991 let (_, after) = html
7992 .split_once("rule-stamp")
7993 .expect("no next-try stamp on the queue");
7994 let stamp: String = after.chars().take(60).collect();
7995 // hh:mm:ss — three groups, not two.
7996 let seconds = stamp
7997 .split(|c: char| !c.is_ascii_digit() && c != ':')
7998 .find(|part| part.matches(':').count() == 2);
7999 assert!(
8000 seconds.is_some(),
8001 "the next-try stamp is not shown to the second: {stamp}"
8002 );
8003}
8004
8005/// The chip reports what the server said, not what the form contains. A
8006/// refusal shows the server's own words, because "535 authentication failed"
8007/// is something an admin can act on and a grey chip is not.
8008#[tokio::test]
8009async fn a_refused_handshake_is_shown_with_what_the_server_said() {
8010 let app = App::open().await;
8011 let admin_cookie = admin(&app).await;
8012 assert!(sender_saved(&app, &admin_cookie).await);
8013
8014 let workspace = app.workspace_id().await;
8015 app.store
8016 .record_sender_check(
8017 &workspace,
8018 iz_core::store::SenderCheck {
8019 at: time::OffsetDateTime::now_utc(),
8020 took_ms: 0,
8021 error: Some("535 authentication failed".into()),
8022 },
8023 )
8024 .await
8025 .unwrap();
8026
8027 let html = String::from_utf8(
8028 app.get("/settings?section=outgoing", Some(&admin_cookie))
8029 .await
8030 .bytes,
8031 )
8032 .unwrap();
8033 assert!(html.contains("Refused"), "{html}");
8034 assert!(
8035 html.contains("535 authentication failed"),
8036 "the server's words are not on the page: {html}"
8037 );
8038 assert!(
8039 !html.contains("chip-connected"),
8040 "a refusal rendered as connected"
8041 );
8042}
8043
8044/// A handshake that worked says when, because the claim is about a moment: a
8045/// password rotated an hour later is not something the panel can know.
8046#[tokio::test]
8047async fn a_passed_handshake_says_when_it_passed() {
8048 let app = App::open().await;
8049 let admin_cookie = admin(&app).await;
8050 assert!(sender_saved(&app, &admin_cookie).await);
8051
8052 let workspace = app.workspace_id().await;
8053 app.store
8054 .record_sender_check(
8055 &workspace,
8056 iz_core::store::SenderCheck {
8057 at: time::OffsetDateTime::now_utc(),
8058 took_ms: 84,
8059 error: None,
8060 },
8061 )
8062 .await
8063 .unwrap();
8064
8065 let html = String::from_utf8(
8066 app.get("/settings?section=outgoing", Some(&admin_cookie))
8067 .await
8068 .bytes,
8069 )
8070 .unwrap();
8071 assert!(html.contains("chip-connected"), "{html}");
8072 assert!(html.contains("Connected"), "{html}");
8073}
8074
8075/// Dialling the mail server is an admin's business.
8076#[tokio::test]
8077async fn a_member_may_not_check_the_sender() {
8078 let app = App::open().await;
8079 let boss = admin(&app).await;
8080 let member = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await;
8081 let answer = app.post("/api/check_sender", Some(&member), &[]).await;
8082 assert_ne!(
8083 answer.body, "null",
8084 "a member was allowed to dial the server"
8085 );
8086}
8087
8088// --- tags -------------------------------------------------------------------
8089
8090/// Makes a tag over HTTP and hands the store row back — the tests need the
8091/// id, and the mutation itself is still a real post.
8092async fn a_tag(app: &App, cookie: &str, name: &str) -> iz_core::store::Tag {
8093 let answer = app
8094 .post("/api/create_tag", Some(cookie), &[("name", name)])
8095 .await;
8096 assert_eq!(answer.body, "null", "the tag was refused: {}", answer.body);
8097 let workspace_id = app.workspace_id().await;
8098 let board = app
8099 .store
8100 .board(&workspace_id)
8101 .await
8102 .unwrap()
8103 .expect("no board");
8104 app.store
8105 .tags(&board.id)
8106 .await
8107 .unwrap()
8108 .into_iter()
8109 .find(|tag| tag.name == name)
8110 .expect("the new tag is not on the board")
8111}
8112
8113#[tokio::test]
8114async fn a_non_admin_cannot_create_rename_delete_or_move_a_tag() {
8115 let app = App::open().await;
8116 let admin_cookie = admin(&app).await;
8117 let member = invited(&app, &admin_cookie, "mem@iz.sh", "Mem Ber", Role::Member).await;
8118
8119 let create = app
8120 .post("/api/create_tag", Some(&member), &[("name", "Sneak")])
8121 .await;
8122 assert!(create.body.contains("Forbidden"), "{}", create.body);
8123 let rename = app
8124 .post(
8125 "/api/rename_tag",
8126 Some(&member),
8127 &[("tag_id", "t1"), ("name", "Sneak")],
8128 )
8129 .await;
8130 assert!(rename.body.contains("Forbidden"), "{}", rename.body);
8131 let delete = app
8132 .post("/api/delete_tag", Some(&member), &[("tag_id", "t1")])
8133 .await;
8134 assert!(delete.body.contains("Forbidden"), "{}", delete.body);
8135 let move_it = app
8136 .post(
8137 "/api/move_tag",
8138 Some(&member),
8139 &[("tag_id", "t1"), ("direction", "up")],
8140 )
8141 .await;
8142 assert!(move_it.body.contains("Forbidden"), "{}", move_it.body);
8143}
8144
8145#[tokio::test]
8146async fn a_viewer_cannot_set_a_task_tag() {
8147 let app = App::open().await;
8148 let admin_cookie = admin(&app).await;
8149 let viewer = invited(&app, &admin_cookie, "hush@iz.sh", "Hush Rao", Role::Viewer).await;
8150 let column = first_column(&app).await;
8151 let task = a_task(&app, &admin_cookie, &column, "Label me not").await;
8152 let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
8153
8154 let answer = app
8155 .post(
8156 "/api/set_task_tag",
8157 Some(&viewer),
8158 &[("task_id", &task), ("tag_id", &aurora.id)],
8159 )
8160 .await;
8161 assert!(answer.body.contains("Forbidden"), "{}", answer.body);
8162}
8163
8164#[tokio::test]
8165async fn the_task_modal_lists_every_tag_and_names_the_current_one() {
8166 let app = App::open().await;
8167 let admin_cookie = admin(&app).await;
8168 let column = first_column(&app).await;
8169 let task = a_task(&app, &admin_cookie, &column, "Sort into color").await;
8170 let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
8171
8172 let workspace_id = app.workspace_id().await;
8173 let board = app
8174 .store
8175 .board(&workspace_id)
8176 .await
8177 .unwrap()
8178 .expect("no board");
8179 let default_id = app
8180 .store
8181 .tags(&board.id)
8182 .await
8183 .unwrap()
8184 .into_iter()
8185 .find(|tag| tag.is_default)
8186 .expect("no default tag")
8187 .id;
8188 let selected = |html: &str, id: &str| html.contains(&format!(r#"value="{id}" selected"#));
8189
8190 let page = String::from_utf8(
8191 app.get(&format!("/?task={task}"), Some(&admin_cookie))
8192 .await
8193 .bytes,
8194 )
8195 .unwrap();
8196 assert!(
8197 page.contains(r#"name="tag_id""#),
8198 "no tag field in the modal: {page}"
8199 );
8200 assert!(
8201 page.contains("General"),
8202 "the default tag is not offered: {page}"
8203 );
8204 assert!(
8205 page.contains("Aurora"),
8206 "the new tag is not offered: {page}"
8207 );
8208 assert!(
8209 selected(&page, &default_id),
8210 "the current tag is not named: {page}"
8211 );
8212 assert!(
8213 !selected(&page, &aurora.id),
8214 "an unchosen tag reads as current: {page}"
8215 );
8216
8217 let switched = app
8218 .post(
8219 "/api/set_task_tag",
8220 Some(&admin_cookie),
8221 &[("task_id", &task), ("tag_id", &aurora.id)],
8222 )
8223 .await;
8224 assert_eq!(
8225 switched.body, "null",
8226 "the switch was refused: {}",
8227 switched.body
8228 );
8229
8230 let page = String::from_utf8(
8231 app.get(&format!("/?task={task}"), Some(&admin_cookie))
8232 .await
8233 .bytes,
8234 )
8235 .unwrap();
8236 assert!(
8237 selected(&page, &aurora.id),
8238 "the switch did not name Aurora: {page}"
8239 );
8240 assert!(
8241 !selected(&page, &default_id),
8242 "the old tag still reads current: {page}"
8243 );
8244}
8245
8246#[tokio::test]
8247async fn the_board_tag_filter_narrows_cards_and_an_unknown_tag_falls_back_to_all() {
8248 let app = App::open().await;
8249 let admin_cookie = admin(&app).await;
8250 let column = first_column(&app).await;
8251 let first = a_task(&app, &admin_cookie, &column, "Aurora work").await;
8252 let second = a_task(&app, &admin_cookie, &column, "Boreal work").await;
8253 let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
8254 let boreal = a_tag(&app, &admin_cookie, "Boreal").await;
8255
8256 let switched = app
8257 .post(
8258 "/api/set_task_tag",
8259 Some(&admin_cookie),
8260 &[("task_id", &second), ("tag_id", &boreal.id)],
8261 )
8262 .await;
8263 assert_eq!(
8264 switched.body, "null",
8265 "the switch was refused: {}",
8266 switched.body
8267 );
8268
8269 let tagged = app
8270 .post(
8271 "/api/set_task_tag",
8272 Some(&admin_cookie),
8273 &[("task_id", &first), ("tag_id", &aurora.id)],
8274 )
8275 .await;
8276 assert_eq!(
8277 tagged.body, "null",
8278 "the first switch was refused: {}",
8279 tagged.body
8280 );
8281
8282 let filtered = String::from_utf8(
8283 app.get(&format!("/?tag={}", aurora.id), Some(&admin_cookie))
8284 .await
8285 .bytes,
8286 )
8287 .unwrap();
8288 assert!(
8289 filtered.contains("Aurora work"),
8290 "the tagged card is gone: {filtered}"
8291 );
8292 assert!(
8293 !filtered.contains("Boreal work"),
8294 "the other card did not filter out: {filtered}"
8295 );
8296
8297 let everything =
8298 String::from_utf8(app.get("/?tag=bogus", Some(&admin_cookie)).await.bytes).unwrap();
8299 assert!(
8300 everything.contains("Aurora work") && everything.contains("Boreal work"),
8301 "an unknown tag did not fall back to all: {everything}"
8302 );
8303 assert!(
8304 everything.contains("General"),
8305 "the default tag is not an option in the filter: {everything}"
8306 );
8307}
8308
8309#[tokio::test]
8310async fn the_default_tag_cannot_be_deleted_and_ships_no_delete_button() {
8311 let app = App::open().await;
8312 let admin_cookie = admin(&app).await;
8313 let _aurora = a_tag(&app, &admin_cookie, "Aurora").await;
8314
8315 let workspace_id = app.workspace_id().await;
8316 let board = app
8317 .store
8318 .board(&workspace_id)
8319 .await
8320 .unwrap()
8321 .expect("no board");
8322 let default_id = app
8323 .store
8324 .tags(&board.id)
8325 .await
8326 .unwrap()
8327 .into_iter()
8328 .find(|tag| tag.is_default)
8329 .expect("no default tag")
8330 .id;
8331
8332 let refused = app
8333 .post(
8334 "/api/delete_tag",
8335 Some(&admin_cookie),
8336 &[("tag_id", &default_id)],
8337 )
8338 .await;
8339 assert!(refused.body.contains("Unavailable"), "{}", refused.body);
8340
8341 let page = String::from_utf8(app.get("/tags", Some(&admin_cookie)).await.bytes).unwrap();
8342 assert_eq!(
8343 page.matches(r#"action="/api/delete_tag""#).count(),
8344 1,
8345 "the default tag's row ships a delete control: {page}"
8346 );
8347 assert!(
8348 page.contains("Aurora"),
8349 "the created tag is not listed: {page}"
8350 );
8351}
8352
8353/// A tag with cards on it stays: no delete control on its row, and the call
8354/// itself refused by name if somebody posts it anyway. Emptying it is what
8355/// makes it deletable.
8356#[tokio::test]
8357async fn a_tag_with_cards_on_it_cannot_be_deleted() {
8358 let app = App::open().await;
8359 let admin_cookie = admin(&app).await;
8360 let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
8361 let workspace_id = app.workspace_id().await;
8362 let board = app
8363 .store
8364 .board(&workspace_id)
8365 .await
8366 .unwrap()
8367 .expect("no board");
8368 let open = app.store.columns(&board.id).await.unwrap()[0].id.clone();
8369 let admin_id = app
8370 .store
8371 .users(&workspace_id)
8372 .await
8373 .unwrap()
8374 .into_iter()
8375 .find(|user| user.role == Role::Admin)
8376 .unwrap()
8377 .id;
8378 let task = a_task_by(&app, &board.id, &open, "Hold the door", &admin_id).await;
8379 app.store.set_task_tag(&task, &aurora.id).await.unwrap();
8380
8381 let page = String::from_utf8(app.get("/tags", Some(&admin_cookie)).await.bytes).unwrap();
8382 assert_eq!(
8383 page.matches(r#"action="/api/delete_tag""#).count(),
8384 0,
8385 "a tag with a card on it still offers a delete: {page}"
8386 );
8387 assert!(
8388 page.contains(r#"<span class="tag-count">1</span>"#),
8389 "the row does not say how many cards are on it: {page}"
8390 );
8391
8392 let refused = app
8393 .post(
8394 "/api/delete_tag",
8395 Some(&admin_cookie),
8396 &[("tag_id", &aurora.id)],
8397 )
8398 .await;
8399 assert!(
8400 refused.body.contains("TagInUse"),
8401 "the refusal does not name itself: {}",
8402 refused.body
8403 );
8404 assert_eq!(
8405 app.store.tags(&board.id).await.unwrap().len(),
8406 2,
8407 "the tag went anyway"
8408 );
8409
8410 // Moved off it, the tag is deletable again — control and call both.
8411 let default_id = app
8412 .store
8413 .tags(&board.id)
8414 .await
8415 .unwrap()
8416 .into_iter()
8417 .find(|tag| tag.is_default)
8418 .unwrap()
8419 .id;
8420 app.store.set_task_tag(&task, &default_id).await.unwrap();
8421 let page = String::from_utf8(app.get("/tags", Some(&admin_cookie)).await.bytes).unwrap();
8422 assert_eq!(page.matches(r#"action="/api/delete_tag""#).count(), 1);
8423 let gone = app
8424 .post(
8425 "/api/delete_tag",
8426 Some(&admin_cookie),
8427 &[("tag_id", &aurora.id)],
8428 )
8429 .await;
8430 assert!(!gone.body.contains("TagInUse"), "{}", gone.body);
8431 assert_eq!(app.store.tags(&board.id).await.unwrap().len(), 1);
8432}
8433
8434/// An open live stream must not be something the shutdown has to wait out.
8435///
8436/// The server stops accepting connections and then gives in-flight requests
8437/// thirty seconds to finish. A live stream intends to sit there for the whole
8438/// window, and every open tab is one, so before this the answer to Ctrl+C was
8439/// a thirty-second pause — measured at 30.00s with three tabs open, 0.003s
8440/// after. The stream is told, and it ends.
8441#[tokio::test]
8442async fn a_live_stream_ends_when_the_server_is_told_to_stop() {
8443 use http_body_util::BodyExt;
8444
8445 let app = App::open().await;
8446 let admin_cookie = admin(&app).await;
8447 let mut body = app.live_open(Some(&admin_cookie)).await.into_body();
8448
8449 // It is open and it is staying open: nothing has changed, so a read now
8450 // finds nothing to say.
8451 assert!(
8452 tokio::time::timeout(std::time::Duration::from_millis(200), body.frame())
8453 .await
8454 .is_err(),
8455 "the stream ended on its own before anything asked it to"
8456 );
8457
8458 app.stop.send(true).unwrap();
8459
8460 // The window is ten seconds and the patience here is one, so a pass cannot
8461 // be the window expiring.
8462 let ended = tokio::time::timeout(std::time::Duration::from_secs(1), async {
8463 while let Some(Ok(_)) = body.frame().await {}
8464 })
8465 .await;
8466 assert!(ended.is_ok(), "the stream outlived the stop");
8467}
8468// --- profile page -----------------------------------------------------------
8469
8470/// One task row id, for the profile fixture. Fixture setup goes through the
8471/// store directly, the way `record_sender_check`'s test does.
8472async fn a_task_by(
8473 app: &App,
8474 board_id: &str,
8475 column_id: &str,
8476 title: &str,
8477 creator: &str,
8478) -> String {
8479 app.store
8480 .create_task(iz_core::store::NewTask {
8481 board_id,
8482 column_id,
8483 parent_id: None,
8484 title,
8485 description: "",
8486 deadline: None,
8487 clock_at: None,
8488 created_by: creator,
8489 })
8490 .await
8491 .unwrap()
8492 .row
8493 .id
8494}
8495
8496/// Two tasks on Mem's plate, one finished under her, three she opened, four
8497/// comments — the numbers the profile page has to show: 2 / 1 / 3 / 4.
8498async fn profile_counts_fixture(app: &App, member: &str, admin: &str) {
8499 let workspace = app.workspace_id().await;
8500 let board = app
8501 .store
8502 .board(&workspace)
8503 .await
8504 .unwrap()
8505 .expect("no board");
8506 let columns = app.store.columns(&board.id).await.unwrap();
8507 let open = columns
8508 .iter()
8509 .find(|column| !column.is_done)
8510 .expect("no open column")
8511 .id
8512 .clone();
8513 let done = columns
8514 .iter()
8515 .find(|column| column.is_done)
8516 .expect("no done column")
8517 .id
8518 .clone();
8519 let now = time::OffsetDateTime::now_utc();
8520
8521 let hold = a_task_by(app, &board.id, &open, "Hold the door", admin).await;
8522 app.store.assign_task(&hold, member).await.unwrap();
8523 let other = a_task_by(app, &board.id, &open, "Oil the hinges", admin).await;
8524 app.store.assign_task(&other, member).await.unwrap();
8525 let finished = a_task_by(app, &board.id, &open, "Paint the frame", admin).await;
8526 app.store.assign_task(&finished, member).await.unwrap();
8527 app.store
8528 .move_task(&finished, &open, &done, admin, now)
8529 .await
8530 .unwrap();
8531 for title in ["Sweep", "Mop", "Dust"] {
8532 a_task_by(app, &board.id, &open, title, member).await;
8533 }
8534 for _ in 0..4 {
8535 app.store
8536 .add_comment(&hold, member, "a note", now)
8537 .await
8538 .unwrap();
8539 }
8540}
8541
8542#[tokio::test]
8543async fn a_member_may_read_another_members_profile_name_address_and_counts() {
8544 let app = App::open().await;
8545 let admin_cookie = admin(&app).await;
8546 invited(&app, &admin_cookie, "mem@iz.sh", "Mem Ber", Role::Member).await;
8547 let reader = invited(&app, &admin_cookie, "ivy@iz.sh", "Ivy Lear", Role::Member).await;
8548 let mem_id = user_id(&app, "mem@iz.sh").await;
8549 let admin_id = app
8550 .store
8551 .users(&app.workspace_id().await)
8552 .await
8553 .unwrap()
8554 .into_iter()
8555 .find(|user| user.role == Role::Admin)
8556 .unwrap()
8557 .id;
8558 profile_counts_fixture(&app, &mem_id, &admin_id).await;
8559
8560 let page = app.get(&format!("/people/{mem_id}"), Some(&reader)).await;
8561 assert_eq!(page.status.as_u16(), 200);
8562 let html = String::from_utf8(page.bytes).unwrap();
8563 assert!(html.contains("Mem Ber"), "{html}");
8564 assert!(html.contains("mem@iz.sh"), "{html}");
8565 for count in [2, 1, 3, 4] {
8566 assert_eq!(
8567 html.matches(&format!(">{count}</dd>")).count(),
8568 1,
8569 "the {count} stat is not on the page once: {html}"
8570 );
8571 }
8572}
8573
8574/// Every fact on a profile sits in a named cell.
8575#[tokio::test]
8576async fn a_profile_names_its_fields() {
8577 let app = App::open().await;
8578 let admin_cookie = admin(&app).await;
8579 invited(&app, &admin_cookie, "mem@iz.sh", "Mem Ber", Role::Member).await;
8580 let mem_id = user_id(&app, "mem@iz.sh").await;
8581
8582 let page = app
8583 .get(&format!("/people/{mem_id}"), Some(&admin_cookie))
8584 .await;
8585 assert_eq!(page.status.as_u16(), 200);
8586 let html = String::from_utf8(page.bytes).unwrap();
8587 for label in ["Email", "Joined", "Last seen"] {
8588 assert!(
8589 html.contains(label),
8590 "the {label} field is not on the page: {html}"
8591 );
8592 }
8593 assert!(html.contains("Mem Ber"), "{html}");
8594 assert!(html.contains("mem@iz.sh"), "{html}");
8595 assert!(
8596 html.contains("avatar-xl"),
8597 "the profile picture is not the page's own size: {html}"
8598 );
8599}
8600
8601/// A face or a name in the task modal leads to the person it names.
8602#[tokio::test]
8603async fn a_comment_author_and_an_assignee_lead_to_their_profiles() {
8604 let app = App::open().await;
8605 let admin_cookie = admin(&app).await;
8606 invited(&app, &admin_cookie, "mem@iz.sh", "Mem Ber", Role::Member).await;
8607 let mem_id = user_id(&app, "mem@iz.sh").await;
8608 let workspace_id = app.workspace_id().await;
8609 let board = app.store.board(&workspace_id).await.unwrap().unwrap();
8610 let open = app.store.columns(&board.id).await.unwrap()[0].id.clone();
8611 let task = a_task_by(&app, &board.id, &open, "Hold the door", &mem_id).await;
8612 app.store.assign_task(&task, &mem_id).await.unwrap();
8613 app.store
8614 .add_comment(&task, &mem_id, "a note", time::OffsetDateTime::now_utc())
8615 .await
8616 .unwrap();
8617
8618 let page = app
8619 .get(&format!("/?task={task}&tab=comments"), Some(&admin_cookie))
8620 .await;
8621 let html = String::from_utf8(page.bytes).unwrap();
8622 assert!(
8623 html.matches(&format!(r#"href="/people/{mem_id}""#)).count() >= 2,
8624 "the comment's author and the assignee do not both lead anywhere: {html}"
8625 );
8626}
8627
8628/// The board's project filter is typed into, like the pickers on the logs
8629/// page: a workspace with many tags is not a list to scroll.
8630#[tokio::test]
8631async fn the_project_filter_is_written_into() {
8632 let app = App::open().await;
8633 let admin_cookie = admin(&app).await;
8634 let page = app.get("/", Some(&admin_cookie)).await;
8635 let html = String::from_utf8(page.bytes).unwrap();
8636 let filter = html
8637 .split("<select")
8638 .find(|chunk| chunk.contains(r#"name="tag""#))
8639 .unwrap_or_else(|| panic!("no project filter on the board: {html}"));
8640 assert!(
8641 filter.contains("data-search"),
8642 "the project filter cannot be typed into: {filter}"
8643 );
8644}
8645
8646#[tokio::test]
8647async fn a_profile_is_not_found_signed_out_or_outside_the_workspace() {
8648 let app = App::open().await;
8649 let admin_cookie = admin(&app).await;
8650 invited(&app, &admin_cookie, "mem@iz.sh", "Mem Ber", Role::Member).await;
8651 let mem_id = user_id(&app, "mem@iz.sh").await;
8652
8653 let signed_out = app.get(&format!("/people/{mem_id}"), None).await;
8654 assert_eq!(signed_out.status.as_u16(), 404, "never a 403, never a page");
8655
8656 // A person who exists, but in another workspace, reads exactly like a
8657 // missing one — the id is not looked at twice.
8658 let other = App::open().await;
8659 // A workspace has to be claimed before it holds anybody to be a stranger.
8660 let _ = admin(&other).await;
8661 let stranger = other
8662 .store
8663 .users(&other.workspace_id().await)
8664 .await
8665 .unwrap()[0]
8666 .id
8667 .clone();
8668 let foreign = app
8669 .get(&format!("/people/{stranger}"), Some(&admin_cookie))
8670 .await;
8671 assert_eq!(foreign.status.as_u16(), 404);
8672
8673 let missing = app.get("/people/nobody", Some(&admin_cookie)).await;
8674 assert_eq!(missing.status.as_u16(), 404);
8675}
8676
8677#[tokio::test]
8678async fn only_your_own_profile_offers_the_edit_link() {
8679 let app = App::open().await;
8680 let admin_cookie = admin(&app).await;
8681 invited(&app, &admin_cookie, "mem@iz.sh", "Mem Ber", Role::Member).await;
8682 let mem_id = user_id(&app, "mem@iz.sh").await;
8683 let ivy = invited(&app, &admin_cookie, "ivy@iz.sh", "Ivy Lear", Role::Member).await;
8684 let ivy_id = user_id(&app, "ivy@iz.sh").await;
8685
8686 let own = app.get(&format!("/people/{ivy_id}"), Some(&ivy)).await;
8687 let own_html = String::from_utf8(own.bytes).unwrap();
8688 assert!(
8689 own_html.contains(r#"href="/settings?section=profile""#),
8690 "no edit link on your own profile: {own_html}"
8691 );
8692
8693 let theirs = app.get(&format!("/people/{mem_id}"), Some(&ivy)).await;
8694 let theirs_html = String::from_utf8(theirs.bytes).unwrap();
8695 assert!(
8696 !theirs_html.contains("settings?section=profile"),
8697 "someone else's profile grew an editor: {theirs_html}"
8698 );
8699}
8700// --- task clock -------------------------------------------------------------
8701
8702#[tokio::test]
8703async fn a_clock_saved_on_a_task_renders_in_the_viewers_stored_timezone() {
8704 let app = App::open().await;
8705 let admin_cookie = admin(&app).await;
8706 let column = first_column(&app).await;
8707 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
8708
8709 // The viewer is still on UTC, so the value typed is the instant stored.
8710 let saved = app
8711 .post(
8712 "/api/save_task",
8713 Some(&admin_cookie),
8714 &[
8715 ("task_id", &task),
8716 ("deadline", "2027-09-02"),
8717 ("clock_hour", "11"),
8718 ("clock_minute", "00"),
8719 ],
8720 )
8721 .await;
8722 assert!(
8723 !saved
8724 .location
8725 .as_deref()
8726 .unwrap_or_default()
8727 .contains("refusal="),
8728 "{:?}",
8729 saved.location
8730 );
8731 let facts = app.store.task(&task).await.unwrap().expect("task gone");
8732 assert!(facts.row.clock_at.is_some(), "the clock did not persist");
8733
8734 let page = app
8735 .get(&format!("/?task={task}"), Some(&admin_cookie))
8736 .await;
8737 let html = String::from_utf8_lossy(&page.bytes);
8738 assert!(
8739 html.contains(r#"<option value="11" selected="">11</option>"#)
8740 && html.contains(r#"<option value="00" selected="">00</option>"#),
8741 "{html}"
8742 );
8743 assert!(html.contains(">Sep 02 11:00<"), "{html}");
8744
8745 // The same instant, read back by a viewer whose row mirrors UTC+03:00
8746 // from im: the field and its label both shift, the stored value does
8747 // not. The mirror is the only path a timezone change still takes.
8748 app.store
8749 .sync_member("im-ada", "ada@iz.sh", "Ada Lovelace", true, 0, "UTC+03:00")
8750 .await
8751 .unwrap();
8752
8753 let shifted = app
8754 .get(&format!("/?task={task}"), Some(&admin_cookie))
8755 .await;
8756 let html = String::from_utf8_lossy(&shifted.bytes);
8757 assert!(
8758 html.contains(r#"<option value="14" selected="">14</option>"#)
8759 && html.contains(r#"<option value="00" selected="">00</option>"#),
8760 "{html}"
8761 );
8762 assert!(html.contains(">Sep 02 14:00<"), "{html}");
8763}
8764
8765#[tokio::test]
8766async fn an_empty_time_clears_the_clock_and_a_clear_clears_both() {
8767 let app = App::open().await;
8768 let admin_cookie = admin(&app).await;
8769 let column = first_column(&app).await;
8770 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
8771 let saved = app
8772 .post(
8773 "/api/save_task",
8774 Some(&admin_cookie),
8775 &[
8776 ("task_id", &task),
8777 ("deadline", "2027-09-02"),
8778 ("clock_hour", "11"),
8779 ("clock_minute", "00"),
8780 ],
8781 )
8782 .await;
8783 assert!(
8784 !saved
8785 .location
8786 .as_deref()
8787 .unwrap_or_default()
8788 .contains("refusal="),
8789 "{:?}",
8790 saved.location
8791 );
8792
8793 // A save that carries neither field — a title edit, a description
8794 // edit — says nothing about the moment at all: clock and day both stay.
8795 let saved = app
8796 .post(
8797 "/api/save_task",
8798 Some(&admin_cookie),
8799 &[("task_id", &task), ("title", "Renamed")],
8800 )
8801 .await;
8802 assert!(
8803 !saved
8804 .location
8805 .as_deref()
8806 .unwrap_or_default()
8807 .contains("refusal="),
8808 "{:?}",
8809 saved.location
8810 );
8811 let facts = app.store.task(&task).await.unwrap().expect("task gone");
8812 assert!(
8813 facts.row.clock_at.is_some(),
8814 "an unrelated edit cleared the clock"
8815 );
8816 assert!(
8817 facts.row.deadline.is_some(),
8818 "an unrelated edit cleared the day"
8819 );
8820 assert_eq!(facts.row.title, "Renamed");
8821
8822 // An empty time clears the clock and keeps the day.
8823 let saved = app
8824 .post(
8825 "/api/save_task",
8826 Some(&admin_cookie),
8827 &[("task_id", &task), ("clock_hour", ""), ("clock_minute", "")],
8828 )
8829 .await;
8830 assert!(
8831 !saved
8832 .location
8833 .as_deref()
8834 .unwrap_or_default()
8835 .contains("refusal="),
8836 "{:?}",
8837 saved.location
8838 );
8839 let facts = app.store.task(&task).await.unwrap().expect("task gone");
8840 assert!(facts.row.clock_at.is_none(), "an empty time did not clear");
8841 assert!(
8842 facts.row.deadline.is_some(),
8843 "an empty time took the day with it"
8844 );
8845
8846 let page = app
8847 .get(&format!("/?task={task}"), Some(&admin_cookie))
8848 .await;
8849 let html = String::from_utf8_lossy(&page.bytes);
8850 assert!(html.contains(">Sep 02<"), "{html}");
8851 // An empty time renders as no selected step at all — the bare "--".
8852 assert!(
8853 html.contains(r#"name="clock_hour""#) && html.contains(r#"name="clock_minute""#),
8854 "{html}"
8855 );
8856 assert!(!html.contains(">Sep 02 11:00<"), "{html}");
8857 let saved = app
8858 .post(
8859 "/api/save_task",
8860 Some(&admin_cookie),
8861 &[
8862 ("task_id", &task),
8863 ("deadline", ""),
8864 ("clock_hour", ""),
8865 ("clock_minute", ""),
8866 ],
8867 )
8868 .await;
8869 assert!(
8870 !saved
8871 .location
8872 .as_deref()
8873 .unwrap_or_default()
8874 .contains("refusal="),
8875 "{:?}",
8876 saved.location
8877 );
8878 let facts = app.store.task(&task).await.unwrap().expect("task gone");
8879 assert!(facts.row.deadline.is_none() && facts.row.clock_at.is_none());
8880
8881 let page = app
8882 .get(&format!("/?task={task}"), Some(&admin_cookie))
8883 .await;
8884 let html = String::from_utf8_lossy(&page.bytes);
8885 assert!(html.contains(">no deadline</span>"), "{html}");
8886}
8887
8888#[tokio::test]
8889async fn a_title_edit_keeps_the_clock() {
8890 // The title form posts neither moment field; its save must not be a
8891 // clock clear wearing a rename's clothes.
8892 let app = App::open().await;
8893 let admin_cookie = admin(&app).await;
8894 let column = first_column(&app).await;
8895 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
8896
8897 let saved = app
8898 .post(
8899 "/api/save_task",
8900 Some(&admin_cookie),
8901 &[
8902 ("task_id", &task),
8903 ("deadline", "2027-09-02"),
8904 ("clock_hour", "11"),
8905 ("clock_minute", "00"),
8906 ],
8907 )
8908 .await;
8909 assert!(
8910 !saved
8911 .location
8912 .as_deref()
8913 .unwrap_or_default()
8914 .contains("refusal="),
8915 "{:?}",
8916 saved.location
8917 );
8918
8919 let saved = app
8920 .post(
8921 "/api/save_task",
8922 Some(&admin_cookie),
8923 &[("task_id", &task), ("title", "Renamed")],
8924 )
8925 .await;
8926 assert!(
8927 !saved
8928 .location
8929 .as_deref()
8930 .unwrap_or_default()
8931 .contains("refusal="),
8932 "{:?}",
8933 saved.location
8934 );
8935
8936 let facts = app.store.task(&task).await.unwrap().expect("task gone");
8937 assert_eq!(facts.row.title, "Renamed");
8938 assert!(
8939 facts.row.clock_at.is_some(),
8940 "the title edit cleared the clock"
8941 );
8942 assert!(
8943 facts.row.deadline.is_some(),
8944 "the title edit cleared the day"
8945 );
8946}
8947
8948#[tokio::test]
8949async fn a_description_edit_keeps_the_clock() {
8950 let app = App::open().await;
8951 let admin_cookie = admin(&app).await;
8952 let column = first_column(&app).await;
8953 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
8954
8955 let saved = app
8956 .post(
8957 "/api/save_task",
8958 Some(&admin_cookie),
8959 &[
8960 ("task_id", &task),
8961 ("deadline", "2027-09-02"),
8962 ("clock_hour", "11"),
8963 ("clock_minute", "00"),
8964 ],
8965 )
8966 .await;
8967 assert!(
8968 !saved
8969 .location
8970 .as_deref()
8971 .unwrap_or_default()
8972 .contains("refusal="),
8973 "{:?}",
8974 saved.location
8975 );
8976
8977 let saved = app
8978 .post(
8979 "/api/save_task",
8980 Some(&admin_cookie),
8981 &[("task_id", &task), ("description", "Now with words")],
8982 )
8983 .await;
8984 assert!(
8985 !saved
8986 .location
8987 .as_deref()
8988 .unwrap_or_default()
8989 .contains("refusal="),
8990 "{:?}",
8991 saved.location
8992 );
8993
8994 let facts = app.store.task(&task).await.unwrap().expect("task gone");
8995 assert_eq!(facts.description, "Now with words");
8996 assert!(
8997 facts.row.clock_at.is_some(),
8998 "the description edit cleared the clock"
8999 );
9000 assert!(
9001 facts.row.deadline.is_some(),
9002 "the description edit cleared the day"
9003 );
9004}
9005
9006#[tokio::test]
9007async fn a_time_that_cannot_be_used_is_refused_and_saves_nothing() {
9008 let app = App::open().await;
9009 let admin_cookie = admin(&app).await;
9010 let column = first_column(&app).await;
9011 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
9012
9013 let answer = app
9014 .post_without_script(
9015 "/api/save_task",
9016 Some(&admin_cookie),
9017 &format!("/?task={task}"),
9018 &[
9019 ("task_id", task.as_str()),
9020 ("title", "Renamed"),
9021 ("deadline", "2027-09-02"),
9022 ("clock_hour", "not-a-time"),
9023 ],
9024 )
9025 .await;
9026 let location = answer.location.as_deref().unwrap_or_default();
9027 assert!(
9028 location.contains("refusal=bad-clock&on=save_task"),
9029 "{location}"
9030 );
9031
9032 // The refused save is the whole save: the title and the day in the same
9033 // form did not go through either.
9034 let facts = app.store.task(&task).await.unwrap().expect("task gone");
9035 assert!(facts.row.clock_at.is_none(), "a bad time was stored");
9036 assert!(
9037 facts.row.deadline.is_none(),
9038 "the refused save kept the day"
9039 );
9040 assert_eq!(facts.row.title, "Ship it", "the refused save half-applied");
9041
9042 let page = app.get(location, Some(&admin_cookie)).await;
9043 let html = String::from_utf8_lossy(&page.bytes);
9044 assert!(html.contains("That is not a time."), "{html}");
9045
9046 // A time with no day anywhere — none posted, none on the task — has
9047 // nothing to sit on.
9048 let orphan = a_task(&app, &admin_cookie, &column, "Orphan").await;
9049 let answer = app
9050 .post_without_script(
9051 "/api/save_task",
9052 Some(&admin_cookie),
9053 &format!("/?task={orphan}"),
9054 &[
9055 ("task_id", orphan.as_str()),
9056 ("clock_hour", "16"),
9057 ("clock_minute", "20"),
9058 ],
9059 )
9060 .await;
9061 let location = answer.location.as_deref().unwrap_or_default();
9062 assert!(
9063 location.contains("refusal=bad-clock&on=save_task"),
9064 "{location}"
9065 );
9066 let facts = app.store.task(&orphan).await.unwrap().expect("task gone");
9067 assert!(facts.row.clock_at.is_none(), "a dayless time was stored");
9068 // And the mirror mistake: a minute with no hour is the same half of
9069 // nothing.
9070 let orphan2 = a_task(&app, &admin_cookie, &column, "Orphan Too").await;
9071 let answer = app
9072 .post_without_script(
9073 "/api/save_task",
9074 Some(&admin_cookie),
9075 &format!("/?task={orphan2}"),
9076 &[("task_id", orphan2.as_str()), ("clock_minute", "45")],
9077 )
9078 .await;
9079 let location = answer.location.as_deref().unwrap_or_default();
9080 assert!(
9081 location.contains("refusal=bad-clock&on=save_task"),
9082 "{location}"
9083 );
9084 let facts = app.store.task(&orphan2).await.unwrap().expect("task gone");
9085 assert!(facts.row.clock_at.is_none(), "a lone minute was stored");
9086}
9087
9088#[tokio::test]
9089async fn a_card_wears_the_clock_chip_in_the_viewers_zone_instead_of_the_deadline() {
9090 let app = App::open().await;
9091 let admin_cookie = admin(&app).await;
9092
9093 // The viewer reads in UTC+03:00, so the typed 14:00 is 11:00 stored and
9094 // 14:00 on the card again — the chip goes through the same zone both ways.
9095 app.store
9096 .sync_member("im-ada", "ada@iz.sh", "Ada Lovelace", true, 0, "UTC+03:00")
9097 .await
9098 .unwrap();
9099
9100 let column = first_column(&app).await;
9101 let answer = app
9102 .post(
9103 "/api/create_task",
9104 Some(&admin_cookie),
9105 &[
9106 ("title", "Kickoff"),
9107 ("column_id", &column),
9108 ("deadline", "2027-09-02"),
9109 ("clock_hour", "14"),
9110 ("clock_minute", "00"),
9111 ],
9112 )
9113 .await;
9114 assert!(
9115 !answer
9116 .location
9117 .as_deref()
9118 .unwrap_or_default()
9119 .contains("refusal="),
9120 "{:?}",
9121 answer.location
9122 );
9123 a_task(&app, &admin_cookie, &column, "No meeting").await;
9124
9125 let page = app.get("/", Some(&admin_cookie)).await;
9126 let html = String::from_utf8_lossy(&page.bytes);
9127 assert!(
9128 html.contains(r#"data-tick="" class="card-deadline">Sep 02 · 14:00<"#),
9129 "{html}"
9130 );
9131 assert!(
9132 html.contains("card-deadline card-deadline-none"),
9133 "the deadline-less card lost its own chip: {html}"
9134 );
9135}
9136
9137/// A clock that has passed makes the card overdue the same way the detail
9138/// already is: the chip carries ` · overdue` and the overdue class, the
9139/// filter count counts it, and the detail field keeps its own
9140/// `day time · overdue` shape. A future clock on the same board stays clean.
9141#[tokio::test]
9142async fn a_past_clock_reads_overdue_on_the_card_like_the_detail() {
9143 let app = App::open().await;
9144 let admin_cookie = admin(&app).await;
9145
9146 // The viewer is pinned to UTC, so the typed 18:00 is the stored instant.
9147 app.store
9148 .sync_member("im-ada", "ada@iz.sh", "Ada Lovelace", true, 0, "UTC")
9149 .await
9150 .unwrap();
9151
9152 let column = first_column(&app).await;
9153 let yesterday = time::OffsetDateTime::now_utc() - time::Duration::days(1);
9154 let ymd = format!(
9155 "{:04}-{:02}-{:02}",
9156 yesterday.year(),
9157 yesterday.month() as u8,
9158 yesterday.day()
9159 );
9160 let answer = app
9161 .post(
9162 "/api/create_task",
9163 Some(&admin_cookie),
9164 &[
9165 ("title", "Standup"),
9166 ("column_id", &column),
9167 ("deadline", &ymd),
9168 ("clock_hour", "18"),
9169 ("clock_minute", "00"),
9170 ],
9171 )
9172 .await;
9173 assert!(
9174 !answer
9175 .location
9176 .as_deref()
9177 .unwrap_or_default()
9178 .contains("refusal="),
9179 "{:?}",
9180 answer.location
9181 );
9182
9183 // A same-request control: a clock still ahead of now never reads overdue.
9184 let later = app
9185 .post(
9186 "/api/create_task",
9187 Some(&admin_cookie),
9188 &[
9189 ("title", "Kickoff later"),
9190 ("column_id", &column),
9191 ("deadline", "2027-09-02"),
9192 ("clock_hour", "18"),
9193 ("clock_minute", "00"),
9194 ],
9195 )
9196 .await;
9197 assert!(
9198 !later
9199 .location
9200 .as_deref()
9201 .unwrap_or_default()
9202 .contains("refusal="),
9203 "{:?}",
9204 later.location
9205 );
9206
9207 let workspace_id = app.workspace_id().await;
9208 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
9209 .await
9210 .unwrap()
9211 .unwrap();
9212 let task = board
9213 .cards()
9214 .find(|card| card.title == "Standup")
9215 .expect("the overdue task is not on the board")
9216 .id
9217 .clone();
9218
9219 let day = iz_core::board::day_label(yesterday.date());
9220 let page = app.get("/", Some(&admin_cookie)).await;
9221 let html = String::from_utf8_lossy(&page.bytes);
9222 assert!(
9223 html.contains(&format!(
9224 r#"data-tick="" class="card-deadline card-deadline-overdue">{day} · 18:00 · overdue<"#
9225 )),
9226 "{html}"
9227 );
9228 assert!(
9229 html.contains(r#"data-tick="" class="card-deadline">Sep 02 · 18:00<"#),
9230 "the future clock picked up an overdue mark: {html}"
9231 );
9232
9233 // The detail keeps its own shape: `day time · overdue`, no middle dot
9234 // between day and time.
9235 let page = app.get(&format!("/?task={task}"), Some(&admin_cookie)).await;
9236 let html = String::from_utf8_lossy(&page.bytes);
9237 assert!(html.contains("detail-overdue"), "{html}");
9238 assert!(html.contains(&format!("{day} 18:00 · overdue")), "{html}");
9239}
9240
9241#[tokio::test]
9242async fn a_time_set_on_an_existing_day_writes_both_columns() {
9243 let app = App::open().await;
9244 let admin_cookie = admin(&app).await;
9245 let column = first_column(&app).await;
9246 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
9247
9248 // A day first, then a time on its own: the day field was absent on the
9249 // second save, so the task's own day is what the moment sits on — and
9250 // the deadline column says the same day the clock does.
9251 let saved = app
9252 .post(
9253 "/api/save_task",
9254 Some(&admin_cookie),
9255 &[("task_id", &task), ("deadline", "2027-09-02")],
9256 )
9257 .await;
9258 assert!(
9259 !saved
9260 .location
9261 .as_deref()
9262 .unwrap_or_default()
9263 .contains("refusal="),
9264 "{:?}",
9265 saved.location
9266 );
9267 let saved = app
9268 .post(
9269 "/api/save_task",
9270 Some(&admin_cookie),
9271 &[
9272 ("task_id", &task),
9273 ("clock_hour", "16"),
9274 ("clock_minute", "20"),
9275 ],
9276 )
9277 .await;
9278 assert!(
9279 !saved
9280 .location
9281 .as_deref()
9282 .unwrap_or_default()
9283 .contains("refusal="),
9284 "{:?}",
9285 saved.location
9286 );
9287 let facts = app.store.task(&task).await.unwrap().expect("task gone");
9288 assert!(facts.row.clock_at.is_some(), "the time did not persist");
9289 assert_eq!(
9290 facts.row.deadline.map(|day| day.to_string()),
9291 Some("2027-09-02".to_string()),
9292 "the time lost its day"
9293 );
9294
9295 // Created with day and time in one form, the two columns agree too.
9296 let answer = app
9297 .post(
9298 "/api/create_task",
9299 Some(&admin_cookie),
9300 &[
9301 ("title", "Kickoff"),
9302 ("column_id", &column),
9303 ("deadline", "2026-09-10"),
9304 ("clock_hour", "9"),
9305 ("clock_minute", "30"),
9306 ],
9307 )
9308 .await;
9309 assert!(
9310 !answer
9311 .location
9312 .as_deref()
9313 .unwrap_or_default()
9314 .contains("refusal="),
9315 "{:?}",
9316 answer.location
9317 );
9318 let board = app
9319 .store
9320 .board(&app.workspace_id().await)
9321 .await
9322 .unwrap()
9323 .expect("no board");
9324 let rows = app.store.tasks_for_board(&board.id).await.unwrap();
9325 let kickoff = rows
9326 .iter()
9327 .find(|row| row.title == "Kickoff")
9328 .expect("created task not on the board");
9329 assert_eq!(
9330 kickoff.deadline.map(|day| day.to_string()),
9331 Some("2026-09-10".to_string())
9332 );
9333 assert!(kickoff.clock_at.is_some());
9334}
9335
9336#[tokio::test]
9337async fn the_reminder_knob_saves_renders_and_keeps_when_absent() {
9338 let app = App::open().await;
9339 let admin_cookie = admin(&app).await;
9340
9341 let answer = app
9342 .post(
9343 "/api/save_limits",
9344 Some(&admin_cookie),
9345 &[
9346 ("attachment_limit_mb", "10"),
9347 ("allowed_file_types", "png, pdf"),
9348 ("mail_batch_minutes", "5"),
9349 ("reminder_minutes", "30"),
9350 ],
9351 )
9352 .await;
9353 assert!(
9354 answer
9355 .location
9356 .as_deref()
9357 .unwrap_or_default()
9358 .contains("saved=save_limits"),
9359 "{:?}",
9360 answer.location
9361 );
9362 let workspace = app.store.workspace().await.unwrap().unwrap();
9363 assert_eq!(workspace.reminder_minutes, 30);
9364
9365 let page = app
9366 .get("/settings?section=limits", Some(&admin_cookie))
9367 .await;
9368 let html = String::from_utf8_lossy(&page.bytes);
9369 assert!(
9370 html.contains(r#"name="reminder_minutes""#)
9371 && html.contains(r#"value="30""#)
9372 && html.contains("Reminder (minutes)"),
9373 "{html}"
9374 );
9375
9376 // An older form's post, with no knob in it, leaves the stored choice.
9377 let answer = app
9378 .post(
9379 "/api/save_limits",
9380 Some(&admin_cookie),
9381 &[
9382 ("attachment_limit_mb", "10"),
9383 ("allowed_file_types", "png, pdf"),
9384 ("mail_batch_minutes", "5"),
9385 ],
9386 )
9387 .await;
9388 assert!(
9389 answer
9390 .location
9391 .as_deref()
9392 .unwrap_or_default()
9393 .contains("saved=save_limits"),
9394 "{:?}",
9395 answer.location
9396 );
9397 let workspace = app.store.workspace().await.unwrap().unwrap();
9398 assert_eq!(workspace.reminder_minutes, 30, "an absent knob reset it");
9399
9400 // Words are not minutes.
9401 let answer = app
9402 .post(
9403 "/api/save_limits",
9404 Some(&admin_cookie),
9405 &[
9406 ("attachment_limit_mb", "10"),
9407 ("allowed_file_types", "png, pdf"),
9408 ("mail_batch_minutes", "5"),
9409 ("reminder_minutes", "later"),
9410 ],
9411 )
9412 .await;
9413 let location = answer.location.as_deref().unwrap_or_default();
9414 assert!(
9415 location.contains("refusal=bad-limit&on=save_limits"),
9416 "{location}"
9417 );
9418 let workspace = app.store.workspace().await.unwrap().unwrap();
9419 assert_eq!(workspace.reminder_minutes, 30, "a bad knob half-applied");
9420
9421 // Zero is the off switch, and it saves.
9422 let answer = app
9423 .post(
9424 "/api/save_limits",
9425 Some(&admin_cookie),
9426 &[
9427 ("attachment_limit_mb", "10"),
9428 ("allowed_file_types", "png, pdf"),
9429 ("mail_batch_minutes", "5"),
9430 ("reminder_minutes", "0"),
9431 ],
9432 )
9433 .await;
9434 assert!(
9435 answer
9436 .location
9437 .as_deref()
9438 .unwrap_or_default()
9439 .contains("saved=save_limits"),
9440 "{:?}",
9441 answer.location
9442 );
9443 let workspace = app.store.workspace().await.unwrap().unwrap();
9444 assert_eq!(workspace.reminder_minutes, 0);
9445}
9446
9447/// A time change is a `ClockSet` activity, and the `deadline_set` rule
9448/// fires on it — the clock is the deadline field's other half, not a
9449/// second trigger to arm. The rule's own words and the rules-page menu
9450/// stay the deadline's.
9451#[tokio::test]
9452async fn a_time_change_fires_the_deadline_rule_and_round_trips() {
9453 let app = App::open_with_mail().await;
9454 let admin_cookie = admin(&app).await;
9455 let member = invited(&app, &admin_cookie, "deniz@iz.sh", "Deniz", Role::Member).await;
9456 let column = first_column(&app).await;
9457 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
9458
9459 let answer = app
9460 .post(
9461 "/api/create_rule",
9462 Some(&admin_cookie),
9463 &[
9464 ("trigger", "deadline_set"),
9465 ("column_id", ""),
9466 ("subject", "Moment moved"),
9467 ("audience", "board"),
9468 ],
9469 )
9470 .await;
9471 assert!(
9472 answer.status == StatusCode::SEE_OTHER
9473 && !answer
9474 .location
9475 .as_deref()
9476 .unwrap_or_default()
9477 .contains("refusal="),
9478 "{:?}",
9479 answer.location
9480 );
9481 let rules = app
9482 .post("/api/current_rules", Some(&admin_cookie), &[])
9483 .await;
9484 assert!(
9485 rules.body.contains(r#""when":"When a deadline is set""#),
9486 "{}",
9487 rules.body
9488 );
9489 let page = app.get("/rules", Some(&admin_cookie)).await;
9490 let html = String::from_utf8_lossy(&page.bytes);
9491 assert!(html.contains("When a deadline is set"), "{html}");
9492
9493 let day = app
9494 .post(
9495 "/api/save_task",
9496 Some(&admin_cookie),
9497 &[("task_id", &task), ("deadline", "2027-09-02")],
9498 )
9499 .await;
9500 assert!(
9501 !day.location
9502 .as_deref()
9503 .unwrap_or_default()
9504 .contains("refusal="),
9505 "{:?}",
9506 day.location
9507 );
9508
9509 // Deniz sets the time and nothing else — a `ClockSet` activity — and
9510 // the deadline rule owes the board, Deniz included, mail for it.
9511 let answer = app
9512 .post(
9513 "/api/save_task",
9514 Some(&member),
9515 &[
9516 ("task_id", &task),
9517 ("clock_hour", "9"),
9518 ("clock_minute", "30"),
9519 ],
9520 )
9521 .await;
9522 assert!(
9523 !answer
9524 .location
9525 .as_deref()
9526 .unwrap_or_default()
9527 .contains("refusal="),
9528 "{:?}",
9529 answer.location
9530 );
9531 let rule = only_rule(&app, &admin_cookie).await;
9532 let send = until_rule_send_to(&app, &rule, "ada@iz.sh", 0).await;
9533 assert_eq!(send.recipient, "ada@iz.sh");
9534}
9535
9536#[tokio::test]
9537async fn the_logs_feed_says_the_clock_in_its_own_words() {
9538 let app = App::open().await;
9539 let admin_cookie = admin(&app).await;
9540 let column = first_column(&app).await;
9541 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
9542
9543 let saved = app
9544 .post(
9545 "/api/save_task",
9546 Some(&admin_cookie),
9547 &[
9548 ("task_id", &task),
9549 ("deadline", "2027-09-02"),
9550 ("clock_hour", "11"),
9551 ("clock_minute", "00"),
9552 ],
9553 )
9554 .await;
9555 assert!(
9556 !saved
9557 .location
9558 .as_deref()
9559 .unwrap_or_default()
9560 .contains("refusal="),
9561 "{:?}",
9562 saved.location
9563 );
9564
9565 let page = app.get("/logs?section=activity", Some(&admin_cookie)).await;
9566 let html = String::from_utf8_lossy(&page.bytes);
9567 assert!(html.contains("set the time to"), "{html}");
9568 assert!(html.contains(r#"<option value="clock_set""#), "{html}");
9569}
9570
9571#[tokio::test]
9572async fn the_datepicker_script_guards_a_panel_with_no_day_input() {
9573 // Every panel the server draws today carries a `.datepick-input`, but
9574 // the shared open handler renders whatever wears the datepick classes —
9575 // the guard is what keeps a future input-less panel from throwing
9576 // instead of drawing nothing.
9577 let app = App::open().await;
9578 let admin_cookie = admin(&app).await;
9579 let column = first_column(&app).await;
9580 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
9581
9582 let page = app
9583 .get(&format!("/?task={task}"), Some(&admin_cookie))
9584 .await;
9585 let html = String::from_utf8_lossy(&page.bytes);
9586 assert!(
9587 html.contains("if (!input) { return; }"),
9588 "the datepicker script lost its no-day-input guard: {html}"
9589 );
9590 // The whole point of a day pick is the hidden input's new value: the
9591 // form posts nothing without it, and only a real browser runs this
9592 // script — so the write itself is asserted here, wire-level. A merge
9593 // once dropped exactly this line and every pick silently saved no day.
9594 assert!(
9595 html.contains("input.value = ymd ?"),
9596 "the datepicker script lost the day write: {html}"
9597 );
9598 assert!(
9599 html.contains(r#"name="clock_hour" aria-label="Hour" data-search=""#)
9600 && html.contains(r#"name="clock_minute" aria-label="Minute" data-search=""#),
9601 "the moment combos lost their searchable chrome: {html}"
9602 );
9603 assert!(html.contains("datepick-input"), "{html}");
9604}
9605
9606#[tokio::test]
9607async fn an_off_step_clock_renders_itself_not_a_rounded_step() {
9608 // A clock that never sat on a five-minute line — one that arrived
9609 // before the menu did — is shown exactly as stored: its own option is
9610 // appended, nothing is rounded onto a step.
9611 let app = App::open().await;
9612 let admin_cookie = admin(&app).await;
9613 let column = first_column(&app).await;
9614 let task = a_task(&app, &admin_cookie, &column, "Ship it").await;
9615
9616 let saved = app
9617 .post(
9618 "/api/save_task",
9619 Some(&admin_cookie),
9620 &[
9621 ("task_id", &task),
9622 ("deadline", "2027-09-02"),
9623 ("clock_hour", "11"),
9624 ("clock_minute", "23"),
9625 ],
9626 )
9627 .await;
9628 assert!(
9629 !saved
9630 .location
9631 .as_deref()
9632 .unwrap_or_default()
9633 .contains("refusal="),
9634 "{:?}",
9635 saved.location
9636 );
9637
9638 let page = app
9639 .get(&format!("/?task={task}"), Some(&admin_cookie))
9640 .await;
9641 let html = String::from_utf8_lossy(&page.bytes);
9642 assert!(
9643 html.contains(r#"<option value="11" selected="">11</option>"#)
9644 && html.contains(r#"<option value="23" selected="">23</option>"#),
9645 "{html}"
9646 );
9647 assert!(html.contains(">Sep 02 11:23<"), "{html}");
9648}
9649
9650#[tokio::test]
9651async fn a_page_revalidates_and_an_asset_caches_forever() {
9652 let app = App::open().await;
9653
9654 // A page the browser kept from before a deploy is the old app answering
9655 // under the new one's address, so HTML is revalidated on every load.
9656 let page = Request::builder()
9657 .method("GET")
9658 .uri("/")
9659 .body(Body::empty())
9660 .unwrap();
9661 let page = app.router.handle(page).await;
9662 assert_eq!(page.status(), StatusCode::OK);
9663 let directive = page
9664 .headers()
9665 .get(header::CACHE_CONTROL)
9666 .and_then(|value| value.to_str().ok());
9667 assert_eq!(directive, Some("no-cache"));
9668
9669 // The asset's name carries its content hash, so the year of `immutable`
9670 // topcoat stamps it with survives the layer untouched.
9671 let stylesheet = std::fs::read_dir(asset_dir())
9672 .unwrap()
9673 .filter_map(|entry| {
9674 let path = entry.ok()?.path();
9675 (path.extension()?.to_str()? == "css").then_some(path)
9676 })
9677 .next()
9678 .expect("no compiled stylesheet in the asset bundle");
9679 let asset_path = format!(
9680 "/_topcoat/assets/{}",
9681 stylesheet.file_name().unwrap().to_str().unwrap()
9682 );
9683 let asset = Request::builder()
9684 .method("GET")
9685 .uri(&asset_path)
9686 .body(Body::empty())
9687 .unwrap();
9688 let asset = app.router.handle(asset).await;
9689 assert_eq!(asset.status(), StatusCode::OK);
9690 let directive = asset
9691 .headers()
9692 .get(header::CACHE_CONTROL)
9693 .and_then(|value| value.to_str().ok());
9694 assert_eq!(directive, Some("public, max-age=31536000, immutable"));
9695
9696 // A redirect carries no directive at all: nothing cached, nothing stale.
9697 let admin = admin(&app).await;
9698 let column = first_column(&app).await;
9699 let redirected = Request::builder()
9700 .method("POST")
9701 .uri("/api/create_task")
9702 .header(header::ACCEPT, "application/json")
9703 .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
9704 .header(
9705 header::COOKIE,
9706 HeaderValue::from_str(&format!("{SESSION_COOKIE}={admin}")).unwrap(),
9707 )
9708 .body(Body::from(format!("title=&column_id={column}")))
9709 .unwrap();
9710 let redirected = app.router.handle(redirected).await;
9711 assert_eq!(redirected.status(), StatusCode::SEE_OTHER);
9712 assert!(redirected.headers().get(header::CACHE_CONTROL).is_none());
9713}
9714
9715/// Every tag write lands on the workspace trail with the acting admin as the
9716/// actor: created, moved, renamed (old -> new) and deleted each name the tag
9717/// itself in the detail.
9718#[tokio::test]
9719async fn tag_writes_record_their_events() {
9720 let app = App::open().await;
9721 let admin_cookie = admin(&app).await;
9722
9723 app.post(
9724 "/api/create_tag",
9725 Some(&admin_cookie),
9726 &[("name", "Urgent")],
9727 )
9728 .await;
9729 let workspace_id = app.workspace_id().await;
9730 let tag = {
9731 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
9732 .await
9733 .unwrap()
9734 .unwrap();
9735 app.store
9736 .tags(&board.board.id)
9737 .await
9738 .unwrap()
9739 .into_iter()
9740 .find(|tag| tag.name == "Urgent")
9741 .expect("the tag was created")
9742 };
9743 app.post(
9744 "/api/move_tag",
9745 Some(&admin_cookie),
9746 &[("tag_id", &tag.id), ("direction", "up")],
9747 )
9748 .await;
9749 app.post(
9750 "/api/rename_tag",
9751 Some(&admin_cookie),
9752 &[("tag_id", &tag.id), ("name", "High")],
9753 )
9754 .await;
9755 app.post(
9756 "/api/delete_tag",
9757 Some(&admin_cookie),
9758 &[("tag_id", &tag.id)],
9759 )
9760 .await;
9761
9762 let lines = app
9763 .store
9764 .recent_activity(
9765 20,
9766 iz_core::store::FeedPage::Newest,
9767 iz_core::store::Dir::Newest,
9768 &iz_core::store::ActivityFilter::default(),
9769 )
9770 .await
9771 .unwrap();
9772 let line_of = |raw: &str| {
9773 lines
9774 .iter()
9775 .find(|line| line.kind.as_str() == raw)
9776 .unwrap_or_else(|| panic!("no {raw} line: {lines:?}"))
9777 };
9778 assert_eq!(line_of("tag_created").detail, "Urgent");
9779 assert_eq!(line_of("tag_renamed").detail, "Urgent -> High");
9780 assert_eq!(line_of("tag_moved").detail, "Urgent");
9781 assert_eq!(line_of("tag_deleted").detail, "High");
9782 for raw in ["tag_created", "tag_renamed", "tag_moved", "tag_deleted"] {
9783 assert_eq!(
9784 line_of(raw).actor_name.as_deref(),
9785 Some("Ada Lovelace"),
9786 "{raw}"
9787 );
9788 }
9789}
9790
9791/// Filing a task under a tag writes one line on the task's own trail, naming
9792/// the tag, with the person who filed it as the actor.
9793#[tokio::test]
9794async fn tagging_a_task_records_a_trail_line() {
9795 let app = App::open().await;
9796 let admin_cookie = admin(&app).await;
9797 let workspace_id = app.workspace_id().await;
9798 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
9799 .await
9800 .unwrap()
9801 .unwrap();
9802 let column = board.columns[0].column.id.clone();
9803 let task = a_task(&app, &admin_cookie, &column, "Audit me").await;
9804 app.post(
9805 "/api/create_tag",
9806 Some(&admin_cookie),
9807 &[("name", "Shipped")],
9808 )
9809 .await;
9810 let tag = {
9811 let board = iz_core::board::load(app.store.as_ref(), &workspace_id)
9812 .await
9813 .unwrap()
9814 .unwrap();
9815 app.store
9816 .tags(&board.board.id)
9817 .await
9818 .unwrap()
9819 .into_iter()
9820 .find(|tag| tag.name == "Shipped")
9821 .expect("the tag was created")
9822 };
9823
9824 app.post(
9825 "/api/set_task_tag",
9826 Some(&admin_cookie),
9827 &[("task_id", &task), ("tag_id", &tag.id)],
9828 )
9829 .await;
9830
9831 let lines = app
9832 .store
9833 .recent_activity(
9834 20,
9835 iz_core::store::FeedPage::Newest,
9836 iz_core::store::Dir::Newest,
9837 &iz_core::store::ActivityFilter {
9838 kind: Some("tagged".to_string()),
9839 ..Default::default()
9840 },
9841 )
9842 .await
9843 .unwrap();
9844 assert_eq!(lines.len(), 1, "{lines:?}");
9845 assert_eq!(lines[0].detail, "Shipped");
9846 assert_eq!(lines[0].actor_name.as_deref(), Some("Ada Lovelace"));
9847}
9848
9849/// Asking for a mail-server check rides the trail too — it writes a check
9850/// row, so the trail says who asked.
9851#[tokio::test]
9852async fn checking_the_sender_records_an_event() {
9853 let app = App::open().await;
9854 let admin_cookie = admin(&app).await;
9855
9856 let answer = app
9857 .post("/api/check_sender", Some(&admin_cookie), &[])
9858 .await;
9859 assert_eq!(answer.status, StatusCode::SEE_OTHER);
9860
9861 let lines = app
9862 .store
9863 .recent_activity(
9864 20,
9865 iz_core::store::FeedPage::Newest,
9866 iz_core::store::Dir::Newest,
9867 &iz_core::store::ActivityFilter {
9868 kind: Some("sender_checked".to_string()),
9869 ..Default::default()
9870 },
9871 )
9872 .await
9873 .unwrap();
9874 assert_eq!(lines.len(), 1, "{lines:?}");
9875 assert_eq!(lines[0].actor_name.as_deref(), Some("Ada Lovelace"));
9876}
9877
9878/// A card's dependency summary names both directions with keys: what the card
9879/// blocks and what blocks it, the same list shape either way.
9880#[tokio::test]
9881async fn a_card_lists_both_dependency_directions_as_keys() {
9882 let app = App::open().await;
9883 let admin = admin(&app).await;
9884 let column = first_column(&app).await;
9885 let first = a_task(&app, &admin, &column, "Lay the cable").await;
9886 let second = a_task(&app, &admin, &column, "Light the cable").await;
9887 let first_key = app
9888 .store
9889 .task(&first)
9890 .await
9891 .unwrap()
9892 .expect("first task gone")
9893 .row
9894 .task_key;
9895 let second_key = app
9896 .store
9897 .task(&second)
9898 .await
9899 .unwrap()
9900 .expect("second task gone")
9901 .row
9902 .task_key;
9903
9904 // `second` is blocked by `first`, so `first` blocks `second`.
9905 let answer = app
9906 .post(
9907 "/api/link_tasks",
9908 Some(&admin),
9909 &[
9910 ("task_id", &second),
9911 ("other_id", &first),
9912 ("direction", "blocked_by"),
9913 ],
9914 )
9915 .await;
9916 assert_eq!(answer.body, "null", "the link was refused: {}", answer.body);
9917
9918 let page = app.get("/", Some(&admin)).await;
9919 let html = String::from_utf8_lossy(&page.bytes);
9920 assert!(
9921 html.contains(&format!(
9922 r#"class="card-blocks">blocks {second_key}</span>"#
9923 )),
9924 "the blocker's card did not name what it blocks: {html}"
9925 );
9926 assert!(html.contains(&format!(
9927 r#"class="card-blocked-by">blocked by {first_key}</span>"#
9928 )),);
9929}
9930
9931/// The board search filters server-side by key and title, composes with the
9932/// project filter, and a query nothing answers says so in one line.
9933#[tokio::test]
9934async fn the_board_search_filters_and_composes_with_the_project_filter() {
9935 let app = App::open().await;
9936 let admin = admin(&app).await;
9937 let column = first_column(&app).await;
9938 let panel = a_task(&app, &admin, &column, "Panel polish").await;
9939 let _wire = a_task(&app, &admin, &column, "Wire the exporter").await;
9940 let aurora = a_tag(&app, &admin, "Aurora").await;
9941 let boreal = a_tag(&app, &admin, "Boreal").await;
9942 let answer = app
9943 .post(
9944 "/api/set_task_tag",
9945 Some(&admin),
9946 &[("task_id", &panel), ("tag_id", &aurora.id)],
9947 )
9948 .await;
9949 assert_eq!(
9950 answer.body, "null",
9951 "the tag did not attach: {}",
9952 answer.body
9953 );
9954 let panel_key = app
9955 .store
9956 .task(&panel)
9957 .await
9958 .unwrap()
9959 .expect("panel task gone")
9960 .row
9961 .task_key;
9962
9963 // By key, typed in any case: its card stays, the other goes.
9964 let page = app
9965 .get(&format!("/?q={}", panel_key.to_lowercase()), Some(&admin))
9966 .await;
9967 let html = String::from_utf8_lossy(&page.bytes);
9968 assert!(html.contains("Panel polish"), "{html}");
9969 assert!(!html.contains("Wire the exporter"), "{html}");
9970
9971 // By title fragment, any case.
9972 let page = app.get("/?q=EXPORTER", Some(&admin)).await;
9973 let html = String::from_utf8_lossy(&page.bytes);
9974 assert!(html.contains("Wire the exporter"), "{html}");
9975 assert!(!html.contains("Panel polish"), "{html}");
9976
9977 // Search and project compose: both must hold for a card to show.
9978 let page = app
9979 .get(&format!("/?q=polish&tag={}", aurora.id), Some(&admin))
9980 .await;
9981 let html = String::from_utf8_lossy(&page.bytes);
9982 assert!(html.contains("Panel polish"), "{html}");
9983 let page = app
9984 .get(&format!("/?q=polish&tag={}", boreal.id), Some(&admin))
9985 .await;
9986 let html = String::from_utf8_lossy(&page.bytes);
9987 assert!(html.contains("No matches"), "{html}");
9988 assert!(!html.contains("Panel polish"), "{html}");
9989
9990 // Clearing the box restores the whole board.
9991 let page = app.get("/", Some(&admin)).await;
9992 let html = String::from_utf8_lossy(&page.bytes);
9993 assert!(
9994 html.contains("Panel polish") && html.contains("Wire the exporter"),
9995 "{html}"
9996 );
9997}
9998
9999// A `multiple` picker posts several `file` parts in one form; every part
10000// lands as its own attachment with its own bytes, under the same type and
10001// size rules the single-file path always had.
10002#[tokio::test]
10003async fn a_multi_file_picker_lands_every_part_as_its_own_attachment() {
10004 let app = App::open().await;
10005 let admin_cookie = admin(&app).await;
10006 let column = first_column(&app).await;
10007 let task = a_task(&app, &admin_cookie, &column, "Two parts, one post").await;
10008
10009 const BOUNDARY: &str = "iz-test-boundary";
10010 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 9, 9];
10011 let text = b"hello, from the second part".as_slice();
10012 let mut body = Vec::new();
10013 body.extend_from_slice(
10014 format!(
10015 "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"task_id\"\r\n\r\n{task}\r\n"
10016 )
10017 .as_bytes(),
10018 );
10019 for (filename, content_type, bytes) in [
10020 ("first.png", "image/png", &png[..]),
10021 ("notes.txt", "text/plain", text),
10022 ] {
10023 body.extend_from_slice(
10024 format!(
10025 "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: {content_type}\r\n\r\n"
10026 )
10027 .as_bytes(),
10028 );
10029 body.extend_from_slice(bytes);
10030 body.extend_from_slice(b"\r\n");
10031 }
10032 body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
10033
10034 let request = Request::builder()
10035 .method("POST")
10036 .uri("/files")
10037 .header(
10038 header::CONTENT_TYPE,
10039 format!("multipart/form-data; boundary={BOUNDARY}"),
10040 )
10041 .header(
10042 header::COOKIE,
10043 HeaderValue::from_str(&format!("{SESSION_COOKIE}={admin_cookie}")).unwrap(),
10044 )
10045 .body(Body::from(body))
10046 .unwrap();
10047 let answer = Answer::from_response(app.router.handle(request).await).await;
10048 assert_eq!(answer.status, StatusCode::SEE_OTHER);
10049 assert_eq!(
10050 answer.location.as_deref(),
10051 Some(format!("/?task={task}&tab=files").as_str())
10052 );
10053
10054 let snapshot = app
10055 .post(
10056 "/api/fetch_task",
10057 Some(&admin_cookie),
10058 &[("task_id", &task)],
10059 )
10060 .await;
10061 let png_id = attachment_id_named(&snapshot.body, "first.png");
10062 let txt_id = attachment_id_named(&snapshot.body, "notes.txt");
10063
10064 let png_back = app
10065 .get(&format!("/files/{png_id}"), Some(&admin_cookie))
10066 .await;
10067 assert_eq!(png_back.bytes, png);
10068 let txt_back = app
10069 .get(&format!("/files/{txt_id}"), Some(&admin_cookie))
10070 .await;
10071 assert_eq!(txt_back.bytes, text);
10072}
10073
10074/// The board's assignee filter narrows to one member's cards, and `none`
10075/// narrows to the cards nobody is on; a bogus id falls back to all.
10076#[tokio::test]
10077async fn the_board_assignee_filter_narrows_and_a_bogus_id_falls_back_to_all() {
10078 let app = App::open().await;
10079 let admin_cookie = admin(&app).await;
10080 invited(&app, &admin_cookie, "deniz@iz.sh", "Deniz", Role::Member).await;
10081 let columns = columns_of(&app).await;
10082 let assigned_task = a_task(&app, &admin_cookie, &columns[0], "Deniz work").await;
10083 a_task(&app, &admin_cookie, &columns[0], "Loose work").await;
10084 let deniz_id = person_id(&app, &admin_cookie, &assigned_task, "Deniz").await;
10085 app.post(
10086 "/api/assign",
10087 Some(&admin_cookie),
10088 &[("task_id", &assigned_task), ("user_id", &deniz_id)],
10089 )
10090 .await;
10091
10092 let filtered = String::from_utf8(
10093 app.get(&format!("/?assigned={deniz_id}"), Some(&admin_cookie))
10094 .await
10095 .bytes,
10096 )
10097 .unwrap();
10098 assert!(
10099 filtered.contains("Deniz work"),
10100 "the assigned card is gone: {filtered}"
10101 );
10102 assert!(
10103 !filtered.contains("Loose work"),
10104 "the unassigned card did not filter out: {filtered}"
10105 );
10106
10107 let nobody =
10108 String::from_utf8(app.get("/?assigned=none", Some(&admin_cookie)).await.bytes).unwrap();
10109 assert!(
10110 nobody.contains("Loose work"),
10111 "the unassigned card is gone: {nobody}"
10112 );
10113 assert!(
10114 !nobody.contains("Deniz work"),
10115 "the assigned card did not filter out: {nobody}"
10116 );
10117
10118 let everything =
10119 String::from_utf8(app.get("/?assigned=bogus", Some(&admin_cookie)).await.bytes).unwrap();
10120 assert!(
10121 everything.contains("Deniz work") && everything.contains("Loose work"),
10122 "a bogus assignee did not fall back to all: {everything}"
10123 );
10124}
10125
10126/// The other filter forms carry the active assignee in a hidden input, so
10127/// switching the tag, the sort or the search keeps the assignee narrow.
10128#[tokio::test]
10129async fn the_board_filter_forms_preserve_the_assignee_filter() {
10130 let app = App::open().await;
10131 let admin_cookie = admin(&app).await;
10132 invited(&app, &admin_cookie, "deniz@iz.sh", "Deniz", Role::Member).await;
10133 let columns = columns_of(&app).await;
10134 let task = a_task(&app, &admin_cookie, &columns[0], "Deniz work").await;
10135 let deniz_id = person_id(&app, &admin_cookie, &task, "Deniz").await;
10136 app.post(
10137 "/api/assign",
10138 Some(&admin_cookie),
10139 &[("task_id", &task), ("user_id", &deniz_id)],
10140 )
10141 .await;
10142
10143 let page = String::from_utf8(
10144 app.get(&format!("/?assigned={deniz_id}"), Some(&admin_cookie))
10145 .await
10146 .bytes,
10147 )
10148 .unwrap();
10149 assert_eq!(
10150 page.matches(&format!(r#"name="assigned" value="{deniz_id}""#))
10151 .count(),
10152 3,
10153 "the tag, sort and search forms do not each carry the assignee: {page}"
10154 );
10155}
10156
10157// The build stamp rides the html element of every render — the page a tab
10158// loaded and every response a soft navigation or live refresh will fetch —
10159// so a tab open across a deploy can tell stale css from current and reload
10160// itself rather than paint new markup with old styles.
10161#[tokio::test]
10162async fn the_build_stamp_matches_across_page_and_refetch() {
10163 let app = App::open().await;
10164 let admin_cookie = admin(&app).await;
10165
10166 let mut stamps = Vec::new();
10167 for path in ["/", "/settings", "/"] {
10168 let page = app.get(path, Some(&admin_cookie)).await;
10169 assert_eq!(page.status, StatusCode::OK);
10170 let html = String::from_utf8_lossy(&page.bytes);
10171 let stamp = html
10172 .split("data-build=\"")
10173 .nth(1)
10174 .map(|rest| rest.split('"').next().unwrap_or("").to_string())
10175 .unwrap_or_default();
10176 assert!(!stamp.is_empty(), "no data-build stamp on {path}");
10177 stamps.push(stamp);
10178 }
10179 assert!(
10180 stamps.windows(2).all(|pair| pair[0] == pair[1]),
10181 "the build stamp drifted between renders: {stamps:?}"
10182 );
10183}
10184
10185/// The served stylesheet is the one compiled into this build: the page
10186/// references it, the route answers it, and the bytes are the bytes
10187/// build.rs wrote — not a bundle from another generation.
10188#[tokio::test]
10189async fn the_served_stylesheet_is_this_builds_bytes() {
10190 let app = App::open().await;
10191 let page = app.get("/", None).await;
10192 assert_eq!(page.status, StatusCode::OK);
10193 let html = String::from_utf8_lossy(&page.bytes);
10194 let url = html
10195 .split('"')
10196 .find(|piece| piece.starts_with("/_topcoat/assets/main-") && piece.ends_with(".css"))
10197 .expect("the page references no stylesheet")
10198 .to_string();
10199 let served = app.get(&url, None).await;
10200 assert_eq!(served.status, StatusCode::OK);
10201 assert!(!served.bytes.is_empty());
10202 let compiled = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/assets/main.css"))
10203 .expect("the compiled stylesheet is gone");
10204 assert_eq!(
10205 served.bytes, compiled,
10206 "the server served another generation's stylesheet"
10207 );
10208}
10209
10210/// The boot guard refuses a bundle whose stylesheet bytes are not the
10211/// generation this binary was compiled against, and accepts its own.
10212#[test]
10213fn the_stylesheet_guard_refuses_a_foreign_bundle() {
10214 let bundle = AssetBundle::load_dir(asset_dir()).expect("no bundle: run `topcoat asset bundle`");
10215 assert!(iz_web::server::stylesheet_guard(&bundle).is_ok());
10216
10217 let foreign = std::env::temp_dir().join(format!("iz-foreign-{}", Ulid::generate()));
10218 std::fs::create_dir_all(&foreign).unwrap();
10219 for entry in std::fs::read_dir(asset_dir()).unwrap().flatten() {
10220 std::fs::copy(entry.path(), foreign.join(entry.file_name())).unwrap();
10221 }
10222 let stylesheet = std::fs::read_dir(&foreign)
10223 .unwrap()
10224 .filter_map(|entry| {
10225 let name = entry.ok()?.file_name().into_string().ok()?;
10226 (name.starts_with("main-") && name.ends_with(".css")).then_some(name)
10227 })
10228 .next()
10229 .expect("no stylesheet in the copied bundle");
10230 std::fs::write(
10231 foreign.join(&stylesheet),
10232 "body { color: another-generation }",
10233 )
10234 .unwrap();
10235
10236 let foreign_bundle = AssetBundle::load_dir(&foreign).expect("the copied bundle does not load");
10237 let problem = iz_web::server::stylesheet_guard(&foreign_bundle)
10238 .expect_err("a foreign bundle passed the guard");
10239 assert!(problem.contains("another build"), "{problem}");
10240 std::fs::remove_dir_all(&foreign).unwrap();
10241}
10242
10243/// Sign-out leaves through the family's front door: the local cookie is
10244/// cleared, and the browser is handed to im's `/logout` with `back` pointed
10245/// at this app. Where "here" is resolves per request — the stored public
10246/// address wins, the configured `base_url` is the fallback, and the
10247/// address the server binds is the last resort.
10248#[tokio::test]
10249async fn a_sign_out_hands_the_browser_to_the_providers_logout_pointed_home() {
10250 // No stored address, no configured one: the bind address answers.
10251 let app = App::open().await;
10252 let admin = admin(&app).await;
10253 let raw = app.get("/auth/logout", Some(&admin)).await;
10254 assert_eq!(raw.status, StatusCode::SEE_OTHER);
10255 let expected = format!(
10256 "{}/logout?back={}",
10257 app.client.issuer,
10258 encode("http://127.0.0.1:7655/")
10259 );
10260 assert_eq!(raw.location.as_deref(), Some(expected.as_str()));
10261
10262 // A configured `base_url` is what the fallback says when nothing is
10263 // stored — a deployment behind a proxy says its name once, in the file.
10264 let configured = App::build_with(Mail::silent(), None, "https://board.example", None).await;
10265 let raw = configured.get("/auth/logout", None).await;
10266 let expected = format!(
10267 "{}/logout?back={}",
10268 configured.client.issuer,
10269 encode("https://board.example/")
10270 );
10271 assert_eq!(raw.location.as_deref(), Some(expected.as_str()));
10272
10273 // A stored public address wins over the configured chain, and it reads
10274 // per request: no restart between the save and the next sign-out.
10275 let stored = App::build_with(Mail::silent(), None, "https://stale.example", None).await;
10276 stored
10277 .store
10278 .set_setting(iz_web::server::PUBLIC_URL_KEY, "https://stored.example")
10279 .await
10280 .unwrap();
10281 let raw = stored.get("/auth/logout", None).await;
10282 let expected = format!(
10283 "{}/logout?back={}",
10284 stored.client.issuer,
10285 encode("https://stored.example/")
10286 );
10287 assert_eq!(raw.location.as_deref(), Some(expected.as_str()));
10288}
10289
10290/// The flyout under the monogram renders the family list the app mirrors
10291/// from im — the stored JSON, in stored order, minus this app's own row,
10292/// each sibling a plain link out wearing its health dot. A list that is
10293/// absent, empty, will not parse, or holds this app alone shows the bare
10294/// mark and no flyout.
10295#[tokio::test]
10296async fn the_topbar_shows_the_family_switcher_and_marks_this_app_only_when_configured() {
10297 let family = "\
10298 [{\"key\":\"in\",\"name\":\"Files\",\"url\":\"http://127.0.0.1:9655\"},\
10299 {\"key\":\"iz\",\"name\":\"Board\",\"url\":\"http://127.0.0.1:9654\"},\
10300 {\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:9650\"}]"
10301 .to_string();
10302 let app = App::build_with(Mail::silent(), Some(family), "", None).await;
10303 let board_admin = admin(&app).await;
10304 let html = String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string();
10305 assert!(html.contains("wordmark-family"), "{html}");
10306 assert!(html.contains("service-switcher"), "{html}");
10307 // This app has no door back into itself: only the siblings hang there,
10308 // in the order im served them.
10309 assert!(!html.contains("href=\"http://127.0.0.1:9654\""), "{html}");
10310 let in_at = html.find("href=\"http://127.0.0.1:9655\"").unwrap();
10311 let im_at = html.find("href=\"http://127.0.0.1:9650\"").unwrap();
10312 assert!(in_at < im_at, "marks out of order: {html}");
10313
10314 // The dots ride along: the fixture's ports answer nobody, so the
10315 // siblings read down — the flyout still renders, dots and all.
10316 assert!(html.contains("health-dot"), "{html}");
10317 assert!(html.contains("health-dot health-off"), "{html}");
10318
10319 // A list that will not parse hides the flyout rather than rendering
10320 // half of it — and so do an empty one, a list holding this app alone,
10321 // and a mirror that never arrived.
10322 let alone = "[{\"key\":\"iz\",\"name\":\"Board\",\"url\":\"http://127.0.0.1:7654\"}]";
10323 for broken in ["[".to_string(), "[]".to_string(), alone.to_string()] {
10324 let app = App::build_with(Mail::silent(), Some(broken), "", None).await;
10325 let board_admin = admin(&app).await;
10326 let html =
10327 String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string();
10328 assert!(!html.contains("service-switcher"), "{html}");
10329 assert!(!html.contains("health-dot"), "{html}");
10330 }
10331 let plain = App::open().await;
10332 let alone_admin = admin(&plain).await;
10333 let plain =
10334 String::from_utf8_lossy(&plain.get("/", Some(&alone_admin)).await.bytes).to_string();
10335 assert!(
10336 !plain.contains("service-switcher"),
10337 "no mirror, no switcher: {plain}"
10338 );
10339}
10340
10341/// The flyout's dots are the probe's reading, live: a sibling answering
10342/// the deploy body renders `health-on`, a port nobody listens on renders
10343/// `health-off` — dots only, the body and the latency never leave the probe.
10344#[tokio::test]
10345async fn the_switcher_marks_a_live_sibling_on_and_a_dark_one_off() {
10346 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
10347
10348 // A stand-in sibling answering the deploy body.
10349 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
10350 let addr = listener.local_addr().unwrap();
10351 let talker = tokio::spawn(async move {
10352 let (mut socket, _) = listener.accept().await.unwrap();
10353 let mut buf = [0u8; 1024];
10354 let _ = socket.read(&mut buf).await;
10355 socket
10356 .write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 6\r\n\r\nok dev")
10357 .await
10358 .unwrap();
10359 });
10360
10361 // And a port nobody listens on: refused the moment the probe dials.
10362 let dark = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
10363 let dark_addr = dark.local_addr().unwrap();
10364 drop(dark);
10365
10366 let family = format!(
10367 "[{{\"key\":\"in\",\"name\":\"Files\",\"url\":\"http://{addr}\"}},\
10368 {{\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://{dark_addr}\"}}]"
10369 );
10370 let app = App::build_with(Mail::silent(), Some(family), "", None).await;
10371 let board_admin = admin(&app).await;
10372 let html = String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string();
10373 assert!(
10374 html.contains("health-dot health-on"),
10375 "the ok sibling reads on: {html}"
10376 );
10377 assert!(html.contains(">in</a>"), "the live sibling renders: {html}");
10378 assert!(
10379 html.contains("health-dot health-off"),
10380 "the dark sibling reads off: {html}"
10381 );
10382 assert!(html.contains(">im</a>"), "the dark sibling renders: {html}");
10383 assert!(
10384 !html.contains("ok dev"),
10385 "the flyout carries dots only: {html}"
10386 );
10387}
10388
10389/// The marks are pinned without a router, a bundle or a live sibling: a
10390/// probe's `Up` reads `health-on` and its `Down` reads `health-off`, the
10391/// keys stay titled links out carrying `data-hard`, iz's own row is no door
10392/// back, the middots separate, and the probe's body and latency never render.
10393#[test]
10394fn the_switcher_marks_render_from_resolved_probes_alone() {
10395 use iz_web::health::{Probe, switcher_marks};
10396
10397 let marks = switcher_marks([
10398 (
10399 "in",
10400 "Files",
10401 "http://127.0.0.1:7655",
10402 Probe::Up {
10403 body: "ok dev".to_string(),
10404 ms: 3,
10405 },
10406 ),
10407 ("iz", "Board", "http://127.0.0.1:7654", Probe::Down),
10408 ("im", "Account", "http://127.0.0.1:7650", Probe::Down),
10409 ]);
10410 assert!(
10411 marks.contains("health-dot health-on"),
10412 "the ok sibling reads on: {marks}"
10413 );
10414 assert!(
10415 marks.contains(">in</a>"),
10416 "the live sibling renders: {marks}"
10417 );
10418 assert!(
10419 marks.contains("health-dot health-off"),
10420 "the dark sibling reads off: {marks}"
10421 );
10422 assert!(
10423 marks.contains(">im</a>"),
10424 "the dark sibling renders: {marks}"
10425 );
10426 assert!(
10427 !marks.contains(">iz</a>"),
10428 "iz's own row stays out: {marks}"
10429 );
10430 assert!(
10431 marks.contains("title=\"Files\""),
10432 "the mark keeps its human name: {marks}"
10433 );
10434 assert!(
10435 marks.contains("data-hard"),
10436 "the links leave this origin: {marks}"
10437 );
10438 assert!(
10439 marks.contains(r#"<span class="service-sep">·</span>"#),
10440 "middots between: {marks}"
10441 );
10442 assert!(
10443 !marks.contains("ok dev") && !marks.contains(" ms"),
10444 "the flyout carries dots only: {marks}"
10445 );
10446}
10447
10448// -- the Files service ------------------------------------------------------
10449
10450/// The Bearer key the storage tests name in `[storage.in]`: the fake in
10451/// answers it and nothing else, so a call that arrives without it is a
10452/// 401 the same way the real service answers an unknown key.
10453const STORAGE_TOKEN: &str = "iz-storage-key";
10454
10455/// A fake in: the Files service's machine side over bare TCP, canned the
10456/// way `iz_web::storage::StorageClient` speaks. Every `/api/service/*`
10457/// call is recorded as `"<METHOD> <path>"` so a test can assert on the
10458/// wire, not only on the rows; a push's file part is kept and served
10459/// back by `GET /api/service/file/{id}`, so the fetch path reads the
10460/// same bytes the push path wrote.
10461struct FakeIn {
10462 addr: std::net::SocketAddr,
10463 calls: Arc<Mutex<Vec<String>>>,
10464 files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
10465 refuse_quota: Arc<std::sync::atomic::AtomicBool>,
10466 down: Arc<std::sync::atomic::AtomicBool>,
10467}
10468
10469impl FakeIn {
10470 async fn spawn() -> Self {
10471 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
10472 let addr = listener.local_addr().unwrap();
10473 let calls: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
10474 let files: Arc<Mutex<HashMap<String, Vec<u8>>>> = Arc::new(Mutex::new(HashMap::new()));
10475 let refuse_quota = Arc::new(std::sync::atomic::AtomicBool::new(false));
10476 let down = Arc::new(std::sync::atomic::AtomicBool::new(false));
10477 let log = calls.clone();
10478 let store = files.clone();
10479 let quota_flag = refuse_quota.clone();
10480 let down_flag = down.clone();
10481 tokio::spawn(async move {
10482 loop {
10483 let Ok((socket, _)) = listener.accept().await else {
10484 return;
10485 };
10486 if down_flag.load(std::sync::atomic::Ordering::SeqCst) {
10487 continue;
10488 }
10489 let log = log.clone();
10490 let store = store.clone();
10491 let quota_flag = quota_flag.clone();
10492 let socket_down = down_flag.clone();
10493 tokio::spawn(async move {
10494 use tokio::io::{AsyncReadExt, AsyncWriteExt};
10495 let mut socket = socket;
10496 let mut buf = vec![0u8; 8192];
10497 let mut req = Vec::new();
10498 // Same keep-alive loop as the fake im: closing after
10499 // every answer races the client's pool.
10500 loop {
10501 let body_start = loop {
10502 let Ok(n) = socket.read(&mut buf).await else {
10503 return;
10504 };
10505 if n == 0 {
10506 return;
10507 }
10508 req.extend_from_slice(&buf[..n]);
10509 if let Some(end) = headers_end(&req) {
10510 let head = String::from_utf8_lossy(&req[..end]).to_string();
10511 let len = content_length(&head);
10512 if req.len() >= end + len {
10513 break end;
10514 }
10515 }
10516 if req.len() > 2_000_000 {
10517 return;
10518 }
10519 };
10520 let head = String::from_utf8_lossy(&req[..body_start]).to_string();
10521 // Down is per request, not per socket: a pooled
10522 // connection that was alive when the service went
10523 // down must stop answering too, the way the real
10524 // service's sockets die mid-conversation.
10525 if socket_down.load(std::sync::atomic::Ordering::SeqCst) {
10526 return;
10527 }
10528 let first = head.lines().next().unwrap_or("").to_string();
10529 let len = content_length(&head);
10530 let body: Vec<u8> = req[body_start..body_start + len].to_vec();
10531 req.drain(..body_start + len);
10532 let (status, content_type, payload) =
10533 storage_answer(&log, &store, &quota_flag, &head, &first, &body);
10534 let response = format!(
10535 "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n",
10536 payload.len()
10537 );
10538 if socket.write_all(response.as_bytes()).await.is_err() {
10539 return;
10540 }
10541 if socket.write_all(&payload).await.is_err() {
10542 return;
10543 }
10544 }
10545 });
10546 }
10547 });
10548 Self {
10549 addr,
10550 calls,
10551 files,
10552 refuse_quota,
10553 down,
10554 }
10555 }
10556
10557 fn url(&self) -> String {
10558 format!("http://{}", self.addr)
10559 }
10560
10561 /// The wire, in order: one `"<METHOD> <path>"` per service call.
10562 fn calls(&self) -> Vec<String> {
10563 self.calls.lock().clone()
10564 }
10565
10566 /// Whether a push under this id is being held by the service.
10567 fn holds(&self, id: &str) -> bool {
10568 self.files.lock().contains_key(id)
10569 }
10570
10571 fn refuse_quota(&self) {
10572 self.refuse_quota
10573 .store(true, std::sync::atomic::Ordering::SeqCst);
10574 }
10575
10576 /// Stops answering — accepts and drops, which reads to the client as
10577 /// the connection the storage ceilings are for.
10578 fn set_down(&self) {
10579 self.down.store(true, std::sync::atomic::Ordering::SeqCst);
10580 }
10581}
10582
10583/// The fake in's one router: the probe is open, the machine side wants
10584/// the Bearer key, and the four service routes answer the JSON shape the
10585/// client parses. A push is kept under its `external_id` — pulled out of
10586/// the multipart body by boundary, the way the real service's form
10587/// parser would — so the fetch and delete routes have something real to
10588/// work on.
10589fn storage_answer(
10590 log: &Arc<Mutex<Vec<String>>>,
10591 files: &Arc<Mutex<HashMap<String, Vec<u8>>>>,
10592 refuse_quota: &Arc<std::sync::atomic::AtomicBool>,
10593 head: &str,
10594 request_line: &str,
10595 body: &[u8],
10596) -> (&'static str, String, Vec<u8>) {
10597 let mut parts = request_line.split_whitespace();
10598 let method = parts.next().unwrap_or("");
10599 let target = parts.next().unwrap_or("");
10600 let path = target
10601 .split_once('?')
10602 .map(|(path, _)| path)
10603 .unwrap_or(target);
10604 if method == "GET" && path == "/healthz" {
10605 return ("200 OK", "text/plain".to_string(), b"ok".to_vec());
10606 }
10607 let authed = head
10608 .lines()
10609 .filter_map(|line| line.split_once(':'))
10610 .any(|(name, value)| {
10611 name.trim().eq_ignore_ascii_case("authorization")
10612 && value.trim() == format!("Bearer {STORAGE_TOKEN}")
10613 });
10614 if !authed {
10615 return (
10616 "401 Unauthorized",
10617 "application/json".to_string(),
10618 br#"{"err":"Unauthorized"}"#.to_vec(),
10619 );
10620 }
10621 log.lock().push(format!("{method} {path}"));
10622 match (method, path) {
10623 ("GET", "/api/service/status") => (
10624 "200 OK",
10625 "application/json".to_string(),
10626 br#"{"ok":true,"quota_bytes":10737418240,"used_bytes":1073741824}"#.to_vec(),
10627 ),
10628 ("POST", "/api/service/files") => {
10629 if refuse_quota.load(std::sync::atomic::Ordering::SeqCst) {
10630 return (
10631 "200 OK",
10632 "application/json".to_string(),
10633 br#"{"err":"QuotaExceeded"}"#.to_vec(),
10634 );
10635 }
10636 let Some(id) = multipart_field(body, head, "external_id") else {
10637 return (
10638 "400 Bad Request",
10639 "application/json".to_string(),
10640 br#"{"err":"NoExternalId"}"#.to_vec(),
10641 );
10642 };
10643 let bytes = multipart_file(body, head);
10644 files.lock().insert(id.clone(), bytes);
10645 let answer = format!("{{\"ok\":\"{id}\"}}");
10646 (
10647 "200 OK",
10648 "application/json".to_string(),
10649 answer.into_bytes(),
10650 )
10651 }
10652 ("GET", path) => match path.strip_prefix("/api/service/file/") {
10653 Some(id) if !id.is_empty() => match files.lock().get(id) {
10654 Some(bytes) => (
10655 "200 OK",
10656 "application/octet-stream".to_string(),
10657 bytes.clone(),
10658 ),
10659 None => (
10660 "404 Not Found",
10661 "application/json".to_string(),
10662 br#"{"err":"NotFound"}"#.to_vec(),
10663 ),
10664 },
10665 _ => (
10666 "404 Not Found",
10667 "application/json".to_string(),
10668 br#"{"err":"NotFound"}"#.to_vec(),
10669 ),
10670 },
10671 ("DELETE", path) => {
10672 if let Some(id) = path.strip_prefix("/api/service/file/") {
10673 files.lock().remove(id);
10674 }
10675 (
10676 "200 OK",
10677 "application/json".to_string(),
10678 br#"{"ok":true}"#.to_vec(),
10679 )
10680 }
10681 _ => ("404 Not Found", "text/plain".to_string(), Vec::new()),
10682 }
10683}
10684/// One text field out of a multipart body, by `name`. The parts are read
10685/// line-wise — a part's headers carry `name="..."`, its value rides the
10686/// lines after them — which is enough for the two fields the client
10687/// writes; the content-type check is the proof this is a multipart body
10688/// at all.
10689fn multipart_field(body: &[u8], head: &str, name: &str) -> Option<String> {
10690 let multipart = head.lines().any(|line| {
10691 line.to_ascii_lowercase()
10692 .starts_with("content-type: multipart/form-data")
10693 });
10694 if !multipart {
10695 return None;
10696 }
10697 let marker = format!("name=\"{name}\"");
10698 let mut in_part = false;
10699 for part in body.split(|&b| b == b'\n') {
10700 let text = String::from_utf8_lossy(part);
10701 let line = text.trim_end_matches('\r');
10702 if line.starts_with("--") {
10703 in_part = false;
10704 continue;
10705 }
10706 // The header line names the part; the value is the first line
10707 // after the blank one that follows it.
10708 if in_part {
10709 if !line.is_empty() {
10710 return Some(line.to_string());
10711 }
10712 } else if line.contains(&marker) && line.contains(':') {
10713 in_part = true;
10714 }
10715 }
10716 None
10717}
10718
10719/// The file part's bytes out of a multipart body: everything between the
10720/// `name="file"` part's blank line and the boundary that closes it.
10721fn multipart_file(body: &[u8], head: &str) -> Vec<u8> {
10722 let Some(boundary) = head
10723 .lines()
10724 .filter_map(|line| line.split_once(':'))
10725 .find(|(field, _)| field.trim().eq_ignore_ascii_case("content-type"))
10726 .and_then(|(_, value)| value.split("boundary=").nth(1).map(str::trim))
10727 else {
10728 return Vec::new();
10729 };
10730 let marker = format!("--{boundary}");
10731 let needle = b"name=\"file\"";
10732 let Some(at) = body.windows(needle.len()).position(|w| w == needle) else {
10733 return Vec::new();
10734 };
10735 let after = &body[at..];
10736 let Some(start) = after.windows(4).position(|w| w == b"\r\n\r\n") else {
10737 return Vec::new();
10738 };
10739 let bytes = &after[start + 4..];
10740 let end = bytes
10741 .windows(marker.len())
10742 .position(|w| w == marker.as_bytes())
10743 .unwrap_or(bytes.len());
10744 bytes[..end]
10745 .strip_suffix(b"\r\n")
10746 .unwrap_or(&bytes[..end])
10747 .to_vec()
10748}
10749
10750/// The family mirror holding a Files row at `url`: the JSON the `setting`
10751/// row keeps, exactly the shape the beat stores.
10752fn family_with_in(url: &str) -> String {
10753 format!(
10754 "[{{\"key\":\"in\",\"name\":\"Files\",\"url\":\"{url}\"}},\
10755 {{\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:7650\"}}]"
10756 )
10757}
10758
10759/// An app whose deployment named a storage key, with a Files service in
10760/// the family mirror to point at.
10761async fn storage_app(fake: &FakeIn) -> App {
10762 App::build_with(
10763 Mail::silent(),
10764 Some(family_with_in(&fake.url())),
10765 "",
10766 Some(STORAGE_TOKEN.to_string()),
10767 )
10768 .await
10769}
10770
10771/// How many files sit in the storage tree's attachment directory: the
10772/// honest count of what is still on this disk.
10773fn local_file_count(app: &App) -> usize {
10774 std::fs::read_dir(app.dir.join("storage").join("attachments"))
10775 .map(|entries| entries.count())
10776 .unwrap_or(0)
10777}
10778
10779#[tokio::test]
10780async fn an_upload_in_in_mode_lands_on_the_service_and_serves_from_it() {
10781 let fake = FakeIn::spawn().await;
10782 let app = storage_app(&fake).await;
10783 let admin_cookie = admin(&app).await;
10784 let column = first_column(&app).await;
10785 let task = a_task(&app, &admin_cookie, &column, "Stored upload").await;
10786
10787 let saved = app
10788 .post(
10789 "/api/save_storage",
10790 Some(&admin_cookie),
10791 &[("backend", "in")],
10792 )
10793 .await;
10794 assert_eq!(saved.status, StatusCode::SEE_OTHER, "{}", saved.body);
10795 assert!(
10796 saved
10797 .location
10798 .as_deref()
10799 .unwrap_or_default()
10800 .contains("saved=save_storage&section=limits"),
10801 "{:?}",
10802 saved.location
10803 );
10804
10805 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
10806 let answer = app
10807 .post_multipart(
10808 "/files",
10809 Some(&admin_cookie),
10810 &[("task_id", &task)],
10811 Some(("spec.png", "image/png", &png)),
10812 )
10813 .await;
10814 assert_eq!(answer.status, StatusCode::SEE_OTHER);
10815 assert_eq!(
10816 answer.location.as_deref(),
10817 Some(format!("/?task={task}&tab=files").as_str())
10818 );
10819 assert!(
10820 fake.calls()
10821 .iter()
10822 .any(|call| call == "POST /api/service/files"),
10823 "the push never happened: {:?}",
10824 fake.calls()
10825 );
10826
10827 let rows = app.store.attachments(&task).await.unwrap();
10828 assert_eq!(rows.len(), 1);
10829 assert_eq!(rows[0].remote, iz_core::store::AttachmentWhere::Stored);
10830 assert_eq!(local_file_count(&app), 0, "a local file was written anyway");
10831 assert!(fake.holds(&rows[0].id));
10832
10833 let download = app
10834 .get(&format!("/files/{}", rows[0].id), Some(&admin_cookie))
10835 .await;
10836 assert_eq!(download.status, StatusCode::OK);
10837 assert_eq!(download.bytes, png);
10838 assert_eq!(download.content_type.as_deref(), Some("image/png"));
10839 assert!(
10840 download
10841 .disposition
10842 .as_deref()
10843 .unwrap_or_default()
10844 .starts_with("inline;"),
10845 "{:?}",
10846 download.disposition
10847 );
10848 assert_eq!(
10849 download.cache_control.as_deref(),
10850 Some("private, max-age=31536000, immutable")
10851 );
10852 assert!(
10853 fake.calls()
10854 .iter()
10855 .any(|call| call.starts_with("GET /api/service/file/")),
10856 "the fetch never happened: {:?}",
10857 fake.calls()
10858 );
10859}
10860
10861/// A Files service that is not there is refused in the moment, on every
10862/// leg: the upload says so, the download is a 503 rather than a
10863/// not-found, and the delete leaves the row exactly where it was.
10864#[tokio::test]
10865async fn a_down_files_service_refuses_uploads_downloads_and_deletes() {
10866 let fake = FakeIn::spawn().await;
10867 let app = storage_app(&fake).await;
10868 let admin_cookie = admin(&app).await;
10869 let column = first_column(&app).await;
10870 let task = a_task(&app, &admin_cookie, &column, "Down service").await;
10871 app.post(
10872 "/api/save_storage",
10873 Some(&admin_cookie),
10874 &[("backend", "in")],
10875 )
10876 .await;
10877
10878 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
10879 app.post_multipart(
10880 "/files",
10881 Some(&admin_cookie),
10882 &[("task_id", &task)],
10883 Some(("up.png", "image/png", &png)),
10884 )
10885 .await;
10886 let rows = app.store.attachments(&task).await.unwrap();
10887 assert_eq!(rows.len(), 1);
10888 let stored = rows[0].id.clone();
10889
10890 fake.set_down();
10891
10892 let answer = app
10893 .post_multipart(
10894 "/files",
10895 Some(&admin_cookie),
10896 &[("task_id", &task)],
10897 Some(("down.png", "image/png", &png)),
10898 )
10899 .await;
10900 assert_eq!(answer.status, StatusCode::SEE_OTHER);
10901 assert!(
10902 answer
10903 .location
10904 .as_deref()
10905 .unwrap_or_default()
10906 .contains("refusal=storage-unavailable&on=upload_file"),
10907 "{:?}",
10908 answer.location
10909 );
10910 assert_eq!(app.store.attachments(&task).await.unwrap().len(), 1);
10911
10912 let download = app
10913 .get(&format!("/files/{stored}"), Some(&admin_cookie))
10914 .await;
10915 assert_eq!(download.status, StatusCode::SERVICE_UNAVAILABLE);
10916
10917 let delete = app
10918 .post(
10919 "/api/delete_file",
10920 Some(&admin_cookie),
10921 &[("file_id", &stored)],
10922 )
10923 .await;
10924 assert_eq!(delete.status, StatusCode::SEE_OTHER);
10925 assert!(
10926 delete.body.contains("StorageUnavailable"),
10927 "the delete did not refuse: {}",
10928 delete.body
10929 );
10930 assert!(
10931 app.store.attachment(&stored).await.unwrap().is_some(),
10932 "the row went while the service was down"
10933 );
10934}
10935
10936/// Deleting a stored row takes the remote copy first and only then the
10937/// row: the service sees the DELETE, its copy is gone, and the task's
10938/// file list is empty.
10939#[tokio::test]
10940async fn deleting_a_stored_row_takes_the_remote_copy_first() {
10941 let fake = FakeIn::spawn().await;
10942 let app = storage_app(&fake).await;
10943 let admin_cookie = admin(&app).await;
10944 let column = first_column(&app).await;
10945 let task = a_task(&app, &admin_cookie, &column, "Remote delete").await;
10946 app.post(
10947 "/api/save_storage",
10948 Some(&admin_cookie),
10949 &[("backend", "in")],
10950 )
10951 .await;
10952
10953 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
10954 app.post_multipart(
10955 "/files",
10956 Some(&admin_cookie),
10957 &[("task_id", &task)],
10958 Some(("gone.png", "image/png", &png)),
10959 )
10960 .await;
10961 let rows = app.store.attachments(&task).await.unwrap();
10962 assert_eq!(rows.len(), 1);
10963 let stored = rows[0].id.clone();
10964 assert!(fake.holds(&stored));
10965
10966 let answer = app
10967 .post(
10968 "/api/delete_file",
10969 Some(&admin_cookie),
10970 &[("file_id", &stored)],
10971 )
10972 .await;
10973 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
10974 assert!(
10975 !answer
10976 .location
10977 .as_deref()
10978 .unwrap_or_default()
10979 .contains("refusal="),
10980 "{:?}",
10981 answer.location
10982 );
10983 assert!(
10984 fake.calls()
10985 .iter()
10986 .any(|call| call == &format!("DELETE /api/service/file/{stored}")),
10987 "the remote copy was never taken: {:?}",
10988 fake.calls()
10989 );
10990 assert!(!fake.holds(&stored));
10991 assert!(
10992 app.store.attachment(&stored).await.unwrap().is_none(),
10993 "the row survived the delete"
10994 );
10995 assert!(app.store.attachments(&task).await.unwrap().is_empty());
10996}
10997
10998/// The mode switch is an admin's, and `in` is only offered when the whole
10999/// road is there: a key in the config and a family row naming the
11000/// service. A member is refused; a keyless deployment is refused; a
11001/// family without the service is refused; with both, the save lands.
11002#[tokio::test]
11003async fn save_storage_is_admin_only_and_refuses_a_road_that_is_not_there() {
11004 // A member cannot switch the surface, on either value.
11005 let fake = FakeIn::spawn().await;
11006 let app = storage_app(&fake).await;
11007 let admin_cookie = admin(&app).await;
11008 let plain = member(&app, "memre@iz.sh", "Memre").await;
11009 let answer = app
11010 .post("/api/save_storage", Some(&plain), &[("backend", "local")])
11011 .await;
11012 assert_eq!(answer.status, StatusCode::SEE_OTHER);
11013 // Settings routes carry the refusal on the redirect's query, not the
11014 // body — the route has no hydrated caller to answer with a value.
11015 assert_eq!(answer.body, "");
11016 assert!(
11017 answer
11018 .location
11019 .as_deref()
11020 .unwrap_or_default()
11021 .contains("refusal=forbidden&on=save_storage&section=limits"),
11022 "{:?}",
11023 answer.location
11024 );
11025
11026 // No `[storage.in]` token: `in` is not a road this deployment can
11027 // take, no matter what the family says.
11028 let keyless =
11029 App::build_with(Mail::silent(), Some(family_with_in(&fake.url())), "", None).await;
11030 let keyless_admin = admin(&keyless).await;
11031 let answer = keyless
11032 .post(
11033 "/api/save_storage",
11034 Some(&keyless_admin),
11035 &[("backend", "in")],
11036 )
11037 .await;
11038 assert!(
11039 answer
11040 .location
11041 .as_deref()
11042 .unwrap_or_default()
11043 .contains("refusal=storage-not-configured&on=save_storage"),
11044 "{:?}",
11045 answer.location
11046 );
11047 // The form never offered it either.
11048 let html = String::from_utf8_lossy(
11049 &keyless
11050 .get("/settings?section=limits", Some(&keyless_admin))
11051 .await
11052 .bytes,
11053 )
11054 .to_string();
11055 assert!(!html.contains("value=\"in\""), "{html}");
11056
11057 // A family with no Files row: there is no URL to push to.
11058 let unlisted = App::build_with(
11059 Mail::silent(),
11060 Some(
11061 "[{\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:7650\"}]".to_string(),
11062 ),
11063 "",
11064 Some(STORAGE_TOKEN.to_string()),
11065 )
11066 .await;
11067 let unlisted_admin = admin(&unlisted).await;
11068 let answer = unlisted
11069 .post(
11070 "/api/save_storage",
11071 Some(&unlisted_admin),
11072 &[("backend", "in")],
11073 )
11074 .await;
11075 assert!(
11076 answer
11077 .location
11078 .as_deref()
11079 .unwrap_or_default()
11080 .contains("refusal=storage-not-listed&on=save_storage"),
11081 "{:?}",
11082 answer.location
11083 );
11084
11085 // Both in place: the save lands, the store says so, and local stands
11086 // as the way back.
11087 let answer = app
11088 .post(
11089 "/api/save_storage",
11090 Some(&admin_cookie),
11091 &[("backend", "in")],
11092 )
11093 .await;
11094 assert_eq!(answer.status, StatusCode::SEE_OTHER);
11095 assert!(
11096 answer
11097 .location
11098 .as_deref()
11099 .unwrap_or_default()
11100 .contains("saved=save_storage&section=limits"),
11101 "{:?}",
11102 answer.location
11103 );
11104 assert_eq!(
11105 app.store.storage_backend().await.unwrap(),
11106 iz_core::store::StorageBackend::In
11107 );
11108 let answer = app
11109 .post(
11110 "/api/save_storage",
11111 Some(&admin_cookie),
11112 &[("backend", "local")],
11113 )
11114 .await;
11115 assert_eq!(answer.status, StatusCode::SEE_OTHER);
11116 assert_eq!(
11117 app.store.storage_backend().await.unwrap(),
11118 iz_core::store::StorageBackend::Local
11119 );
11120}
11121
11122/// The Storage card carries the beat's facts — the family's name for the
11123/// service, the connection's stand, the limit im set, the drain's count,
11124/// the last problem — and never the key the calls speak with.
11125#[tokio::test]
11126async fn the_storage_card_shows_the_beats_facts_without_the_key() {
11127 let fake = FakeIn::spawn().await;
11128 let app = storage_app(&fake).await;
11129 let admin_cookie = admin(&app).await;
11130
11131 app.storage_health.seen(&fake.url(), "Files");
11132 app.storage_health
11133 .reachable(Some(1024 * 1024 * 1024), Some(10 * 1024 * 1024 * 1024));
11134 let html = String::from_utf8_lossy(
11135 &app.get("/settings?section=limits", Some(&admin_cookie))
11136 .await
11137 .bytes,
11138 )
11139 .to_string();
11140 assert!(html.contains("id=\"storage\""), "{html}");
11141 assert!(html.contains(&format!("Files · {}", fake.url())), "{html}");
11142 assert!(html.contains("connection-on"), "{html}");
11143 assert!(html.contains("Connected"), "{html}");
11144 assert!(html.contains("1.0 GiB of 10.0 GiB"), "{html}");
11145 assert!(html.contains("never"), "{html}");
11146 assert!(!html.contains(STORAGE_TOKEN), "the key leaked: {html}");
11147
11148 // The drain's count and the last problem, once the beat has both.
11149 app.post(
11150 "/api/save_storage",
11151 Some(&admin_cookie),
11152 &[("backend", "in")],
11153 )
11154 .await;
11155 app.storage_health.problem("quota");
11156 app.storage_health.migrating(2, 5);
11157 let html = String::from_utf8_lossy(
11158 &app.get("/settings?section=limits", Some(&admin_cookie))
11159 .await
11160 .bytes,
11161 )
11162 .to_string();
11163 assert!(html.contains("2 of 5"), "{html}");
11164 // The meter under the count: the family's quota bar, at the moved
11165 // share, and only while a migration stands.
11166 assert!(html.contains("quota-bar\" role=\"progressbar\""), "{html}");
11167 assert!(html.contains("width: 40%"), "{html}");
11168 assert!(html.contains("quota"), "{html}");
11169 assert!(html.contains("connection-wait"), "{html}");
11170 assert!(html.contains("Unreachable"), "{html}");
11171 assert!(!html.contains(STORAGE_TOKEN), "the key leaked: {html}");
11172}
11173
11174/// One beat of the storage cycle, by hand: a workspace switched to in
11175/// with rows still on this disk has them pushed, flipped to stored, and
11176/// unlinked, and a service that has gone down since is a problem on the
11177/// card rather than a stuck drain.
11178#[tokio::test]
11179async fn the_storage_beat_drains_local_rows_into_the_service() {
11180 let fake = FakeIn::spawn().await;
11181 let app = storage_app(&fake).await;
11182 let admin_cookie = admin(&app).await;
11183 let column = first_column(&app).await;
11184 let task = a_task(&app, &admin_cookie, &column, "Drained rows").await;
11185
11186 // Two rows on local disk, the way every row was before the switch.
11187 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
11188 for name in ["one.png", "two.png"] {
11189 app.post_multipart(
11190 "/files",
11191 Some(&admin_cookie),
11192 &[("task_id", &task)],
11193 Some((name, "image/png", &png)),
11194 )
11195 .await;
11196 }
11197 assert_eq!(local_file_count(&app), 2);
11198 assert!(fake.calls().is_empty());
11199
11200 app.post(
11201 "/api/save_storage",
11202 Some(&admin_cookie),
11203 &[("backend", "in")],
11204 )
11205 .await;
11206 iz_web::storage::storage_cycle(&app.store, &app.storage_client, &app.storage_health).await;
11207
11208 let rows = app.store.attachments(&task).await.unwrap();
11209 assert_eq!(rows.len(), 2);
11210 assert!(
11211 rows.iter()
11212 .all(|row| row.remote == iz_core::store::AttachmentWhere::Stored),
11213 "not every row drained"
11214 );
11215 assert_eq!(
11216 local_file_count(&app),
11217 0,
11218 "the local files survived the drain"
11219 );
11220 assert!(rows.iter().all(|row| fake.holds(&row.id)));
11221 let snap = app.storage_health.snapshot();
11222 assert!(snap.connected);
11223 assert_eq!(snap.migrating, None);
11224
11225 // The service gone: the beat says so on the card and nothing moves —
11226 // there is nothing left to move — while the rows stay serviceable
11227 // from wherever the service comes back.
11228 fake.set_down();
11229 iz_web::storage::storage_cycle(&app.store, &app.storage_client, &app.storage_health).await;
11230 let snap = app.storage_health.snapshot();
11231 assert!(!snap.connected);
11232 assert_eq!(snap.problem_word.as_deref(), Some("unreachable"));
11233}
11234
11235/// A full service refuses the push with its own word, and the upload
11236/// carries it: nothing is stored, on either side.
11237#[tokio::test]
11238async fn a_full_service_refuses_the_upload_with_its_own_word() {
11239 let fake = FakeIn::spawn().await;
11240 let app = storage_app(&fake).await;
11241 let admin_cookie = admin(&app).await;
11242 let column = first_column(&app).await;
11243 let task = a_task(&app, &admin_cookie, &column, "Full service").await;
11244 app.post(
11245 "/api/save_storage",
11246 Some(&admin_cookie),
11247 &[("backend", "in")],
11248 )
11249 .await;
11250 fake.refuse_quota();
11251
11252 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
11253 let answer = app
11254 .post_multipart(
11255 "/files",
11256 Some(&admin_cookie),
11257 &[("task_id", &task)],
11258 Some(("full.png", "image/png", &png)),
11259 )
11260 .await;
11261 assert_eq!(answer.status, StatusCode::SEE_OTHER);
11262 assert!(
11263 answer
11264 .location
11265 .as_deref()
11266 .unwrap_or_default()
11267 .contains("refusal=storage-quota&on=upload_file"),
11268 "{:?}",
11269 answer.location
11270 );
11271 assert!(app.store.attachments(&task).await.unwrap().is_empty());
11272 assert_eq!(local_file_count(&app), 0);
11273}