taudit-core 1.0.3

Authority graph, propagation engine, finding rules — no I/O
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! `.taudit-suppressions.yml` — per-finding waivers with audit trail.
//!
//! ## Why
//!
//! Adopters need a way to formally acknowledge specific findings as
//! accepted-risks without forking taudit's rules. Today they have:
//!
//!   * `.tauditignore` — file-level, by finding category. Whole class of
//!     findings disappears in a single file. Coarse.
//!   * `--severity-threshold` — severity floor. Cuts noise but is a global,
//!     not per-finding, decision.
//!   * Starter invariants — positive policy. Says what's required, not
//!     what's accepted.
//!
//! What's missing: per-finding waivers with audit trail. That's what
//! this module implements.
//!
//! ## Format
//!
//! YAML at the repo root (`.taudit-suppressions.yml`) or under
//! `.taudit/suppressions.yml`. Each entry waives one finding by stable
//! fingerprint and carries the operator who accepted it, the reason,
//! and an optional expiry:
//!
//! ```yaml
//! suppressions:
//!   - fingerprint: "5edb30f4db3b5fa3"
//!     rule_id: "untrusted_with_authority"
//!     reason: "Internal-only action; threat-modeled and accepted by security team."
//!     accepted_by: "ryan@example.com"
//!     accepted_at: "2026-04-26"
//!     expires_at: "2026-07-26"  # optional; required for critical waivers
//! ```
//!
//! ## Behaviour
//!
//! For each finding, if its fingerprint matches an active suppression:
//!
//!   * **Downgrade mode (default):** severity drops by one tier
//!     (`Critical -> High -> Medium -> Low -> Info`). The full finding
//!     still appears so audit trail is preserved.
//!   * **Suppress mode:** `extras.suppressed = true` is set; severity
//!     does not change. Consumers can filter on the boolean.
//!
//! In both modes, `extras.original_severity` records the rule-emitted
//! severity, and `extras.suppression_reason` records the operator's
//! justification.
//!
//! ## Hard rules
//!
//! 1. **Critical findings cannot be fully suppressed without `expires_at`.**
//!    A waiver for a Critical finding that lacks `expires_at` is rejected
//!    at load time — the loader returns an error, and `taudit scan` /
//!    `taudit verify` exits non-zero.
//!
//! 2. **Expired waivers do not apply.** When `expires_at` is in the past
//!    relative to the current date, the waiver is skipped and a warning
//!    is emitted: `WARNING: suppression for fingerprint <X> expired on
//!    <date>; finding restored to original severity`.

use serde::{Deserialize, Serialize};

use crate::finding::{downgrade_severity, Finding};

/// Mode controlling how the suppression applicator modifies a matched
/// finding. `Downgrade` (default) drops severity one tier; `Suppress`
/// flips a boolean and leaves severity untouched.
///
/// Configurable per `taudit scan`/`taudit verify` invocation via the
/// `--suppression-mode` CLI flag (or per-entry `mode:` if a future
/// version makes this finer-grained).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SuppressionMode {
    /// Drop severity by one tier (Critical -> High -> ... -> Info).
    /// Default — preserves visibility while reducing the noise.
    #[default]
    Downgrade,
    /// Set `extras.suppressed = true` and leave severity unchanged.
    /// Consumers filter on the boolean. Highest visibility option.
    Suppress,
}

/// One YAML entry under `suppressions:`. Schema is stable — additions
/// are non-breaking, removals require a major taudit version.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Suppression {
    /// 16-char hex fingerprint of the finding being waived. Matches
    /// the value in JSON `findings[].fingerprint`, SARIF
    /// `partialFingerprints[primaryLocationLineHash]`, and CloudEvents
    /// `tauditfindingfingerprint`.
    pub fingerprint: String,

    /// Snake-case rule id (or custom rule id) being waived. Used for
    /// human-readable display and to surface mismatched waivers when a
    /// fingerprint resolves to a different rule than the operator
    /// expected.
    pub rule_id: String,

    /// Operator-supplied justification. Required — a waiver without a
    /// reason is a documentation gap that defeats the audit trail.
    pub reason: String,

    /// Identity of the person who accepted the risk (email, GitHub
    /// handle, employee id — whatever the org uses).
    pub accepted_by: String,

    /// Date the waiver was created. Used by `taudit suppressions review`
    /// to flag waivers older than 90 days for re-review.
    pub accepted_at: String,

    /// Optional expiry date. **Required** when the waived finding is
    /// Critical — see the "Hard rules" section in the module docs.
    /// When absent, the waiver never expires.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
}

/// Top-level configuration loaded from `.taudit-suppressions.yml`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SuppressionConfig {
    #[serde(default)]
    pub suppressions: Vec<Suppression>,
}

/// Errors raised by the loader. `Parse` is the YAML-syntax case;
/// `MissingExpiryForCritical` is the hard-rule violation.
#[derive(Debug, thiserror::Error)]
pub enum SuppressionError {
    #[error("failed to read suppression file {path}: {source}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("failed to parse suppression file {path}: {source}")]
    Parse {
        path: String,
        #[source]
        source: serde_yaml::Error,
    },
    #[error(
        "suppression for fingerprint {fingerprint} (rule {rule_id}) waives a critical finding but has no expires_at — critical waivers must expire"
    )]
    MissingExpiryForCritical {
        fingerprint: String,
        rule_id: String,
    },
}

/// Status surfaced by `taudit suppressions list` / `review` for each
/// loaded entry. Computed against the current date at call time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SuppressionStatus {
    /// `expires_at` is absent or in the future, and the entry was
    /// accepted within the last 90 days.
    Active,
    /// `expires_at` is in the future but within 30 days.
    ExpiringSoon,
    /// `expires_at` is in the past.
    Expired,
    /// No `expires_at` and `accepted_at` is older than 90 days. The
    /// suppression still applies, but `taudit suppressions review`
    /// flags it for human re-evaluation.
    StaleForReview,
}

impl SuppressionConfig {
    /// Load and parse a `.taudit-suppressions.yml` file. Returns an
    /// empty config when the file does not exist (the common case for
    /// unconfigured repos).
    ///
    /// Critical-without-expiry validation runs against `findings_to_check`
    /// when supplied so the loader can fail fast on a misconfiguration
    /// against a known critical fingerprint. Pass `&[]` to skip that
    /// check (useful for the `suppressions list/review` subcommands
    /// which inspect waivers without a scan in flight).
    pub fn load_from_path(path: &std::path::Path) -> Result<Self, SuppressionError> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let content = std::fs::read_to_string(path).map_err(|e| SuppressionError::Io {
            path: path.display().to_string(),
            source: e,
        })?;
        let cfg: SuppressionConfig =
            serde_yaml::from_str(&content).map_err(|e| SuppressionError::Parse {
                path: path.display().to_string(),
                source: e,
            })?;
        Ok(cfg)
    }

    /// Look up the canonical suppression file for `repo_root`. Returns
    /// the first of `<root>/.taudit-suppressions.yml` and
    /// `<root>/.taudit/suppressions.yml` that exists, or `None`.
    pub fn discover(repo_root: &std::path::Path) -> Option<std::path::PathBuf> {
        let primary = repo_root.join(".taudit-suppressions.yml");
        if primary.exists() {
            return Some(primary);
        }
        let fallback = repo_root.join(".taudit/suppressions.yml");
        if fallback.exists() {
            return Some(fallback);
        }
        None
    }

    /// Validate that critical-finding waivers carry `expires_at`.
    /// Call after loading and after computing each finding's
    /// fingerprint so the check has full context.
    ///
    /// `critical_fingerprints` is the set of fingerprints of findings
    /// the current scan considers Critical. A waiver entry that
    /// matches one of those AND lacks `expires_at` produces an error
    /// per the hard rule in module docs.
    pub fn validate_critical_waivers<'a, I>(
        &self,
        critical_fingerprints: I,
    ) -> Result<(), Vec<SuppressionError>>
    where
        I: IntoIterator<Item = &'a str>,
    {
        let critical_set: std::collections::HashSet<&str> =
            critical_fingerprints.into_iter().collect();
        let mut errors = Vec::new();
        for entry in &self.suppressions {
            if entry.expires_at.is_none() && critical_set.contains(entry.fingerprint.as_str()) {
                errors.push(SuppressionError::MissingExpiryForCritical {
                    fingerprint: entry.fingerprint.clone(),
                    rule_id: entry.rule_id.clone(),
                });
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Apply suppressions to a list of findings. Returns the modified
    /// findings AND a list of human-readable warnings (one per expired
    /// waiver that would otherwise have applied, etc.).
    ///
    /// Mutation contract:
    ///   * `Downgrade` mode: matched finding's `severity` drops one
    ///     tier; `extras.original_severity` records the prior tier;
    ///     `extras.suppression_reason` records the operator reason.
    ///   * `Suppress` mode: matched finding's `extras.suppressed = true`,
    ///     `extras.suppression_reason` set, severity untouched.
    ///   * Expired waivers do not apply but emit a warning.
    pub fn apply(
        &self,
        findings: Vec<Finding>,
        mode: SuppressionMode,
        fingerprints: &[String],
        today: chrono::NaiveDate,
    ) -> (Vec<Finding>, Vec<String>) {
        // Index suppressions by fingerprint for O(1) lookup. If two
        // entries share a fingerprint (operator confusion), the first
        // wins — keep the loader's order so behaviour is predictable.
        let mut by_fp: std::collections::HashMap<&str, &Suppression> =
            std::collections::HashMap::with_capacity(self.suppressions.len());
        for entry in &self.suppressions {
            by_fp.entry(entry.fingerprint.as_str()).or_insert(entry);
        }

        let mut warnings = Vec::new();
        let mut out: Vec<Finding> = Vec::with_capacity(findings.len());

        for (i, mut finding) in findings.into_iter().enumerate() {
            let fp = fingerprints.get(i).map(String::as_str);
            let Some(entry) = fp.and_then(|f| by_fp.get(f)) else {
                out.push(finding);
                continue;
            };

            // Expired? Emit a warning, do not apply.
            if let Some(ref expiry) = entry.expires_at {
                if let Ok(expiry_date) = chrono::NaiveDate::parse_from_str(expiry, "%Y-%m-%d") {
                    if expiry_date < today {
                        warnings.push(format!(
                            "WARNING: suppression for fingerprint {} expired on {}; finding restored to original severity",
                            entry.fingerprint, expiry,
                        ));
                        out.push(finding);
                        continue;
                    }
                } else {
                    warnings.push(format!(
                        "WARNING: suppression for fingerprint {} has unparseable expires_at '{}' (expected YYYY-MM-DD); ignoring entry",
                        entry.fingerprint, expiry,
                    ));
                    out.push(finding);
                    continue;
                }
            }

            // Apply.
            let original = finding.severity;
            match mode {
                SuppressionMode::Downgrade => {
                    finding.severity = downgrade_severity(finding.severity);
                }
                SuppressionMode::Suppress => {
                    finding.extras.suppressed = true;
                }
            }
            // Record the pre-application severity exactly once. Both
            // modes participate: Downgrade because severity changed,
            // Suppress because consumers want the "what would this have
            // been" value alongside the suppressed flag.
            if finding.extras.original_severity.is_none()
                && (finding.severity != original || mode == SuppressionMode::Suppress)
            {
                finding.extras.original_severity = Some(original);
            }
            finding.extras.suppression_reason = Some(entry.reason.clone());
            out.push(finding);
        }

        (out, warnings)
    }

    /// Compute the runtime status of a single suppression entry.
    /// Used by `taudit suppressions list` / `review`.
    pub fn status_of(entry: &Suppression, today: chrono::NaiveDate) -> SuppressionStatus {
        if let Some(ref expiry) = entry.expires_at {
            if let Ok(expiry_date) = chrono::NaiveDate::parse_from_str(expiry, "%Y-%m-%d") {
                if expiry_date < today {
                    return SuppressionStatus::Expired;
                }
                let days_left = (expiry_date - today).num_days();
                if days_left <= 30 {
                    return SuppressionStatus::ExpiringSoon;
                }
                return SuppressionStatus::Active;
            }
        }
        // No expiry: check stale-for-review.
        if let Ok(accepted_date) = chrono::NaiveDate::parse_from_str(&entry.accepted_at, "%Y-%m-%d")
        {
            let age_days = (today - accepted_date).num_days();
            if age_days >= 90 {
                return SuppressionStatus::StaleForReview;
            }
        }
        SuppressionStatus::Active
    }
}

impl SuppressionStatus {
    /// One-word label suitable for tabular output.
    pub fn label(self) -> &'static str {
        match self {
            SuppressionStatus::Active => "active",
            SuppressionStatus::ExpiringSoon => "expiring-soon",
            SuppressionStatus::Expired => "expired",
            SuppressionStatus::StaleForReview => "stale-for-review",
        }
    }
}

/// Format and write a suppression entry as a YAML document fragment
/// suitable for appending to `.taudit-suppressions.yml`. Used by
/// `taudit suppressions add`.
pub fn render_entry_yaml(entry: &Suppression) -> String {
    let mut out = String::new();
    out.push_str(&format!("  - fingerprint: \"{}\"\n", entry.fingerprint));
    out.push_str(&format!("    rule_id: \"{}\"\n", entry.rule_id));
    out.push_str(&format!(
        "    reason: \"{}\"\n",
        entry.reason.replace('"', "\\\"")
    ));
    out.push_str(&format!("    accepted_by: \"{}\"\n", entry.accepted_by));
    out.push_str(&format!("    accepted_at: \"{}\"\n", entry.accepted_at));
    if let Some(ref expiry) = entry.expires_at {
        out.push_str(&format!("    expires_at: \"{}\"\n", expiry));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::finding::{
        Finding, FindingCategory, FindingExtras, FindingSource, Recommendation, Severity,
    };
    use chrono::NaiveDate;

    fn finding(severity: Severity, message: &str) -> Finding {
        Finding {
            severity,
            category: FindingCategory::UnpinnedAction,
            path: None,
            nodes_involved: vec![],
            message: message.into(),
            recommendation: Recommendation::Manual {
                action: "fix".into(),
            },
            source: FindingSource::BuiltIn,
            extras: FindingExtras::default(),
        }
    }

    fn today() -> NaiveDate {
        NaiveDate::from_ymd_opt(2026, 4, 26).unwrap()
    }

    #[test]
    fn loader_returns_empty_when_file_missing() {
        let cfg = SuppressionConfig::load_from_path(std::path::Path::new(
            "/nonexistent/path/to/.taudit-suppressions.yml",
        ))
        .expect("missing file should be Ok(empty)");
        assert!(cfg.suppressions.is_empty());
    }

    #[test]
    fn loader_parses_canonical_yaml() {
        let yaml = r#"
suppressions:
  - fingerprint: "5edb30f4db3b5fa3"
    rule_id: "untrusted_with_authority"
    reason: "Internal-only action; threat-modeled and accepted by security team."
    accepted_by: "ryan@example.com"
    accepted_at: "2026-04-26"
    expires_at: "2026-07-26"
  - fingerprint: "a3c8d9e1f2b4c5d6"
    rule_id: "long_lived_credential"
    reason: "External SaaS does not support OIDC yet; rotation policy in place."
    accepted_by: "ryan@example.com"
    accepted_at: "2026-04-26"
"#;
        let dir = tempdir();
        let path = dir.join(".taudit-suppressions.yml");
        std::fs::write(&path, yaml).unwrap();
        let cfg = SuppressionConfig::load_from_path(&path).expect("parse OK");
        assert_eq!(cfg.suppressions.len(), 2);
        assert_eq!(cfg.suppressions[0].fingerprint, "5edb30f4db3b5fa3");
        assert_eq!(
            cfg.suppressions[0].expires_at.as_deref(),
            Some("2026-07-26")
        );
        assert!(cfg.suppressions[1].expires_at.is_none());
    }

    #[test]
    fn discover_finds_root_then_dot_taudit() {
        let dir = tempdir();
        // Neither present.
        assert!(SuppressionConfig::discover(&dir).is_none());
        // Just .taudit/suppressions.yml present.
        std::fs::create_dir_all(dir.join(".taudit")).unwrap();
        std::fs::write(dir.join(".taudit/suppressions.yml"), "suppressions: []").unwrap();
        assert_eq!(
            SuppressionConfig::discover(&dir).unwrap(),
            dir.join(".taudit/suppressions.yml")
        );
        // Root file takes precedence.
        std::fs::write(dir.join(".taudit-suppressions.yml"), "suppressions: []").unwrap();
        assert_eq!(
            SuppressionConfig::discover(&dir).unwrap(),
            dir.join(".taudit-suppressions.yml")
        );
    }

    #[test]
    fn downgrade_mode_drops_severity_one_tier_and_records_original() {
        let entry = Suppression {
            fingerprint: "deadbeef00000000".into(),
            rule_id: "unpinned_action".into(),
            reason: "internal action; risk owned by platform team".into(),
            accepted_by: "alice@example.com".into(),
            accepted_at: "2026-04-26".into(),
            expires_at: None,
        };
        let cfg = SuppressionConfig {
            suppressions: vec![entry],
        };

        let f = finding(Severity::High, "msg");
        let fingerprints = vec!["deadbeef00000000".to_string()];
        let (out, warnings) =
            cfg.apply(vec![f], SuppressionMode::Downgrade, &fingerprints, today());
        assert!(warnings.is_empty());
        assert_eq!(out[0].severity, Severity::Medium);
        assert_eq!(out[0].extras.original_severity, Some(Severity::High));
        assert_eq!(
            out[0].extras.suppression_reason.as_deref(),
            Some("internal action; risk owned by platform team")
        );
        assert!(!out[0].extras.suppressed);
    }

    #[test]
    fn suppress_mode_sets_flag_and_does_not_change_severity() {
        let cfg = SuppressionConfig {
            suppressions: vec![Suppression {
                fingerprint: "deadbeef00000000".into(),
                rule_id: "unpinned_action".into(),
                reason: "fork-only build; never publishes".into(),
                accepted_by: "alice@example.com".into(),
                accepted_at: "2026-04-26".into(),
                expires_at: Some("2027-04-26".into()),
            }],
        };
        let f = finding(Severity::High, "msg");
        let fingerprints = vec!["deadbeef00000000".to_string()];
        let (out, _w) = cfg.apply(vec![f], SuppressionMode::Suppress, &fingerprints, today());
        assert_eq!(out[0].severity, Severity::High);
        assert!(out[0].extras.suppressed);
        assert_eq!(out[0].extras.original_severity, Some(Severity::High));
    }

    #[test]
    fn expired_waiver_does_not_apply_and_emits_warning() {
        let cfg = SuppressionConfig {
            suppressions: vec![Suppression {
                fingerprint: "deadbeef00000000".into(),
                rule_id: "unpinned_action".into(),
                reason: "needs to rotate".into(),
                accepted_by: "alice@example.com".into(),
                accepted_at: "2026-01-01".into(),
                expires_at: Some("2026-03-01".into()),
            }],
        };
        let f = finding(Severity::High, "msg");
        let fingerprints = vec!["deadbeef00000000".to_string()];
        let (out, warnings) =
            cfg.apply(vec![f], SuppressionMode::Downgrade, &fingerprints, today());
        // Severity unchanged.
        assert_eq!(out[0].severity, Severity::High);
        // Warning surfaced.
        assert_eq!(warnings.len(), 1);
        assert!(
            warnings[0].contains("expired on 2026-03-01"),
            "unexpected warning: {}",
            warnings[0]
        );
    }

    #[test]
    fn critical_without_expiry_is_rejected_at_validation() {
        let cfg = SuppressionConfig {
            suppressions: vec![Suppression {
                fingerprint: "cafebabecafebabe".into(),
                rule_id: "untrusted_with_authority".into(),
                reason: "no expiry on critical — should be rejected".into(),
                accepted_by: "alice@example.com".into(),
                accepted_at: "2026-04-26".into(),
                expires_at: None,
            }],
        };
        let critical = ["cafebabecafebabe"];
        let result = cfg.validate_critical_waivers(critical.iter().copied());
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        match &errors[0] {
            SuppressionError::MissingExpiryForCritical { fingerprint, .. } => {
                assert_eq!(fingerprint, "cafebabecafebabe");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn critical_with_expiry_passes_validation() {
        let cfg = SuppressionConfig {
            suppressions: vec![Suppression {
                fingerprint: "cafebabecafebabe".into(),
                rule_id: "untrusted_with_authority".into(),
                reason: "approved by security; rotates with quarterly review".into(),
                accepted_by: "alice@example.com".into(),
                accepted_at: "2026-04-26".into(),
                expires_at: Some("2026-07-26".into()),
            }],
        };
        let critical = ["cafebabecafebabe"];
        cfg.validate_critical_waivers(critical.iter().copied())
            .expect("expiring waiver should pass");
    }

    #[test]
    fn status_active_for_recent_no_expiry() {
        let entry = Suppression {
            fingerprint: "x".into(),
            rule_id: "y".into(),
            reason: "z".into(),
            accepted_by: "a".into(),
            accepted_at: "2026-04-01".into(),
            expires_at: None,
        };
        assert_eq!(
            SuppressionConfig::status_of(&entry, today()),
            SuppressionStatus::Active
        );
    }

    #[test]
    fn status_stale_for_review_after_90_days_no_expiry() {
        let entry = Suppression {
            fingerprint: "x".into(),
            rule_id: "y".into(),
            reason: "z".into(),
            accepted_by: "a".into(),
            accepted_at: "2025-12-01".into(),
            expires_at: None,
        };
        assert_eq!(
            SuppressionConfig::status_of(&entry, today()),
            SuppressionStatus::StaleForReview
        );
    }

    #[test]
    fn status_expiring_soon_within_30_days() {
        let entry = Suppression {
            fingerprint: "x".into(),
            rule_id: "y".into(),
            reason: "z".into(),
            accepted_by: "a".into(),
            accepted_at: "2026-04-01".into(),
            expires_at: Some("2026-05-15".into()), // 19 days from 2026-04-26
        };
        assert_eq!(
            SuppressionConfig::status_of(&entry, today()),
            SuppressionStatus::ExpiringSoon
        );
    }

    #[test]
    fn status_expired_after_expiry_date() {
        let entry = Suppression {
            fingerprint: "x".into(),
            rule_id: "y".into(),
            reason: "z".into(),
            accepted_by: "a".into(),
            accepted_at: "2025-01-01".into(),
            expires_at: Some("2026-01-01".into()),
        };
        assert_eq!(
            SuppressionConfig::status_of(&entry, today()),
            SuppressionStatus::Expired
        );
    }

    #[test]
    fn render_entry_yaml_round_trips() {
        let entry = Suppression {
            fingerprint: "5edb30f4db3b5fa3".into(),
            rule_id: "untrusted_with_authority".into(),
            reason: "internal action; risk accepted".into(),
            accepted_by: "alice@example.com".into(),
            accepted_at: "2026-04-26".into(),
            expires_at: Some("2026-07-26".into()),
        };
        let body = render_entry_yaml(&entry);
        let wrapped = format!("suppressions:\n{body}");
        let cfg: SuppressionConfig = serde_yaml::from_str(&wrapped).expect("round-trip parse");
        assert_eq!(cfg.suppressions.len(), 1);
        assert_eq!(cfg.suppressions[0].fingerprint, entry.fingerprint);
        assert_eq!(cfg.suppressions[0].rule_id, entry.rule_id);
        assert_eq!(cfg.suppressions[0].reason, entry.reason);
        assert_eq!(cfg.suppressions[0].expires_at, entry.expires_at);
    }

    /// Per-test scratch directory under the OS temp dir. Avoids the
    /// `tempfile` dependency for a single use site.
    fn tempdir() -> std::path::PathBuf {
        let unique = format!(
            "suppressions-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let dir = std::env::temp_dir().join(unique);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }
}