Skip to main content

rushls_common/
metrics.rs

1//! Small, transport-independent pieces shared by metrics endpoints.
2//!
3//! Metric collection and HTTP serving stay in the application. These helpers
4//! provide bearer-token parsing, constant-time comparison, and Prometheus
5//! label escaping without coupling callers to a registry or HTTP framework.
6
7use std::fmt;
8
9use subtle::ConstantTimeEq;
10
11/// An optional bearer credential for a metrics endpoint.
12///
13/// The value is deliberately not exposed through `Debug`, because endpoint
14/// configuration is commonly included in startup diagnostics.
15#[derive(Clone, Eq, PartialEq)]
16pub struct MetricsToken(Vec<u8>);
17
18impl MetricsToken {
19    pub fn new(value: impl Into<Vec<u8>>) -> Self {
20        Self(value.into())
21    }
22
23    /// Whether this token could never be presented as a bearer credential.
24    pub fn is_empty(&self) -> bool {
25        self.0.is_empty()
26    }
27
28    /// Compare a presented credential without exposing matching-prefix timing.
29    pub fn matches(&self, presented: &[u8]) -> bool {
30        self.0.as_slice().ct_eq(presented).into()
31    }
32}
33
34impl fmt::Debug for MetricsToken {
35    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
36        formatter.write_str("MetricsToken([REDACTED])")
37    }
38}
39
40/// Extract a bearer token from an `Authorization` field.
41pub fn bearer_token(value: &str) -> Option<&str> {
42    let (scheme, token) = value.split_once(' ')?;
43    (scheme.eq_ignore_ascii_case("bearer")
44        && !token.is_empty()
45        && !token.chars().any(char::is_whitespace))
46    .then_some(token)
47}
48
49/// Escape a value for a Prometheus text-format label.
50pub fn escape_label(value: &str) -> String {
51    value
52        .replace('\\', r"\\")
53        .replace('\n', r"\n")
54        .replace('"', "\\\"")
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn bearer_tokens_are_parsed_strictly() {
63        assert_eq!(bearer_token("Bearer secret"), Some("secret"));
64        assert_eq!(bearer_token("bearer secret"), Some("secret"));
65        assert_eq!(bearer_token("Basic secret"), None);
66        assert_eq!(bearer_token("Bearer"), None);
67        assert_eq!(bearer_token("Bearer secret extra"), None);
68    }
69
70    #[test]
71    fn labels_escape_prometheus_control_characters() {
72        assert_eq!(escape_label("a\\b\n\"c"), r#"a\\b\n\"c"#);
73    }
74
75    #[test]
76    fn token_debug_output_does_not_reveal_the_secret() {
77        let debug = format!("{:?}", MetricsToken::new("secret"));
78        assert_eq!(debug, "MetricsToken([REDACTED])");
79        assert!(!debug.contains("secret"));
80    }
81}