Skip to main content

vcon_server/api/
report_gate.rs

1//! How many reports of a content-security-policy violation a listener
2//! takes in a minute (`limits.csp_reports`, and from one address
3//! `limits.csp_reports_per_address`).
4//!
5//! The report route takes no key, and each report it answers costs one
6//! write to the registry. The gate bounds that: past either number a
7//! report is refused with 429 before its body is read, and no write is
8//! made for it. Refusals are added up in memory and written as one record
9//! for the minute, so a flood shows in the admin log as one row that says
10//! how many were refused.
11
12use std::collections::HashMap;
13use std::net::IpAddr;
14use std::sync::Mutex;
15
16use time::OffsetDateTime;
17
18/// How many reports a listener takes.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct ReportLimits {
21    /// The most reports taken in one minute, from every address together.
22    pub per_minute: u32,
23    /// The most reports taken in one minute from one address.
24    pub per_address: u32,
25}
26
27impl ReportLimits {
28    /// A browser reports a violation once for each thing a page was
29    /// refused, so a console page with a misbehaving extension sends a
30    /// few reports for each load: 20 a minute is several loads from one
31    /// address, and 120 is six such addresses at once.
32    pub const DEFAULT: Self = Self {
33        per_minute: 120,
34        per_address: 20,
35    };
36}
37
38/// What the gate says of one report.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub(crate) struct Admission {
41    /// Whether the report is taken; one that is not is answered 429.
42    pub(crate) taken: bool,
43    /// The minute of the report.
44    pub(crate) minute: OffsetDateTime,
45    /// Whether this is the first report refused in its minute, the one
46    /// that starts the wait for the minute's end.
47    pub(crate) first_refusal: bool,
48    /// An earlier minute and the refusals in it that no record holds yet:
49    /// the caller writes them.
50    pub(crate) earlier: Option<(OffsetDateTime, u64)>,
51}
52
53/// One listener's count of the reports of the current minute.
54#[derive(Debug)]
55pub struct Gate {
56    limits: ReportLimits,
57    window: Mutex<Window>,
58}
59
60#[derive(Debug, Default)]
61struct Window {
62    minute: Option<OffsetDateTime>,
63    taken: u32,
64    by_address: HashMap<IpAddr, u32>,
65    refused: u64,
66    /// Every task started to write refusals: after one takes the count,
67    /// the next refusal starts another, so there can be several a minute.
68    #[cfg(test)]
69    flushers: Vec<tokio::task::JoinHandle<()>>,
70}
71
72/// The start of the minute `now` is in, in UTC.
73pub(crate) fn minute_of(now: OffsetDateTime) -> OffsetDateTime {
74    now.to_offset(time::UtcOffset::UTC)
75        .replace_second(0)
76        .and_then(|t| t.replace_nanosecond(0))
77        .expect("0 is a valid second and nanosecond")
78}
79
80impl Gate {
81    /// A gate that has seen no report.
82    #[must_use]
83    pub fn new(limits: ReportLimits) -> Self {
84        Self {
85            limits,
86            window: Mutex::new(Window::default()),
87        }
88    }
89
90    /// Takes or refuses one report from `source` at `now`. A report whose
91    /// source is not known counts toward the minute's number only.
92    pub(crate) fn admit(&self, source: Option<IpAddr>, now: OffsetDateTime) -> Admission {
93        let minute = minute_of(now);
94        let mut window = self
95            .window
96            .lock()
97            .unwrap_or_else(std::sync::PoisonError::into_inner);
98        let mut earlier = None;
99        if window.minute != Some(minute) {
100            if let Some(before) = window.minute
101                && window.refused > 0
102            {
103                earlier = Some((before, window.refused));
104            }
105            window.minute = Some(minute);
106            window.taken = 0;
107            window.refused = 0;
108            window.by_address.clear();
109        }
110        let from_source = source.and_then(|address| window.by_address.get(&address).copied());
111        let taken = window.taken < self.limits.per_minute
112            && from_source.unwrap_or(0) < self.limits.per_address;
113        if taken {
114            window.taken += 1;
115            // Only a report that is taken adds an address, so the gate
116            // holds no more of them than the minute's number.
117            if let Some(address) = source {
118                *window.by_address.entry(address).or_insert(0) += 1;
119            }
120        } else {
121            window.refused = window.refused.saturating_add(1);
122        }
123        Admission {
124            taken,
125            minute,
126            first_refusal: !taken && window.refused == 1,
127            earlier,
128        }
129    }
130
131    /// The refusals of `minute` that no record holds yet, which the
132    /// caller writes; they are counted here no longer.
133    pub(crate) fn take_refused(&self, minute: OffsetDateTime) -> u64 {
134        let mut window = self
135            .window
136            .lock()
137            .unwrap_or_else(std::sync::PoisonError::into_inner);
138        if window.minute == Some(minute) {
139            std::mem::take(&mut window.refused)
140        } else {
141            0
142        }
143    }
144
145    /// How many addresses the gate holds a count for.
146    #[cfg(test)]
147    pub(crate) fn addresses(&self) -> usize {
148        self.window.lock().expect("the window").by_address.len()
149    }
150
151    /// Keeps a task that writes a minute's refusals, beside any kept
152    /// before, so a test can wait for each of them.
153    #[cfg(test)]
154    pub(crate) fn set_flusher(&self, task: tokio::task::JoinHandle<()>) {
155        self.window.lock().expect("the window").flushers.push(task);
156    }
157
158    /// Waits for every task kept to write refusals, and panics if one did.
159    #[cfg(test)]
160    pub(crate) async fn settled(&self) {
161        let tasks = std::mem::take(&mut self.window.lock().expect("the window").flushers);
162        for task in tasks {
163            task.await.expect("the task that writes the refusals");
164        }
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
171
172    use time::macros::datetime;
173
174    use super::{Gate, ReportLimits, minute_of};
175
176    const NOON: time::OffsetDateTime = datetime!(2026-10-23 12:00:00 UTC);
177
178    fn gate(per_minute: u32, per_address: u32) -> Gate {
179        Gate::new(ReportLimits {
180            per_minute,
181            per_address,
182        })
183    }
184
185    /// A minute's refusals can be written by more than one task: once a
186    /// task takes the count, the next refusal starts another. `settled`
187    /// waits for each of them, the earlier ones too.
188    #[tokio::test]
189    async fn settled_waits_for_every_task_that_writes_refusals() {
190        let gate = std::sync::Arc::new(gate(1, 1));
191        let (release, released) = tokio::sync::oneshot::channel::<()>();
192        gate.set_flusher(tokio::spawn(async move {
193            released.await.expect("released");
194        }));
195        gate.set_flusher(tokio::spawn(async {}));
196        let waiting = std::sync::Arc::clone(&gate);
197        let settled = tokio::spawn(async move { waiting.settled().await });
198        for _ in 0..50 {
199            tokio::task::yield_now().await;
200        }
201        assert!(
202            !settled.is_finished(),
203            "settled is still waiting for the earlier task"
204        );
205        release.send(()).expect("the earlier task waits");
206        tokio::time::timeout(std::time::Duration::from_secs(20), settled)
207            .await
208            .expect("settled once both tasks ended")
209            .expect("settled did not panic");
210    }
211
212    #[tokio::test]
213    #[should_panic(expected = "the task that writes the refusals")]
214    async fn settled_reports_an_earlier_task_that_failed() {
215        let gate = gate(1, 1);
216        gate.set_flusher(tokio::spawn(async { panic!("a write that failed") }));
217        gate.set_flusher(tokio::spawn(async {}));
218        gate.settled().await;
219    }
220
221    #[tokio::test]
222    async fn settled_with_no_task_returns_at_once() {
223        let gate = gate(1, 1);
224        tokio::time::timeout(std::time::Duration::from_secs(20), gate.settled())
225            .await
226            .expect("nothing to wait for");
227    }
228
229    /// An RFC 5737 address.
230    fn address(last: u8) -> Option<IpAddr> {
231        Some(IpAddr::V4(Ipv4Addr::new(192, 0, 2, last)))
232    }
233
234    /// How many of `reports` reports from `source` at `now` are taken.
235    fn taken(gate: &Gate, source: Option<IpAddr>, now: time::OffsetDateTime, reports: u32) -> u32 {
236        (0..reports)
237            .map(|_| u32::from(gate.admit(source, now).taken))
238            .sum()
239    }
240
241    #[test]
242    fn the_defaults_are_120_a_minute_and_20_from_one_address() {
243        assert_eq!(ReportLimits::DEFAULT.per_minute, 120, "a minute");
244        assert_eq!(ReportLimits::DEFAULT.per_address, 20, "from one address");
245    }
246
247    #[test]
248    fn a_minute_starts_at_its_first_second_in_utc() {
249        assert_eq!(
250            minute_of(datetime!(2026-10-23 12:00:59.999 UTC)),
251            NOON,
252            "the last instant"
253        );
254        assert_eq!(minute_of(NOON), NOON, "the first instant");
255        assert_eq!(
256            minute_of(datetime!(2026-10-23 14:00:30 +02:00)),
257            NOON,
258            "another offset is the same minute"
259        );
260        // An offset with seconds in it: the instant is 12:00:15 UTC.
261        assert_eq!(
262            minute_of(datetime!(2026-10-23 12:00:45 +00:00:30)),
263            NOON,
264            "the minute is UTC's, not the offset's"
265        );
266    }
267
268    #[test]
269    fn the_first_report_is_taken() {
270        let admission = gate(3, 2).admit(address(1), NOON);
271        assert!(admission.taken, "{admission:?}");
272        assert_eq!(admission.minute, NOON, "its minute");
273        assert!(!admission.first_refusal, "nothing was refused");
274        assert_eq!(admission.earlier, None, "nothing to write");
275    }
276
277    #[test]
278    fn one_address_is_taken_up_to_its_number() {
279        let gate = gate(100, 5);
280        assert_eq!(taken(&gate, address(1), NOON, 5), 5, "the first five");
281    }
282
283    #[test]
284    fn one_address_is_refused_past_its_number() {
285        let gate = gate(100, 5);
286        assert_eq!(taken(&gate, address(1), NOON, 9), 5, "five of nine");
287    }
288
289    #[test]
290    fn another_address_is_taken_when_one_is_refused() {
291        let gate = gate(100, 2);
292        assert_eq!(taken(&gate, address(1), NOON, 4), 2, "the first address");
293        assert_eq!(
294            taken(&gate, address(2), NOON, 4),
295            2,
296            "the second has its own count"
297        );
298    }
299
300    #[test]
301    fn all_addresses_together_are_taken_up_to_the_minutes_number() {
302        let gate = gate(6, 4);
303        let total: u32 = (1..=3).map(|a| taken(&gate, address(a), NOON, 4)).sum();
304        assert_eq!(total, 6, "four, two and none of three addresses' four each");
305    }
306
307    #[test]
308    fn a_report_refused_for_the_minutes_number_uses_none_of_its_addresss() {
309        let gate = gate(2, 2);
310        assert_eq!(taken(&gate, address(1), NOON, 2), 2, "the minute's two");
311        assert_eq!(
312            taken(&gate, address(2), NOON, 3),
313            0,
314            "refused for the minute"
315        );
316        assert_eq!(
317            gate.addresses(),
318            1,
319            "no count is kept for a refused address"
320        );
321    }
322
323    #[test]
324    fn the_gate_keeps_a_count_for_no_more_addresses_than_it_takes_reports() {
325        let gate = gate(10, 1);
326        for last in 0..=255 {
327            gate.admit(address(last), NOON);
328        }
329        assert_eq!(gate.addresses(), 10, "256 addresses, ten reports taken");
330    }
331
332    #[test]
333    fn a_report_with_no_known_source_counts_toward_the_minute_only() {
334        let gate = gate(4, 1);
335        assert_eq!(
336            taken(&gate, None, NOON, 6),
337            4,
338            "the minute's four, with no address's one"
339        );
340    }
341
342    #[test]
343    fn an_ipv6_address_has_a_count_of_its_own() {
344        let gate = gate(100, 1);
345        // An RFC 3849 address.
346        let v6 = Some(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 5)));
347        assert_eq!(taken(&gate, v6, NOON, 3), 1, "its one");
348        assert_eq!(
349            taken(&gate, address(1), NOON, 3),
350            1,
351            "and another address's"
352        );
353    }
354
355    #[test]
356    fn the_first_refusal_of_a_minute_is_marked_and_the_next_is_not() {
357        let gate = gate(1, 1);
358        gate.admit(address(1), NOON);
359        let first = gate.admit(address(1), NOON);
360        let second = gate.admit(address(1), NOON);
361        assert!(!first.taken && first.first_refusal, "{first:?}");
362        assert!(!second.taken && !second.first_refusal, "{second:?}");
363    }
364
365    #[test]
366    fn a_new_minute_takes_reports_again() {
367        let gate = gate(2, 2);
368        assert_eq!(taken(&gate, address(1), NOON, 5), 2, "the first minute");
369        let next = NOON + time::Duration::MINUTE;
370        assert_eq!(taken(&gate, address(1), next, 5), 2, "the next");
371    }
372
373    #[test]
374    fn the_last_instant_of_a_minute_is_still_that_minute() {
375        let gate = gate(1, 1);
376        gate.admit(address(1), NOON);
377        let admission = gate.admit(address(1), datetime!(2026-10-23 12:00:59.999999 UTC));
378        assert!(!admission.taken, "{admission:?}");
379        assert_eq!(admission.minute, NOON, "the same minute");
380    }
381
382    #[test]
383    fn a_new_minute_hands_over_the_refusals_of_the_one_before() {
384        let gate = gate(1, 1);
385        taken(&gate, address(1), NOON, 8);
386        let next = gate.admit(address(1), NOON + time::Duration::MINUTE);
387        assert!(next.taken, "{next:?}");
388        assert_eq!(next.earlier, Some((NOON, 7)), "seven were refused at noon");
389    }
390
391    #[test]
392    fn a_new_minute_counts_its_refusals_from_none() {
393        let gate = gate(1, 1);
394        taken(&gate, address(1), NOON, 4);
395        let next = NOON + time::Duration::MINUTE;
396        gate.admit(address(1), next);
397        let refused = gate.admit(address(1), next);
398        assert!(
399            refused.first_refusal,
400            "the first of the new minute: {refused:?}"
401        );
402        assert_eq!(gate.take_refused(next), 1, "one, not noon's three and one");
403    }
404
405    #[test]
406    fn a_new_minute_after_none_refused_hands_over_nothing() {
407        let gate = gate(5, 5);
408        taken(&gate, address(1), NOON, 3);
409        let next = gate.admit(address(1), NOON + time::Duration::MINUTE);
410        assert_eq!(next.earlier, None, "nothing was refused");
411    }
412
413    #[test]
414    fn refusals_are_handed_over_once() {
415        let gate = gate(1, 1);
416        taken(&gate, address(1), NOON, 4);
417        let next = NOON + time::Duration::MINUTE;
418        assert_eq!(
419            gate.admit(address(1), next).earlier,
420            Some((NOON, 3)),
421            "the first report after"
422        );
423        assert_eq!(gate.admit(address(1), next).earlier, None, "the second");
424        assert_eq!(gate.take_refused(NOON), 0, "and none is left to take");
425    }
426
427    #[test]
428    fn the_refusals_of_a_minute_are_taken_by_naming_it() {
429        let gate = gate(1, 1);
430        taken(&gate, address(1), NOON, 6);
431        assert_eq!(gate.take_refused(NOON), 5, "five refused");
432        assert_eq!(gate.take_refused(NOON), 0, "taken once");
433    }
434
435    #[test]
436    fn taking_the_refusals_of_another_minute_takes_none() {
437        let gate = gate(1, 1);
438        taken(&gate, address(1), NOON, 6);
439        assert_eq!(
440            gate.take_refused(NOON + time::Duration::MINUTE),
441            0,
442            "the next minute"
443        );
444        assert_eq!(
445            gate.take_refused(NOON - time::Duration::MINUTE),
446            0,
447            "the one before"
448        );
449        assert_eq!(gate.take_refused(NOON), 5, "they are still there");
450    }
451
452    #[test]
453    fn taking_from_a_gate_that_saw_no_report_takes_none() {
454        assert_eq!(gate(1, 1).take_refused(NOON), 0, "nothing came");
455    }
456
457    #[test]
458    fn taking_the_refusals_frees_no_place() {
459        let gate = gate(1, 1);
460        taken(&gate, address(1), NOON, 3);
461        gate.take_refused(NOON);
462        let again = gate.admit(address(1), NOON);
463        assert!(!again.taken, "the minute's number is still used");
464        assert!(
465            again.first_refusal,
466            "and it is the first refusal no record holds"
467        );
468        assert_eq!(gate.take_refused(NOON), 1, "counted from there");
469    }
470
471    #[test]
472    fn a_handed_over_minute_is_not_taken_again_by_name() {
473        let gate = gate(1, 1);
474        taken(&gate, address(1), NOON, 4);
475        gate.admit(address(1), NOON + time::Duration::MINUTE);
476        assert_eq!(
477            gate.take_refused(NOON),
478            0,
479            "the new minute's report took them"
480        );
481    }
482
483    #[test]
484    fn a_clock_that_goes_back_starts_a_minute_and_loses_no_refusal() {
485        let gate = gate(1, 1);
486        taken(&gate, address(1), NOON, 3);
487        let before = NOON - time::Duration::MINUTE;
488        let admission = gate.admit(address(1), before);
489        assert!(admission.taken, "{admission:?}");
490        assert_eq!(
491            admission.earlier,
492            Some((NOON, 2)),
493            "noon's two are handed over"
494        );
495    }
496
497    #[test]
498    fn a_limit_of_the_largest_number_takes_every_report() {
499        let gate = gate(u32::MAX, u32::MAX);
500        assert_eq!(taken(&gate, address(1), NOON, 1000), 1000, "all of them");
501    }
502
503    #[test]
504    fn refusals_past_four_thousand_million_are_counted() {
505        let gate = gate(1, 1);
506        gate.admit(address(1), NOON);
507        gate.window.lock().expect("the window").refused = u64::from(u32::MAX);
508        gate.admit(address(1), NOON);
509        assert_eq!(
510            gate.take_refused(NOON),
511            u64::from(u32::MAX) + 1,
512            "more than a u32 holds"
513        );
514    }
515}