forge
Explore
Log in

Don't you dare go Hollow

Cover the bridge's boot wiring

Browse files at this commit

266e175d7b87735cf969b618c7154340052a604fAhmet Kaan GümüşParent: 87c8096
  • test
    • cover the bridge's boot wiring
Show full message
✅ test(ai): cover the bridge's boot wiring

`start_ai_bridge` sat in main.rs, so the branches an operator actually
hits had no test: unset address boots fine, bad address fails the boot,
and a set address with no token refuses rather than listening
unauthenticated. Moved to `ai::start_bridge` and tested there, including
a real dial-in against what it returns — a constructed value proves
nothing, a completed handshake does.

The token assertion pins this layer's wording. `AiBridge::bind` rejects
an empty token too, so matching only on "AI_SHARED_TOKEN" passed with
the branch deleted; the test now names AI_QUIC_ADDR and fails without it.

Returns AiError rather than anyhow::Error, keeping anyhow to the binary.
src/ai/mod.rsmodified+39 -2
@@ -17,8 +17,8 @@
17 //! * [`registry`] — who is connected and who gets the next request17 //! * [`registry`] — who is connected and who gets the next request
18 //! * [`tls`] — the listener's certificate18 //! * [`tls`] — the listener's certificate
19 //!19 //!
20-//! Nothing here is wired into a route yet: this is the transport, and the20+//! The transport is generic; the features land on top of it. So far that is
21-//! individual AI features land on top of it.21+//! the chatbot (`web::chat`), which routes on the `chat.reply` capability.
22 22
23 pub mod chat;23 pub mod chat;
24 pub mod error;24 pub mod error;
@@ -31,3 +31,40 @@ pub use chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};
31 pub use error::AiError;31 pub use error::AiError;
32 pub use registry::{AiRegistry, WorkerSnapshot};32 pub use registry::{AiRegistry, WorkerSnapshot};
33 pub use server::{AiBridge, BridgeConfig};33 pub use server::{AiBridge, BridgeConfig};
34+
35+use crate::config::Config;
36+
37+/// Start the QUIC bridge the AI services dial into, if one is configured.
38+///
39+/// Unconfigured is a supported deployment, not a degraded one: the school API
40+/// predates the AI features and must keep running without them, so an absent
41+/// `AI_QUIC_ADDR` returns `None` and nothing else changes. A *misconfigured*
42+/// bridge is the opposite — a bad address, an unreadable certificate or a
43+/// missing token means the operator asked for AI and would otherwise get a
44+/// silently dead feature, so that fails the boot.
45+///
46+/// In particular a set address with no `AI_SHARED_TOKEN` must never fall back
47+/// to listening: an unauthenticated bridge would let anyone who can reach the
48+/// UDP port register a worker and answer real users' messages.
49+pub async fn start_bridge(cfg: &Config) -> Result<Option<AiBridge>, AiError> {
50+ let Some(raw_addr) = cfg.ai_quic_addr.as_deref() else {
51+ tracing::info!("AI bridge disabled (AI_QUIC_ADDR unset)");
52+ return Ok(None);
53+ };
54+ let addr = raw_addr
55+ .parse()
56+ .map_err(|e| AiError::Setup(format!("AI_QUIC_ADDR `{raw_addr}` is not an address: {e}")))?;
57+ let token = cfg
58+ .ai_shared_token
59+ .clone()
60+ .ok_or_else(|| AiError::Setup("AI_SHARED_TOKEN must be set when AI_QUIC_ADDR is".into()))?;
61+ let bridge = AiBridge::bind(BridgeConfig {
62+ addr,
63+ token,
64+ cert_path: cfg.ai_tls_cert.clone(),
65+ key_path: cfg.ai_tls_key.clone(),
66+ request_timeout: std::time::Duration::from_secs(cfg.ai_request_timeout_secs),
67+ })
68+ .await?;
69+ Ok(Some(bridge))
70+}
src/main.rsmodified+1 -34
@@ -1,5 +1,4 @@
1 use anyhow::Context;1 use anyhow::Context;
2-use hezarfen_backend::ai::{AiBridge, BridgeConfig};
3 use hezarfen_backend::config::Config;2 use hezarfen_backend::config::Config;
4 use hezarfen_backend::database::Database;3 use hezarfen_backend::database::Database;
5 use hezarfen_backend::domain::user::{Password, User, Username};4 use hezarfen_backend::domain::user::{Password, User, Username};
@@ -25,7 +24,7 @@ async fn main() -> anyhow::Result<()> {
25 tokio::fs::create_dir_all(&cfg.files_path)24 tokio::fs::create_dir_all(&cfg.files_path)
26 .await25 .await
27 .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?;26 .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?;
28- let ai = start_ai_bridge(&cfg).await?;27+ let ai = hezarfen_backend::ai::start_bridge(&cfg).await?;
29 let app = build_router(AppState {28 let app = build_router(AppState {
30 db,29 db,
31 files_path: cfg.files_path.clone().into(),30 files_path: cfg.files_path.clone().into(),
@@ -52,38 +51,6 @@ async fn main() -> anyhow::Result<()> {
52 Ok(())51 Ok(())
53 }52 }
54 53
55-/// Start the QUIC bridge the AI services dial into, if one is configured.
56-///
57-/// Unconfigured is a supported deployment, not a degraded one: the school API
58-/// predates the AI features and must keep running without them, so an absent
59-/// `AI_QUIC_ADDR` returns `None` and nothing else changes. A *misconfigured*
60-/// bridge is the opposite — a bad address, an unreadable certificate or a
61-/// missing token means the operator asked for AI and would otherwise get a
62-/// silently dead feature, so that fails the boot.
63-async fn start_ai_bridge(cfg: &Config) -> anyhow::Result<Option<AiBridge>> {
64- let Some(raw_addr) = cfg.ai_quic_addr.as_deref() else {
65- tracing::info!("AI bridge disabled (AI_QUIC_ADDR unset)");
66- return Ok(None);
67- };
68- let addr = raw_addr
69- .parse()
70- .with_context(|| format!("AI_QUIC_ADDR `{raw_addr}` is not a socket address"))?;
71- let token = cfg
72- .ai_shared_token
73- .clone()
74- .context("AI_SHARED_TOKEN must be set when AI_QUIC_ADDR is")?;
75- let bridge = AiBridge::bind(BridgeConfig {
76- addr,
77- token,
78- cert_path: cfg.ai_tls_cert.clone(),
79- key_path: cfg.ai_tls_key.clone(),
80- request_timeout: std::time::Duration::from_secs(cfg.ai_request_timeout_secs),
81- })
82- .await
83- .context("failed to start the AI bridge")?;
84- Ok(Some(bridge))
85-}
86-
87 /// Ping the database forever so the WebSocket never sits idle long enough to54 /// Ping the database forever so the WebSocket never sits idle long enough to
88 /// be dropped, and publish each verdict to `health` so the request guard can55 /// be dropped, and publish each verdict to `health` so the request guard can
89 /// refuse callers while the socket is down.56 /// refuse callers while the socket is down.
tests/ai_bridge.rsmodified+81 -0
@@ -1161,3 +1161,84 @@ async fn a_blank_chat_answer_fails_as_empty_reply() {
1161 assert_eq!(turn["status"], "failed", "{turn}");1161 assert_eq!(turn["status"], "failed", "{turn}");
1162 assert_eq!(turn["error_code"], "empty_reply");1162 assert_eq!(turn["error_code"], "empty_reply");
1163 }1163 }
1164+
1165+// ------------------------------------------------------------- boot wiring --
1166+//
1167+// `ai::start_bridge` is the seam between deployment config and the listener.
1168+// Its branches are the ones an operator hits, and the failure branch is the
1169+// one that matters most: a set address with no token must refuse to boot
1170+// rather than listen unauthenticated, since anyone able to reach the UDP port
1171+// could otherwise register a worker and answer real users' messages.
1172+
1173+/// A config with the AI fields under the test's control. Everything else comes
1174+/// from the usual defaults — these tests never touch the database.
1175+fn ai_config(addr: Option<&str>, token: Option<&str>) -> hezarfen_backend::config::Config {
1176+ let mut cfg = hezarfen_backend::config::Config::from_env();
1177+ cfg.ai_quic_addr = addr.map(str::to_string);
1178+ cfg.ai_shared_token = token.map(str::to_string);
1179+ cfg.ai_tls_cert = None;
1180+ cfg.ai_tls_key = None;
1181+ cfg
1182+}
1183+
1184+#[tokio::test]
1185+async fn no_address_means_no_bridge_not_a_failed_boot() {
1186+ // The school API predates the AI features and must still boot without
1187+ // them, so "unconfigured" is a supported deployment, not a degraded one.
1188+ let bridge = hezarfen_backend::ai::start_bridge(&ai_config(None, None))
1189+ .await
1190+ .unwrap_or_else(|e| panic!("an unconfigured bridge is not an error: {e}"));
1191+ assert!(bridge.is_none(), "nothing should be listening");
1192+}
1193+
1194+#[tokio::test]
1195+async fn an_address_without_a_token_refuses_to_boot() {
1196+ // The security branch: never fall back to an unauthenticated listener.
1197+ //
1198+ // Two layers refuse this — `start_bridge` on the absent env var, and
1199+ // `AiBridge::bind` on an empty token — so the assertion pins the message
1200+ // to *this* layer's wording (`AI_QUIC_ADDR`). Asserting only on
1201+ // "AI_SHARED_TOKEN" would match either, and would still pass with this
1202+ // branch deleted.
1203+ let Err(err) = hezarfen_backend::ai::start_bridge(&ai_config(Some("127.0.0.1:0"), None)).await
1204+ else {
1205+ panic!("a tokenless bridge must not start");
1206+ };
1207+ assert!(
1208+ matches!(&err, AiError::Setup(m) if m.contains("AI_SHARED_TOKEN") && m.contains("AI_QUIC_ADDR")),
1209+ "got {err:?}"
1210+ );
1211+}
1212+
1213+#[tokio::test]
1214+async fn a_bad_address_fails_the_boot_rather_than_going_quiet() {
1215+ // The operator asked for AI; a typo must not degrade to a silently dead
1216+ // feature they only notice when a student sends the first message.
1217+ let Err(err) =
1218+ hezarfen_backend::ai::start_bridge(&ai_config(Some("not-an-address"), Some(TOKEN))).await
1219+ else {
1220+ panic!("a malformed address must not be ignored");
1221+ };
1222+ assert!(
1223+ matches!(&err, AiError::Setup(m) if m.contains("AI_QUIC_ADDR")),
1224+ "got {err:?}"
1225+ );
1226+}
1227+
1228+#[tokio::test]
1229+async fn a_configured_bridge_listens_and_serves_a_real_handshake() {
1230+ // The whole point of the wiring: what `start_bridge` returns is a live
1231+ // listener, not just a constructed value — so dial it for real.
1232+ let bridge = hezarfen_backend::ai::start_bridge(&ai_config(Some("127.0.0.1:0"), Some(TOKEN)))
1233+ .await
1234+ .unwrap_or_else(|e| panic!("a fully configured bridge starts: {e}"))
1235+ .expect("a configured bridge is Some");
1236+ let _service = connect_service(
1237+ &bridge,
1238+ hello("tutor", &[AI_CHAT_CAPABILITY]),
1239+ Behaviour::Echo,
1240+ )
1241+ .await;
1242+ await_workers(&bridge, 1).await;
1243+ assert_eq!(bridge.workers().len(), 1);
1244+}