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

ai_protocol.rs1749 lines, 68.7 KiBHistoryRawDownload
1//! Wire-contract tests for the AI bridge — the regression net for `hab/2`.
2//!
3//! # Why this file exists separately from `ai_bridge.rs`
4//!
5//! `ai_bridge.rs` drives real QUIC clients, but its fake service calls the
6//! library's own `write_frame` / `read_frame` and its own `Hello` / `Request`
7//! structs. Both ends therefore share one Rust definition, so it cannot notice
8//! a change to the wire: rename `deadline_ms` to `timeout_ms` and every test
9//! there still passes, while every service written in another language breaks.
10//!
11//! So nothing here imports `hezarfen_backend::ai::protocol`. Frames are built
12//! as byte literals and parsed as untyped JSON, exactly as a Python or Go
13//! service would. A field rename, a re-tagged enum, a flipped length-prefix
14//! endianness, or a newly-required field fails a test here instead of failing
15//! in a service repo.
16//!
17//! It doubles as the reference implementation: `raw::Service` below is the
18//! whole client side of `hab/2` in about a hundred lines.
19
20mod common;
21
22use std::sync::Arc;
23use std::time::Duration;
24
25use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig};
26use hezarfen_backend::module::ModuleSet;
27use hezarfen_backend::tenant::{SchoolStatus, SchoolId, Tenants};
28use serde_json::{Value, json};
29
30const TOKEN: &str = "shared-ai-token";
31
32/// The school every frame in this suite names. A literal for the same reason
33/// `PROTOCOL` is one: a service spells the slug out, it is not a Rust constant.
34const SCHOOL: &str = "019732e3-7b00-7000-8000-00000000dead";
35
36/// The protocol identifier this suite pins. Deliberately a literal, not
37/// `AI_PROTOCOL`: importing the constant would let a rename sail through, and
38/// the whole point is that the string is a published contract.
39const PROTOCOL: &str = "hab/2";
40
41// ------------------------------------------------------------------- raw --
42
43/// A minimal `hab/2` client with no dependency on the crate's protocol types.
44mod raw {
45 use super::*;
46
47 /// Length-prefix one JSON body: `u32` **big-endian** byte count, then the
48 /// bytes. Written out by hand so an endianness change is caught here.
49 pub fn frame(body: &[u8]) -> Vec<u8> {
50 let mut out = Vec::with_capacity(4 + body.len());
51 let len = body.len() as u32;
52 out.push((len >> 24) as u8);
53 out.push((len >> 16) as u8);
54 out.push((len >> 8) as u8);
55 out.push(len as u8);
56 out.extend_from_slice(body);
57 out
58 }
59
60 /// Read exactly `n` bytes, or fail.
61 async fn read_exact(recv: &mut quinn::RecvStream, n: usize) -> Result<Vec<u8>, String> {
62 let mut buf = vec![0u8; n];
63 recv.read_exact(&mut buf)
64 .await
65 .map_err(|e| format!("short read of {n} bytes: {e}"))?;
66 Ok(buf)
67 }
68
69 /// Read one frame and parse it as untyped JSON, plus the raw bytes so a
70 /// test can assert on the encoding itself.
71 pub async fn read_frame(recv: &mut quinn::RecvStream) -> Result<(Value, Vec<u8>), String> {
72 let header = read_exact(recv, 4).await?;
73 let len = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize;
74 let body = read_exact(recv, len).await?;
75 let value =
76 serde_json::from_slice(&body).map_err(|e| format!("frame was not JSON: {e}"))?;
77 Ok((value, body))
78 }
79
80 /// A QUIC endpoint trusting exactly the bridge's certificate — what a
81 /// service does after `GET /ai/certificate`.
82 pub fn endpoint(bridge: &AiBridge) -> quinn::Endpoint {
83 hezarfen_backend::ai::tls::install_crypto_provider();
84 let mut roots = rustls::RootCertStore::empty();
85 roots.add(bridge.certificate()).expect("pin the leaf");
86 let mut tls = rustls::ClientConfig::builder()
87 .with_root_certificates(roots)
88 .with_no_client_auth();
89 tls.alpn_protocols = vec![PROTOCOL.as_bytes().to_vec()];
90 finish_endpoint(tls)
91 }
92
93 /// Same, but announcing some other ALPN — for the version-gate test.
94 pub fn endpoint_with_alpn(bridge: &AiBridge, alpn: &[u8]) -> quinn::Endpoint {
95 hezarfen_backend::ai::tls::install_crypto_provider();
96 let mut roots = rustls::RootCertStore::empty();
97 roots.add(bridge.certificate()).expect("pin the leaf");
98 let mut tls = rustls::ClientConfig::builder()
99 .with_root_certificates(roots)
100 .with_no_client_auth();
101 tls.alpn_protocols = vec![alpn.to_vec()];
102 finish_endpoint(tls)
103 }
104
105 fn finish_endpoint(tls: rustls::ClientConfig) -> quinn::Endpoint {
106 let mut config = quinn::ClientConfig::new(Arc::new(
107 quinn::crypto::rustls::QuicClientConfig::try_from(tls).expect("QUIC-usable TLS"),
108 ));
109 let mut transport = quinn::TransportConfig::default();
110 // Requests arrive as server-initiated streams; this is the ceiling on
111 // how many the bridge may open toward us.
112 transport.max_concurrent_bidi_streams(128u32.into());
113 config.transport_config(Arc::new(transport));
114 let mut endpoint =
115 quinn::Endpoint::client("127.0.0.1:0".parse().unwrap()).expect("client bind");
116 endpoint.set_default_client_config(config);
117 endpoint
118 }
119
120 /// A connected raw service: the QUIC connection plus its control stream.
121 pub struct Service {
122 pub _endpoint: quinn::Endpoint,
123 pub conn: quinn::Connection,
124 pub control: (quinn::SendStream, quinn::RecvStream),
125 /// The bridge's answer to the `Hello`, as untyped JSON.
126 pub greeting: Value,
127 }
128
129 /// Dial and send `hello_body` verbatim on the control stream.
130 pub async fn handshake(bridge: &AiBridge, hello_body: &[u8]) -> Service {
131 let endpoint = endpoint(bridge);
132 let conn = endpoint
133 .connect(bridge.local_addr().unwrap(), "localhost")
134 .expect("dial")
135 .await
136 .expect("QUIC handshake");
137 let (mut send, mut recv) = conn.open_bi().await.expect("control stream");
138 send.write_all(&frame(hello_body))
139 .await
140 .expect("write Hello");
141 let (greeting, _) = frame_or_fail(&mut recv, "read Greeting").await;
142 Service {
143 _endpoint: endpoint,
144 conn,
145 control: (send, recv),
146 greeting,
147 }
148 }
149
150 /// A well-formed `Hello` for a service offering one capability.
151 pub fn hello(service: &str, capability: &str) -> Vec<u8> {
152 format!(
153 r#"{{"protocol":"{PROTOCOL}","service":"{service}","capabilities":["{capability}"],"token":"{TOKEN}"}}"#
154 )
155 .into_bytes()
156 }
157
158 /// Accept one request stream, returning the parsed request, its raw bytes,
159 /// and the stream to answer on.
160 pub async fn take_request(
161 conn: &quinn::Connection,
162 ) -> (Value, Vec<u8>, quinn::SendStream, quinn::RecvStream) {
163 let (send, mut recv) = conn
164 .accept_bi()
165 .await
166 .expect("bridge opened a request stream");
167 let (request, bytes) = frame_or_fail(&mut recv, "read Request").await;
168 (request, bytes, send, recv)
169 }
170
171 /// Answer a request stream with `body` verbatim, then finish.
172 pub async fn answer(mut send: quinn::SendStream, body: &[u8]) {
173 send.write_all(&frame(body)).await.expect("write Response");
174 let _ = send.finish();
175 let _ = send.stopped().await;
176 }
177
178 /// Send one api-read frame verbatim on a fresh *client*-initiated stream
179 /// and read the single answer frame. This is the whole api-read client:
180 /// after the handshake a service opens a stream, writes an `ApiRequest`,
181 /// and reads one `ApiResponse`.
182 pub async fn api_read(conn: &quinn::Connection, body: &[u8]) -> (Value, Vec<u8>) {
183 let (mut send, mut recv) = conn.open_bi().await.expect("api-read stream");
184 send.write_all(&frame(body))
185 .await
186 .expect("write ApiRequest");
187 let _ = send.finish();
188 frame_or_fail(&mut recv, "read ApiResponse").await
189 }
190
191 /// Send one frame verbatim on a fresh *client*-initiated stream, read the
192 /// single answer frame, and then read whatever raw bytes followed it. That
193 /// is the whole blob client: one `BlobRequest`, one header frame, then
194 /// exactly `size` bytes and EOF.
195 pub async fn blob_read(conn: &quinn::Connection, body: &[u8]) -> (Value, Vec<u8>, Vec<u8>) {
196 let (mut send, mut recv) = conn.open_bi().await.expect("blob stream");
197 send.write_all(&frame(body))
198 .await
199 .expect("write BlobRequest");
200 let _ = send.finish();
201 let (header, bytes) = frame_or_fail(&mut recv, "read BlobResponse").await;
202 // Deliberately asks for more than the header promised: a stream that
203 // wrote one byte too many would show up here, not as a silent pass.
204 let body = recv
205 .read_to_end(16 * 1024 * 1024)
206 .await
207 .expect("read to EOF after the header");
208 (header, bytes, body)
209 }
210
211 /// One frame, **bounded**: the raw client must fail a stalled bridge by
212 /// name in seconds rather than hang the run (and the serialized deploy
213 /// behind it). `what` is the wait this call is doing, for the panic.
214 pub async fn frame_or_fail(recv: &mut quinn::RecvStream, what: &str) -> (Value, Vec<u8>) {
215 match tokio::time::timeout(Duration::from_secs(10), read_frame(recv)).await {
216 Ok(Ok(frame)) => frame,
217 Ok(Err(err)) => panic!("{what}: the frame could not be read: {err}"),
218 Err(_) => panic!("{what}: no frame arrived within 10s — the bridge did not answer"),
219 }
220 }
221
222 /// The set of top-level keys of a JSON object, sorted.
223 pub fn keys(value: &Value) -> Vec<String> {
224 let mut k: Vec<String> = value
225 .as_object()
226 .expect("a JSON object")
227 .keys()
228 .cloned()
229 .collect();
230 k.sort();
231 k
232 }
233}
234
235// --------------------------------------------------------------- harness --
236
237async fn bridge_with_timeout(timeout: Duration) -> AiBridge {
238 AiBridge::bind(BridgeConfig {
239 addr: "127.0.0.1:0".parse().unwrap(),
240 token: TOKEN.to_string(),
241 cert_path: None,
242 key_path: None,
243 request_timeout: timeout,
244 })
245 .await
246 .expect("bridge binds")
247}
248
249async fn bridge() -> AiBridge {
250 bridge_with_timeout(Duration::from_secs(5)).await
251}
252
253async fn await_workers(bridge: &AiBridge, expected: usize) {
254 for _ in 0..300 {
255 if bridge.workers().len() == expected {
256 return;
257 }
258 tokio::time::sleep(Duration::from_millis(10)).await;
259 }
260 panic!("expected {expected} workers, saw {:?}", bridge.workers());
261}
262
263/// Dispatch on a background task so the test can play the service in the
264/// foreground.
265fn dispatch(
266 bridge: &AiBridge,
267 capability: &str,
268 payload: Value,
269) -> tokio::task::JoinHandle<Result<Value, AiError>> {
270 let bridge = bridge.clone();
271 let capability = capability.to_string();
272 let school = hezarfen_backend::tenant::SchoolId::try_parse(SCHOOL).expect("the demo slug");
273 tokio::spawn(async move { bridge.dispatch(&school, &capability, payload).await })
274}
275
276// ------------------------------------------------------- framing contract --
277
278#[tokio::test]
279async fn the_length_prefix_is_four_byte_big_endian() {
280 // Flipping to little-endian would still round-trip between two Rust peers
281 // that share this crate — and break every foreign service instantly. Here
282 // the header is read as four separate bytes and reassembled by hand.
283 let bridge = bridge().await;
284 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
285 await_workers(&bridge, 1).await;
286
287 let call = dispatch(&bridge, "ocr.extract", json!({ "k": "v" }));
288 let (_send, mut recv) = service.conn.accept_bi().await.unwrap();
289
290 let mut header = [0u8; 4];
291 recv.read_exact(&mut header)
292 .await
293 .expect("four header bytes");
294 let big_endian = u32::from_be_bytes(header) as usize;
295 let little_endian = u32::from_le_bytes(header) as usize;
296
297 let mut body = vec![0u8; big_endian];
298 recv.read_exact(&mut body)
299 .await
300 .expect("the body the header promised");
301 assert_eq!(body.len(), big_endian);
302 // A real request frame is well under 16 MiB, so the two top bytes are zero
303 // and only the big-endian reading is plausible.
304 assert_eq!(
305 header[0], 0,
306 "top byte of a small frame's length must be zero"
307 );
308 assert_eq!(header[1], 0);
309 assert_ne!(
310 big_endian, little_endian,
311 "test is only meaningful when the two readings differ"
312 );
313 assert!(
314 serde_json::from_slice::<Value>(&body).is_ok(),
315 "the big-endian length delimited exactly one JSON document"
316 );
317 call.abort();
318}
319
320#[tokio::test]
321async fn a_frame_split_across_many_writes_is_reassembled() {
322 // QUIC delivers a stream, not messages. A reader that assumed one read
323 // yields one whole frame would pass every other test and fail under real
324 // network conditions, so the Hello is dribbled out a byte at a time.
325 let bridge = bridge().await;
326 let endpoint = raw::endpoint(&bridge);
327 let conn = endpoint
328 .connect(bridge.local_addr().unwrap(), "localhost")
329 .unwrap()
330 .await
331 .unwrap();
332 let (mut send, mut recv) = conn.open_bi().await.unwrap();
333
334 let bytes = raw::frame(&raw::hello("ocr", "ocr.extract"));
335 for byte in &bytes {
336 send.write_all(&[*byte]).await.expect("dribble");
337 tokio::task::yield_now().await;
338 }
339
340 let (greeting, _) = raw::frame_or_fail(&mut recv, "still welcomed").await;
341 assert_eq!(greeting["type"], "welcome");
342 await_workers(&bridge, 1).await;
343}
344
345#[tokio::test]
346async fn a_declared_length_over_the_cap_is_refused_without_the_body() {
347 // The guard is the reason a bad four-byte header cannot make the backend
348 // reserve gigabytes. Only the header is ever sent; the bridge must reject
349 // on that alone rather than waiting for a body that never comes.
350 let bridge = bridge().await;
351 let endpoint = raw::endpoint(&bridge);
352 let conn = endpoint
353 .connect(bridge.local_addr().unwrap(), "localhost")
354 .unwrap()
355 .await
356 .unwrap();
357 let (mut send, _recv) = conn.open_bi().await.unwrap();
358 let oversized: u32 = 9 * 1024 * 1024; // over the 8 MiB cap
359 send.write_all(&oversized.to_be_bytes()).await.unwrap();
360
361 // No body follows. The bridge must not register the service, and must not
362 // still be waiting when the handshake timeout would otherwise apply.
363 tokio::time::sleep(Duration::from_millis(300)).await;
364 assert!(
365 bridge.workers().is_empty(),
366 "an oversized frame must not produce a registration"
367 );
368}
369
370#[tokio::test]
371async fn a_zero_length_frame_is_rejected_not_treated_as_empty() {
372 let bridge = bridge().await;
373 let service = raw::handshake(&bridge, b"").await;
374 assert_eq!(service.greeting["type"], "rejected");
375 assert_eq!(service.greeting["code"], "malformed");
376 assert!(bridge.workers().is_empty());
377}
378
379// ------------------------------------------------- handshake key contract --
380
381#[tokio::test]
382async fn the_welcome_frame_carries_exactly_the_published_keys() {
383 let bridge = bridge().await;
384 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
385
386 assert_eq!(
387 raw::keys(&service.greeting),
388 ["protocol", "type", "worker_id"]
389 );
390 assert_eq!(service.greeting["type"], "welcome");
391 assert_eq!(service.greeting["protocol"], PROTOCOL);
392 assert!(
393 service.greeting["worker_id"]
394 .as_str()
395 .is_some_and(|w| !w.is_empty()),
396 "worker_id is a non-empty string a service can log"
397 );
398}
399
400#[tokio::test]
401async fn the_rejection_frame_carries_exactly_the_published_keys_and_codes() {
402 // A service switches on these literals. Re-tagging the enum or renaming a
403 // variant is a breaking change and must fail here.
404 let bridge = bridge().await;
405
406 let cases: [(&str, Vec<u8>); 5] = [
407 (
408 "unauthorized",
409 format!(
410 r#"{{"protocol":"{PROTOCOL}","service":"s","capabilities":["c"],"token":"wrong"}}"#
411 )
412 .into_bytes(),
413 ),
414 (
415 "unsupported_protocol",
416 format!(
417 r#"{{"protocol":"hab/99","service":"s","capabilities":["c"],"token":"{TOKEN}"}}"#
418 )
419 .into_bytes(),
420 ),
421 // The immediate predecessor, named on purpose: `hab/1` frames carry no
422 // school, so a service still speaking it must be turned away here
423 // rather than reaching a path that would have to guess one.
424 (
425 "unsupported_protocol",
426 format!(
427 r#"{{"protocol":"hab/1","service":"s","capabilities":["c"],"token":"{TOKEN}"}}"#
428 )
429 .into_bytes(),
430 ),
431 (
432 "no_capabilities",
433 format!(
434 r#"{{"protocol":"{PROTOCOL}","service":"s","capabilities":[],"token":"{TOKEN}"}}"#
435 )
436 .into_bytes(),
437 ),
438 ("malformed", b"not json".to_vec()),
439 ];
440
441 for (expected_code, hello) in cases {
442 let service = raw::handshake(&bridge, &hello).await;
443 assert_eq!(
444 raw::keys(&service.greeting),
445 ["code", "message", "type"],
446 "rejection shape changed for {expected_code}"
447 );
448 assert_eq!(service.greeting["type"], "rejected");
449 assert_eq!(
450 service.greeting["code"], expected_code,
451 "reject code spelling changed: {}",
452 service.greeting
453 );
454 assert!(
455 service.greeting["message"].as_str().is_some(),
456 "message must be a string a service can log"
457 );
458 }
459 assert!(bridge.workers().is_empty());
460}
461
462#[tokio::test]
463async fn hello_accepts_unknown_fields_so_services_can_run_ahead() {
464 // Forward compatibility: a newer service sending a field this backend does
465 // not know must still register, or every rollout becomes lockstep.
466 let bridge = bridge().await;
467 let hello = format!(
468 r#"{{"protocol":"{PROTOCOL}","service":"ocr","capabilities":["ocr.extract"],"token":"{TOKEN}","future_field":{{"nested":true}},"model":"gpt-9"}}"#
469 );
470 let service = raw::handshake(&bridge, hello.as_bytes()).await;
471 assert_eq!(service.greeting["type"], "welcome");
472 await_workers(&bridge, 1).await;
473}
474
475#[tokio::test]
476async fn hello_requires_its_documented_fields() {
477 // The mirror of the test above: dropping a *required* field must be a
478 // clean `malformed` rejection, never a silent default that registers a
479 // half-configured worker.
480 let bridge = bridge().await;
481 let required = ["protocol", "service", "capabilities", "token"];
482
483 for missing in required {
484 let mut fields = json!({
485 "protocol": PROTOCOL,
486 "service": "ocr",
487 "capabilities": ["ocr.extract"],
488 "token": TOKEN,
489 });
490 fields.as_object_mut().unwrap().remove(missing);
491 let body = serde_json::to_vec(&fields).unwrap();
492
493 let service = raw::handshake(&bridge, &body).await;
494 assert_eq!(
495 service.greeting["type"], "rejected",
496 "a Hello without `{missing}` was accepted"
497 );
498 assert_eq!(service.greeting["code"], "malformed");
499 }
500 assert!(bridge.workers().is_empty());
501}
502
503#[tokio::test]
504async fn max_concurrent_stays_optional() {
505 // `raw::hello` omits it entirely — a service that never sets it must still
506 // register and get the default.
507 let bridge = bridge().await;
508 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
509 assert_eq!(service.greeting["type"], "welcome");
510 await_workers(&bridge, 1).await;
511 assert!(
512 bridge.workers()[0].max_concurrent >= 1,
513 "an omitted max_concurrent yields a usable default"
514 );
515}
516
517#[tokio::test]
518async fn a_foreign_alpn_is_refused_at_the_tls_handshake() {
519 // The version gate: an incompatible service must be stopped before it can
520 // send a frame this backend would misparse.
521 let bridge = bridge().await;
522 // `hab/1` included by name: the version gate is the *first* line of defence
523 // against a service whose frames name no school, ahead of the Hello check.
524 for alpn in [b"hab/99".as_slice(), b"hab/1".as_slice()] {
525 let endpoint = raw::endpoint_with_alpn(&bridge, alpn);
526 let result = endpoint
527 .connect(bridge.local_addr().unwrap(), "localhost")
528 .unwrap()
529 .await;
530 assert!(
531 result.is_err(),
532 "ALPN {} must not connect",
533 String::from_utf8_lossy(alpn)
534 );
535 }
536 assert!(bridge.workers().is_empty());
537}
538
539// --------------------------------------------------- request key contract --
540
541#[tokio::test]
542async fn the_request_frame_carries_exactly_the_published_keys() {
543 // The contract a foreign service parses. An added, removed or renamed key
544 // fails here — this is the assertion `ai_bridge.rs` structurally cannot
545 // make, because there both ends share one Rust struct.
546 let bridge = bridge_with_timeout(Duration::from_secs(7)).await;
547 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
548 await_workers(&bridge, 1).await;
549
550 let call = dispatch(&bridge, "ocr.extract", json!({ "image": "abc", "n": 3 }));
551 let (request, _bytes, send, _recv) = raw::take_request(&service.conn).await;
552
553 assert_eq!(
554 raw::keys(&request),
555 ["capability", "deadline_ms", "id", "payload", "school"],
556 "request shape changed: {request}"
557 );
558 assert_eq!(request["capability"], "ocr.extract");
559 assert_eq!(request["deadline_ms"], 7000);
560 assert!(request["id"].as_str().is_some_and(|i| !i.is_empty()));
561 // The payload is passed through untouched — the transport must not wrap,
562 // stringify or reorder a caller's body.
563 assert_eq!(request["payload"], json!({ "image": "abc", "n": 3 }));
564
565 let id = request["id"].as_str().unwrap().to_string();
566 raw::answer(
567 send,
568 format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"text":"hi"}}}}"#)
569 .as_bytes(),
570 )
571 .await;
572 let answer = call.await.unwrap().expect("dispatch succeeded");
573 assert_eq!(answer, json!({ "text": "hi" }));
574}
575
576#[tokio::test]
577async fn a_payload_of_any_json_shape_survives_unchanged() {
578 // The transport is payload-agnostic by contract. Anything that "helpfully"
579 // normalised a body — dropping nulls, coercing numbers, flattening — would
580 // corrupt a capability's data in a way no typed test would notice.
581 let bridge = bridge().await;
582 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
583 await_workers(&bridge, 1).await;
584
585 let payloads = [
586 json!(null),
587 json!(true),
588 json!(-17),
589 json!(1.5),
590 json!("düz metin — ünicode"),
591 json!([]),
592 json!([1, [2, [3]], { "deep": { "deeper": null } }]),
593 json!({ "empty": {}, "zero": 0, "false": false, "nul": null }),
594 ];
595
596 for payload in payloads {
597 let call = dispatch(&bridge, "ocr.extract", payload.clone());
598 let (request, _, send, _recv) = raw::take_request(&service.conn).await;
599 assert_eq!(request["payload"], payload, "payload mutated in flight");
600
601 let id = request["id"].as_str().unwrap();
602 let echo = json!({ "status": "ok", "id": id, "school": SCHOOL, "payload": payload });
603 raw::answer(send, &serde_json::to_vec(&echo).unwrap()).await;
604 assert_eq!(
605 call.await.unwrap().unwrap(),
606 payload,
607 "payload mutated on return"
608 );
609 }
610}
611
612#[tokio::test]
613async fn the_response_tags_are_the_published_literals() {
614 // A service *writes* these, so the backend's parser is the contract. Both
615 // spellings are exercised, plus a wrong one to prove they are checked.
616 let bridge = bridge().await;
617 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
618 await_workers(&bridge, 1).await;
619
620 let ok = dispatch(&bridge, "ocr.extract", json!(1));
621 let (request, _, send, _r) = raw::take_request(&service.conn).await;
622 let id = request["id"].as_str().unwrap().to_string();
623 raw::answer(
624 send,
625 format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":42}}"#).as_bytes(),
626 )
627 .await;
628 assert_eq!(ok.await.unwrap().unwrap(), json!(42));
629
630 let err = dispatch(&bridge, "ocr.extract", json!(2));
631 let (request, _, send, _r) = raw::take_request(&service.conn).await;
632 let id = request["id"].as_str().unwrap().to_string();
633 raw::answer(
634 send,
635 format!(r#"{{"status":"err","id":"{id}","school":"{SCHOOL}","code":"bad_input","message":"nope"}}"#).as_bytes(),
636 )
637 .await;
638 match err.await.unwrap() {
639 Err(AiError::Remote { code, message }) => {
640 assert_eq!(code, "bad_input");
641 assert_eq!(message, "nope");
642 }
643 other => panic!("expected a remote error, got {other:?}"),
644 }
645
646 let bogus = dispatch(&bridge, "ocr.extract", json!(3));
647 let (request, _, send, _r) = raw::take_request(&service.conn).await;
648 let id = request["id"].as_str().unwrap().to_string();
649 raw::answer(
650 send,
651 format!(r#"{{"status":"success","id":"{id}","school":"{SCHOOL}","payload":1}}"#).as_bytes(),
652 )
653 .await;
654 assert!(
655 matches!(bogus.await.unwrap(), Err(AiError::Protocol(_))),
656 "an unpublished status tag must be refused, not guessed at"
657 );
658}
659
660#[tokio::test]
661async fn a_response_may_carry_unknown_fields() {
662 // Same forward-compatibility rule as `Hello`: a newer service adding a
663 // field (timings, model name) must not break an older backend.
664 let bridge = bridge().await;
665 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
666 await_workers(&bridge, 1).await;
667
668 let call = dispatch(&bridge, "ocr.extract", json!(null));
669 let (request, _, send, _r) = raw::take_request(&service.conn).await;
670 let id = request["id"].as_str().unwrap().to_string();
671 raw::answer(
672 send,
673 format!(
674 r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"text":"x"}},"took_ms":91,"model":"v2"}}"#
675 )
676 .as_bytes(),
677 )
678 .await;
679 assert_eq!(call.await.unwrap().unwrap(), json!({ "text": "x" }));
680}
681
682#[tokio::test]
683async fn a_response_missing_its_id_is_refused() {
684 let bridge = bridge().await;
685 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
686 await_workers(&bridge, 1).await;
687
688 let call = dispatch(&bridge, "ocr.extract", json!(null));
689 let (_request, _, send, _r) = raw::take_request(&service.conn).await;
690 raw::answer(send, br#"{"status":"ok","payload":1}"#).await;
691 assert!(
692 matches!(call.await.unwrap(), Err(AiError::Protocol(_))),
693 "id is required on the wire"
694 );
695}
696
697// ------------------------------------------------------- stream behaviour --
698
699#[tokio::test]
700async fn each_request_gets_its_own_stream_and_answers_may_come_back_in_any_order() {
701 // The core promise of using QUIC: correlation is the stream, so answering
702 // out of order — the natural case when inference times differ — must route
703 // every payload to its own caller.
704 let bridge = bridge_with_timeout(Duration::from_secs(20)).await;
705 let hello = format!(
706 r#"{{"protocol":"{PROTOCOL}","service":"ocr","capabilities":["ocr.extract"],"token":"{TOKEN}","max_concurrent":8}}"#
707 );
708 let service = raw::handshake(&bridge, hello.as_bytes()).await;
709 await_workers(&bridge, 1).await;
710
711 let calls: Vec<_> = (0..5)
712 .map(|i| dispatch(&bridge, "ocr.extract", json!({ "n": i })))
713 .collect();
714
715 // Collect all five streams before answering any: they must all be open at
716 // once, which is only true if each request took a fresh stream.
717 let mut pending = Vec::new();
718 for _ in 0..5 {
719 let (request, _, send, _recv) = raw::take_request(&service.conn).await;
720 pending.push((request, send));
721 }
722
723 // Answer in reverse arrival order.
724 pending.reverse();
725 for (request, send) in pending {
726 let id = request["id"].as_str().unwrap().to_string();
727 let n = request["payload"]["n"].clone();
728 raw::answer(
729 send,
730 format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"n":{n}}}}}"#)
731 .as_bytes(),
732 )
733 .await;
734 }
735
736 for (i, call) in calls.into_iter().enumerate() {
737 let answer = call.await.unwrap().expect("dispatch ok");
738 assert_eq!(
739 answer["n"], i as u64,
740 "answer {i} came back on the wrong caller's future"
741 );
742 }
743}
744
745#[tokio::test]
746async fn request_ids_are_unique_per_request() {
747 // The id is only a trace id, but a repeated one makes production logs
748 // unreadable and would silently pass the id-echo check.
749 let bridge = bridge().await;
750 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
751 await_workers(&bridge, 1).await;
752
753 let mut seen = std::collections::HashSet::new();
754 for _ in 0..6 {
755 let call = dispatch(&bridge, "ocr.extract", json!(null));
756 let (request, _, send, _r) = raw::take_request(&service.conn).await;
757 let id = request["id"].as_str().unwrap().to_string();
758 assert!(seen.insert(id.clone()), "id {id} was reused");
759 raw::answer(
760 send,
761 format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":1}}"#).as_bytes(),
762 )
763 .await;
764 call.await.unwrap().unwrap();
765 }
766}
767
768#[tokio::test]
769async fn the_control_stream_carries_no_frames_after_the_welcome() {
770 // Its only remaining job is to be open. If the backend ever started
771 // expecting heartbeats here, a service that just holds it open would be
772 // dropped — so assert the silence is fine, then prove the worker still
773 // serves.
774 let bridge = bridge().await;
775 let mut service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
776 await_workers(&bridge, 1).await;
777
778 let quiet = tokio::time::timeout(
779 Duration::from_millis(400),
780 raw::read_frame(&mut service.control.1),
781 )
782 .await;
783 assert!(
784 quiet.is_err(),
785 "nothing should arrive on the control stream"
786 );
787
788 let call = dispatch(&bridge, "ocr.extract", json!(null));
789 let (request, _, send, _r) = raw::take_request(&service.conn).await;
790 let id = request["id"].as_str().unwrap().to_string();
791 raw::answer(
792 send,
793 format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":1}}"#).as_bytes(),
794 )
795 .await;
796 call.await
797 .unwrap()
798 .expect("still serving after the silence");
799}
800
801#[tokio::test]
802async fn closing_the_control_stream_deregisters_the_service() {
803 // The documented goodbye. A service that finishes the control stream is
804 // saying "I am going away" even though the QUIC connection is still up.
805 let bridge = bridge().await;
806 let mut service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
807 await_workers(&bridge, 1).await;
808
809 let _ = service.control.0.finish();
810 drop(service.control);
811 service.conn.close(0u32.into(), b"goodbye");
812 await_workers(&bridge, 0).await;
813
814 assert!(matches!(
815 bridge
816 .dispatch(
817 &hezarfen_backend::tenant::SchoolId::try_parse(SCHOOL).unwrap(),
818 "ocr.extract",
819 json!(null)
820 )
821 .await,
822 Err(AiError::NoWorker(_))
823 ));
824}
825
826#[tokio::test]
827async fn a_service_that_drops_a_request_stream_fails_that_request_only() {
828 // A crash mid-inference. The caller must get a transport error, and the
829 // connection must remain usable for the next request rather than being
830 // torn down.
831 let bridge = bridge().await;
832 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
833 await_workers(&bridge, 1).await;
834
835 let doomed = dispatch(&bridge, "ocr.extract", json!("first"));
836 let (_request, _, send, recv) = raw::take_request(&service.conn).await;
837 drop(send);
838 drop(recv);
839 let err = doomed
840 .await
841 .unwrap()
842 .expect_err("the dropped stream failed");
843 assert!(
844 matches!(err, AiError::Transport(_) | AiError::Protocol(_)),
845 "unexpected error: {err}"
846 );
847
848 assert_eq!(
849 bridge.workers().len(),
850 1,
851 "the worker survives one bad stream"
852 );
853 let next = dispatch(&bridge, "ocr.extract", json!("second"));
854 let (request, _, send, _r) = raw::take_request(&service.conn).await;
855 let id = request["id"].as_str().unwrap().to_string();
856 raw::answer(
857 send,
858 format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":"ok"}}"#).as_bytes(),
859 )
860 .await;
861 assert_eq!(next.await.unwrap().unwrap(), json!("ok"));
862}
863
864#[tokio::test]
865async fn a_late_answer_after_the_deadline_is_not_delivered() {
866 // The deadline is a promise to the caller, not a hint. A service that
867 // ignores `deadline_ms` must not be able to resolve a future that already
868 // failed.
869 let bridge = bridge_with_timeout(Duration::from_millis(250)).await;
870 let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await;
871 await_workers(&bridge, 1).await;
872
873 let call = dispatch(&bridge, "ocr.extract", json!(null));
874 let (request, _, send, _r) = raw::take_request(&service.conn).await;
875 assert_eq!(
876 request["deadline_ms"], 250,
877 "the service was told the deadline"
878 );
879
880 assert!(
881 matches!(call.await.unwrap(), Err(AiError::Timeout(250))),
882 "the call fails at the deadline"
883 );
884 assert_eq!(bridge.workers()[0].inflight, 0, "the slot was released");
885
886 // Abandoning the request also tears the stream down, so a service that
887 // ignored `deadline_ms` finds out: the backend stops the stream and the
888 // service's send half reports it. Not synchronous — a QUIC reset costs a
889 // round trip — so wait for it rather than probing once.
890 //
891 // This is why a service should read a write failure on a request stream as
892 // "the caller gave up", not as a bug, and stop the work.
893 let stopped = tokio::time::timeout(Duration::from_secs(2), send.stopped()).await;
894 assert!(
895 stopped.is_ok(),
896 "the abandoned stream must be torn down, not left open for a late answer"
897 );
898
899 // And the caller is unaffected by whatever the service does afterwards:
900 // the worker is idle and immediately reusable.
901 assert_eq!(bridge.workers()[0].inflight, 0);
902}
903
904#[tokio::test]
905async fn several_raw_services_serve_one_capability_together() {
906 // Scale-out as a service author experiences it: three independent
907 // connections, no backend config change, every request answered exactly
908 // once by exactly one of them.
909 let bridge = bridge_with_timeout(Duration::from_secs(20)).await;
910 let mut services = Vec::new();
911 for i in 0..3 {
912 services
913 .push(raw::handshake(&bridge, &raw::hello(&format!("ocr-{i}"), "ocr.extract")).await);
914 }
915 await_workers(&bridge, 3).await;
916
917 // Each service answers whatever it is handed, forever.
918 for service in &services {
919 let conn = service.conn.clone();
920 tokio::spawn(async move {
921 while let Ok((send, mut recv)) = conn.accept_bi().await {
922 let Ok((request, _)) = raw::read_frame(&mut recv).await else {
923 return;
924 };
925 let id = request["id"].as_str().unwrap().to_string();
926 let n = request["payload"]["n"].clone();
927 raw::answer(
928 send,
929 format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{n}}}"#)
930 .as_bytes(),
931 )
932 .await;
933 }
934 });
935 }
936
937 let calls: Vec<_> = (0..12)
938 .map(|n| dispatch(&bridge, "ocr.extract", json!({ "n": n })))
939 .collect();
940 let mut got: Vec<u64> = Vec::new();
941 for call in calls {
942 got.push(call.await.unwrap().unwrap().as_u64().expect("echoed n"));
943 }
944 got.sort_unstable();
945 assert_eq!(
946 got,
947 (0..12).collect::<Vec<u64>>(),
948 "every request answered once"
949 );
950}
951
952// ------------------------------------------------------ capability payload --
953//
954// The frame shapes above are capability-agnostic. `chat.reply` is the one
955// capability whose *payload* is a published contract too, and the payload is
956// built by the HTTP handler — so the only way to pin it as a foreign service
957// sees it is to drive the real endpoint and read the bytes off the wire.
958
959#[tokio::test]
960async fn a_chat_request_names_the_askers_school_role() {
961 // A chat service scopes its answer by who is asking, so the payload must
962 // carry the asker's school role as a bare lowercase string — read here out
963 // of the raw frame bytes, never through the crate's own payload struct.
964 let bridge = bridge().await;
965 let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
966 await_workers(&bridge, 1).await;
967
968 let tenants = hezarfen_backend::database::init_test_tenants().await;
969 let db = tenants
970 .get(&hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).unwrap())
971 .await
972 .expect("the demo school");
973 let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState {
974 db: tenants.control().clone(),
975 tenants,
976 files_path: common::files_dir(),
977 cookie_secure: false,
978 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
979 chatbot_limit: Default::default(),
980 rag_limit: Default::default(),
981 exam_presence: Default::default(),
982 board_hub: Default::default(),
983 ai: Some(bridge.clone()),
984 metrics: hezarfen_backend::telemetry::Metrics::noop(),
985 });
986 let cookie = common::login_as(&app, &db, "veli", "teacher").await;
987 let res = common::send(
988 &app,
989 "POST",
990 "/chatbot/threads",
991 Some(&cookie),
992 Some(json!({})),
993 )
994 .await;
995 let thread = common::id_of(&res.body);
996 let res = common::send(
997 &app,
998 "POST",
999 &format!("/chatbot/threads/{thread}/messages"),
1000 Some(&cookie),
1001 Some(json!({ "content": "ikinci yasa nedir?" })),
1002 )
1003 .await;
1004 assert_eq!(res.status, axum::http::StatusCode::ACCEPTED, "{}", res.body);
1005
1006 let (request, bytes, send, _recv) = raw::take_request(&service.conn).await;
1007 assert_eq!(request["capability"], "chat.reply");
1008 assert_eq!(
1009 raw::keys(&request["payload"]),
1010 ["asker_role", "history", "message"],
1011 "the documented chat request payload keys"
1012 );
1013 assert_eq!(request["payload"]["message"], "ikinci yasa nedir?");
1014 assert_eq!(request["payload"]["asker_role"], "teacher");
1015 // Byte-level: a bare `"teacher"`, not an object-wrapped or capitalised
1016 // enum — a re-tagged role would still parse as JSON above.
1017 let text = String::from_utf8(bytes).expect("the frame body is UTF-8 JSON");
1018 assert!(text.contains(r#""asker_role":"teacher""#), "{text}");
1019
1020 let id = request["id"].as_str().expect("trace id").to_string();
1021 raw::answer(
1022 send,
1023 format!(
1024 r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"text":"F = ma"}}}}"#
1025 )
1026 .as_bytes(),
1027 )
1028 .await;
1029}
1030
1031// ------------------------------------------------- rag.chat payload keys --
1032//
1033// `rag.chat` is the other capability whose payload is a published contract.
1034// In this wave nothing in the HTTP surface builds one yet, so its payload is
1035// pinned by putting the crate's own payload through the real bridge and reading
1036// the bytes exactly as a foreign service would: raw frames, and the documented
1037// key sets — never parsed back through the crate's payload structs.
1038
1039#[tokio::test]
1040async fn rag_chat_payloads_carry_the_documented_wire_keys() {
1041 use hezarfen_backend::ai::{
1042 RagChatReplyPayload, RagChatRequestPayload, RagCitation, RagScopePair,
1043 };
1044
1045 let bridge = bridge().await;
1046 let service = raw::handshake(&bridge, &raw::hello("rag", "rag.chat")).await;
1047 await_workers(&bridge, 1).await;
1048
1049 let request = serde_json::to_value(RagChatRequestPayload {
1050 message: "ikinci yasa nedir?".into(),
1051 asker: "01ASKER".into(),
1052 asker_role: "student".into(),
1053 scope: vec![RagScopePair {
1054 sinif: Some("11".into()),
1055 ders: "Fizik".into(),
1056 }],
1057 history: Vec::new(),
1058 })
1059 .unwrap();
1060 let call = dispatch(&bridge, "rag.chat", request);
1061
1062 let (frame, bytes, send, _recv) = raw::take_request(&service.conn).await;
1063 assert_eq!(frame["capability"], "rag.chat");
1064 assert_eq!(
1065 raw::keys(&frame["payload"]),
1066 ["asker", "asker_role", "history", "message", "scope"],
1067 "the documented rag.chat request payload keys"
1068 );
1069 assert_eq!(
1070 raw::keys(&frame["payload"]["scope"][0]),
1071 ["ders", "sinif"],
1072 "a scope pair is routed by (sinif, ders)"
1073 );
1074 // Byte-level: the `(sinif, ders)` pair set, not a re-wrapped shape.
1075 let text = String::from_utf8(bytes).expect("the frame body is UTF-8 JSON");
1076 assert!(
1077 text.contains(r#""scope":[{"ders":"Fizik","sinif":"11"}]"#),
1078 "{text}"
1079 );
1080
1081 let reply = serde_json::to_value(RagChatReplyPayload {
1082 text: "F = m·a [1]".into(),
1083 abstained: false,
1084 reason: String::new(),
1085 citations: vec![RagCitation {
1086 n: 1,
1087 doc_id: "01DOC".into(),
1088 pages: vec![3],
1089 span_ids: vec!["s-7".into()],
1090 ders: Some("Fizik".into()),
1091 }],
1092 })
1093 .unwrap();
1094 let id = frame["id"].as_str().expect("trace id").to_string();
1095 raw::answer(
1096 send,
1097 format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{reply}}}"#)
1098 .as_bytes(),
1099 )
1100 .await;
1101
1102 let answer = call.await.unwrap().unwrap();
1103 assert_eq!(
1104 raw::keys(&answer),
1105 ["abstained", "citations", "reason", "text"],
1106 "the documented rag.chat reply payload keys"
1107 );
1108 assert_eq!(
1109 raw::keys(&answer["citations"][0]),
1110 ["ders", "doc_id", "n", "pages", "span_ids"],
1111 "the documented citation keys"
1112 );
1113}
1114
1115// ------------------------------------------------------------- api reads --
1116//
1117// The other direction: a service opens its own stream and asks the school API
1118// a question. Its request and the backend's answer are a published contract in
1119// exactly the same way as the frames above, so they are built and read here as
1120// bytes — a renamed field or a re-tagged outcome breaks every foreign service
1121// and must break this file first.
1122
1123/// A bridge whose api-read path is armed by a real router, plus a seeded
1124/// student's id. Holding the router is what `build_router` arms, so it is
1125/// returned rather than dropped.
1126async fn armed(bridge: &AiBridge) -> (axum::Router, String) {
1127 let (app, db) = common::app_with_ai(Some(bridge.clone())).await;
1128 let cookie = common::login_as(&app, &db, "ayse", "student").await;
1129 let student = common::me_id(&app, &cookie).await;
1130 (app, student)
1131}
1132
1133#[tokio::test]
1134async fn the_api_request_field_names_are_the_published_literals() {
1135 // Every documented field spelled out by hand: a rename of `on_behalf_of`
1136 // or `query` would leave a service sending a field the backend ignores,
1137 // which fails silently as "the AI answered about the wrong person".
1138 let bridge = bridge().await;
1139 let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
1140 await_workers(&bridge, 1).await;
1141 let (_app, student) = armed(&bridge).await;
1142
1143 let (answer, bytes) = raw::api_read(
1144 &service.conn,
1145 format!(
1146 r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","school":"{SCHOOL}","path":"/notes","query":"limit=1&offset=0","on_behalf_of":"{student}","method":"GET"}}"#
1147 )
1148 .as_bytes(),
1149 )
1150 .await;
1151
1152 assert_eq!(
1153 raw::keys(&answer),
1154 ["body", "id", "outcome", "school", "status"],
1155 "api answer shape changed: {answer}"
1156 );
1157 assert_eq!(answer["outcome"], "ok");
1158 assert_eq!(answer["status"], 200);
1159 assert_eq!(
1160 answer["id"], "01ARZ3NDEKTSV4RRFFQ69G5FAV",
1161 "the trace id is echoed"
1162 );
1163 assert!(answer["body"]["items"].is_array(), "{answer}");
1164 // Byte level: the tag key is `outcome` and its value a bare lowercase
1165 // literal, not an object-wrapped or capitalised variant name.
1166 let text = String::from_utf8(bytes).expect("the answer frame is UTF-8 JSON");
1167 assert!(text.contains(r#""outcome":"ok""#), "{text}");
1168 assert!(text.contains(r#""status":200"#), "{text}");
1169}
1170
1171#[tokio::test]
1172async fn only_id_and_path_are_required_of_an_api_request() {
1173 // `query`, `on_behalf_of` and `method` are optional by contract: a service
1174 // that sends neither must read as the service itself, over GET.
1175 let bridge = bridge().await;
1176 let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
1177 await_workers(&bridge, 1).await;
1178 let (_app, _student) = armed(&bridge).await;
1179
1180 let (answer, _) = raw::api_read(
1181 &service.conn,
1182 br#"{"id":"trace-1","school":"019732e3-7b00-7000-8000-00000000dead","path":"/auth/me","unknown_field":true}"#,
1183 )
1184 .await;
1185 assert_eq!(answer["outcome"], "ok", "{answer}");
1186 assert_eq!(answer["status"], 200);
1187 // The synthetic principal the bridge runs as when nobody is named.
1188 assert_eq!(answer["body"]["role"], "ai", "{answer}");
1189}
1190
1191#[tokio::test]
1192async fn the_api_refusal_frame_carries_exactly_the_published_keys_and_codes() {
1193 // A service switches on these code literals. The `method` cases also pin
1194 // the refusal *order*: a non-GET on a path that is not allowlisted either
1195 // is `method_not_allowed`, because the method is judged first.
1196 let bridge = bridge().await;
1197 let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
1198 await_workers(&bridge, 1).await;
1199 let (_app, _student) = armed(&bridge).await;
1200
1201 let cases = [
1202 (
1203 "method_not_allowed",
1204 r#"{"id":"t1","school":"019732e3-7b00-7000-8000-00000000dead","path":"/notes","method":"DELETE"}"#.to_string(),
1205 ),
1206 (
1207 "method_not_allowed",
1208 // Lowercase is not the method: the literal is exactly `GET`.
1209 r#"{"id":"t2","school":"019732e3-7b00-7000-8000-00000000dead","path":"/notes","method":"get"}"#.to_string(),
1210 ),
1211 (
1212 "path_not_allowed",
1213 r#"{"id":"t3","school":"019732e3-7b00-7000-8000-00000000dead","path":"/courses"}"#.to_string(),
1214 ),
1215 (
1216 // Order pin: both refusals apply, the method one wins.
1217 "method_not_allowed",
1218 r#"{"id":"t4","school":"019732e3-7b00-7000-8000-00000000dead","path":"/nope","method":"POST"}"#.to_string(),
1219 ),
1220 (
1221 "unknown_user",
1222 r#"{"id":"t5","school":"019732e3-7b00-7000-8000-00000000dead","path":"/auth/me","on_behalf_of":"nobodyatall"}"#
1223 .to_string(),
1224 ),
1225 (
1226 "malformed",
1227 r#"{"id":"t6","school":"019732e3-7b00-7000-8000-00000000dead","path":42}"#.to_string(),
1228 ),
1229 // A frame that names no school at all: required, never defaulted.
1230 ("malformed", r#"{"id":"t7","path":"/auth/me"}"#.to_string()),
1231 // A string that is not a hyphenated uuid is `unknown_school`, not
1232 // `malformed`. `malformed` stays the frame-shape error (t7, above).
1233 (
1234 "unknown_school",
1235 r#"{"id":"t8","school":"NOT A SLUG","path":"/auth/me"}"#.to_string(),
1236 ),
1237 // A hyphenated uuid this deployment does not serve.
1238 (
1239 "unknown_school",
1240 r#"{"id":"t9","school":"019732e3-7b00-7000-8000-00000000eeee","path":"/auth/me"}"#.to_string(),
1241 ),
1242 ];
1243
1244 for (expected_code, request) in cases {
1245 let (answer, _) = raw::api_read(&service.conn, request.as_bytes()).await;
1246 assert_eq!(
1247 raw::keys(&answer),
1248 ["code", "id", "message", "outcome", "school"],
1249 "refusal shape changed for {expected_code}: {answer}"
1250 );
1251 assert_eq!(answer["outcome"], "err", "{answer}");
1252 assert_eq!(
1253 answer["code"], expected_code,
1254 "refusal code spelling changed: {answer}"
1255 );
1256 assert!(
1257 answer["message"].as_str().is_some_and(|m| !m.is_empty()),
1258 "message must be a string a service can log: {answer}"
1259 );
1260 // Even a frame the backend could not parse into a request echoes the
1261 // id, which is what the service correlates its own logs by.
1262 assert!(
1263 answer["id"].as_str().is_some_and(|i| i.starts_with('t')),
1264 "{answer}"
1265 );
1266 }
1267}
1268
1269#[tokio::test]
1270async fn an_api_read_answers_a_named_user_with_that_users_own_data() {
1271 // The happy path a service actually uses: read an own-scoped endpoint as
1272 // the student who asked. The answer must be that student's row, not the
1273 // service's synthetic principal.
1274 let bridge = bridge().await;
1275 let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
1276 await_workers(&bridge, 1).await;
1277 let (_app, student) = armed(&bridge).await;
1278
1279 let (answer, _) = raw::api_read(
1280 &service.conn,
1281 format!(
1282 r#"{{"id":"tme","school":"{SCHOOL}","path":"/auth/me","on_behalf_of":"{student}"}}"#
1283 )
1284 .as_bytes(),
1285 )
1286 .await;
1287 assert_eq!(answer["outcome"], "ok", "{answer}");
1288 assert_eq!(answer["status"], 200);
1289 assert_eq!(answer["body"]["id"], student, "{answer}");
1290 assert_eq!(answer["body"]["role"], "student", "{answer}");
1291}
1292
1293// --------------------------------------------------------------- tenancy --
1294//
1295// `hab/2`'s whole reason for existing: one shared fleet of services, every
1296// frame naming the school it means. These drive that through the raw client,
1297// because the refusal codes and the school echo are published contract exactly
1298// like the frame keys above.
1299
1300/// An armed bridge over a deployment with a *second* school, `beta`, holding a
1301/// user of the same name as the demo school's. Returns the router (holding it
1302/// is what keeps the bridge armed), the registry, and the two ids of `ayse`.
1303async fn two_schools(bridge: &AiBridge) -> (axum::Router, Tenants, String, String) {
1304 let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
1305 let beta_db = tenants
1306 .create(
1307 hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap(),
1308 "Beta College",
1309 ModuleSet::all(),
1310 )
1311 .await
1312 .expect("a second school");
1313
1314 let demo_cookie = common::login_as(&app, &demo_db, "ayse", "student").await;
1315 let beta_cookie = common::login_as_school(&app, &beta_db, "beta", "ayse", "student").await;
1316 let demo_ayse = common::me_id(&app, &demo_cookie).await;
1317 let beta_ayse = common::me_id(&app, &beta_cookie).await;
1318 assert_ne!(
1319 demo_ayse, beta_ayse,
1320 "two schools, two separate `ayse` rows"
1321 );
1322 (app, tenants, demo_ayse, beta_ayse)
1323}
1324
1325#[tokio::test]
1326async fn an_api_read_answers_out_of_the_school_the_frame_named() {
1327 // The isolation the field buys, proved both ways with one username: each
1328 // school's `ayse` is reachable in her own school and *nowhere else*. A
1329 // bridge that resolved the principal against the wrong database would
1330 // answer one of the cross reads with a user instead of `unknown_user`.
1331 let bridge = bridge().await;
1332 let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
1333 await_workers(&bridge, 1).await;
1334 let (_app, _tenants, demo_ayse, beta_ayse) = two_schools(&bridge).await;
1335
1336 for (school, who) in [("019732e3-7b00-7000-8000-00000000dead", &demo_ayse), ("019732e3-7b00-7000-8000-00000000beef", &beta_ayse)] {
1337 let (answer, _) = raw::api_read(
1338 &service.conn,
1339 format!(
1340 r#"{{"id":"t-own","school":"{school}","path":"/auth/me","on_behalf_of":"{who}"}}"#
1341 )
1342 .as_bytes(),
1343 )
1344 .await;
1345 assert_eq!(answer["outcome"], "ok", "{answer}");
1346 assert_eq!(answer["school"], school, "the school is echoed: {answer}");
1347 assert_eq!(answer["body"]["id"], who.as_str(), "{answer}");
1348 assert_eq!(answer["body"]["username"], "ayse");
1349 }
1350
1351 // And crossed over: the other school's id names nobody here.
1352 for (school, who) in [("019732e3-7b00-7000-8000-00000000dead", &beta_ayse), ("019732e3-7b00-7000-8000-00000000beef", &demo_ayse)] {
1353 let (answer, _) = raw::api_read(
1354 &service.conn,
1355 format!(
1356 r#"{{"id":"t-cross","school":"{school}","path":"/auth/me","on_behalf_of":"{who}"}}"#
1357 )
1358 .as_bytes(),
1359 )
1360 .await;
1361 assert_eq!(
1362 answer["code"], "unknown_user",
1363 "a user id from another school resolved in `{school}`: {answer}"
1364 );
1365 }
1366}
1367
1368#[tokio::test]
1369async fn a_suspended_school_is_refused_with_its_own_code() {
1370 // Distinct from `unknown_school` on purpose: this deployment does serve
1371 // `beta`, it is switched off — the one refusal here worth retrying later.
1372 let bridge = bridge().await;
1373 let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
1374 await_workers(&bridge, 1).await;
1375 let (_app, tenants, _demo_ayse, beta_ayse) = two_schools(&bridge).await;
1376
1377 let read = format!(
1378 r#"{{"id":"t-susp","school":"019732e3-7b00-7000-8000-00000000beef","path":"/auth/me","on_behalf_of":"{beta_ayse}"}}"#
1379 );
1380 let (answer, _) = raw::api_read(&service.conn, read.as_bytes()).await;
1381 assert_eq!(answer["outcome"], "ok", "the school starts out active");
1382
1383 tenants
1384 .set_status(&SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap(), SchoolStatus::Suspended)
1385 .await
1386 .expect("suspend beta");
1387
1388 let (answer, _) = raw::api_read(&service.conn, read.as_bytes()).await;
1389 assert_eq!(answer["outcome"], "err", "{answer}");
1390 assert_eq!(answer["code"], "school_suspended", "{answer}");
1391 assert_eq!(
1392 answer["school"], "019732e3-7b00-7000-8000-00000000beef",
1393 "the refusal names the school back"
1394 );
1395 assert_eq!(answer["id"], "t-susp");
1396
1397 // The demo school is untouched by its neighbour's suspension.
1398 let (answer, _) = raw::api_read(
1399 &service.conn,
1400 br#"{"id":"t-neighbour","school":"019732e3-7b00-7000-8000-00000000dead","path":"/auth/me"}"#,
1401 )
1402 .await;
1403 assert_eq!(answer["outcome"], "ok", "{answer}");
1404}
1405
1406#[tokio::test]
1407async fn a_blob_read_names_its_school_too() {
1408 // The blob path resolves the school independently of the api path, and its
1409 // refusals are the same three codes — so it gets the same proof.
1410 let bridge = bridge().await;
1411 let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await;
1412 await_workers(&bridge, 1).await;
1413 let (_app, student, file, uploaded, _tenants) = armed_with_file(&bridge).await;
1414
1415 let (header, _, body) = raw::blob_read(
1416 &service.conn,
1417 format!(
1418 r#"{{"id":"t-b1","school":"{SCHOOL}","file":"{file}","on_behalf_of":"{student}"}}"#
1419 )
1420 .as_bytes(),
1421 )
1422 .await;
1423 assert_eq!(header["status"], "ok", "{header}");
1424 assert_eq!(body.len(), uploaded.len());
1425
1426 for (school, code) in [("019732e3-7b00-7000-8000-00000000eeee", "unknown_school"), ("NOT A SLUG", "unknown_school")] {
1427 let (header, _, body) = raw::blob_read(
1428 &service.conn,
1429 format!(
1430 r#"{{"id":"t-b2","school":"{school}","file":"{file}","on_behalf_of":"{student}"}}"#
1431 )
1432 .as_bytes(),
1433 )
1434 .await;
1435 assert_eq!(header["status"], "err", "{header}");
1436 assert_eq!(header["code"], code, "{header}");
1437 assert!(body.is_empty(), "a refused blob stream carries no bytes");
1438 }
1439
1440 // And with no school named at all the frame does not parse.
1441 let (header, _, _) = raw::blob_read(
1442 &service.conn,
1443 format!(r#"{{"id":"t-b3","file":"{file}","on_behalf_of":"{student}"}}"#).as_bytes(),
1444 )
1445 .await;
1446 assert_eq!(header["code"], "malformed", "{header}");
1447}
1448
1449// --------------------------------------------------- blob stream contract --
1450//
1451// The bytes behind a course-note attachment, which no JSON frame can carry.
1452// The header frame is a published contract exactly like the ones above, and
1453// the `size`-then-EOF rule is what a foreign service implements by hand — so
1454// both are asserted here as bytes.
1455
1456/// An armed router plus an uploaded course-note file: its id, and the bytes
1457/// that were uploaded, read back by a service that must receive them verbatim.
1458async fn armed_with_file(bridge: &AiBridge) -> (axum::Router, String, String, Vec<u8>, Tenants) {
1459 let (app, db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
1460 let student_cookie = common::login_as(&app, &db, "ayse", "student").await;
1461 let student = common::me_id(&app, &student_cookie).await;
1462 let teacher = common::login_as(&app, &db, "hoca", "teacher").await;
1463 let mudur = common::login_as(&app, &db, "mudur", "manager").await;
1464 // The roster hangs off the şube's instance, so a manager mints the stack
1465 // with the teacher as its homeroom teacher.
1466 let t = common::taught_under(&app, &mudur, &teacher, "Physics").await;
1467 common::enroll(&app, &teacher, &t.instance, &student).await;
1468 let course = t.course.clone();
1469
1470 let res = common::send(
1471 &app,
1472 "POST",
1473 "/course-notes",
1474 Some(&teacher),
1475 Some(json!({ "course": course, "title": "Newton", "content": "F = ma" })),
1476 )
1477 .await;
1478 assert_eq!(res.status, 201, "{}", res.body);
1479 let note = common::id_of(&res.body);
1480
1481 // Larger than one QUIC datagram, so the answer is a genuine multi-write
1482 // stream rather than something that happened to fit beside the header.
1483 let uploaded: Vec<u8> = (0..200 * 1024u32).map(|i| (i % 251) as u8).collect();
1484 let res = common::upload_file_at(
1485 &app,
1486 &teacher,
1487 &format!("/course-notes/{note}/files"),
1488 "recap.pdf",
1489 "application/pdf",
1490 &uploaded,
1491 )
1492 .await;
1493 assert_eq!(res.status, 201, "{}", res.body);
1494 let file = common::id_of(&res.body);
1495 (app, student, file, uploaded, tenants)
1496}
1497
1498#[tokio::test]
1499async fn the_blob_header_frame_carries_exactly_the_published_keys_then_size_bytes() {
1500 // Every documented field spelled out by hand, and the byte rule with it: a
1501 // service reads the header, then exactly `size` raw bytes, then EOF. A
1502 // length prefix sneaking in front of the body, or one byte too many after
1503 // it, would leave a foreign service parsing garbage.
1504 let bridge = bridge().await;
1505 let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await;
1506 await_workers(&bridge, 1).await;
1507 let (_app, student, file, uploaded, _tenants) = armed_with_file(&bridge).await;
1508
1509 let (header, bytes, body) = raw::blob_read(
1510 &service.conn,
1511 format!(
1512 r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","school":"{SCHOOL}","file":"{file}","on_behalf_of":"{student}"}}"#
1513 )
1514 .as_bytes(),
1515 )
1516 .await;
1517
1518 assert_eq!(
1519 raw::keys(&header),
1520 ["content_type", "id", "name", "school", "size", "status"],
1521 "blob header shape changed: {header}"
1522 );
1523 assert_eq!(header["status"], "ok");
1524 assert_eq!(
1525 header["id"], "01ARZ3NDEKTSV4RRFFQ69G5FAV",
1526 "the trace id is echoed"
1527 );
1528 assert_eq!(header["name"], "recap.pdf");
1529 assert_eq!(header["content_type"], "application/pdf");
1530 assert_eq!(header["size"], uploaded.len(), "{header}");
1531
1532 // Byte level: the tag key is `status` with a bare lowercase literal, and
1533 // `size` is a JSON number, not a string a service would have to parse.
1534 let text = String::from_utf8(bytes).expect("the header frame is UTF-8 JSON");
1535 assert!(text.contains(r#""status":"ok""#), "{text}");
1536 assert!(
1537 text.contains(&format!(r#""size":{}"#, uploaded.len())),
1538 "{text}"
1539 );
1540
1541 // The body is raw: no four-byte length prefix, exactly `size` bytes, EOF.
1542 assert_eq!(body.len(), uploaded.len(), "`size` bytes then EOF");
1543 assert!(body == uploaded, "the bytes differ from what was uploaded");
1544}
1545
1546#[tokio::test]
1547async fn a_blob_refusal_frame_carries_exactly_the_published_keys_and_no_bytes() {
1548 let bridge = bridge().await;
1549 let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await;
1550 await_workers(&bridge, 1).await;
1551 let (_app, student, file, _uploaded, tenants) = armed_with_file(&bridge).await;
1552
1553 let (header, _, body) = raw::blob_read(
1554 &service.conn,
1555 format!(
1556 r#"{{"id":"t-blob","school":"{SCHOOL}","file":"01NOSUCHFILE","on_behalf_of":"{student}"}}"#
1557 )
1558 .as_bytes(),
1559 )
1560 .await;
1561 assert_eq!(
1562 raw::keys(&header),
1563 ["code", "id", "message", "school", "status"],
1564 "blob refusal shape changed: {header}"
1565 );
1566 assert_eq!(header["status"], "err");
1567 assert_eq!(header["code"], "not_found");
1568 assert_eq!(header["id"], "t-blob");
1569 assert!(body.is_empty(), "a refusal is followed by nothing at all");
1570
1571 // The entitlement refusal is the same published shape, under the code the
1572 // README's refusal table names. It is checked on this stream by hand — the
1573 // router's module gate cannot reach here — so it is a wire contract too.
1574 let mut modules = ModuleSet::all();
1575 modules.remove(hezarfen_backend::module::Module::CourseNotes);
1576 tenants
1577 .set_modules(&SchoolId::try_parse(SCHOOL).unwrap(), &modules)
1578 .await
1579 .expect("take course_notes off the demo school");
1580
1581 let (header, _, body) = raw::blob_read(
1582 &service.conn,
1583 format!(
1584 r#"{{"id":"t-mod","school":"{SCHOOL}","file":"{file}","on_behalf_of":"{student}"}}"#
1585 )
1586 .as_bytes(),
1587 )
1588 .await;
1589 assert_eq!(
1590 raw::keys(&header),
1591 ["code", "id", "message", "school", "status"],
1592 "blob refusal shape changed: {header}"
1593 );
1594 assert_eq!(header["code"], "module_disabled", "{header}");
1595 assert_eq!(header["school"], SCHOOL, "{header}");
1596 assert_eq!(header["id"], "t-mod");
1597 assert!(body.is_empty(), "a refused blob stream carries no bytes");
1598}
1599
1600#[tokio::test]
1601async fn an_api_read_still_answers_on_the_shared_client_stream_path() {
1602 // The discriminator guard. Both request shapes now arrive on the same
1603 // client-initiated streams and are told apart by their required field —
1604 // `path` for an api read, `file` for a blob. An api read must keep
1605 // answering exactly as it did before the blob shape existed, and a frame
1606 // that is neither must still be the api read's `malformed` refusal rather
1607 // than a silent hang.
1608 let bridge = bridge().await;
1609 let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await;
1610 await_workers(&bridge, 1).await;
1611 let (_app, student, file, _uploaded, _tenants) = armed_with_file(&bridge).await;
1612
1613 let (answer, _) = raw::api_read(
1614 &service.conn,
1615 format!(
1616 r#"{{"id":"t-api","school":"{SCHOOL}","path":"/auth/me","on_behalf_of":"{student}"}}"#
1617 )
1618 .as_bytes(),
1619 )
1620 .await;
1621 assert_eq!(answer["outcome"], "ok", "{answer}");
1622 assert_eq!(answer["status"], 200);
1623 assert_eq!(answer["body"]["id"], student, "{answer}");
1624
1625 // `path` wins over `file`: a frame carrying both is the api read it has
1626 // always been, so nothing that parsed before is re-routed now.
1627 let (answer, _) = raw::api_read(
1628 &service.conn,
1629 format!(
1630 r#"{{"id":"t-both","school":"{SCHOOL}","path":"/auth/me","file":"{file}","on_behalf_of":"{student}"}}"#
1631 )
1632 .as_bytes(),
1633 )
1634 .await;
1635 assert_eq!(answer["outcome"], "ok", "{answer}");
1636 assert_eq!(answer["status"], 200);
1637
1638 // Neither shape: still the api read's refusal, with its `outcome` tag.
1639 let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither","school":"019732e3-7b00-7000-8000-00000000dead"}"#).await;
1640 assert_eq!(answer["outcome"], "err", "{answer}");
1641 assert_eq!(answer["code"], "malformed");
1642 assert_eq!(answer["id"], "t-neither");
1643}
1644
1645// ---------------------------------------------------- capability calls --
1646//
1647// The third client-initiated shape: a service calling an operation the
1648// *backend* serves (ZEKA's storage surface — no AI service holds a school
1649// database credential here). Nothing about the two shapes that existed before
1650// may move: an api read is still routed on `path`, a blob read on `file`, and
1651// a service that never calls a capability never receives one — the new frame
1652// only ever appears on a stream the service itself opened, so a client that
1653// does not speak it cannot be surprised by it. These tests pin the shape the
1654// way a foreign service reads it: bytes in, untyped JSON out.
1655
1656#[tokio::test]
1657async fn a_capability_call_carries_exactly_the_published_keys() {
1658 let bridge = bridge().await;
1659 let service = raw::handshake(&bridge, &raw::hello("zeka", "insight.refresh")).await;
1660 await_workers(&bridge, 1).await;
1661 // The storage surface runs against a real school database, so the bridge
1662 // needs the api handle armed (`app_with_ai`) and a student that exists.
1663 let (app, db) = common::app_with_ai(Some(bridge.clone())).await;
1664 let _ = db;
1665 let ayse = common::login(&app, "ayse").await;
1666 let student = common::me_id(&app, &ayse).await;
1667
1668 let body = format!(
1669 r#"{{"id":"t-cap","school":"{SCHOOL}","capability":"insight.summary.upsert","payload":{{"rows":[{{"student":"{student}","marks":{{"ortalama":72}},"confidence":"stable","computed_at":1700000000000,"retain_until":1800000000000}}]}}}}"#
1670 );
1671 let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await;
1672
1673 assert_eq!(
1674 raw::keys(&answer),
1675 ["id", "payload", "school", "status"],
1676 "capability answer shape changed: {answer}"
1677 );
1678 assert_eq!(answer["status"], "ok", "{answer}");
1679 assert_eq!(answer["id"], "t-cap");
1680 assert_eq!(
1681 answer["school"], SCHOOL,
1682 "the answer echoes the school the call named"
1683 );
1684 assert_eq!(answer["payload"]["written"], 1, "{answer}");
1685}
1686
1687#[tokio::test]
1688async fn a_capability_refusal_is_flat_and_never_reports_ok() {
1689 // A service branches on `status` first and on `code` second; both are
1690 // pinned literals, and a refusal carries no payload — there is no
1691 // half-answer to read.
1692 let bridge = bridge().await;
1693 let service = raw::handshake(&bridge, &raw::hello("zeka", "insight.refresh")).await;
1694 await_workers(&bridge, 1).await;
1695 let (_app, _db) = common::app_with_ai(Some(bridge.clone())).await;
1696
1697 let body = format!(
1698 r#"{{"id":"t-nope","school":"{SCHOOL}","capability":"insight.database.query","payload":{{"sql":"select 1"}}}}"#
1699 );
1700 let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await;
1701 assert_eq!(
1702 raw::keys(&answer),
1703 ["code", "id", "message", "school", "status"],
1704 "capability refusal shape changed: {answer}"
1705 );
1706 assert_eq!(answer["status"], "err", "{answer}");
1707 assert_eq!(answer["code"], "unknown_capability", "{answer}");
1708 assert_eq!(answer["id"], "t-nope");
1709 assert_eq!(answer["school"], SCHOOL);
1710 assert!(
1711 answer["message"].as_str().is_some_and(|m| !m.is_empty()),
1712 "message must be a string a service can log"
1713 );
1714}
1715
1716#[tokio::test]
1717async fn the_capability_shape_does_not_steal_the_shapes_that_existed_before() {
1718 // Precedence, pinned: `path` wins over `file` wins over `capability`, so
1719 // every frame that parsed as one of the older shapes still parses as it
1720 // did — the capability branch is only reached when neither is present.
1721 let bridge = bridge().await;
1722 let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await;
1723 await_workers(&bridge, 1).await;
1724 let (app, _db) = common::app_with_ai(Some(bridge.clone())).await;
1725 let ayse = common::login(&app, "ayse").await;
1726 let student = common::me_id(&app, &ayse).await;
1727
1728 // A frame carrying both: still the api read it has always been.
1729 let body = format!(
1730 r#"{{"id":"t-both","school":"{SCHOOL}","path":"/auth/me","capability":"insight.pending.list","payload":{{}},"on_behalf_of":"{student}"}}"#
1731 );
1732 let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await;
1733 assert_eq!(answer["outcome"], "ok", "{answer}");
1734 assert_eq!(answer["status"], 200, "{answer}");
1735
1736 // A capability-only frame: the capability call, and a read the service
1737 // asked for comes back in its own envelope.
1738 let body = format!(
1739 r#"{{"id":"t-pending","school":"{SCHOOL}","capability":"insight.pending.list","payload":{{}}}}"#
1740 );
1741 let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await;
1742 assert_eq!(answer["status"], "ok", "{answer}");
1743 assert_eq!(answer["payload"]["students"], json!([]), "{answer}");
1744
1745 // Neither: the same api-read refusal as before this shape existed.
1746 let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither","school":"019732e3-7b00-7000-8000-00000000dead"}"#).await;
1747 assert_eq!(answer["outcome"], "err", "{answer}");
1748 assert_eq!(answer["code"], "malformed");
1749}