Pin the quic api-read wire and behavior
Browse files at this commit01f55da179371c27ece6e004089f70c3f3af516dParent: 08854ee- test
- pin the quic api-read wire and behavior
3 changed files +393 -1
- tests/ai_bridge.rs +213 -0
- tests/ai_protocol.rs +171 -0
- tests/common/mod.rs +9 -1
tests/ai_bridge.rsmodified+213 -0
| @@ -1393,6 +1393,219 @@ async fn a_bad_address_fails_the_boot_rather_than_going_quiet() { | |||
| 1393 | ); | 1393 | ); |
| 1394 | } | 1394 | } |
| 1395 | 1395 | ||
| 1396 | +// --------------------------------------------------------------- api read -- | ||
| 1397 | +// | ||
| 1398 | +// The reverse direction: a registered service opens its own stream and reads | ||
| 1399 | +// the school API. These drive the real router over real QUIC, so what they | ||
| 1400 | +// assert is what a service actually receives — including who it is allowed to | ||
| 1401 | +// be, which is the security half of the feature. | ||
| 1402 | + | ||
| 1403 | +use hezarfen_backend::ai::protocol::{ApiRequest, ApiResponse}; | ||
| 1404 | + | ||
| 1405 | +/// One api read on a fresh client-initiated stream. | ||
| 1406 | +async fn api_read(conn: &quinn::Connection, request: ApiRequest) -> ApiResponse { | ||
| 1407 | + let (mut send, mut recv) = conn.open_bi().await.expect("api-read stream"); | ||
| 1408 | + write_frame(&mut send, &request) | ||
| 1409 | + .await | ||
| 1410 | + .expect("write ApiRequest"); | ||
| 1411 | + let _ = send.finish(); | ||
| 1412 | + read_frame(&mut recv).await.expect("read ApiResponse") | ||
| 1413 | +} | ||
| 1414 | + | ||
| 1415 | +/// A `GET` of `path` as `on_behalf_of` (or as the service itself). | ||
| 1416 | +fn read_of(path: &str, on_behalf_of: Option<&str>) -> ApiRequest { | ||
| 1417 | + ApiRequest { | ||
| 1418 | + id: format!("trace-{path}"), | ||
| 1419 | + path: path.to_string(), | ||
| 1420 | + query: None, | ||
| 1421 | + on_behalf_of: on_behalf_of.map(str::to_string), | ||
| 1422 | + method: None, | ||
| 1423 | + } | ||
| 1424 | +} | ||
| 1425 | + | ||
| 1426 | +/// Unwrap an `Ok` answer into (status, body); panics on a refusal, naming it. | ||
| 1427 | +fn ok_answer(answer: ApiResponse) -> (u16, Value) { | ||
| 1428 | + match answer { | ||
| 1429 | + ApiResponse::Ok { status, body, .. } => (status, body), | ||
| 1430 | + ApiResponse::Err { code, message, .. } => { | ||
| 1431 | + panic!("expected the api to answer, got refusal {code}: {message}") | ||
| 1432 | + } | ||
| 1433 | + } | ||
| 1434 | +} | ||
| 1435 | + | ||
| 1436 | +/// A registered service plus a router armed for its reads, plus a seeded | ||
| 1437 | +/// student (id and session cookie). | ||
| 1438 | +async fn api_service(bridge: &AiBridge) -> (FakeService, Router, String, String) { | ||
| 1439 | + let service = connect_service( | ||
| 1440 | + bridge, | ||
| 1441 | + hello("tutor", &[AI_CHAT_CAPABILITY]), | ||
| 1442 | + Behaviour::Echo, | ||
| 1443 | + ) | ||
| 1444 | + .await; | ||
| 1445 | + await_workers(bridge, 1).await; | ||
| 1446 | + let (app, db) = common::app_with_ai(Some(bridge.clone())).await; | ||
| 1447 | + let cookie = common::login_as(&app, &db, "ayse", "student").await; | ||
| 1448 | + let student = common::me_id(&app, &cookie).await; | ||
| 1449 | + (service, app, student, cookie) | ||
| 1450 | +} | ||
| 1451 | + | ||
| 1452 | +#[tokio::test] | ||
| 1453 | +async fn a_service_reading_on_behalf_of_a_student_gets_that_students_own_answer() { | ||
| 1454 | + // The entry surface, end to end: what the service reads over QUIC must be | ||
| 1455 | + // byte-for-byte the JSON that student's own browser gets from REST. A | ||
| 1456 | + // second-hand answer (the service's own principal, a stale row) would | ||
| 1457 | + // differ here rather than in whatever the model says weeks later. | ||
| 1458 | + let bridge = bridge().await; | ||
| 1459 | + let (service, app, student, cookie) = api_service(&bridge).await; | ||
| 1460 | + | ||
| 1461 | + let rest = common::send(&app, "GET", "/auth/me", Some(&cookie), None).await; | ||
| 1462 | + assert_eq!(rest.status, StatusCode::OK); | ||
| 1463 | + | ||
| 1464 | + let (status, body) = | ||
| 1465 | + ok_answer(api_read(&service.conn, read_of("/auth/me", Some(&student))).await); | ||
| 1466 | + assert_eq!(status, 200); | ||
| 1467 | + assert_eq!(body, rest.body, "the service read a different /auth/me"); | ||
| 1468 | +} | ||
| 1469 | + | ||
| 1470 | +#[tokio::test] | ||
| 1471 | +async fn a_service_reading_as_itself_is_the_ai_principal() { | ||
| 1472 | + // With nobody named, the request runs as the synthetic `ai` principal. | ||
| 1473 | + // That principal is authenticated (the extension satisfies the extractor), | ||
| 1474 | + // so an own-scoped read succeeds and returns *its* empty data — while a | ||
| 1475 | + // role-gated read is a 403, not a 401: the caller is known, just below | ||
| 1476 | + // every human role. | ||
| 1477 | + let bridge = bridge().await; | ||
| 1478 | + let (service, _app, student, _cookie) = api_service(&bridge).await; | ||
| 1479 | + | ||
| 1480 | + let (status, body) = ok_answer(api_read(&service.conn, read_of("/notes", None)).await); | ||
| 1481 | + assert_eq!(status, 200); | ||
| 1482 | + assert_eq!( | ||
| 1483 | + common::items(&body).len(), | ||
| 1484 | + 0, | ||
| 1485 | + "the ai principal owns nothing" | ||
| 1486 | + ); | ||
| 1487 | + | ||
| 1488 | + let (status, _) = | ||
| 1489 | + ok_answer(api_read(&service.conn, read_of(&format!("/marks/{student}"), None)).await); | ||
| 1490 | + assert_eq!( | ||
| 1491 | + status, 403, | ||
| 1492 | + "reading another person's marks needs teacher+ or a parent link" | ||
| 1493 | + ); | ||
| 1494 | +} | ||
| 1495 | + | ||
| 1496 | +#[tokio::test] | ||
| 1497 | +async fn a_router_status_rides_back_as_an_ok_answer_not_a_refusal() { | ||
| 1498 | + // The `Err` frame is reserved for bridge refusals. Anything the API itself | ||
| 1499 | + // answered — including a 404 — is an `Ok` carrying that status, so a | ||
| 1500 | + // service can tell "I was not allowed to ask" from "I asked and this is | ||
| 1501 | + // the answer". | ||
| 1502 | + let bridge = bridge().await; | ||
| 1503 | + let (service, _app, _student, _cookie) = api_service(&bridge).await; | ||
| 1504 | + | ||
| 1505 | + let (status, _) = ok_answer(api_read(&service.conn, read_of("/notes/nosuchnote", None)).await); | ||
| 1506 | + assert_eq!(status, 404); | ||
| 1507 | +} | ||
| 1508 | + | ||
| 1509 | +#[tokio::test] | ||
| 1510 | +async fn a_dead_user_id_is_refused_rather_than_run_as_somebody() { | ||
| 1511 | + // The principal is loaded live, so a service holding an id of a user who | ||
| 1512 | + // has since been deleted is told so — never silently downgraded to the ai | ||
| 1513 | + // principal, which would answer a question about the wrong person. | ||
| 1514 | + let bridge = bridge().await; | ||
| 1515 | + let (service, _app, _student, _cookie) = api_service(&bridge).await; | ||
| 1516 | + | ||
| 1517 | + match api_read(&service.conn, read_of("/auth/me", Some("ghost"))).await { | ||
| 1518 | + ApiResponse::Err { code, id, .. } => { | ||
| 1519 | + assert_eq!(code, "unknown_user"); | ||
| 1520 | + assert_eq!(id, "trace-/auth/me", "the trace id comes back"); | ||
| 1521 | + } | ||
| 1522 | + other => panic!("a dead id must not be dispatched: {other:?}"), | ||
| 1523 | + } | ||
| 1524 | +} | ||
| 1525 | + | ||
| 1526 | +#[tokio::test] | ||
| 1527 | +async fn the_record_form_of_a_user_id_reads_the_same_as_the_bare_key() { | ||
| 1528 | + // The protocol doc spells the id `user:<key>`, REST paths spell it bare. | ||
| 1529 | + // Both are the same person; accepting only one would make the contract a | ||
| 1530 | + // trap for the first service that copies the doc example. | ||
| 1531 | + let bridge = bridge().await; | ||
| 1532 | + let (service, _app, student, _cookie) = api_service(&bridge).await; | ||
| 1533 | + | ||
| 1534 | + let bare = ok_answer(api_read(&service.conn, read_of("/auth/me", Some(&student))).await); | ||
| 1535 | + let prefixed = ok_answer( | ||
| 1536 | + api_read( | ||
| 1537 | + &service.conn, | ||
| 1538 | + read_of("/auth/me", Some(&format!("user:{student}"))), | ||
| 1539 | + ) | ||
| 1540 | + .await, | ||
| 1541 | + ); | ||
| 1542 | + assert_eq!(bare, prefixed); | ||
| 1543 | +} | ||
| 1544 | + | ||
| 1545 | +#[tokio::test] | ||
| 1546 | +async fn the_query_field_reaches_the_route_as_a_real_query_string() { | ||
| 1547 | + // Paging is how a service reads a long list without blowing the frame cap, | ||
| 1548 | + // so `query` has to arrive at the handler rather than being dropped: two | ||
| 1549 | + // notes exist, `limit=1` must return one of them and still report the total. | ||
| 1550 | + let bridge = bridge().await; | ||
| 1551 | + let (service, app, student, cookie) = api_service(&bridge).await; | ||
| 1552 | + for title in ["ilk not", "ikinci not"] { | ||
| 1553 | + let res = common::send( | ||
| 1554 | + &app, | ||
| 1555 | + "POST", | ||
| 1556 | + "/notes", | ||
| 1557 | + Some(&cookie), | ||
| 1558 | + Some(json!({ "title": title })), | ||
| 1559 | + ) | ||
| 1560 | + .await; | ||
| 1561 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 1562 | + } | ||
| 1563 | + | ||
| 1564 | + let mut request = read_of("/notes", Some(&student)); | ||
| 1565 | + request.query = Some("limit=1&offset=0".to_string()); | ||
| 1566 | + let (status, body) = ok_answer(api_read(&service.conn, request).await); | ||
| 1567 | + assert_eq!(status, 200); | ||
| 1568 | + assert_eq!( | ||
| 1569 | + common::items(&body).len(), | ||
| 1570 | + 1, | ||
| 1571 | + "limit=1 was honoured: {body}" | ||
| 1572 | + ); | ||
| 1573 | + assert_eq!(common::total(&body), 2, "both notes were counted: {body}"); | ||
| 1574 | +} | ||
| 1575 | + | ||
| 1576 | +#[tokio::test] | ||
| 1577 | +async fn the_ai_principal_cannot_be_forged_over_http() { | ||
| 1578 | + // The whole reason the principal travels as a request *extension*: nothing | ||
| 1579 | + // arriving on the public HTTP port can set one. A caller with no cookie | ||
| 1580 | + // stays unauthenticated however it names the header. | ||
| 1581 | + use tower::ServiceExt; | ||
| 1582 | + let bridge = bridge().await; | ||
| 1583 | + let (_service, app, student, _cookie) = api_service(&bridge).await; | ||
| 1584 | + | ||
| 1585 | + let spoofs = [ | ||
| 1586 | + ("ai-principal", student.as_str()), | ||
| 1587 | + ("x-ai-principal", student.as_str()), | ||
| 1588 | + ("aiprincipal", student.as_str()), | ||
| 1589 | + ("on-behalf-of", student.as_str()), | ||
| 1590 | + ]; | ||
| 1591 | + for (header, value) in spoofs { | ||
| 1592 | + let request = axum::http::Request::builder() | ||
| 1593 | + .uri("/auth/me") | ||
| 1594 | + .header(header, value) | ||
| 1595 | + .body(axum::body::Body::empty()) | ||
| 1596 | + .unwrap(); | ||
| 1597 | + let response = app.clone().oneshot(request).await.expect("router answered"); | ||
| 1598 | + assert_eq!( | ||
| 1599 | + response.status(), | ||
| 1600 | + StatusCode::UNAUTHORIZED, | ||
| 1601 | + "header `{header}` bought a session" | ||
| 1602 | + ); | ||
| 1603 | + } | ||
| 1604 | + // And a cookie-less read of the same path is 401 with no header at all. | ||
| 1605 | + let res = common::send(&app, "GET", "/auth/me", None, None).await; | ||
| 1606 | + assert_eq!(res.status, StatusCode::UNAUTHORIZED); | ||
| 1607 | +} | ||
| 1608 | + | ||
| 1396 | #[tokio::test] | 1609 | #[tokio::test] |
| 1397 | async fn a_configured_bridge_listens_and_serves_a_real_handshake() { | 1610 | async fn a_configured_bridge_listens_and_serves_a_real_handshake() { |
| 1398 | // The whole point of the wiring: what `start_bridge` returns is a live | 1611 | // The whole point of the wiring: what `start_bridge` returns is a live |
tests/ai_protocol.rsmodified+171 -0
| @@ -169,6 +169,19 @@ mod raw { | |||
| 169 | let _ = send.stopped().await; | 169 | let _ = send.stopped().await; |
| 170 | } | 170 | } |
| 171 | 171 | ||
| 172 | + /// Send one api-read frame verbatim on a fresh *client*-initiated stream | ||
| 173 | + /// and read the single answer frame. This is the whole api-read client: | ||
| 174 | + /// after the handshake a service opens a stream, writes an `ApiRequest`, | ||
| 175 | + /// and reads one `ApiResponse`. | ||
| 176 | + pub async fn api_read(conn: &quinn::Connection, body: &[u8]) -> (Value, Vec<u8>) { | ||
| 177 | + let (mut send, mut recv) = conn.open_bi().await.expect("api-read stream"); | ||
| 178 | + send.write_all(&frame(body)) | ||
| 179 | + .await | ||
| 180 | + .expect("write ApiRequest"); | ||
| 181 | + let _ = send.finish(); | ||
| 182 | + read_frame(&mut recv).await.expect("read ApiResponse") | ||
| 183 | + } | ||
| 184 | + | ||
| 172 | /// The set of top-level keys of a JSON object, sorted. | 185 | /// The set of top-level keys of a JSON object, sorted. |
| 173 | pub fn keys(value: &Value) -> Vec<String> { | 186 | pub fn keys(value: &Value) -> Vec<String> { |
| 174 | let mut k: Vec<String> = value | 187 | let mut k: Vec<String> = value |
| @@ -942,3 +955,161 @@ async fn a_chat_request_names_the_askers_school_role() { | |||
| 942 | ) | 955 | ) |
| 943 | .await; | 956 | .await; |
| 944 | } | 957 | } |
| 958 | + | ||
| 959 | +// ------------------------------------------------------------- api reads -- | ||
| 960 | +// | ||
| 961 | +// The other direction: a service opens its own stream and asks the school API | ||
| 962 | +// a question. Its request and the backend's answer are a published contract in | ||
| 963 | +// exactly the same way as the frames above, so they are built and read here as | ||
| 964 | +// bytes — a renamed field or a re-tagged outcome breaks every foreign service | ||
| 965 | +// and must break this file first. | ||
| 966 | + | ||
| 967 | +/// A bridge whose api-read path is armed by a real router, plus a seeded | ||
| 968 | +/// student's id. Holding the router is what `build_router` arms, so it is | ||
| 969 | +/// returned rather than dropped. | ||
| 970 | +async fn armed(bridge: &AiBridge) -> (axum::Router, String) { | ||
| 971 | + let (app, db) = common::app_with_ai(Some(bridge.clone())).await; | ||
| 972 | + let cookie = common::login_as(&app, &db, "ayse", "student").await; | ||
| 973 | + let student = common::me_id(&app, &cookie).await; | ||
| 974 | + (app, student) | ||
| 975 | +} | ||
| 976 | + | ||
| 977 | +#[tokio::test] | ||
| 978 | +async fn the_api_request_field_names_are_the_published_literals() { | ||
| 979 | + // Every documented field spelled out by hand: a rename of `on_behalf_of` | ||
| 980 | + // or `query` would leave a service sending a field the backend ignores, | ||
| 981 | + // which fails silently as "the AI answered about the wrong person". | ||
| 982 | + let bridge = bridge().await; | ||
| 983 | + let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; | ||
| 984 | + await_workers(&bridge, 1).await; | ||
| 985 | + let (_app, student) = armed(&bridge).await; | ||
| 986 | + | ||
| 987 | + let (answer, bytes) = raw::api_read( | ||
| 988 | + &service.conn, | ||
| 989 | + format!( | ||
| 990 | + r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","path":"/notes","query":"limit=1&offset=0","on_behalf_of":"{student}","method":"GET"}}"# | ||
| 991 | + ) | ||
| 992 | + .as_bytes(), | ||
| 993 | + ) | ||
| 994 | + .await; | ||
| 995 | + | ||
| 996 | + assert_eq!( | ||
| 997 | + raw::keys(&answer), | ||
| 998 | + ["body", "id", "outcome", "status"], | ||
| 999 | + "api answer shape changed: {answer}" | ||
| 1000 | + ); | ||
| 1001 | + assert_eq!(answer["outcome"], "ok"); | ||
| 1002 | + assert_eq!(answer["status"], 200); | ||
| 1003 | + assert_eq!( | ||
| 1004 | + answer["id"], "01ARZ3NDEKTSV4RRFFQ69G5FAV", | ||
| 1005 | + "the trace id is echoed" | ||
| 1006 | + ); | ||
| 1007 | + assert!(answer["body"]["items"].is_array(), "{answer}"); | ||
| 1008 | + // Byte level: the tag key is `outcome` and its value a bare lowercase | ||
| 1009 | + // literal, not an object-wrapped or capitalised variant name. | ||
| 1010 | + let text = String::from_utf8(bytes).expect("the answer frame is UTF-8 JSON"); | ||
| 1011 | + assert!(text.contains(r#""outcome":"ok""#), "{text}"); | ||
| 1012 | + assert!(text.contains(r#""status":200"#), "{text}"); | ||
| 1013 | +} | ||
| 1014 | + | ||
| 1015 | +#[tokio::test] | ||
| 1016 | +async fn only_id_and_path_are_required_of_an_api_request() { | ||
| 1017 | + // `query`, `on_behalf_of` and `method` are optional by contract: a service | ||
| 1018 | + // that sends neither must read as the service itself, over GET. | ||
| 1019 | + let bridge = bridge().await; | ||
| 1020 | + let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; | ||
| 1021 | + await_workers(&bridge, 1).await; | ||
| 1022 | + let (_app, _student) = armed(&bridge).await; | ||
| 1023 | + | ||
| 1024 | + let (answer, _) = raw::api_read( | ||
| 1025 | + &service.conn, | ||
| 1026 | + br#"{"id":"trace-1","path":"/auth/me","unknown_field":true}"#, | ||
| 1027 | + ) | ||
| 1028 | + .await; | ||
| 1029 | + assert_eq!(answer["outcome"], "ok", "{answer}"); | ||
| 1030 | + assert_eq!(answer["status"], 200); | ||
| 1031 | + // The synthetic principal the bridge runs as when nobody is named. | ||
| 1032 | + assert_eq!(answer["body"]["role"], "ai", "{answer}"); | ||
| 1033 | +} | ||
| 1034 | + | ||
| 1035 | +#[tokio::test] | ||
| 1036 | +async fn the_api_refusal_frame_carries_exactly_the_published_keys_and_codes() { | ||
| 1037 | + // A service switches on these code literals. The `method` cases also pin | ||
| 1038 | + // the refusal *order*: a non-GET on a path that is not allowlisted either | ||
| 1039 | + // is `method_not_allowed`, because the method is judged first. | ||
| 1040 | + let bridge = bridge().await; | ||
| 1041 | + let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; | ||
| 1042 | + await_workers(&bridge, 1).await; | ||
| 1043 | + let (_app, _student) = armed(&bridge).await; | ||
| 1044 | + | ||
| 1045 | + let cases = [ | ||
| 1046 | + ( | ||
| 1047 | + "method_not_allowed", | ||
| 1048 | + r#"{"id":"t1","path":"/notes","method":"DELETE"}"#.to_string(), | ||
| 1049 | + ), | ||
| 1050 | + ( | ||
| 1051 | + "method_not_allowed", | ||
| 1052 | + // Lowercase is not the method: the literal is exactly `GET`. | ||
| 1053 | + r#"{"id":"t2","path":"/notes","method":"get"}"#.to_string(), | ||
| 1054 | + ), | ||
| 1055 | + ( | ||
| 1056 | + "path_not_allowed", | ||
| 1057 | + r#"{"id":"t3","path":"/courses"}"#.to_string(), | ||
| 1058 | + ), | ||
| 1059 | + ( | ||
| 1060 | + // Order pin: both refusals apply, the method one wins. | ||
| 1061 | + "method_not_allowed", | ||
| 1062 | + r#"{"id":"t4","path":"/nope","method":"POST"}"#.to_string(), | ||
| 1063 | + ), | ||
| 1064 | + ( | ||
| 1065 | + "unknown_user", | ||
| 1066 | + r#"{"id":"t5","path":"/auth/me","on_behalf_of":"nobodyatall"}"#.to_string(), | ||
| 1067 | + ), | ||
| 1068 | + ("malformed", r#"{"id":"t6","path":42}"#.to_string()), | ||
| 1069 | + ]; | ||
| 1070 | + | ||
| 1071 | + for (expected_code, request) in cases { | ||
| 1072 | + let (answer, _) = raw::api_read(&service.conn, request.as_bytes()).await; | ||
| 1073 | + assert_eq!( | ||
| 1074 | + raw::keys(&answer), | ||
| 1075 | + ["code", "id", "message", "outcome"], | ||
| 1076 | + "refusal shape changed for {expected_code}: {answer}" | ||
| 1077 | + ); | ||
| 1078 | + assert_eq!(answer["outcome"], "err", "{answer}"); | ||
| 1079 | + assert_eq!( | ||
| 1080 | + answer["code"], expected_code, | ||
| 1081 | + "refusal code spelling changed: {answer}" | ||
| 1082 | + ); | ||
| 1083 | + assert!( | ||
| 1084 | + answer["message"].as_str().is_some_and(|m| !m.is_empty()), | ||
| 1085 | + "message must be a string a service can log: {answer}" | ||
| 1086 | + ); | ||
| 1087 | + // Even a frame the backend could not parse into a request echoes the | ||
| 1088 | + // id, which is what the service correlates its own logs by. | ||
| 1089 | + assert!( | ||
| 1090 | + answer["id"].as_str().is_some_and(|i| i.starts_with('t')), | ||
| 1091 | + "{answer}" | ||
| 1092 | + ); | ||
| 1093 | + } | ||
| 1094 | +} | ||
| 1095 | + | ||
| 1096 | +#[tokio::test] | ||
| 1097 | +async fn an_api_read_answers_a_named_user_with_that_users_own_data() { | ||
| 1098 | + // The happy path a service actually uses: read an own-scoped endpoint as | ||
| 1099 | + // the student who asked. The answer must be that student's row, not the | ||
| 1100 | + // service's synthetic principal. | ||
| 1101 | + let bridge = bridge().await; | ||
| 1102 | + let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; | ||
| 1103 | + await_workers(&bridge, 1).await; | ||
| 1104 | + let (_app, student) = armed(&bridge).await; | ||
| 1105 | + | ||
| 1106 | + let (answer, _) = raw::api_read( | ||
| 1107 | + &service.conn, | ||
| 1108 | + format!(r#"{{"id":"t9","path":"/auth/me","on_behalf_of":"{student}"}}"#).as_bytes(), | ||
| 1109 | + ) | ||
| 1110 | + .await; | ||
| 1111 | + assert_eq!(answer["outcome"], "ok", "{answer}"); | ||
| 1112 | + assert_eq!(answer["status"], 200); | ||
| 1113 | + assert_eq!(answer["body"]["id"], student, "{answer}"); | ||
| 1114 | + assert_eq!(answer["body"]["role"], "student", "{answer}"); | ||
| 1115 | +} | ||
tests/common/mod.rsmodified+9 -1
| @@ -8,6 +8,7 @@ use std::sync::OnceLock; | |||
| 8 | use axum::Router; | 8 | use axum::Router; |
| 9 | use axum::body::Body; | 9 | use axum::body::Body; |
| 10 | use axum::http::{HeaderMap, Request, StatusCode}; | 10 | use axum::http::{HeaderMap, Request, StatusCode}; |
| 11 | +use hezarfen_backend::ai::AiBridge; | ||
| 11 | use hezarfen_backend::database::Database; | 12 | use hezarfen_backend::database::Database; |
| 12 | use hezarfen_backend::rate_limit::RateLimitConfig; | 13 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 13 | use hezarfen_backend::state::AppState; | 14 | use hezarfen_backend::state::AppState; |
| @@ -39,6 +40,13 @@ pub fn files_dir() -> PathBuf { | |||
| 39 | /// grant roles use the handle to seed them directly — the app's only role | 40 | /// grant roles use the handle to seed them directly — the app's only role |
| 40 | /// bootstrap path is out-of-band, exactly like production's manual SQL. | 41 | /// bootstrap path is out-of-band, exactly like production's manual SQL. |
| 41 | pub async fn app_and_db() -> (Router, Database) { | 42 | pub async fn app_and_db() -> (Router, Database) { |
| 43 | + app_with_ai(None).await | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/// The same router, with the AI bridge wired into its state. `build_router` | ||
| 47 | +/// arms the bridge's api-read handle whenever `ai` is `Some`, so this is the | ||
| 48 | +/// bootstrap that makes a QUIC service's reads dispatch into a real router. | ||
| 49 | +pub async fn app_with_ai(ai: Option<AiBridge>) -> (Router, Database) { | ||
| 42 | let db = database::init_mem().await.expect("in-memory db"); | 50 | let db = database::init_mem().await.expect("in-memory db"); |
| 43 | let app = build_router(AppState { | 51 | let app = build_router(AppState { |
| 44 | db: db.clone(), | 52 | db: db.clone(), |
| @@ -51,7 +59,7 @@ pub async fn app_and_db() -> (Router, Database) { | |||
| 51 | exam_presence: Default::default(), | 59 | exam_presence: Default::default(), |
| 52 | board_hub: Default::default(), | 60 | board_hub: Default::default(), |
| 53 | db_up: Default::default(), | 61 | db_up: Default::default(), |
| 54 | - ai: None, | 62 | + ai, |
| 55 | }); | 63 | }); |
| 56 | (app, db) | 64 | (app, db) |
| 57 | } | 65 | } |