forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

insight_report.rs654 lines, 25.4 KiBHistoryRawDownload
1//! End-to-end tests for the school-report doors, against a fake ZEKA service.
2//!
3//! `POST /insights/runs/{run_day}/report` reads this school's own `zeka_*`
4//! rows, dispatches them to the service that declares `insight.report`, stores
5//! the returned HTML under the school's blob directory, and answers `200` with
6//! what was stored; `GET` streams that document back. Everything runs over a
7//! real QUIC socket on loopback — a real handshake, real TLS, real streams —
8//! with [`Behaviour::Report`] standing in for what ZEKA does with the request.
9//!
10//! The assertions split the same way `tests/podcast.rs` splits them: what a
11//! browser gets from the real router, and what the *service* received
12//! ([`FakeService::seen`]) — a door that quietly sent nothing, or asked the
13//! wrong principal, fails the `seen` assertions rather than looking green.
14
15mod common;
16
17use std::sync::{Arc, Mutex};
18use std::time::Duration;
19
20use axum::Router;
21use axum::http::StatusCode;
22use hezarfen_backend::ai::protocol::{Greeting, Hello, Request, Response, read_frame, write_frame};
23use hezarfen_backend::ai::{AiBridge, BridgeConfig};
24use hezarfen_backend::constant::{
25 AI_ALPN, AI_INSIGHT_REPORT_CAPABILITY, AI_PROTOCOL,
26};
27use hezarfen_backend::database::Database;
28use hezarfen_backend::domain::timestamp::Timestamp;
29use hezarfen_backend::tenant::DEMO_SCHOOL_ID;
30use serde_json::{Value, json};
31use uuid::Uuid;
32
33const TOKEN: &str = "shared-ai-token";
34
35/// One answer frame, **bounded**: a bridge that never answers must fail this
36/// test by name in seconds rather than hang the run — a hung Test step holds
37/// the serialized deploy lock behind it.
38async fn frame_or_fail<T: serde::de::DeserializeOwned>(
39 recv: &mut quinn::RecvStream,
40 what: &str,
41) -> T {
42 match tokio::time::timeout(Duration::from_secs(10), read_frame(recv)).await {
43 Ok(Ok(frame)) => frame,
44 Ok(Err(err)) => panic!("{what}: the frame could not be read: {err}"),
45 Err(_) => panic!("{what}: no frame arrived within 10s — the bridge did not answer"),
46 }
47}
48
49// ---------------------------------------------------------------- harness --
50
51/// Start a bridge on an ephemeral port.
52async fn bridge() -> AiBridge {
53 AiBridge::bind(BridgeConfig {
54 addr: "127.0.0.1:0".parse().unwrap(),
55 token: TOKEN.to_string(),
56 cert_path: None,
57 key_path: None,
58 request_timeout: Duration::from_secs(5),
59 })
60 .await
61 .expect("bridge binds on an ephemeral port")
62}
63
64/// A QUIC client endpoint that trusts exactly the bridge's own certificate —
65/// the same pinning a real service does, rather than a verification bypass.
66fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint {
67 hezarfen_backend::ai::tls::install_crypto_provider();
68 let mut roots = rustls::RootCertStore::empty();
69 roots.add(bridge.certificate()).expect("pin the leaf");
70 let mut tls = rustls::ClientConfig::builder()
71 .with_root_certificates(roots)
72 .with_no_client_auth();
73 tls.alpn_protocols = vec![AI_ALPN.to_vec()];
74
75 let quic_tls =
76 quinn::crypto::rustls::QuicClientConfig::try_from(tls).expect("client TLS is QUIC-usable");
77 let mut config = quinn::ClientConfig::new(Arc::new(quic_tls));
78 let mut transport = quinn::TransportConfig::default();
79 transport.max_concurrent_bidi_streams(64u32.into());
80 config.transport_config(Arc::new(transport));
81
82 let mut endpoint =
83 quinn::Endpoint::client("127.0.0.1:0".parse().unwrap()).expect("client bind");
84 endpoint.set_default_client_config(config);
85 endpoint
86}
87
88fn hello(service: &str, capabilities: &[&str]) -> Hello {
89 Hello {
90 protocol: AI_PROTOCOL.to_string(),
91 service: service.to_string(),
92 capabilities: capabilities.iter().map(|c| c.to_string()).collect(),
93 token: TOKEN.to_string(),
94 max_concurrent: None,
95 }
96}
97
98/// A connected fake service. Holding it keeps the connection (and so the
99/// registration) alive; dropping it is how a test simulates a crash.
100struct FakeService {
101 _endpoint: quinn::Endpoint,
102 _control: (quinn::SendStream, quinn::RecvStream),
103 /// Every request this service received, in arrival order.
104 seen: Arc<Mutex<Vec<Request>>>,
105}
106
107impl FakeService {
108 fn seen(&self) -> Vec<Request> {
109 self.seen.lock().unwrap().clone()
110 }
111
112 /// The one report request this service was handed.
113 fn report_request(&self) -> Request {
114 self.seen()
115 .into_iter()
116 .find(|request| request.capability == AI_INSIGHT_REPORT_CAPABILITY)
117 .expect("the door dispatched the report capability")
118 }
119}
120
121/// What the fake service does with each request it receives.
122#[derive(Clone)]
123enum Behaviour {
124 /// Answer like ZEKA's report package: a self-contained HTML document that
125 /// echoes the run day and how many summaries it was handed.
126 Report,
127 /// Refuse like ZEKA's report handler does: the code is chosen by the run
128 /// day, so one connection can drive every refusal class.
129 Refuse,
130 /// Answer `200` with an html member that is the empty string — a service
131 /// defect the door must not persist.
132 Empty,
133}
134
135/// The refusal code the fake service answers for a run day — all four codes
136/// the real handler closes, one day each.
137fn refusal_code(run_day: &str) -> String {
138 match run_day {
139 "2026-09-11" => "bad_request",
140 "2026-09-12" => "insufficient_rows",
141 "2026-09-13" => "document_too_large",
142 "2026-09-14" => "internal",
143 other => panic!("the fake service was asked for an unmapped day `{other}`"),
144 }
145 .to_string()
146}
147
148/// Dial, register, and start serving requests with `behaviour`.
149async fn connect_service(bridge: &AiBridge, hello: Hello, behaviour: Behaviour) -> FakeService {
150 let endpoint = client_endpoint(bridge);
151 let conn = endpoint
152 .connect(bridge.local_addr().unwrap(), "localhost")
153 .expect("dial")
154 .await
155 .expect("QUIC handshake");
156 let (mut send, mut recv) = conn.open_bi().await.expect("control stream");
157 write_frame(&mut send, &hello).await.expect("send Hello");
158 let greeting: Greeting = frame_or_fail(&mut recv, "read Greeting").await;
159 match greeting {
160 Greeting::Welcome { protocol, .. } => assert_eq!(protocol, AI_PROTOCOL),
161 other => panic!("expected a welcome, got {other:?}"),
162 }
163
164 let seen = Arc::new(Mutex::new(Vec::new()));
165 serve(conn.clone(), behaviour, Arc::clone(&seen));
166 FakeService {
167 _endpoint: endpoint,
168 _control: (send, recv),
169 seen,
170 }
171}
172
173/// The service's request loop: one task per incoming server-initiated stream.
174fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Request>>>) {
175 tokio::spawn(async move {
176 while let Ok((mut send, mut recv)) = conn.accept_bi().await {
177 let behaviour = behaviour.clone();
178 let seen = Arc::clone(&seen);
179 tokio::spawn(async move {
180 let Ok(request) = read_frame::<_, Request>(&mut recv).await else {
181 return;
182 };
183 seen.lock().unwrap().push(request.clone());
184 let response = match behaviour {
185 Behaviour::Report => Response::Ok {
186 id: request.id.clone(),
187 school: request.school.clone(),
188 payload: report_answer(&request),
189 },
190 Behaviour::Refuse => {
191 let code = refusal_code(
192 request.payload["run_day"].as_str().unwrap_or_default(),
193 );
194 Response::Err {
195 id: request.id.clone(),
196 school: request.school.clone(),
197 message: format!("`{code}` reddedildi"),
198 code,
199 }
200 }
201 Behaviour::Empty => Response::Ok {
202 id: request.id.clone(),
203 school: request.school.clone(),
204 payload: json!({
205 "kind": "okul",
206 "run_day": request.payload["run_day"],
207 "format": "html",
208 "html": "",
209 "byte_size": 0,
210 "truncated": false,
211 "notes": [],
212 }),
213 },
214 };
215 let _ = write_frame(&mut send, &response).await;
216 let _ = send.finish();
217 let _ = send.stopped().await;
218 });
219 }
220 });
221}
222
223/// The HTML a fake report render produces for the request it was handed.
224fn report_html(request: &Request) -> String {
225 let run_day = request.payload["run_day"].as_str().unwrap_or("<gun yok>");
226 let students = request.payload["summaries"]
227 .as_array()
228 .map(|rows| rows.len())
229 .unwrap_or(0);
230 format!(
231 "<!doctype html>\n<html lang=\"tr\"><head><meta charset=\"utf-8\">\
232 <title>Okul analiz raporu</title></head>\
233 <body><h1>Okul analiz raporu — {run_day}</h1>\
234 <p>{students} öğrenci özeti</p></body></html>"
235 )
236}
237
238/// What the fake ZEKA report package answers: the document plus its own
239/// bookkeeping.
240fn report_answer(request: &Request) -> Value {
241 let html = report_html(request);
242 json!({
243 "kind": "okul",
244 "run_day": request.payload["run_day"],
245 "format": "html",
246 "byte_size": html.len(),
247 "html": html,
248 "truncated": false,
249 "notes": ["koşu defteri okundu"],
250 })
251}
252
253/// Registration completes asynchronously after the welcome is on the wire, so
254/// tests that assert on the registry wait for it rather than racing it.
255async fn await_workers(bridge: &AiBridge, expected: usize) {
256 for _ in 0..300 {
257 if bridge.workers().len() == expected {
258 return;
259 }
260 tokio::time::sleep(Duration::from_millis(10)).await;
261 }
262 panic!(
263 "expected {expected} workers, registry holds {:?}",
264 bridge.workers()
265 );
266}
267
268/// A registered ZEKA service, the router wired to its bridge, a logged-in
269/// manager, and the school's database handle — the fixture the round-trip
270/// tests start from.
271async fn report_app() -> (FakeService, Router, String, Database) {
272 let bridge = bridge().await;
273 let service = connect_service(
274 &bridge,
275 hello("zeka", &[AI_INSIGHT_REPORT_CAPABILITY]),
276 Behaviour::Report,
277 )
278 .await;
279 await_workers(&bridge, 1).await;
280 let (app, db) = common::app_with_ai(Some(bridge)).await;
281 let manager = common::login_as(&app, &db, "mudur", "manager").await;
282 (service, app, manager, db)
283}
284
285// --------------------------------------------------------------- fixtures --
286
287/// Seed one student's ZEKA rows the way the service writes them: a summary
288/// with one attention item, one live card, one segment profile, and the
289/// ledger row for `run_day` with its pending student and failed module. All of
290/// it is what the report dispatch must carry.
291async fn seed_report_rows(db: &Database, run_day: &str, student: &str, audience: &str) {
292 let student_uuid = Uuid::parse_str(student).expect("student id");
293 let audience_uuid = Uuid::parse_str(audience).expect("audience id");
294 let now = Timestamp::now().as_millis();
295
296 sqlx::query(
297 "INSERT INTO zeka_student_summary
298 (student, marks, attendance, submission, study, confidence, computed_at, retain_until)
299 VALUES ($1, '{\"courses\":{\"matematik\":{\"average\":72}}}'::jsonb, NULL, NULL, NULL,
300 'stable', $2, $3)",
301 )
302 .bind(student_uuid)
303 .bind(now)
304 .bind(now + 400 * 86_400_000)
305 .execute(db)
306 .await
307 .unwrap();
308
309 sqlx::query(
310 "INSERT INTO zeka_attention_item
311 (student, trigger, course, fact, window_from, window_to, evidence, ord)
312 VALUES ($1, 'attendance', NULL, 'son 30 gunun 4 dersi kacirildi', $2, $3,
313 '{\"absent_days\":4}'::jsonb, 1)",
314 )
315 .bind(student_uuid)
316 .bind(now - 30 * 86_400_000)
317 .bind(now)
318 .execute(db)
319 .await
320 .unwrap();
321
322 sqlx::query(
323 "INSERT INTO zeka_recommendation
324 (id, audience, product, rule_id, rule_version, scope, about, audience_role,
325 course, evidence, confidence, created_at, expires_at, retain_until,
326 dismissed_at, dismissed_by, dismiss_reason)
327 VALUES ($1, $2, 'T4', 'T4.attendance', 1, NULL, $3, 'teacher', NULL,
328 '{\"absent_days\":4,\"limitation\":\"yalniz ders yoklamasi\"}'::jsonb,
329 'stable', $4, $5, $6, NULL, NULL, NULL)",
330 )
331 .bind(Uuid::now_v7())
332 .bind(audience_uuid)
333 .bind(student_uuid)
334 .bind(now)
335 .bind(now + 86_400_000)
336 .bind(now + 90 * 86_400_000)
337 .execute(db)
338 .await
339 .unwrap();
340
341 sqlx::query(
342 "INSERT INTO zeka_student_segment_profile
343 (student, dimension, label, n_answers, n_correct, accuracy,
344 overall_n_answers, overall_accuracy, contrast, confidence,
345 computed_at, retain_until)
346 VALUES ($1, 'bilissel_talep', 'analiz', 120, 48, 0.40, 240, 0.55, -0.15,
347 'stable', $2, $3)",
348 )
349 .bind(student_uuid)
350 .bind(now)
351 .bind(now + 400 * 86_400_000)
352 .execute(db)
353 .await
354 .unwrap();
355
356 sqlx::query(
357 "INSERT INTO zeka_run
358 (run_day, started_at, finished_at, status, duration_ms,
359 students_total, students_ok, students_failed, students_skipped,
360 rows_written, budget_exceeded, budget_ms, retain_until)
361 VALUES ($1, $2, $3, 'ok', 61000, 1, 1, 0, 0, 44, false, 60000, $4)",
362 )
363 .bind(run_day)
364 .bind(now - 61_000)
365 .bind(now)
366 .bind(now + 90 * 86_400_000)
367 .execute(db)
368 .await
369 .unwrap();
370 sqlx::query("INSERT INTO zeka_run_pending (run, student, ord) VALUES ($1, $2, 1)")
371 .bind(run_day)
372 .bind(student_uuid)
373 .execute(db)
374 .await
375 .unwrap();
376 sqlx::query("INSERT INTO zeka_run_failed_module (run, module, ord) VALUES ($1, 'study', 1)")
377 .bind(run_day)
378 .execute(db)
379 .await
380 .unwrap();
381}
382
383// ------------------------------------------------------------- http doors --
384
385/// One `POST /insights/runs/{run_day}/report`.
386async fn generate(app: &Router, cookie: &str, run_day: &str) -> common::Res {
387 common::send(
388 app,
389 "POST",
390 &format!("/insights/runs/{run_day}/report"),
391 Some(cookie),
392 None,
393 )
394 .await
395}
396
397/// One `GET /insights/runs/{run_day}/report`, raw — the body is an HTML
398/// document or a JSON refusal, never a parsed envelope.
399async fn fetch_report(
400 app: &Router,
401 cookie: &str,
402 run_day: &str,
403) -> (StatusCode, axum::http::HeaderMap, Vec<u8>) {
404 common::send_raw(
405 app,
406 "GET",
407 &format!("/insights/runs/{run_day}/report"),
408 Some(cookie),
409 None,
410 Vec::new(),
411 )
412 .await
413}
414
415/// A refusal body parsed out of raw bytes.
416fn refusal_body(bytes: &[u8]) -> Value {
417 serde_json::from_slice(bytes).expect("a refusal body is JSON")
418}
419
420// ------------------------------------------------------------------ tests --
421
422/// The whole round trip: the manager generates the document, the service is
423/// handed the school's own rows and the caller's identity, and the stored
424/// artifact is served back with the document's content type — byte for byte
425/// what the service rendered.
426#[tokio::test]
427async fn a_generated_report_is_stored_and_served_to_its_manager() {
428 let (service, app, manager, db) = report_app().await;
429 let manager_id = common::me_id(&app, &manager).await;
430 let student = common::login(&app, "ali").await;
431 let student_id = common::me_id(&app, &student).await;
432 let class_id = common::create_class(&app, &manager, "8-A", json!({})).await;
433 seed_report_rows(&db, "2026-09-16", &student_id, &manager_id).await;
434
435 let res = generate(&app, &manager, "2026-09-16").await;
436 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
437 assert_eq!(res.body["run_day"], "2026-09-16");
438 assert_eq!(res.body["truncated"], false);
439 assert_eq!(res.body["notes"], json!(["koşu defteri okundu"]));
440 assert!(res.body["generated_at"].as_i64().unwrap() > 0);
441 assert_eq!(
442 res.body["byte_size"].as_u64().unwrap(),
443 report_html(&service.report_request()).len() as u64,
444 "the receipt sizes the stored document, not the service's claim"
445 );
446
447 // What the service was handed. This is the payload contract: the rows the
448 // backend holds, the caller's identity, and the school's own fields.
449 let request = service.report_request();
450 assert_eq!(request.payload["kind"], "okul");
451 assert_eq!(request.payload["run_day"], "2026-09-16");
452 assert_eq!(
453 request.payload["requested_by"], manager_id,
454 "the dispatch names the authenticated caller, not the school"
455 );
456 assert!(request.payload["school"].get("slug").is_none(), "the report school has no slug");
457 assert_eq!(request.payload["school"]["id"], DEMO_SCHOOL_ID);
458 assert_eq!(request.payload["school"]["name"], "Demo School");
459 assert!(
460 request.payload["school"]["name"]
461 .as_str()
462 .is_some_and(|name| !name.is_empty()),
463 "the school's display name travels"
464 );
465 // The class (şube) lookup: the summaries' evidence carries class ids, and
466 // the document must print the name a reader recognizes.
467 let classes = request.payload["classes"]
468 .as_array()
469 .expect("classes is a list");
470 let seeded = classes
471 .iter()
472 .find(|row| row["id"] == class_id.as_str())
473 .expect("the school's own class is in the payload");
474 assert_eq!(seeded["name"], "8-A");
475 let summaries = request.payload["summaries"]
476 .as_array()
477 .expect("summaries is a list");
478 let mine = summaries
479 .iter()
480 .find(|row| row["student"] == student_id)
481 .expect("the seeded student's summary is in the payload");
482 assert_eq!(mine["confidence"], "stable");
483 assert_eq!(mine["attention"][0]["trigger"], "attendance");
484 assert_eq!(mine["attention"][0]["evidence"]["absent_days"], 4);
485 let cards = request.payload["recommendations"].as_array().unwrap();
486 assert_eq!(cards.len(), 1);
487 assert_eq!(cards[0]["rule_id"], "T4.attendance");
488 assert_eq!(cards[0]["about"], student_id);
489 assert_eq!(request.payload["profiles"][0]["dimension"], "bilissel_talep");
490 assert_eq!(request.payload["profiles"][0]["contrast"], -0.15);
491 let runs = request.payload["runs"].as_array().unwrap();
492 assert_eq!(runs[0]["run_day"], "2026-09-16");
493 assert_eq!(runs[0]["pending_students"], json!([student_id]));
494 assert_eq!(runs[0]["failed_modules"], json!(["study"]));
495
496 // The artifact a browser gets back.
497 let (status, headers, bytes) = fetch_report(&app, &manager, "2026-09-16").await;
498 assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes));
499 assert_eq!(headers["content-type"], "text/html; charset=utf-8");
500 assert_eq!(headers["x-content-type-options"], "nosniff");
501 assert_eq!(headers["cache-control"], "private, no-store");
502 let html = String::from_utf8(bytes).expect("the stored document is UTF-8");
503 assert_eq!(html, report_html(&service.report_request()));
504 assert!(html.starts_with("<!doctype html>"));
505}
506
507/// Generation is deliberately synchronous and does not require a ledger row:
508/// a run day with no `zeka_run` row still dispatches (the service says in
509/// `notes` what it found), and the artifact it returns is served. A `404`
510/// here would refuse a day the POST door had just answered `200` for.
511#[tokio::test]
512async fn a_run_day_with_no_ledger_row_still_generates_and_serves() {
513 let (service, app, manager, _db) = report_app().await;
514
515 let res = generate(&app, &manager, "2099-01-01").await;
516 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
517 assert_eq!(res.body["run_day"], "2099-01-01");
518
519 let request = service.report_request();
520 assert_eq!(request.payload["run_day"], "2099-01-01");
521 assert_eq!(
522 request.payload["runs"].as_array().map(Vec::len),
523 Some(0),
524 "no ledger row means no ledger rows, not a refusal"
525 );
526
527 let (status, headers, _bytes) = fetch_report(&app, &manager, "2099-01-01").await;
528 assert_eq!(status, StatusCode::OK);
529 assert_eq!(headers["content-type"], "text/html; charset=utf-8");
530}
531
532/// Reading before anything was generated is the coded `409` — the refusal a
533/// client branches on, never a `404` it could confuse with a missing route.
534#[tokio::test]
535async fn a_report_that_was_never_generated_is_a_coded_conflict() {
536 let (app, db) = common::app_and_db().await;
537 let manager = common::login_as(&app, &db, "mudur", "manager").await;
538
539 let (status, _headers, bytes) = fetch_report(&app, &manager, "2099-12-31").await;
540 assert_eq!(status, StatusCode::CONFLICT);
541 let body = refusal_body(&bytes);
542 assert_eq!(body["code"], "report_missing");
543 assert!(
544 body["error"].as_str().unwrap().contains("2099-12-31"),
545 "the message names the day: {body}"
546 );
547}
548
549/// A service that answers, refusing, maps each of its four codes to the right
550/// HTTP class — and stores nothing on any of them.
551#[tokio::test]
552async fn service_refusals_map_each_code_to_its_http_class() {
553 let bridge = bridge().await;
554 let _service = connect_service(
555 &bridge,
556 hello("zeka", &[AI_INSIGHT_REPORT_CAPABILITY]),
557 Behaviour::Refuse,
558 )
559 .await;
560 await_workers(&bridge, 1).await;
561 let (app, db) = common::app_with_ai(Some(bridge)).await;
562 let manager = common::login_as(&app, &db, "mudur", "manager").await;
563
564 // `bad_request`: the service judged the composed request bad.
565 let res = generate(&app, &manager, "2026-09-11").await;
566 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
567
568 // `insufficient_rows`: nothing to render — a coded conflict, not a 500.
569 let res = generate(&app, &manager, "2026-09-12").await;
570 assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
571 assert_eq!(res.body["code"], "report_empty");
572 assert!(
573 res.body["error"]
574 .as_str()
575 .is_some_and(|message| message.contains("insufficient_rows")),
576 "the service's own words survive: {}",
577 res.body
578 );
579
580 // `document_too_large`: the render happened but is over the ceiling.
581 let res = generate(&app, &manager, "2026-09-13").await;
582 assert_eq!(res.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", res.body);
583
584 // `internal`: the render failed on the service's side.
585 let res = generate(&app, &manager, "2026-09-14").await;
586 assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", res.body);
587
588 // None of the four stored a document.
589 for day in ["2026-09-11", "2026-09-12", "2026-09-13", "2026-09-14"] {
590 let (status, _headers, bytes) = fetch_report(&app, &manager, day).await;
591 assert_eq!(status, StatusCode::CONFLICT, "{day}");
592 assert_eq!(refusal_body(&bytes)["code"], "report_missing", "{day}");
593 }
594}
595
596/// No service at all: `503` before any read, and nothing was stored.
597#[tokio::test]
598async fn generating_without_a_service_is_unavailable() {
599 let (app, db) = common::app_and_db().await;
600 let manager = common::login_as(&app, &db, "mudur", "manager").await;
601
602 let res = generate(&app, &manager, "2026-09-14").await;
603 assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
604 assert!(res.body["error"].is_string());
605}
606
607/// A service that answers `200` with an empty document is refused: a blank
608/// page must never be stored and served as if it were the report.
609#[tokio::test]
610async fn an_empty_document_is_never_stored() {
611 let bridge = bridge().await;
612 let _service = connect_service(
613 &bridge,
614 hello("zeka", &[AI_INSIGHT_REPORT_CAPABILITY]),
615 Behaviour::Empty,
616 )
617 .await;
618 await_workers(&bridge, 1).await;
619 let (app, db) = common::app_with_ai(Some(bridge)).await;
620 let manager = common::login_as(&app, &db, "mudur", "manager").await;
621
622 let res = generate(&app, &manager, "2026-09-10").await;
623 assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", res.body);
624
625 let (status, _headers, bytes) = fetch_report(&app, &manager, "2026-09-10").await;
626 assert_eq!(status, StatusCode::CONFLICT);
627 assert_eq!(refusal_body(&bytes)["code"], "report_missing");
628}
629
630/// Both doors are manager+; a teacher is refused before anything is read or
631/// dispatched, and a malformed day never shapes a path.
632#[tokio::test]
633async fn report_doors_are_manager_only_and_validate_the_day() {
634 let (app, db) = common::app_and_db().await;
635 let teacher = common::login_as(&app, &db, "ayse", "teacher").await;
636
637 let res = generate(&app, &teacher, "2026-09-16").await;
638 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
639 let (status, _headers, _bytes) = fetch_report(&app, &teacher, "2026-09-16").await;
640 assert_eq!(status, StatusCode::FORBIDDEN);
641
642 let manager = common::login_as(&app, &db, "mudur", "manager").await;
643 let res = generate(&app, &manager, "2026-9-16").await;
644 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
645 // A percent-encoded traversal in the day segment decodes to something no
646 // `YYYY-MM-DD` day is, so it is refused before it could shape a path.
647 let (status, _headers, bytes) = fetch_report(&app, &manager, "%2e%2e%2f%2e%2e%2fetc%2fpasswd").await;
648 assert_eq!(
649 status,
650 StatusCode::BAD_REQUEST,
651 "a path-shaped day is refused before it is joined: {}",
652 String::from_utf8_lossy(&bytes)
653 );
654}