1mod admin;
2mod forwarding;
3mod handlers;
4pub mod obs;
5mod state;
6#[cfg(feature = "tls")]
7pub mod tls;
8
9pub use forwarding::build_forward_clients;
10pub use state::{AppState, LiveSignerState, SignerContext};
11
12use axum::Router;
13
14pub async fn announce_bundle_scopes(gossip: &hoike_gossip::GossipNode, bytes: &[u8]) {
28 let bundle = match ahu::Bundle::from_bytes(bytes) {
29 Ok(b) => b,
30 Err(e) => {
31 tracing::warn!(error = %e, "gossip announce: failed to parse produced bundle");
32 return;
33 }
34 };
35 let producer_id = bundle.manifest.producer_id.clone();
36 let manifest_digest = ahu::manifest_digest(&bundle.manifest_bytes);
37 for scope in &bundle.manifest.ca_scopes {
38 if let Err(e) = gossip
39 .announce_generation(
40 producer_id.clone(),
41 scope.issuer_key_hash.clone(),
42 scope.epoch,
43 manifest_digest,
44 None,
45 )
46 .await
47 {
48 tracing::warn!(error = %e, epoch = scope.epoch, "gossip announce failed");
49 }
50 }
51}
52use axum::extract::State;
53use axum::http::{StatusCode, header};
54use axum::response::{IntoResponse, Response};
55use axum::routing::{get, post};
56
57pub fn install_metrics() -> bool {
60 obs::install()
61}
62
63pub fn build_metrics_router(state: AppState) -> Router {
68 Router::new()
69 .route("/metrics", get(metrics_handler))
70 .with_state(state)
71}
72
73async fn metrics_handler(State(state): State<AppState>) -> Response {
74 let now = std::time::SystemTime::now()
77 .duration_since(std::time::UNIX_EPOCH)
78 .unwrap_or_default()
79 .as_secs();
80 obs::update_bundle_gauges(&state.responder.bundle_scopes(), now);
81
82 if let Some(gossip) = state.gossip.as_ref() {
84 use hoike_gossip::node::MemberState;
85 let members = gossip.members().await;
86 let (mut alive, mut suspect, mut down) = (0u64, 0u64, 0u64);
87 for m in &members {
88 match m.state {
89 MemberState::Alive => alive += 1,
90 MemberState::Suspect => suspect += 1,
91 MemberState::Down => down += 1,
92 }
93 }
94 obs::record_gossip_members(alive, suspect, down);
95 }
96
97 match obs::render() {
98 Some(body) => (
99 StatusCode::OK,
100 [(header::CONTENT_TYPE, "text/plain; version=0.0.4")],
101 body,
102 )
103 .into_response(),
104 None => (
105 StatusCode::SERVICE_UNAVAILABLE,
106 "metrics not enabled (build with --features metrics)",
107 )
108 .into_response(),
109 }
110}
111
112pub fn build_router(state: AppState) -> Router {
122 let mut app = Router::new()
123 .route("/", post(handlers::handle_post))
124 .route("/", get(handlers::handle_get_root))
125 .route("/{*path}", get(handlers::handle_get))
126 .route("/{*path}", post(handlers::handle_post))
127 .with_state(state.clone());
128
129 if state.admin.config.server.admin_listen.is_none() {
132 let admin_router = admin::build_admin_router(state.clone());
133 app = app.nest("/api/admin", admin_router);
134 app = mount_webui(app, &state);
135 }
136
137 app
138}
139
140pub fn build_admin_router_standalone(state: AppState) -> Router {
144 let admin_router = admin::build_admin_router(state.clone());
147 let app = Router::new().nest("/api/admin", admin_router);
148 mount_webui(app, &state)
149}
150
151fn mount_webui(mut app: Router, state: &AppState) -> Router {
155 if let Some(webui_config) = &state.admin.config.server.webui {
156 if let Some(static_dir) = &webui_config.static_dir {
157 let serve = tower_http::services::ServeDir::new(static_dir).fallback(
158 tower_http::services::ServeFile::new(
159 std::path::Path::new(static_dir).join("index.html"),
160 ),
161 );
162 app = app.nest_service("/ui", serve);
163 }
164 }
165
166 #[cfg(feature = "embed-webui")]
167 {
168 if state
169 .admin
170 .config
171 .server
172 .webui
173 .as_ref()
174 .is_some_and(|w| w.static_dir.is_none())
175 {
176 app = embedded_ui::mount(app);
177 }
178 }
179
180 app
181}
182
183#[cfg(feature = "embed-webui")]
184mod embedded_ui {
185 use axum::Router;
186 use axum::extract::Path;
187 use axum::http::{StatusCode, header};
188 use axum::response::{IntoResponse, Redirect};
189 use axum::routing::get;
190 use include_dir::{Dir, include_dir};
191
192 static WEBUI_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../webui/dist");
193
194 pub fn mount<S>(app: Router<S>) -> Router<S>
204 where
205 S: Clone + Send + Sync + 'static,
206 {
207 app.route("/ui", get(|| async { Redirect::permanent("/ui/") }))
208 .route("/ui/", get(serve_index))
209 .route("/ui/{*path}", get(serve_file))
210 }
211
212 async fn serve_index() -> axum::response::Response {
213 serve_path("index.html")
214 }
215
216 async fn serve_file(Path(path): Path<String>) -> axum::response::Response {
217 serve_path(&path)
218 }
219
220 fn serve_path(path: &str) -> axum::response::Response {
221 match WEBUI_DIR.get_file(path) {
222 Some(file) => {
223 let mime = mime_from_path(path);
224 (
225 StatusCode::OK,
226 [(header::CONTENT_TYPE, mime)],
227 file.contents().to_vec(),
228 )
229 .into_response()
230 }
231 None => {
232 if let Some(index) = WEBUI_DIR.get_file("index.html") {
233 (
234 StatusCode::OK,
235 [(header::CONTENT_TYPE, "text/html; charset=utf-8")],
236 index.contents().to_vec(),
237 )
238 .into_response()
239 } else {
240 StatusCode::NOT_FOUND.into_response()
241 }
242 }
243 }
244 }
245
246 fn mime_from_path(path: &str) -> &'static str {
247 match path.rsplit('.').next() {
248 Some("html") => "text/html; charset=utf-8",
249 Some("js") => "application/javascript; charset=utf-8",
250 Some("css") => "text/css; charset=utf-8",
251 Some("json") => "application/json",
252 Some("svg") => "image/svg+xml",
253 Some("png") => "image/png",
254 Some("ico") => "image/x-icon",
255 Some("woff2") => "font/woff2",
256 Some("woff") => "font/woff",
257 _ => "application/octet-stream",
258 }
259 }
260}
261
262#[cfg(all(test, feature = "embed-webui"))]
263mod embedded_ui_tests {
264 use axum::Router;
265 use axum::body::Body;
266 use axum::http::{Request, StatusCode, header};
267 use axum::routing::get;
268 use tower::ServiceExt; fn test_router() -> Router {
276 async fn ocsp_catch_all() -> &'static [u8] {
277 &[0x30, 0x03, 0x0a, 0x01, 0x01]
279 }
280 let app = Router::new().route("/{*path}", get(ocsp_catch_all));
281 super::embedded_ui::mount(app)
282 }
283
284 #[tokio::test]
285 async fn ui_root_serves_spa_not_ocsp() {
286 let resp = test_router()
287 .oneshot(Request::get("/ui/").body(Body::empty()).unwrap())
288 .await
289 .unwrap();
290 assert_eq!(resp.status(), StatusCode::OK);
291 let ctype = resp
292 .headers()
293 .get(header::CONTENT_TYPE)
294 .and_then(|v| v.to_str().ok())
295 .unwrap_or("");
296 assert!(
297 ctype.starts_with("text/html"),
298 "GET /ui/ must serve the SPA index (text/html), got content-type {ctype:?}"
299 );
300 }
301
302 #[tokio::test]
303 async fn ui_bare_redirects_to_slash() {
304 let resp = test_router()
305 .oneshot(Request::get("/ui").body(Body::empty()).unwrap())
306 .await
307 .unwrap();
308 assert_eq!(resp.status(), StatusCode::PERMANENT_REDIRECT);
309 assert_eq!(
310 resp.headers().get(header::LOCATION).unwrap(),
311 "/ui/",
312 "GET /ui must redirect to /ui/"
313 );
314 }
315
316 #[tokio::test]
317 async fn non_ui_path_still_hits_ocsp() {
318 let resp = test_router()
320 .oneshot(Request::get("/MFQwUj...").body(Body::empty()).unwrap())
321 .await
322 .unwrap();
323 assert_eq!(resp.status(), StatusCode::OK);
324 let body = axum::body::to_bytes(resp.into_body(), 64).await.unwrap();
325 assert_eq!(body.len(), 5, "OCSP-over-GET path must still be served");
326 }
327}