forge
Explore
Log in

Don't you dare go Hollow

AI bridge speaks hab/2

Browse files at this commit

cedd07fa18e2519a65e4aff4264a54a6b7fdd8b3Ahmet Kaan GümüşParent: b7dfc0c
  • feat
    • AI bridge speaks hab/2
    • every frame names its school
Show full message
✨ feat: AI bridge speaks hab/2; every frame names its school

The shared AI fleet now serves every school: `Request`, `ApiRequest` and
`BlobRequest` carry `school`, responses echo it, api-reads and blob opens
resolve that school's database and files, and rag answers land in the same
school. New refusals `unknown_school` / `school_suspended`; hab/1 is rejected
at ALPN and at `Hello`.
README.mdmodified+78 -33
@@ -3503,18 +3503,19 @@ of the API is unaffected.
35033503
35043504 ### Handshake
35053505
3506-The service connects with ALPN `hab/1`, then opens the **control stream** (the
3506+The service connects with ALPN `hab/2`, then opens the **control stream** (the
35073507 first client-initiated bidi stream) and writes one `Hello`:
35083508
35093509 ```json
3510-{ "protocol": "hab/1", "service": "ocr", "capabilities": ["ocr.extract"],
3510+{ "protocol": "hab/2", "service": "ocr", "capabilities": ["ocr.extract"],
35113511 "token": "<AI_SHARED_TOKEN>", "max_concurrent": 8 }
35123512 ```
35133513
3514-The backend answers one `Greeting` and leaves the stream open:
3514+`Hello` names **no school** — see "School scoping" below. The backend answers
3515+one `Greeting` and leaves the stream open:
35153516
35163517 ```json
3517-{ "type": "welcome", "worker_id": "01J...", "protocol": "hab/1" }
3518+{ "type": "welcome", "worker_id": "01J...", "protocol": "hab/2" }
35183519 { "type": "rejected", "code": "unauthorized", "message": "invalid token" }
35193520 ```
35203521
@@ -3529,23 +3530,52 @@ timeout (30s, with a 10s keepalive) and deregistered then.
35293530 `max_concurrent` is advisory and clamped to `1..=64` (default 8). Requests
35303531 beyond it are refused with "busy" rather than queued.
35313532
3533+### School scoping
3534+
3535+This deployment serves many schools, one database each, and the AI fleet is
3536+**shared** across all of them: one connected service answers for every school.
3537+So the school cannot be bound at handshake time — a service pinned to one
3538+school would have to be run once per customer — and every *frame* names it
3539+instead.
3540+
3541+`school` is the school's slug, exactly as it appears in a login (`demo`), and
3542+it is **required** on `Request`, `ApiRequest` and `BlobRequest`. Every answer
3543+echoes it, refusals included, so a service can tell which of its in-flight
3544+streams a refusal belongs to. There is no default and no fallback: a frame
3545+naming no school is `malformed`.
3546+
3547+| `code` | Meaning |
3548+| ------ | ------- |
3549+| `malformed` | `school` is absent, or is not a slug at all |
3550+| `unknown_school` | A well-formed slug this deployment does not serve — not retryable without a config change |
3551+| `school_suspended` | The school exists and is switched off; worth retrying later |
3552+
3553+A read is answered out of that school's own database, `on_behalf_of` is
3554+resolved there too (so the same username in two schools is two different
3555+people, and one school's user id names nobody in another), and blob bytes come
3556+from that school's own directory. That is the whole point of `hab/2`: the
3557+previous wire version carried no school, and a service still announcing it is
3558+refused at the ALPN, before it can send a frame.
3559+
35323560 ### Requests
35333561
35343562 For each request the **backend** opens a bidi stream, writes one `Request`,
35353563 finishes its send side, and reads one `Response`:
35363564
35373565 ```json
3538-{ "id": "01J...", "capability": "ocr.extract", "deadline_ms": 30000,
3539- "payload": { "image": "<base64>" } }
3566+{ "id": "01J...", "school": "demo", "capability": "ocr.extract",
3567+ "deadline_ms": 30000, "payload": { "image": "<base64>" } }
35403568 ```
35413569
35423570 ```json
3543-{ "status": "ok", "id": "01J...", "payload": { "text": "..." } }
3544-{ "status": "err", "id": "01J...", "code": "unsupported_image",
3545- "message": "only png and jpeg" }
3571+{ "status": "ok", "id": "01J...", "school": "demo",
3572+ "payload": { "text": "..." } }
3573+{ "status": "err", "id": "01J...", "school": "demo",
3574+ "code": "unsupported_image", "message": "only png and jpeg" }
35463575 ```
35473576
3548-`id` is a trace id for logs on both sides — correlation is the stream, not the
3577+`school` is the school the work belongs to, echoed back like `id`. `id` is a
3578+trace id for logs on both sides — correlation is the stream, not the
35493579 id. It must still be echoed: an answer carrying a different id means the
35503580 service lost track of whose work it is, and the payload is refused. `payload`
35513581 is opaque to the transport; its shape belongs to the capability.
@@ -3563,15 +3593,17 @@ already has.
35633593
35643594 After the handshake the *service* may open further bidi streams, one per read:
35653595 write one `ApiRequest`, finish the send side, read one `ApiResponse`, done.
3566-Same framing as every other `hab/1` frame; concurrency and correlation are the
3596+Same framing as every other `hab/2` frame; concurrency and correlation are the
35673597 stream, exactly as for capability requests.
35683598
35693599 ```json
3570-{ "id": "01J...", "path": "/marks/me", "query": "limit=10&offset=0",
3571- "on_behalf_of": "user:01J...", "method": "GET" }
3600+{ "id": "01J...", "school": "demo", "path": "/marks/me",
3601+ "query": "limit=10&offset=0", "on_behalf_of": "user:01J...",
3602+ "method": "GET" }
35723603 ```
35733604
3574-`id` is a trace id, echoed back. `path` is the path alone as the REST API
3605+`id` is a trace id, echoed back, and so is `school` — which names the database
3606+the read is answered from and is required. `path` is the path alone as the REST API
35753607 spells it — no host, and **no query string**, which travels in `query` (without
35763608 the leading `?`). `query`, `on_behalf_of` and `method` are all optional; an
35773609 absent `method` means `GET`, and anything else is refused.
@@ -3579,8 +3611,10 @@ absent `method` means `GET`, and anything else is refused.
35793611 The answer is tagged by `outcome`:
35803612
35813613 ```json
3582-{ "outcome": "ok", "id": "01J...", "status": 200, "body": { } }
3583-{ "outcome": "err", "id": "01J...", "code": "path_not_allowed",
3614+{ "outcome": "ok", "id": "01J...", "school": "demo", "status": 200,
3615+ "body": { } }
3616+{ "outcome": "err", "id": "01J...", "school": "demo",
3617+ "code": "path_not_allowed",
35843618 "message": "`/users` is not a path AI services may read" }
35853619 ```
35863620
@@ -3592,16 +3626,19 @@ failure has misread the contract.
35923626
35933627 | `code` | Meaning |
35943628 | ------ | ------- |
3595-| `malformed` | The frame was not a readable `ApiRequest`, or `path`+`query` do not form a request target |
3629+| `malformed` | The frame was not a readable `ApiRequest` (a missing `school` lands here), `school` is not a slug, or `path`+`query` do not form a request target |
35963630 | `method_not_allowed` | `method` was present and was not `GET` |
35973631 | `path_not_allowed` | `path` is not in the read scope below |
3598-| `unknown_user` | `on_behalf_of` names no user (deleted since the service last saw them) |
3632+| `unknown_school` | `school` is a slug this deployment does not serve |
3633+| `school_suspended` | That school is suspended — retryable once it is not |
3634+| `unknown_user` | `on_behalf_of` names no user *of that school* (deleted since the service last saw them, or an id belonging to a different school) |
35993635 | `unavailable` | The API is not serving yet, the database socket is down, or the read outran the request timeout — retryable |
36003636 | `not_json` | The endpoint answered with a body that is not JSON |
36013637 | `too_large` | The answer does not fit one frame |
36023638
36033639 Refusals are decided in that order — method, then the allowlist, then the
3604-principal — so an unknown user on a forbidden path reports the path.
3640+school, then the principal — so an unknown user on a forbidden path reports the
3641+path, and an unknown user in an unknown school reports the school.
36053642
36063643 #### The read scope
36073644
@@ -3637,7 +3674,8 @@ With `on_behalf_of`, the read executes **as that user**: own-scoped endpoints
36373674 (`/auth/me`, `/notes`, `/marks/me`) return *their* data. Both spellings are
36383675 accepted — the bare key (`01J...`, as a REST path writes it) and the record
36393676 form (`user:01J...`). The account is loaded live from the database on every
3640-request and never trusted from the frame, so a service holding a stale id acts
3677+request — from the named school's database, never the control one — and never
3678+trusted from the frame, so a service holding a stale id acts
36413679 as a user who has since been deleted (`unknown_user`) or demoted (the new role,
36423680 not the old one) — never as who they used to be.
36433681
@@ -3663,11 +3701,13 @@ the shape differs, and the two are told apart by the field each *requires*: an
36633701 `ApiRequest` has `path`, a `BlobRequest` has `file`.
36643702
36653703 ```json
3666-{ "id": "01J...", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V",
3704+{ "id": "01J...", "school": "demo", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V",
36673705 "on_behalf_of": "user:01J..." }
36683706 ```
36693707
3670-`file` is a `course_note_file` record key — the id `GET
3708+`school` names the school the file belongs to; the bytes are read from that
3709+school's own blob directory, so a file id is meaningless outside it. `file` is
3710+a `course_note_file` record key — the id `GET
36713711 /course-notes/{id}/files` publishes and the one every `rag.index` payload
36723712 carries in `files[].id`. `on_behalf_of` is optional on the wire but required in
36733713 practice: without it the principal is the `ai` role, which is enrolled in
@@ -3679,9 +3719,9 @@ tag `Response` uses, not the api read's `outcome`, since a blob header carries
36793719 no HTTP status to collide with:
36803720
36813721 ```json
3682-{ "status": "ok", "id": "01J...", "name": "recap.pdf",
3722+{ "status": "ok", "id": "01J...", "school": "demo", "name": "recap.pdf",
36833723 "content_type": "application/pdf", "size": 204800 }
3684-{ "status": "err", "id": "01J...", "code": "forbidden",
3724+{ "status": "err", "id": "01J...", "school": "demo", "code": "forbidden",
36853725 "message": "`01J...` may not view the course this file belongs to" }
36863726 ```
36873727
@@ -3699,9 +3739,11 @@ slow-but-reading service is never cut off.
36993739
37003740 | `code` | Meaning |
37013741 | ------ | ------- |
3702-| `not_found` | No `course_note_file` with that key, or its note or course is gone |
3742+| `malformed` | The frame was not a readable `BlobRequest`, or `school` is absent or not a slug |
3743+| `not_found` | No `course_note_file` with that key *in that school*, or its note or course is gone |
37033744 | `forbidden` | The principal may not view that file's course |
3704-| `unknown_user` | `on_behalf_of` names no user |
3745+| `unknown_school` / `school_suspended` | As for an api read |
3746+| `unknown_user` | `on_behalf_of` names no user of that school |
37053747 | `unavailable` | The api is not serving yet, the database socket is down, or the row's blob is missing from disk — retryable |
37063748
37073749 **Course-note attachments only.** The key is looked up in `course_note_file`
@@ -3738,11 +3780,12 @@ not retryable), `Protocol` / `IdMismatch` (broken peer), `Transport`.
37383780 ### Conformance suite
37393781
37403782 `tests/ai_protocol.rs` is the wire contract, enforced on every `cargo test`. It
3741-speaks `hab/1` with a client that imports none of the crate's protocol types —
3783+speaks `hab/2` with a client that imports none of the crate's protocol types —
37423784 frames built as byte literals, answers parsed as untyped JSON — so it fails on
37433785 exactly the changes a service in another language would notice: a renamed
37443786 field, a re-tagged enum, a flipped length-prefix endianness, a newly-required
3745-`Hello` field. (`tests/ai_bridge.rs` drives real QUIC clients too, but shares
3787+`Hello` field, a frame that stopped naming its school. (`tests/ai_bridge.rs`
3788+drives real QUIC clients too, but shares
37463789 the Rust structs with the backend, so it cannot see those.)
37473790
37483791 It is also the reference implementation: its `raw` module is the whole client
@@ -3773,7 +3816,7 @@ published over HTTP:
37733816
37743817 ```
37753818 GET /ai/certificate # no auth; 404 when the bridge is disabled
3776-{ "protocol": "hab/1",
3819+{ "protocol": "hab/2",
37773820 "certificate_pem": "-----BEGIN CERTIFICATE-----\n...",
37783821 "fingerprint_sha256": "6745e8..." }
37793822 ```
@@ -3846,7 +3889,7 @@ closes. A stream opened *after* the answer already landed still emits
38463889 `delta`s and a `done` — the replay is deliberate, so a client that connects
38473890 late (or reconnects) never hangs waiting for events that already happened.
38483891
3849-**The deltas are sliced by the backend from the finished answer.** `hab/1` is
3892+**The deltas are sliced by the backend from the finished answer.** `hab/2` is
38503893 unary — the service returns the whole reply text, not tokens — so today the
38513894 chunking is cosmetic pacing, not real streaming. The event shape exists now so
38523895 that the day a service streams, it becomes a drop-in change behind an
@@ -3922,7 +3965,8 @@ fall back to the human-readable text for the rest.
39223965 ### The `chat.reply` capability (for AI-service authors)
39233966
39243967 A chat service declares `chat.reply` in its `Hello` (see "AI bridge (QUIC)").
3925-Requests then arrive as ordinary `hab/1` `Request` frames whose `payload` is:
3968+Requests then arrive as ordinary `hab/2` `Request` frames — the asker's school
3969+is on the frame, not in the payload — whose `payload` is:
39263970
39273971 ```json
39283972 { "message": "and the second law?",
@@ -3969,7 +4013,8 @@ context without either end having to be redeployed in lockstep.
39694013 An indexing service declares `rag.index` in its `Hello` (see "AI bridge
39704014 (QUIC)"). The backend dispatches one request whenever a course note is
39714015 created, edited, or gains or loses a file — never on a read. Requests arrive
3972-as ordinary `hab/1` `Request` frames whose `payload` is:
4016+as ordinary `hab/2` `Request` frames — the note's school is on the frame, not
4017+in the payload — whose `payload` is:
39734018
39744019 ```json
39754020 { "course_note": "01J8XZ0K3Q8G7X2M4N5P6R7S8T",
@@ -4560,5 +4605,5 @@ db), rate-limit (both tiers, proxy-header and peer-address keying, shipped
45604605 limits over every route, two limiters sharing one budget over one db), e2e
45614606 (real TCP + reqwest cookie jar), persistence
45624607 (tempfile file engine, including close + reopen), ai-bridge (real QUIC on
4563-loopback against a fake AI service), ai-protocol (the `hab/1` wire contract,
4608+loopback against a fake AI service), ai-protocol (the `hab/2` wire contract,
45644609 driven by a client that shares no code with the backend).
src/ai/protocol.rsmodified+71 -6
@@ -1,4 +1,4 @@
1-//! Wire format for the AI bridge ("hab/1" — hezarfen ai bridge).
1+//! Wire format for the AI bridge ("hab/2" — hezarfen ai bridge).
22 //!
33 //! # Shape
44 //!
@@ -33,6 +33,19 @@
3333 //! The two client-initiated request shapes are told apart by their required
3434 //! field: an [`ApiRequest`] has `path`, a [`BlobRequest`] has `file`.
3535 //!
36+//! # School scoping
37+//!
38+//! Every request frame names its school by slug, and every answer echoes it:
39+//! [`Request::school`], [`ApiRequest::school`], [`BlobRequest::school`] and
40+//! their responses. The AI fleet is *shared* across the deployment — one
41+//! service serves every school — so the school cannot be bound once at
42+//! handshake time and [`Hello`] deliberately carries none: a service pinned to
43+//! one school would have to be run once per customer. A frame without a
44+//! `school` is `malformed`, an unknown slug is `unknown_school`, a suspended
45+//! one `school_suspended`; there is no default and no fallback, because a read
46+//! answered out of the wrong school's database is the one failure this field
47+//! exists to make impossible.
48+//!
3649 //! There is deliberately no correlation-id matching: QUIC stream IDs already
3750 //! multiplex concurrent requests over the one connection, independently
3851 //! flow-controlled, with no head-of-line blocking between them. [`Request::id`]
@@ -65,6 +78,10 @@ pub enum FrameError {
6578 }
6679
6780 /// The service's opening frame on the control stream.
81+///
82+/// Carries **no** school on purpose: the fleet is shared, so one connection
83+/// serves every school on the deployment and each frame names its own (see
84+/// this module's "School scoping").
6885 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
6986 pub struct Hello {
7087 /// Must equal [`crate::constant::AI_PROTOCOL`]; anything else is rejected
@@ -118,6 +135,9 @@ pub enum RejectCode {
118135 pub struct Request {
119136 /// Trace id (ULID). Not used for correlation — the stream does that.
120137 pub id: String,
138+ /// Slug of the school this work belongs to. Required — see this module's
139+ /// "School scoping".
140+ pub school: String,
121141 /// Which capability from the worker's [`Hello::capabilities`] to invoke.
122142 pub capability: String,
123143 /// How long the backend will wait before abandoning the stream. The
@@ -135,10 +155,14 @@ pub struct Request {
135155 pub enum Response {
136156 Ok {
137157 id: String,
158+ /// Echo of [`Request::school`].
159+ school: String,
138160 payload: Value,
139161 },
140162 Err {
141163 id: String,
164+ /// Echo of [`Request::school`].
165+ school: String,
142166 /// Service-defined, stable, machine-readable (`"unsupported_image"`).
143167 code: String,
144168 message: String,
@@ -151,6 +175,9 @@ pub enum Response {
151175 pub struct ApiRequest {
152176 /// Trace id (ULID). Not used for correlation — the stream does that.
153177 pub id: String,
178+ /// Slug of the school to read. Required — see this module's "School
179+ /// scoping"; the answer comes out of that school's own database.
180+ pub school: String,
154181 /// Path as the REST API spells it, e.g. `"/users/me"`. No host, no query.
155182 pub path: String,
156183 /// Query string without the leading `?`, e.g. `"limit=10&offset=0"`.
@@ -174,13 +201,20 @@ pub struct ApiRequest {
174201 pub enum ApiResponse {
175202 Ok {
176203 id: String,
204+ /// Echo of [`ApiRequest::school`].
205+ school: String,
177206 /// HTTP status the router produced.
178207 status: u16,
179208 body: Value,
180209 },
181210 Err {
182211 id: String,
183- /// Bridge-defined, stable, machine-readable (`"path_not_allowed"`).
212+ /// Echo of the school the frame named — as sent, even when it named no
213+ /// school a slug could be made of, so a service can tell which of its
214+ /// in-flight reads was refused.
215+ school: String,
216+ /// Bridge-defined, stable, machine-readable (`"path_not_allowed"`,
217+ /// `"unknown_school"`, `"school_suspended"`).
184218 code: String,
185219 message: String,
186220 },
@@ -193,6 +227,9 @@ pub enum ApiResponse {
193227 pub struct BlobRequest {
194228 /// Trace id (ULID). Not used for correlation — the stream does that.
195229 pub id: String,
230+ /// Slug of the school the file belongs to. Required — see this module's
231+ /// "School scoping"; the bytes come out of that school's blob directory.
232+ pub school: String,
196233 /// The `course_note_file` record key, as `GET /course-notes/{id}/files`
197234 /// and the `rag.index` payload both publish it.
198235 pub file: String,
@@ -210,6 +247,8 @@ pub struct BlobRequest {
210247 pub enum BlobResponse {
211248 Ok {
212249 id: String,
250+ /// Echo of [`BlobRequest::school`].
251+ school: String,
213252 name: String,
214253 content_type: String,
215254 /// Exactly how many raw bytes follow this frame.
@@ -217,6 +256,8 @@ pub enum BlobResponse {
217256 },
218257 Err {
219258 id: String,
259+ /// Echo of the school the frame named, as sent.
260+ school: String,
220261 /// Bridge-defined, stable, machine-readable (`"not_found"`).
221262 code: String,
222263 message: String,
@@ -313,10 +354,12 @@ mod tests {
313354 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
314355 let a = Response::Ok {
315356 id: "a".into(),
357+ school: "demo".into(),
316358 payload: json!({ "n": 1 }),
317359 };
318360 let b = Response::Err {
319361 id: "b".into(),
362+ school: "demo".into(),
320363 code: "bad_input".into(),
321364 message: "nope".into(),
322365 };
@@ -394,6 +437,7 @@ mod tests {
394437 assert_eq!(rejected["code"], "unauthorized");
395438 let ok = serde_json::to_value(Response::Ok {
396439 id: "1".into(),
440+ school: "demo".into(),
397441 payload: json!(null),
398442 })
399443 .unwrap();
@@ -406,6 +450,7 @@ mod tests {
406450 // The tag is `outcome`, not `status` — `status` is the HTTP code.
407451 let ok = serde_json::to_value(ApiResponse::Ok {
408452 id: "1".into(),
453+ school: "demo".into(),
409454 status: 404,
410455 body: json!(null),
411456 })
@@ -414,6 +459,7 @@ mod tests {
414459 assert_eq!(ok["status"], 404);
415460 let err = serde_json::to_value(ApiResponse::Err {
416461 id: "1".into(),
462+ school: "demo".into(),
417463 code: "path_not_allowed".into(),
418464 message: "nope".into(),
419465 })
@@ -423,18 +469,26 @@ mod tests {
423469 }
424470
425471 #[tokio::test]
426- async fn an_api_request_needs_only_an_id_and_a_path() {
472+ async fn an_api_request_needs_only_an_id_a_school_and_a_path() {
427473 let bare: ApiRequest = serde_json::from_value(json!({
428474 "id": "01J",
475+ "school": "demo",
429476 "path": "/users/me",
430477 }))
431478 .unwrap();
432479 assert_eq!(bare.query, None);
433480 assert_eq!(bare.on_behalf_of, None);
434481 assert_eq!(bare.method, None);
482+ // The school is required, not defaulted: a frame that names none has
483+ // no school to fall back on and must not parse.
484+ assert!(
485+ serde_json::from_value::<ApiRequest>(json!({ "id": "01J", "path": "/users/me" }))
486+ .is_err()
487+ );
435488
436489 let full = ApiRequest {
437490 id: "01J".into(),
491+ school: "demo".into(),
438492 path: "/notes".into(),
439493 query: Some("limit=10".into()),
440494 on_behalf_of: Some("user:abc".into()),
@@ -442,6 +496,7 @@ mod tests {
442496 method: Some("GET".into()),
443497 };
444498 let raw = serde_json::to_value(&full).unwrap();
499+ assert_eq!(raw["school"], "demo");
445500 assert_eq!(raw["path"], "/notes");
446501 assert_eq!(raw["query"], "limit=10");
447502 assert_eq!(raw["on_behalf_of"], "user:abc");
@@ -456,6 +511,7 @@ mod tests {
456511 // carries no HTTP status for it to collide with.
457512 let ok = serde_json::to_value(BlobResponse::Ok {
458513 id: "1".into(),
514+ school: "demo".into(),
459515 name: "recap.pdf".into(),
460516 content_type: "application/pdf".into(),
461517 size: 204_800,
@@ -465,6 +521,7 @@ mod tests {
465521 assert_eq!(ok["size"], 204_800);
466522 let err = serde_json::to_value(BlobResponse::Err {
467523 id: "1".into(),
524+ school: "demo".into(),
468525 code: "not_found".into(),
469526 message: "nope".into(),
470527 })
@@ -475,14 +532,22 @@ mod tests {
475532 // `file` is what tells a blob request apart from an api read, so it is
476533 // required; `on_behalf_of` is the only optional field.
477534 let bare: BlobRequest = serde_json::from_value(json!({
478- "id": "01J", "file": "01FILE",
535+ "id": "01J", "school": "demo", "file": "01FILE",
479536 }))
480537 .unwrap();
481538 assert_eq!(bare.on_behalf_of, None);
482- assert!(serde_json::from_value::<BlobRequest>(json!({ "id": "01J" })).is_err());
539+ assert!(serde_json::from_value::<BlobRequest>(json!({ "id": "01J", "school": "demo" }))
540+ .is_err());
541+ // The school is required here too.
542+ assert!(
543+ serde_json::from_value::<BlobRequest>(json!({ "id": "01J", "file": "01FILE" })).is_err()
544+ );
483545 // And the two shapes never parse as each other.
484546 assert!(
485- serde_json::from_value::<ApiRequest>(json!({ "id": "01J", "file": "01FILE" })).is_err()
547+ serde_json::from_value::<ApiRequest>(json!({
548+ "id": "01J", "school": "demo", "file": "01FILE",
549+ }))
550+ .is_err()
486551 );
487552 }
488553
src/ai/rag.rsmodified+10 -3
@@ -20,6 +20,7 @@ use crate::domain::course_note::CourseNote;
2020 use crate::domain::course_note_file::CourseNoteFile;
2121 use crate::domain::rag_output::RagOutput;
2222 use crate::state::AppState;
23+use crate::tenant::Slug;
2324
2425 /// The capability string routed to an indexing service. Defined once, in
2526 /// [`crate::constant`]; re-exported here so a reader of the payload contract
@@ -80,7 +81,11 @@ impl RagIndexPayload {
8081 /// Re-index `note` and replace its stored outputs with what the service
8182 /// answered. Silent no-op when the bridge is off or no worker offers
8283 /// `rag.index`.
83-pub async fn index_course_note(state: &AppState, note: &CourseNote) {
84+///
85+/// `school` is the caller's own school: it rides the `hab/2` frame, and
86+/// `state.db` — the same school's database, since the caller reached this
87+/// through the shadow `State` — is where the answer is stored.
88+pub async fn index_course_note(state: &AppState, school: &Slug, note: &CourseNote) {
8489 let Some(bridge) = state.ai.as_ref() else {
8590 return;
8691 };
@@ -107,6 +112,7 @@ pub async fn index_course_note(state: &AppState, note: &CourseNote) {
107112
108113 let answer = match bridge
109114 .dispatch_with_timeout(
115+ school,
110116 AI_RAG_INDEX_CAPABILITY,
111117 payload,
112118 std::time::Duration::from_secs(AI_RAG_INDEX_TIMEOUT_SECS),
@@ -151,10 +157,11 @@ async fn replace(
151157
152158 /// [`index_course_note`] off the request path: the handler has already
153159 /// answered by the time the service is asked.
154-pub fn spawn_index(state: &AppState, note: CourseNote) {
160+pub fn spawn_index(state: &AppState, school: &Slug, note: CourseNote) {
155161 // Cheap when AI is off — the spawned task returns on the first `let else`.
156162 let state = state.clone();
157- tokio::spawn(async move { index_course_note(&state, &note).await });
163+ let school = school.clone();
164+ tokio::spawn(async move { index_course_note(&state, &school, &note).await });
158165 }
159166
160167 #[cfg(test)]
src/ai/server.rsmodified+95 -56
@@ -24,6 +24,7 @@ use crate::constant::{
2424 REQUEST_TIMEOUT_SECS,
2525 };
2626 use crate::database::Database;
27+use crate::error::AppError;
2728 use crate::domain::course::Course;
2829 use crate::domain::course_note::CourseNote;
2930 use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId};
@@ -50,40 +51,52 @@ pub struct BridgeConfig {
5051 }
5152
5253 /// What an api read needs to be answered: the router to dispatch into, the
53-/// school the acting principal is loaded from, and the liveness flag that
54+/// registry every school is resolved through, and the liveness flag that
5455 /// stands in for the HTTP db guard this path bypasses.
56+///
57+/// Deployment-wide, not per-school: `hab/2` frames name their own school, so
58+/// one bridge (and one AI fleet) serves every school here.
5559 struct ApiHandle {
5660 router: axum::Router,
5761 tenants: Tenants,
58- /// The one school this bridge serves.
59- ///
60- /// corner-cut: `hab/1` frames carry no school, so the reverse api-read path
61- /// is pinned to [`crate::tenant::DEMO_SLUG`] — a deployment whose schools
62- /// are named anything else answers `unavailable` to every service read.
63- /// The upgrade is `hab/2`: put the school on `Hello`/`ApiRequest` and
64- /// resolve it per request. Nothing else about the bridge is single-school —
65- /// the outbound chatbot dispatch never touches a database.
66- slug: Slug,
6762 db_up: DbHealth,
68- /// Where uploaded blobs live — the deployment root; the school's own
63+ /// Where uploaded blobs live — the deployment root; a school's own
6964 /// directory is [`school_files_path`] of it.
7065 files_path: std::path::PathBuf,
7166 }
7267
7368 impl ApiHandle {
74- /// The school database this bridge reads, or the refusal a service gets.
75- async fn db(&self) -> Result<Database, (&'static str, String)> {
76- self.tenants.get(&self.slug).await.map_err(|err| {
77- (
69+ /// Resolve the slug a frame named into that school's database, or the
70+ /// refusal the service gets.
71+ ///
72+ /// The three codes are distinct on purpose: `malformed` is the service's
73+ /// own bug (that string is no slug), `unknown_school` means the deployment
74+ /// has no such customer, and `school_suspended` means it has one that is
75+ /// switched off — a service that retries the first two forever learns
76+ /// nothing, while the third is worth retrying later.
77+ async fn school(&self, school: &str) -> Result<(Slug, Database), (&'static str, String)> {
78+ let slug = Slug::try_new(school)
79+ .map_err(|err| ("malformed", format!("`{school}` is not a school slug: {err}")))?;
80+ let db = self.tenants.get(&slug).await.map_err(|err| match err {
81+ AppError::Unauthorized => (
82+ "unknown_school",
83+ format!("this deployment serves no `{slug}` school"),
84+ ),
85+ AppError::Forbidden(_) => (
86+ "school_suspended",
87+ format!("the `{slug}` school is suspended"),
88+ ),
89+ other => (
7890 "unavailable",
79- format!("the `{}` school is not reachable: {err}", self.slug),
80- )
81- })
91+ format!("the `{slug}` school is not reachable: {other}"),
92+ ),
93+ })?;
94+ Ok((slug, db))
8295 }
8396
84- /// That school's blob directory.
85- fn files_dir(&self) -> std::path::PathBuf {
86- school_files_path(&self.files_path, &self.slug)
97+ /// One school's blob directory.
98+ fn files_dir(&self, slug: &Slug) -> std::path::PathBuf {
99+ school_files_path(&self.files_path, slug)
87100 }
88101 }
89102
@@ -188,8 +201,13 @@ impl AiBridge {
188201 /// Each call takes a fresh QUIC bidirectional stream, so concurrent calls
189202 /// over the same connection neither block nor interleave: the stream *is*
190203 /// the correlation, and a slow one cannot stall a fast one.
191- pub async fn dispatch(&self, capability: &str, payload: Value) -> Result<Value, AiError> {
192- self.dispatch_with_timeout(capability, payload, self.inner.request_timeout)
204+ pub async fn dispatch(
205+ &self,
206+ school: &Slug,
207+ capability: &str,
208+ payload: Value,
209+ ) -> Result<Value, AiError> {
210+ self.dispatch_with_timeout(school, capability, payload, self.inner.request_timeout)
193211 .await
194212 }
195213
@@ -198,6 +216,7 @@ impl AiBridge {
198216 /// generation).
199217 pub async fn dispatch_with_timeout(
200218 &self,
219+ school: &Slug,
201220 capability: &str,
202221 payload: Value,
203222 timeout: Duration,
@@ -210,6 +229,7 @@ impl AiBridge {
210229 let deadline_ms = timeout.as_millis().min(u64::MAX as u128) as u64;
211230 let request = Request {
212231 id: id.clone(),
232+ school: school.as_str().to_string(),
213233 capability: capability.to_string(),
214234 deadline_ms,
215235 payload,
@@ -248,6 +268,7 @@ impl AiBridge {
248268 id: got,
249269 code,
250270 message,
271+ ..
251272 } if got == id => Err(AiError::Remote { code, message }),
252273 // A mismatched id means the service is not tracking which stream it
253274 // is on. Nothing here depends on the id for correlation, but the
@@ -278,7 +299,6 @@ impl AiBridge {
278299 .set(ApiHandle {
279300 router,
280301 tenants,
281- slug: Slug::try_new(crate::tenant::DEMO_SLUG).expect("the demo slug is a slug"),
282302 db_up,
283303 files_path,
284304 })
@@ -369,17 +389,16 @@ async fn serve_client_stream(
369389 Err(e) => {
370390 answer(
371391 &mut send,
372- refusal(String::new(), "malformed", e.to_string()),
392+ refusal(String::new(), String::new(), "malformed", e.to_string()),
373393 )
374394 .await;
375395 return;
376396 }
377397 };
378- let id = raw
379- .get("id")
380- .and_then(Value::as_str)
381- .unwrap_or_default()
382- .to_string();
398+ let id = string_field(&raw, "id");
399+ // Echoed verbatim on a refusal, before it is known to be a slug at all:
400+ // it is how the service tells which of its in-flight reads was refused.
401+ let school = string_field(&raw, "school");
383402 // Routed on the shape's required field rather than by parsing one and
384403 // falling back to the other: that fallback cloned the whole `Value` on
385404 // every api read. `path` still wins when a frame carries both.
@@ -387,9 +406,9 @@ async fn serve_client_stream(
387406 let response = match serde_json::from_value::<ApiRequest>(raw) {
388407 Ok(request) => match read_api(&inner, request).await {
389408 Ok(response) => response,
390- Err((code, message)) => refusal(id, code, message),
409+ Err((code, message)) => refusal(id, school, code, message),
391410 },
392- Err(e) => refusal(id, "malformed", e.to_string()),
411+ Err(e) => refusal(id, school, "malformed", e.to_string()),
393412 };
394413 answer(&mut send, response).await;
395414 return;
@@ -397,7 +416,7 @@ async fn serve_client_stream(
397416 if raw.get("file").is_some() {
398417 match serde_json::from_value::<BlobRequest>(raw) {
399418 Ok(request) => serve_blob(&inner, &mut send, request).await,
400- Err(e) => answer(&mut send, refusal(id, "malformed", e.to_string())).await,
419+ Err(e) => answer(&mut send, refusal(id, school, "malformed", e.to_string())).await,
401420 }
402421 return;
403422 }
@@ -406,7 +425,16 @@ async fn serve_client_stream(
406425 let api_err = serde_json::from_value::<ApiRequest>(raw)
407426 .err()
408427 .map_or_else(String::new, |e| e.to_string());
409- answer(&mut send, refusal(id, "malformed", api_err)).await;
428+ answer(&mut send, refusal(id, school, "malformed", api_err)).await;
429+}
430+
431+/// One string field of a raw frame, or the empty string. Used for the fields a
432+/// refusal echoes back before the frame has been proved to be anything.
433+fn string_field(raw: &Value, name: &str) -> String {
434+ raw.get(name)
435+ .and_then(Value::as_str)
436+ .unwrap_or_default()
437+ .to_string()
410438 }
411439
412440 /// Answer one blob read: the [`BlobResponse`] header frame, then — on `Ok` —
@@ -417,6 +445,7 @@ async fn serve_client_stream(
417445 /// because such a thing does not fit a frame.
418446 async fn serve_blob(inner: &Inner, send: &mut quinn::SendStream, request: BlobRequest) {
419447 let id = request.id.clone();
448+ let school = request.school.clone();
420449 match open_blob(inner, request).await {
421450 Ok((header, mut file)) => {
422451 if let Err(e) = write_frame(send, &header).await {
@@ -433,6 +462,7 @@ async fn serve_blob(inner: &Inner, send: &mut quinn::SendStream, request: BlobRe
433462 Err((code, message)) => {
434463 let refused = BlobResponse::Err {
435464 id,
465+ school,
436466 code: code.to_string(),
437467 message,
438468 };
@@ -497,8 +527,8 @@ async fn open_blob(
497527 "the database socket is down — retry".to_string(),
498528 ));
499529 }
500- let db = api.db().await?;
501- let user = principal(api, request.on_behalf_of.as_deref()).await?;
530+ let (slug, db) = api.school(&request.school).await?;
531+ let user = principal(&db, request.on_behalf_of.as_deref()).await?;
502532
503533 let missing = || {
504534 (
@@ -534,7 +564,7 @@ async fn open_blob(
534564
535565 // The row exists but its blob does not: server-side damage (a lost volume
536566 // path), exactly as `download_file` reads it — not the service's `404`.
537- let path = blob_path(&api.files_dir(), file.get_id().key());
567+ let path = blob_path(&api.files_dir(&slug), file.get_id().key());
538568 let handle = tokio::fs::File::open(&path).await.map_err(|e| {
539569 (
540570 "unavailable",
@@ -555,6 +585,7 @@ async fn open_blob(
555585 Ok((
556586 BlobResponse::Ok {
557587 id: request.id,
588+ school: request.school,
558589 name: file.get_name().as_str().to_string(),
559590 content_type: file.get_content_type().as_str().to_string(),
560591 size,
@@ -565,20 +596,18 @@ async fn open_blob(
565596
566597 /// Who a client-initiated read runs as.
567598 ///
568-/// Loaded live, never trusted from the frame: a service holding a stale id must
569-/// not act as a user who has since been deleted or demoted. With nobody named
570-/// the principal is the synthetic `ai` role.
571-async fn principal(
572- api: &ApiHandle,
573- on_behalf_of: Option<&str>,
574-) -> Result<User, (&'static str, String)> {
599+/// Loaded live out of the *school's own* database — never the control one and
600+/// never trusted from the frame: a service holding a stale id must not act as a
601+/// user who has since been deleted or demoted, nor as a same-named user of
602+/// another school. With nobody named the principal is the synthetic `ai` role.
603+async fn principal(db: &Database, on_behalf_of: Option<&str>) -> Result<User, (&'static str, String)> {
575604 let Some(who) = on_behalf_of else {
576605 return Ok(User::ai_principal());
577606 };
578607 // Both the bare key (`abc`, as a REST path spells it) and the record form
579608 // (`user:abc`) are accepted.
580609 let key = who.strip_prefix("user:").unwrap_or(who);
581- User::read(&UserId::from_key(key), &api.db().await?)
610+ User::read(&UserId::from_key(key), db)
582611 .await
583612 .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))?
584613 .ok_or_else(|| ("unknown_user", format!("no user `{who}`")))
@@ -639,6 +668,7 @@ async fn dispatch_api(
639668 ) -> Result<ApiResponse, (&'static str, String)> {
640669 let ApiRequest {
641670 id,
671+ school,
642672 path,
643673 query,
644674 on_behalf_of,
@@ -655,10 +685,13 @@ async fn dispatch_api(
655685 ));
656686 }
657687
688+ // The school comes off the frame, so this is where a service naming a
689+ // stranger's slug (or a suspended school's) is stopped — before a row of
690+ // anyone's data is read.
691+ let (slug, db) = api.school(&school).await?;
658692 // The role itself is re-read again by the extractor on the dispatched
659693 // request; see [`principal`] for why it is never taken from the frame.
660- let db = api.db().await?;
661- let user = principal(api, on_behalf_of.as_deref()).await?;
694+ let user = principal(&db, on_behalf_of.as_deref()).await?;
662695
663696 let target = match query.as_deref() {
664697 Some(query) if !query.is_empty() => format!("{path}?{query}"),
@@ -679,10 +712,7 @@ async fn dispatch_api(
679712 dispatched.extensions_mut().insert(AiPrincipal(user));
680713 // The dispatched request carries no cookie, so the school is handed over
681714 // in the extension the shadow `State` reads first.
682- dispatched.extensions_mut().insert(TenantExt {
683- slug: api.slug.clone(),
684- db,
685- });
715+ dispatched.extensions_mut().insert(TenantExt { slug, db });
686716
687717 let response = tokio::time::timeout(
688718 Duration::from_secs(REQUEST_TIMEOUT_SECS),
@@ -718,12 +748,18 @@ async fn dispatch_api(
718748 })?
719749 };
720750
721- Ok(ApiResponse::Ok { id, status, body })
751+ Ok(ApiResponse::Ok {
752+ id,
753+ school,
754+ status,
755+ body,
756+ })
722757 }
723758
724-fn refusal(id: String, code: &str, message: String) -> ApiResponse {
759+fn refusal(id: String, school: String, code: &str, message: String) -> ApiResponse {
725760 ApiResponse::Err {
726761 id,
762+ school,
727763 code: code.to_string(),
728764 message,
729765 }
@@ -750,11 +786,13 @@ async fn write_answer<W: tokio::io::AsyncWrite + Unpin>(
750786 response: &ApiResponse,
751787 ) -> Result<(), FrameError> {
752788 let written = write_frame(w, response).await;
753- if let (Err(FrameError::TooLarge(_)), ApiResponse::Ok { id, .. }) = (&written, response) {
789+ if let (Err(FrameError::TooLarge(_)), ApiResponse::Ok { id, school, .. }) = (&written, response)
790+ {
754791 return write_frame(
755792 w,
756793 &refusal(
757794 id.clone(),
795+ school.clone(),
758796 "too_large",
759797 format!("the answer exceeds the {AI_MAX_FRAME_BYTES}-byte frame limit"),
760798 ),
@@ -896,7 +934,7 @@ mod tests {
896934 refuse_before_dispatch,
897935 };
898936 use crate::ai::protocol::read_frame;
899- use crate::tenant::Slug;
937+ use crate::tenant::DEMO_SLUG;
900938
901939 /// An armed handle serving `router`. The database is never touched by these
902940 /// reads (nobody is named, so the principal is synthetic), but the handle
@@ -907,7 +945,6 @@ mod tests {
907945 tenants: crate::database::init_mem_tenants()
908946 .await
909947 .expect("in-memory deployment"),
910- slug: Slug::try_new(crate::tenant::DEMO_SLUG).unwrap(),
911948 db_up: Default::default(),
912949 files_path: std::env::temp_dir(),
913950 }
@@ -917,6 +954,7 @@ mod tests {
917954 fn read_of(path: &str) -> ApiRequest {
918955 ApiRequest {
919956 id: "trace-1".to_string(),
957+ school: DEMO_SLUG.to_string(),
920958 path: path.to_string(),
921959 query: None,
922960 on_behalf_of: None,
@@ -987,6 +1025,7 @@ mod tests {
9871025 // frame may precede it on the stream.
9881026 let big = ApiResponse::Ok {
9891027 id: "trace-1".to_string(),
1028+ school: DEMO_SLUG.to_string(),
9901029 status: 200,
9911030 body: serde_json::Value::String("x".repeat(AI_MAX_FRAME_BYTES)),
9921031 };
src/constant.rsmodified+2 -2
@@ -514,8 +514,8 @@ pub const MAX_PAGE_LIMIT: i64 = 500;
514514 /// and used as the QUIC ALPN. Bump both together on a breaking frame change:
515515 /// ALPN mismatch rejects an old service at the TLS handshake, before it can
516516 /// send a frame we would misparse.
517-pub const AI_PROTOCOL: &str = "hab/1";
518-pub const AI_ALPN: &[u8] = b"hab/1";
517+pub const AI_PROTOCOL: &str = "hab/2";
518+pub const AI_ALPN: &[u8] = b"hab/2";
519519
520520 /// Hard ceiling on one AI-bridge frame. Checked against the length prefix
521521 /// before the body buffer is allocated. Generous because a payload may carry a
src/lib.rsmodified+1 -1
@@ -42,7 +42,7 @@ use crate::state::AppState;
4242 modifiers(&SecurityAddon),
4343 tags(
4444 (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),
45- (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
45+ (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
4646 (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"),
4747 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
4848 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
src/web/ai.rsmodified+2 -2
@@ -35,8 +35,8 @@ pub fn routes() -> OpenApiRouter<AppState> {
3535 /// (which is a secret and is configured out of band).
3636 #[derive(Serialize, ToSchema)]
3737 pub struct BridgeCertificateResponse {
38- /// Wire protocol and ALPN the service must announce, currently `hab/1`.
39- #[schema(example = "hab/1")]
38+ /// Wire protocol and ALPN the service must announce, currently `hab/2`.
39+ #[schema(example = "hab/2")]
4040 protocol: String,
4141 /// The listener's leaf certificate, PEM-encoded — feed straight into a TLS
4242 /// client's trust store (Python: `ssl_context.load_verify_locations(cadata=...)`).
src/web/chatbot.rsmodified+16 -7
@@ -20,7 +20,7 @@
2020
2121 use std::time::Duration;
2222
23-use crate::web::tenant_state::State;
23+use crate::web::tenant_state::{SchoolSlug, State, TenantExt};
2424 use axum::Json;
2525 use axum::extract::{Path, Query};
2626 use axum::http::StatusCode;
@@ -377,6 +377,7 @@ async fn list_messages(
377377 )]
378378 async fn send_message(
379379 State(st): State<AppState>,
380+ SchoolSlug(school): SchoolSlug,
380381 CurrentUser(user): CurrentUser,
381382 Path(id): Path<String>,
382383 Json(req): Json<SendChatbotMessage>,
@@ -436,8 +437,14 @@ async fn send_message(
436437 // request), so it is the live role at the moment the question was asked —
437438 // never a stored copy, and never anything the body could assert.
438439 tokio::spawn(answer_turn(
440+ // The school and its database travel together — they are the pair the
441+ // request was already resolved into, and one without the other is how
442+ // an answer lands in the wrong school.
443+ TenantExt {
444+ slug: school,
445+ db: st.db.clone(),
446+ },
439447 bridge,
440- st.db.clone(),
441448 prompt.get_id().clone(),
442449 answer,
443450 user.get_role(),
@@ -477,14 +484,15 @@ fn unavailable(message: &str) -> Response {
477484 ///
478485 /// Every path settles: a row left `pending` would show as a spinner forever.
479486 async fn answer_turn(
487+ tenant: TenantExt,
480488 bridge: AiBridge,
481- db: Database,
482489 prompt_id: ChatbotMessageId,
483490 answer: ChatbotMessage,
484491 asker_role: Role,
485492 history_turns: usize,
486493 reply_cap: usize,
487494 ) {
495+ let db = tenant.db.clone();
488496 let answer_id = answer.get_id().clone();
489497 let thread = answer.get_thread_id().clone();
490498 // This request's own question, read back by id — the text is already
@@ -511,7 +519,7 @@ async fn answer_turn(
511519 let fresh = [prompt.get_id().clone(), answer_id.clone()];
512520 let settled = match fetch_reply(
513521 &bridge,
514- &db,
522+ &tenant,
515523 &thread,
516524 &fresh,
517525 prompt.get_content().as_str().to_string(),
@@ -542,7 +550,7 @@ async fn answer_turn(
542550 /// The bridge round trip, with every failure mapped to a stable code.
543551 async fn fetch_reply(
544552 bridge: &AiBridge,
545- db: &Database,
553+ tenant: &TenantExt,
546554 thread: &ChatbotThreadId,
547555 fresh: &[ChatbotMessageId; 2],
548556 prompt: String,
@@ -550,6 +558,7 @@ async fn fetch_reply(
550558 history_turns: usize,
551559 reply_cap: usize,
552560 ) -> Result<(ChatContent, bool), String> {
561+ let db = &tenant.db;
553562 let history = match history_for(db, thread, fresh, history_turns).await {
554563 Ok(history) => history,
555564 Err(err) => {
@@ -568,7 +577,7 @@ async fn fetch_reply(
568577 })?;
569578
570579 let raw = bridge
571- .dispatch(AI_CHAT_CAPABILITY, payload)
580+ .dispatch(&tenant.slug, AI_CHAT_CAPABILITY, payload)
572581 .await
573582 .map_err(failure_code)?;
574583 let reply: ChatReplyPayload = serde_json::from_value(raw).map_err(|err| {
@@ -820,7 +829,7 @@ async fn send_error(tx: &EventSender, code: &str, message: &str) {
820829
821830 /// Cut a finished answer into a handful of `delta` chunks.
822831 ///
823-/// Fake streaming: `hab/1` is unary, so the whole text is already in hand and
832+/// Fake streaming: `hab/2` is unary, so the whole text is already in hand and
824833 /// this only lets the UI paint it progressively instead of in one jump. The
825834 /// day the protocol grows chunk frames, this is the single function that goes
826835 /// away — nothing else in the stream knows where a chunk came from.
src/web/course_notes.rsmodified+9 -5
@@ -5,7 +5,7 @@
55 //! teacher, or manager+), reads need [`super::courses::can_view_course`]
66 //! (management rights, or enrollment).
77
8-use crate::web::tenant_state::State;
8+use crate::web::tenant_state::{SchoolSlug, State};
99 use axum::Json;
1010 use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
1111 use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
@@ -126,6 +126,7 @@ impl CourseNoteResponse {
126126 )]
127127 async fn create(
128128 State(st): State<AppState>,
129+ SchoolSlug(school): SchoolSlug,
129130 RequireTeacher(user): RequireTeacher,
130131 Json(req): Json<CreateCourseNote>,
131132 ) -> Result<(StatusCode, Json<CourseNoteResponse>), AppError> {
@@ -144,7 +145,7 @@ async fn create(
144145 // Indexing is a background bonus, never a condition of storing the note:
145146 // the dispatch runs in its own task, so a slow or absent AI service cannot
146147 // delay or fail this 201.
147- spawn_index(&st, note.clone());
148+ spawn_index(&st, &school, note.clone());
148149 Ok((StatusCode::CREATED, Json(CourseNoteResponse::new(&note))))
149150 }
150151
@@ -242,6 +243,7 @@ async fn get_one(
242243 )]
243244 async fn update(
244245 State(st): State<AppState>,
246+ SchoolSlug(school): SchoolSlug,
245247 RequireTeacher(user): RequireTeacher,
246248 Path(id): Path<String>,
247249 Json(req): Json<UpdateCourseNote>,
@@ -267,7 +269,7 @@ async fn update(
267269
268270 let updated = note.update(title, content, &st.db).await?;
269271 // The stored index describes the old text — refresh it.
270- spawn_index(&st, updated.clone());
272+ spawn_index(&st, &school, updated.clone());
271273 Ok(Json(CourseNoteResponse::new(&updated)))
272274 }
273275
@@ -365,6 +367,7 @@ impl CourseNoteFileResponse {
365367 )]
366368 async fn upload_file(
367369 State(st): State<AppState>,
370+ SchoolSlug(school): SchoolSlug,
368371 RequireTeacher(user): RequireTeacher,
369372 Path(id): Path<String>,
370373 mut multipart: Multipart,
@@ -395,7 +398,7 @@ async fn upload_file(
395398 match file.insert(&st.db).await {
396399 Ok(created) => {
397400 // The note now holds one more source than the stored index knows.
398- spawn_index(&st, note);
401+ spawn_index(&st, &school, note);
399402 Ok((
400403 StatusCode::CREATED,
401404 Json(CourseNoteFileResponse::new(&created)),
@@ -520,6 +523,7 @@ async fn download_file(
520523 )]
521524 async fn delete_file(
522525 State(st): State<AppState>,
526+ SchoolSlug(school): SchoolSlug,
523527 RequireTeacher(user): RequireTeacher,
524528 Path((id, file_id)): Path<(String, String)>,
525529 ) -> Result<StatusCode, AppError> {
@@ -541,7 +545,7 @@ async fn delete_file(
541545 RagOutput::delete_with_source(file.get_id(), &st.db).await?;
542546 let file = file.delete(&st.db).await?;
543547 remove_blob(&st.files_path, file.get_id().key()).await;
544- spawn_index(&st, note);
548+ spawn_index(&st, &school, note);
545549 Ok(StatusCode::NO_CONTENT)
546550 }
547551
tests/ai_bridge.rsmodified+96 -20
@@ -18,6 +18,7 @@ use hezarfen_backend::ai::protocol::{
1818 };
1919 use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig};
2020 use hezarfen_backend::constant::{AI_ALPN, AI_MAX_CONCURRENT_PER_WORKER, AI_PROTOCOL};
21+use hezarfen_backend::tenant::{DEMO_SLUG, Slug};
2122 use serde_json::{Value, json};
2223
2324 const TOKEN: &str = "shared-ai-token";
@@ -68,6 +69,11 @@ fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint {
6869 endpoint
6970 }
7071
72+/// The demo school, which every dispatch in this suite is made on behalf of.
73+fn demo() -> Slug {
74+ Slug::try_new(DEMO_SLUG).expect("the demo slug")
75+}
76+
7177 fn hello(service: &str, capabilities: &[&str]) -> Hello {
7278 Hello {
7379 protocol: AI_PROTOCOL.to_string(),
@@ -188,10 +194,12 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ
188194 }
189195 Behaviour::Answer(payload) => Some(Response::Ok {
190196 id: request.id.clone(),
197+ school: request.school.clone(),
191198 payload,
192199 }),
193200 Behaviour::Reply(text) => Some(Response::Ok {
194201 id: request.id.clone(),
202+ school: request.school.clone(),
195203 payload: json!({ "text": text }),
196204 }),
197205 Behaviour::EchoPrompt => {
@@ -200,16 +208,19 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ
200208 .unwrap_or("<no message>");
201209 Some(Response::Ok {
202210 id: request.id.clone(),
211+ school: request.school.clone(),
203212 payload: json!({ "text": format!("cevap::{asked}") }),
204213 })
205214 }
206215 Behaviour::Fail { code, message } => Some(Response::Err {
207216 id: request.id.clone(),
217+ school: request.school.clone(),
208218 code,
209219 message,
210220 }),
211221 Behaviour::WrongId => Some(Response::Ok {
212222 id: "01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string(),
223+ school: request.school.clone(),
213224 payload: json!("from some other request"),
214225 }),
215226 Behaviour::Garbage => {
@@ -241,6 +252,7 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ
241252 fn echo(request: &Request) -> Response {
242253 Response::Ok {
243254 id: request.id.clone(),
255+ school: request.school.clone(),
244256 payload: json!({ "echo": request.payload, "capability": request.capability }),
245257 }
246258 }
@@ -285,7 +297,7 @@ async fn a_service_registers_and_a_request_round_trips() {
285297 assert!(bridge.has_capability("ocr.extract"));
286298
287299 let answer = bridge
288- .dispatch("ocr.extract", json!({ "image": "abc" }))
300+ .dispatch(&demo(), "ocr.extract", json!({ "image": "abc" }))
289301 .await
290302 .expect("the service answered");
291303 assert_eq!(answer["echo"]["image"], "abc");
@@ -320,7 +332,7 @@ async fn concurrent_requests_share_one_connection_without_blocking_each_other()
320332
321333 let calls = (0..N).map(|i| {
322334 let bridge = bridge.clone();
323- tokio::spawn(async move { bridge.dispatch("ocr.extract", json!({ "n": i })).await })
335+ tokio::spawn(async move { bridge.dispatch(&demo(), "ocr.extract", json!({ "n": i })).await })
324336 });
325337 let answers = futures_util::future::join_all(calls).await;
326338
@@ -344,8 +356,8 @@ async fn requests_route_to_the_service_declaring_the_capability() {
344356 let grader = connect_service(&bridge, hello("grader", &["grade.essay"]), Behaviour::Echo).await;
345357 await_workers(&bridge, 2).await;
346358
347- bridge.dispatch("grade.essay", json!("text")).await.unwrap();
348- bridge.dispatch("ocr.extract", json!("png")).await.unwrap();
359+ bridge.dispatch(&demo(), "grade.essay", json!("text")).await.unwrap();
360+ bridge.dispatch(&demo(), "ocr.extract", json!("png")).await.unwrap();
349361
350362 assert_eq!(ocr.seen().len(), 1, "ocr only saw its own capability");
351363 assert_eq!(ocr.seen()[0].capability, "ocr.extract");
@@ -401,7 +413,7 @@ async fn a_bad_token_is_rejected_and_never_registers() {
401413 );
402414 assert!(bridge.workers().is_empty());
403415 assert!(matches!(
404- bridge.dispatch("ocr.extract", json!(null)).await,
416+ bridge.dispatch(&demo(), "ocr.extract", json!(null)).await,
405417 Err(AiError::NoWorker(_))
406418 ));
407419 }
@@ -502,7 +514,7 @@ async fn an_unknown_capability_fails_fast_instead_of_waiting() {
502514 await_workers(&bridge, 1).await;
503515
504516 let err = bridge
505- .dispatch("grade.essay", json!(null))
517+ .dispatch(&demo(), "grade.essay", json!(null))
506518 .await
507519 .expect_err("nothing serves that capability");
508520 assert!(
@@ -527,7 +539,7 @@ async fn a_service_error_frame_surfaces_as_a_remote_error() {
527539 await_workers(&bridge, 1).await;
528540
529541 let err = bridge
530- .dispatch("ocr.extract", json!({ "image": "x" }))
542+ .dispatch(&demo(), "ocr.extract", json!({ "image": "x" }))
531543 .await
532544 .unwrap_err();
533545 match &err {
@@ -550,7 +562,7 @@ async fn a_silent_service_times_out_and_gives_the_slot_back() {
550562 await_workers(&bridge, 1).await;
551563
552564 let err = bridge
553- .dispatch("ocr.extract", json!(null))
565+ .dispatch(&demo(), "ocr.extract", json!(null))
554566 .await
555567 .unwrap_err();
556568 assert!(matches!(err, AiError::Timeout(300)), "{err}");
@@ -560,7 +572,7 @@ async fn a_silent_service_times_out_and_gives_the_slot_back() {
560572 // An abandoned request must not leak the worker's capacity.
561573 assert_eq!(bridge.workers()[0].inflight, 0);
562574 // And the worker is immediately usable again.
563- assert!(bridge.dispatch("ocr.extract", json!(null)).await.is_err());
575+ assert!(bridge.dispatch(&demo(), "ocr.extract", json!(null)).await.is_err());
564576 }
565577
566578 #[tokio::test]
@@ -576,12 +588,12 @@ async fn a_per_call_timeout_overrides_the_default() {
576588
577589 // The default deadline is too short for this service...
578590 assert!(matches!(
579- bridge.dispatch("ocr.extract", json!(null)).await,
591+ bridge.dispatch(&demo(), "ocr.extract", json!(null)).await,
580592 Err(AiError::Timeout(100))
581593 ));
582594 // ...but a capability known to be slow can ask for more.
583595 let answer = bridge
584- .dispatch_with_timeout("ocr.extract", json!("slow"), Duration::from_secs(5))
596+ .dispatch_with_timeout(&demo(), "ocr.extract", json!("slow"), Duration::from_secs(5))
585597 .await
586598 .expect("the longer deadline held");
587599 assert_eq!(answer["echo"], "slow");
@@ -597,12 +609,12 @@ async fn a_full_worker_reports_busy_rather_than_queueing() {
597609
598610 let hog = {
599611 let bridge = bridge.clone();
600- tokio::spawn(async move { bridge.dispatch("ocr.extract", json!(null)).await })
612+ tokio::spawn(async move { bridge.dispatch(&demo(), "ocr.extract", json!(null)).await })
601613 };
602614 await_inflight(&bridge, 1).await;
603615
604616 let err = bridge
605- .dispatch("ocr.extract", json!(null))
617+ .dispatch(&demo(), "ocr.extract", json!(null))
606618 .await
607619 .unwrap_err();
608620 assert!(
@@ -626,7 +638,7 @@ async fn an_answer_carrying_the_wrong_trace_id_is_refused() {
626638 await_workers(&bridge, 1).await;
627639
628640 let err = bridge
629- .dispatch("ocr.extract", json!(null))
641+ .dispatch(&demo(), "ocr.extract", json!(null))
630642 .await
631643 .unwrap_err();
632644 assert!(matches!(err, AiError::IdMismatch { .. }), "{err}");
@@ -641,7 +653,7 @@ async fn a_malformed_answer_is_a_protocol_error_not_a_hang() {
641653 await_workers(&bridge, 1).await;
642654
643655 let err = bridge
644- .dispatch("ocr.extract", json!(null))
656+ .dispatch(&demo(), "ocr.extract", json!(null))
645657 .await
646658 .unwrap_err();
647659 assert!(matches!(err, AiError::Protocol(_)), "{err}");
@@ -655,7 +667,7 @@ async fn a_disconnected_service_is_deregistered() {
655667 let bridge = bridge().await;
656668 let service = connect_service(&bridge, hello("ocr", &["ocr.extract"]), Behaviour::Echo).await;
657669 await_workers(&bridge, 1).await;
658- bridge.dispatch("ocr.extract", json!(null)).await.unwrap();
670+ bridge.dispatch(&demo(), "ocr.extract", json!(null)).await.unwrap();
659671
660672 service.conn.close(0u32.into(), b"service shutting down");
661673 drop(service);
@@ -663,7 +675,7 @@ async fn a_disconnected_service_is_deregistered() {
663675
664676 assert!(!bridge.has_capability("ocr.extract"));
665677 let err = bridge
666- .dispatch("ocr.extract", json!(null))
678+ .dispatch(&demo(), "ocr.extract", json!(null))
667679 .await
668680 .unwrap_err();
669681 assert!(matches!(err, AiError::NoWorker(_)), "{err}");
@@ -683,7 +695,7 @@ async fn a_service_that_reconnects_serves_again() {
683695 let second = connect_service(&bridge, hello("ocr", &["ocr.extract"]), Behaviour::Echo).await;
684696 await_workers(&bridge, 1).await;
685697 let answer = bridge
686- .dispatch("ocr.extract", json!("again"))
698+ .dispatch(&demo(), "ocr.extract", json!("again"))
687699 .await
688700 .unwrap();
689701 assert_eq!(answer["echo"], "again");
@@ -703,7 +715,7 @@ async fn losing_one_service_leaves_the_other_serving() {
703715 await_workers(&bridge, 1).await;
704716
705717 for _ in 0..4 {
706- bridge.dispatch("ocr.extract", json!("x")).await.unwrap();
718+ bridge.dispatch(&demo(), "ocr.extract", json!("x")).await.unwrap();
707719 }
708720 assert_eq!(
709721 survivor.seen().len(),
@@ -794,7 +806,7 @@ async fn a_large_payload_survives_the_round_trip_intact() {
794806
795807 let blob: String = std::iter::repeat_n('x', 512 * 1024).collect();
796808 let answer = bridge
797- .dispatch("ocr.extract", json!({ "image": blob }))
809+ .dispatch(&demo(), "ocr.extract", json!({ "image": blob }))
798810 .await
799811 .expect("a multi-packet frame round-trips");
800812 let echoed = answer["echo"]["image"].as_str().expect("string came back");
@@ -1418,8 +1430,14 @@ async fn api_read(conn: &quinn::Connection, request: ApiRequest) -> ApiResponse
14181430
14191431 /// A `GET` of `path` as `on_behalf_of` (or as the service itself).
14201432 fn read_of(path: &str, on_behalf_of: Option<&str>) -> ApiRequest {
1433+ read_of_school(DEMO_SLUG, path, on_behalf_of)
1434+}
1435+
1436+/// The same, naming the school explicitly — the tenancy tests below.
1437+fn read_of_school(school: &str, path: &str, on_behalf_of: Option<&str>) -> ApiRequest {
14211438 ApiRequest {
14221439 id: format!("trace-{path}"),
1440+ school: school.to_string(),
14231441 path: path.to_string(),
14241442 query: None,
14251443 on_behalf_of: on_behalf_of.map(str::to_string),
@@ -1710,6 +1728,52 @@ async fn course_note(app: &Router, db: &Database) -> (String, String) {
17101728 (cookie, common::id_of(&res.body))
17111729 }
17121730
1731+#[tokio::test]
1732+async fn an_index_dispatch_names_the_notes_own_school_and_stores_the_answer_there() {
1733+ // The outbound half of `hab/2`, end to end and across two schools: the
1734+ // frame the service receives names the school whose teacher wrote the note,
1735+ // and the answer is stored in *that* school's database — not the control
1736+ // one, and not the neighbour's. A bridge that carried no school could only
1737+ // have guessed, and this is the test that would catch the guess.
1738+ let bridge = bridge().await;
1739+ let service = connect_service(
1740+ &bridge,
1741+ hello("indexer", &[AI_RAG_INDEX_CAPABILITY]),
1742+ Behaviour::Answer(json!({ "summary": "beta" })),
1743+ )
1744+ .await;
1745+ await_workers(&bridge, 1).await;
1746+
1747+ let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
1748+ let beta = Slug::try_new("beta").unwrap();
1749+ let beta_db = tenants.create(&beta, "Beta College").await.expect("beta");
1750+
1751+ let cookie = common::login_as_school(&app, &beta_db, "beta", "ogretmen", "teacher").await;
1752+ let course = common::create_course(&app, &cookie, "fizik").await;
1753+ let res = common::send(
1754+ &app,
1755+ "POST",
1756+ "/course-notes",
1757+ Some(&cookie),
1758+ Some(json!({ "course": course, "title": "Bölüm 3", "content": "özet" })),
1759+ )
1760+ .await;
1761+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1762+ let note = common::id_of(&res.body);
1763+
1764+ let stored = await_outputs(&beta_db, &note).await;
1765+ assert_eq!(stored.len(), 1);
1766+ assert_eq!(stored[0].get_payload()["summary"], "beta");
1767+ assert!(
1768+ outputs(&demo_db, &note).await.is_empty(),
1769+ "the neighbouring school must hold no row for beta's note"
1770+ );
1771+
1772+ let seen = service.seen();
1773+ assert_eq!(seen[0].school, "beta", "the frame named the wrong school");
1774+ assert_eq!(seen[0].payload["course_note"], note);
1775+}
1776+
17131777 #[tokio::test]
17141778 async fn a_course_note_is_indexed_and_its_output_stored_with_its_sources() {
17151779 let bridge = bridge().await;
@@ -1731,6 +1795,7 @@ async fn a_course_note_is_indexed_and_its_output_stored_with_its_sources() {
17311795 // The service saw the note itself, under the documented capability.
17321796 let seen = service.seen();
17331797 assert_eq!(seen[0].capability, AI_RAG_INDEX_CAPABILITY);
1798+ assert_eq!(seen[0].school, DEMO_SLUG, "the frame names the caller's school");
17341799 assert_eq!(seen[0].payload["course_note"], note);
17351800 assert_eq!(seen[0].payload["title"], "Bölüm 3");
17361801 assert_eq!(seen[0].payload["content"], "özet");
@@ -1876,6 +1941,7 @@ async fn a_service_reads_a_course_note_on_behalf_of_an_enrolled_student() {
18761941
18771942 let request = ApiRequest {
18781943 id: "trace-course-notes".into(),
1944+ school: DEMO_SLUG.into(),
18791945 path: "/course-notes".into(),
18801946 query: Some(format!("course={course}")),
18811947 on_behalf_of: Some(student),
@@ -1903,6 +1969,7 @@ async fn a_course_the_student_is_not_in_is_refused_by_the_handler() {
19031969
19041970 let request = ApiRequest {
19051971 id: "trace-foreign-course".into(),
1972+ school: DEMO_SLUG.into(),
19061973 path: "/course-notes".into(),
19071974 query: Some(format!("course={foreign}")),
19081975 on_behalf_of: Some(student),
@@ -1922,6 +1989,7 @@ async fn writing_a_course_note_is_refused_before_dispatch() {
19221989
19231990 let request = ApiRequest {
19241991 id: "trace-post".into(),
1992+ school: DEMO_SLUG.into(),
19251993 path: "/course-notes".into(),
19261994 query: None,
19271995 on_behalf_of: None,
@@ -1990,8 +2058,14 @@ async fn blob_read(conn: &quinn::Connection, request: BlobRequest) -> (BlobRespo
19902058 }
19912059
19922060 fn blob_of(file: &str, on_behalf_of: Option<&str>) -> BlobRequest {
2061+ blob_of_school(DEMO_SLUG, file, on_behalf_of)
2062+}
2063+
2064+/// The same, naming the school explicitly.
2065+fn blob_of_school(school: &str, file: &str, on_behalf_of: Option<&str>) -> BlobRequest {
19932066 BlobRequest {
19942067 id: format!("trace-blob-{file}"),
2068+ school: school.to_string(),
19952069 file: file.to_string(),
19962070 on_behalf_of: on_behalf_of.map(str::to_string),
19972071 }
@@ -2033,6 +2107,7 @@ async fn a_service_streams_a_course_note_file_on_behalf_of_an_enrolled_student()
20332107 let (header, bytes) = blob_read(&service.conn, blob_of(&file, Some(&student))).await;
20342108 let BlobResponse::Ok {
20352109 id,
2110+ school,
20362111 name,
20372112 content_type,
20382113 size,
@@ -2041,6 +2116,7 @@ async fn a_service_streams_a_course_note_file_on_behalf_of_an_enrolled_student()
20412116 panic!("the enrolled student was refused: {}", blob_refusal(header));
20422117 };
20432118 assert_eq!(id, format!("trace-blob-{file}"), "the trace id is echoed");
2119+ assert_eq!(school, DEMO_SLUG, "the school is echoed too");
20442120 assert_eq!(name, "recap.pdf");
20452121 assert_eq!(content_type, "application/pdf");
20462122 assert_eq!(size as usize, uploaded.len(), "the promised byte count");
tests/ai_protocol.rsmodified+234 -44
@@ -1,4 +1,4 @@
1-//! Wire-contract tests for the AI bridge — the regression net for `hab/1`.
1+//! Wire-contract tests for the AI bridge — the regression net for `hab/2`.
22 //!
33 //! # Why this file exists separately from `ai_bridge.rs`
44 //!
@@ -15,7 +15,7 @@
1515 //! in a service repo.
1616 //!
1717 //! It doubles as the reference implementation: `raw::Service` below is the
18-//! whole client side of `hab/1` in about a hundred lines.
18+//! whole client side of `hab/2` in about a hundred lines.
1919
2020 mod common;
2121
@@ -23,18 +23,23 @@ use std::sync::Arc;
2323 use std::time::Duration;
2424
2525 use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig};
26+use hezarfen_backend::tenant::{SchoolStatus, Slug, Tenants};
2627 use serde_json::{Value, json};
2728
2829 const TOKEN: &str = "shared-ai-token";
2930
31+/// The school every frame in this suite names. A literal for the same reason
32+/// `PROTOCOL` is one: a service spells the slug out, it is not a Rust constant.
33+const SCHOOL: &str = "demo";
34+
3035 /// The protocol identifier this suite pins. Deliberately a literal, not
3136 /// `AI_PROTOCOL`: importing the constant would let a rename sail through, and
3237 /// the whole point is that the string is a published contract.
33-const PROTOCOL: &str = "hab/1";
38+const PROTOCOL: &str = "hab/2";
3439
3540 // ------------------------------------------------------------------- raw --
3641
37-/// A minimal `hab/1` client with no dependency on the crate's protocol types.
42+/// A minimal `hab/2` client with no dependency on the crate's protocol types.
3843 mod raw {
3944 use super::*;
4045
@@ -252,7 +257,8 @@ fn dispatch(
252257 ) -> tokio::task::JoinHandle<Result<Value, AiError>> {
253258 let bridge = bridge.clone();
254259 let capability = capability.to_string();
255- tokio::spawn(async move { bridge.dispatch(&capability, payload).await })
260+ let school = hezarfen_backend::tenant::Slug::try_new(SCHOOL).expect("the demo slug");
261+ tokio::spawn(async move { bridge.dispatch(&school, &capability, payload).await })
256262 }
257263
258264 // ------------------------------------------------------- framing contract --
@@ -385,7 +391,7 @@ async fn the_rejection_frame_carries_exactly_the_published_keys_and_codes() {
385391 // variant is a breaking change and must fail here.
386392 let bridge = bridge().await;
387393
388- let cases: [(&str, Vec<u8>); 4] = [
394+ let cases: [(&str, Vec<u8>); 5] = [
389395 (
390396 "unauthorized",
391397 format!(
@@ -400,6 +406,16 @@ async fn the_rejection_frame_carries_exactly_the_published_keys_and_codes() {
400406 )
401407 .into_bytes(),
402408 ),
409+ // The immediate predecessor, named on purpose: `hab/1` frames carry no
410+ // school, so a service still speaking it must be turned away here
411+ // rather than reaching a path that would have to guess one.
412+ (
413+ "unsupported_protocol",
414+ format!(
415+ r#"{{"protocol":"hab/1","service":"s","capabilities":["c"],"token":"{TOKEN}"}}"#
416+ )
417+ .into_bytes(),
418+ ),
403419 (
404420 "no_capabilities",
405421 format!(
@@ -491,12 +507,20 @@ async fn a_foreign_alpn_is_refused_at_the_tls_handshake() {
491507 // The version gate: an incompatible service must be stopped before it can
492508 // send a frame this backend would misparse.
493509 let bridge = bridge().await;
494- let endpoint = raw::endpoint_with_alpn(&bridge, b"hab/99");
495- let result = endpoint
496- .connect(bridge.local_addr().unwrap(), "localhost")
497- .unwrap()
498- .await;
499- assert!(result.is_err(), "ALPN hab/99 must not connect");
510+ // `hab/1` included by name: the version gate is the *first* line of defence
511+ // against a service whose frames name no school, ahead of the Hello check.
512+ for alpn in [b"hab/99".as_slice(), b"hab/1".as_slice()] {
513+ let endpoint = raw::endpoint_with_alpn(&bridge, alpn);
514+ let result = endpoint
515+ .connect(bridge.local_addr().unwrap(), "localhost")
516+ .unwrap()
517+ .await;
518+ assert!(
519+ result.is_err(),
520+ "ALPN {} must not connect",
521+ String::from_utf8_lossy(alpn)
522+ );
523+ }
500524 assert!(bridge.workers().is_empty());
501525 }
502526
@@ -516,7 +540,7 @@ async fn the_request_frame_carries_exactly_the_published_keys() {
516540
517541 assert_eq!(
518542 raw::keys(&request),
519- ["capability", "deadline_ms", "id", "payload"],
543+ ["capability", "deadline_ms", "id", "payload", "school"],
520544 "request shape changed: {request}"
521545 );
522546 assert_eq!(request["capability"], "ocr.extract");
@@ -529,7 +553,7 @@ async fn the_request_frame_carries_exactly_the_published_keys() {
529553 let id = request["id"].as_str().unwrap().to_string();
530554 raw::answer(
531555 send,
532- format!(r#"{{"status":"ok","id":"{id}","payload":{{"text":"hi"}}}}"#).as_bytes(),
556+ format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"text":"hi"}}}}"#).as_bytes(),
533557 )
534558 .await;
535559 let answer = call.await.unwrap().expect("dispatch succeeded");
@@ -562,7 +586,7 @@ async fn a_payload_of_any_json_shape_survives_unchanged() {
562586 assert_eq!(request["payload"], payload, "payload mutated in flight");
563587
564588 let id = request["id"].as_str().unwrap();
565- let echo = json!({ "status": "ok", "id": id, "payload": payload });
589+ let echo = json!({ "status": "ok", "id": id, "school": SCHOOL, "payload": payload });
566590 raw::answer(send, &serde_json::to_vec(&echo).unwrap()).await;
567591 assert_eq!(
568592 call.await.unwrap().unwrap(),
@@ -585,7 +609,7 @@ async fn the_response_tags_are_the_published_literals() {
585609 let id = request["id"].as_str().unwrap().to_string();
586610 raw::answer(
587611 send,
588- format!(r#"{{"status":"ok","id":"{id}","payload":42}}"#).as_bytes(),
612+ format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":42}}"#).as_bytes(),
589613 )
590614 .await;
591615 assert_eq!(ok.await.unwrap().unwrap(), json!(42));
@@ -595,7 +619,7 @@ async fn the_response_tags_are_the_published_literals() {
595619 let id = request["id"].as_str().unwrap().to_string();
596620 raw::answer(
597621 send,
598- format!(r#"{{"status":"err","id":"{id}","code":"bad_input","message":"nope"}}"#).as_bytes(),
622+ format!(r#"{{"status":"err","id":"{id}","school":"{SCHOOL}","code":"bad_input","message":"nope"}}"#).as_bytes(),
599623 )
600624 .await;
601625 match err.await.unwrap() {
@@ -611,7 +635,7 @@ async fn the_response_tags_are_the_published_literals() {
611635 let id = request["id"].as_str().unwrap().to_string();
612636 raw::answer(
613637 send,
614- format!(r#"{{"status":"success","id":"{id}","payload":1}}"#).as_bytes(),
638+ format!(r#"{{"status":"success","id":"{id}","school":"{SCHOOL}","payload":1}}"#).as_bytes(),
615639 )
616640 .await;
617641 assert!(
@@ -634,7 +658,7 @@ async fn a_response_may_carry_unknown_fields() {
634658 raw::answer(
635659 send,
636660 format!(
637- r#"{{"status":"ok","id":"{id}","payload":{{"text":"x"}},"took_ms":91,"model":"v2"}}"#
661+ r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"text":"x"}},"took_ms":91,"model":"v2"}}"#
638662 )
639663 .as_bytes(),
640664 )
@@ -690,7 +714,7 @@ async fn each_request_gets_its_own_stream_and_answers_may_come_back_in_any_order
690714 let n = request["payload"]["n"].clone();
691715 raw::answer(
692716 send,
693- format!(r#"{{"status":"ok","id":"{id}","payload":{{"n":{n}}}}}"#).as_bytes(),
717+ format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"n":{n}}}}}"#).as_bytes(),
694718 )
695719 .await;
696720 }
@@ -720,7 +744,7 @@ async fn request_ids_are_unique_per_request() {
720744 assert!(seen.insert(id.clone()), "id {id} was reused");
721745 raw::answer(
722746 send,
723- format!(r#"{{"status":"ok","id":"{id}","payload":1}}"#).as_bytes(),
747+ format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":1}}"#).as_bytes(),
724748 )
725749 .await;
726750 call.await.unwrap().unwrap();
@@ -752,7 +776,7 @@ async fn the_control_stream_carries_no_frames_after_the_welcome() {
752776 let id = request["id"].as_str().unwrap().to_string();
753777 raw::answer(
754778 send,
755- format!(r#"{{"status":"ok","id":"{id}","payload":1}}"#).as_bytes(),
779+ format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":1}}"#).as_bytes(),
756780 )
757781 .await;
758782 call.await
@@ -774,7 +798,13 @@ async fn closing_the_control_stream_deregisters_the_service() {
774798 await_workers(&bridge, 0).await;
775799
776800 assert!(matches!(
777- bridge.dispatch("ocr.extract", json!(null)).await,
801+ bridge
802+ .dispatch(
803+ &hezarfen_backend::tenant::Slug::try_new(SCHOOL).unwrap(),
804+ "ocr.extract",
805+ json!(null)
806+ )
807+ .await,
778808 Err(AiError::NoWorker(_))
779809 ));
780810 }
@@ -811,7 +841,7 @@ async fn a_service_that_drops_a_request_stream_fails_that_request_only() {
811841 let id = request["id"].as_str().unwrap().to_string();
812842 raw::answer(
813843 send,
814- format!(r#"{{"status":"ok","id":"{id}","payload":"ok"}}"#).as_bytes(),
844+ format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":"ok"}}"#).as_bytes(),
815845 )
816846 .await;
817847 assert_eq!(next.await.unwrap().unwrap(), json!("ok"));
@@ -882,7 +912,7 @@ async fn several_raw_services_serve_one_capability_together() {
882912 let n = request["payload"]["n"].clone();
883913 raw::answer(
884914 send,
885- format!(r#"{{"status":"ok","id":"{id}","payload":{n}}}"#).as_bytes(),
915+ format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{n}}}"#).as_bytes(),
886916 )
887917 .await;
888918 }
@@ -976,7 +1006,7 @@ async fn a_chat_request_names_the_askers_school_role() {
9761006 let id = request["id"].as_str().expect("trace id").to_string();
9771007 raw::answer(
9781008 send,
979- format!(r#"{{"status":"ok","id":"{id}","payload":{{"text":"F = ma"}}}}"#).as_bytes(),
1009+ format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"text":"F = ma"}}}}"#).as_bytes(),
9801010 )
9811011 .await;
9821012 }
@@ -1012,7 +1042,7 @@ async fn the_api_request_field_names_are_the_published_literals() {
10121042 let (answer, bytes) = raw::api_read(
10131043 &service.conn,
10141044 format!(
1015- r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","path":"/notes","query":"limit=1&offset=0","on_behalf_of":"{student}","method":"GET"}}"#
1045+ r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","school":"{SCHOOL}","path":"/notes","query":"limit=1&offset=0","on_behalf_of":"{student}","method":"GET"}}"#
10161046 )
10171047 .as_bytes(),
10181048 )
@@ -1020,7 +1050,7 @@ async fn the_api_request_field_names_are_the_published_literals() {
10201050
10211051 assert_eq!(
10221052 raw::keys(&answer),
1023- ["body", "id", "outcome", "status"],
1053+ ["body", "id", "outcome", "school", "status"],
10241054 "api answer shape changed: {answer}"
10251055 );
10261056 assert_eq!(answer["outcome"], "ok");
@@ -1048,7 +1078,7 @@ async fn only_id_and_path_are_required_of_an_api_request() {
10481078
10491079 let (answer, _) = raw::api_read(
10501080 &service.conn,
1051- br#"{"id":"trace-1","path":"/auth/me","unknown_field":true}"#,
1081+ br#"{"id":"trace-1","school":"demo","path":"/auth/me","unknown_field":true}"#,
10521082 )
10531083 .await;
10541084 assert_eq!(answer["outcome"], "ok", "{answer}");
@@ -1070,34 +1100,47 @@ async fn the_api_refusal_frame_carries_exactly_the_published_keys_and_codes() {
10701100 let cases = [
10711101 (
10721102 "method_not_allowed",
1073- r#"{"id":"t1","path":"/notes","method":"DELETE"}"#.to_string(),
1103+ r#"{"id":"t1","school":"demo","path":"/notes","method":"DELETE"}"#.to_string(),
10741104 ),
10751105 (
10761106 "method_not_allowed",
10771107 // Lowercase is not the method: the literal is exactly `GET`.
1078- r#"{"id":"t2","path":"/notes","method":"get"}"#.to_string(),
1108+ r#"{"id":"t2","school":"demo","path":"/notes","method":"get"}"#.to_string(),
10791109 ),
10801110 (
10811111 "path_not_allowed",
1082- r#"{"id":"t3","path":"/courses"}"#.to_string(),
1112+ r#"{"id":"t3","school":"demo","path":"/courses"}"#.to_string(),
10831113 ),
10841114 (
10851115 // Order pin: both refusals apply, the method one wins.
10861116 "method_not_allowed",
1087- r#"{"id":"t4","path":"/nope","method":"POST"}"#.to_string(),
1117+ r#"{"id":"t4","school":"demo","path":"/nope","method":"POST"}"#.to_string(),
10881118 ),
10891119 (
10901120 "unknown_user",
1091- r#"{"id":"t5","path":"/auth/me","on_behalf_of":"nobodyatall"}"#.to_string(),
1121+ r#"{"id":"t5","school":"demo","path":"/auth/me","on_behalf_of":"nobodyatall"}"#.to_string(),
1122+ ),
1123+ ("malformed", r#"{"id":"t6","school":"demo","path":42}"#.to_string()),
1124+ // A frame that names no school at all: required, never defaulted.
1125+ ("malformed", r#"{"id":"t7","path":"/auth/me"}"#.to_string()),
1126+ // A string that is no slug — the service's own bug, not a missing
1127+ // customer, so it is `malformed` rather than `unknown_school`.
1128+ (
1129+ "malformed",
1130+ r#"{"id":"t8","school":"NOT A SLUG","path":"/auth/me"}"#.to_string(),
1131+ ),
1132+ // A well-formed slug this deployment does not serve.
1133+ (
1134+ "unknown_school",
1135+ r#"{"id":"t9","school":"nope","path":"/auth/me"}"#.to_string(),
10921136 ),
1093- ("malformed", r#"{"id":"t6","path":42}"#.to_string()),
10941137 ];
10951138
10961139 for (expected_code, request) in cases {
10971140 let (answer, _) = raw::api_read(&service.conn, request.as_bytes()).await;
10981141 assert_eq!(
10991142 raw::keys(&answer),
1100- ["code", "id", "message", "outcome"],
1143+ ["code", "id", "message", "outcome", "school"],
11011144 "refusal shape changed for {expected_code}: {answer}"
11021145 );
11031146 assert_eq!(answer["outcome"], "err", "{answer}");
@@ -1130,7 +1173,8 @@ async fn an_api_read_answers_a_named_user_with_that_users_own_data() {
11301173
11311174 let (answer, _) = raw::api_read(
11321175 &service.conn,
1133- format!(r#"{{"id":"t9","path":"/auth/me","on_behalf_of":"{student}"}}"#).as_bytes(),
1176+ format!(r#"{{"id":"tme","school":"{SCHOOL}","path":"/auth/me","on_behalf_of":"{student}"}}"#)
1177+ .as_bytes(),
11341178 )
11351179 .await;
11361180 assert_eq!(answer["outcome"], "ok", "{answer}");
@@ -1139,6 +1183,148 @@ async fn an_api_read_answers_a_named_user_with_that_users_own_data() {
11391183 assert_eq!(answer["body"]["role"], "student", "{answer}");
11401184 }
11411185
1186+// --------------------------------------------------------------- tenancy --
1187+//
1188+// `hab/2`'s whole reason for existing: one shared fleet of services, every
1189+// frame naming the school it means. These drive that through the raw client,
1190+// because the refusal codes and the school echo are published contract exactly
1191+// like the frame keys above.
1192+
1193+/// An armed bridge over a deployment with a *second* school, `beta`, holding a
1194+/// user of the same name as the demo school's. Returns the router (holding it
1195+/// is what keeps the bridge armed), the registry, and the two ids of `ayse`.
1196+async fn two_schools(bridge: &AiBridge) -> (axum::Router, Tenants, String, String) {
1197+ let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
1198+ let beta_db = tenants
1199+ .create(&Slug::try_new("beta").unwrap(), "Beta College")
1200+ .await
1201+ .expect("a second school");
1202+
1203+ let demo_cookie = common::login_as(&app, &demo_db, "ayse", "student").await;
1204+ let beta_cookie = common::login_as_school(&app, &beta_db, "beta", "ayse", "student").await;
1205+ let demo_ayse = common::me_id(&app, &demo_cookie).await;
1206+ let beta_ayse = common::me_id(&app, &beta_cookie).await;
1207+ assert_ne!(demo_ayse, beta_ayse, "two schools, two separate `ayse` rows");
1208+ (app, tenants, demo_ayse, beta_ayse)
1209+}
1210+
1211+#[tokio::test]
1212+async fn an_api_read_answers_out_of_the_school_the_frame_named() {
1213+ // The isolation the field buys, proved both ways with one username: each
1214+ // school's `ayse` is reachable in her own school and *nowhere else*. A
1215+ // bridge that resolved the principal against the wrong database would
1216+ // answer one of the cross reads with a user instead of `unknown_user`.
1217+ let bridge = bridge().await;
1218+ let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
1219+ await_workers(&bridge, 1).await;
1220+ let (_app, _tenants, demo_ayse, beta_ayse) = two_schools(&bridge).await;
1221+
1222+ for (school, who) in [("demo", &demo_ayse), ("beta", &beta_ayse)] {
1223+ let (answer, _) = raw::api_read(
1224+ &service.conn,
1225+ format!(r#"{{"id":"t-own","school":"{school}","path":"/auth/me","on_behalf_of":"{who}"}}"#)
1226+ .as_bytes(),
1227+ )
1228+ .await;
1229+ assert_eq!(answer["outcome"], "ok", "{answer}");
1230+ assert_eq!(answer["school"], school, "the school is echoed: {answer}");
1231+ assert_eq!(answer["body"]["id"], who.as_str(), "{answer}");
1232+ assert_eq!(answer["body"]["username"], "ayse");
1233+ }
1234+
1235+ // And crossed over: the other school's id names nobody here.
1236+ for (school, who) in [("demo", &beta_ayse), ("beta", &demo_ayse)] {
1237+ let (answer, _) = raw::api_read(
1238+ &service.conn,
1239+ format!(
1240+ r#"{{"id":"t-cross","school":"{school}","path":"/auth/me","on_behalf_of":"{who}"}}"#
1241+ )
1242+ .as_bytes(),
1243+ )
1244+ .await;
1245+ assert_eq!(
1246+ answer["code"], "unknown_user",
1247+ "a user id from another school resolved in `{school}`: {answer}"
1248+ );
1249+ }
1250+}
1251+
1252+#[tokio::test]
1253+async fn a_suspended_school_is_refused_with_its_own_code() {
1254+ // Distinct from `unknown_school` on purpose: this deployment does serve
1255+ // `beta`, it is switched off — the one refusal here worth retrying later.
1256+ let bridge = bridge().await;
1257+ let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
1258+ await_workers(&bridge, 1).await;
1259+ let (_app, tenants, _demo_ayse, beta_ayse) = two_schools(&bridge).await;
1260+
1261+ let read = format!(
1262+ r#"{{"id":"t-susp","school":"beta","path":"/auth/me","on_behalf_of":"{beta_ayse}"}}"#
1263+ );
1264+ let (answer, _) = raw::api_read(&service.conn, read.as_bytes()).await;
1265+ assert_eq!(answer["outcome"], "ok", "the school starts out active");
1266+
1267+ tenants
1268+ .set_status(&Slug::try_new("beta").unwrap(), SchoolStatus::Suspended)
1269+ .await
1270+ .expect("suspend beta");
1271+
1272+ let (answer, _) = raw::api_read(&service.conn, read.as_bytes()).await;
1273+ assert_eq!(answer["outcome"], "err", "{answer}");
1274+ assert_eq!(answer["code"], "school_suspended", "{answer}");
1275+ assert_eq!(answer["school"], "beta", "the refusal names the school back");
1276+ assert_eq!(answer["id"], "t-susp");
1277+
1278+ // The demo school is untouched by its neighbour's suspension.
1279+ let (answer, _) = raw::api_read(
1280+ &service.conn,
1281+ br#"{"id":"t-neighbour","school":"demo","path":"/auth/me"}"#,
1282+ )
1283+ .await;
1284+ assert_eq!(answer["outcome"], "ok", "{answer}");
1285+}
1286+
1287+#[tokio::test]
1288+async fn a_blob_read_names_its_school_too() {
1289+ // The blob path resolves the school independently of the api path, and its
1290+ // refusals are the same three codes — so it gets the same proof.
1291+ let bridge = bridge().await;
1292+ let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await;
1293+ await_workers(&bridge, 1).await;
1294+ let (_app, student, file, uploaded) = armed_with_file(&bridge).await;
1295+
1296+ let (header, _, body) = raw::blob_read(
1297+ &service.conn,
1298+ format!(r#"{{"id":"t-b1","school":"{SCHOOL}","file":"{file}","on_behalf_of":"{student}"}}"#)
1299+ .as_bytes(),
1300+ )
1301+ .await;
1302+ assert_eq!(header["status"], "ok", "{header}");
1303+ assert_eq!(body.len(), uploaded.len());
1304+
1305+ for (school, code) in [("nope", "unknown_school"), ("NOT A SLUG", "malformed")] {
1306+ let (header, _, body) = raw::blob_read(
1307+ &service.conn,
1308+ format!(
1309+ r#"{{"id":"t-b2","school":"{school}","file":"{file}","on_behalf_of":"{student}"}}"#
1310+ )
1311+ .as_bytes(),
1312+ )
1313+ .await;
1314+ assert_eq!(header["status"], "err", "{header}");
1315+ assert_eq!(header["code"], code, "{header}");
1316+ assert!(body.is_empty(), "a refused blob stream carries no bytes");
1317+ }
1318+
1319+ // And with no school named at all the frame does not parse.
1320+ let (header, _, _) = raw::blob_read(
1321+ &service.conn,
1322+ format!(r#"{{"id":"t-b3","file":"{file}","on_behalf_of":"{student}"}}"#).as_bytes(),
1323+ )
1324+ .await;
1325+ assert_eq!(header["code"], "malformed", "{header}");
1326+}
1327+
11421328 // --------------------------------------------------- blob stream contract --
11431329 //
11441330 // The bytes behind a course-note attachment, which no JSON frame can carry.
@@ -1198,7 +1384,7 @@ async fn the_blob_header_frame_carries_exactly_the_published_keys_then_size_byte
11981384 let (header, bytes, body) = raw::blob_read(
11991385 &service.conn,
12001386 format!(
1201- r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","file":"{file}","on_behalf_of":"{student}"}}"#
1387+ r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","school":"{SCHOOL}","file":"{file}","on_behalf_of":"{student}"}}"#
12021388 )
12031389 .as_bytes(),
12041390 )
@@ -1206,7 +1392,7 @@ async fn the_blob_header_frame_carries_exactly_the_published_keys_then_size_byte
12061392
12071393 assert_eq!(
12081394 raw::keys(&header),
1209- ["content_type", "id", "name", "size", "status"],
1395+ ["content_type", "id", "name", "school", "size", "status"],
12101396 "blob header shape changed: {header}"
12111397 );
12121398 assert_eq!(header["status"], "ok");
@@ -1241,12 +1427,15 @@ async fn a_blob_refusal_frame_carries_exactly_the_published_keys_and_no_bytes()
12411427
12421428 let (header, _, body) = raw::blob_read(
12431429 &service.conn,
1244- format!(r#"{{"id":"t-blob","file":"01NOSUCHFILE","on_behalf_of":"{student}"}}"#).as_bytes(),
1430+ format!(
1431+ r#"{{"id":"t-blob","school":"{SCHOOL}","file":"01NOSUCHFILE","on_behalf_of":"{student}"}}"#
1432+ )
1433+ .as_bytes(),
12451434 )
12461435 .await;
12471436 assert_eq!(
12481437 raw::keys(&header),
1249- ["code", "id", "message", "status"],
1438+ ["code", "id", "message", "school", "status"],
12501439 "blob refusal shape changed: {header}"
12511440 );
12521441 assert_eq!(header["status"], "err");
@@ -1270,7 +1459,8 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() {
12701459
12711460 let (answer, _) = raw::api_read(
12721461 &service.conn,
1273- format!(r#"{{"id":"t-api","path":"/auth/me","on_behalf_of":"{student}"}}"#).as_bytes(),
1462+ format!(r#"{{"id":"t-api","school":"{SCHOOL}","path":"/auth/me","on_behalf_of":"{student}"}}"#)
1463+ .as_bytes(),
12741464 )
12751465 .await;
12761466 assert_eq!(answer["outcome"], "ok", "{answer}");
@@ -1282,7 +1472,7 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() {
12821472 let (answer, _) = raw::api_read(
12831473 &service.conn,
12841474 format!(
1285- r#"{{"id":"t-both","path":"/auth/me","file":"{file}","on_behalf_of":"{student}"}}"#
1475+ r#"{{"id":"t-both","school":"{SCHOOL}","path":"/auth/me","file":"{file}","on_behalf_of":"{student}"}}"#
12861476 )
12871477 .as_bytes(),
12881478 )
@@ -1291,7 +1481,7 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() {
12911481 assert_eq!(answer["status"], 200);
12921482
12931483 // Neither shape: still the api read's refusal, with its `outcome` tag.
1294- let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither"}"#).await;
1484+ let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither","school":"demo"}"#).await;
12951485 assert_eq!(answer["outcome"], "err", "{answer}");
12961486 assert_eq!(answer["code"], "malformed");
12971487 assert_eq!(answer["id"], "t-neither");
tests/common/mod.rsmodified+20 -1
@@ -94,6 +94,12 @@ pub async fn app_with_ai(ai: Option<AiBridge>) -> (Router, Database) {
9494 app_with_ai_health(ai, Default::default()).await
9595 }
9696
97+/// [`app_with_ai`] plus the registry behind it, for the suites whose subject is
98+/// an AI service reading *across* schools.
99+pub async fn app_with_ai_tenants(ai: Option<AiBridge>) -> (Router, Database, Tenants) {
100+ app_parts(ai, Default::default()).await
101+}
102+
97103 /// [`app_with_ai`] with the liveness flag handed in, so a test can take the
98104 /// database socket down under a running app — the api-read path re-checks it in
99105 /// place of the HTTP db guard it bypasses.
@@ -148,7 +154,20 @@ pub async fn set_role(db: &Database, username: &str, role: &str) {
148154 /// Register (password `secret1`), promote to `role`, then log in. Returns the
149155 /// session `Cookie` value.
150156 pub async fn login_as(app: &Router, db: &Database, username: &str, role: &str) -> String {
151- let creds = json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" });
157+ login_as_school(app, db, DEMO_SLUG, username, role).await
158+}
159+
160+/// [`login_as`] in a named school. `db` must be that school's own handle — the
161+/// role is written where the user was created, which is what makes two schools
162+/// able to hold the same username independently.
163+pub async fn login_as_school(
164+ app: &Router,
165+ db: &Database,
166+ school: &str,
167+ username: &str,
168+ role: &str,
169+) -> String {
170+ let creds = json!({ "school": school, "username": username, "password": "secret1" });
152171 let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await;
153172 assert_eq!(reg.status, StatusCode::CREATED, "register {username}");
154173 set_role(db, username, role).await;
tests/e2e.rsmodified+1 -0
@@ -1797,6 +1797,7 @@ async fn chat_service(text: &str) -> ChatService {
17971797 };
17981798 let response = AiResponse::Ok {
17991799 id: request.id.clone(),
1800+ school: request.school.clone(),
18001801 payload: json!({ "text": answer }),
18011802 };
18021803 let _ = write_frame(&mut send, &response).await;