forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

ai.rs212 lines, 8.4 KiBHistoryRawDownload
1//! Public discovery for the AI bridge.
2//!
3//! Two reads: the bridge's certificate, which a service needs before it can
4//! dial in, and the capabilities currently on offer, which a client needs
5//! before it offers an AI feature it cannot get an answer from.
6//!
7//! An AI service needs the bridge's certificate before it can dial in, and the
8//! certificate is regenerated on every boot when no PEM pair is configured. So
9//! it is published here: the service fetches this over HTTP, pins what it gets,
10//! and then connects over QUIC.
11//!
12//! Unauthenticated on purpose. A server certificate is public by construction —
13//! it is handed to every peer during the TLS handshake — so serving it reveals
14//! nothing a port scan would not. The private key never leaves the process.
15//!
16//! What this is *not*: a substitute for a CA. Fetch-then-pin over plain HTTP is
17//! trust-on-first-use, only as trustworthy as that HTTP hop. On a hostile
18//! network, put a real certificate in `AI_TLS_CERT`/`AI_TLS_KEY` and distribute
19//! it out of band.
20
21use std::collections::BTreeMap;
22
23use axum::Json;
24use axum::extract::State;
25use base64::Engine;
26use serde::Serialize;
27use utoipa::ToSchema;
28use utoipa_axum::router::OpenApiRouter;
29use utoipa_axum::routes;
30
31use crate::ai::tls;
32use crate::constant::AI_PROTOCOL;
33use crate::error::{AppError, ErrorResponse};
34use crate::state::AppState;
35use crate::web::CurrentUser;
36
37pub fn routes() -> OpenApiRouter<AppState> {
38 // One `routes!` per path: the multi-handler form groups methods under a
39 // single path, so two `get` handlers never share one.
40 OpenApiRouter::new()
41 .routes(routes!(bridge_certificate))
42 .routes(routes!(capabilities))
43}
44
45/// Everything a service needs to reach the bridge, except the shared token
46/// (which is a secret and is configured out of band).
47#[derive(Serialize, ToSchema)]
48pub struct BridgeCertificateResponse {
49 /// Wire protocol and ALPN the service must announce, currently `hab/2`.
50 #[schema(example = "hab/2")]
51 protocol: String,
52 /// The listener's leaf certificate, PEM-encoded — feed straight into a TLS
53 /// client's trust store (Python: `ssl_context.load_verify_locations(cadata=...)`).
54 certificate_pem: String,
55 /// SHA-256 of the DER certificate, hex. Same value the backend logs at
56 /// startup; compare it if the PEM is pinned from somewhere else.
57 #[schema(example = "6745e87f8a995e57b58297ac8058cd634d59557f3061144fa61127c96136e7fe")]
58 fingerprint_sha256: String,
59}
60
61/// The AI bridge's certificate (PEM + SHA-256 fingerprint) for a service to
62/// pin; `404` when the bridge is off.
63///
64/// Public: a server certificate is presented to every peer in the TLS
65/// handshake, so publishing it discloses nothing.
66///
67/// **Re-fetch on every reconnect.** With no `AI_TLS_CERT`/`AI_TLS_KEY`
68/// configured the bridge generates a fresh self-signed certificate at each
69/// boot, so a certificate pinned once at service startup goes stale the moment
70/// the *backend* restarts. A service whose reconnect loop only redials will
71/// then fail forever; one that re-fetches this first recovers on its own.
72#[utoipa::path(
73 get,
74 path = "/certificate",
75 tag = "ai",
76 responses(
77 (status = 200, description = "The bridge's certificate and its fingerprint", body = BridgeCertificateResponse),
78 (status = 404, description = "The AI bridge is not enabled on this deployment", body = ErrorResponse),
79 ),
80)]
81async fn bridge_certificate(
82 State(state): State<AppState>,
83) -> Result<Json<BridgeCertificateResponse>, AppError> {
84 // 404 rather than a null body: with AI_QUIC_ADDR unset there is no bridge
85 // to describe, and a service should fail loudly on a deployment that never
86 // intended to run it.
87 let bridge = state.ai.as_ref().ok_or(AppError::NotFound)?;
88 let der = bridge.certificate();
89 Ok(Json(BridgeCertificateResponse {
90 protocol: AI_PROTOCOL.to_string(),
91 certificate_pem: to_pem(der.as_ref()),
92 fingerprint_sha256: tls::fingerprint(&der),
93 }))
94}
95
96/// What the bridge can currently do, grouped by capability.
97#[derive(Serialize, ToSchema)]
98pub struct CapabilitiesResponse {
99 /// Whether a bridge is listening at all (`AI_QUIC_ADDR` set). `false` here
100 /// is a discovery answer, not an error: the deployment simply runs no AI.
101 enabled: bool,
102 /// The wire protocol the bridge speaks, currently `hab/2`.
103 #[schema(example = "hab/2")]
104 protocol: String,
105 /// One entry per capability any connected worker serves, sorted by name.
106 capabilities: Vec<CapabilityWorkers>,
107}
108
109/// One capability's live fleet: how many workers serve it, and the work in
110/// flight across them.
111#[derive(Serialize, ToSchema)]
112pub struct CapabilityWorkers {
113 /// The capability string a service declared, e.g. `chat.reply` or
114 /// `rag.chat`.
115 #[schema(example = "chat.reply")]
116 capability: String,
117 /// How many connected workers have declared this capability.
118 workers: usize,
119 /// Requests currently being answered across those workers.
120 inflight: u64,
121}
122
123/// The capabilities connected AI services are serving right now, per
124/// capability, with the work in flight — a discovery read for an operator or a
125/// service deciding what it may ask this bridge to do.
126///
127/// **`200`, even with the bridge off.** This lists what is available rather
128/// than probing a dependency, so a disabled bridge answers `enabled: false`
129/// and an empty list, not a `503` — a caller learns *that* there is no AI
130/// fleet rather than that the request itself failed.
131#[utoipa::path(
132 get,
133 path = "/capabilities",
134 tag = "ai",
135 security(("session_cookie" = [])),
136 responses(
137 (status = 200, description = "Every capability a connected worker serves, grouped and sorted", body = CapabilitiesResponse),
138 (status = 401, description = "No authenticated session", body = ErrorResponse),
139 ),
140)]
141async fn capabilities(
142 State(state): State<AppState>,
143 _user: CurrentUser,
144) -> Json<CapabilitiesResponse> {
145 let (enabled, workers) = match &state.ai {
146 Some(bridge) => (true, bridge.workers()),
147 None => (false, Vec::new()),
148 };
149 // A worker serving N capabilities counts once toward each of them, so the
150 // group totals are per-capability fleets, not a partition of the workers.
151 let mut by_capability: BTreeMap<String, (usize, u64)> = BTreeMap::new();
152 for worker in workers {
153 for capability in &worker.capabilities {
154 let entry = by_capability.entry(capability.clone()).or_insert((0, 0));
155 entry.0 += 1;
156 entry.1 += worker.inflight as u64;
157 }
158 }
159 Json(CapabilitiesResponse {
160 enabled,
161 protocol: AI_PROTOCOL.to_string(),
162 capabilities: by_capability
163 .into_iter()
164 .map(|(capability, (workers, inflight))| CapabilityWorkers {
165 capability,
166 workers,
167 inflight,
168 })
169 .collect(),
170 })
171}
172
173/// Wrap DER bytes as a PEM certificate: base64 in 64-character lines between
174/// the standard armour, which is what every TLS library's loader expects.
175fn to_pem(der: &[u8]) -> String {
176 let body = base64::engine::general_purpose::STANDARD.encode(der);
177 let mut pem = String::from("-----BEGIN CERTIFICATE-----\n");
178 for line in body.as_bytes().chunks(64) {
179 pem.push_str(std::str::from_utf8(line).expect("base64 is ASCII"));
180 pem.push('\n');
181 }
182 pem.push_str("-----END CERTIFICATE-----\n");
183 pem
184}
185
186#[cfg(test)]
187mod tests {
188 use super::to_pem;
189
190 #[tokio::test]
191 async fn pem_armour_wraps_at_64_columns_and_round_trips() {
192 // 200 bytes -> 268 base64 chars -> 5 lines (64,64,64,64,12).
193 let der: Vec<u8> = (0..200u32).map(|i| (i % 256) as u8).collect();
194 let pem = to_pem(&der);
195 assert!(pem.starts_with("-----BEGIN CERTIFICATE-----\n"));
196 assert!(pem.ends_with("-----END CERTIFICATE-----\n"));
197
198 let body: Vec<&str> = pem.lines().filter(|l| !l.starts_with("-----")).collect();
199 assert!(
200 body.iter().all(|l| l.len() <= 64),
201 "no line may exceed 64 columns: {body:?}"
202 );
203 assert_eq!(body.len(), 5);
204
205 // The real check: a PEM parser gets the original DER back.
206 let parsed = rustls_pemfile::certs(&mut pem.as_bytes())
207 .collect::<Result<Vec<_>, _>>()
208 .expect("valid PEM");
209 assert_eq!(parsed.len(), 1);
210 assert_eq!(parsed[0].as_ref(), der.as_slice());
211 }
212}