Skip to main content

quack_rs/
warning.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! Structured security warning API for extensions.
7//!
8//! Extensions that access external resources (network, files, credentials) should
9//! emit structured warnings when potentially unsafe operations occur. This module
10//! provides [`ExtensionWarning`], [`WarningSeverity`], and a thread-safe
11//! [`WarningCollector`] that extensions can use to accumulate warnings during
12//! execution and surface them through a consistent interface (e.g., a `DuckDB`
13//! table function like `__extension_warnings()`).
14//!
15//! # Example
16//!
17//! ```rust
18//! use quack_rs::warning::{ExtensionWarning, WarningSeverity, WarningCollector};
19//!
20//! let collector = WarningCollector::new();
21//!
22//! collector.emit(ExtensionWarning {
23//!     code: "TLS_NO_VERIFY",
24//!     severity: WarningSeverity::High,
25//!     message: "TLS certificate verification is disabled".into(),
26//!     cwe: Some(295),
27//! });
28//!
29//! let warnings = collector.drain();
30//! assert_eq!(warnings.len(), 1);
31//! assert_eq!(warnings[0].code, "TLS_NO_VERIFY");
32//! ```
33
34use std::fmt;
35use std::sync::atomic::{AtomicU64, Ordering};
36use std::sync::{Mutex, MutexGuard, PoisonError};
37
38/// Severity level for extension warnings.
39///
40/// Mirrors common security advisory severity levels, and orders by them:
41/// `Info < Low < Medium < High < Critical`, so `severity >= High` selects the
42/// warnings that need attention.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
44pub enum WarningSeverity {
45    /// Informational — no security impact, but worth noting.
46    Info,
47    /// Low severity — minimal security impact.
48    Low,
49    /// Medium severity — potential security concern.
50    Medium,
51    /// High severity — significant security risk.
52    High,
53    /// Critical severity — immediate action recommended.
54    Critical,
55}
56
57impl fmt::Display for WarningSeverity {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            Self::Info => f.write_str("INFO"),
61            Self::Low => f.write_str("LOW"),
62            Self::Medium => f.write_str("MEDIUM"),
63            Self::High => f.write_str("HIGH"),
64            Self::Critical => f.write_str("CRITICAL"),
65        }
66    }
67}
68
69/// A structured warning emitted by an extension.
70///
71/// Warnings carry a machine-readable `code`, a human-readable `message`, a
72/// [`WarningSeverity`] level, and an optional [CWE](https://cwe.mitre.org/)
73/// identifier for security-related warnings.
74#[derive(Debug, Clone)]
75pub struct ExtensionWarning {
76    /// Machine-readable warning code (e.g., `"TLS_NO_VERIFY"`, `"PLAINTEXT_SECRET"`).
77    pub code: &'static str,
78
79    /// Severity level of this warning.
80    pub severity: WarningSeverity,
81
82    /// Human-readable description of the warning.
83    pub message: String,
84
85    /// Optional [CWE](https://cwe.mitre.org/) identifier (e.g., `295` for
86    /// "Improper Certificate Validation").
87    pub cwe: Option<u32>,
88}
89
90impl fmt::Display for ExtensionWarning {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        write!(f, "[{}] {}: {}", self.severity, self.code, self.message)?;
93        if let Some(cwe) = self.cwe {
94            write!(f, " (CWE-{cwe})")?;
95        }
96        Ok(())
97    }
98}
99
100/// A thread-safe collector for [`ExtensionWarning`]s.
101///
102/// Extensions create a single `WarningCollector` (typically stored in their
103/// global or bind-data state) and call [`emit`][Self::emit] whenever a warning
104/// condition is detected. Warnings can later be surfaced through a table
105/// function (e.g., `SELECT * FROM __extension_warnings()`).
106///
107/// # Thread safety
108///
109/// `WarningCollector` uses a [`Mutex`] internally and is safe to share across
110/// threads via `Arc<WarningCollector>`. A panic on another thread while it held
111/// the lock does not lose warnings: every operation is a single `Vec` call, so
112/// the list is intact, and the collector keeps using it.
113///
114/// # Bounded
115///
116/// A collector keeps at most a limit of warnings between drains
117/// ([`DEFAULT_MAX_WARNINGS`], 10,000, from [`new`][Self::new]; any other with
118/// [`with_limit`][Self::with_limit]). Past it, [`emit`][Self::emit] does not
119/// store the warning but counts it in [`dropped`][Self::dropped], so a
120/// condition reported once per request or row cannot grow the list without
121/// bound in a long-lived process (2,000,000 warnings were 381 MB). The first
122/// warnings are the ones kept.
123///
124/// **Behaviour change** in 0.20.0: before it, every warning was stored, and
125/// a collector never drained grew for as long as the process lived.
126pub struct WarningCollector {
127    warnings: Mutex<Vec<ExtensionWarning>>,
128    /// The most warnings kept at once; later ones are counted, not stored.
129    limit: usize,
130    /// How many warnings were discarded because the collector was full.
131    dropped: AtomicU64,
132}
133
134/// How many warnings a [`WarningCollector::new`] collector keeps before it
135/// starts counting instead of storing.
136///
137/// A warning is emitted by the code that notices the condition, and that code
138/// runs once per request or per row: an extension that warns about every
139/// request made without certificate verification grew the list by about 190
140/// bytes each (380 MB for two million), without bound, for as long as nobody
141/// drained it.
142pub const DEFAULT_MAX_WARNINGS: usize = 10_000;
143
144impl WarningCollector {
145    /// Creates a new, empty `WarningCollector` that keeps at most
146    /// [`DEFAULT_MAX_WARNINGS`] warnings between drains.
147    ///
148    /// Warnings past the limit are counted ([`dropped`][Self::dropped]), not
149    /// stored.
150    #[must_use]
151    pub const fn new() -> Self {
152        Self::with_limit(DEFAULT_MAX_WARNINGS)
153    }
154
155    /// Creates a collector that keeps at most `limit` warnings between drains.
156    #[must_use]
157    pub const fn with_limit(limit: usize) -> Self {
158        Self {
159            warnings: Mutex::new(Vec::new()),
160            limit,
161            dropped: AtomicU64::new(0),
162        }
163    }
164
165    /// How many warnings were discarded because the collector already held
166    /// its limit. [`drain`][Self::drain] and [`clear`][Self::clear] reset it.
167    #[must_use]
168    pub fn dropped(&self) -> u64 {
169        self.dropped.load(Ordering::Relaxed)
170    }
171
172    /// Locks the list, recovering it if a panic poisoned the lock: each
173    /// critical section below is one `Vec` operation, which leaves the `Vec`
174    /// valid even if it panics, so there is nothing to repair.
175    fn lock(&self) -> MutexGuard<'_, Vec<ExtensionWarning>> {
176        self.warnings.lock().unwrap_or_else(PoisonError::into_inner)
177    }
178
179    /// Emits a warning, adding it to the collector, or counting it in
180    /// [`dropped`][Self::dropped] when the collector is full.
181    pub fn emit(&self, warning: ExtensionWarning) {
182        let mut list = self.lock();
183        if list.len() < self.limit {
184            list.push(warning);
185        } else {
186            // Under the lock, so the count always describes the list a
187            // concurrent `drain` takes.
188            self.dropped.fetch_add(1, Ordering::Relaxed);
189        }
190        drop(list);
191    }
192
193    /// Returns the number of warnings currently collected.
194    #[must_use]
195    pub fn len(&self) -> usize {
196        self.lock().len()
197    }
198
199    /// Returns `true` if no warnings have been collected.
200    #[must_use]
201    pub fn is_empty(&self) -> bool {
202        self.len() == 0
203    }
204
205    /// Returns a snapshot of all collected warnings without clearing them.
206    #[must_use]
207    pub fn snapshot(&self) -> Vec<ExtensionWarning> {
208        self.lock().clone()
209    }
210
211    /// Drains all collected warnings, returning them and leaving the collector empty.
212    ///
213    /// Resets [`dropped`][Self::dropped]: read it first to learn how many
214    /// warnings the full collector discarded since the last drain.
215    pub fn drain(&self) -> Vec<ExtensionWarning> {
216        let mut list = self.lock();
217        self.dropped.store(0, Ordering::Relaxed);
218        std::mem::take(&mut *list)
219    }
220
221    /// Clears all collected warnings and resets [`dropped`][Self::dropped].
222    pub fn clear(&self) {
223        let mut list = self.lock();
224        self.dropped.store(0, Ordering::Relaxed);
225        list.clear();
226    }
227}
228
229impl Default for WarningCollector {
230    fn default() -> Self {
231        Self::new()
232    }
233}
234
235// `WarningCollector` is `Send + Sync` automatically: `Mutex<T>` is both when
236// `T: Send`, and `ExtensionWarning` holds only `String`, `&'static str` and
237// `Copy` fields. No `unsafe impl` is involved; this pins the property.
238const _: () = {
239    const fn assert_send_sync<T: Send + Sync>() {}
240    assert_send_sync::<WarningCollector>();
241};
242
243impl core::fmt::Debug for WarningCollector {
244    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
245        // `try_lock`, not `lock`: printing a value must never block, and must
246        // not deadlock when the caller is already inside `emit`.
247        // A poisoned lock still guards an intact list (see `lock`).
248        let guard = match self.warnings.try_lock() {
249            Ok(guard) => Ok(guard),
250            Err(std::sync::TryLockError::Poisoned(poisoned)) => Ok(poisoned.into_inner()),
251            Err(std::sync::TryLockError::WouldBlock) => Err(()),
252        };
253        match guard {
254            Ok(warnings) => f
255                .debug_struct("WarningCollector")
256                .field("warnings", &*warnings)
257                .field("limit", &self.limit)
258                .field("dropped", &self.dropped())
259                .finish(),
260            Err(()) => f
261                .debug_struct("WarningCollector")
262                .field("warnings", &"<locked>")
263                .field("limit", &self.limit)
264                .field("dropped", &self.dropped())
265                .finish(),
266        }
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    fn warning(code: &'static str, severity: WarningSeverity) -> ExtensionWarning {
275        ExtensionWarning {
276            code,
277            severity,
278            message: String::new(),
279            cwe: None,
280        }
281    }
282
283    /// A panic while the lock is held poisons it. The `Vec` behind it is
284    /// still whole (every critical section is a single `Vec` operation), so
285    /// the collector must keep working rather than drop warnings.
286    #[test]
287    fn a_poisoned_lock_does_not_lose_warnings() {
288        let c = WarningCollector::new();
289        c.emit(warning("BEFORE", WarningSeverity::Low));
290        let poisoner = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
291            let _guard = c.warnings.lock();
292            panic!("poison the collector's lock");
293        }));
294        assert!(poisoner.is_err());
295        assert!(c.warnings.is_poisoned());
296
297        c.emit(warning("AFTER", WarningSeverity::High));
298        assert!(format!("{c:?}").contains("AFTER"), "Debug reads through it");
299        assert_eq!(c.len(), 2);
300        assert!(!c.is_empty());
301        let codes: Vec<_> = c.snapshot().iter().map(|w| w.code).collect();
302        assert_eq!(codes, ["BEFORE", "AFTER"]);
303        assert_eq!(c.drain().len(), 2);
304        c.emit(warning("AGAIN", WarningSeverity::Info));
305        c.clear();
306        assert!(c.is_empty());
307    }
308
309    #[test]
310    fn severities_order_from_info_to_critical() {
311        use WarningSeverity::{Critical, High, Info, Low, Medium};
312        assert!(Info < Low && Low < Medium && Medium < High && High < Critical);
313        let mut shuffled = [High, Info, Critical, Low, Medium];
314        shuffled.sort();
315        assert_eq!(shuffled, [Info, Low, Medium, High, Critical]);
316        assert_eq!([Low, Critical, Medium].iter().max(), Some(&Critical));
317    }
318
319    #[test]
320    fn severity_display() {
321        assert_eq!(WarningSeverity::Info.to_string(), "INFO");
322        assert_eq!(WarningSeverity::Low.to_string(), "LOW");
323        assert_eq!(WarningSeverity::Medium.to_string(), "MEDIUM");
324        assert_eq!(WarningSeverity::High.to_string(), "HIGH");
325        assert_eq!(WarningSeverity::Critical.to_string(), "CRITICAL");
326    }
327
328    #[test]
329    fn warning_display_without_cwe() {
330        let w = ExtensionWarning {
331            code: "TEST_WARN",
332            severity: WarningSeverity::Medium,
333            message: "something happened".into(),
334            cwe: None,
335        };
336        assert_eq!(w.to_string(), "[MEDIUM] TEST_WARN: something happened");
337    }
338
339    #[test]
340    fn warning_display_with_cwe() {
341        let w = ExtensionWarning {
342            code: "TLS_NO_VERIFY",
343            severity: WarningSeverity::High,
344            message: "TLS verification disabled".into(),
345            cwe: Some(295),
346        };
347        assert_eq!(
348            w.to_string(),
349            "[HIGH] TLS_NO_VERIFY: TLS verification disabled (CWE-295)"
350        );
351    }
352
353    #[test]
354    fn collector_emit_and_drain() {
355        let c = WarningCollector::new();
356        assert!(c.is_empty());
357        assert_eq!(c.len(), 0);
358
359        c.emit(ExtensionWarning {
360            code: "A",
361            severity: WarningSeverity::Low,
362            message: "first".into(),
363            cwe: None,
364        });
365        c.emit(ExtensionWarning {
366            code: "B",
367            severity: WarningSeverity::High,
368            message: "second".into(),
369            cwe: Some(200),
370        });
371
372        assert_eq!(c.len(), 2);
373        assert!(!c.is_empty());
374
375        let warnings = c.drain();
376        assert_eq!(warnings.len(), 2);
377        assert_eq!(warnings[0].code, "A");
378        assert_eq!(warnings[1].code, "B");
379
380        // After drain, collector should be empty.
381        assert!(c.is_empty());
382    }
383
384    #[test]
385    fn collector_snapshot_does_not_clear() {
386        let c = WarningCollector::new();
387        c.emit(ExtensionWarning {
388            code: "X",
389            severity: WarningSeverity::Info,
390            message: "test".into(),
391            cwe: None,
392        });
393
394        let snap = c.snapshot();
395        assert_eq!(snap.len(), 1);
396        // Snapshot should not clear.
397        assert_eq!(c.len(), 1);
398    }
399
400    #[test]
401    fn collector_clear() {
402        let c = WarningCollector::new();
403        c.emit(ExtensionWarning {
404            code: "Y",
405            severity: WarningSeverity::Critical,
406            message: "urgent".into(),
407            cwe: Some(798),
408        });
409        assert_eq!(c.len(), 1);
410
411        c.clear();
412        assert!(c.is_empty());
413    }
414
415    #[test]
416    fn collector_default() {
417        let c = WarningCollector::default();
418        assert!(c.is_empty());
419    }
420
421    #[test]
422    fn collector_is_send_sync() {
423        fn assert_send_sync<T: Send + Sync>() {}
424        assert_send_sync::<WarningCollector>();
425    }
426
427    #[test]
428    fn severity_clone_eq_hash() {
429        use std::collections::HashSet;
430
431        let s1 = WarningSeverity::High;
432        let s2 = s1;
433        assert_eq!(s1, s2);
434        let mut set = HashSet::new();
435        set.insert(WarningSeverity::Low);
436        set.insert(WarningSeverity::High);
437        assert_eq!(set.len(), 2);
438    }
439
440    #[test]
441    fn collector_drain_returns_in_order() {
442        let c = WarningCollector::new();
443        for i in 0..10 {
444            c.emit(ExtensionWarning {
445                code: "SEQ",
446                severity: WarningSeverity::Info,
447                message: format!("msg-{i}"),
448                cwe: None,
449            });
450        }
451        let warnings = c.drain();
452        assert_eq!(warnings.len(), 10);
453        for (i, w) in warnings.iter().enumerate() {
454            assert_eq!(w.message, format!("msg-{i}"));
455        }
456    }
457
458    #[test]
459    fn collector_clear_then_emit() {
460        let c = WarningCollector::new();
461        c.emit(ExtensionWarning {
462            code: "A",
463            severity: WarningSeverity::Low,
464            message: "first".into(),
465            cwe: None,
466        });
467        c.clear();
468        c.emit(ExtensionWarning {
469            code: "B",
470            severity: WarningSeverity::High,
471            message: "second".into(),
472            cwe: None,
473        });
474        let warnings = c.drain();
475        assert_eq!(warnings.len(), 1);
476        assert_eq!(warnings[0].code, "B");
477    }
478
479    #[test]
480    fn warning_clone() {
481        let w = ExtensionWarning {
482            code: "TEST",
483            severity: WarningSeverity::Critical,
484            message: "important".into(),
485            cwe: Some(798),
486        };
487        let w2 = w.clone();
488        assert_eq!(w.code, w2.code);
489        assert_eq!(w.severity, w2.severity);
490        assert_eq!(w.message, w2.message);
491        assert_eq!(w.cwe, w2.cwe);
492    }
493
494    #[test]
495    fn warning_debug_contains_fields() {
496        let w = ExtensionWarning {
497            code: "DBG",
498            severity: WarningSeverity::Medium,
499            message: "test debug".into(),
500            cwe: Some(100),
501        };
502        let debug = format!("{w:?}");
503        assert!(debug.contains("DBG"));
504        assert!(debug.contains("Medium"));
505        assert!(debug.contains("test debug"));
506        assert!(debug.contains("100"));
507    }
508
509    #[test]
510    fn snapshot_after_drain_is_empty() {
511        let c = WarningCollector::new();
512        c.emit(ExtensionWarning {
513            code: "X",
514            severity: WarningSeverity::Info,
515            message: "test".into(),
516            cwe: None,
517        });
518        let _ = c.drain();
519        let snap = c.snapshot();
520        assert!(snap.is_empty());
521    }
522
523    #[test]
524    fn multiple_drains_second_is_empty() {
525        let c = WarningCollector::new();
526        c.emit(ExtensionWarning {
527            code: "X",
528            severity: WarningSeverity::Info,
529            message: "test".into(),
530            cwe: None,
531        });
532        let first = c.drain();
533        assert_eq!(first.len(), 1);
534        let second = c.drain();
535        assert!(second.is_empty());
536    }
537    /// A collector nobody drains must not grow without bound: past its limit
538    /// a warning is counted, not stored (2,000,000 stored ones were 380 MB).
539    #[test]
540    fn a_full_collector_counts_instead_of_growing() {
541        let c = WarningCollector::with_limit(3);
542        for i in 0..10 {
543            c.emit(warning(
544                if i < 3 { "KEPT" } else { "LOST" },
545                WarningSeverity::Low,
546            ));
547        }
548        assert_eq!(c.len(), 3);
549        assert_eq!(c.dropped(), 7);
550        assert!(c.snapshot().iter().all(|w| w.code == "KEPT"));
551        assert!(format!("{c:?}").contains("dropped: 7"));
552        assert_eq!(c.drain().len(), 3);
553        assert_eq!(c.dropped(), 0, "draining resets the count");
554        c.emit(warning("AGAIN", WarningSeverity::Low));
555        assert_eq!((c.len(), c.dropped()), (1, 0));
556        let full = WarningCollector::with_limit(0);
557        full.emit(warning("X", WarningSeverity::Info));
558        assert_eq!((full.len(), full.dropped()), (0, 1));
559        full.clear();
560        assert_eq!(full.dropped(), 0);
561    }
562
563    #[test]
564    fn the_default_collector_keeps_the_documented_number() {
565        let c = WarningCollector::new();
566        for _ in 0..DEFAULT_MAX_WARNINGS + 5 {
567            c.emit(warning("W", WarningSeverity::Info));
568        }
569        assert_eq!(c.len(), DEFAULT_MAX_WARNINGS);
570        assert_eq!(c.dropped(), 5);
571    }
572}