From 266e175d7b87735cf969b618c7154340052a604f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 23 Jul 2026 07:18:06 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=85=20test(ai):=20cover=20the=20bridge's?= =?UTF-8?q?=20boot=20wiring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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.rs | 41 +++++++++++++++++++++-- src/main.rs | 35 +------------------- tests/ai_bridge.rs | 81 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 121 insertions(+), 36 deletions(-) diff --git a/src/ai/mod.rs b/src/ai/mod.rs index 6b6540f..7e74374 100644 --- a/src/ai/mod.rs +++ b/src/ai/mod.rs @@ -17,8 +17,8 @@ //! * [`registry`] — who is connected and who gets the next request //! * [`tls`] — the listener's certificate //! -//! Nothing here is wired into a route yet: this is the transport, and the -//! individual AI features land on top of it. +//! The transport is generic; the features land on top of it. So far that is +//! the chatbot (`web::chat`), which routes on the `chat.reply` capability. pub mod chat; pub mod error; @@ -31,3 +31,40 @@ pub use chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn}; pub use error::AiError; pub use registry::{AiRegistry, WorkerSnapshot}; pub use server::{AiBridge, BridgeConfig}; + +use crate::config::Config; + +/// Start the QUIC bridge the AI services dial into, if one is configured. +/// +/// Unconfigured is a supported deployment, not a degraded one: the school API +/// predates the AI features and must keep running without them, so an absent +/// `AI_QUIC_ADDR` returns `None` and nothing else changes. A *misconfigured* +/// bridge is the opposite — a bad address, an unreadable certificate or a +/// missing token means the operator asked for AI and would otherwise get a +/// silently dead feature, so that fails the boot. +/// +/// In particular a set address with no `AI_SHARED_TOKEN` must never fall back +/// to listening: an unauthenticated bridge would let anyone who can reach the +/// UDP port register a worker and answer real users' messages. +pub async fn start_bridge(cfg: &Config) -> Result, AiError> { + let Some(raw_addr) = cfg.ai_quic_addr.as_deref() else { + tracing::info!("AI bridge disabled (AI_QUIC_ADDR unset)"); + return Ok(None); + }; + let addr = raw_addr + .parse() + .map_err(|e| AiError::Setup(format!("AI_QUIC_ADDR `{raw_addr}` is not an address: {e}")))?; + let token = cfg + .ai_shared_token + .clone() + .ok_or_else(|| AiError::Setup("AI_SHARED_TOKEN must be set when AI_QUIC_ADDR is".into()))?; + let bridge = AiBridge::bind(BridgeConfig { + addr, + token, + cert_path: cfg.ai_tls_cert.clone(), + key_path: cfg.ai_tls_key.clone(), + request_timeout: std::time::Duration::from_secs(cfg.ai_request_timeout_secs), + }) + .await?; + Ok(Some(bridge)) +} diff --git a/src/main.rs b/src/main.rs index 22c63e3..2d76d6c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,4 @@ use anyhow::Context; -use hezarfen_backend::ai::{AiBridge, BridgeConfig}; use hezarfen_backend::config::Config; use hezarfen_backend::database::Database; use hezarfen_backend::domain::user::{Password, User, Username}; @@ -25,7 +24,7 @@ async fn main() -> anyhow::Result<()> { tokio::fs::create_dir_all(&cfg.files_path) .await .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?; - let ai = start_ai_bridge(&cfg).await?; + let ai = hezarfen_backend::ai::start_bridge(&cfg).await?; let app = build_router(AppState { db, files_path: cfg.files_path.clone().into(), @@ -52,38 +51,6 @@ async fn main() -> anyhow::Result<()> { Ok(()) } -/// Start the QUIC bridge the AI services dial into, if one is configured. -/// -/// Unconfigured is a supported deployment, not a degraded one: the school API -/// predates the AI features and must keep running without them, so an absent -/// `AI_QUIC_ADDR` returns `None` and nothing else changes. A *misconfigured* -/// bridge is the opposite — a bad address, an unreadable certificate or a -/// missing token means the operator asked for AI and would otherwise get a -/// silently dead feature, so that fails the boot. -async fn start_ai_bridge(cfg: &Config) -> anyhow::Result> { - let Some(raw_addr) = cfg.ai_quic_addr.as_deref() else { - tracing::info!("AI bridge disabled (AI_QUIC_ADDR unset)"); - return Ok(None); - }; - let addr = raw_addr - .parse() - .with_context(|| format!("AI_QUIC_ADDR `{raw_addr}` is not a socket address"))?; - let token = cfg - .ai_shared_token - .clone() - .context("AI_SHARED_TOKEN must be set when AI_QUIC_ADDR is")?; - let bridge = AiBridge::bind(BridgeConfig { - addr, - token, - cert_path: cfg.ai_tls_cert.clone(), - key_path: cfg.ai_tls_key.clone(), - request_timeout: std::time::Duration::from_secs(cfg.ai_request_timeout_secs), - }) - .await - .context("failed to start the AI bridge")?; - Ok(Some(bridge)) -} - /// Ping the database forever so the WebSocket never sits idle long enough to /// be dropped, and publish each verdict to `health` so the request guard can /// refuse callers while the socket is down. diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 5e859c4..277b2ff 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -1161,3 +1161,84 @@ async fn a_blank_chat_answer_fails_as_empty_reply() { assert_eq!(turn["status"], "failed", "{turn}"); assert_eq!(turn["error_code"], "empty_reply"); } + +// ------------------------------------------------------------- boot wiring -- +// +// `ai::start_bridge` is the seam between deployment config and the listener. +// Its branches are the ones an operator hits, and the failure branch is the +// one that matters most: a set address with no token must refuse to boot +// rather than listen unauthenticated, since anyone able to reach the UDP port +// could otherwise register a worker and answer real users' messages. + +/// A config with the AI fields under the test's control. Everything else comes +/// from the usual defaults — these tests never touch the database. +fn ai_config(addr: Option<&str>, token: Option<&str>) -> hezarfen_backend::config::Config { + let mut cfg = hezarfen_backend::config::Config::from_env(); + cfg.ai_quic_addr = addr.map(str::to_string); + cfg.ai_shared_token = token.map(str::to_string); + cfg.ai_tls_cert = None; + cfg.ai_tls_key = None; + cfg +} + +#[tokio::test] +async fn no_address_means_no_bridge_not_a_failed_boot() { + // The school API predates the AI features and must still boot without + // them, so "unconfigured" is a supported deployment, not a degraded one. + let bridge = hezarfen_backend::ai::start_bridge(&ai_config(None, None)) + .await + .unwrap_or_else(|e| panic!("an unconfigured bridge is not an error: {e}")); + assert!(bridge.is_none(), "nothing should be listening"); +} + +#[tokio::test] +async fn an_address_without_a_token_refuses_to_boot() { + // The security branch: never fall back to an unauthenticated listener. + // + // Two layers refuse this — `start_bridge` on the absent env var, and + // `AiBridge::bind` on an empty token — so the assertion pins the message + // to *this* layer's wording (`AI_QUIC_ADDR`). Asserting only on + // "AI_SHARED_TOKEN" would match either, and would still pass with this + // branch deleted. + let Err(err) = hezarfen_backend::ai::start_bridge(&ai_config(Some("127.0.0.1:0"), None)).await + else { + panic!("a tokenless bridge must not start"); + }; + assert!( + matches!(&err, AiError::Setup(m) if m.contains("AI_SHARED_TOKEN") && m.contains("AI_QUIC_ADDR")), + "got {err:?}" + ); +} + +#[tokio::test] +async fn a_bad_address_fails_the_boot_rather_than_going_quiet() { + // The operator asked for AI; a typo must not degrade to a silently dead + // feature they only notice when a student sends the first message. + let Err(err) = + hezarfen_backend::ai::start_bridge(&ai_config(Some("not-an-address"), Some(TOKEN))).await + else { + panic!("a malformed address must not be ignored"); + }; + assert!( + matches!(&err, AiError::Setup(m) if m.contains("AI_QUIC_ADDR")), + "got {err:?}" + ); +} + +#[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 + // listener, not just a constructed value — so dial it for real. + let bridge = hezarfen_backend::ai::start_bridge(&ai_config(Some("127.0.0.1:0"), Some(TOKEN))) + .await + .unwrap_or_else(|e| panic!("a fully configured bridge starts: {e}")) + .expect("a configured bridge is Some"); + let _service = connect_service( + &bridge, + hello("tutor", &[AI_CHAT_CAPABILITY]), + Behaviour::Echo, + ) + .await; + await_workers(&bridge, 1).await; + assert_eq!(bridge.workers().len(), 1); +}