Skip to main content

hyprstream_core/services/oauth/
replay_metrics.rs

1//! OpenTelemetry signals for fail-closed OAuth replay barriers.
2
3use hyprstream_util::InsertIfAbsentNoEvictResult;
4use once_cell::sync::Lazy;
5use parking_lot::Mutex;
6use std::collections::HashMap;
7use std::time::{Duration, Instant};
8
9pub const DPOP: &str = "dpop";
10pub const CLIENT_ASSERTION: &str = "client_assertion";
11pub const ATPROTO_SERVICE_ASSERTION: &str = "atproto_service_assertion";
12
13const FULL_WARNING_INTERVAL: Duration = Duration::from_secs(60);
14static LAST_FULL_WARNING: Lazy<Mutex<HashMap<&'static str, Instant>>> =
15    Lazy::new(|| Mutex::new(HashMap::new()));
16
17#[cfg(all(feature = "otel", not(target_arch = "wasm32")))]
18mod metered {
19    use once_cell::sync::Lazy;
20    use opentelemetry::KeyValue;
21
22    use super::*;
23
24    const METER_NAME: &str = "hyprstream.oauth";
25    const METRIC_REJECTIONS: &str = "oauth_replay_barrier_rejections_total";
26
27    struct ReplayBarrierMeter {
28        rejections: opentelemetry::metrics::Counter<u64>,
29    }
30
31    impl ReplayBarrierMeter {
32        fn global() -> Self {
33            let meter = opentelemetry::global::meter(METER_NAME);
34            Self {
35                rejections: meter
36                    .u64_counter(METRIC_REJECTIONS)
37                    .with_description(
38                        "OAuth replay barrier rejections, by barrier and rejection reason",
39                    )
40                    .build(),
41            }
42        }
43
44        fn record(&self, barrier: &'static str, result: InsertIfAbsentNoEvictResult) {
45            let reason = match result {
46                InsertIfAbsentNoEvictResult::Duplicate => "duplicate",
47                InsertIfAbsentNoEvictResult::Full => "full",
48                InsertIfAbsentNoEvictResult::Inserted => return,
49            };
50            self.rejections.add(
51                1,
52                &[
53                    KeyValue::new("barrier", barrier),
54                    KeyValue::new("reason", reason),
55                ],
56            );
57        }
58    }
59
60    static METER: Lazy<ReplayBarrierMeter> = Lazy::new(ReplayBarrierMeter::global);
61
62    pub(super) fn record(barrier: &'static str, result: InsertIfAbsentNoEvictResult) {
63        METER.record(barrier, result);
64    }
65}
66
67#[cfg(not(all(feature = "otel", not(target_arch = "wasm32"))))]
68mod metered {
69    use super::*;
70
71    pub(super) fn record(_barrier: &'static str, _result: InsertIfAbsentNoEvictResult) {}
72}
73
74/// Record every failed replay-barrier insertion. The `reason` attribute makes
75/// a blocked replay distinguishable from legitimate traffic refused because
76/// the fail-closed barrier is saturated.
77pub fn record_rejection(barrier: &'static str, result: InsertIfAbsentNoEvictResult) {
78    metered::record(barrier, result);
79}
80
81/// Return `true` at most once per barrier per minute for a full-barrier
82/// rejection. Metrics still record every rejection; this only prevents an
83/// attacker from turning saturation into unbounded warning-log volume.
84pub fn should_warn_full(barrier: &'static str, result: InsertIfAbsentNoEvictResult) -> bool {
85    if result != InsertIfAbsentNoEvictResult::Full {
86        return false;
87    }
88    let now = Instant::now();
89    let mut last_warning = LAST_FULL_WARNING.lock();
90    match last_warning.get_mut(barrier) {
91        Some(last) if now.duration_since(*last) < FULL_WARNING_INTERVAL => false,
92        Some(last) => {
93            *last = now;
94            true
95        }
96        None => {
97            last_warning.insert(barrier, now);
98            true
99        }
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn full_warnings_are_rate_limited_per_barrier() {
109        let barrier = "replay_metrics_rate_limit_test";
110        assert!(should_warn_full(barrier, InsertIfAbsentNoEvictResult::Full));
111        assert!(!should_warn_full(
112            barrier,
113            InsertIfAbsentNoEvictResult::Full
114        ));
115        assert!(!should_warn_full(
116            barrier,
117            InsertIfAbsentNoEvictResult::Duplicate
118        ));
119    }
120}