forge
Explore
Log in

Don't you dare go Hollow

Pay the api-read err-code coverage debt

Browse files at this commit

a3cf87f0e9a7bf0c31c548fa6e1b35b1c357cd0cAhmet Kaan GümüşParent: b97b802
  • test
    • pay the api-read err-code coverage debt
Show full message
🧪 test: pay the api-read err-code coverage debt

`unavailable`, `not_json` and `too_large` shipped code-read only. Each now
has a test that bites when its branch is removed (both were checked against
a mutated source):

- `unavailable` behaviourally, over real QUIC: `app_with_ai_health` hands the
  test the `DbHealth` flag, so the socket can be taken down under a running
  app and put back — the second read answering 200 is what proves the refusal
  was the flag's doing.
- `not_json` and both `too_large` paths at module level: no allowlisted route
  answers non-JSON or 8 MiB today, so a QUIC-level test would need a seam in
  the release binary to invent one. Two pure extractions instead —
  `dispatch_api` (everything after the arm check, so a stub router can be
  dispatched into without a listener) and `write_answer` (the framing, so the
  oversize-Ok downgrade can be read back off a buffer). No release behaviour
  moves: the refusal order is unchanged and the downgrade is the same code.

The downgrade test also pins that nothing of the oversize frame reaches the
wire before the refusal — `write_frame` size-checks before its first byte.
src/ai/server.rsmodified+154 -18
@@ -370,15 +370,7 @@ async fn read_api(
370 inner: &Inner,370 inner: &Inner,
371 request: ApiRequest,371 request: ApiRequest,
372 ) -> Result<ApiResponse, (&'static str, String)> {372 ) -> Result<ApiResponse, (&'static str, String)> {
373- let ApiRequest {373+ if let Some(refusal) = refuse_before_dispatch(request.method.as_deref(), &request.path) {
374- id,
375- path,
376- query,
377- on_behalf_of,
378- method,
379- } = request;
380-
381- if let Some(refusal) = refuse_before_dispatch(method.as_deref(), &path) {
382 return Err(refusal);374 return Err(refusal);
383 }375 }
384 376
@@ -388,6 +380,25 @@ async fn read_api(
388 "unavailable",380 "unavailable",
389 "the api is not serving yet — retry".to_string(),381 "the api is not serving yet — retry".to_string(),
390 ))?;382 ))?;
383+ dispatch_api(api, request).await
384+}
385+
386+/// The half of [`read_api`] that needs only the armed handle: liveness,
387+/// principal, dispatch, and framing the router's answer. Split out from the
388+/// listener so the refusal codes it owns can be exercised without a QUIC
389+/// endpoint (see this module's tests).
390+async fn dispatch_api(
391+ api: &ApiHandle,
392+ request: ApiRequest,
393+) -> Result<ApiResponse, (&'static str, String)> {
394+ let ApiRequest {
395+ id,
396+ path,
397+ query,
398+ on_behalf_of,
399+ ..
400+ } = request;
401+
391 // The outer db guard is one of the layers this path deliberately skips, so402 // The outer db guard is one of the layers this path deliberately skips, so
392 // the same liveness check happens here instead: a query issued against a403 // the same liveness check happens here instead: a query issued against a
393 // dead socket hangs rather than failing (see [`DbHealth`]).404 // dead socket hangs rather than failing (see [`DbHealth`]).
@@ -483,10 +494,24 @@ fn refusal(id: String, code: &str, message: String) -> ApiResponse {
483 /// dropped: a service that got no frame at all would wait out its own deadline494 /// dropped: a service that got no frame at all would wait out its own deadline
484 /// to learn nothing.495 /// to learn nothing.
485 async fn answer(send: &mut quinn::SendStream, response: ApiResponse) {496 async fn answer(send: &mut quinn::SendStream, response: ApiResponse) {
486- let mut written = write_frame(send, &response).await;497+ if let Err(e) = write_answer(send, &response).await {
487- if let (Err(FrameError::TooLarge(_)), ApiResponse::Ok { id, .. }) = (&written, &response) {498+ tracing::warn!("could not answer an AI service's api read: {e}");
488- written = write_frame(499+ }
489- send,500+ let _ = send.finish();
501+}
502+
503+/// Frame one answer, downgrading an oversize `Ok` as above. [`write_frame`]
504+/// checks the size *before* it writes a byte, so the refusal never follows a
505+/// half-written frame. Generic over the writer so the downgrade can be asserted
506+/// against a buffer.
507+async fn write_answer<W: tokio::io::AsyncWrite + Unpin>(
508+ w: &mut W,
509+ response: &ApiResponse,
510+) -> Result<(), FrameError> {
511+ let written = write_frame(w, response).await;
512+ if let (Err(FrameError::TooLarge(_)), ApiResponse::Ok { id, .. }) = (&written, response) {
513+ return write_frame(
514+ w,
490 &refusal(515 &refusal(
491 id.clone(),516 id.clone(),
492 "too_large",517 "too_large",
@@ -495,10 +520,7 @@ async fn answer(send: &mut quinn::SendStream, response: ApiResponse) {
495 )520 )
496 .await;521 .await;
497 }522 }
498- if let Err(e) = written {523+ written
499- tracing::warn!("could not answer an AI service's api read: {e}");
500- }
501- let _ = send.finish();
502 }524 }
503 525
504 /// Read the `Hello`, decide, answer, and register on success.526 /// Read the `Hello`, decide, answer, and register on success.
@@ -626,7 +648,121 @@ fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
626 648
627 #[cfg(test)]649 #[cfg(test)]
628 mod tests {650 mod tests {
629- use super::{constant_time_eq, refuse_before_dispatch};651+ use axum::routing::get;
652+
653+ use super::{
654+ AI_MAX_FRAME_BYTES, ApiHandle, ApiRequest, ApiResponse, constant_time_eq,
655+ refuse_before_dispatch,
656+ };
657+ use crate::ai::protocol::read_frame;
658+
659+ /// An armed handle serving `router`. The database is never touched by these
660+ /// reads (nobody is named, so the principal is synthetic), but the handle
661+ /// carries one exactly as the live path does.
662+ async fn armed(router: axum::Router) -> ApiHandle {
663+ ApiHandle {
664+ router,
665+ db: crate::database::init_mem().await.expect("in-memory db"),
666+ db_up: Default::default(),
667+ }
668+ }
669+
670+ /// A read of `/notes` as the service itself.
671+ fn read_of(path: &str) -> ApiRequest {
672+ ApiRequest {
673+ id: "trace-1".to_string(),
674+ path: path.to_string(),
675+ query: None,
676+ on_behalf_of: None,
677+ method: None,
678+ }
679+ }
680+
681+ /// The refusal code, or a panic naming the answer that was not one.
682+ fn refused(answer: Result<ApiResponse, (&'static str, String)>) -> &'static str {
683+ match answer {
684+ Err((code, _)) => code,
685+ Ok(other) => panic!("expected a refusal, got {other:?}"),
686+ }
687+ }
688+
689+ #[tokio::test]
690+ async fn a_body_that_is_not_json_is_refused_as_not_json() {
691+ // No allowlisted route answers text today, so this stands in for the
692+ // day one does: the service is told the body was unreadable rather
693+ // than handed a frame whose `body` field silently became a string.
694+ let router = axum::Router::new().route("/notes", get(|| async { "plain text" }));
695+ let api = armed(router).await;
696+ assert_eq!(
697+ refused(super::dispatch_api(&api, read_of("/notes")).await),
698+ "not_json"
699+ );
700+ }
701+
702+ #[tokio::test]
703+ async fn an_empty_body_is_a_null_answer_not_a_parse_failure() {
704+ // The other side of the same branch: a `204` has nothing to parse and
705+ // must not read as `not_json`.
706+ let router = axum::Router::new().route(
707+ "/notes",
708+ get(|| async { axum::http::StatusCode::NO_CONTENT }),
709+ );
710+ let api = armed(router).await;
711+ match super::dispatch_api(&api, read_of("/notes")).await {
712+ Ok(ApiResponse::Ok { status, body, .. }) => {
713+ assert_eq!(status, 204);
714+ assert_eq!(body, serde_json::Value::Null);
715+ }
716+ other => panic!("an empty body is an Ok answer: {other:?}"),
717+ }
718+ }
719+
720+ #[tokio::test]
721+ async fn a_router_answer_over_the_frame_cap_is_refused_as_too_large() {
722+ // The read-side cap: the body is drained with a limit, so an answer
723+ // that cannot fit a frame is refused instead of being buffered whole.
724+ let router = axum::Router::new().route(
725+ "/notes",
726+ get(|| async { "x".repeat(AI_MAX_FRAME_BYTES + 1) }),
727+ );
728+ let api = armed(router).await;
729+ assert_eq!(
730+ refused(super::dispatch_api(&api, read_of("/notes")).await),
731+ "too_large"
732+ );
733+ }
734+
735+ #[tokio::test]
736+ async fn an_oversize_ok_is_downgraded_to_a_too_large_refusal() {
737+ // The write-side cap: a body that passed the read limit can still
738+ // overflow once it is wrapped in its frame. The service must get a
739+ // refusal it can log, never silence it waits out — and, because the
740+ // size is checked before any byte is written, nothing of the oversize
741+ // frame may precede it on the stream.
742+ let big = ApiResponse::Ok {
743+ id: "trace-1".to_string(),
744+ status: 200,
745+ body: serde_json::Value::String("x".repeat(AI_MAX_FRAME_BYTES)),
746+ };
747+ let mut wire = Vec::new();
748+ super::write_answer(&mut wire, &big)
749+ .await
750+ .expect("the downgrade is written");
751+
752+ let mut rest = &wire[..];
753+ match read_frame::<_, ApiResponse>(&mut rest).await {
754+ Ok(ApiResponse::Err { id, code, .. }) => {
755+ assert_eq!(code, "too_large");
756+ assert_eq!(id, "trace-1", "the trace id survives the downgrade");
757+ }
758+ other => panic!("expected a too_large refusal on the wire: {other:?}"),
759+ }
760+ assert!(
761+ rest.is_empty(),
762+ "{} bytes of the oversize frame were written before the refusal",
763+ rest.len()
764+ );
765+ }
630 766
631 #[test]767 #[test]
632 fn only_a_get_on_an_allowlisted_path_is_ever_dispatched() {768 fn only_a_get_on_an_allowlisted_path_is_ever_dispatched() {
tests/ai_bridge.rsmodified+33 -0
@@ -1506,6 +1506,39 @@ async fn a_router_status_rides_back_as_an_ok_answer_not_a_refusal() {
1506 assert_eq!(status, 404);1506 assert_eq!(status, 404);
1507 }1507 }
1508 1508
1509+#[tokio::test]
1510+async fn a_down_database_socket_is_refused_as_unavailable_rather_than_parked() {
1511+ // This path skips the HTTP layers, the db guard among them, so it re-checks
1512+ // liveness itself: a query issued while the socket is down does not fail,
1513+ // it parks until the socket returns. A service has to be told to retry
1514+ // instead of waiting out its own deadline on a read nobody is running.
1515+ let bridge = bridge().await;
1516+ let service = connect_service(
1517+ &bridge,
1518+ hello("tutor", &[AI_CHAT_CAPABILITY]),
1519+ Behaviour::Echo,
1520+ )
1521+ .await;
1522+ await_workers(&bridge, 1).await;
1523+ let health = hezarfen_backend::state::DbHealth::default();
1524+ let (_app, _db) = common::app_with_ai_health(Some(bridge.clone()), health.clone()).await;
1525+
1526+ health.set(false);
1527+ match api_read(&service.conn, read_of("/notes", None)).await {
1528+ ApiResponse::Err { code, id, .. } => {
1529+ assert_eq!(code, "unavailable");
1530+ assert_eq!(id, "trace-/notes", "the trace id comes back");
1531+ }
1532+ other => panic!("a read against a down database must be refused: {other:?}"),
1533+ }
1534+
1535+ // And that refusal is the flag's doing, not a broken bridge: the same read
1536+ // on the same stream-opening service answers once the socket is back.
1537+ health.set(true);
1538+ let (status, _) = ok_answer(api_read(&service.conn, read_of("/notes", None)).await);
1539+ assert_eq!(status, 200);
1540+}
1541+
1509 #[tokio::test]1542 #[tokio::test]
1510 async fn a_dead_user_id_is_refused_rather_than_run_as_somebody() {1543 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 who1544 // The principal is loaded live, so a service holding an id of a user who
tests/common/mod.rsmodified+9 -2
@@ -11,7 +11,7 @@ use axum::http::{HeaderMap, Request, StatusCode};
11 use hezarfen_backend::ai::AiBridge;11 use hezarfen_backend::ai::AiBridge;
12 use hezarfen_backend::database::Database;12 use hezarfen_backend::database::Database;
13 use hezarfen_backend::rate_limit::RateLimitConfig;13 use hezarfen_backend::rate_limit::RateLimitConfig;
14-use hezarfen_backend::state::AppState;14+use hezarfen_backend::state::{AppState, DbHealth};
15 use hezarfen_backend::{build_router, database};15 use hezarfen_backend::{build_router, database};
16 use serde_json::{Value, json};16 use serde_json::{Value, json};
17 use tempfile::TempDir;17 use tempfile::TempDir;
@@ -47,6 +47,13 @@ pub async fn app_and_db() -> (Router, Database) {
47 /// arms the bridge's api-read handle whenever `ai` is `Some`, so this is the47 /// 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.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) {49 pub async fn app_with_ai(ai: Option<AiBridge>) -> (Router, Database) {
50+ app_with_ai_health(ai, Default::default()).await
51+}
52+
53+/// [`app_with_ai`] with the liveness flag handed in, so a test can take the
54+/// database socket down under a running app — the api-read path re-checks it in
55+/// place of the HTTP db guard it bypasses.
56+pub async fn app_with_ai_health(ai: Option<AiBridge>, db_up: DbHealth) -> (Router, Database) {
50 let db = database::init_mem().await.expect("in-memory db");57 let db = database::init_mem().await.expect("in-memory db");
51 let app = build_router(AppState {58 let app = build_router(AppState {
52 db: db.clone(),59 db: db.clone(),
@@ -58,7 +65,7 @@ pub async fn app_with_ai(ai: Option<AiBridge>) -> (Router, Database) {
58 chatbot_limit: Default::default(),65 chatbot_limit: Default::default(),
59 exam_presence: Default::default(),66 exam_presence: Default::default(),
60 board_hub: Default::default(),67 board_hub: Default::default(),
61- db_up: Default::default(),68+ db_up,
62 ai,69 ai,
63 });70 });
64 (app, db)71 (app, db)