AI bridge speaks hab/2
Browse files at this commitcedd07fa18e2519a65e4aff4264a54a6b7fdd8b3Parent: b7dfc0c- feat
- AI bridge speaks hab/2
- every frame names its school
13 changed files +635 -180
- README.md +78 -33
- src/ai/protocol.rs +71 -6
- src/ai/rag.rs +10 -3
- src/ai/server.rs +95 -56
- src/constant.rs +2 -2
- src/lib.rs +1 -1
- src/web/ai.rs +2 -2
- src/web/chatbot.rs +16 -7
- src/web/course_notes.rs +9 -5
- tests/ai_bridge.rs +96 -20
- tests/ai_protocol.rs +234 -44
- tests/common/mod.rs +20 -1
- tests/e2e.rs +1 -0
README.mdmodified+78 -33
| @@ -3503,18 +3503,19 @@ of the API is unaffected. | ||
| 3503 | 3503 | |
| 3504 | 3504 | ### Handshake |
| 3505 | 3505 | |
| 3506 | -The service connects with ALPN `hab/1`, then opens the **control stream** (the | |
| 3506 | +The service connects with ALPN `hab/2`, then opens the **control stream** (the | |
| 3507 | 3507 | first client-initiated bidi stream) and writes one `Hello`: |
| 3508 | 3508 | |
| 3509 | 3509 | ```json |
| 3510 | -{ "protocol": "hab/1", "service": "ocr", "capabilities": ["ocr.extract"], | |
| 3510 | +{ "protocol": "hab/2", "service": "ocr", "capabilities": ["ocr.extract"], | |
| 3511 | 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 | 3517 | ```json |
| 3517 | -{ "type": "welcome", "worker_id": "01J...", "protocol": "hab/1" } | |
| 3518 | +{ "type": "welcome", "worker_id": "01J...", "protocol": "hab/2" } | |
| 3518 | 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 | 3530 | `max_concurrent` is advisory and clamped to `1..=64` (default 8). Requests |
| 3530 | 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 | 3560 | ### Requests |
| 3533 | 3561 | |
| 3534 | 3562 | For each request the **backend** opens a bidi stream, writes one `Request`, |
| 3535 | 3563 | finishes its send side, and reads one `Response`: |
| 3536 | 3564 | |
| 3537 | 3565 | ```json |
| 3538 | -{ "id": "01J...", "capability": "ocr.extract", "deadline_ms": 30000, | |
| 3539 | - "payload": { "image": "<base64>" } } | |
| 3566 | +{ "id": "01J...", "school": "demo", "capability": "ocr.extract", | |
| 3567 | + "deadline_ms": 30000, "payload": { "image": "<base64>" } } | |
| 3540 | 3568 | ``` |
| 3541 | 3569 | |
| 3542 | 3570 | ```json |
| 3543 | -{ "status": "ok", "id": "01J...", "payload": { "text": "..." } } | |
| 3544 | -{ "status": "err", "id": "01J...", "code": "unsupported_image", | |
| 3545 | - "message": "only png and jpeg" } | |
| 3571 | +{ "status": "ok", "id": "01J...", "school": "demo", | |
| 3572 | + "payload": { "text": "..." } } | |
| 3573 | +{ "status": "err", "id": "01J...", "school": "demo", | |
| 3574 | + "code": "unsupported_image", "message": "only png and jpeg" } | |
| 3546 | 3575 | ``` |
| 3547 | 3576 | |
| 3548 | -`id` is a trace id for logs on both sides — correlation is the stream, not the | |
| 3577 | +`school` is the school the work belongs to, echoed back like `id`. `id` is a | |
| 3578 | +trace id for logs on both sides — correlation is the stream, not the | |
| 3549 | 3579 | id. It must still be echoed: an answer carrying a different id means the |
| 3550 | 3580 | service lost track of whose work it is, and the payload is refused. `payload` |
| 3551 | 3581 | is opaque to the transport; its shape belongs to the capability. |
| @@ -3563,15 +3593,17 @@ already has. | ||
| 3563 | 3593 | |
| 3564 | 3594 | After the handshake the *service* may open further bidi streams, one per read: |
| 3565 | 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 the | |
| 3596 | +Same framing as every other `hab/2` frame; concurrency and correlation are the | |
| 3567 | 3597 | stream, exactly as for capability requests. |
| 3568 | 3598 | |
| 3569 | 3599 | ```json |
| 3570 | -{ "id": "01J...", "path": "/marks/me", "query": "limit=10&offset=0", | |
| 3571 | - "on_behalf_of": "user:01J...", "method": "GET" } | |
| 3600 | +{ "id": "01J...", "school": "demo", "path": "/marks/me", | |
| 3601 | + "query": "limit=10&offset=0", "on_behalf_of": "user:01J...", | |
| 3602 | + "method": "GET" } | |
| 3572 | 3603 | ``` |
| 3573 | 3604 | |
| 3574 | -`id` is a trace id, echoed back. `path` is the path alone as the REST API | |
| 3605 | +`id` is a trace id, echoed back, and so is `school` — which names the database | |
| 3606 | +the read is answered from and is required. `path` is the path alone as the REST API | |
| 3575 | 3607 | spells it — no host, and **no query string**, which travels in `query` (without |
| 3576 | 3608 | the leading `?`). `query`, `on_behalf_of` and `method` are all optional; an |
| 3577 | 3609 | absent `method` means `GET`, and anything else is refused. |
| @@ -3579,8 +3611,10 @@ absent `method` means `GET`, and anything else is refused. | ||
| 3579 | 3611 | The answer is tagged by `outcome`: |
| 3580 | 3612 | |
| 3581 | 3613 | ```json |
| 3582 | -{ "outcome": "ok", "id": "01J...", "status": 200, "body": { } } | |
| 3583 | -{ "outcome": "err", "id": "01J...", "code": "path_not_allowed", | |
| 3614 | +{ "outcome": "ok", "id": "01J...", "school": "demo", "status": 200, | |
| 3615 | + "body": { } } | |
| 3616 | +{ "outcome": "err", "id": "01J...", "school": "demo", | |
| 3617 | + "code": "path_not_allowed", | |
| 3584 | 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 | 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 | 3630 | | `method_not_allowed` | `method` was present and was not `GET` | |
| 3597 | 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 | 3635 | | `unavailable` | The API is not serving yet, the database socket is down, or the read outran the request timeout — retryable | |
| 3600 | 3636 | | `not_json` | The endpoint answered with a body that is not JSON | |
| 3601 | 3637 | | `too_large` | The answer does not fit one frame | |
| 3602 | 3638 | |
| 3603 | 3639 | 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 | 3643 | #### The read scope |
| 3607 | 3644 | |
| @@ -3637,7 +3674,8 @@ With `on_behalf_of`, the read executes **as that user**: own-scoped endpoints | ||
| 3637 | 3674 | (`/auth/me`, `/notes`, `/marks/me`) return *their* data. Both spellings are |
| 3638 | 3675 | accepted — the bare key (`01J...`, as a REST path writes it) and the record |
| 3639 | 3676 | form (`user:01J...`). The account is loaded live from the database on every |
| 3640 | -request and never trusted from the frame, so a service holding a stale id acts | |
| 3677 | +request — from the named school's database, never the control one — and never | |
| 3678 | +trusted from the frame, so a service holding a stale id acts | |
| 3641 | 3679 | as a user who has since been deleted (`unknown_user`) or demoted (the new role, |
| 3642 | 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 | 3701 | `ApiRequest` has `path`, a `BlobRequest` has `file`. |
| 3664 | 3702 | |
| 3665 | 3703 | ```json |
| 3666 | -{ "id": "01J...", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V", | |
| 3704 | +{ "id": "01J...", "school": "demo", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V", | |
| 3667 | 3705 | "on_behalf_of": "user:01J..." } |
| 3668 | 3706 | ``` |
| 3669 | 3707 | |
| 3670 | -`file` is a `course_note_file` record key — the id `GET | |
| 3708 | +`school` names the school the file belongs to; the bytes are read from that | |
| 3709 | +school's own blob directory, so a file id is meaningless outside it. `file` is | |
| 3710 | +a `course_note_file` record key — the id `GET | |
| 3671 | 3711 | /course-notes/{id}/files` publishes and the one every `rag.index` payload |
| 3672 | 3712 | carries in `files[].id`. `on_behalf_of` is optional on the wire but required in |
| 3673 | 3713 | 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 | 3719 | no HTTP status to collide with: |
| 3680 | 3720 | |
| 3681 | 3721 | ```json |
| 3682 | -{ "status": "ok", "id": "01J...", "name": "recap.pdf", | |
| 3722 | +{ "status": "ok", "id": "01J...", "school": "demo", "name": "recap.pdf", | |
| 3683 | 3723 | "content_type": "application/pdf", "size": 204800 } |
| 3684 | -{ "status": "err", "id": "01J...", "code": "forbidden", | |
| 3724 | +{ "status": "err", "id": "01J...", "school": "demo", "code": "forbidden", | |
| 3685 | 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 | 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 | 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 | 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 | 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 | 3780 | ### Conformance suite |
| 3739 | 3781 | |
| 3740 | 3782 | `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 | 3784 | frames built as byte literals, answers parsed as untyped JSON — so it fails on |
| 3743 | 3785 | exactly the changes a service in another language would notice: a renamed |
| 3744 | 3786 | field, a re-tagged enum, a flipped length-prefix endianness, a newly-required |
| 3745 | -`Hello` field. (`tests/ai_bridge.rs` drives real QUIC clients too, but shares | |
| 3787 | +`Hello` field, a frame that stopped naming its school. (`tests/ai_bridge.rs` | |
| 3788 | +drives real QUIC clients too, but shares | |
| 3746 | 3789 | the Rust structs with the backend, so it cannot see those.) |
| 3747 | 3790 | |
| 3748 | 3791 | 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 | 3818 | GET /ai/certificate # no auth; 404 when the bridge is disabled |
| 3776 | -{ "protocol": "hab/1", | |
| 3819 | +{ "protocol": "hab/2", | |
| 3777 | 3820 | "certificate_pem": "-----BEGIN CERTIFICATE-----\n...", |
| 3778 | 3821 | "fingerprint_sha256": "6745e8..." } |
| 3779 | 3822 | ``` |
| @@ -3846,7 +3889,7 @@ closes. A stream opened *after* the answer already landed still emits | ||
| 3846 | 3889 | `delta`s and a `done` — the replay is deliberate, so a client that connects |
| 3847 | 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` is | |
| 3892 | +**The deltas are sliced by the backend from the finished answer.** `hab/2` is | |
| 3850 | 3893 | unary — the service returns the whole reply text, not tokens — so today the |
| 3851 | 3894 | chunking is cosmetic pacing, not real streaming. The event shape exists now so |
| 3852 | 3895 | 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 | 3965 | ### The `chat.reply` capability (for AI-service authors) |
| 3923 | 3966 | |
| 3924 | 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 | 3971 | ```json |
| 3928 | 3972 | { "message": "and the second law?", |
| @@ -3969,7 +4013,8 @@ context without either end having to be redeployed in lockstep. | ||
| 3969 | 4013 | An indexing service declares `rag.index` in its `Hello` (see "AI bridge |
| 3970 | 4014 | (QUIC)"). The backend dispatches one request whenever a course note is |
| 3971 | 4015 | 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 | 4019 | ```json |
| 3975 | 4020 | { "course_note": "01J8XZ0K3Q8G7X2M4N5P6R7S8T", |
| @@ -4560,5 +4605,5 @@ db), rate-limit (both tiers, proxy-header and peer-address keying, shipped | ||
| 4560 | 4605 | limits over every route, two limiters sharing one budget over one db), e2e |
| 4561 | 4606 | (real TCP + reqwest cookie jar), persistence |
| 4562 | 4607 | (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 | 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 | 3 | //! # Shape |
| 4 | 4 | //! |
| @@ -33,6 +33,19 @@ | ||
| 33 | 33 | //! The two client-initiated request shapes are told apart by their required |
| 34 | 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 | 49 | //! There is deliberately no correlation-id matching: QUIC stream IDs already |
| 37 | 50 | //! multiplex concurrent requests over the one connection, independently |
| 38 | 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 | 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 | 85 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 69 | 86 | pub struct Hello { |
| 70 | 87 | /// Must equal [`crate::constant::AI_PROTOCOL`]; anything else is rejected |
| @@ -118,6 +135,9 @@ pub enum RejectCode { | ||
| 118 | 135 | pub struct Request { |
| 119 | 136 | /// Trace id (ULID). Not used for correlation — the stream does that. |
| 120 | 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 | 141 | /// Which capability from the worker's [`Hello::capabilities`] to invoke. |
| 122 | 142 | pub capability: String, |
| 123 | 143 | /// How long the backend will wait before abandoning the stream. The |
| @@ -135,10 +155,14 @@ pub struct Request { | ||
| 135 | 155 | pub enum Response { |
| 136 | 156 | Ok { |
| 137 | 157 | id: String, |
| 158 | + /// Echo of [`Request::school`]. | |
| 159 | + school: String, | |
| 138 | 160 | payload: Value, |
| 139 | 161 | }, |
| 140 | 162 | Err { |
| 141 | 163 | id: String, |
| 164 | + /// Echo of [`Request::school`]. | |
| 165 | + school: String, | |
| 142 | 166 | /// Service-defined, stable, machine-readable (`"unsupported_image"`). |
| 143 | 167 | code: String, |
| 144 | 168 | message: String, |
| @@ -151,6 +175,9 @@ pub enum Response { | ||
| 151 | 175 | pub struct ApiRequest { |
| 152 | 176 | /// Trace id (ULID). Not used for correlation — the stream does that. |
| 153 | 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 | 181 | /// Path as the REST API spells it, e.g. `"/users/me"`. No host, no query. |
| 155 | 182 | pub path: String, |
| 156 | 183 | /// Query string without the leading `?`, e.g. `"limit=10&offset=0"`. |
| @@ -174,13 +201,20 @@ pub struct ApiRequest { | ||
| 174 | 201 | pub enum ApiResponse { |
| 175 | 202 | Ok { |
| 176 | 203 | id: String, |
| 204 | + /// Echo of [`ApiRequest::school`]. | |
| 205 | + school: String, | |
| 177 | 206 | /// HTTP status the router produced. |
| 178 | 207 | status: u16, |
| 179 | 208 | body: Value, |
| 180 | 209 | }, |
| 181 | 210 | Err { |
| 182 | 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 | 218 | code: String, |
| 185 | 219 | message: String, |
| 186 | 220 | }, |
| @@ -193,6 +227,9 @@ pub enum ApiResponse { | ||
| 193 | 227 | pub struct BlobRequest { |
| 194 | 228 | /// Trace id (ULID). Not used for correlation — the stream does that. |
| 195 | 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 | 233 | /// The `course_note_file` record key, as `GET /course-notes/{id}/files` |
| 197 | 234 | /// and the `rag.index` payload both publish it. |
| 198 | 235 | pub file: String, |
| @@ -210,6 +247,8 @@ pub struct BlobRequest { | ||
| 210 | 247 | pub enum BlobResponse { |
| 211 | 248 | Ok { |
| 212 | 249 | id: String, |
| 250 | + /// Echo of [`BlobRequest::school`]. | |
| 251 | + school: String, | |
| 213 | 252 | name: String, |
| 214 | 253 | content_type: String, |
| 215 | 254 | /// Exactly how many raw bytes follow this frame. |
| @@ -217,6 +256,8 @@ pub enum BlobResponse { | ||
| 217 | 256 | }, |
| 218 | 257 | Err { |
| 219 | 258 | id: String, |
| 259 | + /// Echo of the school the frame named, as sent. | |
| 260 | + school: String, | |
| 220 | 261 | /// Bridge-defined, stable, machine-readable (`"not_found"`). |
| 221 | 262 | code: String, |
| 222 | 263 | message: String, |
| @@ -313,10 +354,12 @@ mod tests { | ||
| 313 | 354 | let (mut client, mut server) = tokio::io::duplex(64 * 1024); |
| 314 | 355 | let a = Response::Ok { |
| 315 | 356 | id: "a".into(), |
| 357 | + school: "demo".into(), | |
| 316 | 358 | payload: json!({ "n": 1 }), |
| 317 | 359 | }; |
| 318 | 360 | let b = Response::Err { |
| 319 | 361 | id: "b".into(), |
| 362 | + school: "demo".into(), | |
| 320 | 363 | code: "bad_input".into(), |
| 321 | 364 | message: "nope".into(), |
| 322 | 365 | }; |
| @@ -394,6 +437,7 @@ mod tests { | ||
| 394 | 437 | assert_eq!(rejected["code"], "unauthorized"); |
| 395 | 438 | let ok = serde_json::to_value(Response::Ok { |
| 396 | 439 | id: "1".into(), |
| 440 | + school: "demo".into(), | |
| 397 | 441 | payload: json!(null), |
| 398 | 442 | }) |
| 399 | 443 | .unwrap(); |
| @@ -406,6 +450,7 @@ mod tests { | ||
| 406 | 450 | // The tag is `outcome`, not `status` — `status` is the HTTP code. |
| 407 | 451 | let ok = serde_json::to_value(ApiResponse::Ok { |
| 408 | 452 | id: "1".into(), |
| 453 | + school: "demo".into(), | |
| 409 | 454 | status: 404, |
| 410 | 455 | body: json!(null), |
| 411 | 456 | }) |
| @@ -414,6 +459,7 @@ mod tests { | ||
| 414 | 459 | assert_eq!(ok["status"], 404); |
| 415 | 460 | let err = serde_json::to_value(ApiResponse::Err { |
| 416 | 461 | id: "1".into(), |
| 462 | + school: "demo".into(), | |
| 417 | 463 | code: "path_not_allowed".into(), |
| 418 | 464 | message: "nope".into(), |
| 419 | 465 | }) |
| @@ -423,18 +469,26 @@ mod tests { | ||
| 423 | 469 | } |
| 424 | 470 | |
| 425 | 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 | 473 | let bare: ApiRequest = serde_json::from_value(json!({ |
| 428 | 474 | "id": "01J", |
| 475 | + "school": "demo", | |
| 429 | 476 | "path": "/users/me", |
| 430 | 477 | })) |
| 431 | 478 | .unwrap(); |
| 432 | 479 | assert_eq!(bare.query, None); |
| 433 | 480 | assert_eq!(bare.on_behalf_of, None); |
| 434 | 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 | 489 | let full = ApiRequest { |
| 437 | 490 | id: "01J".into(), |
| 491 | + school: "demo".into(), | |
| 438 | 492 | path: "/notes".into(), |
| 439 | 493 | query: Some("limit=10".into()), |
| 440 | 494 | on_behalf_of: Some("user:abc".into()), |
| @@ -442,6 +496,7 @@ mod tests { | ||
| 442 | 496 | method: Some("GET".into()), |
| 443 | 497 | }; |
| 444 | 498 | let raw = serde_json::to_value(&full).unwrap(); |
| 499 | + assert_eq!(raw["school"], "demo"); | |
| 445 | 500 | assert_eq!(raw["path"], "/notes"); |
| 446 | 501 | assert_eq!(raw["query"], "limit=10"); |
| 447 | 502 | assert_eq!(raw["on_behalf_of"], "user:abc"); |
| @@ -456,6 +511,7 @@ mod tests { | ||
| 456 | 511 | // carries no HTTP status for it to collide with. |
| 457 | 512 | let ok = serde_json::to_value(BlobResponse::Ok { |
| 458 | 513 | id: "1".into(), |
| 514 | + school: "demo".into(), | |
| 459 | 515 | name: "recap.pdf".into(), |
| 460 | 516 | content_type: "application/pdf".into(), |
| 461 | 517 | size: 204_800, |
| @@ -465,6 +521,7 @@ mod tests { | ||
| 465 | 521 | assert_eq!(ok["size"], 204_800); |
| 466 | 522 | let err = serde_json::to_value(BlobResponse::Err { |
| 467 | 523 | id: "1".into(), |
| 524 | + school: "demo".into(), | |
| 468 | 525 | code: "not_found".into(), |
| 469 | 526 | message: "nope".into(), |
| 470 | 527 | }) |
| @@ -475,14 +532,22 @@ mod tests { | ||
| 475 | 532 | // `file` is what tells a blob request apart from an api read, so it is |
| 476 | 533 | // required; `on_behalf_of` is the only optional field. |
| 477 | 534 | let bare: BlobRequest = serde_json::from_value(json!({ |
| 478 | - "id": "01J", "file": "01FILE", | |
| 535 | + "id": "01J", "school": "demo", "file": "01FILE", | |
| 479 | 536 | })) |
| 480 | 537 | .unwrap(); |
| 481 | 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 | 545 | // And the two shapes never parse as each other. |
| 484 | 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 | 20 | use crate::domain::course_note_file::CourseNoteFile; |
| 21 | 21 | use crate::domain::rag_output::RagOutput; |
| 22 | 22 | use crate::state::AppState; |
| 23 | +use crate::tenant::Slug; | |
| 23 | 24 | |
| 24 | 25 | /// The capability string routed to an indexing service. Defined once, in |
| 25 | 26 | /// [`crate::constant`]; re-exported here so a reader of the payload contract |
| @@ -80,7 +81,11 @@ impl RagIndexPayload { | ||
| 80 | 81 | /// Re-index `note` and replace its stored outputs with what the service |
| 81 | 82 | /// answered. Silent no-op when the bridge is off or no worker offers |
| 82 | 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 | 89 | let Some(bridge) = state.ai.as_ref() else { |
| 85 | 90 | return; |
| 86 | 91 | }; |
| @@ -107,6 +112,7 @@ pub async fn index_course_note(state: &AppState, note: &CourseNote) { | ||
| 107 | 112 | |
| 108 | 113 | let answer = match bridge |
| 109 | 114 | .dispatch_with_timeout( |
| 115 | + school, | |
| 110 | 116 | AI_RAG_INDEX_CAPABILITY, |
| 111 | 117 | payload, |
| 112 | 118 | std::time::Duration::from_secs(AI_RAG_INDEX_TIMEOUT_SECS), |
| @@ -151,10 +157,11 @@ async fn replace( | ||
| 151 | 157 | |
| 152 | 158 | /// [`index_course_note`] off the request path: the handler has already |
| 153 | 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 | 161 | // Cheap when AI is off — the spawned task returns on the first `let else`. |
| 156 | 162 | let state = state.clone(); |
| 157 | - tokio::spawn(async move { index_course_note(&state, ¬e).await }); | |
| 163 | + let school = school.clone(); | |
| 164 | + tokio::spawn(async move { index_course_note(&state, &school, ¬e).await }); | |
| 158 | 165 | } |
| 159 | 166 | |
| 160 | 167 | #[cfg(test)] |
src/ai/server.rsmodified+95 -56
| @@ -24,6 +24,7 @@ use crate::constant::{ | ||
| 24 | 24 | REQUEST_TIMEOUT_SECS, |
| 25 | 25 | }; |
| 26 | 26 | use crate::database::Database; |
| 27 | +use crate::error::AppError; | |
| 27 | 28 | use crate::domain::course::Course; |
| 28 | 29 | use crate::domain::course_note::CourseNote; |
| 29 | 30 | use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; |
| @@ -50,40 +51,52 @@ pub struct BridgeConfig { | ||
| 50 | 51 | } |
| 51 | 52 | |
| 52 | 53 | /// What an api read needs to be answered: the router to dispatch into, the |
| 53 | -/// school the acting principal is loaded from, and the liveness flag that | |
| 54 | +/// registry every school is resolved through, and the liveness flag that | |
| 54 | 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 | 59 | struct ApiHandle { |
| 56 | 60 | router: axum::Router, |
| 57 | 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 | 62 | db_up: DbHealth, |
| 68 | - /// Where uploaded blobs live — the deployment root; the school's own | |
| 63 | + /// Where uploaded blobs live — the deployment root; a school's own | |
| 69 | 64 | /// directory is [`school_files_path`] of it. |
| 70 | 65 | files_path: std::path::PathBuf, |
| 71 | 66 | } |
| 72 | 67 | |
| 73 | 68 | impl ApiHandle { |
| 74 | - /// The school database this bridge reads, or the refusal a service gets. | |
| 75 | - async fn db(&self) -> Result<Database, (&'static str, String)> { | |
| 76 | - self.tenants.get(&self.slug).await.map_err(|err| { | |
| 77 | - ( | |
| 69 | + /// Resolve the slug a frame named into that school's database, or the | |
| 70 | + /// refusal the service gets. | |
| 71 | + /// | |
| 72 | + /// The three codes are distinct on purpose: `malformed` is the service's | |
| 73 | + /// own bug (that string is no slug), `unknown_school` means the deployment | |
| 74 | + /// has no such customer, and `school_suspended` means it has one that is | |
| 75 | + /// switched off — a service that retries the first two forever learns | |
| 76 | + /// nothing, while the third is worth retrying later. | |
| 77 | + async fn school(&self, school: &str) -> Result<(Slug, Database), (&'static str, String)> { | |
| 78 | + let slug = Slug::try_new(school) | |
| 79 | + .map_err(|err| ("malformed", format!("`{school}` is not a school slug: {err}")))?; | |
| 80 | + let db = self.tenants.get(&slug).await.map_err(|err| match err { | |
| 81 | + AppError::Unauthorized => ( | |
| 82 | + "unknown_school", | |
| 83 | + format!("this deployment serves no `{slug}` school"), | |
| 84 | + ), | |
| 85 | + AppError::Forbidden(_) => ( | |
| 86 | + "school_suspended", | |
| 87 | + format!("the `{slug}` school is suspended"), | |
| 88 | + ), | |
| 89 | + other => ( | |
| 78 | 90 | "unavailable", |
| 79 | - format!("the `{}` school is not reachable: {err}", self.slug), | |
| 80 | - ) | |
| 81 | - }) | |
| 91 | + format!("the `{slug}` school is not reachable: {other}"), | |
| 92 | + ), | |
| 93 | + })?; | |
| 94 | + Ok((slug, db)) | |
| 82 | 95 | } |
| 83 | 96 | |
| 84 | - /// That school's blob directory. | |
| 85 | - fn files_dir(&self) -> std::path::PathBuf { | |
| 86 | - school_files_path(&self.files_path, &self.slug) | |
| 97 | + /// One school's blob directory. | |
| 98 | + fn files_dir(&self, slug: &Slug) -> std::path::PathBuf { | |
| 99 | + school_files_path(&self.files_path, slug) | |
| 87 | 100 | } |
| 88 | 101 | } |
| 89 | 102 | |
| @@ -188,8 +201,13 @@ impl AiBridge { | ||
| 188 | 201 | /// Each call takes a fresh QUIC bidirectional stream, so concurrent calls |
| 189 | 202 | /// over the same connection neither block nor interleave: the stream *is* |
| 190 | 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> { | |
| 192 | - self.dispatch_with_timeout(capability, payload, self.inner.request_timeout) | |
| 204 | + pub async fn dispatch( | |
| 205 | + &self, | |
| 206 | + school: &Slug, | |
| 207 | + capability: &str, | |
| 208 | + payload: Value, | |
| 209 | + ) -> Result<Value, AiError> { | |
| 210 | + self.dispatch_with_timeout(school, capability, payload, self.inner.request_timeout) | |
| 193 | 211 | .await |
| 194 | 212 | } |
| 195 | 213 | |
| @@ -198,6 +216,7 @@ impl AiBridge { | ||
| 198 | 216 | /// generation). |
| 199 | 217 | pub async fn dispatch_with_timeout( |
| 200 | 218 | &self, |
| 219 | + school: &Slug, | |
| 201 | 220 | capability: &str, |
| 202 | 221 | payload: Value, |
| 203 | 222 | timeout: Duration, |
| @@ -210,6 +229,7 @@ impl AiBridge { | ||
| 210 | 229 | let deadline_ms = timeout.as_millis().min(u64::MAX as u128) as u64; |
| 211 | 230 | let request = Request { |
| 212 | 231 | id: id.clone(), |
| 232 | + school: school.as_str().to_string(), | |
| 213 | 233 | capability: capability.to_string(), |
| 214 | 234 | deadline_ms, |
| 215 | 235 | payload, |
| @@ -248,6 +268,7 @@ impl AiBridge { | ||
| 248 | 268 | id: got, |
| 249 | 269 | code, |
| 250 | 270 | message, |
| 271 | + .. | |
| 251 | 272 | } if got == id => Err(AiError::Remote { code, message }), |
| 252 | 273 | // A mismatched id means the service is not tracking which stream it |
| 253 | 274 | // is on. Nothing here depends on the id for correlation, but the |
| @@ -278,7 +299,6 @@ impl AiBridge { | ||
| 278 | 299 | .set(ApiHandle { |
| 279 | 300 | router, |
| 280 | 301 | tenants, |
| 281 | - slug: Slug::try_new(crate::tenant::DEMO_SLUG).expect("the demo slug is a slug"), | |
| 282 | 302 | db_up, |
| 283 | 303 | files_path, |
| 284 | 304 | }) |
| @@ -369,17 +389,16 @@ async fn serve_client_stream( | ||
| 369 | 389 | Err(e) => { |
| 370 | 390 | answer( |
| 371 | 391 | &mut send, |
| 372 | - refusal(String::new(), "malformed", e.to_string()), | |
| 392 | + refusal(String::new(), String::new(), "malformed", e.to_string()), | |
| 373 | 393 | ) |
| 374 | 394 | .await; |
| 375 | 395 | return; |
| 376 | 396 | } |
| 377 | 397 | }; |
| 378 | - let id = raw | |
| 379 | - .get("id") | |
| 380 | - .and_then(Value::as_str) | |
| 381 | - .unwrap_or_default() | |
| 382 | - .to_string(); | |
| 398 | + let id = string_field(&raw, "id"); | |
| 399 | + // Echoed verbatim on a refusal, before it is known to be a slug at all: | |
| 400 | + // it is how the service tells which of its in-flight reads was refused. | |
| 401 | + let school = string_field(&raw, "school"); | |
| 383 | 402 | // Routed on the shape's required field rather than by parsing one and |
| 384 | 403 | // falling back to the other: that fallback cloned the whole `Value` on |
| 385 | 404 | // every api read. `path` still wins when a frame carries both. |
| @@ -387,9 +406,9 @@ async fn serve_client_stream( | ||
| 387 | 406 | let response = match serde_json::from_value::<ApiRequest>(raw) { |
| 388 | 407 | Ok(request) => match read_api(&inner, request).await { |
| 389 | 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 | 413 | answer(&mut send, response).await; |
| 395 | 414 | return; |
| @@ -397,7 +416,7 @@ async fn serve_client_stream( | ||
| 397 | 416 | if raw.get("file").is_some() { |
| 398 | 417 | match serde_json::from_value::<BlobRequest>(raw) { |
| 399 | 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 | 421 | return; |
| 403 | 422 | } |
| @@ -406,7 +425,16 @@ async fn serve_client_stream( | ||
| 406 | 425 | let api_err = serde_json::from_value::<ApiRequest>(raw) |
| 407 | 426 | .err() |
| 408 | 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 | 440 | /// Answer one blob read: the [`BlobResponse`] header frame, then — on `Ok` — |
| @@ -417,6 +445,7 @@ async fn serve_client_stream( | ||
| 417 | 445 | /// because such a thing does not fit a frame. |
| 418 | 446 | async fn serve_blob(inner: &Inner, send: &mut quinn::SendStream, request: BlobRequest) { |
| 419 | 447 | let id = request.id.clone(); |
| 448 | + let school = request.school.clone(); | |
| 420 | 449 | match open_blob(inner, request).await { |
| 421 | 450 | Ok((header, mut file)) => { |
| 422 | 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 | 462 | Err((code, message)) => { |
| 434 | 463 | let refused = BlobResponse::Err { |
| 435 | 464 | id, |
| 465 | + school, | |
| 436 | 466 | code: code.to_string(), |
| 437 | 467 | message, |
| 438 | 468 | }; |
| @@ -497,8 +527,8 @@ async fn open_blob( | ||
| 497 | 527 | "the database socket is down — retry".to_string(), |
| 498 | 528 | )); |
| 499 | 529 | } |
| 500 | - let db = api.db().await?; | |
| 501 | - let user = principal(api, request.on_behalf_of.as_deref()).await?; | |
| 530 | + let (slug, db) = api.school(&request.school).await?; | |
| 531 | + let user = principal(&db, request.on_behalf_of.as_deref()).await?; | |
| 502 | 532 | |
| 503 | 533 | let missing = || { |
| 504 | 534 | ( |
| @@ -534,7 +564,7 @@ async fn open_blob( | ||
| 534 | 564 | |
| 535 | 565 | // The row exists but its blob does not: server-side damage (a lost volume |
| 536 | 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 | 568 | let handle = tokio::fs::File::open(&path).await.map_err(|e| { |
| 539 | 569 | ( |
| 540 | 570 | "unavailable", |
| @@ -555,6 +585,7 @@ async fn open_blob( | ||
| 555 | 585 | Ok(( |
| 556 | 586 | BlobResponse::Ok { |
| 557 | 587 | id: request.id, |
| 588 | + school: request.school, | |
| 558 | 589 | name: file.get_name().as_str().to_string(), |
| 559 | 590 | content_type: file.get_content_type().as_str().to_string(), |
| 560 | 591 | size, |
| @@ -565,20 +596,18 @@ async fn open_blob( | ||
| 565 | 596 | |
| 566 | 597 | /// Who a client-initiated read runs as. |
| 567 | 598 | /// |
| 568 | -/// Loaded live, never trusted from the frame: a service holding a stale id must | |
| 569 | -/// not act as a user who has since been deleted or demoted. With nobody named | |
| 570 | -/// the principal is the synthetic `ai` role. | |
| 571 | -async fn principal( | |
| 572 | - api: &ApiHandle, | |
| 573 | - on_behalf_of: Option<&str>, | |
| 574 | -) -> Result<User, (&'static str, String)> { | |
| 599 | +/// Loaded live out of the *school's own* database — never the control one and | |
| 600 | +/// never trusted from the frame: a service holding a stale id must not act as a | |
| 601 | +/// user who has since been deleted or demoted, nor as a same-named user of | |
| 602 | +/// another school. With nobody named the principal is the synthetic `ai` role. | |
| 603 | +async fn principal(db: &Database, on_behalf_of: Option<&str>) -> Result<User, (&'static str, String)> { | |
| 575 | 604 | let Some(who) = on_behalf_of else { |
| 576 | 605 | return Ok(User::ai_principal()); |
| 577 | 606 | }; |
| 578 | 607 | // Both the bare key (`abc`, as a REST path spells it) and the record form |
| 579 | 608 | // (`user:abc`) are accepted. |
| 580 | 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 | 611 | .await |
| 583 | 612 | .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))? |
| 584 | 613 | .ok_or_else(|| ("unknown_user", format!("no user `{who}`"))) |
| @@ -639,6 +668,7 @@ async fn dispatch_api( | ||
| 639 | 668 | ) -> Result<ApiResponse, (&'static str, String)> { |
| 640 | 669 | let ApiRequest { |
| 641 | 670 | id, |
| 671 | + school, | |
| 642 | 672 | path, |
| 643 | 673 | query, |
| 644 | 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 | 692 | // The role itself is re-read again by the extractor on the dispatched |
| 659 | 693 | // request; see [`principal`] for why it is never taken from the frame. |
| 660 | - let db = api.db().await?; | |
| 661 | - let user = principal(api, on_behalf_of.as_deref()).await?; | |
| 694 | + let user = principal(&db, on_behalf_of.as_deref()).await?; | |
| 662 | 695 | |
| 663 | 696 | let target = match query.as_deref() { |
| 664 | 697 | Some(query) if !query.is_empty() => format!("{path}?{query}"), |
| @@ -679,10 +712,7 @@ async fn dispatch_api( | ||
| 679 | 712 | dispatched.extensions_mut().insert(AiPrincipal(user)); |
| 680 | 713 | // The dispatched request carries no cookie, so the school is handed over |
| 681 | 714 | // in the extension the shadow `State` reads first. |
| 682 | - dispatched.extensions_mut().insert(TenantExt { | |
| 683 | - slug: api.slug.clone(), | |
| 684 | - db, | |
| 685 | - }); | |
| 715 | + dispatched.extensions_mut().insert(TenantExt { slug, db }); | |
| 686 | 716 | |
| 687 | 717 | let response = tokio::time::timeout( |
| 688 | 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 | 760 | ApiResponse::Err { |
| 726 | 761 | id, |
| 762 | + school, | |
| 727 | 763 | code: code.to_string(), |
| 728 | 764 | message, |
| 729 | 765 | } |
| @@ -750,11 +786,13 @@ async fn write_answer<W: tokio::io::AsyncWrite + Unpin>( | ||
| 750 | 786 | response: &ApiResponse, |
| 751 | 787 | ) -> Result<(), FrameError> { |
| 752 | 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 | 791 | return write_frame( |
| 755 | 792 | w, |
| 756 | 793 | &refusal( |
| 757 | 794 | id.clone(), |
| 795 | + school.clone(), | |
| 758 | 796 | "too_large", |
| 759 | 797 | format!("the answer exceeds the {AI_MAX_FRAME_BYTES}-byte frame limit"), |
| 760 | 798 | ), |
| @@ -896,7 +934,7 @@ mod tests { | ||
| 896 | 934 | refuse_before_dispatch, |
| 897 | 935 | }; |
| 898 | 936 | use crate::ai::protocol::read_frame; |
| 899 | - use crate::tenant::Slug; | |
| 937 | + use crate::tenant::DEMO_SLUG; | |
| 900 | 938 | |
| 901 | 939 | /// An armed handle serving `router`. The database is never touched by these |
| 902 | 940 | /// reads (nobody is named, so the principal is synthetic), but the handle |
| @@ -907,7 +945,6 @@ mod tests { | ||
| 907 | 945 | tenants: crate::database::init_mem_tenants() |
| 908 | 946 | .await |
| 909 | 947 | .expect("in-memory deployment"), |
| 910 | - slug: Slug::try_new(crate::tenant::DEMO_SLUG).unwrap(), | |
| 911 | 948 | db_up: Default::default(), |
| 912 | 949 | files_path: std::env::temp_dir(), |
| 913 | 950 | } |
| @@ -917,6 +954,7 @@ mod tests { | ||
| 917 | 954 | fn read_of(path: &str) -> ApiRequest { |
| 918 | 955 | ApiRequest { |
| 919 | 956 | id: "trace-1".to_string(), |
| 957 | + school: DEMO_SLUG.to_string(), | |
| 920 | 958 | path: path.to_string(), |
| 921 | 959 | query: None, |
| 922 | 960 | on_behalf_of: None, |
| @@ -987,6 +1025,7 @@ mod tests { | ||
| 987 | 1025 | // frame may precede it on the stream. |
| 988 | 1026 | let big = ApiResponse::Ok { |
| 989 | 1027 | id: "trace-1".to_string(), |
| 1028 | + school: DEMO_SLUG.to_string(), | |
| 990 | 1029 | status: 200, |
| 991 | 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 | 514 | /// and used as the QUIC ALPN. Bump both together on a breaking frame change: |
| 515 | 515 | /// ALPN mismatch rejects an old service at the TLS handshake, before it can |
| 516 | 516 | /// send a frame we would misparse. |
| 517 | -pub const AI_PROTOCOL: &str = "hab/1"; | |
| 518 | -pub const AI_ALPN: &[u8] = b"hab/1"; | |
| 517 | +pub const AI_PROTOCOL: &str = "hab/2"; | |
| 518 | +pub const AI_ALPN: &[u8] = b"hab/2"; | |
| 519 | 519 | |
| 520 | 520 | /// Hard ceiling on one AI-bridge frame. Checked against the length prefix |
| 521 | 521 | /// 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 | 42 | modifiers(&SecurityAddon), |
| 43 | 43 | tags( |
| 44 | 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 | 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 | 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 | 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 | 35 | /// (which is a secret and is configured out of band). |
| 36 | 36 | #[derive(Serialize, ToSchema)] |
| 37 | 37 | pub struct BridgeCertificateResponse { |
| 38 | - /// Wire protocol and ALPN the service must announce, currently `hab/1`. | |
| 39 | - #[schema(example = "hab/1")] | |
| 38 | + /// Wire protocol and ALPN the service must announce, currently `hab/2`. | |
| 39 | + #[schema(example = "hab/2")] | |
| 40 | 40 | protocol: String, |
| 41 | 41 | /// The listener's leaf certificate, PEM-encoded — feed straight into a TLS |
| 42 | 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 | 21 | use std::time::Duration; |
| 22 | 22 | |
| 23 | -use crate::web::tenant_state::State; | |
| 23 | +use crate::web::tenant_state::{SchoolSlug, State, TenantExt}; | |
| 24 | 24 | use axum::Json; |
| 25 | 25 | use axum::extract::{Path, Query}; |
| 26 | 26 | use axum::http::StatusCode; |
| @@ -377,6 +377,7 @@ async fn list_messages( | ||
| 377 | 377 | )] |
| 378 | 378 | async fn send_message( |
| 379 | 379 | State(st): State<AppState>, |
| 380 | + SchoolSlug(school): SchoolSlug, | |
| 380 | 381 | CurrentUser(user): CurrentUser, |
| 381 | 382 | Path(id): Path<String>, |
| 382 | 383 | Json(req): Json<SendChatbotMessage>, |
| @@ -436,8 +437,14 @@ async fn send_message( | ||
| 436 | 437 | // request), so it is the live role at the moment the question was asked — |
| 437 | 438 | // never a stored copy, and never anything the body could assert. |
| 438 | 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 | 447 | bridge, |
| 440 | - st.db.clone(), | |
| 441 | 448 | prompt.get_id().clone(), |
| 442 | 449 | answer, |
| 443 | 450 | user.get_role(), |
| @@ -477,14 +484,15 @@ fn unavailable(message: &str) -> Response { | ||
| 477 | 484 | /// |
| 478 | 485 | /// Every path settles: a row left `pending` would show as a spinner forever. |
| 479 | 486 | async fn answer_turn( |
| 487 | + tenant: TenantExt, | |
| 480 | 488 | bridge: AiBridge, |
| 481 | - db: Database, | |
| 482 | 489 | prompt_id: ChatbotMessageId, |
| 483 | 490 | answer: ChatbotMessage, |
| 484 | 491 | asker_role: Role, |
| 485 | 492 | history_turns: usize, |
| 486 | 493 | reply_cap: usize, |
| 487 | 494 | ) { |
| 495 | + let db = tenant.db.clone(); | |
| 488 | 496 | let answer_id = answer.get_id().clone(); |
| 489 | 497 | let thread = answer.get_thread_id().clone(); |
| 490 | 498 | // This request's own question, read back by id — the text is already |
| @@ -511,7 +519,7 @@ async fn answer_turn( | ||
| 511 | 519 | let fresh = [prompt.get_id().clone(), answer_id.clone()]; |
| 512 | 520 | let settled = match fetch_reply( |
| 513 | 521 | &bridge, |
| 514 | - &db, | |
| 522 | + &tenant, | |
| 515 | 523 | &thread, |
| 516 | 524 | &fresh, |
| 517 | 525 | prompt.get_content().as_str().to_string(), |
| @@ -542,7 +550,7 @@ async fn answer_turn( | ||
| 542 | 550 | /// The bridge round trip, with every failure mapped to a stable code. |
| 543 | 551 | async fn fetch_reply( |
| 544 | 552 | bridge: &AiBridge, |
| 545 | - db: &Database, | |
| 553 | + tenant: &TenantExt, | |
| 546 | 554 | thread: &ChatbotThreadId, |
| 547 | 555 | fresh: &[ChatbotMessageId; 2], |
| 548 | 556 | prompt: String, |
| @@ -550,6 +558,7 @@ async fn fetch_reply( | ||
| 550 | 558 | history_turns: usize, |
| 551 | 559 | reply_cap: usize, |
| 552 | 560 | ) -> Result<(ChatContent, bool), String> { |
| 561 | + let db = &tenant.db; | |
| 553 | 562 | let history = match history_for(db, thread, fresh, history_turns).await { |
| 554 | 563 | Ok(history) => history, |
| 555 | 564 | Err(err) => { |
| @@ -568,7 +577,7 @@ async fn fetch_reply( | ||
| 568 | 577 | })?; |
| 569 | 578 | |
| 570 | 579 | let raw = bridge |
| 571 | - .dispatch(AI_CHAT_CAPABILITY, payload) | |
| 580 | + .dispatch(&tenant.slug, AI_CHAT_CAPABILITY, payload) | |
| 572 | 581 | .await |
| 573 | 582 | .map_err(failure_code)?; |
| 574 | 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 | 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 and | |
| 832 | +/// Fake streaming: `hab/2` is unary, so the whole text is already in hand and | |
| 824 | 833 | /// this only lets the UI paint it progressively instead of in one jump. The |
| 825 | 834 | /// day the protocol grows chunk frames, this is the single function that goes |
| 826 | 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 | 5 | //! teacher, or manager+), reads need [`super::courses::can_view_course`] |
| 6 | 6 | //! (management rights, or enrollment). |
| 7 | 7 | |
| 8 | -use crate::web::tenant_state::State; | |
| 8 | +use crate::web::tenant_state::{SchoolSlug, State}; | |
| 9 | 9 | use axum::Json; |
| 10 | 10 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; |
| 11 | 11 | use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; |
| @@ -126,6 +126,7 @@ impl CourseNoteResponse { | ||
| 126 | 126 | )] |
| 127 | 127 | async fn create( |
| 128 | 128 | State(st): State<AppState>, |
| 129 | + SchoolSlug(school): SchoolSlug, | |
| 129 | 130 | RequireTeacher(user): RequireTeacher, |
| 130 | 131 | Json(req): Json<CreateCourseNote>, |
| 131 | 132 | ) -> Result<(StatusCode, Json<CourseNoteResponse>), AppError> { |
| @@ -144,7 +145,7 @@ async fn create( | ||
| 144 | 145 | // Indexing is a background bonus, never a condition of storing the note: |
| 145 | 146 | // the dispatch runs in its own task, so a slow or absent AI service cannot |
| 146 | 147 | // delay or fail this 201. |
| 147 | - spawn_index(&st, note.clone()); | |
| 148 | + spawn_index(&st, &school, note.clone()); | |
| 148 | 149 | Ok((StatusCode::CREATED, Json(CourseNoteResponse::new(¬e)))) |
| 149 | 150 | } |
| 150 | 151 | |
| @@ -242,6 +243,7 @@ async fn get_one( | ||
| 242 | 243 | )] |
| 243 | 244 | async fn update( |
| 244 | 245 | State(st): State<AppState>, |
| 246 | + SchoolSlug(school): SchoolSlug, | |
| 245 | 247 | RequireTeacher(user): RequireTeacher, |
| 246 | 248 | Path(id): Path<String>, |
| 247 | 249 | Json(req): Json<UpdateCourseNote>, |
| @@ -267,7 +269,7 @@ async fn update( | ||
| 267 | 269 | |
| 268 | 270 | let updated = note.update(title, content, &st.db).await?; |
| 269 | 271 | // The stored index describes the old text — refresh it. |
| 270 | - spawn_index(&st, updated.clone()); | |
| 272 | + spawn_index(&st, &school, updated.clone()); | |
| 271 | 273 | Ok(Json(CourseNoteResponse::new(&updated))) |
| 272 | 274 | } |
| 273 | 275 | |
| @@ -365,6 +367,7 @@ impl CourseNoteFileResponse { | ||
| 365 | 367 | )] |
| 366 | 368 | async fn upload_file( |
| 367 | 369 | State(st): State<AppState>, |
| 370 | + SchoolSlug(school): SchoolSlug, | |
| 368 | 371 | RequireTeacher(user): RequireTeacher, |
| 369 | 372 | Path(id): Path<String>, |
| 370 | 373 | mut multipart: Multipart, |
| @@ -395,7 +398,7 @@ async fn upload_file( | ||
| 395 | 398 | match file.insert(&st.db).await { |
| 396 | 399 | Ok(created) => { |
| 397 | 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 | 402 | Ok(( |
| 400 | 403 | StatusCode::CREATED, |
| 401 | 404 | Json(CourseNoteFileResponse::new(&created)), |
| @@ -520,6 +523,7 @@ async fn download_file( | ||
| 520 | 523 | )] |
| 521 | 524 | async fn delete_file( |
| 522 | 525 | State(st): State<AppState>, |
| 526 | + SchoolSlug(school): SchoolSlug, | |
| 523 | 527 | RequireTeacher(user): RequireTeacher, |
| 524 | 528 | Path((id, file_id)): Path<(String, String)>, |
| 525 | 529 | ) -> Result<StatusCode, AppError> { |
| @@ -541,7 +545,7 @@ async fn delete_file( | ||
| 541 | 545 | RagOutput::delete_with_source(file.get_id(), &st.db).await?; |
| 542 | 546 | let file = file.delete(&st.db).await?; |
| 543 | 547 | remove_blob(&st.files_path, file.get_id().key()).await; |
| 544 | - spawn_index(&st, note); | |
| 548 | + spawn_index(&st, &school, note); | |
| 545 | 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 | 19 | use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; |
| 20 | 20 | use hezarfen_backend::constant::{AI_ALPN, AI_MAX_CONCURRENT_PER_WORKER, AI_PROTOCOL}; |
| 21 | +use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; | |
| 21 | 22 | use serde_json::{Value, json}; |
| 22 | 23 | |
| 23 | 24 | const TOKEN: &str = "shared-ai-token"; |
| @@ -68,6 +69,11 @@ fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint { | ||
| 68 | 69 | 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 | 77 | fn hello(service: &str, capabilities: &[&str]) -> Hello { |
| 72 | 78 | Hello { |
| 73 | 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 | 195 | Behaviour::Answer(payload) => Some(Response::Ok { |
| 190 | 196 | id: request.id.clone(), |
| 197 | + school: request.school.clone(), | |
| 191 | 198 | payload, |
| 192 | 199 | }), |
| 193 | 200 | Behaviour::Reply(text) => Some(Response::Ok { |
| 194 | 201 | id: request.id.clone(), |
| 202 | + school: request.school.clone(), | |
| 195 | 203 | payload: json!({ "text": text }), |
| 196 | 204 | }), |
| 197 | 205 | Behaviour::EchoPrompt => { |
| @@ -200,16 +208,19 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ | ||
| 200 | 208 | .unwrap_or("<no message>"); |
| 201 | 209 | Some(Response::Ok { |
| 202 | 210 | id: request.id.clone(), |
| 211 | + school: request.school.clone(), | |
| 203 | 212 | payload: json!({ "text": format!("cevap::{asked}") }), |
| 204 | 213 | }) |
| 205 | 214 | } |
| 206 | 215 | Behaviour::Fail { code, message } => Some(Response::Err { |
| 207 | 216 | id: request.id.clone(), |
| 217 | + school: request.school.clone(), | |
| 208 | 218 | code, |
| 209 | 219 | message, |
| 210 | 220 | }), |
| 211 | 221 | Behaviour::WrongId => Some(Response::Ok { |
| 212 | 222 | id: "01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string(), |
| 223 | + school: request.school.clone(), | |
| 213 | 224 | payload: json!("from some other request"), |
| 214 | 225 | }), |
| 215 | 226 | Behaviour::Garbage => { |
| @@ -241,6 +252,7 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ | ||
| 241 | 252 | fn echo(request: &Request) -> Response { |
| 242 | 253 | Response::Ok { |
| 243 | 254 | id: request.id.clone(), |
| 255 | + school: request.school.clone(), | |
| 244 | 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 | 297 | assert!(bridge.has_capability("ocr.extract")); |
| 286 | 298 | |
| 287 | 299 | let answer = bridge |
| 288 | - .dispatch("ocr.extract", json!({ "image": "abc" })) | |
| 300 | + .dispatch(&demo(), "ocr.extract", json!({ "image": "abc" })) | |
| 289 | 301 | .await |
| 290 | 302 | .expect("the service answered"); |
| 291 | 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 | 333 | let calls = (0..N).map(|i| { |
| 322 | 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 | 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 | 356 | let grader = connect_service(&bridge, hello("grader", &["grade.essay"]), Behaviour::Echo).await; |
| 345 | 357 | await_workers(&bridge, 2).await; |
| 346 | 358 | |
| 347 | - bridge.dispatch("grade.essay", json!("text")).await.unwrap(); | |
| 348 | - bridge.dispatch("ocr.extract", json!("png")).await.unwrap(); | |
| 359 | + bridge.dispatch(&demo(), "grade.essay", json!("text")).await.unwrap(); | |
| 360 | + bridge.dispatch(&demo(), "ocr.extract", json!("png")).await.unwrap(); | |
| 349 | 361 | |
| 350 | 362 | assert_eq!(ocr.seen().len(), 1, "ocr only saw its own capability"); |
| 351 | 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 | 414 | assert!(bridge.workers().is_empty()); |
| 403 | 415 | assert!(matches!( |
| 404 | - bridge.dispatch("ocr.extract", json!(null)).await, | |
| 416 | + bridge.dispatch(&demo(), "ocr.extract", json!(null)).await, | |
| 405 | 417 | Err(AiError::NoWorker(_)) |
| 406 | 418 | )); |
| 407 | 419 | } |
| @@ -502,7 +514,7 @@ async fn an_unknown_capability_fails_fast_instead_of_waiting() { | ||
| 502 | 514 | await_workers(&bridge, 1).await; |
| 503 | 515 | |
| 504 | 516 | let err = bridge |
| 505 | - .dispatch("grade.essay", json!(null)) | |
| 517 | + .dispatch(&demo(), "grade.essay", json!(null)) | |
| 506 | 518 | .await |
| 507 | 519 | .expect_err("nothing serves that capability"); |
| 508 | 520 | assert!( |
| @@ -527,7 +539,7 @@ async fn a_service_error_frame_surfaces_as_a_remote_error() { | ||
| 527 | 539 | await_workers(&bridge, 1).await; |
| 528 | 540 | |
| 529 | 541 | let err = bridge |
| 530 | - .dispatch("ocr.extract", json!({ "image": "x" })) | |
| 542 | + .dispatch(&demo(), "ocr.extract", json!({ "image": "x" })) | |
| 531 | 543 | .await |
| 532 | 544 | .unwrap_err(); |
| 533 | 545 | match &err { |
| @@ -550,7 +562,7 @@ async fn a_silent_service_times_out_and_gives_the_slot_back() { | ||
| 550 | 562 | await_workers(&bridge, 1).await; |
| 551 | 563 | |
| 552 | 564 | let err = bridge |
| 553 | - .dispatch("ocr.extract", json!(null)) | |
| 565 | + .dispatch(&demo(), "ocr.extract", json!(null)) | |
| 554 | 566 | .await |
| 555 | 567 | .unwrap_err(); |
| 556 | 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 | 572 | // An abandoned request must not leak the worker's capacity. |
| 561 | 573 | assert_eq!(bridge.workers()[0].inflight, 0); |
| 562 | 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 | 578 | #[tokio::test] |
| @@ -576,12 +588,12 @@ async fn a_per_call_timeout_overrides_the_default() { | ||
| 576 | 588 | |
| 577 | 589 | // The default deadline is too short for this service... |
| 578 | 590 | assert!(matches!( |
| 579 | - bridge.dispatch("ocr.extract", json!(null)).await, | |
| 591 | + bridge.dispatch(&demo(), "ocr.extract", json!(null)).await, | |
| 580 | 592 | Err(AiError::Timeout(100)) |
| 581 | 593 | )); |
| 582 | 594 | // ...but a capability known to be slow can ask for more. |
| 583 | 595 | 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 | 597 | .await |
| 586 | 598 | .expect("the longer deadline held"); |
| 587 | 599 | assert_eq!(answer["echo"], "slow"); |
| @@ -597,12 +609,12 @@ async fn a_full_worker_reports_busy_rather_than_queueing() { | ||
| 597 | 609 | |
| 598 | 610 | let hog = { |
| 599 | 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 | 614 | await_inflight(&bridge, 1).await; |
| 603 | 615 | |
| 604 | 616 | let err = bridge |
| 605 | - .dispatch("ocr.extract", json!(null)) | |
| 617 | + .dispatch(&demo(), "ocr.extract", json!(null)) | |
| 606 | 618 | .await |
| 607 | 619 | .unwrap_err(); |
| 608 | 620 | assert!( |
| @@ -626,7 +638,7 @@ async fn an_answer_carrying_the_wrong_trace_id_is_refused() { | ||
| 626 | 638 | await_workers(&bridge, 1).await; |
| 627 | 639 | |
| 628 | 640 | let err = bridge |
| 629 | - .dispatch("ocr.extract", json!(null)) | |
| 641 | + .dispatch(&demo(), "ocr.extract", json!(null)) | |
| 630 | 642 | .await |
| 631 | 643 | .unwrap_err(); |
| 632 | 644 | assert!(matches!(err, AiError::IdMismatch { .. }), "{err}"); |
| @@ -641,7 +653,7 @@ async fn a_malformed_answer_is_a_protocol_error_not_a_hang() { | ||
| 641 | 653 | await_workers(&bridge, 1).await; |
| 642 | 654 | |
| 643 | 655 | let err = bridge |
| 644 | - .dispatch("ocr.extract", json!(null)) | |
| 656 | + .dispatch(&demo(), "ocr.extract", json!(null)) | |
| 645 | 657 | .await |
| 646 | 658 | .unwrap_err(); |
| 647 | 659 | assert!(matches!(err, AiError::Protocol(_)), "{err}"); |
| @@ -655,7 +667,7 @@ async fn a_disconnected_service_is_deregistered() { | ||
| 655 | 667 | let bridge = bridge().await; |
| 656 | 668 | let service = connect_service(&bridge, hello("ocr", &["ocr.extract"]), Behaviour::Echo).await; |
| 657 | 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 | 672 | service.conn.close(0u32.into(), b"service shutting down"); |
| 661 | 673 | drop(service); |
| @@ -663,7 +675,7 @@ async fn a_disconnected_service_is_deregistered() { | ||
| 663 | 675 | |
| 664 | 676 | assert!(!bridge.has_capability("ocr.extract")); |
| 665 | 677 | let err = bridge |
| 666 | - .dispatch("ocr.extract", json!(null)) | |
| 678 | + .dispatch(&demo(), "ocr.extract", json!(null)) | |
| 667 | 679 | .await |
| 668 | 680 | .unwrap_err(); |
| 669 | 681 | assert!(matches!(err, AiError::NoWorker(_)), "{err}"); |
| @@ -683,7 +695,7 @@ async fn a_service_that_reconnects_serves_again() { | ||
| 683 | 695 | let second = connect_service(&bridge, hello("ocr", &["ocr.extract"]), Behaviour::Echo).await; |
| 684 | 696 | await_workers(&bridge, 1).await; |
| 685 | 697 | let answer = bridge |
| 686 | - .dispatch("ocr.extract", json!("again")) | |
| 698 | + .dispatch(&demo(), "ocr.extract", json!("again")) | |
| 687 | 699 | .await |
| 688 | 700 | .unwrap(); |
| 689 | 701 | assert_eq!(answer["echo"], "again"); |
| @@ -703,7 +715,7 @@ async fn losing_one_service_leaves_the_other_serving() { | ||
| 703 | 715 | await_workers(&bridge, 1).await; |
| 704 | 716 | |
| 705 | 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 | 720 | assert_eq!( |
| 709 | 721 | survivor.seen().len(), |
| @@ -794,7 +806,7 @@ async fn a_large_payload_survives_the_round_trip_intact() { | ||
| 794 | 806 | |
| 795 | 807 | let blob: String = std::iter::repeat_n('x', 512 * 1024).collect(); |
| 796 | 808 | let answer = bridge |
| 797 | - .dispatch("ocr.extract", json!({ "image": blob })) | |
| 809 | + .dispatch(&demo(), "ocr.extract", json!({ "image": blob })) | |
| 798 | 810 | .await |
| 799 | 811 | .expect("a multi-packet frame round-trips"); |
| 800 | 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 | 1431 | /// A `GET` of `path` as `on_behalf_of` (or as the service itself). |
| 1420 | 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 | 1438 | ApiRequest { |
| 1422 | 1439 | id: format!("trace-{path}"), |
| 1440 | + school: school.to_string(), | |
| 1423 | 1441 | path: path.to_string(), |
| 1424 | 1442 | query: None, |
| 1425 | 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 | 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, ¬e).await; | |
| 1765 | + assert_eq!(stored.len(), 1); | |
| 1766 | + assert_eq!(stored[0].get_payload()["summary"], "beta"); | |
| 1767 | + assert!( | |
| 1768 | + outputs(&demo_db, ¬e).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 | 1777 | #[tokio::test] |
| 1714 | 1778 | async fn a_course_note_is_indexed_and_its_output_stored_with_its_sources() { |
| 1715 | 1779 | let bridge = bridge().await; |
| @@ -1731,6 +1795,7 @@ async fn a_course_note_is_indexed_and_its_output_stored_with_its_sources() { | ||
| 1731 | 1795 | // The service saw the note itself, under the documented capability. |
| 1732 | 1796 | let seen = service.seen(); |
| 1733 | 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 | 1799 | assert_eq!(seen[0].payload["course_note"], note); |
| 1735 | 1800 | assert_eq!(seen[0].payload["title"], "Bölüm 3"); |
| 1736 | 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 | 1942 | let request = ApiRequest { |
| 1878 | 1943 | id: "trace-course-notes".into(), |
| 1944 | + school: DEMO_SLUG.into(), | |
| 1879 | 1945 | path: "/course-notes".into(), |
| 1880 | 1946 | query: Some(format!("course={course}")), |
| 1881 | 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 | 1970 | let request = ApiRequest { |
| 1905 | 1971 | id: "trace-foreign-course".into(), |
| 1972 | + school: DEMO_SLUG.into(), | |
| 1906 | 1973 | path: "/course-notes".into(), |
| 1907 | 1974 | query: Some(format!("course={foreign}")), |
| 1908 | 1975 | on_behalf_of: Some(student), |
| @@ -1922,6 +1989,7 @@ async fn writing_a_course_note_is_refused_before_dispatch() { | ||
| 1922 | 1989 | |
| 1923 | 1990 | let request = ApiRequest { |
| 1924 | 1991 | id: "trace-post".into(), |
| 1992 | + school: DEMO_SLUG.into(), | |
| 1925 | 1993 | path: "/course-notes".into(), |
| 1926 | 1994 | query: None, |
| 1927 | 1995 | on_behalf_of: None, |
| @@ -1990,8 +2058,14 @@ async fn blob_read(conn: &quinn::Connection, request: BlobRequest) -> (BlobRespo | ||
| 1990 | 2058 | } |
| 1991 | 2059 | |
| 1992 | 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 | 2066 | BlobRequest { |
| 1994 | 2067 | id: format!("trace-blob-{file}"), |
| 2068 | + school: school.to_string(), | |
| 1995 | 2069 | file: file.to_string(), |
| 1996 | 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 | 2107 | let (header, bytes) = blob_read(&service.conn, blob_of(&file, Some(&student))).await; |
| 2034 | 2108 | let BlobResponse::Ok { |
| 2035 | 2109 | id, |
| 2110 | + school, | |
| 2036 | 2111 | name, |
| 2037 | 2112 | content_type, |
| 2038 | 2113 | size, |
| @@ -2041,6 +2116,7 @@ async fn a_service_streams_a_course_note_file_on_behalf_of_an_enrolled_student() | ||
| 2041 | 2116 | panic!("the enrolled student was refused: {}", blob_refusal(header)); |
| 2042 | 2117 | }; |
| 2043 | 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 | 2120 | assert_eq!(name, "recap.pdf"); |
| 2045 | 2121 | assert_eq!(content_type, "application/pdf"); |
| 2046 | 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 | 3 | //! # Why this file exists separately from `ai_bridge.rs` |
| 4 | 4 | //! |
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | //! in a service repo. |
| 16 | 16 | //! |
| 17 | 17 | //! 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 | 20 | mod common; |
| 21 | 21 | |
| @@ -23,18 +23,23 @@ use std::sync::Arc; | ||
| 23 | 23 | use std::time::Duration; |
| 24 | 24 | |
| 25 | 25 | use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; |
| 26 | +use hezarfen_backend::tenant::{SchoolStatus, Slug, Tenants}; | |
| 26 | 27 | use serde_json::{Value, json}; |
| 27 | 28 | |
| 28 | 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 | 35 | /// The protocol identifier this suite pins. Deliberately a literal, not |
| 31 | 36 | /// `AI_PROTOCOL`: importing the constant would let a rename sail through, and |
| 32 | 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 | 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 | 43 | mod raw { |
| 39 | 44 | use super::*; |
| 40 | 45 | |
| @@ -252,7 +257,8 @@ fn dispatch( | ||
| 252 | 257 | ) -> tokio::task::JoinHandle<Result<Value, AiError>> { |
| 253 | 258 | let bridge = bridge.clone(); |
| 254 | 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 | 264 | // ------------------------------------------------------- framing contract -- |
| @@ -385,7 +391,7 @@ async fn the_rejection_frame_carries_exactly_the_published_keys_and_codes() { | ||
| 385 | 391 | // variant is a breaking change and must fail here. |
| 386 | 392 | let bridge = bridge().await; |
| 387 | 393 | |
| 388 | - let cases: [(&str, Vec<u8>); 4] = [ | |
| 394 | + let cases: [(&str, Vec<u8>); 5] = [ | |
| 389 | 395 | ( |
| 390 | 396 | "unauthorized", |
| 391 | 397 | format!( |
| @@ -400,6 +406,16 @@ async fn the_rejection_frame_carries_exactly_the_published_keys_and_codes() { | ||
| 400 | 406 | ) |
| 401 | 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 | 420 | "no_capabilities", |
| 405 | 421 | format!( |
| @@ -491,12 +507,20 @@ async fn a_foreign_alpn_is_refused_at_the_tls_handshake() { | ||
| 491 | 507 | // The version gate: an incompatible service must be stopped before it can |
| 492 | 508 | // send a frame this backend would misparse. |
| 493 | 509 | let bridge = bridge().await; |
| 494 | - let endpoint = raw::endpoint_with_alpn(&bridge, b"hab/99"); | |
| 495 | - let result = endpoint | |
| 496 | - .connect(bridge.local_addr().unwrap(), "localhost") | |
| 497 | - .unwrap() | |
| 498 | - .await; | |
| 499 | - assert!(result.is_err(), "ALPN hab/99 must not connect"); | |
| 510 | + // `hab/1` included by name: the version gate is the *first* line of defence | |
| 511 | + // against a service whose frames name no school, ahead of the Hello check. | |
| 512 | + for alpn in [b"hab/99".as_slice(), b"hab/1".as_slice()] { | |
| 513 | + let endpoint = raw::endpoint_with_alpn(&bridge, alpn); | |
| 514 | + let result = endpoint | |
| 515 | + .connect(bridge.local_addr().unwrap(), "localhost") | |
| 516 | + .unwrap() | |
| 517 | + .await; | |
| 518 | + assert!( | |
| 519 | + result.is_err(), | |
| 520 | + "ALPN {} must not connect", | |
| 521 | + String::from_utf8_lossy(alpn) | |
| 522 | + ); | |
| 523 | + } | |
| 500 | 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 | 541 | assert_eq!( |
| 518 | 542 | raw::keys(&request), |
| 519 | - ["capability", "deadline_ms", "id", "payload"], | |
| 543 | + ["capability", "deadline_ms", "id", "payload", "school"], | |
| 520 | 544 | "request shape changed: {request}" |
| 521 | 545 | ); |
| 522 | 546 | assert_eq!(request["capability"], "ocr.extract"); |
| @@ -529,7 +553,7 @@ async fn the_request_frame_carries_exactly_the_published_keys() { | ||
| 529 | 553 | let id = request["id"].as_str().unwrap().to_string(); |
| 530 | 554 | raw::answer( |
| 531 | 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 | 558 | .await; |
| 535 | 559 | let answer = call.await.unwrap().expect("dispatch succeeded"); |
| @@ -562,7 +586,7 @@ async fn a_payload_of_any_json_shape_survives_unchanged() { | ||
| 562 | 586 | assert_eq!(request["payload"], payload, "payload mutated in flight"); |
| 563 | 587 | |
| 564 | 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 | 590 | raw::answer(send, &serde_json::to_vec(&echo).unwrap()).await; |
| 567 | 591 | assert_eq!( |
| 568 | 592 | call.await.unwrap().unwrap(), |
| @@ -585,7 +609,7 @@ async fn the_response_tags_are_the_published_literals() { | ||
| 585 | 609 | let id = request["id"].as_str().unwrap().to_string(); |
| 586 | 610 | raw::answer( |
| 587 | 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 | 614 | .await; |
| 591 | 615 | assert_eq!(ok.await.unwrap().unwrap(), json!(42)); |
| @@ -595,7 +619,7 @@ async fn the_response_tags_are_the_published_literals() { | ||
| 595 | 619 | let id = request["id"].as_str().unwrap().to_string(); |
| 596 | 620 | raw::answer( |
| 597 | 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 | 624 | .await; |
| 601 | 625 | match err.await.unwrap() { |
| @@ -611,7 +635,7 @@ async fn the_response_tags_are_the_published_literals() { | ||
| 611 | 635 | let id = request["id"].as_str().unwrap().to_string(); |
| 612 | 636 | raw::answer( |
| 613 | 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 | 640 | .await; |
| 617 | 641 | assert!( |
| @@ -634,7 +658,7 @@ async fn a_response_may_carry_unknown_fields() { | ||
| 634 | 658 | raw::answer( |
| 635 | 659 | send, |
| 636 | 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 | 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 | 714 | let n = request["payload"]["n"].clone(); |
| 691 | 715 | raw::answer( |
| 692 | 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 | 719 | .await; |
| 696 | 720 | } |
| @@ -720,7 +744,7 @@ async fn request_ids_are_unique_per_request() { | ||
| 720 | 744 | assert!(seen.insert(id.clone()), "id {id} was reused"); |
| 721 | 745 | raw::answer( |
| 722 | 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 | 749 | .await; |
| 726 | 750 | call.await.unwrap().unwrap(); |
| @@ -752,7 +776,7 @@ async fn the_control_stream_carries_no_frames_after_the_welcome() { | ||
| 752 | 776 | let id = request["id"].as_str().unwrap().to_string(); |
| 753 | 777 | raw::answer( |
| 754 | 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 | 781 | .await; |
| 758 | 782 | call.await |
| @@ -774,7 +798,13 @@ async fn closing_the_control_stream_deregisters_the_service() { | ||
| 774 | 798 | await_workers(&bridge, 0).await; |
| 775 | 799 | |
| 776 | 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 | 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 | 841 | let id = request["id"].as_str().unwrap().to_string(); |
| 812 | 842 | raw::answer( |
| 813 | 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 | 846 | .await; |
| 817 | 847 | assert_eq!(next.await.unwrap().unwrap(), json!("ok")); |
| @@ -882,7 +912,7 @@ async fn several_raw_services_serve_one_capability_together() { | ||
| 882 | 912 | let n = request["payload"]["n"].clone(); |
| 883 | 913 | raw::answer( |
| 884 | 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 | 917 | .await; |
| 888 | 918 | } |
| @@ -976,7 +1006,7 @@ async fn a_chat_request_names_the_askers_school_role() { | ||
| 976 | 1006 | let id = request["id"].as_str().expect("trace id").to_string(); |
| 977 | 1007 | raw::answer( |
| 978 | 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 | 1011 | .await; |
| 982 | 1012 | } |
| @@ -1012,7 +1042,7 @@ async fn the_api_request_field_names_are_the_published_literals() { | ||
| 1012 | 1042 | let (answer, bytes) = raw::api_read( |
| 1013 | 1043 | &service.conn, |
| 1014 | 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 | 1047 | .as_bytes(), |
| 1018 | 1048 | ) |
| @@ -1020,7 +1050,7 @@ async fn the_api_request_field_names_are_the_published_literals() { | ||
| 1020 | 1050 | |
| 1021 | 1051 | assert_eq!( |
| 1022 | 1052 | raw::keys(&answer), |
| 1023 | - ["body", "id", "outcome", "status"], | |
| 1053 | + ["body", "id", "outcome", "school", "status"], | |
| 1024 | 1054 | "api answer shape changed: {answer}" |
| 1025 | 1055 | ); |
| 1026 | 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 | 1079 | let (answer, _) = raw::api_read( |
| 1050 | 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 | 1083 | .await; |
| 1054 | 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 | 1100 | let cases = [ |
| 1071 | 1101 | ( |
| 1072 | 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 | 1106 | "method_not_allowed", |
| 1077 | 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 | 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 | 1115 | // Order pin: both refusals apply, the method one wins. |
| 1086 | 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 | 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 | 1139 | for (expected_code, request) in cases { |
| 1097 | 1140 | let (answer, _) = raw::api_read(&service.conn, request.as_bytes()).await; |
| 1098 | 1141 | assert_eq!( |
| 1099 | 1142 | raw::keys(&answer), |
| 1100 | - ["code", "id", "message", "outcome"], | |
| 1143 | + ["code", "id", "message", "outcome", "school"], | |
| 1101 | 1144 | "refusal shape changed for {expected_code}: {answer}" |
| 1102 | 1145 | ); |
| 1103 | 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 | 1174 | let (answer, _) = raw::api_read( |
| 1132 | 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 | 1179 | .await; |
| 1136 | 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 | 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 | 1328 | // --------------------------------------------------- blob stream contract -- |
| 1143 | 1329 | // |
| 1144 | 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 | 1384 | let (header, bytes, body) = raw::blob_read( |
| 1199 | 1385 | &service.conn, |
| 1200 | 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 | 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 | 1393 | assert_eq!( |
| 1208 | 1394 | raw::keys(&header), |
| 1209 | - ["content_type", "id", "name", "size", "status"], | |
| 1395 | + ["content_type", "id", "name", "school", "size", "status"], | |
| 1210 | 1396 | "blob header shape changed: {header}" |
| 1211 | 1397 | ); |
| 1212 | 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 | 1428 | let (header, _, body) = raw::blob_read( |
| 1243 | 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 | 1435 | .await; |
| 1247 | 1436 | assert_eq!( |
| 1248 | 1437 | raw::keys(&header), |
| 1249 | - ["code", "id", "message", "status"], | |
| 1438 | + ["code", "id", "message", "school", "status"], | |
| 1250 | 1439 | "blob refusal shape changed: {header}" |
| 1251 | 1440 | ); |
| 1252 | 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 | 1460 | let (answer, _) = raw::api_read( |
| 1272 | 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 | 1465 | .await; |
| 1276 | 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 | 1472 | let (answer, _) = raw::api_read( |
| 1283 | 1473 | &service.conn, |
| 1284 | 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 | 1477 | .as_bytes(), |
| 1288 | 1478 | ) |
| @@ -1291,7 +1481,7 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() { | ||
| 1291 | 1481 | assert_eq!(answer["status"], 200); |
| 1292 | 1482 | |
| 1293 | 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 | 1485 | assert_eq!(answer["outcome"], "err", "{answer}"); |
| 1296 | 1486 | assert_eq!(answer["code"], "malformed"); |
| 1297 | 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 | 94 | 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 | 103 | /// [`app_with_ai`] with the liveness flag handed in, so a test can take the |
| 98 | 104 | /// database socket down under a running app — the api-read path re-checks it in |
| 99 | 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 | 154 | /// Register (password `secret1`), promote to `role`, then log in. Returns the |
| 149 | 155 | /// session `Cookie` value. |
| 150 | 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 | 171 | let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; |
| 153 | 172 | assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); |
| 154 | 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 | 1798 | let response = AiResponse::Ok { |
| 1799 | 1799 | id: request.id.clone(), |
| 1800 | + school: request.school.clone(), | |
| 1800 | 1801 | payload: json!({ "text": answer }), |
| 1801 | 1802 | }; |
| 1802 | 1803 | let _ = write_frame(&mut send, &response).await; |