Skip to content

Commit bb00f82

Browse files
feat: a Prometheus scrape endpoint and the relay counters it reads (#1282)
Landed as job 042, row 1 of #868. Reviewed at 17d64b6; the tree merged is the tree the approver read.
2 parents 1514e7f + 17d64b6 commit bb00f82

28 files changed

Lines changed: 1972 additions & 41 deletions

File tree

‎.changeset/prometheus-metrics.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
---
2+
---
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
//! `GET <prefix>/metrics`: the relay's counters as Prometheus text format 0.0.4.
2+
//!
3+
//! Not the console's SSE stream (`get_metrics.rs`, at `<prefix>/admin/metrics`): this handler
4+
//! serves a scraper, is mounted outside the admin gate and reads no session cookie (ADR 0021,
5+
//! decisions 1 and 2). Its one credential is the configured bearer token, compared in constant
6+
//! time; the arms are decided in this order — no configured token, no `Authorization` header,
7+
//! no `Bearer ` prefix, a mismatch — and every one of them answers the same `401`.
8+
9+
use std::sync::Arc;
10+
11+
use axum::extract::State;
12+
use axum::http::{HeaderMap, StatusCode, header};
13+
use axum::response::{IntoResponse, Response};
14+
15+
use crate::controllers::with_admin_controller_request_handler::error_message;
16+
use crate::state::PrometheusMetrics;
17+
18+
/// The scheme the token rides in, exactly: the `Authorization` header's bytes after this
19+
/// prefix are the presented token (ADR 0021, decision 2).
20+
pub const BEARER_PREFIX: &str = "Bearer ";
21+
22+
/// The Prometheus text format's own version string, which is what a scraper's parser reads.
23+
const CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8";
24+
25+
/// Serves the exposition, or the tree's `401 {"error":"Unauthorized"}`.
26+
pub async fn handle(State(metrics): State<Arc<PrometheusMetrics>>, headers: HeaderMap) -> Response {
27+
let Some(token) = metrics.token.as_deref() else {
28+
return unauthorized();
29+
};
30+
31+
let Some(presented) = headers
32+
.get(header::AUTHORIZATION)
33+
.and_then(|value| value.to_str().ok())
34+
.and_then(|value| value.strip_prefix(BEARER_PREFIX))
35+
else {
36+
return unauthorized();
37+
};
38+
39+
if !tokens_match(presented.as_bytes(), token) {
40+
return unauthorized();
41+
}
42+
43+
(
44+
StatusCode::OK,
45+
[(header::CONTENT_TYPE, CONTENT_TYPE)],
46+
nostream_relay::metrics::render(&metrics.counters, metrics.connections.live_total()),
47+
)
48+
.into_response()
49+
}
50+
51+
/// The tree's unauthorized answer, byte for byte (`admin_auth_middleware.rs:62`).
52+
fn unauthorized() -> Response {
53+
error_message(StatusCode::UNAUTHORIZED, "Unauthorized")
54+
}
55+
56+
/// Whether `presented` is `configured`, in time that does not depend on where the first
57+
/// difference is: one XOR-accumulated loop over the bytes.
58+
///
59+
/// A length mismatch answers `false` early. That leaks the configured token's length to a
60+
/// caller who can time the response, and nothing else: the bytes are never compared, so no
61+
/// prefix of a guess can be distinguished from another.
62+
fn tokens_match(presented: &[u8], configured: &[u8]) -> bool {
63+
if presented.len() != configured.len() {
64+
return false;
65+
}
66+
67+
let mut difference = 0u8;
68+
69+
for (left, right) in presented.iter().zip(configured) {
70+
difference |= left ^ right;
71+
}
72+
73+
difference == 0
74+
}
75+
76+
#[cfg(test)]
77+
mod tests {
78+
#![allow(clippy::unwrap_used, clippy::expect_used)]
79+
80+
use super::*;
81+
82+
#[test]
83+
fn an_equal_token_matches() {
84+
assert!(tokens_match(b"sekrit", b"sekrit"));
85+
}
86+
87+
#[test]
88+
fn a_different_token_does_not_match() {
89+
assert!(!tokens_match(b"sekret", b"sekrit"));
90+
assert!(!tokens_match(b"xekrit", b"sekrit"));
91+
}
92+
93+
#[test]
94+
fn a_length_mismatch_does_not_match() {
95+
assert!(!tokens_match(b"sekri", b"sekrit"));
96+
assert!(!tokens_match(b"sekritt", b"sekrit"));
97+
assert!(!tokens_match(b"", b"sekrit"));
98+
}
99+
}

‎crates/nostream-admin/src/controllers/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ pub mod get_ops_nip05_verifications;
3939
pub mod get_ops_storage_counts;
4040
pub mod get_ops_workers;
4141
pub mod get_privacy;
42+
pub mod get_prometheus_metrics;
4243
pub mod get_readyz;
4344
pub mod get_session;
4445
pub mod get_settings;

‎crates/nostream-admin/src/lib.rs‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,13 @@
2323
//! daemon serves that router from the one listener it binds (D13): this crate never opens a
2424
//! socket.
2525
//!
26+
//! **The scrape endpoint is the one route outside the gate.** `GET <prefix>/metrics`
27+
//! ([`METRICS_PATH`], ADR 0021, decision 1) serves the relay's counters as Prometheus text
28+
//! format; it is mounted only when the composition root enabled it, and it is merged after the
29+
//! admin router is `with_state`d, so `admin_enabled`, `content_security` and the admin limiter
30+
//! do not apply to it. Its credential is the bearer token on
31+
//! [`PrometheusMetrics`](state::PrometheusMetrics), never the session cookie.
32+
//!
2633
//! **Deliberately not owned here** — a reader should be able to tell an omission from a gap:
2734
//!
2835
//! - the listening socket, the WebSocket upgrade and the drain — `nostreamd` and
@@ -48,8 +55,8 @@ pub mod state;
4855
pub mod utils;
4956

5057
pub use error::AdminError;
51-
pub use routes::{ADMIN_ROUTES, AdminRoute, PREFIX_MIDDLEWARE, mount};
52-
pub use state::{AdminState, AdminStateConfig, GrafanaSettings, MaintenanceRun};
58+
pub use routes::{ADMIN_ROUTES, AdminRoute, METRICS_PATH, PREFIX_MIDDLEWARE, mount};
59+
pub use state::{AdminState, AdminStateConfig, GrafanaSettings, MaintenanceRun, PrometheusMetrics};
5360

5461
/// The CSP nonce the page's `<script>` tags carry, for a caller that mounts the page itself.
5562
pub use controllers::admin_enabled_middleware::Nonce;

‎crates/nostream-admin/src/routes/mod.rs‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ pub const PREFIX_MIDDLEWARE: [&str; 3] = [
2929
"/assets (static)",
3030
];
3131

32+
/// The scrape endpoint's path below the prefix: `GET <prefix>/metrics` (ADR 0021, decision 1).
33+
///
34+
/// Outside `/admin`, because the console's SSE stream owns `<prefix>/admin/metrics`.
35+
pub const METRICS_PATH: &str = "/metrics";
36+
3237
/// The table, in the order the capture registers them (`src/routes/admin/index.ts:49-221`).
3338
pub const ADMIN_ROUTES: [AdminRoute; 30] = [
3439
AdminRoute {
@@ -177,7 +182,8 @@ pub fn axum_path(path: &str) -> String {
177182
converted
178183
}
179184

180-
/// Builds the whole admin surface under `<prefix>/admin`.
185+
/// Builds the whole admin surface under `<prefix>/admin`, and the scrape route at
186+
/// `<prefix>/metrics` when the composition root enabled it.
181187
///
182188
/// The prefix is fixed here, when the router is built: a page whose scripts were rewritten for
183189
/// a prefix the routes are not mounted at would `404` (D10). `nostream-admin` does not bind a
@@ -186,7 +192,7 @@ pub fn mount(state: Arc<AdminState>) -> Router {
186192
let prefix = state.path_prefix();
187193
let base = format!("{prefix}/admin");
188194

189-
Router::new()
195+
let admin = Router::new()
190196
// The console requests `<prefix>/admin/`; the bare `<prefix>/admin` is the same page
191197
// for a hand-typed URL, as the capture's `router.get('/')` under its mount is.
192198
.route(&format!("{base}/"), get(controllers::get_dashboard::handle))
@@ -325,7 +331,25 @@ pub fn mount(state: Arc<AdminState>) -> Router {
325331
Arc::clone(&state),
326332
controllers::admin_enabled_middleware::content_security,
327333
))
328-
.with_state(state)
334+
.with_state(Arc::clone(&state));
335+
336+
// The scrape endpoint is built into its own router and merged after the admin router has
337+
// been `with_state`d, so it sits outside `admin_enabled`, `content_security` and the admin
338+
// limiter without changing any of them: a layer applies to the routes already on the
339+
// router, and axum keeps this router's custom fallback when the merged one has the default
340+
// fallback (ADR 0021, decision 1).
341+
let Some(metrics) = state.prometheus_metrics() else {
342+
return admin;
343+
};
344+
345+
let scrape = Router::new()
346+
.route(
347+
&format!("{prefix}{METRICS_PATH}"),
348+
get(controllers::get_prometheus_metrics::handle),
349+
)
350+
.with_state(Arc::clone(metrics));
351+
352+
admin.merge(scrape)
329353
}
330354

331355
#[cfg(test)]

‎crates/nostream-admin/src/state.rs‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,35 @@ pub struct AdminStateConfig {
193193
pub worker_count_override: Option<u32>,
194194
/// `ADMIN_PASSWORD` when the environment set a non-empty one (Value 10).
195195
pub password_override: Option<String>,
196+
/// The scrape endpoint, when the composition root enabled it. `None` leaves
197+
/// `<prefix>/metrics` unregistered, so it answers the router's `404` (ADR 0021,
198+
/// decision 2).
199+
pub metrics: Option<Arc<PrometheusMetrics>>,
200+
}
201+
202+
/// The scrape endpoint's composition: the bearer token it accepts and the counters it renders.
203+
///
204+
/// Built by the daemon's edge from `METRICS_ENABLED` and `METRICS_TOKEN` (ADR 0021, decision
205+
/// 2); a case constructs it directly. `token: None` is the enabled endpoint with no token
206+
/// configured, which answers `401` to everything.
207+
pub struct PrometheusMetrics {
208+
pub token: Option<Vec<u8>>,
209+
pub counters: Arc<nostream_relay::metrics::RelayMetrics>,
210+
pub connections: Arc<nostream_relay::connection_cap::ConnectionCap>,
211+
}
212+
213+
/// The token is the bearer credential and prints redacted, as `AdminState`'s secret does; the
214+
/// two counters print as their type name, because their own `Debug` dumps every gauge and a
215+
/// log line needs the handle, not its contents.
216+
impl std::fmt::Debug for PrometheusMetrics {
217+
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218+
formatter
219+
.debug_struct("PrometheusMetrics")
220+
.field("token", &self.token.as_ref().map(|_| "***"))
221+
.field("counters", &"RelayMetrics")
222+
.field("connections", &"ConnectionCap")
223+
.finish()
224+
}
196225
}
197226

198227
/// The Grafana links the dashboard template substitutes (`src/utils/admin-grafana.ts`).
@@ -229,6 +258,7 @@ pub struct AdminState {
229258
worker_index: Option<String>,
230259
worker_count_override: Option<u32>,
231260
password_override: Option<String>,
261+
metrics: Option<Arc<PrometheusMetrics>>,
232262
}
233263

234264
impl AdminState {
@@ -257,9 +287,15 @@ impl AdminState {
257287
worker_index: config.worker_index,
258288
worker_count_override: config.worker_count_override,
259289
password_override: config.password_override,
290+
metrics: config.metrics,
260291
}
261292
}
262293

294+
/// The scrape endpoint, when the composition root enabled it.
295+
pub fn prometheus_metrics(&self) -> Option<&Arc<PrometheusMetrics>> {
296+
self.metrics.as_ref()
297+
}
298+
263299
/// The resolved settings paths.
264300
pub fn paths(&self) -> &SettingsPaths {
265301
&self.paths
@@ -812,3 +848,30 @@ fn log_issues(issues: &[Issue]) {
812848
tracing::warn!(issue = %issue, "the settings document does not validate");
813849
}
814850
}
851+
852+
#[cfg(test)]
853+
mod tests {
854+
#![allow(clippy::unwrap_used, clippy::expect_used)]
855+
856+
use super::*;
857+
858+
/// The bearer credential must not reach a log through `Debug`: the derived impl printed it
859+
/// as decimal bytes.
860+
#[test]
861+
fn debug_redacts_the_metrics_token() {
862+
let token = b"probe-token".to_vec();
863+
let leaked = format!("{token:?}");
864+
let metrics = PrometheusMetrics {
865+
token: Some(token),
866+
counters: Arc::new(nostream_relay::metrics::RelayMetrics::default()),
867+
connections: Arc::new(nostream_relay::connection_cap::ConnectionCap::new(
868+
usize::MAX,
869+
)),
870+
};
871+
872+
let printed = format!("{metrics:?}");
873+
874+
assert!(printed.contains(r#"token: Some("***")"#), "{printed}");
875+
assert!(!printed.contains(&leaked), "{printed}");
876+
}
877+
}

‎crates/nostream-admin/tests/common/mod.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use std::sync::Arc;
1515
use std::time::Duration;
1616

1717
use nostream_admin::state::AdminStateConfig;
18-
use nostream_admin::{AdminState, GrafanaSettings};
18+
use nostream_admin::{AdminState, GrafanaSettings, PrometheusMetrics};
1919
use nostream_config::{SettingsPaths, load_defaults};
2020
use nostream_core::clock::{Clock, TestClock};
2121
use nostream_core::nip05::Nip05Fetch;
@@ -79,6 +79,8 @@ pub struct Fixture {
7979
Option<Arc<dyn nostream_storage::repositories::NotificationDeliveryLogRepository>>,
8080
/// The NIP-05 fetch seam, when a case scripts the verification outcome.
8181
pub fetch: Option<Arc<dyn Nip05Fetch>>,
82+
/// The scrape endpoint, when the case enables it (ADR 0021, decision 2).
83+
pub metrics: Option<Arc<PrometheusMetrics>>,
8284
}
8385

8486
impl Default for Fixture {
@@ -94,6 +96,7 @@ impl Default for Fixture {
9496
nip05: None,
9597
delivery_log: None,
9698
fetch: None,
99+
metrics: None,
97100
}
98101
}
99102
}
@@ -206,6 +209,7 @@ impl TestServer {
206209
worker_index: None,
207210
worker_count_override: fixture.worker_count,
208211
password_override: fixture.password_override,
212+
metrics: fixture.metrics,
209213
},
210214
Arc::new(SystemRandom),
211215
));

0 commit comments

Comments
 (0)