Skip to main content

hoike_server/
lib.rs

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
14/// Announce every CA scope in a freshly produced bundle to the gossip mesh.
15///
16/// Parses the sealed bundle bytes to recover each scope's `producer_id`,
17/// `issuer_key_hash`, and `epoch`, then broadcasts one `GenerationAnnouncement`
18/// per scope. The generation identity is `ahu::manifest_digest` of the
19/// serialized manifest — it changes whenever any signed manifest metadata
20/// (epoch, window, continuity) changes, unlike the index digest, which only
21/// covers the index section. `bundle_url` stays `None` until a bundle
22/// retrieval route actually exists; announcing a fabricated URL would point
23/// receivers at nothing. Failures are logged, never fatal — gossip is
24/// best-effort and must not break a successful signing pass. Centralized
25/// here because this is the only crate that depends on both `ahu` (to parse)
26/// and `hoike-gossip` (to send).
27pub 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
57/// Install the global Prometheus recorder. No-op (returns `false`) unless the
58/// `metrics` feature is enabled. Call once at startup before serving.
59pub fn install_metrics() -> bool {
60    obs::install()
61}
62
63/// Build a minimal router exposing `GET /metrics` in Prometheus text format.
64///
65/// Kept separate from the main OCSP router so operators bind it on a private
66/// listener (`server.metrics_listen`), never the public OCSP port.
67pub 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    // Collect-on-scrape: refresh the freshness gauges from the loaded scopes so
75    // age/next-update reflect the scrape-time clock, not the last request.
76    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    // Census the gossip fleet on scrape, if a node is attached.
83    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
112/// Build the public OCSP router.
113///
114/// When no dedicated admin listener is configured (`server.admin_listen`
115/// unset), the admin API and web UI are nested onto this same router for
116/// backward compatibility — the legacy single-port layout. When `admin_listen`
117/// *is* set, the management surface moves to its own listener
118/// (`build_admin_router`) so it can be given a trusted path (TLS, FTP_TRP.1)
119/// without wrapping the plaintext OCSP data plane; this router then serves OCSP
120/// only.
121pub 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    // Legacy layout: admin + UI ride the OCSP port only when no dedicated admin
130    // listener is configured.
131    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
140/// Build the standalone admin router (admin API + web UI) for a dedicated
141/// management listener. Contains no OCSP routes, so it can be TLS-terminated
142/// independently of the plaintext OCSP data plane.
143pub fn build_admin_router_standalone(state: AppState) -> Router {
144    // `admin::build_admin_router` already applies `.with_state`, yielding a
145    // fully-stated `Router<()>`; nesting it needs no further state.
146    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
151/// Mount the web UI (disk-served `static_dir`, or the embedded SPA) onto a
152/// router. Shared by the legacy single-port layout and the standalone admin
153/// router so both surface the UI identically.
154fn 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    /// Mount the embedded SPA on the main router.
195    ///
196    /// The OCSP protocol occupies a greedy `GET /{*path}` catch-all (OCSP-over-GET
197    /// carries a base64 request in the path). Nesting a sub-router for the SPA is
198    /// unreliable under axum 0.8: `GET /ui/` (the directory root, trailing slash)
199    /// loses to the catch-all and returns the 5-byte OCSP `malformedRequest` error.
200    /// Registering explicit static routes — which outrank the wildcard in matchit —
201    /// keeps the SPA entry point (`/ui`, `/ui/`) and its assets (`/ui/{*path}`)
202    /// deterministically routed. `/ui` and `/ui/` redirect to the app index.
203    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; // for `oneshot`
269
270    /// Reproduce the production route layout: the SPA is mounted alongside the
271    /// greedy OCSP-over-GET catch-all (`GET /{*path}`). This guards against two
272    /// regressions: (1) a matchit wildcard-conflict panic at router-build time,
273    /// and (2) `GET /ui/` falling through to the OCSP handler (which returns the
274    /// 5-byte `malformedRequest` DER, not the SPA).
275    fn test_router() -> Router {
276        async fn ocsp_catch_all() -> &'static [u8] {
277            // The static OCSP malformedRequest response is 5 bytes.
278            &[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        // A non-/ui path must still reach the OCSP catch-all unchanged.
319        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}