From 01f55da179371c27ece6e004089f70c3f3af516d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 12 Aug 2026 17:30:47 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=AA=20test:=20pin=20the=20quic=20api-r?= =?UTF-8?q?ead=20wire=20and=20behavior?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/ai_bridge.rs | 213 +++++++++++++++++++++++++++++++++++++++++++ tests/ai_protocol.rs | 171 ++++++++++++++++++++++++++++++++++ tests/common/mod.rs | 10 +- 3 files changed, 393 insertions(+), 1 deletion(-) diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index bb94379..3d2bf5d 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -1393,6 +1393,219 @@ async fn a_bad_address_fails_the_boot_rather_than_going_quiet() { ); } +// --------------------------------------------------------------- api read -- +// +// The reverse direction: a registered service opens its own stream and reads +// the school API. These drive the real router over real QUIC, so what they +// assert is what a service actually receives — including who it is allowed to +// be, which is the security half of the feature. + +use hezarfen_backend::ai::protocol::{ApiRequest, ApiResponse}; + +/// One api read on a fresh client-initiated stream. +async fn api_read(conn: &quinn::Connection, request: ApiRequest) -> ApiResponse { + let (mut send, mut recv) = conn.open_bi().await.expect("api-read stream"); + write_frame(&mut send, &request) + .await + .expect("write ApiRequest"); + let _ = send.finish(); + read_frame(&mut recv).await.expect("read ApiResponse") +} + +/// A `GET` of `path` as `on_behalf_of` (or as the service itself). +fn read_of(path: &str, on_behalf_of: Option<&str>) -> ApiRequest { + ApiRequest { + id: format!("trace-{path}"), + path: path.to_string(), + query: None, + on_behalf_of: on_behalf_of.map(str::to_string), + method: None, + } +} + +/// Unwrap an `Ok` answer into (status, body); panics on a refusal, naming it. +fn ok_answer(answer: ApiResponse) -> (u16, Value) { + match answer { + ApiResponse::Ok { status, body, .. } => (status, body), + ApiResponse::Err { code, message, .. } => { + panic!("expected the api to answer, got refusal {code}: {message}") + } + } +} + +/// A registered service plus a router armed for its reads, plus a seeded +/// student (id and session cookie). +async fn api_service(bridge: &AiBridge) -> (FakeService, Router, String, String) { + let service = connect_service( + bridge, + hello("tutor", &[AI_CHAT_CAPABILITY]), + Behaviour::Echo, + ) + .await; + await_workers(bridge, 1).await; + let (app, db) = common::app_with_ai(Some(bridge.clone())).await; + let cookie = common::login_as(&app, &db, "ayse", "student").await; + let student = common::me_id(&app, &cookie).await; + (service, app, student, cookie) +} + +#[tokio::test] +async fn a_service_reading_on_behalf_of_a_student_gets_that_students_own_answer() { + // The entry surface, end to end: what the service reads over QUIC must be + // byte-for-byte the JSON that student's own browser gets from REST. A + // second-hand answer (the service's own principal, a stale row) would + // differ here rather than in whatever the model says weeks later. + let bridge = bridge().await; + let (service, app, student, cookie) = api_service(&bridge).await; + + let rest = common::send(&app, "GET", "/auth/me", Some(&cookie), None).await; + assert_eq!(rest.status, StatusCode::OK); + + let (status, body) = + ok_answer(api_read(&service.conn, read_of("/auth/me", Some(&student))).await); + assert_eq!(status, 200); + assert_eq!(body, rest.body, "the service read a different /auth/me"); +} + +#[tokio::test] +async fn a_service_reading_as_itself_is_the_ai_principal() { + // With nobody named, the request runs as the synthetic `ai` principal. + // That principal is authenticated (the extension satisfies the extractor), + // so an own-scoped read succeeds and returns *its* empty data — while a + // role-gated read is a 403, not a 401: the caller is known, just below + // every human role. + let bridge = bridge().await; + let (service, _app, student, _cookie) = api_service(&bridge).await; + + let (status, body) = ok_answer(api_read(&service.conn, read_of("/notes", None)).await); + assert_eq!(status, 200); + assert_eq!( + common::items(&body).len(), + 0, + "the ai principal owns nothing" + ); + + let (status, _) = + ok_answer(api_read(&service.conn, read_of(&format!("/marks/{student}"), None)).await); + assert_eq!( + status, 403, + "reading another person's marks needs teacher+ or a parent link" + ); +} + +#[tokio::test] +async fn a_router_status_rides_back_as_an_ok_answer_not_a_refusal() { + // The `Err` frame is reserved for bridge refusals. Anything the API itself + // answered — including a 404 — is an `Ok` carrying that status, so a + // service can tell "I was not allowed to ask" from "I asked and this is + // the answer". + let bridge = bridge().await; + let (service, _app, _student, _cookie) = api_service(&bridge).await; + + let (status, _) = ok_answer(api_read(&service.conn, read_of("/notes/nosuchnote", None)).await); + assert_eq!(status, 404); +} + +#[tokio::test] +async fn a_dead_user_id_is_refused_rather_than_run_as_somebody() { + // The principal is loaded live, so a service holding an id of a user who + // has since been deleted is told so — never silently downgraded to the ai + // principal, which would answer a question about the wrong person. + let bridge = bridge().await; + let (service, _app, _student, _cookie) = api_service(&bridge).await; + + match api_read(&service.conn, read_of("/auth/me", Some("ghost"))).await { + ApiResponse::Err { code, id, .. } => { + assert_eq!(code, "unknown_user"); + assert_eq!(id, "trace-/auth/me", "the trace id comes back"); + } + other => panic!("a dead id must not be dispatched: {other:?}"), + } +} + +#[tokio::test] +async fn the_record_form_of_a_user_id_reads_the_same_as_the_bare_key() { + // The protocol doc spells the id `user:`, REST paths spell it bare. + // Both are the same person; accepting only one would make the contract a + // trap for the first service that copies the doc example. + let bridge = bridge().await; + let (service, _app, student, _cookie) = api_service(&bridge).await; + + let bare = ok_answer(api_read(&service.conn, read_of("/auth/me", Some(&student))).await); + let prefixed = ok_answer( + api_read( + &service.conn, + read_of("/auth/me", Some(&format!("user:{student}"))), + ) + .await, + ); + assert_eq!(bare, prefixed); +} + +#[tokio::test] +async fn the_query_field_reaches_the_route_as_a_real_query_string() { + // Paging is how a service reads a long list without blowing the frame cap, + // so `query` has to arrive at the handler rather than being dropped: two + // notes exist, `limit=1` must return one of them and still report the total. + let bridge = bridge().await; + let (service, app, student, cookie) = api_service(&bridge).await; + for title in ["ilk not", "ikinci not"] { + let res = common::send( + &app, + "POST", + "/notes", + Some(&cookie), + Some(json!({ "title": title })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + } + + let mut request = read_of("/notes", Some(&student)); + request.query = Some("limit=1&offset=0".to_string()); + let (status, body) = ok_answer(api_read(&service.conn, request).await); + assert_eq!(status, 200); + assert_eq!( + common::items(&body).len(), + 1, + "limit=1 was honoured: {body}" + ); + assert_eq!(common::total(&body), 2, "both notes were counted: {body}"); +} + +#[tokio::test] +async fn the_ai_principal_cannot_be_forged_over_http() { + // The whole reason the principal travels as a request *extension*: nothing + // arriving on the public HTTP port can set one. A caller with no cookie + // stays unauthenticated however it names the header. + use tower::ServiceExt; + let bridge = bridge().await; + let (_service, app, student, _cookie) = api_service(&bridge).await; + + let spoofs = [ + ("ai-principal", student.as_str()), + ("x-ai-principal", student.as_str()), + ("aiprincipal", student.as_str()), + ("on-behalf-of", student.as_str()), + ]; + for (header, value) in spoofs { + let request = axum::http::Request::builder() + .uri("/auth/me") + .header(header, value) + .body(axum::body::Body::empty()) + .unwrap(); + let response = app.clone().oneshot(request).await.expect("router answered"); + assert_eq!( + response.status(), + StatusCode::UNAUTHORIZED, + "header `{header}` bought a session" + ); + } + // And a cookie-less read of the same path is 401 with no header at all. + let res = common::send(&app, "GET", "/auth/me", None, None).await; + assert_eq!(res.status, StatusCode::UNAUTHORIZED); +} + #[tokio::test] async fn a_configured_bridge_listens_and_serves_a_real_handshake() { // The whole point of the wiring: what `start_bridge` returns is a live diff --git a/tests/ai_protocol.rs b/tests/ai_protocol.rs index cdc7a8d..2a42e2b 100644 --- a/tests/ai_protocol.rs +++ b/tests/ai_protocol.rs @@ -169,6 +169,19 @@ mod raw { let _ = send.stopped().await; } + /// Send one api-read frame verbatim on a fresh *client*-initiated stream + /// and read the single answer frame. This is the whole api-read client: + /// after the handshake a service opens a stream, writes an `ApiRequest`, + /// and reads one `ApiResponse`. + pub async fn api_read(conn: &quinn::Connection, body: &[u8]) -> (Value, Vec) { + let (mut send, mut recv) = conn.open_bi().await.expect("api-read stream"); + send.write_all(&frame(body)) + .await + .expect("write ApiRequest"); + let _ = send.finish(); + read_frame(&mut recv).await.expect("read ApiResponse") + } + /// The set of top-level keys of a JSON object, sorted. pub fn keys(value: &Value) -> Vec { let mut k: Vec = value @@ -942,3 +955,161 @@ async fn a_chat_request_names_the_askers_school_role() { ) .await; } + +// ------------------------------------------------------------- api reads -- +// +// The other direction: a service opens its own stream and asks the school API +// a question. Its request and the backend's answer are a published contract in +// exactly the same way as the frames above, so they are built and read here as +// bytes — a renamed field or a re-tagged outcome breaks every foreign service +// and must break this file first. + +/// A bridge whose api-read path is armed by a real router, plus a seeded +/// student's id. Holding the router is what `build_router` arms, so it is +/// returned rather than dropped. +async fn armed(bridge: &AiBridge) -> (axum::Router, String) { + let (app, db) = common::app_with_ai(Some(bridge.clone())).await; + let cookie = common::login_as(&app, &db, "ayse", "student").await; + let student = common::me_id(&app, &cookie).await; + (app, student) +} + +#[tokio::test] +async fn the_api_request_field_names_are_the_published_literals() { + // Every documented field spelled out by hand: a rename of `on_behalf_of` + // or `query` would leave a service sending a field the backend ignores, + // which fails silently as "the AI answered about the wrong person". + let bridge = bridge().await; + let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; + await_workers(&bridge, 1).await; + let (_app, student) = armed(&bridge).await; + + let (answer, bytes) = raw::api_read( + &service.conn, + format!( + r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","path":"/notes","query":"limit=1&offset=0","on_behalf_of":"{student}","method":"GET"}}"# + ) + .as_bytes(), + ) + .await; + + assert_eq!( + raw::keys(&answer), + ["body", "id", "outcome", "status"], + "api answer shape changed: {answer}" + ); + assert_eq!(answer["outcome"], "ok"); + assert_eq!(answer["status"], 200); + assert_eq!( + answer["id"], "01ARZ3NDEKTSV4RRFFQ69G5FAV", + "the trace id is echoed" + ); + assert!(answer["body"]["items"].is_array(), "{answer}"); + // Byte level: the tag key is `outcome` and its value a bare lowercase + // literal, not an object-wrapped or capitalised variant name. + let text = String::from_utf8(bytes).expect("the answer frame is UTF-8 JSON"); + assert!(text.contains(r#""outcome":"ok""#), "{text}"); + assert!(text.contains(r#""status":200"#), "{text}"); +} + +#[tokio::test] +async fn only_id_and_path_are_required_of_an_api_request() { + // `query`, `on_behalf_of` and `method` are optional by contract: a service + // that sends neither must read as the service itself, over GET. + let bridge = bridge().await; + let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; + await_workers(&bridge, 1).await; + let (_app, _student) = armed(&bridge).await; + + let (answer, _) = raw::api_read( + &service.conn, + br#"{"id":"trace-1","path":"/auth/me","unknown_field":true}"#, + ) + .await; + assert_eq!(answer["outcome"], "ok", "{answer}"); + assert_eq!(answer["status"], 200); + // The synthetic principal the bridge runs as when nobody is named. + assert_eq!(answer["body"]["role"], "ai", "{answer}"); +} + +#[tokio::test] +async fn the_api_refusal_frame_carries_exactly_the_published_keys_and_codes() { + // A service switches on these code literals. The `method` cases also pin + // the refusal *order*: a non-GET on a path that is not allowlisted either + // is `method_not_allowed`, because the method is judged first. + let bridge = bridge().await; + let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; + await_workers(&bridge, 1).await; + let (_app, _student) = armed(&bridge).await; + + let cases = [ + ( + "method_not_allowed", + r#"{"id":"t1","path":"/notes","method":"DELETE"}"#.to_string(), + ), + ( + "method_not_allowed", + // Lowercase is not the method: the literal is exactly `GET`. + r#"{"id":"t2","path":"/notes","method":"get"}"#.to_string(), + ), + ( + "path_not_allowed", + r#"{"id":"t3","path":"/courses"}"#.to_string(), + ), + ( + // Order pin: both refusals apply, the method one wins. + "method_not_allowed", + r#"{"id":"t4","path":"/nope","method":"POST"}"#.to_string(), + ), + ( + "unknown_user", + r#"{"id":"t5","path":"/auth/me","on_behalf_of":"nobodyatall"}"#.to_string(), + ), + ("malformed", r#"{"id":"t6","path":42}"#.to_string()), + ]; + + for (expected_code, request) in cases { + let (answer, _) = raw::api_read(&service.conn, request.as_bytes()).await; + assert_eq!( + raw::keys(&answer), + ["code", "id", "message", "outcome"], + "refusal shape changed for {expected_code}: {answer}" + ); + assert_eq!(answer["outcome"], "err", "{answer}"); + assert_eq!( + answer["code"], expected_code, + "refusal code spelling changed: {answer}" + ); + assert!( + answer["message"].as_str().is_some_and(|m| !m.is_empty()), + "message must be a string a service can log: {answer}" + ); + // Even a frame the backend could not parse into a request echoes the + // id, which is what the service correlates its own logs by. + assert!( + answer["id"].as_str().is_some_and(|i| i.starts_with('t')), + "{answer}" + ); + } +} + +#[tokio::test] +async fn an_api_read_answers_a_named_user_with_that_users_own_data() { + // The happy path a service actually uses: read an own-scoped endpoint as + // the student who asked. The answer must be that student's row, not the + // service's synthetic principal. + let bridge = bridge().await; + let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; + await_workers(&bridge, 1).await; + let (_app, student) = armed(&bridge).await; + + let (answer, _) = raw::api_read( + &service.conn, + format!(r#"{{"id":"t9","path":"/auth/me","on_behalf_of":"{student}"}}"#).as_bytes(), + ) + .await; + assert_eq!(answer["outcome"], "ok", "{answer}"); + assert_eq!(answer["status"], 200); + assert_eq!(answer["body"]["id"], student, "{answer}"); + assert_eq!(answer["body"]["role"], "student", "{answer}"); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index d0c45be..ab681ae 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -8,6 +8,7 @@ use std::sync::OnceLock; use axum::Router; use axum::body::Body; use axum::http::{HeaderMap, Request, StatusCode}; +use hezarfen_backend::ai::AiBridge; use hezarfen_backend::database::Database; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::AppState; @@ -39,6 +40,13 @@ pub fn files_dir() -> PathBuf { /// grant roles use the handle to seed them directly — the app's only role /// bootstrap path is out-of-band, exactly like production's manual SQL. pub async fn app_and_db() -> (Router, Database) { + app_with_ai(None).await +} + +/// The same router, with the AI bridge wired into its state. `build_router` +/// arms the bridge's api-read handle whenever `ai` is `Some`, so this is the +/// bootstrap that makes a QUIC service's reads dispatch into a real router. +pub async fn app_with_ai(ai: Option) -> (Router, Database) { let db = database::init_mem().await.expect("in-memory db"); let app = build_router(AppState { db: db.clone(), @@ -51,7 +59,7 @@ pub async fn app_and_db() -> (Router, Database) { exam_presence: Default::default(), board_hub: Default::default(), db_up: Default::default(), - ai: None, + ai, }); (app, db) }