Course-note file bytes stream to AI services over QUIC
Browse files at this commit6d3456a485e3b8aa6b26e00ff4f5584c9a84ea23Parent: ff36c8c- feat
- course-note file bytes stream to AI services over QUIC
9 changed files +786 -48
- README.md +63 -3
- src/ai/protocol.rs +85 -0
- src/ai/rag.rs +11 -4
- src/ai/server.rs +197 -33
- src/domain/course_note.rs +4 -0
- src/domain/course_note_file.rs +15 -0
- src/lib.rs +7 -2
- tests/ai_bridge.rs +226 -6
- tests/ai_protocol.rs +178 -0
README.mdmodified+63 -3
| @@ -3621,6 +3621,63 @@ Responses share the frame cap (8 MiB); an answer that does not fit comes back | ||
| 3621 | 3621 | as `too_large` rather than a dropped stream, so a page too big is narrowed with |
| 3622 | 3622 | `query` instead of waited out. |
| 3623 | 3623 | |
| 3624 | +### Blob reads (course-note file bytes) | |
| 3625 | + | |
| 3626 | +A PDF cannot ride a JSON frame, so an indexing service pulls a course note's | |
| 3627 | +attachment over a **raw byte stream** instead. Same direction and same framing | |
| 3628 | +as an api read — the service opens a bidi stream and writes one frame — only | |
| 3629 | +the shape differs, and the two are told apart by the field each *requires*: an | |
| 3630 | +`ApiRequest` has `path`, a `BlobRequest` has `file`. | |
| 3631 | + | |
| 3632 | +```json | |
| 3633 | +{ "id": "01J...", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V", | |
| 3634 | + "on_behalf_of": "user:01J..." } | |
| 3635 | +``` | |
| 3636 | + | |
| 3637 | +`file` is a `course_note_file` record key — the id `GET | |
| 3638 | +/course-notes/{id}/files` publishes and the one every `rag.index` payload | |
| 3639 | +carries in `files[].id`. `on_behalf_of` is optional on the wire but required in | |
| 3640 | +practice: without it the principal is the `ai` role, which is enrolled in | |
| 3641 | +nothing and can view no course, so every read is `forbidden`. Send the note's | |
| 3642 | +`author` (the `rag.index` payload carries it) or the student who asked. | |
| 3643 | + | |
| 3644 | +The backend answers with **one header frame**, tagged by `status` — the same | |
| 3645 | +tag `Response` uses, not the api read's `outcome`, since a blob header carries | |
| 3646 | +no HTTP status to collide with: | |
| 3647 | + | |
| 3648 | +```json | |
| 3649 | +{ "status": "ok", "id": "01J...", "name": "recap.pdf", | |
| 3650 | + "content_type": "application/pdf", "size": 204800 } | |
| 3651 | +{ "status": "err", "id": "01J...", "code": "forbidden", | |
| 3652 | + "message": "`01J...` may not view the course this file belongs to" } | |
| 3653 | +``` | |
| 3654 | + | |
| 3655 | +On `ok`, **exactly `size` raw bytes follow the header frame**, then the stream | |
| 3656 | +is finished. Those bytes are *not* a frame: they carry no length prefix and the | |
| 3657 | +8 MiB frame cap does not apply to them, which is the whole point — read | |
| 3658 | +`size` bytes and then expect EOF. `size` is measured off the stored blob | |
| 3659 | +itself, so it is what will actually arrive rather than what a row remembers. | |
| 3660 | +On `err` nothing follows the frame at all. A read that breaks after its header | |
| 3661 | +resets the stream instead of finishing it, so a truncated file is never | |
| 3662 | +mistaken for a complete one. | |
| 3663 | + | |
| 3664 | +| `code` | Meaning | | |
| 3665 | +| ------ | ------- | | |
| 3666 | +| `not_found` | No `course_note_file` with that key, or its note or course is gone | | |
| 3667 | +| `forbidden` | The principal may not view that file's course | | |
| 3668 | +| `unknown_user` | `on_behalf_of` names no user | | |
| 3669 | +| `unavailable` | The api is not serving yet, the database socket is down, or the row's blob is missing from disk — retryable | | |
| 3670 | + | |
| 3671 | +**Course-note attachments only.** The key is looked up in `course_note_file` | |
| 3672 | +and in no other table, so a personal note's file id (`/notes/{id}/files`) is | |
| 3673 | +`not_found` here rather than a different table's row: personal notes have no | |
| 3674 | +reader but their owner, and this stream does not become one. | |
| 3675 | + | |
| 3676 | +Authorization is the very guard `GET /course-notes/{id}/files/{file_id}` | |
| 3677 | +applies — course management rights or enrollment. The bridge widens *who may | |
| 3678 | +ask*, never *what may be read*: the file's note, and that note's course, are | |
| 3679 | +loaded and gated exactly as they are over HTTP. | |
| 3680 | + | |
| 3624 | 3681 | ### Framing |
| 3625 | 3682 | |
| 3626 | 3683 | `u32` big-endian byte length, then that many bytes of JSON. One frame per |
| @@ -3881,15 +3938,18 @@ as ordinary `hab/1` `Request` frames whose `payload` is: | ||
| 3881 | 3938 | ```json |
| 3882 | 3939 | { "course_note": "01J8XZ0K3Q8G7X2M4N5P6R7S8T", |
| 3883 | 3940 | "course": "01J8XZ0K3Q8G7X2M4N5P6R7S8U", |
| 3941 | + "author": "01J8XZ0K3Q8G7X2M4N5P6R7S8W", | |
| 3884 | 3942 | "title": "Chapter 3 recap", |
| 3885 | 3943 | "content": "Covered quadratics; homework due Friday", |
| 3886 | 3944 | "files": [ {"id":"01J8…","name":"recap.pdf", |
| 3887 | 3945 | "content_type":"application/pdf","size":24576} ] } |
| 3888 | 3946 | ``` |
| 3889 | 3947 | |
| 3890 | -`files` is attachment **metadata only** — file bytes are deliberately not on | |
| 3891 | -the wire, so a service that needs them reads them out of band. It is optional | |
| 3892 | -(absent or `[]` = a note with no attachments). | |
| 3948 | +`files` is attachment **metadata only**; the bytes ride their own QUIC stream | |
| 3949 | +(see "Blob reads" above — one `BlobRequest` per `files[].id`), never a JSON | |
| 3950 | +frame. It is optional (absent or `[]` = a note with no attachments). `author` | |
| 3951 | +is the note's own teacher: a service reads the bytes `on_behalf_of` them, | |
| 3952 | +since the `ai` principal can view no course. | |
| 3893 | 3953 | |
| 3894 | 3954 | The answer is a `Response::Ok` whose payload is **any JSON object**: its shape |
| 3895 | 3955 | belongs to the service, and the backend stores it verbatim against the note |
src/ai/protocol.rsmodified+85 -0
| @@ -22,6 +22,17 @@ | ||
| 22 | 22 | //! That mirrors the REST API — the backend dispatches the path internally — |
| 23 | 23 | //! so a service asks for school data instead of being handed it. |
| 24 | 24 | //! |
| 25 | +//! * Each **blob read** goes the same way as an api read, on its own | |
| 26 | +//! client-initiated bidirectional stream: the service writes one | |
| 27 | +//! [`BlobRequest`], finishes its send side, and reads one [`BlobResponse`] | |
| 28 | +//! header frame. On [`BlobResponse::Ok`] exactly `size` **raw** bytes follow | |
| 29 | +//! the header — not a frame, so [`AI_MAX_FRAME_BYTES`] does not bound them — | |
| 30 | +//! and then the stream is finished. That is how a service gets a course | |
| 31 | +//! note's file bytes, which no JSON frame could carry. | |
| 32 | +//! | |
| 33 | +//! The two client-initiated request shapes are told apart by their required | |
| 34 | +//! field: an [`ApiRequest`] has `path`, a [`BlobRequest`] has `file`. | |
| 35 | +//! | |
| 25 | 36 | //! There is deliberately no correlation-id matching: QUIC stream IDs already |
| 26 | 37 | //! multiplex concurrent requests over the one connection, independently |
| 27 | 38 | //! flow-controlled, with no head-of-line blocking between them. [`Request::id`] |
| @@ -175,6 +186,43 @@ pub enum ApiResponse { | ||
| 175 | 186 | }, |
| 176 | 187 | } |
| 177 | 188 | |
| 189 | +/// A read of one course-note file's *bytes*, written by the *service* on a | |
| 190 | +/// fresh client-initiated stream. Distinguished from an [`ApiRequest`] by its | |
| 191 | +/// required `file` field. | |
| 192 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 193 | +pub struct BlobRequest { | |
| 194 | + /// Trace id (ULID). Not used for correlation — the stream does that. | |
| 195 | + pub id: String, | |
| 196 | + /// The `course_note_file` record key, as `GET /course-notes/{id}/files` | |
| 197 | + /// and the `rag.index` payload both publish it. | |
| 198 | + pub file: String, | |
| 199 | + /// User id to read as. Absent means the service itself, which can view no | |
| 200 | + /// course and so always earns `forbidden`. | |
| 201 | + #[serde(default)] | |
| 202 | + pub on_behalf_of: Option<String>, | |
| 203 | +} | |
| 204 | + | |
| 205 | +/// The header frame that opens (or refuses) a blob stream. On `Ok` exactly | |
| 206 | +/// `size` raw bytes follow it, then FIN; on `Err` the stream is finished with | |
| 207 | +/// nothing after the frame. | |
| 208 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 209 | +#[serde(tag = "status", rename_all = "snake_case")] | |
| 210 | +pub enum BlobResponse { | |
| 211 | + Ok { | |
| 212 | + id: String, | |
| 213 | + name: String, | |
| 214 | + content_type: String, | |
| 215 | + /// Exactly how many raw bytes follow this frame. | |
| 216 | + size: u64, | |
| 217 | + }, | |
| 218 | + Err { | |
| 219 | + id: String, | |
| 220 | + /// Bridge-defined, stable, machine-readable (`"not_found"`). | |
| 221 | + code: String, | |
| 222 | + message: String, | |
| 223 | + }, | |
| 224 | +} | |
| 225 | + | |
| 178 | 226 | /// Write one length-prefixed JSON frame. |
| 179 | 227 | pub async fn write_frame<W, T>(w: &mut W, message: &T) -> Result<(), FrameError> |
| 180 | 228 | where |
| @@ -401,6 +449,43 @@ mod tests { | ||
| 401 | 449 | assert_eq!(serde_json::from_value::<ApiRequest>(raw).unwrap(), full); |
| 402 | 450 | } |
| 403 | 451 | |
| 452 | + #[tokio::test] | |
| 453 | + async fn blob_frame_tags_are_the_documented_wire_names() { | |
| 454 | + // Same reason as above: other-language services match these literals. | |
| 455 | + // The tag is `status` (as on `Response`), not `outcome` — a blob header | |
| 456 | + // carries no HTTP status for it to collide with. | |
| 457 | + let ok = serde_json::to_value(BlobResponse::Ok { | |
| 458 | + id: "1".into(), | |
| 459 | + name: "recap.pdf".into(), | |
| 460 | + content_type: "application/pdf".into(), | |
| 461 | + size: 204_800, | |
| 462 | + }) | |
| 463 | + .unwrap(); | |
| 464 | + assert_eq!(ok["status"], "ok"); | |
| 465 | + assert_eq!(ok["size"], 204_800); | |
| 466 | + let err = serde_json::to_value(BlobResponse::Err { | |
| 467 | + id: "1".into(), | |
| 468 | + code: "not_found".into(), | |
| 469 | + message: "nope".into(), | |
| 470 | + }) | |
| 471 | + .unwrap(); | |
| 472 | + assert_eq!(err["status"], "err"); | |
| 473 | + assert_eq!(err["code"], "not_found"); | |
| 474 | + | |
| 475 | + // `file` is what tells a blob request apart from an api read, so it is | |
| 476 | + // required; `on_behalf_of` is the only optional field. | |
| 477 | + let bare: BlobRequest = serde_json::from_value(json!({ | |
| 478 | + "id": "01J", "file": "01FILE", | |
| 479 | + })) | |
| 480 | + .unwrap(); | |
| 481 | + assert_eq!(bare.on_behalf_of, None); | |
| 482 | + assert!(serde_json::from_value::<BlobRequest>(json!({ "id": "01J" })).is_err()); | |
| 483 | + // And the two shapes never parse as each other. | |
| 484 | + assert!( | |
| 485 | + serde_json::from_value::<ApiRequest>(json!({ "id": "01J", "file": "01FILE" })).is_err() | |
| 486 | + ); | |
| 487 | + } | |
| 488 | + | |
| 404 | 489 | #[tokio::test] |
| 405 | 490 | async fn max_concurrent_is_optional_on_the_wire() { |
| 406 | 491 | let raw = json!({ |
src/ai/rag.rsmodified+11 -4
| @@ -44,11 +44,14 @@ pub struct RagIndexPayload { | ||
| 44 | 44 | /// — the backend keys the stored answer itself. |
| 45 | 45 | pub course_note: String, |
| 46 | 46 | pub course: String, |
| 47 | + /// The note author's user id — who a service reads the file bytes | |
| 48 | + /// `on_behalf_of` on the blob stream, since the note's own teacher can | |
| 49 | + /// always view its course and the `ai` principal never can. | |
| 50 | + pub author: String, | |
| 47 | 51 | pub title: String, |
| 48 | 52 | pub content: String, |
| 49 | - /// Attachment **metadata only** — file bytes are deliberately not on the | |
| 50 | - /// wire (open with the service owner: today a service that wants them must | |
| 51 | - /// read them out of band). | |
| 53 | + /// Attachment **metadata only** — the bytes ride their own QUIC stream | |
| 54 | + /// (one `BlobRequest` per `files[].id`), never a JSON frame. | |
| 52 | 55 | #[serde(default)] |
| 53 | 56 | pub files: Vec<RagFile>, |
| 54 | 57 | } |
| @@ -58,6 +61,7 @@ impl RagIndexPayload { | ||
| 58 | 61 | Self { |
| 59 | 62 | course_note: note.get_id().key().to_string(), |
| 60 | 63 | course: note.get_course().key().to_string(), |
| 64 | + author: note.get_author().key().to_string(), | |
| 61 | 65 | title: note.get_title().as_str().to_string(), |
| 62 | 66 | content: note.get_content().as_str().to_string(), |
| 63 | 67 | files: files |
| @@ -165,6 +169,7 @@ mod tests { | ||
| 165 | 169 | let payload = serde_json::to_value(RagIndexPayload { |
| 166 | 170 | course_note: "01NOTE".into(), |
| 167 | 171 | course: "01COURSE".into(), |
| 172 | + author: "01AUTHOR".into(), | |
| 168 | 173 | title: "Chapter 3".into(), |
| 169 | 174 | content: "quadratics".into(), |
| 170 | 175 | files: vec![RagFile { |
| @@ -180,6 +185,7 @@ mod tests { | ||
| 180 | 185 | json!({ |
| 181 | 186 | "course_note": "01NOTE", |
| 182 | 187 | "course": "01COURSE", |
| 188 | + "author": "01AUTHOR", | |
| 183 | 189 | "title": "Chapter 3", |
| 184 | 190 | "content": "quadratics", |
| 185 | 191 | "files": [{ |
| @@ -194,7 +200,8 @@ mod tests { | ||
| 194 | 200 | // A note with no attachments is the common case — `files` is optional |
| 195 | 201 | // on the wire, so a minimal service need not send it back or expect it. |
| 196 | 202 | let bare: RagIndexPayload = serde_json::from_value(json!({ |
| 197 | - "course_note": "01NOTE", "course": "01COURSE", "title": "t", "content": "c", | |
| 203 | + "course_note": "01NOTE", "course": "01COURSE", "author": "01AUTHOR", | |
| 204 | + "title": "t", "content": "c", | |
| 198 | 205 | })) |
| 199 | 206 | .unwrap(); |
| 200 | 207 | assert!(bare.files.is_empty()); |
src/ai/server.rsmodified+197 -33
| @@ -14,8 +14,8 @@ use ulid::Ulid; | ||
| 14 | 14 | |
| 15 | 15 | use crate::ai::error::AiError; |
| 16 | 16 | use crate::ai::protocol::{ |
| 17 | - ApiRequest, ApiResponse, FrameError, Greeting, Hello, RejectCode, Request, Response, | |
| 18 | - protocol_matches, read_frame, write_frame, | |
| 17 | + ApiRequest, ApiResponse, BlobRequest, BlobResponse, FrameError, Greeting, Hello, RejectCode, | |
| 18 | + Request, Response, protocol_matches, read_frame, write_frame, | |
| 19 | 19 | }; |
| 20 | 20 | use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency}; |
| 21 | 21 | use crate::ai::tls; |
| @@ -23,8 +23,13 @@ use crate::constant::{ | ||
| 23 | 23 | AI_HANDSHAKE_TIMEOUT_SECS, AI_MAX_FRAME_BYTES, AI_PROTOCOL, REQUEST_TIMEOUT_SECS, |
| 24 | 24 | }; |
| 25 | 25 | use crate::database::Database; |
| 26 | +use crate::domain::course::Course; | |
| 27 | +use crate::domain::course_note::CourseNote; | |
| 28 | +use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; | |
| 26 | 29 | use crate::domain::user::{User, UserId}; |
| 27 | 30 | use crate::state::DbHealth; |
| 31 | +use crate::web::blob_path; | |
| 32 | +use crate::web::courses::can_view_course; | |
| 28 | 33 | use crate::web::extractor::AiPrincipal; |
| 29 | 34 | |
| 30 | 35 | /// What the bridge needs to come up. |
| @@ -48,6 +53,9 @@ struct ApiHandle { | ||
| 48 | 53 | router: axum::Router, |
| 49 | 54 | db: Database, |
| 50 | 55 | db_up: DbHealth, |
| 56 | + /// Where course-note blobs live, for the byte stream — the same directory | |
| 57 | + /// `GET /course-notes/{id}/files/{file_id}` serves from. | |
| 58 | + files_path: std::path::PathBuf, | |
| 51 | 59 | } |
| 52 | 60 | |
| 53 | 61 | struct Inner { |
| @@ -228,8 +236,24 @@ impl AiBridge { | ||
| 228 | 236 | /// a synthetic QUIC request skips the per-IP limiter, CORS and `ETag` (see |
| 229 | 237 | /// the comment there). A second call keeps the first router: the process |
| 230 | 238 | /// only ever builds one. |
| 231 | - pub(crate) fn arm_api(&self, router: axum::Router, db: Database, db_up: DbHealth) { | |
| 232 | - if self.inner.api.set(ApiHandle { router, db, db_up }).is_err() { | |
| 239 | + pub(crate) fn arm_api( | |
| 240 | + &self, | |
| 241 | + router: axum::Router, | |
| 242 | + db: Database, | |
| 243 | + db_up: DbHealth, | |
| 244 | + files_path: std::path::PathBuf, | |
| 245 | + ) { | |
| 246 | + if self | |
| 247 | + .inner | |
| 248 | + .api | |
| 249 | + .set(ApiHandle { | |
| 250 | + router, | |
| 251 | + db, | |
| 252 | + db_up, | |
| 253 | + files_path, | |
| 254 | + }) | |
| 255 | + .is_err() | |
| 256 | + { | |
| 233 | 257 | tracing::warn!("the AI bridge api path was already armed — keeping the first router"); |
| 234 | 258 | } |
| 235 | 259 | } |
| @@ -279,14 +303,15 @@ async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection, remote: So | ||
| 279 | 303 | // service says goodbye, and the QUIC idle timeout covers the case where it |
| 280 | 304 | // dies without saying anything. |
| 281 | 305 | // |
| 282 | - // Every *further* client-initiated stream is one api read. A service that | |
| 283 | - // opens none behaves exactly as it did before this loop existed. | |
| 306 | + // Every *further* client-initiated stream is one api read or one blob | |
| 307 | + // read. A service that opens none behaves exactly as it did before this | |
| 308 | + // loop existed. | |
| 284 | 309 | let reason = loop { |
| 285 | 310 | tokio::select! { |
| 286 | 311 | reason = conn.closed() => break reason, |
| 287 | 312 | accepted = conn.accept_bi() => match accepted { |
| 288 | 313 | Ok((send, recv)) => { |
| 289 | - tokio::spawn(serve_api_read(Arc::clone(&inner), send, recv)); | |
| 314 | + tokio::spawn(serve_client_stream(Arc::clone(&inner), send, recv)); | |
| 290 | 315 | } |
| 291 | 316 | // The connection is going away; `closed()` has the real reason. |
| 292 | 317 | Err(_) => break conn.closed().await, |
| @@ -297,9 +322,11 @@ async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection, remote: So | ||
| 297 | 322 | tracing::info!("AI service `{service}` ({worker_id}) at {remote} disconnected: {reason}"); |
| 298 | 323 | } |
| 299 | 324 | |
| 300 | -/// Answer one api read on its own stream: one [`ApiRequest`] in, one | |
| 301 | -/// [`ApiResponse`] out, then the stream is finished. | |
| 302 | -async fn serve_api_read( | |
| 325 | +/// Answer one client-initiated stream. Two shapes ride this path and are told | |
| 326 | +/// apart by the field each requires: an [`ApiRequest`] has `path`, a | |
| 327 | +/// [`BlobRequest`] has `file`. The api read is tried first, so every frame that | |
| 328 | +/// parsed as one before still does, byte for byte. | |
| 329 | +async fn serve_client_stream( | |
| 303 | 330 | inner: Arc<Inner>, |
| 304 | 331 | mut send: quinn::SendStream, |
| 305 | 332 | mut recv: quinn::RecvStream, |
| @@ -323,19 +350,167 @@ async fn serve_api_read( | ||
| 323 | 350 | .and_then(Value::as_str) |
| 324 | 351 | .unwrap_or_default() |
| 325 | 352 | .to_string(); |
| 326 | - let request: ApiRequest = match serde_json::from_value(raw) { | |
| 327 | - Ok(request) => request, | |
| 328 | - Err(e) => { | |
| 329 | - answer(&mut send, refusal(id, "malformed", e.to_string())).await; | |
| 353 | + let api_err = match serde_json::from_value::<ApiRequest>(raw.clone()) { | |
| 354 | + Ok(request) => { | |
| 355 | + let response = match read_api(&inner, request).await { | |
| 356 | + Ok(response) => response, | |
| 357 | + Err((code, message)) => refusal(id, code, message), | |
| 358 | + }; | |
| 359 | + answer(&mut send, response).await; | |
| 330 | 360 | return; |
| 331 | 361 | } |
| 362 | + Err(e) => e, | |
| 332 | 363 | }; |
| 364 | + if let Ok(request) = serde_json::from_value::<BlobRequest>(raw) { | |
| 365 | + serve_blob(&inner, &mut send, request).await; | |
| 366 | + return; | |
| 367 | + } | |
| 368 | + // Neither shape. Reported as the api-read refusal it has always been — | |
| 369 | + // `path` is the field a frame this far off most likely meant to carry. | |
| 370 | + answer(&mut send, refusal(id, "malformed", api_err.to_string())).await; | |
| 371 | +} | |
| 372 | + | |
| 373 | +/// Answer one blob read: the [`BlobResponse`] header frame, then — on `Ok` — | |
| 374 | +/// exactly `size` raw bytes copied straight off disk, then FIN. | |
| 375 | +/// | |
| 376 | +/// The bytes are streamed rather than buffered: a course-note attachment can | |
| 377 | +/// be the school's whole `max_file_bytes`, and this path exists precisely | |
| 378 | +/// because such a thing does not fit a frame. | |
| 379 | +async fn serve_blob(inner: &Inner, send: &mut quinn::SendStream, request: BlobRequest) { | |
| 380 | + let id = request.id.clone(); | |
| 381 | + match open_blob(inner, request).await { | |
| 382 | + Ok((header, mut file)) => { | |
| 383 | + if let Err(e) = write_frame(send, &header).await { | |
| 384 | + tracing::warn!("could not answer an AI service's blob read {id}: {e}"); | |
| 385 | + } else if let Err(e) = tokio::io::copy(&mut file, send).await { | |
| 386 | + // The header already promised `size` bytes, so a short body | |
| 387 | + // would read as a silently truncated file. Reset instead: the | |
| 388 | + // service sees a broken stream and can ask again. | |
| 389 | + tracing::warn!("blob read {id} failed after its header: {e}"); | |
| 390 | + let _ = send.reset(1u32.into()); | |
| 391 | + return; | |
| 392 | + } | |
| 393 | + } | |
| 394 | + Err((code, message)) => { | |
| 395 | + let refused = BlobResponse::Err { | |
| 396 | + id, | |
| 397 | + code: code.to_string(), | |
| 398 | + message, | |
| 399 | + }; | |
| 400 | + if let Err(e) = write_frame(send, &refused).await { | |
| 401 | + tracing::warn!("could not refuse an AI service's blob read: {e}"); | |
| 402 | + } | |
| 403 | + } | |
| 404 | + } | |
| 405 | + let _ = send.finish(); | |
| 406 | +} | |
| 333 | 407 | |
| 334 | - let response = match read_api(&inner, request).await { | |
| 335 | - Ok(response) => response, | |
| 336 | - Err((code, message)) => refusal(id, code, message), | |
| 408 | +/// Resolve, authorize and open one blob. `Err` is the refusal that becomes a | |
| 409 | +/// [`BlobResponse::Err`] code. | |
| 410 | +/// | |
| 411 | +/// Scope is course-note attachments and nothing else: the id is looked up in | |
| 412 | +/// `course_note_file` alone, so a personal note's file id reads as `not_found` | |
| 413 | +/// rather than reaching another table's row. Authorization is the very guard | |
| 414 | +/// `download_file` applies over HTTP — [`can_view_course`] on the note's own | |
| 415 | +/// course — so the bridge widens who may ask, never what may be read. | |
| 416 | +async fn open_blob( | |
| 417 | + inner: &Inner, | |
| 418 | + request: BlobRequest, | |
| 419 | +) -> Result<(BlobResponse, tokio::fs::File), (&'static str, String)> { | |
| 420 | + let api = inner.api.get().ok_or(( | |
| 421 | + "unavailable", | |
| 422 | + "the api is not serving yet — retry".to_string(), | |
| 423 | + ))?; | |
| 424 | + if !api.db_up.is_up() { | |
| 425 | + return Err(( | |
| 426 | + "unavailable", | |
| 427 | + "the database socket is down — retry".to_string(), | |
| 428 | + )); | |
| 429 | + } | |
| 430 | + let user = principal(api, request.on_behalf_of.as_deref()).await?; | |
| 431 | + | |
| 432 | + let missing = || { | |
| 433 | + ( | |
| 434 | + "not_found", | |
| 435 | + format!("no course note file `{}`", request.file), | |
| 436 | + ) | |
| 337 | 437 | }; |
| 338 | - answer(&mut send, response).await; | |
| 438 | + let unavailable = |e: crate::error::AppError| ("unavailable", e.to_string()); | |
| 439 | + let file = CourseNoteFile::read(&CourseNoteFileId::from_key(&request.file), &api.db) | |
| 440 | + .await | |
| 441 | + .map_err(unavailable)? | |
| 442 | + .ok_or_else(missing)?; | |
| 443 | + let note = CourseNote::read(file.get_course_note(), &api.db) | |
| 444 | + .await | |
| 445 | + .map_err(unavailable)? | |
| 446 | + .ok_or_else(missing)?; | |
| 447 | + let course = Course::read(note.get_course(), &api.db) | |
| 448 | + .await | |
| 449 | + .map_err(unavailable)? | |
| 450 | + .ok_or_else(missing)?; | |
| 451 | + if !can_view_course(&course, &user, &api.db) | |
| 452 | + .await | |
| 453 | + .map_err(unavailable)? | |
| 454 | + { | |
| 455 | + return Err(( | |
| 456 | + "forbidden", | |
| 457 | + format!( | |
| 458 | + "`{}` may not view the course this file belongs to", | |
| 459 | + user.get_id().key() | |
| 460 | + ), | |
| 461 | + )); | |
| 462 | + } | |
| 463 | + | |
| 464 | + // The row exists but its blob does not: server-side damage (a lost volume | |
| 465 | + // path), exactly as `download_file` reads it — not the service's `404`. | |
| 466 | + let path = blob_path(&api.files_path, file.get_id().key()); | |
| 467 | + let handle = tokio::fs::File::open(&path).await.map_err(|e| { | |
| 468 | + ( | |
| 469 | + "unavailable", | |
| 470 | + format!( | |
| 471 | + "missing blob for course note file {}: {e}", | |
| 472 | + file.get_id().key() | |
| 473 | + ), | |
| 474 | + ) | |
| 475 | + })?; | |
| 476 | + // The header's `size` is what will actually be copied, so it is taken from | |
| 477 | + // the file on disk rather than the row's column: a service reading exactly | |
| 478 | + // `size` bytes must never over- or under-read. | |
| 479 | + let size = handle | |
| 480 | + .metadata() | |
| 481 | + .await | |
| 482 | + .map_err(|e| ("unavailable", format!("could not stat the blob: {e}")))? | |
| 483 | + .len(); | |
| 484 | + Ok(( | |
| 485 | + BlobResponse::Ok { | |
| 486 | + id: request.id, | |
| 487 | + name: file.get_name().as_str().to_string(), | |
| 488 | + content_type: file.get_content_type().as_str().to_string(), | |
| 489 | + size, | |
| 490 | + }, | |
| 491 | + handle, | |
| 492 | + )) | |
| 493 | +} | |
| 494 | + | |
| 495 | +/// Who a client-initiated read runs as. | |
| 496 | +/// | |
| 497 | +/// Loaded live, never trusted from the frame: a service holding a stale id must | |
| 498 | +/// not act as a user who has since been deleted or demoted. With nobody named | |
| 499 | +/// the principal is the synthetic `ai` role. | |
| 500 | +async fn principal( | |
| 501 | + api: &ApiHandle, | |
| 502 | + on_behalf_of: Option<&str>, | |
| 503 | +) -> Result<User, (&'static str, String)> { | |
| 504 | + let Some(who) = on_behalf_of else { | |
| 505 | + return Ok(User::ai_principal()); | |
| 506 | + }; | |
| 507 | + // Both the bare key (`abc`, as a REST path spells it) and the record form | |
| 508 | + // (`user:abc`) are accepted. | |
| 509 | + let key = who.strip_prefix("user:").unwrap_or(who); | |
| 510 | + User::read(&UserId::from_key(key), &api.db) | |
| 511 | + .await | |
| 512 | + .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))? | |
| 513 | + .ok_or_else(|| ("unknown_user", format!("no user `{who}`"))) | |
| 339 | 514 | } |
| 340 | 515 | |
| 341 | 516 | /// The bridge-level refusal this request earns *before* anything is dispatched, |
| @@ -409,21 +584,9 @@ async fn dispatch_api( | ||
| 409 | 584 | )); |
| 410 | 585 | } |
| 411 | 586 | |
| 412 | - // Loaded live, never trusted from the frame: a service holding a stale id | |
| 413 | - // must not act as a user who has since been deleted or demoted. The role | |
| 414 | - // itself is re-read again by the extractor on the dispatched request. | |
| 415 | - let user = match &on_behalf_of { | |
| 416 | - Some(who) => { | |
| 417 | - // Both the bare key (`abc`, as a REST path spells it) and the | |
| 418 | - // record form (`user:abc`) are accepted. | |
| 419 | - let key = who.strip_prefix("user:").unwrap_or(who); | |
| 420 | - User::read(&UserId::from_key(key), &api.db) | |
| 421 | - .await | |
| 422 | - .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))? | |
| 423 | - .ok_or_else(|| ("unknown_user", format!("no user `{who}`")))? | |
| 424 | - } | |
| 425 | - None => User::ai_principal(), | |
| 426 | - }; | |
| 587 | + // The role itself is re-read again by the extractor on the dispatched | |
| 588 | + // request; see [`principal`] for why it is never taken from the frame. | |
| 589 | + let user = principal(api, on_behalf_of.as_deref()).await?; | |
| 427 | 590 | |
| 428 | 591 | let target = match query.as_deref() { |
| 429 | 592 | Some(query) if !query.is_empty() => format!("{path}?{query}"), |
| @@ -664,6 +827,7 @@ mod tests { | ||
| 664 | 827 | router, |
| 665 | 828 | db: crate::database::init_mem().await.expect("in-memory db"), |
| 666 | 829 | db_up: Default::default(), |
| 830 | + files_path: std::env::temp_dir(), | |
| 667 | 831 | } |
| 668 | 832 | } |
| 669 | 833 |
src/domain/course_note.rsmodified+4 -0
| @@ -97,6 +97,10 @@ impl CourseNote { | ||
| 97 | 97 | &self.course |
| 98 | 98 | } |
| 99 | 99 | |
| 100 | + pub fn get_author(&self) -> &UserId { | |
| 101 | + &self.author | |
| 102 | + } | |
| 103 | + | |
| 100 | 104 | pub fn get_title(&self) -> &CourseNoteTitle { |
| 101 | 105 | &self.title |
| 102 | 106 | } |
src/domain/course_note_file.rsmodified+15 -0
| @@ -84,6 +84,10 @@ impl CourseNoteFile { | ||
| 84 | 84 | &self.id |
| 85 | 85 | } |
| 86 | 86 | |
| 87 | + pub fn get_course_note(&self) -> &CourseNoteId { | |
| 88 | + &self.course_note | |
| 89 | + } | |
| 90 | + | |
| 87 | 91 | pub fn get_name(&self) -> &FileName { |
| 88 | 92 | &self.name |
| 89 | 93 | } |
| @@ -125,6 +129,17 @@ impl CourseNoteFile { | ||
| 125 | 129 | } |
| 126 | 130 | } |
| 127 | 131 | |
| 132 | + /// Read a file's row by id alone, for the callers that have no note in | |
| 133 | + /// hand yet and reach the note *through* the file (the AI bridge's blob | |
| 134 | + /// stream). A key from any other table simply reads as `None`, which is | |
| 135 | + /// what keeps a personal note's file id unreachable here. | |
| 136 | + pub async fn read( | |
| 137 | + id: &CourseNoteFileId, | |
| 138 | + db: &Database, | |
| 139 | + ) -> Result<Option<CourseNoteFile>, AppError> { | |
| 140 | + Ok(db.select(id.record()).await?) | |
| 141 | + } | |
| 142 | + | |
| 128 | 143 | /// Read a file's row only if it belongs to `note` — callers have already |
| 129 | 144 | /// checked the note belongs to a course the caller may act on. |
| 130 | 145 | pub async fn read_for( |
src/lib.rsmodified+7 -2
| @@ -41,7 +41,7 @@ use crate::state::AppState; | ||
| 41 | 41 | modifiers(&SecurityAddon), |
| 42 | 42 | tags( |
| 43 | 43 | (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"), |
| 44 | - (name = "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`. 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"), | |
| 44 | + (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 | 45 | (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), |
| 46 | 46 | (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), |
| 47 | 47 | (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 (teacher+, optionally role-filtered), 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`"), |
| @@ -159,7 +159,12 @@ pub fn build_router(state: AppState) -> Router { | ||
| 159 | 159 | // layers means skipping the db guard too, so the bridge runs the liveness |
| 160 | 160 | // check and the request timeout itself (see `ai::server`). |
| 161 | 161 | if let Some(ai) = &state.ai { |
| 162 | - ai.arm_api(service.clone(), state.db.clone(), state.db_up.clone()); | |
| 162 | + ai.arm_api( | |
| 163 | + service.clone(), | |
| 164 | + state.db.clone(), | |
| 165 | + state.db_up.clone(), | |
| 166 | + state.files_path.clone(), | |
| 167 | + ); | |
| 163 | 168 | } |
| 164 | 169 | |
| 165 | 170 | service |
tests/ai_bridge.rsmodified+226 -6
| @@ -1825,7 +1825,18 @@ async fn deleting_a_course_note_takes_its_rag_outputs_with_it() { | ||
| 1825 | 1825 | /// A registered service, a router, and a course the seeded student is |
| 1826 | 1826 | /// enrolled in (plus one they are not) with a teacher's note in each. |
| 1827 | 1827 | /// Returns (service, student id, note id, enrolled course, foreign course). |
| 1828 | -async fn course_notes_fixture(bridge: &AiBridge) -> (FakeService, String, String, String, String) { | |
| 1828 | +async fn course_notes_fixture( | |
| 1829 | + bridge: &AiBridge, | |
| 1830 | +) -> ( | |
| 1831 | + FakeService, | |
| 1832 | + String, | |
| 1833 | + String, | |
| 1834 | + String, | |
| 1835 | + String, | |
| 1836 | + Router, | |
| 1837 | + Database, | |
| 1838 | + String, | |
| 1839 | +) { | |
| 1829 | 1840 | let service = connect_service( |
| 1830 | 1841 | bridge, |
| 1831 | 1842 | hello("tutor", &[AI_CHAT_CAPABILITY]), |
| @@ -1854,7 +1865,7 @@ async fn course_notes_fixture(bridge: &AiBridge) -> (FakeService, String, String | ||
| 1854 | 1865 | assert_eq!(res.status, StatusCode::CREATED, "teacher creates the note"); |
| 1855 | 1866 | let note = common::id_of(&res.body); |
| 1856 | 1867 | |
| 1857 | - (service, student, note, course, foreign) | |
| 1868 | + (service, student, note, course, foreign, app, db, teacher) | |
| 1858 | 1869 | } |
| 1859 | 1870 | |
| 1860 | 1871 | #[tokio::test] |
| @@ -1862,7 +1873,8 @@ async fn a_service_reads_a_course_note_on_behalf_of_an_enrolled_student() { | ||
| 1862 | 1873 | // The point of #27: a study companion answering about a lesson needs the |
| 1863 | 1874 | // teacher's own material, read with the student's reach and no wider. |
| 1864 | 1875 | let bridge = bridge().await; |
| 1865 | - let (service, student, note, course, _foreign) = course_notes_fixture(&bridge).await; | |
| 1876 | + let (service, student, note, course, _foreign, _app, _db, _teacher) = | |
| 1877 | + course_notes_fixture(&bridge).await; | |
| 1866 | 1878 | |
| 1867 | 1879 | let request = ApiRequest { |
| 1868 | 1880 | id: "trace-course-notes".into(), |
| @@ -1888,7 +1900,8 @@ async fn a_course_the_student_is_not_in_is_refused_by_the_handler() { | ||
| 1888 | 1900 | // The bridge widens the scope, never the reach: the handler's own guard |
| 1889 | 1901 | // is what answers, and it rides back as an `Ok` carrying that status. |
| 1890 | 1902 | let bridge = bridge().await; |
| 1891 | - let (service, student, _note, _course, foreign) = course_notes_fixture(&bridge).await; | |
| 1903 | + let (service, student, _note, _course, foreign, _app, _db, _teacher) = | |
| 1904 | + course_notes_fixture(&bridge).await; | |
| 1892 | 1905 | |
| 1893 | 1906 | let request = ApiRequest { |
| 1894 | 1907 | id: "trace-foreign-course".into(), |
| @@ -1906,7 +1919,8 @@ async fn writing_a_course_note_is_refused_before_dispatch() { | ||
| 1906 | 1919 | // Read scope means read: the allowlist admits the path, the method gate |
| 1907 | 1920 | // still refuses, and nothing reaches the router. |
| 1908 | 1921 | let bridge = bridge().await; |
| 1909 | - let (service, _student, _note, _course, _foreign) = course_notes_fixture(&bridge).await; | |
| 1922 | + let (service, _student, _note, _course, _foreign, _app, _db, _teacher) = | |
| 1923 | + course_notes_fixture(&bridge).await; | |
| 1910 | 1924 | |
| 1911 | 1925 | let request = ApiRequest { |
| 1912 | 1926 | id: "trace-post".into(), |
| @@ -1926,7 +1940,8 @@ async fn a_course_note_file_download_stays_out_of_the_read_scope() { | ||
| 1926 | 1940 | // The listing of a note's files is JSON and allowed; the bytes behind one |
| 1927 | 1941 | // are not — frames carry JSON under an 8 MiB cap. |
| 1928 | 1942 | let bridge = bridge().await; |
| 1929 | - let (service, student, note, _course, _foreign) = course_notes_fixture(&bridge).await; | |
| 1943 | + let (service, student, note, _course, _foreign, _app, _db, _teacher) = | |
| 1944 | + course_notes_fixture(&bridge).await; | |
| 1930 | 1945 | |
| 1931 | 1946 | let path = format!("/course-notes/{note}/files/somefile"); |
| 1932 | 1947 | match api_read(&service.conn, read_of(&path, Some(&student))).await { |
| @@ -1934,3 +1949,208 @@ async fn a_course_note_file_download_stays_out_of_the_read_scope() { | ||
| 1934 | 1949 | ApiResponse::Ok { status, .. } => panic!("a blob route was dispatched, answering {status}"), |
| 1935 | 1950 | } |
| 1936 | 1951 | } |
| 1952 | + | |
| 1953 | +// -------------------------------------------------------------- blob read -- | |
| 1954 | +// | |
| 1955 | +// The third stream shape: a service pulls a course-note attachment's raw | |
| 1956 | +// bytes, which no JSON frame could carry. The header frame is authorized by | |
| 1957 | +// the very guard the HTTP download carries, so these drive the real upload | |
| 1958 | +// route and then read the bytes back over real QUIC. | |
| 1959 | + | |
| 1960 | +use hezarfen_backend::ai::protocol::{BlobRequest, BlobResponse}; | |
| 1961 | + | |
| 1962 | +/// 200 KiB of deterministic pseudo-random bytes — well past one QUIC datagram, | |
| 1963 | +/// so a passing read proves the copy really streamed rather than fitting in a | |
| 1964 | +/// single write. | |
| 1965 | +fn blob_bytes() -> Vec<u8> { | |
| 1966 | + let mut state = 0x2545_F491_4F6C_DD1Du64; | |
| 1967 | + (0..200 * 1024) | |
| 1968 | + .map(|_| { | |
| 1969 | + state ^= state << 13; | |
| 1970 | + state ^= state >> 7; | |
| 1971 | + state ^= state << 17; | |
| 1972 | + state as u8 | |
| 1973 | + }) | |
| 1974 | + .collect() | |
| 1975 | +} | |
| 1976 | + | |
| 1977 | +/// One blob read on a fresh client-initiated stream: the header frame, then | |
| 1978 | +/// everything that followed it up to EOF. | |
| 1979 | +async fn blob_read(conn: &quinn::Connection, request: BlobRequest) -> (BlobResponse, Vec<u8>) { | |
| 1980 | + let (mut send, mut recv) = conn.open_bi().await.expect("blob stream"); | |
| 1981 | + write_frame(&mut send, &request) | |
| 1982 | + .await | |
| 1983 | + .expect("write BlobRequest"); | |
| 1984 | + let _ = send.finish(); | |
| 1985 | + let header: BlobResponse = read_frame(&mut recv).await.expect("read BlobResponse"); | |
| 1986 | + let bytes = recv | |
| 1987 | + .read_to_end(16 * 1024 * 1024) | |
| 1988 | + .await | |
| 1989 | + .expect("read the blob body to EOF"); | |
| 1990 | + (header, bytes) | |
| 1991 | +} | |
| 1992 | + | |
| 1993 | +fn blob_of(file: &str, on_behalf_of: Option<&str>) -> BlobRequest { | |
| 1994 | + BlobRequest { | |
| 1995 | + id: format!("trace-blob-{file}"), | |
| 1996 | + file: file.to_string(), | |
| 1997 | + on_behalf_of: on_behalf_of.map(str::to_string), | |
| 1998 | + } | |
| 1999 | +} | |
| 2000 | + | |
| 2001 | +/// The refusal code of a header that must be one; panics on an `Ok`. | |
| 2002 | +fn blob_refusal(header: BlobResponse) -> String { | |
| 2003 | + match header { | |
| 2004 | + BlobResponse::Err { code, .. } => code, | |
| 2005 | + BlobResponse::Ok { name, size, .. } => { | |
| 2006 | + panic!("expected a refusal, got {size} bytes of `{name}`") | |
| 2007 | + } | |
| 2008 | + } | |
| 2009 | +} | |
| 2010 | + | |
| 2011 | +#[tokio::test] | |
| 2012 | +async fn a_service_streams_a_course_note_file_on_behalf_of_an_enrolled_student() { | |
| 2013 | + // The whole point of the slice: the service can index the PDF, not just | |
| 2014 | + // its filename. The bytes must come back identical to what was uploaded | |
| 2015 | + // through the ordinary multipart route, and `size` must be exactly how | |
| 2016 | + // many of them arrive — a service reads that count and then expects EOF. | |
| 2017 | + let bridge = bridge().await; | |
| 2018 | + let (service, student, note, _course, _foreign, app, _db, teacher) = | |
| 2019 | + course_notes_fixture(&bridge).await; | |
| 2020 | + | |
| 2021 | + let uploaded = blob_bytes(); | |
| 2022 | + let res = common::upload_file_at( | |
| 2023 | + &app, | |
| 2024 | + &teacher, | |
| 2025 | + &format!("/course-notes/{note}/files"), | |
| 2026 | + "recap.pdf", | |
| 2027 | + "application/pdf", | |
| 2028 | + &uploaded, | |
| 2029 | + ) | |
| 2030 | + .await; | |
| 2031 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 2032 | + let file = common::id_of(&res.body); | |
| 2033 | + | |
| 2034 | + let (header, bytes) = blob_read(&service.conn, blob_of(&file, Some(&student))).await; | |
| 2035 | + let BlobResponse::Ok { | |
| 2036 | + id, | |
| 2037 | + name, | |
| 2038 | + content_type, | |
| 2039 | + size, | |
| 2040 | + } = header | |
| 2041 | + else { | |
| 2042 | + panic!("the enrolled student was refused: {}", blob_refusal(header)); | |
| 2043 | + }; | |
| 2044 | + assert_eq!(id, format!("trace-blob-{file}"), "the trace id is echoed"); | |
| 2045 | + assert_eq!(name, "recap.pdf"); | |
| 2046 | + assert_eq!(content_type, "application/pdf"); | |
| 2047 | + assert_eq!(size as usize, uploaded.len(), "the promised byte count"); | |
| 2048 | + assert_eq!(bytes.len(), size as usize, "exactly `size` bytes, then FIN"); | |
| 2049 | + assert!(bytes == uploaded, "the bytes differ from what was uploaded"); | |
| 2050 | +} | |
| 2051 | + | |
| 2052 | +#[tokio::test] | |
| 2053 | +async fn a_student_outside_the_course_is_refused_the_bytes() { | |
| 2054 | + // The bridge widens who may ask, never what may be read: the file's own | |
| 2055 | + // course-view guard answers, exactly as it does over HTTP. | |
| 2056 | + let bridge = bridge().await; | |
| 2057 | + let (service, _student, note, _course, _foreign, app, db, teacher) = | |
| 2058 | + course_notes_fixture(&bridge).await; | |
| 2059 | + | |
| 2060 | + let res = common::upload_file_at( | |
| 2061 | + &app, | |
| 2062 | + &teacher, | |
| 2063 | + &format!("/course-notes/{note}/files"), | |
| 2064 | + "recap.pdf", | |
| 2065 | + "application/pdf", | |
| 2066 | + b"gizli", | |
| 2067 | + ) | |
| 2068 | + .await; | |
| 2069 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 2070 | + let file = common::id_of(&res.body); | |
| 2071 | + | |
| 2072 | + let outsider_cookie = common::login_as(&app, &db, "veli", "student").await; | |
| 2073 | + let outsider = common::me_id(&app, &outsider_cookie).await; | |
| 2074 | + let (header, bytes) = blob_read(&service.conn, blob_of(&file, Some(&outsider))).await; | |
| 2075 | + assert_eq!(blob_refusal(header), "forbidden"); | |
| 2076 | + assert!(bytes.is_empty(), "a refusal is followed by nothing at all"); | |
| 2077 | +} | |
| 2078 | + | |
| 2079 | +#[tokio::test] | |
| 2080 | +async fn a_service_reading_the_bytes_as_itself_is_forbidden() { | |
| 2081 | + // Without `on_behalf_of` the principal is the `ai` role, which is enrolled | |
| 2082 | + // in nothing and manages nothing — so it can view no course, and the blob | |
| 2083 | + // stream grants it no reach the api read would not. | |
| 2084 | + let bridge = bridge().await; | |
| 2085 | + let (service, _student, note, _course, _foreign, app, _db, teacher) = | |
| 2086 | + course_notes_fixture(&bridge).await; | |
| 2087 | + | |
| 2088 | + let res = common::upload_file_at( | |
| 2089 | + &app, | |
| 2090 | + &teacher, | |
| 2091 | + &format!("/course-notes/{note}/files"), | |
| 2092 | + "recap.pdf", | |
| 2093 | + "application/pdf", | |
| 2094 | + b"gizli", | |
| 2095 | + ) | |
| 2096 | + .await; | |
| 2097 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 2098 | + let file = common::id_of(&res.body); | |
| 2099 | + | |
| 2100 | + let (header, _) = blob_read(&service.conn, blob_of(&file, None)).await; | |
| 2101 | + assert_eq!(blob_refusal(header), "forbidden"); | |
| 2102 | +} | |
| 2103 | + | |
| 2104 | +#[tokio::test] | |
| 2105 | +async fn an_unknown_file_key_is_not_found_rather_than_a_dropped_stream() { | |
| 2106 | + let bridge = bridge().await; | |
| 2107 | + let (service, student, _note, _course, _foreign, _app, _db, _teacher) = | |
| 2108 | + course_notes_fixture(&bridge).await; | |
| 2109 | + | |
| 2110 | + let (header, _) = blob_read(&service.conn, blob_of("01NOSUCHFILE", Some(&student))).await; | |
| 2111 | + assert_eq!(blob_refusal(header), "not_found"); | |
| 2112 | +} | |
| 2113 | + | |
| 2114 | +#[tokio::test] | |
| 2115 | +async fn a_personal_notes_file_is_invisible_to_the_blob_stream() { | |
| 2116 | + // Scope is course-note attachments and nothing else. A personal note has | |
| 2117 | + // no reader but its owner, and the id is looked up in `course_note_file` | |
| 2118 | + // alone — so the owner's own id does not open it either: `not_found`, not | |
| 2119 | + // `forbidden`, because no such course-note file exists. | |
| 2120 | + let bridge = bridge().await; | |
| 2121 | + let (service, student, _note, _course, _foreign, app, db, _teacher) = | |
| 2122 | + course_notes_fixture(&bridge).await; | |
| 2123 | + | |
| 2124 | + let owner = common::login_as(&app, &db, "kemal", "student").await; | |
| 2125 | + let owner_id = common::me_id(&app, &owner).await; | |
| 2126 | + let res = common::send( | |
| 2127 | + &app, | |
| 2128 | + "POST", | |
| 2129 | + "/notes", | |
| 2130 | + Some(&owner), | |
| 2131 | + Some(json!({ "title": "özel", "content": "kimseye yok" })), | |
| 2132 | + ) | |
| 2133 | + .await; | |
| 2134 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 2135 | + let personal = common::id_of(&res.body); | |
| 2136 | + let res = common::upload_file( | |
| 2137 | + &app, | |
| 2138 | + &owner, | |
| 2139 | + &personal, | |
| 2140 | + "gizli.pdf", | |
| 2141 | + "application/pdf", | |
| 2142 | + b"ozel", | |
| 2143 | + ) | |
| 2144 | + .await; | |
| 2145 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 2146 | + let personal_file = common::id_of(&res.body); | |
| 2147 | + | |
| 2148 | + for who in [&student, &owner_id] { | |
| 2149 | + let (header, _) = blob_read(&service.conn, blob_of(&personal_file, Some(who))).await; | |
| 2150 | + assert_eq!( | |
| 2151 | + blob_refusal(header), | |
| 2152 | + "not_found", | |
| 2153 | + "a personal note's file must not be reachable as a course-note file" | |
| 2154 | + ); | |
| 2155 | + } | |
| 2156 | +} |
tests/ai_protocol.rsmodified+178 -0
| @@ -182,6 +182,26 @@ mod raw { | ||
| 182 | 182 | read_frame(&mut recv).await.expect("read ApiResponse") |
| 183 | 183 | } |
| 184 | 184 | |
| 185 | + /// Send one frame verbatim on a fresh *client*-initiated stream, read the | |
| 186 | + /// single answer frame, and then read whatever raw bytes followed it. That | |
| 187 | + /// is the whole blob client: one `BlobRequest`, one header frame, then | |
| 188 | + /// exactly `size` bytes and EOF. | |
| 189 | + pub async fn blob_read(conn: &quinn::Connection, body: &[u8]) -> (Value, Vec<u8>, Vec<u8>) { | |
| 190 | + let (mut send, mut recv) = conn.open_bi().await.expect("blob stream"); | |
| 191 | + send.write_all(&frame(body)) | |
| 192 | + .await | |
| 193 | + .expect("write BlobRequest"); | |
| 194 | + let _ = send.finish(); | |
| 195 | + let (header, bytes) = read_frame(&mut recv).await.expect("read BlobResponse"); | |
| 196 | + // Deliberately asks for more than the header promised: a stream that | |
| 197 | + // wrote one byte too many would show up here, not as a silent pass. | |
| 198 | + let body = recv | |
| 199 | + .read_to_end(16 * 1024 * 1024) | |
| 200 | + .await | |
| 201 | + .expect("read to EOF after the header"); | |
| 202 | + (header, bytes, body) | |
| 203 | + } | |
| 204 | + | |
| 185 | 205 | /// The set of top-level keys of a JSON object, sorted. |
| 186 | 206 | pub fn keys(value: &Value) -> Vec<String> { |
| 187 | 207 | let mut k: Vec<String> = value |
| @@ -1113,3 +1133,161 @@ async fn an_api_read_answers_a_named_user_with_that_users_own_data() { | ||
| 1113 | 1133 | assert_eq!(answer["body"]["id"], student, "{answer}"); |
| 1114 | 1134 | assert_eq!(answer["body"]["role"], "student", "{answer}"); |
| 1115 | 1135 | } |
| 1136 | + | |
| 1137 | +// --------------------------------------------------- blob stream contract -- | |
| 1138 | +// | |
| 1139 | +// The bytes behind a course-note attachment, which no JSON frame can carry. | |
| 1140 | +// The header frame is a published contract exactly like the ones above, and | |
| 1141 | +// the `size`-then-EOF rule is what a foreign service implements by hand — so | |
| 1142 | +// both are asserted here as bytes. | |
| 1143 | + | |
| 1144 | +/// An armed router plus an uploaded course-note file: its id, and the bytes | |
| 1145 | +/// that were uploaded, read back by a service that must receive them verbatim. | |
| 1146 | +async fn armed_with_file(bridge: &AiBridge) -> (axum::Router, String, String, Vec<u8>) { | |
| 1147 | + let (app, db) = common::app_with_ai(Some(bridge.clone())).await; | |
| 1148 | + let student_cookie = common::login_as(&app, &db, "ayse", "student").await; | |
| 1149 | + let student = common::me_id(&app, &student_cookie).await; | |
| 1150 | + let teacher = common::login_as(&app, &db, "hoca", "teacher").await; | |
| 1151 | + let course = common::create_course(&app, &teacher, "Physics").await; | |
| 1152 | + common::enroll(&app, &teacher, &course, &student).await; | |
| 1153 | + | |
| 1154 | + let res = common::send( | |
| 1155 | + &app, | |
| 1156 | + "POST", | |
| 1157 | + "/course-notes", | |
| 1158 | + Some(&teacher), | |
| 1159 | + Some(json!({ "course": course, "title": "Newton", "content": "F = ma" })), | |
| 1160 | + ) | |
| 1161 | + .await; | |
| 1162 | + assert_eq!(res.status, 201, "{}", res.body); | |
| 1163 | + let note = common::id_of(&res.body); | |
| 1164 | + | |
| 1165 | + // Larger than one QUIC datagram, so the answer is a genuine multi-write | |
| 1166 | + // stream rather than something that happened to fit beside the header. | |
| 1167 | + let uploaded: Vec<u8> = (0..200 * 1024u32).map(|i| (i % 251) as u8).collect(); | |
| 1168 | + let res = common::upload_file_at( | |
| 1169 | + &app, | |
| 1170 | + &teacher, | |
| 1171 | + &format!("/course-notes/{note}/files"), | |
| 1172 | + "recap.pdf", | |
| 1173 | + "application/pdf", | |
| 1174 | + &uploaded, | |
| 1175 | + ) | |
| 1176 | + .await; | |
| 1177 | + assert_eq!(res.status, 201, "{}", res.body); | |
| 1178 | + let file = common::id_of(&res.body); | |
| 1179 | + (app, student, file, uploaded) | |
| 1180 | +} | |
| 1181 | + | |
| 1182 | +#[tokio::test] | |
| 1183 | +async fn the_blob_header_frame_carries_exactly_the_published_keys_then_size_bytes() { | |
| 1184 | + // Every documented field spelled out by hand, and the byte rule with it: a | |
| 1185 | + // service reads the header, then exactly `size` raw bytes, then EOF. A | |
| 1186 | + // length prefix sneaking in front of the body, or one byte too many after | |
| 1187 | + // it, would leave a foreign service parsing garbage. | |
| 1188 | + let bridge = bridge().await; | |
| 1189 | + let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await; | |
| 1190 | + await_workers(&bridge, 1).await; | |
| 1191 | + let (_app, student, file, uploaded) = armed_with_file(&bridge).await; | |
| 1192 | + | |
| 1193 | + let (header, bytes, body) = raw::blob_read( | |
| 1194 | + &service.conn, | |
| 1195 | + format!( | |
| 1196 | + r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","file":"{file}","on_behalf_of":"{student}"}}"# | |
| 1197 | + ) | |
| 1198 | + .as_bytes(), | |
| 1199 | + ) | |
| 1200 | + .await; | |
| 1201 | + | |
| 1202 | + assert_eq!( | |
| 1203 | + raw::keys(&header), | |
| 1204 | + ["content_type", "id", "name", "size", "status"], | |
| 1205 | + "blob header shape changed: {header}" | |
| 1206 | + ); | |
| 1207 | + assert_eq!(header["status"], "ok"); | |
| 1208 | + assert_eq!( | |
| 1209 | + header["id"], "01ARZ3NDEKTSV4RRFFQ69G5FAV", | |
| 1210 | + "the trace id is echoed" | |
| 1211 | + ); | |
| 1212 | + assert_eq!(header["name"], "recap.pdf"); | |
| 1213 | + assert_eq!(header["content_type"], "application/pdf"); | |
| 1214 | + assert_eq!(header["size"], uploaded.len(), "{header}"); | |
| 1215 | + | |
| 1216 | + // Byte level: the tag key is `status` with a bare lowercase literal, and | |
| 1217 | + // `size` is a JSON number, not a string a service would have to parse. | |
| 1218 | + let text = String::from_utf8(bytes).expect("the header frame is UTF-8 JSON"); | |
| 1219 | + assert!(text.contains(r#""status":"ok""#), "{text}"); | |
| 1220 | + assert!( | |
| 1221 | + text.contains(&format!(r#""size":{}"#, uploaded.len())), | |
| 1222 | + "{text}" | |
| 1223 | + ); | |
| 1224 | + | |
| 1225 | + // The body is raw: no four-byte length prefix, exactly `size` bytes, EOF. | |
| 1226 | + assert_eq!(body.len(), uploaded.len(), "`size` bytes then EOF"); | |
| 1227 | + assert!(body == uploaded, "the bytes differ from what was uploaded"); | |
| 1228 | +} | |
| 1229 | + | |
| 1230 | +#[tokio::test] | |
| 1231 | +async fn a_blob_refusal_frame_carries_exactly_the_published_keys_and_no_bytes() { | |
| 1232 | + let bridge = bridge().await; | |
| 1233 | + let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await; | |
| 1234 | + await_workers(&bridge, 1).await; | |
| 1235 | + let (_app, student, _file, _uploaded) = armed_with_file(&bridge).await; | |
| 1236 | + | |
| 1237 | + let (header, _, body) = raw::blob_read( | |
| 1238 | + &service.conn, | |
| 1239 | + format!(r#"{{"id":"t-blob","file":"01NOSUCHFILE","on_behalf_of":"{student}"}}"#).as_bytes(), | |
| 1240 | + ) | |
| 1241 | + .await; | |
| 1242 | + assert_eq!( | |
| 1243 | + raw::keys(&header), | |
| 1244 | + ["code", "id", "message", "status"], | |
| 1245 | + "blob refusal shape changed: {header}" | |
| 1246 | + ); | |
| 1247 | + assert_eq!(header["status"], "err"); | |
| 1248 | + assert_eq!(header["code"], "not_found"); | |
| 1249 | + assert_eq!(header["id"], "t-blob"); | |
| 1250 | + assert!(body.is_empty(), "a refusal is followed by nothing at all"); | |
| 1251 | +} | |
| 1252 | + | |
| 1253 | +#[tokio::test] | |
| 1254 | +async fn an_api_read_still_answers_on_the_shared_client_stream_path() { | |
| 1255 | + // The discriminator guard. Both request shapes now arrive on the same | |
| 1256 | + // client-initiated streams and are told apart by their required field — | |
| 1257 | + // `path` for an api read, `file` for a blob. An api read must keep | |
| 1258 | + // answering exactly as it did before the blob shape existed, and a frame | |
| 1259 | + // that is neither must still be the api read's `malformed` refusal rather | |
| 1260 | + // than a silent hang. | |
| 1261 | + let bridge = bridge().await; | |
| 1262 | + let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await; | |
| 1263 | + await_workers(&bridge, 1).await; | |
| 1264 | + let (_app, student, file, _uploaded) = armed_with_file(&bridge).await; | |
| 1265 | + | |
| 1266 | + let (answer, _) = raw::api_read( | |
| 1267 | + &service.conn, | |
| 1268 | + format!(r#"{{"id":"t-api","path":"/auth/me","on_behalf_of":"{student}"}}"#).as_bytes(), | |
| 1269 | + ) | |
| 1270 | + .await; | |
| 1271 | + assert_eq!(answer["outcome"], "ok", "{answer}"); | |
| 1272 | + assert_eq!(answer["status"], 200); | |
| 1273 | + assert_eq!(answer["body"]["id"], student, "{answer}"); | |
| 1274 | + | |
| 1275 | + // `path` wins over `file`: a frame carrying both is the api read it has | |
| 1276 | + // always been, so nothing that parsed before is re-routed now. | |
| 1277 | + let (answer, _) = raw::api_read( | |
| 1278 | + &service.conn, | |
| 1279 | + format!( | |
| 1280 | + r#"{{"id":"t-both","path":"/auth/me","file":"{file}","on_behalf_of":"{student}"}}"# | |
| 1281 | + ) | |
| 1282 | + .as_bytes(), | |
| 1283 | + ) | |
| 1284 | + .await; | |
| 1285 | + assert_eq!(answer["outcome"], "ok", "{answer}"); | |
| 1286 | + assert_eq!(answer["status"], 200); | |
| 1287 | + | |
| 1288 | + // Neither shape: still the api read's refusal, with its `outcome` tag. | |
| 1289 | + let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither"}"#).await; | |
| 1290 | + assert_eq!(answer["outcome"], "err", "{answer}"); | |
| 1291 | + assert_eq!(answer["code"], "malformed"); | |
| 1292 | + assert_eq!(answer["id"], "t-neither"); | |
| 1293 | +} |