Skip to main content

dekopon_webui/
lib.rs

1//! Unauthenticated, read-only operational web UI for `dekopon-brokerd`.
2//!
3//! The HTTP surface exposes only `GET`/`HEAD` views. It has no login because it has no mutation or
4//! authorization path, but its contents are still deployment information: agent names, provider
5//! schemas, artifact paths and digests, Wasmtime counters, and credential-free OTLP settings. An
6//! operator chooses the listener address explicitly and owns the network boundary around it.
7//!
8//! The listener is bounded like the broker's Unix socket rather than left open-ended: see
9//! [`WebUiLimits`].
10
11#![forbid(unsafe_code)]
12
13mod listener;
14mod render;
15mod status;
16
17use std::{future::Future, sync::Arc, time::Duration};
18
19use axum::{
20    Router,
21    body::{Body, Bytes, HttpBody as _},
22    extract::{Path, Request, State},
23    http::{HeaderName, HeaderValue, StatusCode, header},
24    middleware::Next,
25    response::{Html, IntoResponse, Redirect, Response},
26    routing::get,
27};
28use dekopon_broker_host::{BrokerHostMetrics, LoadedProviderMetadata};
29use thiserror::Error;
30use tokio::net::TcpListener;
31
32use crate::listener::BoundedListener;
33
34pub use status::{ServiceStatus, TokenTotals};
35
36/// Concurrent connections the informational listener accepts before refusing.
37pub const DEFAULT_MAX_CONNECTIONS: usize = 16;
38/// Wall-clock budget one accepted connection has from accept to close.
39pub const DEFAULT_CONNECTION_TIMEOUT: Duration = Duration::from_secs(30);
40
41/// Credential-free OTLP settings safe to render in the informational UI.
42#[derive(Clone, Debug, Eq, PartialEq)]
43pub struct OtelSummary {
44    /// Configured receiver base endpoint.
45    pub endpoint: String,
46    /// `grpc` or `http`.
47    pub transport: String,
48    /// Resource service name.
49    pub service_name: String,
50    /// Per-export timeout.
51    pub export_timeout_ms: u64,
52    /// Whether payload-bearing telemetry is enabled.
53    pub telemetry_payloads: bool,
54    /// Whether any standard OTLP header environment variable is present.
55    ///
56    /// Values are never retained or rendered.
57    pub headers_configured: bool,
58    /// Whether `OTEL_RESOURCE_ATTRIBUTES` is present. Its value is not retained or rendered.
59    pub resource_attributes_configured: bool,
60}
61
62/// Ceilings the informational listener enforces on an unauthenticated network surface.
63///
64/// This listener lives inside the privileged broker process, whose worst deployment failure is an
65/// OOM kill, so it mirrors the broker socket's `maxConnections`/`ioTimeoutMs` philosophy: a fixed
66/// concurrency ceiling that **refuses** rather than queues, and one wall-clock budget per accepted
67/// connection covering header read, rendering, and body write.
68#[derive(Clone, Copy, Debug, Eq, PartialEq)]
69pub struct WebUiLimits {
70    /// Connections served concurrently. Further connections are closed without a response.
71    pub max_connections: usize,
72    /// Budget one connection has from accept to close, including HTTP/1 keep-alive reuse.
73    pub connection_timeout: Duration,
74}
75
76impl Default for WebUiLimits {
77    fn default() -> Self {
78        Self {
79            max_connections: DEFAULT_MAX_CONNECTIONS,
80            connection_timeout: DEFAULT_CONNECTION_TIMEOUT,
81        }
82    }
83}
84
85/// One provider's startup-immutable rendered page beside the metadata it was rendered from.
86#[derive(Clone, Debug)]
87pub(crate) struct ProviderPage {
88    metadata: LoadedProviderMetadata,
89    page: Bytes,
90}
91
92impl ProviderPage {
93    pub(crate) const fn metadata(&self) -> &LoadedProviderMetadata {
94        &self.metadata
95    }
96}
97
98/// Shared immutable deployment metadata and live process-local counters.
99#[derive(Clone, Debug)]
100pub struct Dashboard {
101    pub(crate) version: String,
102    pub(crate) providers: Arc<[ProviderPage]>,
103    pub(crate) host_metrics: BrokerHostMetrics,
104    pub(crate) service_status: ServiceStatus,
105    pub(crate) otel: Option<OtelSummary>,
106}
107
108impl Dashboard {
109    /// Builds a dashboard from provider metadata captured during broker startup.
110    ///
111    /// Provider pages derive solely from that metadata and the broker version, both fixed for the
112    /// life of the process, so each page is serialized, escaped, and rendered exactly once here
113    /// instead of on every request.
114    #[must_use]
115    pub fn new(
116        version: impl Into<String>,
117        mut providers: Vec<LoadedProviderMetadata>,
118        host_metrics: BrokerHostMetrics,
119        service_status: ServiceStatus,
120        otel: Option<OtelSummary>,
121    ) -> Self {
122        let version = version.into();
123        providers.sort_by(|left, right| left.manifest.id.cmp(&right.manifest.id));
124        let providers = providers
125            .into_iter()
126            .map(|metadata| ProviderPage {
127                page: Bytes::from(render::provider_page(&version, &metadata)),
128                metadata,
129            })
130            .collect();
131        Self {
132            version,
133            providers,
134            host_metrics,
135            service_status,
136            otel,
137        }
138    }
139
140    fn provider(&self, id: &str) -> Option<&ProviderPage> {
141        self.providers
142            .iter()
143            .find(|provider| provider.metadata.manifest.id.as_str() == id)
144    }
145}
146
147/// Builds the GET-only router used by `dekopon-brokerd`.
148pub fn router(dashboard: Dashboard) -> Router {
149    Router::new()
150        .route("/", get(root))
151        .route("/ui", get(index))
152        .route("/ui/", get(ui_slash))
153        .route("/ui/providers/{provider}", get(provider))
154        .fallback(not_found)
155        // Applied to the whole router rather than inside the response helpers so the closed policy
156        // also covers responses this crate never authors, notably axum's 405 for a mutating method.
157        .layer(axum::middleware::map_response(apply_secure_headers))
158        .layer(axum::middleware::from_fn(trace_request))
159        .with_state(dashboard)
160}
161
162/// Serves the dashboard on an already-bound listener until graceful shutdown.
163///
164/// Connections are bounded by [`WebUiLimits::default`].
165pub async fn serve<F>(
166    listener: TcpListener,
167    dashboard: Dashboard,
168    shutdown: F,
169) -> Result<(), WebUiError>
170where
171    F: Future<Output = ()> + Send + 'static,
172{
173    serve_with_limits(listener, dashboard, WebUiLimits::default(), shutdown).await
174}
175
176/// Serves the dashboard with explicit connection ceilings.
177pub async fn serve_with_limits<F>(
178    listener: TcpListener,
179    dashboard: Dashboard,
180    limits: WebUiLimits,
181    shutdown: F,
182) -> Result<(), WebUiError>
183where
184    F: Future<Output = ()> + Send + 'static,
185{
186    if limits.max_connections == 0 || limits.connection_timeout.is_zero() {
187        return Err(WebUiError::InvalidLimits);
188    }
189    axum::serve(BoundedListener::new(listener, limits), router(dashboard))
190        .with_graceful_shutdown(shutdown)
191        .await
192        .map_err(WebUiError::Serve)
193}
194
195async fn root() -> Response {
196    redirect("/ui")
197}
198
199async fn ui_slash() -> Response {
200    redirect("/ui")
201}
202
203async fn index(State(dashboard): State<Dashboard>) -> Response {
204    html(StatusCode::OK, render::dashboard(&dashboard))
205}
206
207async fn provider(State(dashboard): State<Dashboard>, Path(provider): Path<String>) -> Response {
208    match dashboard.provider(&provider) {
209        Some(provider) => rendered(StatusCode::OK, provider.page.clone()),
210        None => html(
211            StatusCode::NOT_FOUND,
212            render::not_found(&dashboard, "Provider not found"),
213        ),
214    }
215}
216
217async fn not_found(State(dashboard): State<Dashboard>) -> Response {
218    html(
219        StatusCode::NOT_FOUND,
220        render::not_found(&dashboard, "Page not found"),
221    )
222}
223
224fn redirect(location: &'static str) -> Response {
225    Redirect::permanent(location).into_response()
226}
227
228fn html(status: StatusCode, body: String) -> Response {
229    (status, Html(body)).into_response()
230}
231
232fn rendered(status: StatusCode, body: Bytes) -> Response {
233    (
234        status,
235        [(
236            header::CONTENT_TYPE,
237            HeaderValue::from_static("text/html; charset=utf-8"),
238        )],
239        Body::from(body),
240    )
241        .into_response()
242}
243
244async fn apply_secure_headers(mut response: Response) -> Response {
245    let headers = response.headers_mut();
246    headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
247    headers.insert(
248        header::X_CONTENT_TYPE_OPTIONS,
249        HeaderValue::from_static("nosniff"),
250    );
251    headers.insert(
252        header::REFERRER_POLICY,
253        HeaderValue::from_static("no-referrer"),
254    );
255    headers.insert(
256        HeaderName::from_static("content-security-policy"),
257        HeaderValue::from_static(
258            "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",
259        ),
260    );
261    response
262}
263
264/// Records one line per request so probe traffic and path scans on this listener are observable.
265///
266/// Debug level: an `info` production filter ships nothing, and the signal is one `RUST_LOG` away.
267/// The path is recorded without its query string, and no request or response body ever is.
268async fn trace_request(request: Request, next: Next) -> Response {
269    let method = request.method().clone();
270    let path = request.uri().path().to_owned();
271    let response = next.run(request).await;
272    tracing::debug!(
273        event = "webui_request",
274        http.method = %method,
275        http.path = %path,
276        http.status = response.status().as_u16(),
277        http.response_bytes = response.body().size_hint().exact().unwrap_or_default()
278    );
279    response
280}
281
282/// HTTP listener or serving failure.
283#[derive(Debug, Error)]
284pub enum WebUiError {
285    /// Axum could not serve or gracefully close the listener.
286    #[error("Dekopon web UI server failed")]
287    Serve(#[source] std::io::Error),
288    /// Connection ceilings would have left the listener unbounded.
289    #[error("Dekopon web UI connection limits are invalid")]
290    InvalidLimits,
291}