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.
3503 3503
3504 ### Handshake3504 ### Handshake
3505 3505
3506-The service connects with ALPN `hab/1`, then opens the **control stream** (the3506+The service connects with ALPN `hab/2`, then opens the **control stream** (the
3507 first client-initiated bidi stream) and writes one `Hello`:3507 first client-initiated bidi stream) and writes one `Hello`:
3508 3508
3509 ```json3509 ```json
3510-{ "protocol": "hab/1", "service": "ocr", "capabilities": ["ocr.extract"],3510+{ "protocol": "hab/2", "service": "ocr", "capabilities": ["ocr.extract"],
3511 "token": "<AI_SHARED_TOKEN>", "max_concurrent": 8 }3511 "token": "<AI_SHARED_TOKEN>", "max_concurrent": 8 }
3512 ```3512 ```
3513 3513
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:
3515 3516
3516 ```json3517 ```json
3517-{ "type": "welcome", "worker_id": "01J...", "protocol": "hab/1" }3518+{ "type": "welcome", "worker_id": "01J...", "protocol": "hab/2" }
3518 { "type": "rejected", "code": "unauthorized", "message": "invalid token" }3519 { "type": "rejected", "code": "unauthorized", "message": "invalid token" }
3519 ```3520 ```
3520 3521
@@ -3529,23 +3530,52 @@ timeout (30s, with a 10s keepalive) and deregistered then.
3529 `max_concurrent` is advisory and clamped to `1..=64` (default 8). Requests3530 `max_concurrent` is advisory and clamped to `1..=64` (default 8). Requests
3530 beyond it are refused with "busy" rather than queued.3531 beyond it are refused with "busy" rather than queued.
3531 3532
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+
3532 ### Requests3560 ### Requests
3533 3561
3534 For each request the **backend** opens a bidi stream, writes one `Request`,3562 For each request the **backend** opens a bidi stream, writes one `Request`,
3535 finishes its send side, and reads one `Response`:3563 finishes its send side, and reads one `Response`:
3536 3564
3537 ```json3565 ```json
3538-{ "id": "01J...", "capability": "ocr.extract", "deadline_ms": 30000,3566+{ "id": "01J...", "school": "demo", "capability": "ocr.extract",
3539- "payload": { "image": "<base64>" } }3567+ "deadline_ms": 30000, "payload": { "image": "<base64>" } }
3540 ```3568 ```
3541 3569
3542 ```json3570 ```json
3543-{ "status": "ok", "id": "01J...", "payload": { "text": "..." } }3571+{ "status": "ok", "id": "01J...", "school": "demo",
3544-{ "status": "err", "id": "01J...", "code": "unsupported_image",3572+ "payload": { "text": "..." } }
3545- "message": "only png and jpeg" }3573+{ "status": "err", "id": "01J...", "school": "demo",
3574+ "code": "unsupported_image", "message": "only png and jpeg" }
3546 ```3575 ```
3547 3576
3548-`id` is a trace id for logs on both sides — correlation is the stream, not the3577+`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
3549 id. It must still be echoed: an answer carrying a different id means the3579 id. It must still be echoed: an answer carrying a different id means the
3550 service lost track of whose work it is, and the payload is refused. `payload`3580 service lost track of whose work it is, and the payload is refused. `payload`
3551 is opaque to the transport; its shape belongs to the capability.3581 is opaque to the transport; its shape belongs to the capability.
@@ -3563,15 +3593,17 @@ already has.
3563 3593
3564 After the handshake the *service* may open further bidi streams, one per read:3594 After the handshake the *service* may open further bidi streams, one per read:
3565 write one `ApiRequest`, finish the send side, read one `ApiResponse`, done.3595 write one `ApiRequest`, finish the send side, read one `ApiResponse`, done.
3566-Same framing as every other `hab/1` frame; concurrency and correlation are the3596+Same framing as every other `hab/2` frame; concurrency and correlation are the
3567 stream, exactly as for capability requests.3597 stream, exactly as for capability requests.
3568 3598
3569 ```json3599 ```json
3570-{ "id": "01J...", "path": "/marks/me", "query": "limit=10&offset=0",3600+{ "id": "01J...", "school": "demo", "path": "/marks/me",
3571- "on_behalf_of": "user:01J...", "method": "GET" }3601+ "query": "limit=10&offset=0", "on_behalf_of": "user:01J...",
3602+ "method": "GET" }
3572 ```3603 ```
3573 3604
3574-`id` is a trace id, echoed back. `path` is the path alone as the REST API3605+`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
3575 spells it — no host, and **no query string**, which travels in `query` (without3607 spells it — no host, and **no query string**, which travels in `query` (without
3576 the leading `?`). `query`, `on_behalf_of` and `method` are all optional; an3608 the leading `?`). `query`, `on_behalf_of` and `method` are all optional; an
3577 absent `method` means `GET`, and anything else is refused.3609 absent `method` means `GET`, and anything else is refused.
@@ -3579,8 +3611,10 @@ absent `method` means `GET`, and anything else is refused.
3579 The answer is tagged by `outcome`:3611 The answer is tagged by `outcome`:
3580 3612
3581 ```json3613 ```json
3582-{ "outcome": "ok", "id": "01J...", "status": 200, "body": { } }3614+{ "outcome": "ok", "id": "01J...", "school": "demo", "status": 200,
3583-{ "outcome": "err", "id": "01J...", "code": "path_not_allowed",3615+ "body": { } }
3616+{ "outcome": "err", "id": "01J...", "school": "demo",
3617+ "code": "path_not_allowed",
3584 "message": "`/users` is not a path AI services may read" }3618 "message": "`/users` is not a path AI services may read" }
3585 ```3619 ```
3586 3620
@@ -3592,16 +3626,19 @@ failure has misread the contract.
3592 3626
3593 | `code` | Meaning |3627 | `code` | Meaning |
3594 | ------ | ------- |3628 | ------ | ------- |
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 |
3596 | `method_not_allowed` | `method` was present and was not `GET` |3630 | `method_not_allowed` | `method` was present and was not `GET` |
3597 | `path_not_allowed` | `path` is not in the read scope below |3631 | `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) |
3599 | `unavailable` | The API is not serving yet, the database socket is down, or the read outran the request timeout — retryable |3635 | `unavailable` | The API is not serving yet, the database socket is down, or the read outran the request timeout — retryable |
3600 | `not_json` | The endpoint answered with a body that is not JSON |3636 | `not_json` | The endpoint answered with a body that is not JSON |
3601 | `too_large` | The answer does not fit one frame |3637 | `too_large` | The answer does not fit one frame |
3602 3638
3603 Refusals are decided in that order — method, then the allowlist, then the3639 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.
3605 3642
3606 #### The read scope3643 #### The read scope
3607 3644
@@ -3637,7 +3674,8 @@ With `on_behalf_of`, the read executes **as that user**: own-scoped endpoints
3637 (`/auth/me`, `/notes`, `/marks/me`) return *their* data. Both spellings are3674 (`/auth/me`, `/notes`, `/marks/me`) return *their* data. Both spellings are
3638 accepted — the bare key (`01J...`, as a REST path writes it) and the record3675 accepted — the bare key (`01J...`, as a REST path writes it) and the record
3639 form (`user:01J...`). The account is loaded live from the database on every3676 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 acts3677+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
3641 as a user who has since been deleted (`unknown_user`) or demoted (the new role,3679 as a user who has since been deleted (`unknown_user`) or demoted (the new role,
3642 not the old one) — never as who they used to be.3680 not the old one) — never as who they used to be.
3643 3681
@@ -3663,11 +3701,13 @@ the shape differs, and the two are told apart by the field each *requires*: an
3663 `ApiRequest` has `path`, a `BlobRequest` has `file`.3701 `ApiRequest` has `path`, a `BlobRequest` has `file`.
3664 3702
3665 ```json3703 ```json
3666-{ "id": "01J...", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V",3704+{ "id": "01J...", "school": "demo", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V",
3667 "on_behalf_of": "user:01J..." }3705 "on_behalf_of": "user:01J..." }
3668 ```3706 ```
3669 3707
3670-`file` is a `course_note_file` record key — the id `GET3708+`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
3671 /course-notes/{id}/files` publishes and the one every `rag.index` payload3711 /course-notes/{id}/files` publishes and the one every `rag.index` payload
3672 carries in `files[].id`. `on_behalf_of` is optional on the wire but required in3712 carries in `files[].id`. `on_behalf_of` is optional on the wire but required in
3673 practice: without it the principal is the `ai` role, which is enrolled in3713 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
3679 no HTTP status to collide with:3719 no HTTP status to collide with:
3680 3720
3681 ```json3721 ```json
3682-{ "status": "ok", "id": "01J...", "name": "recap.pdf",3722+{ "status": "ok", "id": "01J...", "school": "demo", "name": "recap.pdf",
3683 "content_type": "application/pdf", "size": 204800 }3723 "content_type": "application/pdf", "size": 204800 }
3684-{ "status": "err", "id": "01J...", "code": "forbidden",3724+{ "status": "err", "id": "01J...", "school": "demo", "code": "forbidden",
3685 "message": "`01J...` may not view the course this file belongs to" }3725 "message": "`01J...` may not view the course this file belongs to" }
3686 ```3726 ```
3687 3727
@@ -3699,9 +3739,11 @@ slow-but-reading service is never cut off.
3699 3739
3700 | `code` | Meaning |3740 | `code` | Meaning |
3701 | ------ | ------- |3741 | ------ | ------- |
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 |
3703 | `forbidden` | The principal may not view that file's course |3744 | `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 |
3705 | `unavailable` | The api is not serving yet, the database socket is down, or the row's blob is missing from disk — retryable |3747 | `unavailable` | The api is not serving yet, the database socket is down, or the row's blob is missing from disk — retryable |
3706 3748
3707 **Course-note attachments only.** The key is looked up in `course_note_file`3749 **Course-note attachments only.** The key is looked up in `course_note_file`
@@ -3738,11 +3780,12 @@ not retryable), `Protocol` / `IdMismatch` (broken peer), `Transport`.
3738 ### Conformance suite3780 ### Conformance suite
3739 3781
3740 `tests/ai_protocol.rs` is the wire contract, enforced on every `cargo test`. It3782 `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 —
3742 frames built as byte literals, answers parsed as untyped JSON — so it fails on3784 frames built as byte literals, answers parsed as untyped JSON — so it fails on
3743 exactly the changes a service in another language would notice: a renamed3785 exactly the changes a service in another language would notice: a renamed
3744 field, a re-tagged enum, a flipped length-prefix endianness, a newly-required3786 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 shares3787+`Hello` field, a frame that stopped naming its school. (`tests/ai_bridge.rs`
3788+drives real QUIC clients too, but shares
3746 the Rust structs with the backend, so it cannot see those.)3789 the Rust structs with the backend, so it cannot see those.)
3747 3790
3748 It is also the reference implementation: its `raw` module is the whole client3791 It is also the reference implementation: its `raw` module is the whole client
@@ -3773,7 +3816,7 @@ published over HTTP:
3773 3816
3774 ```3817 ```
3775 GET /ai/certificate # no auth; 404 when the bridge is disabled3818 GET /ai/certificate # no auth; 404 when the bridge is disabled
3776-{ "protocol": "hab/1",3819+{ "protocol": "hab/2",
3777 "certificate_pem": "-----BEGIN CERTIFICATE-----\n...",3820 "certificate_pem": "-----BEGIN CERTIFICATE-----\n...",
3778 "fingerprint_sha256": "6745e8..." }3821 "fingerprint_sha256": "6745e8..." }
3779 ```3822 ```
@@ -3846,7 +3889,7 @@ closes. A stream opened *after* the answer already landed still emits
3846 `delta`s and a `done` — the replay is deliberate, so a client that connects3889 `delta`s and a `done` — the replay is deliberate, so a client that connects
3847 late (or reconnects) never hangs waiting for events that already happened.3890 late (or reconnects) never hangs waiting for events that already happened.
3848 3891
3849-**The deltas are sliced by the backend from the finished answer.** `hab/1` is3892+**The deltas are sliced by the backend from the finished answer.** `hab/2` is
3850 unary — the service returns the whole reply text, not tokens — so today the3893 unary — the service returns the whole reply text, not tokens — so today the
3851 chunking is cosmetic pacing, not real streaming. The event shape exists now so3894 chunking is cosmetic pacing, not real streaming. The event shape exists now so
3852 that the day a service streams, it becomes a drop-in change behind an3895 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.
3922 ### The `chat.reply` capability (for AI-service authors)3965 ### The `chat.reply` capability (for AI-service authors)
3923 3966
3924 A chat service declares `chat.reply` in its `Hello` (see "AI bridge (QUIC)").3967 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:
3926 3970
3927 ```json3971 ```json
3928 { "message": "and the second law?",3972 { "message": "and the second law?",
@@ -3969,7 +4013,8 @@ context without either end having to be redeployed in lockstep.
3969 An indexing service declares `rag.index` in its `Hello` (see "AI bridge4013 An indexing service declares `rag.index` in its `Hello` (see "AI bridge
3970 (QUIC)"). The backend dispatches one request whenever a course note is4014 (QUIC)"). The backend dispatches one request whenever a course note is
3971 created, edited, or gains or loses a file — never on a read. Requests arrive4015 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:
3973 4018
3974 ```json4019 ```json
3975 { "course_note": "01J8XZ0K3Q8G7X2M4N5P6R7S8T",4020 { "course_note": "01J8XZ0K3Q8G7X2M4N5P6R7S8T",
@@ -4560,5 +4605,5 @@ db), rate-limit (both tiers, proxy-header and peer-address keying, shipped
4560 limits over every route, two limiters sharing one budget over one db), e2e4605 limits over every route, two limiters sharing one budget over one db), e2e
4561 (real TCP + reqwest cookie jar), persistence4606 (real TCP + reqwest cookie jar), persistence
4562 (tempfile file engine, including close + reopen), ai-bridge (real QUIC on4607 (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,
4564 driven by a client that shares no code with the backend).4609 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).
2 //!2 //!
3 //! # Shape3 //! # Shape
4 //!4 //!
@@ -33,6 +33,19 @@
33 //! The two client-initiated request shapes are told apart by their required33 //! The two client-initiated request shapes are told apart by their required
34 //! field: an [`ApiRequest`] has `path`, a [`BlobRequest`] has `file`.34 //! field: an [`ApiRequest`] has `path`, a [`BlobRequest`] has `file`.
35 //!35 //!
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+//!
36 //! There is deliberately no correlation-id matching: QUIC stream IDs already49 //! There is deliberately no correlation-id matching: QUIC stream IDs already
37 //! multiplex concurrent requests over the one connection, independently50 //! multiplex concurrent requests over the one connection, independently
38 //! flow-controlled, with no head-of-line blocking between them. [`Request::id`]51 //! flow-controlled, with no head-of-line blocking between them. [`Request::id`]
@@ -65,6 +78,10 @@ pub enum FrameError {
65 }78 }
66 79
67 /// The service's opening frame on the control stream.80 /// 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").
68 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]85 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69 pub struct Hello {86 pub struct Hello {
70 /// Must equal [`crate::constant::AI_PROTOCOL`]; anything else is rejected87 /// Must equal [`crate::constant::AI_PROTOCOL`]; anything else is rejected
@@ -118,6 +135,9 @@ pub enum RejectCode {
118 pub struct Request {135 pub struct Request {
119 /// Trace id (ULID). Not used for correlation — the stream does that.136 /// Trace id (ULID). Not used for correlation — the stream does that.
120 pub id: String,137 pub id: String,
138+ /// Slug of the school this work belongs to. Required — see this module's
139+ /// "School scoping".
140+ pub school: String,
121 /// Which capability from the worker's [`Hello::capabilities`] to invoke.141 /// Which capability from the worker's [`Hello::capabilities`] to invoke.
122 pub capability: String,142 pub capability: String,
123 /// How long the backend will wait before abandoning the stream. The143 /// How long the backend will wait before abandoning the stream. The
@@ -135,10 +155,14 @@ pub struct Request {
135 pub enum Response {155 pub enum Response {
136 Ok {156 Ok {
137 id: String,157 id: String,
158+ /// Echo of [`Request::school`].
159+ school: String,
138 payload: Value,160 payload: Value,
139 },161 },
140 Err {162 Err {
141 id: String,163 id: String,
164+ /// Echo of [`Request::school`].
165+ school: String,
142 /// Service-defined, stable, machine-readable (`"unsupported_image"`).166 /// Service-defined, stable, machine-readable (`"unsupported_image"`).
143 code: String,167 code: String,
144 message: String,168 message: String,
@@ -151,6 +175,9 @@ pub enum Response {
151 pub struct ApiRequest {175 pub struct ApiRequest {
152 /// Trace id (ULID). Not used for correlation — the stream does that.176 /// Trace id (ULID). Not used for correlation — the stream does that.
153 pub id: String,177 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,
154 /// Path as the REST API spells it, e.g. `"/users/me"`. No host, no query.181 /// Path as the REST API spells it, e.g. `"/users/me"`. No host, no query.
155 pub path: String,182 pub path: String,
156 /// Query string without the leading `?`, e.g. `"limit=10&offset=0"`.183 /// Query string without the leading `?`, e.g. `"limit=10&offset=0"`.
@@ -174,13 +201,20 @@ pub struct ApiRequest {
174 pub enum ApiResponse {201 pub enum ApiResponse {
175 Ok {202 Ok {
176 id: String,203 id: String,
204+ /// Echo of [`ApiRequest::school`].
205+ school: String,
177 /// HTTP status the router produced.206 /// HTTP status the router produced.
178 status: u16,207 status: u16,
179 body: Value,208 body: Value,
180 },209 },
181 Err {210 Err {
182 id: String,211 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"`).
184 code: String,218 code: String,
185 message: String,219 message: String,
186 },220 },
@@ -193,6 +227,9 @@ pub enum ApiResponse {
193 pub struct BlobRequest {227 pub struct BlobRequest {
194 /// Trace id (ULID). Not used for correlation — the stream does that.228 /// Trace id (ULID). Not used for correlation — the stream does that.
195 pub id: String,229 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,
196 /// The `course_note_file` record key, as `GET /course-notes/{id}/files`233 /// The `course_note_file` record key, as `GET /course-notes/{id}/files`
197 /// and the `rag.index` payload both publish it.234 /// and the `rag.index` payload both publish it.
198 pub file: String,235 pub file: String,
@@ -210,6 +247,8 @@ pub struct BlobRequest {
210 pub enum BlobResponse {247 pub enum BlobResponse {
211 Ok {248 Ok {
212 id: String,249 id: String,
250+ /// Echo of [`BlobRequest::school`].
251+ school: String,
213 name: String,252 name: String,
214 content_type: String,253 content_type: String,
215 /// Exactly how many raw bytes follow this frame.254 /// Exactly how many raw bytes follow this frame.
@@ -217,6 +256,8 @@ pub enum BlobResponse {
217 },256 },
218 Err {257 Err {
219 id: String,258 id: String,
259+ /// Echo of the school the frame named, as sent.
260+ school: String,
220 /// Bridge-defined, stable, machine-readable (`"not_found"`).261 /// Bridge-defined, stable, machine-readable (`"not_found"`).
221 code: String,262 code: String,
222 message: String,263 message: String,
@@ -313,10 +354,12 @@ mod tests {
313 let (mut client, mut server) = tokio::io::duplex(64 * 1024);354 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
314 let a = Response::Ok {355 let a = Response::Ok {
315 id: "a".into(),356 id: "a".into(),
357+ school: "demo".into(),
316 payload: json!({ "n": 1 }),358 payload: json!({ "n": 1 }),
317 };359 };
318 let b = Response::Err {360 let b = Response::Err {
319 id: "b".into(),361 id: "b".into(),
362+ school: "demo".into(),
320 code: "bad_input".into(),363 code: "bad_input".into(),
321 message: "nope".into(),364 message: "nope".into(),
322 };365 };
@@ -394,6 +437,7 @@ mod tests {
394 assert_eq!(rejected["code"], "unauthorized");437 assert_eq!(rejected["code"], "unauthorized");
395 let ok = serde_json::to_value(Response::Ok {438 let ok = serde_json::to_value(Response::Ok {
396 id: "1".into(),439 id: "1".into(),
440+ school: "demo".into(),
397 payload: json!(null),441 payload: json!(null),
398 })442 })
399 .unwrap();443 .unwrap();
@@ -406,6 +450,7 @@ mod tests {
406 // The tag is `outcome`, not `status` — `status` is the HTTP code.450 // The tag is `outcome`, not `status` — `status` is the HTTP code.
407 let ok = serde_json::to_value(ApiResponse::Ok {451 let ok = serde_json::to_value(ApiResponse::Ok {
408 id: "1".into(),452 id: "1".into(),
453+ school: "demo".into(),
409 status: 404,454 status: 404,
410 body: json!(null),455 body: json!(null),
411 })456 })
@@ -414,6 +459,7 @@ mod tests {
414 assert_eq!(ok["status"], 404);459 assert_eq!(ok["status"], 404);
415 let err = serde_json::to_value(ApiResponse::Err {460 let err = serde_json::to_value(ApiResponse::Err {
416 id: "1".into(),461 id: "1".into(),
462+ school: "demo".into(),
417 code: "path_not_allowed".into(),463 code: "path_not_allowed".into(),
418 message: "nope".into(),464 message: "nope".into(),
419 })465 })
@@ -423,18 +469,26 @@ mod tests {
423 }469 }
424 470
425 #[tokio::test]471 #[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() {
427 let bare: ApiRequest = serde_json::from_value(json!({473 let bare: ApiRequest = serde_json::from_value(json!({
428 "id": "01J",474 "id": "01J",
475+ "school": "demo",
429 "path": "/users/me",476 "path": "/users/me",
430 }))477 }))
431 .unwrap();478 .unwrap();
432 assert_eq!(bare.query, None);479 assert_eq!(bare.query, None);
433 assert_eq!(bare.on_behalf_of, None);480 assert_eq!(bare.on_behalf_of, None);
434 assert_eq!(bare.method, None);481 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+ );
435 488
436 let full = ApiRequest {489 let full = ApiRequest {
437 id: "01J".into(),490 id: "01J".into(),
491+ school: "demo".into(),
438 path: "/notes".into(),492 path: "/notes".into(),
439 query: Some("limit=10".into()),493 query: Some("limit=10".into()),
440 on_behalf_of: Some("user:abc".into()),494 on_behalf_of: Some("user:abc".into()),
@@ -442,6 +496,7 @@ mod tests {
442 method: Some("GET".into()),496 method: Some("GET".into()),
443 };497 };
444 let raw = serde_json::to_value(&full).unwrap();498 let raw = serde_json::to_value(&full).unwrap();
499+ assert_eq!(raw["school"], "demo");
445 assert_eq!(raw["path"], "/notes");500 assert_eq!(raw["path"], "/notes");
446 assert_eq!(raw["query"], "limit=10");501 assert_eq!(raw["query"], "limit=10");
447 assert_eq!(raw["on_behalf_of"], "user:abc");502 assert_eq!(raw["on_behalf_of"], "user:abc");
@@ -456,6 +511,7 @@ mod tests {
456 // carries no HTTP status for it to collide with.511 // carries no HTTP status for it to collide with.
457 let ok = serde_json::to_value(BlobResponse::Ok {512 let ok = serde_json::to_value(BlobResponse::Ok {
458 id: "1".into(),513 id: "1".into(),
514+ school: "demo".into(),
459 name: "recap.pdf".into(),515 name: "recap.pdf".into(),
460 content_type: "application/pdf".into(),516 content_type: "application/pdf".into(),
461 size: 204_800,517 size: 204_800,
@@ -465,6 +521,7 @@ mod tests {
465 assert_eq!(ok["size"], 204_800);521 assert_eq!(ok["size"], 204_800);
466 let err = serde_json::to_value(BlobResponse::Err {522 let err = serde_json::to_value(BlobResponse::Err {
467 id: "1".into(),523 id: "1".into(),
524+ school: "demo".into(),
468 code: "not_found".into(),525 code: "not_found".into(),
469 message: "nope".into(),526 message: "nope".into(),
470 })527 })
@@ -475,14 +532,22 @@ mod tests {
475 // `file` is what tells a blob request apart from an api read, so it is532 // `file` is what tells a blob request apart from an api read, so it is
476 // required; `on_behalf_of` is the only optional field.533 // required; `on_behalf_of` is the only optional field.
477 let bare: BlobRequest = serde_json::from_value(json!({534 let bare: BlobRequest = serde_json::from_value(json!({
478- "id": "01J", "file": "01FILE",535+ "id": "01J", "school": "demo", "file": "01FILE",
479 }))536 }))
480 .unwrap();537 .unwrap();
481 assert_eq!(bare.on_behalf_of, None);538 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+ );
483 // And the two shapes never parse as each other.545 // And the two shapes never parse as each other.
484 assert!(546 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()
486 );551 );
487 }552 }
488 553
src/ai/rag.rsmodified+10 -3
@@ -20,6 +20,7 @@ use crate::domain::course_note::CourseNote;
20 use crate::domain::course_note_file::CourseNoteFile;20 use crate::domain::course_note_file::CourseNoteFile;
21 use crate::domain::rag_output::RagOutput;21 use crate::domain::rag_output::RagOutput;
22 use crate::state::AppState;22 use crate::state::AppState;
23+use crate::tenant::Slug;
23 24
24 /// The capability string routed to an indexing service. Defined once, in25 /// The capability string routed to an indexing service. Defined once, in
25 /// [`crate::constant`]; re-exported here so a reader of the payload contract26 /// [`crate::constant`]; re-exported here so a reader of the payload contract
@@ -80,7 +81,11 @@ impl RagIndexPayload {
80 /// Re-index `note` and replace its stored outputs with what the service81 /// Re-index `note` and replace its stored outputs with what the service
81 /// answered. Silent no-op when the bridge is off or no worker offers82 /// answered. Silent no-op when the bridge is off or no worker offers
82 /// `rag.index`.83 /// `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) {
84 let Some(bridge) = state.ai.as_ref() else {89 let Some(bridge) = state.ai.as_ref() else {
85 return;90 return;
86 };91 };
@@ -107,6 +112,7 @@ pub async fn index_course_note(state: &AppState, note: &CourseNote) {
107 112
108 let answer = match bridge113 let answer = match bridge
109 .dispatch_with_timeout(114 .dispatch_with_timeout(
115+ school,
110 AI_RAG_INDEX_CAPABILITY,116 AI_RAG_INDEX_CAPABILITY,
111 payload,117 payload,
112 std::time::Duration::from_secs(AI_RAG_INDEX_TIMEOUT_SECS),118 std::time::Duration::from_secs(AI_RAG_INDEX_TIMEOUT_SECS),
@@ -151,10 +157,11 @@ async fn replace(
151 157
152 /// [`index_course_note`] off the request path: the handler has already158 /// [`index_course_note`] off the request path: the handler has already
153 /// answered by the time the service is asked.159 /// 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) {
155 // Cheap when AI is off — the spawned task returns on the first `let else`.161 // Cheap when AI is off — the spawned task returns on the first `let else`.
156 let state = state.clone();162 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 });
158 }165 }
159 166
160 #[cfg(test)]167 #[cfg(test)]
src/ai/server.rsmodified+95 -56
@@ -24,6 +24,7 @@ use crate::constant::{
24 REQUEST_TIMEOUT_SECS,24 REQUEST_TIMEOUT_SECS,
25 };25 };
26 use crate::database::Database;26 use crate::database::Database;
27+use crate::error::AppError;
27 use crate::domain::course::Course;28 use crate::domain::course::Course;
28 use crate::domain::course_note::CourseNote;29 use crate::domain::course_note::CourseNote;
29 use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId};30 use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId};
@@ -50,40 +51,52 @@ pub struct BridgeConfig {
50 }51 }
51 52
52 /// What an api read needs to be answered: the router to dispatch into, the53 /// 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 that54+/// registry every school is resolved through, and the liveness flag that
54 /// stands in for the HTTP db guard this path bypasses.55 /// 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.
55 struct ApiHandle {59 struct ApiHandle {
56 router: axum::Router,60 router: axum::Router,
57 tenants: Tenants,61 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,
67 db_up: DbHealth,62 db_up: DbHealth,
68- /// Where uploaded blobs live — the deployment root; the school's own63+ /// Where uploaded blobs live — the deployment root; a school's own
69 /// directory is [`school_files_path`] of it.64 /// directory is [`school_files_path`] of it.
70 files_path: std::path::PathBuf,65 files_path: std::path::PathBuf,
71 }66 }
72 67
73 impl ApiHandle {68 impl ApiHandle {
74- /// The school database this bridge reads, or the refusal a service gets.69+ /// Resolve the slug a frame named into that school's database, or the
75- async fn db(&self) -> Result<Database, (&'static str, String)> {70+ /// refusal the service gets.
76- self.tenants.get(&self.slug).await.map_err(|err| {71+ ///
77- (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 => (
78 "unavailable",90 "unavailable",
79- format!("the `{}` school is not reachable: {err}", self.slug),91+ format!("the `{slug}` school is not reachable: {other}"),
80- )92+ ),
81- })93+ })?;
94+ Ok((slug, db))
82 }95 }
83 96
84- /// That school's blob directory.97+ /// One school's blob directory.
85- fn files_dir(&self) -> std::path::PathBuf {98+ fn files_dir(&self, slug: &Slug) -> std::path::PathBuf {
86- school_files_path(&self.files_path, &self.slug)99+ school_files_path(&self.files_path, slug)
87 }100 }
88 }101 }
89 102
@@ -188,8 +201,13 @@ impl AiBridge {
188 /// Each call takes a fresh QUIC bidirectional stream, so concurrent calls201 /// Each call takes a fresh QUIC bidirectional stream, so concurrent calls
189 /// over the same connection neither block nor interleave: the stream *is*202 /// over the same connection neither block nor interleave: the stream *is*
190 /// the correlation, and a slow one cannot stall a fast one.203 /// the correlation, and a slow one cannot stall a fast one.
191- pub async fn dispatch(&self, capability: &str, payload: Value) -> Result<Value, AiError> {204+ pub async fn dispatch(
192- self.dispatch_with_timeout(capability, payload, self.inner.request_timeout)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)
193 .await211 .await
194 }212 }
195 213
@@ -198,6 +216,7 @@ impl AiBridge {
198 /// generation).216 /// generation).
199 pub async fn dispatch_with_timeout(217 pub async fn dispatch_with_timeout(
200 &self,218 &self,
219+ school: &Slug,
201 capability: &str,220 capability: &str,
202 payload: Value,221 payload: Value,
203 timeout: Duration,222 timeout: Duration,
@@ -210,6 +229,7 @@ impl AiBridge {
210 let deadline_ms = timeout.as_millis().min(u64::MAX as u128) as u64;229 let deadline_ms = timeout.as_millis().min(u64::MAX as u128) as u64;
211 let request = Request {230 let request = Request {
212 id: id.clone(),231 id: id.clone(),
232+ school: school.as_str().to_string(),
213 capability: capability.to_string(),233 capability: capability.to_string(),
214 deadline_ms,234 deadline_ms,
215 payload,235 payload,
@@ -248,6 +268,7 @@ impl AiBridge {
248 id: got,268 id: got,
249 code,269 code,
250 message,270 message,
271+ ..
251 } if got == id => Err(AiError::Remote { code, message }),272 } if got == id => Err(AiError::Remote { code, message }),
252 // A mismatched id means the service is not tracking which stream it273 // A mismatched id means the service is not tracking which stream it
253 // is on. Nothing here depends on the id for correlation, but the274 // is on. Nothing here depends on the id for correlation, but the
@@ -278,7 +299,6 @@ impl AiBridge {
278 .set(ApiHandle {299 .set(ApiHandle {
279 router,300 router,
280 tenants,301 tenants,
281- slug: Slug::try_new(crate::tenant::DEMO_SLUG).expect("the demo slug is a slug"),
282 db_up,302 db_up,
283 files_path,303 files_path,
284 })304 })
@@ -369,17 +389,16 @@ async fn serve_client_stream(
369 Err(e) => {389 Err(e) => {
370 answer(390 answer(
371 &mut send,391 &mut send,
372- refusal(String::new(), "malformed", e.to_string()),392+ refusal(String::new(), String::new(), "malformed", e.to_string()),
373 )393 )
374 .await;394 .await;
375 return;395 return;
376 }396 }
377 };397 };
378- let id = raw398+ let id = string_field(&raw, "id");
379- .get("id")399+ // Echoed verbatim on a refusal, before it is known to be a slug at all:
380- .and_then(Value::as_str)400+ // it is how the service tells which of its in-flight reads was refused.
381- .unwrap_or_default()401+ let school = string_field(&raw, "school");
382- .to_string();
383 // Routed on the shape's required field rather than by parsing one and402 // Routed on the shape's required field rather than by parsing one and
384 // falling back to the other: that fallback cloned the whole `Value` on403 // falling back to the other: that fallback cloned the whole `Value` on
385 // every api read. `path` still wins when a frame carries both.404 // every api read. `path` still wins when a frame carries both.
@@ -387,9 +406,9 @@ async fn serve_client_stream(
387 let response = match serde_json::from_value::<ApiRequest>(raw) {406 let response = match serde_json::from_value::<ApiRequest>(raw) {
388 Ok(request) => match read_api(&inner, request).await {407 Ok(request) => match read_api(&inner, request).await {
389 Ok(response) => response,408 Ok(response) => response,
390- Err((code, message)) => refusal(id, code, message),409+ Err((code, message)) => refusal(id, school, code, message),
391 },410 },
392- Err(e) => refusal(id, "malformed", e.to_string()),411+ Err(e) => refusal(id, school, "malformed", e.to_string()),
393 };412 };
394 answer(&mut send, response).await;413 answer(&mut send, response).await;
395 return;414 return;
@@ -397,7 +416,7 @@ async fn serve_client_stream(
397 if raw.get("file").is_some() {416 if raw.get("file").is_some() {
398 match serde_json::from_value::<BlobRequest>(raw) {417 match serde_json::from_value::<BlobRequest>(raw) {
399 Ok(request) => serve_blob(&inner, &mut send, request).await,418 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,
401 }420 }
402 return;421 return;
403 }422 }
@@ -406,7 +425,16 @@ async fn serve_client_stream(
406 let api_err = serde_json::from_value::<ApiRequest>(raw)425 let api_err = serde_json::from_value::<ApiRequest>(raw)
407 .err()426 .err()
408 .map_or_else(String::new, |e| e.to_string());427 .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()
410 }438 }
411 439
412 /// Answer one blob read: the [`BlobResponse`] header frame, then — on `Ok` —440 /// Answer one blob read: the [`BlobResponse`] header frame, then — on `Ok` —
@@ -417,6 +445,7 @@ async fn serve_client_stream(
417 /// because such a thing does not fit a frame.445 /// because such a thing does not fit a frame.
418 async fn serve_blob(inner: &Inner, send: &mut quinn::SendStream, request: BlobRequest) {446 async fn serve_blob(inner: &Inner, send: &mut quinn::SendStream, request: BlobRequest) {
419 let id = request.id.clone();447 let id = request.id.clone();
448+ let school = request.school.clone();
420 match open_blob(inner, request).await {449 match open_blob(inner, request).await {
421 Ok((header, mut file)) => {450 Ok((header, mut file)) => {
422 if let Err(e) = write_frame(send, &header).await {451 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
433 Err((code, message)) => {462 Err((code, message)) => {
434 let refused = BlobResponse::Err {463 let refused = BlobResponse::Err {
435 id,464 id,
465+ school,
436 code: code.to_string(),466 code: code.to_string(),
437 message,467 message,
438 };468 };
@@ -497,8 +527,8 @@ async fn open_blob(
497 "the database socket is down — retry".to_string(),527 "the database socket is down — retry".to_string(),
498 ));528 ));
499 }529 }
500- let db = api.db().await?;530+ let (slug, db) = api.school(&request.school).await?;
501- let user = principal(api, request.on_behalf_of.as_deref()).await?;531+ let user = principal(&db, request.on_behalf_of.as_deref()).await?;
502 532
503 let missing = || {533 let missing = || {
504 (534 (
@@ -534,7 +564,7 @@ async fn open_blob(
534 564
535 // The row exists but its blob does not: server-side damage (a lost volume565 // The row exists but its blob does not: server-side damage (a lost volume
536 // path), exactly as `download_file` reads it — not the service's `404`.566 // 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());
538 let handle = tokio::fs::File::open(&path).await.map_err(|e| {568 let handle = tokio::fs::File::open(&path).await.map_err(|e| {
539 (569 (
540 "unavailable",570 "unavailable",
@@ -555,6 +585,7 @@ async fn open_blob(
555 Ok((585 Ok((
556 BlobResponse::Ok {586 BlobResponse::Ok {
557 id: request.id,587 id: request.id,
588+ school: request.school,
558 name: file.get_name().as_str().to_string(),589 name: file.get_name().as_str().to_string(),
559 content_type: file.get_content_type().as_str().to_string(),590 content_type: file.get_content_type().as_str().to_string(),
560 size,591 size,
@@ -565,20 +596,18 @@ async fn open_blob(
565 596
566 /// Who a client-initiated read runs as.597 /// Who a client-initiated read runs as.
567 ///598 ///
568-/// Loaded live, never trusted from the frame: a service holding a stale id must599+/// Loaded live out of the *school's own* database — never the control one and
569-/// not act as a user who has since been deleted or demoted. With nobody named600+/// never trusted from the frame: a service holding a stale id must not act as a
570-/// the principal is the synthetic `ai` role.601+/// user who has since been deleted or demoted, nor as a same-named user of
571-async fn principal(602+/// another school. With nobody named the principal is the synthetic `ai` role.
572- api: &ApiHandle,603+async fn principal(db: &Database, on_behalf_of: Option<&str>) -> Result<User, (&'static str, String)> {
573- on_behalf_of: Option<&str>,
574-) -> Result<User, (&'static str, String)> {
575 let Some(who) = on_behalf_of else {604 let Some(who) = on_behalf_of else {
576 return Ok(User::ai_principal());605 return Ok(User::ai_principal());
577 };606 };
578 // Both the bare key (`abc`, as a REST path spells it) and the record form607 // Both the bare key (`abc`, as a REST path spells it) and the record form
579 // (`user:abc`) are accepted.608 // (`user:abc`) are accepted.
580 let key = who.strip_prefix("user:").unwrap_or(who);609 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)
582 .await611 .await
583 .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))?612 .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))?
584 .ok_or_else(|| ("unknown_user", format!("no user `{who}`")))613 .ok_or_else(|| ("unknown_user", format!("no user `{who}`")))
@@ -639,6 +668,7 @@ async fn dispatch_api(
639 ) -> Result<ApiResponse, (&'static str, String)> {668 ) -> Result<ApiResponse, (&'static str, String)> {
640 let ApiRequest {669 let ApiRequest {
641 id,670 id,
671+ school,
642 path,672 path,
643 query,673 query,
644 on_behalf_of,674 on_behalf_of,
@@ -655,10 +685,13 @@ async fn dispatch_api(
655 ));685 ));
656 }686 }
657 687
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?;
658 // The role itself is re-read again by the extractor on the dispatched692 // The role itself is re-read again by the extractor on the dispatched
659 // request; see [`principal`] for why it is never taken from the frame.693 // request; see [`principal`] for why it is never taken from the frame.
660- let db = api.db().await?;694+ let user = principal(&db, on_behalf_of.as_deref()).await?;
661- let user = principal(api, on_behalf_of.as_deref()).await?;
662 695
663 let target = match query.as_deref() {696 let target = match query.as_deref() {
664 Some(query) if !query.is_empty() => format!("{path}?{query}"),697 Some(query) if !query.is_empty() => format!("{path}?{query}"),
@@ -679,10 +712,7 @@ async fn dispatch_api(
679 dispatched.extensions_mut().insert(AiPrincipal(user));712 dispatched.extensions_mut().insert(AiPrincipal(user));
680 // The dispatched request carries no cookie, so the school is handed over713 // The dispatched request carries no cookie, so the school is handed over
681 // in the extension the shadow `State` reads first.714 // in the extension the shadow `State` reads first.
682- dispatched.extensions_mut().insert(TenantExt {715+ dispatched.extensions_mut().insert(TenantExt { slug, db });
683- slug: api.slug.clone(),
684- db,
685- });
686 716
687 let response = tokio::time::timeout(717 let response = tokio::time::timeout(
688 Duration::from_secs(REQUEST_TIMEOUT_SECS),718 Duration::from_secs(REQUEST_TIMEOUT_SECS),
@@ -718,12 +748,18 @@ async fn dispatch_api(
718 })?748 })?
719 };749 };
720 750
721- Ok(ApiResponse::Ok { id, status, body })751+ Ok(ApiResponse::Ok {
752+ id,
753+ school,
754+ status,
755+ body,
756+ })
722 }757 }
723 758
724-fn refusal(id: String, code: &str, message: String) -> ApiResponse {759+fn refusal(id: String, school: String, code: &str, message: String) -> ApiResponse {
725 ApiResponse::Err {760 ApiResponse::Err {
726 id,761 id,
762+ school,
727 code: code.to_string(),763 code: code.to_string(),
728 message,764 message,
729 }765 }
@@ -750,11 +786,13 @@ async fn write_answer<W: tokio::io::AsyncWrite + Unpin>(
750 response: &ApiResponse,786 response: &ApiResponse,
751 ) -> Result<(), FrameError> {787 ) -> Result<(), FrameError> {
752 let written = write_frame(w, response).await;788 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+ {
754 return write_frame(791 return write_frame(
755 w,792 w,
756 &refusal(793 &refusal(
757 id.clone(),794 id.clone(),
795+ school.clone(),
758 "too_large",796 "too_large",
759 format!("the answer exceeds the {AI_MAX_FRAME_BYTES}-byte frame limit"),797 format!("the answer exceeds the {AI_MAX_FRAME_BYTES}-byte frame limit"),
760 ),798 ),
@@ -896,7 +934,7 @@ mod tests {
896 refuse_before_dispatch,934 refuse_before_dispatch,
897 };935 };
898 use crate::ai::protocol::read_frame;936 use crate::ai::protocol::read_frame;
899- use crate::tenant::Slug;937+ use crate::tenant::DEMO_SLUG;
900 938
901 /// An armed handle serving `router`. The database is never touched by these939 /// An armed handle serving `router`. The database is never touched by these
902 /// reads (nobody is named, so the principal is synthetic), but the handle940 /// reads (nobody is named, so the principal is synthetic), but the handle
@@ -907,7 +945,6 @@ mod tests {
907 tenants: crate::database::init_mem_tenants()945 tenants: crate::database::init_mem_tenants()
908 .await946 .await
909 .expect("in-memory deployment"),947 .expect("in-memory deployment"),
910- slug: Slug::try_new(crate::tenant::DEMO_SLUG).unwrap(),
911 db_up: Default::default(),948 db_up: Default::default(),
912 files_path: std::env::temp_dir(),949 files_path: std::env::temp_dir(),
913 }950 }
@@ -917,6 +954,7 @@ mod tests {
917 fn read_of(path: &str) -> ApiRequest {954 fn read_of(path: &str) -> ApiRequest {
918 ApiRequest {955 ApiRequest {
919 id: "trace-1".to_string(),956 id: "trace-1".to_string(),
957+ school: DEMO_SLUG.to_string(),
920 path: path.to_string(),958 path: path.to_string(),
921 query: None,959 query: None,
922 on_behalf_of: None,960 on_behalf_of: None,
@@ -987,6 +1025,7 @@ mod tests {
987 // frame may precede it on the stream.1025 // frame may precede it on the stream.
988 let big = ApiResponse::Ok {1026 let big = ApiResponse::Ok {
989 id: "trace-1".to_string(),1027 id: "trace-1".to_string(),
1028+ school: DEMO_SLUG.to_string(),
990 status: 200,1029 status: 200,
991 body: serde_json::Value::String("x".repeat(AI_MAX_FRAME_BYTES)),1030 body: serde_json::Value::String("x".repeat(AI_MAX_FRAME_BYTES)),
992 };1031 };
src/constant.rsmodified+2 -2
@@ -514,8 +514,8 @@ pub const MAX_PAGE_LIMIT: i64 = 500;
514 /// and used as the QUIC ALPN. Bump both together on a breaking frame change:514 /// and used as the QUIC ALPN. Bump both together on a breaking frame change:
515 /// ALPN mismatch rejects an old service at the TLS handshake, before it can515 /// ALPN mismatch rejects an old service at the TLS handshake, before it can
516 /// send a frame we would misparse.516 /// send a frame we would misparse.
517-pub const AI_PROTOCOL: &str = "hab/1";517+pub const AI_PROTOCOL: &str = "hab/2";
518-pub const AI_ALPN: &[u8] = b"hab/1";518+pub const AI_ALPN: &[u8] = b"hab/2";
519 519
520 /// Hard ceiling on one AI-bridge frame. Checked against the length prefix520 /// Hard ceiling on one AI-bridge frame. Checked against the length prefix
521 /// before the body buffer is allocated. Generous because a payload may carry a521 /// 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;
42 modifiers(&SecurityAddon),42 modifiers(&SecurityAddon),
43 tags(43 tags(
44 (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"),44 (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"),
46 (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`"),46 (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`"),
47 (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"),47 (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"),
48 (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`"),48 (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> {
35 /// (which is a secret and is configured out of band).35 /// (which is a secret and is configured out of band).
36 #[derive(Serialize, ToSchema)]36 #[derive(Serialize, ToSchema)]
37 pub struct BridgeCertificateResponse {37 pub struct BridgeCertificateResponse {
38- /// Wire protocol and ALPN the service must announce, currently `hab/1`.38+ /// Wire protocol and ALPN the service must announce, currently `hab/2`.
39- #[schema(example = "hab/1")]39+ #[schema(example = "hab/2")]
40 protocol: String,40 protocol: String,
41 /// The listener's leaf certificate, PEM-encoded — feed straight into a TLS41 /// The listener's leaf certificate, PEM-encoded — feed straight into a TLS
42 /// client's trust store (Python: `ssl_context.load_verify_locations(cadata=...)`).42 /// client's trust store (Python: `ssl_context.load_verify_locations(cadata=...)`).
src/web/chatbot.rsmodified+16 -7
@@ -20,7 +20,7 @@
20 20
21 use std::time::Duration;21 use std::time::Duration;
22 22
23-use crate::web::tenant_state::State;23+use crate::web::tenant_state::{SchoolSlug, State, TenantExt};
24 use axum::Json;24 use axum::Json;
25 use axum::extract::{Path, Query};25 use axum::extract::{Path, Query};
26 use axum::http::StatusCode;26 use axum::http::StatusCode;
@@ -377,6 +377,7 @@ async fn list_messages(
377 )]377 )]
378 async fn send_message(378 async fn send_message(
379 State(st): State<AppState>,379 State(st): State<AppState>,
380+ SchoolSlug(school): SchoolSlug,
380 CurrentUser(user): CurrentUser,381 CurrentUser(user): CurrentUser,
381 Path(id): Path<String>,382 Path(id): Path<String>,
382 Json(req): Json<SendChatbotMessage>,383 Json(req): Json<SendChatbotMessage>,
@@ -436,8 +437,14 @@ async fn send_message(
436 // request), so it is the live role at the moment the question was asked —437 // request), so it is the live role at the moment the question was asked —
437 // never a stored copy, and never anything the body could assert.438 // never a stored copy, and never anything the body could assert.
438 tokio::spawn(answer_turn(439 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+ },
439 bridge,447 bridge,
440- st.db.clone(),
441 prompt.get_id().clone(),448 prompt.get_id().clone(),
442 answer,449 answer,
443 user.get_role(),450 user.get_role(),
@@ -477,14 +484,15 @@ fn unavailable(message: &str) -> Response {
477 ///484 ///
478 /// Every path settles: a row left `pending` would show as a spinner forever.485 /// Every path settles: a row left `pending` would show as a spinner forever.
479 async fn answer_turn(486 async fn answer_turn(
487+ tenant: TenantExt,
480 bridge: AiBridge,488 bridge: AiBridge,
481- db: Database,
482 prompt_id: ChatbotMessageId,489 prompt_id: ChatbotMessageId,
483 answer: ChatbotMessage,490 answer: ChatbotMessage,
484 asker_role: Role,491 asker_role: Role,
485 history_turns: usize,492 history_turns: usize,
486 reply_cap: usize,493 reply_cap: usize,
487 ) {494 ) {
495+ let db = tenant.db.clone();
488 let answer_id = answer.get_id().clone();496 let answer_id = answer.get_id().clone();
489 let thread = answer.get_thread_id().clone();497 let thread = answer.get_thread_id().clone();
490 // This request's own question, read back by id — the text is already498 // This request's own question, read back by id — the text is already
@@ -511,7 +519,7 @@ async fn answer_turn(
511 let fresh = [prompt.get_id().clone(), answer_id.clone()];519 let fresh = [prompt.get_id().clone(), answer_id.clone()];
512 let settled = match fetch_reply(520 let settled = match fetch_reply(
513 &bridge,521 &bridge,
514- &db,522+ &tenant,
515 &thread,523 &thread,
516 &fresh,524 &fresh,
517 prompt.get_content().as_str().to_string(),525 prompt.get_content().as_str().to_string(),
@@ -542,7 +550,7 @@ async fn answer_turn(
542 /// The bridge round trip, with every failure mapped to a stable code.550 /// The bridge round trip, with every failure mapped to a stable code.
543 async fn fetch_reply(551 async fn fetch_reply(
544 bridge: &AiBridge,552 bridge: &AiBridge,
545- db: &Database,553+ tenant: &TenantExt,
546 thread: &ChatbotThreadId,554 thread: &ChatbotThreadId,
547 fresh: &[ChatbotMessageId; 2],555 fresh: &[ChatbotMessageId; 2],
548 prompt: String,556 prompt: String,
@@ -550,6 +558,7 @@ async fn fetch_reply(
550 history_turns: usize,558 history_turns: usize,
551 reply_cap: usize,559 reply_cap: usize,
552 ) -> Result<(ChatContent, bool), String> {560 ) -> Result<(ChatContent, bool), String> {
561+ let db = &tenant.db;
553 let history = match history_for(db, thread, fresh, history_turns).await {562 let history = match history_for(db, thread, fresh, history_turns).await {
554 Ok(history) => history,563 Ok(history) => history,
555 Err(err) => {564 Err(err) => {
@@ -568,7 +577,7 @@ async fn fetch_reply(
568 })?;577 })?;
569 578
570 let raw = bridge579 let raw = bridge
571- .dispatch(AI_CHAT_CAPABILITY, payload)580+ .dispatch(&tenant.slug, AI_CHAT_CAPABILITY, payload)
572 .await581 .await
573 .map_err(failure_code)?;582 .map_err(failure_code)?;
574 let reply: ChatReplyPayload = serde_json::from_value(raw).map_err(|err| {583 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) {
820 829
821 /// Cut a finished answer into a handful of `delta` chunks.830 /// Cut a finished answer into a handful of `delta` chunks.
822 ///831 ///
823-/// Fake streaming: `hab/1` is unary, so the whole text is already in hand and832+/// Fake streaming: `hab/2` is unary, so the whole text is already in hand and
824 /// this only lets the UI paint it progressively instead of in one jump. The833 /// this only lets the UI paint it progressively instead of in one jump. The
825 /// day the protocol grows chunk frames, this is the single function that goes834 /// day the protocol grows chunk frames, this is the single function that goes
826 /// away — nothing else in the stream knows where a chunk came from.835 /// away — nothing else in the stream knows where a chunk came from.
src/web/course_notes.rsmodified+9 -5
@@ -5,7 +5,7 @@
5 //! teacher, or manager+), reads need [`super::courses::can_view_course`]5 //! teacher, or manager+), reads need [`super::courses::can_view_course`]
6 //! (management rights, or enrollment).6 //! (management rights, or enrollment).
7 7
8-use crate::web::tenant_state::State;8+use crate::web::tenant_state::{SchoolSlug, State};
9 use axum::Json;9 use axum::Json;
10 use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};10 use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
11 use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};11 use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
@@ -126,6 +126,7 @@ impl CourseNoteResponse {
126 )]126 )]
127 async fn create(127 async fn create(
128 State(st): State<AppState>,128 State(st): State<AppState>,
129+ SchoolSlug(school): SchoolSlug,
129 RequireTeacher(user): RequireTeacher,130 RequireTeacher(user): RequireTeacher,
130 Json(req): Json<CreateCourseNote>,131 Json(req): Json<CreateCourseNote>,
131 ) -> Result<(StatusCode, Json<CourseNoteResponse>), AppError> {132 ) -> Result<(StatusCode, Json<CourseNoteResponse>), AppError> {
@@ -144,7 +145,7 @@ async fn create(
144 // Indexing is a background bonus, never a condition of storing the note:145 // Indexing is a background bonus, never a condition of storing the note:
145 // the dispatch runs in its own task, so a slow or absent AI service cannot146 // the dispatch runs in its own task, so a slow or absent AI service cannot
146 // delay or fail this 201.147 // delay or fail this 201.
147- spawn_index(&st, note.clone());148+ spawn_index(&st, &school, note.clone());
148 Ok((StatusCode::CREATED, Json(CourseNoteResponse::new(&note))))149 Ok((StatusCode::CREATED, Json(CourseNoteResponse::new(&note))))
149 }150 }
150 151
@@ -242,6 +243,7 @@ async fn get_one(
242 )]243 )]
243 async fn update(244 async fn update(
244 State(st): State<AppState>,245 State(st): State<AppState>,
246+ SchoolSlug(school): SchoolSlug,
245 RequireTeacher(user): RequireTeacher,247 RequireTeacher(user): RequireTeacher,
246 Path(id): Path<String>,248 Path(id): Path<String>,
247 Json(req): Json<UpdateCourseNote>,249 Json(req): Json<UpdateCourseNote>,
@@ -267,7 +269,7 @@ async fn update(
267 269
268 let updated = note.update(title, content, &st.db).await?;270 let updated = note.update(title, content, &st.db).await?;
269 // The stored index describes the old text — refresh it.271 // The stored index describes the old text — refresh it.
270- spawn_index(&st, updated.clone());272+ spawn_index(&st, &school, updated.clone());
271 Ok(Json(CourseNoteResponse::new(&updated)))273 Ok(Json(CourseNoteResponse::new(&updated)))
272 }274 }
273 275
@@ -365,6 +367,7 @@ impl CourseNoteFileResponse {
365 )]367 )]
366 async fn upload_file(368 async fn upload_file(
367 State(st): State<AppState>,369 State(st): State<AppState>,
370+ SchoolSlug(school): SchoolSlug,
368 RequireTeacher(user): RequireTeacher,371 RequireTeacher(user): RequireTeacher,
369 Path(id): Path<String>,372 Path(id): Path<String>,
370 mut multipart: Multipart,373 mut multipart: Multipart,
@@ -395,7 +398,7 @@ async fn upload_file(
395 match file.insert(&st.db).await {398 match file.insert(&st.db).await {
396 Ok(created) => {399 Ok(created) => {
397 // The note now holds one more source than the stored index knows.400 // The note now holds one more source than the stored index knows.
398- spawn_index(&st, note);401+ spawn_index(&st, &school, note);
399 Ok((402 Ok((
400 StatusCode::CREATED,403 StatusCode::CREATED,
401 Json(CourseNoteFileResponse::new(&created)),404 Json(CourseNoteFileResponse::new(&created)),
@@ -520,6 +523,7 @@ async fn download_file(
520 )]523 )]
521 async fn delete_file(524 async fn delete_file(
522 State(st): State<AppState>,525 State(st): State<AppState>,
526+ SchoolSlug(school): SchoolSlug,
523 RequireTeacher(user): RequireTeacher,527 RequireTeacher(user): RequireTeacher,
524 Path((id, file_id)): Path<(String, String)>,528 Path((id, file_id)): Path<(String, String)>,
525 ) -> Result<StatusCode, AppError> {529 ) -> Result<StatusCode, AppError> {
@@ -541,7 +545,7 @@ async fn delete_file(
541 RagOutput::delete_with_source(file.get_id(), &st.db).await?;545 RagOutput::delete_with_source(file.get_id(), &st.db).await?;
542 let file = file.delete(&st.db).await?;546 let file = file.delete(&st.db).await?;
543 remove_blob(&st.files_path, file.get_id().key()).await;547 remove_blob(&st.files_path, file.get_id().key()).await;
544- spawn_index(&st, note);548+ spawn_index(&st, &school, note);
545 Ok(StatusCode::NO_CONTENT)549 Ok(StatusCode::NO_CONTENT)
546 }550 }
547 551
tests/ai_bridge.rsmodified+96 -20
@@ -18,6 +18,7 @@ use hezarfen_backend::ai::protocol::{
18 };18 };
19 use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig};19 use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig};
20 use hezarfen_backend::constant::{AI_ALPN, AI_MAX_CONCURRENT_PER_WORKER, AI_PROTOCOL};20 use hezarfen_backend::constant::{AI_ALPN, AI_MAX_CONCURRENT_PER_WORKER, AI_PROTOCOL};
21+use hezarfen_backend::tenant::{DEMO_SLUG, Slug};
21 use serde_json::{Value, json};22 use serde_json::{Value, json};
22 23
23 const TOKEN: &str = "shared-ai-token";24 const TOKEN: &str = "shared-ai-token";
@@ -68,6 +69,11 @@ fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint {
68 endpoint69 endpoint
69 }70 }
70 71
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+
71 fn hello(service: &str, capabilities: &[&str]) -> Hello {77 fn hello(service: &str, capabilities: &[&str]) -> Hello {
72 Hello {78 Hello {
73 protocol: AI_PROTOCOL.to_string(),79 protocol: AI_PROTOCOL.to_string(),
@@ -188,10 +194,12 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ
188 }194 }
189 Behaviour::Answer(payload) => Some(Response::Ok {195 Behaviour::Answer(payload) => Some(Response::Ok {
190 id: request.id.clone(),196 id: request.id.clone(),
197+ school: request.school.clone(),
191 payload,198 payload,
192 }),199 }),
193 Behaviour::Reply(text) => Some(Response::Ok {200 Behaviour::Reply(text) => Some(Response::Ok {
194 id: request.id.clone(),201 id: request.id.clone(),
202+ school: request.school.clone(),
195 payload: json!({ "text": text }),203 payload: json!({ "text": text }),
196 }),204 }),
197 Behaviour::EchoPrompt => {205 Behaviour::EchoPrompt => {
@@ -200,16 +208,19 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ
200 .unwrap_or("<no message>");208 .unwrap_or("<no message>");
201 Some(Response::Ok {209 Some(Response::Ok {
202 id: request.id.clone(),210 id: request.id.clone(),
211+ school: request.school.clone(),
203 payload: json!({ "text": format!("cevap::{asked}") }),212 payload: json!({ "text": format!("cevap::{asked}") }),
204 })213 })
205 }214 }
206 Behaviour::Fail { code, message } => Some(Response::Err {215 Behaviour::Fail { code, message } => Some(Response::Err {
207 id: request.id.clone(),216 id: request.id.clone(),
217+ school: request.school.clone(),
208 code,218 code,
209 message,219 message,
210 }),220 }),
211 Behaviour::WrongId => Some(Response::Ok {221 Behaviour::WrongId => Some(Response::Ok {
212 id: "01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string(),222 id: "01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string(),
223+ school: request.school.clone(),
213 payload: json!("from some other request"),224 payload: json!("from some other request"),
214 }),225 }),
215 Behaviour::Garbage => {226 Behaviour::Garbage => {
@@ -241,6 +252,7 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ
241 fn echo(request: &Request) -> Response {252 fn echo(request: &Request) -> Response {
242 Response::Ok {253 Response::Ok {
243 id: request.id.clone(),254 id: request.id.clone(),
255+ school: request.school.clone(),
244 payload: json!({ "echo": request.payload, "capability": request.capability }),256 payload: json!({ "echo": request.payload, "capability": request.capability }),
245 }257 }
246 }258 }
@@ -285,7 +297,7 @@ async fn a_service_registers_and_a_request_round_trips() {
285 assert!(bridge.has_capability("ocr.extract"));297 assert!(bridge.has_capability("ocr.extract"));
286 298
287 let answer = bridge299 let answer = bridge
288- .dispatch("ocr.extract", json!({ "image": "abc" }))300+ .dispatch(&demo(), "ocr.extract", json!({ "image": "abc" }))
289 .await301 .await
290 .expect("the service answered");302 .expect("the service answered");
291 assert_eq!(answer["echo"]["image"], "abc");303 assert_eq!(answer["echo"]["image"], "abc");
@@ -320,7 +332,7 @@ async fn concurrent_requests_share_one_connection_without_blocking_each_other()
320 332
321 let calls = (0..N).map(|i| {333 let calls = (0..N).map(|i| {
322 let bridge = bridge.clone();334 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 })
324 });336 });
325 let answers = futures_util::future::join_all(calls).await;337 let answers = futures_util::future::join_all(calls).await;
326 338
@@ -344,8 +356,8 @@ async fn requests_route_to_the_service_declaring_the_capability() {
344 let grader = connect_service(&bridge, hello("grader", &["grade.essay"]), Behaviour::Echo).await;356 let grader = connect_service(&bridge, hello("grader", &["grade.essay"]), Behaviour::Echo).await;
345 await_workers(&bridge, 2).await;357 await_workers(&bridge, 2).await;
346 358
347- bridge.dispatch("grade.essay", json!("text")).await.unwrap();359+ bridge.dispatch(&demo(), "grade.essay", json!("text")).await.unwrap();
348- bridge.dispatch("ocr.extract", json!("png")).await.unwrap();360+ bridge.dispatch(&demo(), "ocr.extract", json!("png")).await.unwrap();
349 361
350 assert_eq!(ocr.seen().len(), 1, "ocr only saw its own capability");362 assert_eq!(ocr.seen().len(), 1, "ocr only saw its own capability");
351 assert_eq!(ocr.seen()[0].capability, "ocr.extract");363 assert_eq!(ocr.seen()[0].capability, "ocr.extract");
@@ -401,7 +413,7 @@ async fn a_bad_token_is_rejected_and_never_registers() {
401 );413 );
402 assert!(bridge.workers().is_empty());414 assert!(bridge.workers().is_empty());
403 assert!(matches!(415 assert!(matches!(
404- bridge.dispatch("ocr.extract", json!(null)).await,416+ bridge.dispatch(&demo(), "ocr.extract", json!(null)).await,
405 Err(AiError::NoWorker(_))417 Err(AiError::NoWorker(_))
406 ));418 ));
407 }419 }
@@ -502,7 +514,7 @@ async fn an_unknown_capability_fails_fast_instead_of_waiting() {
502 await_workers(&bridge, 1).await;514 await_workers(&bridge, 1).await;
503 515
504 let err = bridge516 let err = bridge
505- .dispatch("grade.essay", json!(null))517+ .dispatch(&demo(), "grade.essay", json!(null))
506 .await518 .await
507 .expect_err("nothing serves that capability");519 .expect_err("nothing serves that capability");
508 assert!(520 assert!(
@@ -527,7 +539,7 @@ async fn a_service_error_frame_surfaces_as_a_remote_error() {
527 await_workers(&bridge, 1).await;539 await_workers(&bridge, 1).await;
528 540
529 let err = bridge541 let err = bridge
530- .dispatch("ocr.extract", json!({ "image": "x" }))542+ .dispatch(&demo(), "ocr.extract", json!({ "image": "x" }))
531 .await543 .await
532 .unwrap_err();544 .unwrap_err();
533 match &err {545 match &err {
@@ -550,7 +562,7 @@ async fn a_silent_service_times_out_and_gives_the_slot_back() {
550 await_workers(&bridge, 1).await;562 await_workers(&bridge, 1).await;
551 563
552 let err = bridge564 let err = bridge
553- .dispatch("ocr.extract", json!(null))565+ .dispatch(&demo(), "ocr.extract", json!(null))
554 .await566 .await
555 .unwrap_err();567 .unwrap_err();
556 assert!(matches!(err, AiError::Timeout(300)), "{err}");568 assert!(matches!(err, AiError::Timeout(300)), "{err}");
@@ -560,7 +572,7 @@ async fn a_silent_service_times_out_and_gives_the_slot_back() {
560 // An abandoned request must not leak the worker's capacity.572 // An abandoned request must not leak the worker's capacity.
561 assert_eq!(bridge.workers()[0].inflight, 0);573 assert_eq!(bridge.workers()[0].inflight, 0);
562 // And the worker is immediately usable again.574 // 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());
564 }576 }
565 577
566 #[tokio::test]578 #[tokio::test]
@@ -576,12 +588,12 @@ async fn a_per_call_timeout_overrides_the_default() {
576 588
577 // The default deadline is too short for this service...589 // The default deadline is too short for this service...
578 assert!(matches!(590 assert!(matches!(
579- bridge.dispatch("ocr.extract", json!(null)).await,591+ bridge.dispatch(&demo(), "ocr.extract", json!(null)).await,
580 Err(AiError::Timeout(100))592 Err(AiError::Timeout(100))
581 ));593 ));
582 // ...but a capability known to be slow can ask for more.594 // ...but a capability known to be slow can ask for more.
583 let answer = bridge595 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))
585 .await597 .await
586 .expect("the longer deadline held");598 .expect("the longer deadline held");
587 assert_eq!(answer["echo"], "slow");599 assert_eq!(answer["echo"], "slow");
@@ -597,12 +609,12 @@ async fn a_full_worker_reports_busy_rather_than_queueing() {
597 609
598 let hog = {610 let hog = {
599 let bridge = bridge.clone();611 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 })
601 };613 };
602 await_inflight(&bridge, 1).await;614 await_inflight(&bridge, 1).await;
603 615
604 let err = bridge616 let err = bridge
605- .dispatch("ocr.extract", json!(null))617+ .dispatch(&demo(), "ocr.extract", json!(null))
606 .await618 .await
607 .unwrap_err();619 .unwrap_err();
608 assert!(620 assert!(
@@ -626,7 +638,7 @@ async fn an_answer_carrying_the_wrong_trace_id_is_refused() {
626 await_workers(&bridge, 1).await;638 await_workers(&bridge, 1).await;
627 639
628 let err = bridge640 let err = bridge
629- .dispatch("ocr.extract", json!(null))641+ .dispatch(&demo(), "ocr.extract", json!(null))
630 .await642 .await
631 .unwrap_err();643 .unwrap_err();
632 assert!(matches!(err, AiError::IdMismatch { .. }), "{err}");644 assert!(matches!(err, AiError::IdMismatch { .. }), "{err}");
@@ -641,7 +653,7 @@ async fn a_malformed_answer_is_a_protocol_error_not_a_hang() {
641 await_workers(&bridge, 1).await;653 await_workers(&bridge, 1).await;
642 654
643 let err = bridge655 let err = bridge
644- .dispatch("ocr.extract", json!(null))656+ .dispatch(&demo(), "ocr.extract", json!(null))
645 .await657 .await
646 .unwrap_err();658 .unwrap_err();
647 assert!(matches!(err, AiError::Protocol(_)), "{err}");659 assert!(matches!(err, AiError::Protocol(_)), "{err}");
@@ -655,7 +667,7 @@ async fn a_disconnected_service_is_deregistered() {
655 let bridge = bridge().await;667 let bridge = bridge().await;
656 let service = connect_service(&bridge, hello("ocr", &["ocr.extract"]), Behaviour::Echo).await;668 let service = connect_service(&bridge, hello("ocr", &["ocr.extract"]), Behaviour::Echo).await;
657 await_workers(&bridge, 1).await;669 await_workers(&bridge, 1).await;
658- bridge.dispatch("ocr.extract", json!(null)).await.unwrap();670+ bridge.dispatch(&demo(), "ocr.extract", json!(null)).await.unwrap();
659 671
660 service.conn.close(0u32.into(), b"service shutting down");672 service.conn.close(0u32.into(), b"service shutting down");
661 drop(service);673 drop(service);
@@ -663,7 +675,7 @@ async fn a_disconnected_service_is_deregistered() {
663 675
664 assert!(!bridge.has_capability("ocr.extract"));676 assert!(!bridge.has_capability("ocr.extract"));
665 let err = bridge677 let err = bridge
666- .dispatch("ocr.extract", json!(null))678+ .dispatch(&demo(), "ocr.extract", json!(null))
667 .await679 .await
668 .unwrap_err();680 .unwrap_err();
669 assert!(matches!(err, AiError::NoWorker(_)), "{err}");681 assert!(matches!(err, AiError::NoWorker(_)), "{err}");
@@ -683,7 +695,7 @@ async fn a_service_that_reconnects_serves_again() {
683 let second = connect_service(&bridge, hello("ocr", &["ocr.extract"]), Behaviour::Echo).await;695 let second = connect_service(&bridge, hello("ocr", &["ocr.extract"]), Behaviour::Echo).await;
684 await_workers(&bridge, 1).await;696 await_workers(&bridge, 1).await;
685 let answer = bridge697 let answer = bridge
686- .dispatch("ocr.extract", json!("again"))698+ .dispatch(&demo(), "ocr.extract", json!("again"))
687 .await699 .await
688 .unwrap();700 .unwrap();
689 assert_eq!(answer["echo"], "again");701 assert_eq!(answer["echo"], "again");
@@ -703,7 +715,7 @@ async fn losing_one_service_leaves_the_other_serving() {
703 await_workers(&bridge, 1).await;715 await_workers(&bridge, 1).await;
704 716
705 for _ in 0..4 {717 for _ in 0..4 {
706- bridge.dispatch("ocr.extract", json!("x")).await.unwrap();718+ bridge.dispatch(&demo(), "ocr.extract", json!("x")).await.unwrap();
707 }719 }
708 assert_eq!(720 assert_eq!(
709 survivor.seen().len(),721 survivor.seen().len(),
@@ -794,7 +806,7 @@ async fn a_large_payload_survives_the_round_trip_intact() {
794 806
795 let blob: String = std::iter::repeat_n('x', 512 * 1024).collect();807 let blob: String = std::iter::repeat_n('x', 512 * 1024).collect();
796 let answer = bridge808 let answer = bridge
797- .dispatch("ocr.extract", json!({ "image": blob }))809+ .dispatch(&demo(), "ocr.extract", json!({ "image": blob }))
798 .await810 .await
799 .expect("a multi-packet frame round-trips");811 .expect("a multi-packet frame round-trips");
800 let echoed = answer["echo"]["image"].as_str().expect("string came back");812 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
1418 1430
1419 /// A `GET` of `path` as `on_behalf_of` (or as the service itself).1431 /// A `GET` of `path` as `on_behalf_of` (or as the service itself).
1420 fn read_of(path: &str, on_behalf_of: Option<&str>) -> ApiRequest {1432 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 {
1421 ApiRequest {1438 ApiRequest {
1422 id: format!("trace-{path}"),1439 id: format!("trace-{path}"),
1440+ school: school.to_string(),
1423 path: path.to_string(),1441 path: path.to_string(),
1424 query: None,1442 query: None,
1425 on_behalf_of: on_behalf_of.map(str::to_string),1443 on_behalf_of: on_behalf_of.map(str::to_string),
@@ -1710,6 +1728,52 @@ async fn course_note(app: &Router, db: &Database) -> (String, String) {
1710 (cookie, common::id_of(&res.body))1728 (cookie, common::id_of(&res.body))
1711 }1729 }
1712 1730
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+
1713 #[tokio::test]1777 #[tokio::test]
1714 async fn a_course_note_is_indexed_and_its_output_stored_with_its_sources() {1778 async fn a_course_note_is_indexed_and_its_output_stored_with_its_sources() {
1715 let bridge = bridge().await;1779 let bridge = bridge().await;
@@ -1731,6 +1795,7 @@ async fn a_course_note_is_indexed_and_its_output_stored_with_its_sources() {
1731 // The service saw the note itself, under the documented capability.1795 // The service saw the note itself, under the documented capability.
1732 let seen = service.seen();1796 let seen = service.seen();
1733 assert_eq!(seen[0].capability, AI_RAG_INDEX_CAPABILITY);1797 assert_eq!(seen[0].capability, AI_RAG_INDEX_CAPABILITY);
1798+ assert_eq!(seen[0].school, DEMO_SLUG, "the frame names the caller's school");
1734 assert_eq!(seen[0].payload["course_note"], note);1799 assert_eq!(seen[0].payload["course_note"], note);
1735 assert_eq!(seen[0].payload["title"], "Bölüm 3");1800 assert_eq!(seen[0].payload["title"], "Bölüm 3");
1736 assert_eq!(seen[0].payload["content"], "özet");1801 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() {
1876 1941
1877 let request = ApiRequest {1942 let request = ApiRequest {
1878 id: "trace-course-notes".into(),1943 id: "trace-course-notes".into(),
1944+ school: DEMO_SLUG.into(),
1879 path: "/course-notes".into(),1945 path: "/course-notes".into(),
1880 query: Some(format!("course={course}")),1946 query: Some(format!("course={course}")),
1881 on_behalf_of: Some(student),1947 on_behalf_of: Some(student),
@@ -1903,6 +1969,7 @@ async fn a_course_the_student_is_not_in_is_refused_by_the_handler() {
1903 1969
1904 let request = ApiRequest {1970 let request = ApiRequest {
1905 id: "trace-foreign-course".into(),1971 id: "trace-foreign-course".into(),
1972+ school: DEMO_SLUG.into(),
1906 path: "/course-notes".into(),1973 path: "/course-notes".into(),
1907 query: Some(format!("course={foreign}")),1974 query: Some(format!("course={foreign}")),
1908 on_behalf_of: Some(student),1975 on_behalf_of: Some(student),
@@ -1922,6 +1989,7 @@ async fn writing_a_course_note_is_refused_before_dispatch() {
1922 1989
1923 let request = ApiRequest {1990 let request = ApiRequest {
1924 id: "trace-post".into(),1991 id: "trace-post".into(),
1992+ school: DEMO_SLUG.into(),
1925 path: "/course-notes".into(),1993 path: "/course-notes".into(),
1926 query: None,1994 query: None,
1927 on_behalf_of: None,1995 on_behalf_of: None,
@@ -1990,8 +2058,14 @@ async fn blob_read(conn: &quinn::Connection, request: BlobRequest) -> (BlobRespo
1990 }2058 }
1991 2059
1992 fn blob_of(file: &str, on_behalf_of: Option<&str>) -> BlobRequest {2060 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 {
1993 BlobRequest {2066 BlobRequest {
1994 id: format!("trace-blob-{file}"),2067 id: format!("trace-blob-{file}"),
2068+ school: school.to_string(),
1995 file: file.to_string(),2069 file: file.to_string(),
1996 on_behalf_of: on_behalf_of.map(str::to_string),2070 on_behalf_of: on_behalf_of.map(str::to_string),
1997 }2071 }
@@ -2033,6 +2107,7 @@ async fn a_service_streams_a_course_note_file_on_behalf_of_an_enrolled_student()
2033 let (header, bytes) = blob_read(&service.conn, blob_of(&file, Some(&student))).await;2107 let (header, bytes) = blob_read(&service.conn, blob_of(&file, Some(&student))).await;
2034 let BlobResponse::Ok {2108 let BlobResponse::Ok {
2035 id,2109 id,
2110+ school,
2036 name,2111 name,
2037 content_type,2112 content_type,
2038 size,2113 size,
@@ -2041,6 +2116,7 @@ async fn a_service_streams_a_course_note_file_on_behalf_of_an_enrolled_student()
2041 panic!("the enrolled student was refused: {}", blob_refusal(header));2116 panic!("the enrolled student was refused: {}", blob_refusal(header));
2042 };2117 };
2043 assert_eq!(id, format!("trace-blob-{file}"), "the trace id is echoed");2118 assert_eq!(id, format!("trace-blob-{file}"), "the trace id is echoed");
2119+ assert_eq!(school, DEMO_SLUG, "the school is echoed too");
2044 assert_eq!(name, "recap.pdf");2120 assert_eq!(name, "recap.pdf");
2045 assert_eq!(content_type, "application/pdf");2121 assert_eq!(content_type, "application/pdf");
2046 assert_eq!(size as usize, uploaded.len(), "the promised byte count");2122 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`.
2 //!2 //!
3 //! # Why this file exists separately from `ai_bridge.rs`3 //! # Why this file exists separately from `ai_bridge.rs`
4 //!4 //!
@@ -15,7 +15,7 @@
15 //! in a service repo.15 //! in a service repo.
16 //!16 //!
17 //! It doubles as the reference implementation: `raw::Service` below is the17 //! 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.
19 19
20 mod common;20 mod common;
21 21
@@ -23,18 +23,23 @@ use std::sync::Arc;
23 use std::time::Duration;23 use std::time::Duration;
24 24
25 use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig};25 use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig};
26+use hezarfen_backend::tenant::{SchoolStatus, Slug, Tenants};
26 use serde_json::{Value, json};27 use serde_json::{Value, json};
27 28
28 const TOKEN: &str = "shared-ai-token";29 const TOKEN: &str = "shared-ai-token";
29 30
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+
30 /// The protocol identifier this suite pins. Deliberately a literal, not35 /// The protocol identifier this suite pins. Deliberately a literal, not
31 /// `AI_PROTOCOL`: importing the constant would let a rename sail through, and36 /// `AI_PROTOCOL`: importing the constant would let a rename sail through, and
32 /// the whole point is that the string is a published contract.37 /// the whole point is that the string is a published contract.
33-const PROTOCOL: &str = "hab/1";38+const PROTOCOL: &str = "hab/2";
34 39
35 // ------------------------------------------------------------------- raw --40 // ------------------------------------------------------------------- raw --
36 41
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.
38 mod raw {43 mod raw {
39 use super::*;44 use super::*;
40 45
@@ -252,7 +257,8 @@ fn dispatch(
252 ) -> tokio::task::JoinHandle<Result<Value, AiError>> {257 ) -> tokio::task::JoinHandle<Result<Value, AiError>> {
253 let bridge = bridge.clone();258 let bridge = bridge.clone();
254 let capability = capability.to_string();259 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 })
256 }262 }
257 263
258 // ------------------------------------------------------- framing contract --264 // ------------------------------------------------------- framing contract --
@@ -385,7 +391,7 @@ async fn the_rejection_frame_carries_exactly_the_published_keys_and_codes() {
385 // variant is a breaking change and must fail here.391 // variant is a breaking change and must fail here.
386 let bridge = bridge().await;392 let bridge = bridge().await;
387 393
388- let cases: [(&str, Vec<u8>); 4] = [394+ let cases: [(&str, Vec<u8>); 5] = [
389 (395 (
390 "unauthorized",396 "unauthorized",
391 format!(397 format!(
@@ -400,6 +406,16 @@ async fn the_rejection_frame_carries_exactly_the_published_keys_and_codes() {
400 )406 )
401 .into_bytes(),407 .into_bytes(),
402 ),408 ),
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+ ),
403 (419 (
404 "no_capabilities",420 "no_capabilities",
405 format!(421 format!(
@@ -491,12 +507,20 @@ async fn a_foreign_alpn_is_refused_at_the_tls_handshake() {
491 // The version gate: an incompatible service must be stopped before it can507 // The version gate: an incompatible service must be stopped before it can
492 // send a frame this backend would misparse.508 // send a frame this backend would misparse.
493 let bridge = bridge().await;509 let bridge = bridge().await;
494- let endpoint = raw::endpoint_with_alpn(&bridge, b"hab/99");510+ // `hab/1` included by name: the version gate is the *first* line of defence
495- let result = endpoint511+ // against a service whose frames name no school, ahead of the Hello check.
496- .connect(bridge.local_addr().unwrap(), "localhost")512+ for alpn in [b"hab/99".as_slice(), b"hab/1".as_slice()] {
497- .unwrap()513+ let endpoint = raw::endpoint_with_alpn(&bridge, alpn);
498- .await;514+ let result = endpoint
499- assert!(result.is_err(), "ALPN hab/99 must not connect");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+ }
500 assert!(bridge.workers().is_empty());524 assert!(bridge.workers().is_empty());
501 }525 }
502 526
@@ -516,7 +540,7 @@ async fn the_request_frame_carries_exactly_the_published_keys() {
516 540
517 assert_eq!(541 assert_eq!(
518 raw::keys(&request),542 raw::keys(&request),
519- ["capability", "deadline_ms", "id", "payload"],543+ ["capability", "deadline_ms", "id", "payload", "school"],
520 "request shape changed: {request}"544 "request shape changed: {request}"
521 );545 );
522 assert_eq!(request["capability"], "ocr.extract");546 assert_eq!(request["capability"], "ocr.extract");
@@ -529,7 +553,7 @@ async fn the_request_frame_carries_exactly_the_published_keys() {
529 let id = request["id"].as_str().unwrap().to_string();553 let id = request["id"].as_str().unwrap().to_string();
530 raw::answer(554 raw::answer(
531 send,555 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(),
533 )557 )
534 .await;558 .await;
535 let answer = call.await.unwrap().expect("dispatch succeeded");559 let answer = call.await.unwrap().expect("dispatch succeeded");
@@ -562,7 +586,7 @@ async fn a_payload_of_any_json_shape_survives_unchanged() {
562 assert_eq!(request["payload"], payload, "payload mutated in flight");586 assert_eq!(request["payload"], payload, "payload mutated in flight");
563 587
564 let id = request["id"].as_str().unwrap();588 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 });
566 raw::answer(send, &serde_json::to_vec(&echo).unwrap()).await;590 raw::answer(send, &serde_json::to_vec(&echo).unwrap()).await;
567 assert_eq!(591 assert_eq!(
568 call.await.unwrap().unwrap(),592 call.await.unwrap().unwrap(),
@@ -585,7 +609,7 @@ async fn the_response_tags_are_the_published_literals() {
585 let id = request["id"].as_str().unwrap().to_string();609 let id = request["id"].as_str().unwrap().to_string();
586 raw::answer(610 raw::answer(
587 send,611 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(),
589 )613 )
590 .await;614 .await;
591 assert_eq!(ok.await.unwrap().unwrap(), json!(42));615 assert_eq!(ok.await.unwrap().unwrap(), json!(42));
@@ -595,7 +619,7 @@ async fn the_response_tags_are_the_published_literals() {
595 let id = request["id"].as_str().unwrap().to_string();619 let id = request["id"].as_str().unwrap().to_string();
596 raw::answer(620 raw::answer(
597 send,621 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(),
599 )623 )
600 .await;624 .await;
601 match err.await.unwrap() {625 match err.await.unwrap() {
@@ -611,7 +635,7 @@ async fn the_response_tags_are_the_published_literals() {
611 let id = request["id"].as_str().unwrap().to_string();635 let id = request["id"].as_str().unwrap().to_string();
612 raw::answer(636 raw::answer(
613 send,637 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(),
615 )639 )
616 .await;640 .await;
617 assert!(641 assert!(
@@ -634,7 +658,7 @@ async fn a_response_may_carry_unknown_fields() {
634 raw::answer(658 raw::answer(
635 send,659 send,
636 format!(660 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"}}"#
638 )662 )
639 .as_bytes(),663 .as_bytes(),
640 )664 )
@@ -690,7 +714,7 @@ async fn each_request_gets_its_own_stream_and_answers_may_come_back_in_any_order
690 let n = request["payload"]["n"].clone();714 let n = request["payload"]["n"].clone();
691 raw::answer(715 raw::answer(
692 send,716 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(),
694 )718 )
695 .await;719 .await;
696 }720 }
@@ -720,7 +744,7 @@ async fn request_ids_are_unique_per_request() {
720 assert!(seen.insert(id.clone()), "id {id} was reused");744 assert!(seen.insert(id.clone()), "id {id} was reused");
721 raw::answer(745 raw::answer(
722 send,746 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(),
724 )748 )
725 .await;749 .await;
726 call.await.unwrap().unwrap();750 call.await.unwrap().unwrap();
@@ -752,7 +776,7 @@ async fn the_control_stream_carries_no_frames_after_the_welcome() {
752 let id = request["id"].as_str().unwrap().to_string();776 let id = request["id"].as_str().unwrap().to_string();
753 raw::answer(777 raw::answer(
754 send,778 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(),
756 )780 )
757 .await;781 .await;
758 call.await782 call.await
@@ -774,7 +798,13 @@ async fn closing_the_control_stream_deregisters_the_service() {
774 await_workers(&bridge, 0).await;798 await_workers(&bridge, 0).await;
775 799
776 assert!(matches!(800 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,
778 Err(AiError::NoWorker(_))808 Err(AiError::NoWorker(_))
779 ));809 ));
780 }810 }
@@ -811,7 +841,7 @@ async fn a_service_that_drops_a_request_stream_fails_that_request_only() {
811 let id = request["id"].as_str().unwrap().to_string();841 let id = request["id"].as_str().unwrap().to_string();
812 raw::answer(842 raw::answer(
813 send,843 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(),
815 )845 )
816 .await;846 .await;
817 assert_eq!(next.await.unwrap().unwrap(), json!("ok"));847 assert_eq!(next.await.unwrap().unwrap(), json!("ok"));
@@ -882,7 +912,7 @@ async fn several_raw_services_serve_one_capability_together() {
882 let n = request["payload"]["n"].clone();912 let n = request["payload"]["n"].clone();
883 raw::answer(913 raw::answer(
884 send,914 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(),
886 )916 )
887 .await;917 .await;
888 }918 }
@@ -976,7 +1006,7 @@ async fn a_chat_request_names_the_askers_school_role() {
976 let id = request["id"].as_str().expect("trace id").to_string();1006 let id = request["id"].as_str().expect("trace id").to_string();
977 raw::answer(1007 raw::answer(
978 send,1008 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(),
980 )1010 )
981 .await;1011 .await;
982 }1012 }
@@ -1012,7 +1042,7 @@ async fn the_api_request_field_names_are_the_published_literals() {
1012 let (answer, bytes) = raw::api_read(1042 let (answer, bytes) = raw::api_read(
1013 &service.conn,1043 &service.conn,
1014 format!(1044 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"}}"#
1016 )1046 )
1017 .as_bytes(),1047 .as_bytes(),
1018 )1048 )
@@ -1020,7 +1050,7 @@ async fn the_api_request_field_names_are_the_published_literals() {
1020 1050
1021 assert_eq!(1051 assert_eq!(
1022 raw::keys(&answer),1052 raw::keys(&answer),
1023- ["body", "id", "outcome", "status"],1053+ ["body", "id", "outcome", "school", "status"],
1024 "api answer shape changed: {answer}"1054 "api answer shape changed: {answer}"
1025 );1055 );
1026 assert_eq!(answer["outcome"], "ok");1056 assert_eq!(answer["outcome"], "ok");
@@ -1048,7 +1078,7 @@ async fn only_id_and_path_are_required_of_an_api_request() {
1048 1078
1049 let (answer, _) = raw::api_read(1079 let (answer, _) = raw::api_read(
1050 &service.conn,1080 &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}"#,
1052 )1082 )
1053 .await;1083 .await;
1054 assert_eq!(answer["outcome"], "ok", "{answer}");1084 assert_eq!(answer["outcome"], "ok", "{answer}");
@@ -1070,34 +1100,47 @@ async fn the_api_refusal_frame_carries_exactly_the_published_keys_and_codes() {
1070 let cases = [1100 let cases = [
1071 (1101 (
1072 "method_not_allowed",1102 "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(),
1074 ),1104 ),
1075 (1105 (
1076 "method_not_allowed",1106 "method_not_allowed",
1077 // Lowercase is not the method: the literal is exactly `GET`.1107 // 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(),
1079 ),1109 ),
1080 (1110 (
1081 "path_not_allowed",1111 "path_not_allowed",
1082- r#"{"id":"t3","path":"/courses"}"#.to_string(),1112+ r#"{"id":"t3","school":"demo","path":"/courses"}"#.to_string(),
1083 ),1113 ),
1084 (1114 (
1085 // Order pin: both refusals apply, the method one wins.1115 // Order pin: both refusals apply, the method one wins.
1086 "method_not_allowed",1116 "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(),
1088 ),1118 ),
1089 (1119 (
1090 "unknown_user",1120 "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(),
1092 ),1136 ),
1093- ("malformed", r#"{"id":"t6","path":42}"#.to_string()),
1094 ];1137 ];
1095 1138
1096 for (expected_code, request) in cases {1139 for (expected_code, request) in cases {
1097 let (answer, _) = raw::api_read(&service.conn, request.as_bytes()).await;1140 let (answer, _) = raw::api_read(&service.conn, request.as_bytes()).await;
1098 assert_eq!(1141 assert_eq!(
1099 raw::keys(&answer),1142 raw::keys(&answer),
1100- ["code", "id", "message", "outcome"],1143+ ["code", "id", "message", "outcome", "school"],
1101 "refusal shape changed for {expected_code}: {answer}"1144 "refusal shape changed for {expected_code}: {answer}"
1102 );1145 );
1103 assert_eq!(answer["outcome"], "err", "{answer}");1146 assert_eq!(answer["outcome"], "err", "{answer}");
@@ -1130,7 +1173,8 @@ async fn an_api_read_answers_a_named_user_with_that_users_own_data() {
1130 1173
1131 let (answer, _) = raw::api_read(1174 let (answer, _) = raw::api_read(
1132 &service.conn,1175 &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(),
1134 )1178 )
1135 .await;1179 .await;
1136 assert_eq!(answer["outcome"], "ok", "{answer}");1180 assert_eq!(answer["outcome"], "ok", "{answer}");
@@ -1139,6 +1183,148 @@ async fn an_api_read_answers_a_named_user_with_that_users_own_data() {
1139 assert_eq!(answer["body"]["role"], "student", "{answer}");1183 assert_eq!(answer["body"]["role"], "student", "{answer}");
1140 }1184 }
1141 1185
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+
1142 // --------------------------------------------------- blob stream contract --1328 // --------------------------------------------------- blob stream contract --
1143 //1329 //
1144 // The bytes behind a course-note attachment, which no JSON frame can carry.1330 // 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
1198 let (header, bytes, body) = raw::blob_read(1384 let (header, bytes, body) = raw::blob_read(
1199 &service.conn,1385 &service.conn,
1200 format!(1386 format!(
1201- r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","file":"{file}","on_behalf_of":"{student}"}}"#1387+ r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","school":"{SCHOOL}","file":"{file}","on_behalf_of":"{student}"}}"#
1202 )1388 )
1203 .as_bytes(),1389 .as_bytes(),
1204 )1390 )
@@ -1206,7 +1392,7 @@ async fn the_blob_header_frame_carries_exactly_the_published_keys_then_size_byte
1206 1392
1207 assert_eq!(1393 assert_eq!(
1208 raw::keys(&header),1394 raw::keys(&header),
1209- ["content_type", "id", "name", "size", "status"],1395+ ["content_type", "id", "name", "school", "size", "status"],
1210 "blob header shape changed: {header}"1396 "blob header shape changed: {header}"
1211 );1397 );
1212 assert_eq!(header["status"], "ok");1398 assert_eq!(header["status"], "ok");
@@ -1241,12 +1427,15 @@ async fn a_blob_refusal_frame_carries_exactly_the_published_keys_and_no_bytes()
1241 1427
1242 let (header, _, body) = raw::blob_read(1428 let (header, _, body) = raw::blob_read(
1243 &service.conn,1429 &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(),
1245 )1434 )
1246 .await;1435 .await;
1247 assert_eq!(1436 assert_eq!(
1248 raw::keys(&header),1437 raw::keys(&header),
1249- ["code", "id", "message", "status"],1438+ ["code", "id", "message", "school", "status"],
1250 "blob refusal shape changed: {header}"1439 "blob refusal shape changed: {header}"
1251 );1440 );
1252 assert_eq!(header["status"], "err");1441 assert_eq!(header["status"], "err");
@@ -1270,7 +1459,8 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() {
1270 1459
1271 let (answer, _) = raw::api_read(1460 let (answer, _) = raw::api_read(
1272 &service.conn,1461 &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(),
1274 )1464 )
1275 .await;1465 .await;
1276 assert_eq!(answer["outcome"], "ok", "{answer}");1466 assert_eq!(answer["outcome"], "ok", "{answer}");
@@ -1282,7 +1472,7 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() {
1282 let (answer, _) = raw::api_read(1472 let (answer, _) = raw::api_read(
1283 &service.conn,1473 &service.conn,
1284 format!(1474 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}"}}"#
1286 )1476 )
1287 .as_bytes(),1477 .as_bytes(),
1288 )1478 )
@@ -1291,7 +1481,7 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() {
1291 assert_eq!(answer["status"], 200);1481 assert_eq!(answer["status"], 200);
1292 1482
1293 // Neither shape: still the api read's refusal, with its `outcome` tag.1483 // 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;
1295 assert_eq!(answer["outcome"], "err", "{answer}");1485 assert_eq!(answer["outcome"], "err", "{answer}");
1296 assert_eq!(answer["code"], "malformed");1486 assert_eq!(answer["code"], "malformed");
1297 assert_eq!(answer["id"], "t-neither");1487 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) {
94 app_with_ai_health(ai, Default::default()).await94 app_with_ai_health(ai, Default::default()).await
95 }95 }
96 96
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+
97 /// [`app_with_ai`] with the liveness flag handed in, so a test can take the103 /// [`app_with_ai`] with the liveness flag handed in, so a test can take the
98 /// database socket down under a running app — the api-read path re-checks it in104 /// database socket down under a running app — the api-read path re-checks it in
99 /// place of the HTTP db guard it bypasses.105 /// place of the HTTP db guard it bypasses.
@@ -148,7 +154,20 @@ pub async fn set_role(db: &Database, username: &str, role: &str) {
148 /// Register (password `secret1`), promote to `role`, then log in. Returns the154 /// Register (password `secret1`), promote to `role`, then log in. Returns the
149 /// session `Cookie` value.155 /// session `Cookie` value.
150 pub async fn login_as(app: &Router, db: &Database, username: &str, role: &str) -> String {156 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" });
152 let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await;171 let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await;
153 assert_eq!(reg.status, StatusCode::CREATED, "register {username}");172 assert_eq!(reg.status, StatusCode::CREATED, "register {username}");
154 set_role(db, username, role).await;173 set_role(db, username, role).await;
tests/e2e.rsmodified+1 -0
@@ -1797,6 +1797,7 @@ async fn chat_service(text: &str) -> ChatService {
1797 };1797 };
1798 let response = AiResponse::Ok {1798 let response = AiResponse::Ok {
1799 id: request.id.clone(),1799 id: request.id.clone(),
1800+ school: request.school.clone(),
1800 payload: json!({ "text": answer }),1801 payload: json!({ "text": answer }),
1801 };1802 };
1802 let _ = write_frame(&mut send, &response).await;1803 let _ = write_frame(&mut send, &response).await;