tsafe-cli 1.0.26

Secrets runtime for developers — inject credentials into processes via exec, never into shell history or .env files
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
//! Audit log display, HIBP breach-check, chain-coverage, and rotation command handlers.
//!
//! Implements `tsafe audit`, `tsafe audit --explain`, `tsafe audit --hibp`,
//! `tsafe audit verify`, and `tsafe audit rotate` — displaying the per-profile
//! append-only audit log, projecting explanations without secret names, checking
//! secret values against Have I Been Pwned using k-anonymity (only the first 5
//! SHA-1 hex chars leave the machine), reporting HMAC chain coverage, and rotating
//! the log file into gzip-compressed archives.

use std::path::Path;

use anyhow::Result;
use colored::Colorize;
use tsafe_core::{
    audit::AuditStatus,
    audit_explain::{
        AuditSession, AuditTimeline, ExecutionAuthoritySummary, ExecutionGap,
        ExplainedAuditOperation, ExplainedOperationKind, SessionBoundary,
    },
    contracts::AuthorityTargetDecision,
};

use crate::helpers::*;

pub(crate) fn cmd_audit(
    profile: &str,
    limit: usize,
    hibp: bool,
    explain: bool,
    json: bool,
    cell_id: Option<&str>,
) -> Result<()> {
    if hibp {
        return cmd_audit_hibp(profile);
    }
    if explain {
        return cmd_audit_explain(profile, limit, json);
    }

    let mut entries = audit(profile).read(Some(limit))?;

    // Filter by CellOS cell_id if requested.
    if let Some(cid) = cell_id {
        entries.retain(|e| {
            e.context
                .as_ref()
                .and_then(|ctx| ctx.cellos.as_ref())
                .map(|c| c.cellos_cell_id == cid)
                .unwrap_or(false)
        });
    }

    if entries.is_empty() {
        match cell_id {
            Some(cid) => println!(
                "{} No audit entries for profile '{profile}' with cell-id '{cid}'",
                "i".blue()
            ),
            None => println!("{} No audit entries for profile '{profile}'", "i".blue()),
        }
        return Ok(());
    }

    if let Some(cid) = cell_id {
        if json {
            println!("{}", serde_json::to_string_pretty(&entries)?);
            return Ok(());
        }
        println!(
            "{} Audit chain for cell '{}' ({})",
            "i".blue(),
            cid,
            entries.len()
        );
    }

    for e in &entries {
        let status = match e.status {
            AuditStatus::Success => "OK  ".green(),
            AuditStatus::Failure => "FAIL".red(),
        };
        let key = e.key.as_deref().unwrap_or("-");
        let msg = e.message.as_deref().unwrap_or("");
        println!(
            "{} [{}] {:8} {:30} {}",
            e.timestamp.format("%Y-%m-%d %H:%M:%S"),
            status,
            e.operation.cyan(),
            key,
            msg
        );
        if let Some(ctx) = &e.context {
            if let Some(cellos) = &ctx.cellos {
                println!(
                    "       cell_id={} token={}",
                    cellos.cellos_cell_id.dimmed(),
                    cellos.cell_token.as_deref().unwrap_or("-").dimmed()
                );
            }
        }
    }
    Ok(())
}

fn cmd_audit_explain(profile: &str, limit: usize, json: bool) -> Result<()> {
    let entries = audit(profile).read(Some(limit))?;
    let timeline = tsafe_core::audit_explain::explain_entries(&entries);
    if json {
        println!("{}", serde_json::to_string_pretty(&timeline)?);
        return Ok(());
    }
    if entries.is_empty() {
        println!("{} No audit entries for profile '{profile}'", "i".blue());
        return Ok(());
    }
    print_audit_timeline_human(profile, entries.len(), limit, &timeline);
    Ok(())
}

fn print_audit_timeline_human(
    profile: &str,
    entry_count: usize,
    limit: usize,
    timeline: &AuditTimeline,
) {
    println!(
        "{} Audit explanation — profile '{}' — {} session(s), {} audit line(s) loaded (limit {})",
        "i".blue(),
        profile,
        timeline.sessions.len(),
        entry_count,
        limit
    );
    for session in &timeline.sessions {
        print_session(session);
    }
}

fn print_session(session: &AuditSession) {
    let boundary = session_boundary_label(session.boundary);
    println!();
    println!(
        "{} Session {}{}{}{}",
        "".cyan().bold(),
        session.session_index + 1,
        session.profile,
        session.start.format("%Y-%m-%d %H:%M:%S UTC"),
        session.end.format("%Y-%m-%d %H:%M:%S UTC")
    );
    println!(
        "  Boundary: {}  ops: {}  exec: {}  failures: {}",
        boundary, session.operation_count, session.exec_count, session.failure_count
    );
    for op in &session.operations {
        print_operation(op);
    }
}

fn print_operation(op: &ExplainedAuditOperation) {
    let status = match op.status {
        AuditStatus::Success => "OK  ".green(),
        AuditStatus::Failure => "FAIL".red(),
    };
    let kind = explained_kind_display(op.kind);
    println!(
        "{} [{}] {:12} {:24} {}",
        op.timestamp.format("%Y-%m-%d %H:%M:%S"),
        status,
        op.operation.cyan(),
        kind.dimmed(),
        op.message.as_deref().unwrap_or("")
    );
    if let Some(ref k) = op.key_ref {
        println!("      key_ref: {}", k.dimmed());
    }
    if let Some(ref auth) = op.authority {
        print_authority(auth);
    }
}

/// Render an exec authority summary as a three-question narrative:
///   1. What authority was granted?
///   2. Why was it allowed?
///   3. What was denied or stripped?
fn print_authority(a: &ExecutionAuthoritySummary) {
    // ── 1. What authority was granted ────────────────────────────────────────
    let mut grant_parts: Vec<String> = Vec::new();
    if let Some(ref c) = a.contract_name {
        grant_parts.push(format!("contract={}", c.cyan()));
    }
    if let Some(ref p) = a.authority_profile {
        grant_parts.push(format!("profile={p}"));
    }
    if let Some(ref n) = a.authority_namespace {
        grant_parts.push(format!("ns={n}"));
    }
    if let Some(t) = a.trust_level {
        grant_parts.push(format!("trust={}", t.as_str()));
    }
    if let Some(i) = a.inherit {
        grant_parts.push(format!("inherit={}", i.as_str()));
    }
    if a.deny_dangerous_env == Some(true) {
        grant_parts.push("deny_dangerous_env".into());
    }
    if a.redact_output == Some(true) {
        grant_parts.push("redact_output".into());
    }
    if let Some(n) = a.network {
        grant_parts.push(format!("network={}", n.as_str()));
    }
    if !grant_parts.is_empty() {
        println!("      {} {}", "granted:".bold(), grant_parts.join("  "));
    }

    if !a.injected_secret_refs.is_empty() {
        println!(
            "      {} {}",
            "injected:".bold(),
            a.injected_secret_refs.join(", ").green()
        );
    } else if a.gaps.contains(&ExecutionGap::MissingInjectedSecretSet) {
        println!(
            "      {} (not recorded — old audit entry)",
            "injected:".bold()
        );
    } else {
        println!("      {} (none)", "injected:".bold());
    }

    if !a.required_secret_refs.is_empty() {
        println!(
            "      {} {}",
            "required:".bold(),
            a.required_secret_refs.join(", ")
        );
    }
    if !a.allowed_secret_refs.is_empty() {
        println!(
            "      {} {} (ceiling)",
            "allowed:".bold(),
            a.allowed_secret_refs.join(", ").dimmed()
        );
    }

    // ── 2. Why was it allowed ─────────────────────────────────────────────────
    if let (Some(ref t), Some(d)) = (&a.target, a.target_decision) {
        let decision = target_decision_label(d);
        let verdict = match d {
            AuthorityTargetDecision::Unconstrained => decision.normal(),
            AuthorityTargetDecision::AllowedExact | AuthorityTargetDecision::AllowedBasename => {
                decision.green()
            }
            AuthorityTargetDecision::MissingTarget | AuthorityTargetDecision::Denied => {
                decision.red()
            }
        };
        let matched = a
            .matched_target
            .as_deref()
            .map(|m| format!(" (matched '{m}')"))
            .unwrap_or_default();
        println!("      {} {t}{verdict}{matched}", "target:".bold());
    } else if let Some(ref t) = a.target {
        println!("      {} {t}", "target:".bold());
    }

    // ── 3. What was denied or stripped ───────────────────────────────────────
    let diff = &a.contract_diff;
    let mut denied: Vec<String> = Vec::new();
    if !diff.unexpected_injected_secret_refs.is_empty() {
        denied.push(format!(
            "injected outside contract: {}",
            diff.unexpected_injected_secret_refs.join(", ")
        ));
    }
    if !diff.missing_required_secret_refs.is_empty() {
        denied.push(format!(
            "required but missing: {}",
            diff.missing_required_secret_refs.join(", ")
        ));
    }
    if diff.target_mismatch {
        denied.push("target did not match contract".into());
    }
    if !diff.dropped_env_names.is_empty() {
        denied.push(format!("stripped: {}", diff.dropped_env_names.join(", ")));
    }
    if !denied.is_empty() {
        println!(
            "      {} {}",
            "denied/stripped:".bold(),
            denied.join(" | ").yellow()
        );
    }

    // gaps — only show if interesting
    let notable_gaps: Vec<&str> = a
        .gaps
        .iter()
        .copied()
        .filter(|g| !matches!(g, ExecutionGap::MissingInjectedSecretSet))
        .map(gap_label)
        .collect();
    if !notable_gaps.is_empty() {
        println!(
            "      {} {}",
            "audit gaps:".bold(),
            notable_gaps.join(", ").dimmed()
        );
    }
}

fn session_boundary_label(b: SessionBoundary) -> &'static str {
    match b {
        SessionBoundary::StartOfLog => "start of log",
        SessionBoundary::UnlockBoundary => "unlock",
        SessionBoundary::TimeGap => "idle gap",
        SessionBoundary::ProfileChange => "profile change",
    }
}

fn explained_kind_label(k: ExplainedOperationKind) -> &'static str {
    match k {
        ExplainedOperationKind::SecretLifecycle => "secret",
        ExplainedOperationKind::VaultLifecycle => "vault",
        ExplainedOperationKind::Execution => "exec",
        ExplainedOperationKind::Session => "session",
        ExplainedOperationKind::Sync => "sync",
        ExplainedOperationKind::Share => "share",
        ExplainedOperationKind::Team => "team",
        ExplainedOperationKind::RotationPolicy => "policy",
        ExplainedOperationKind::CredentialHelper => "git_cred",
        ExplainedOperationKind::Other => "other",
    }
}

fn explained_kind_build_note(k: ExplainedOperationKind) -> Option<&'static str> {
    match k {
        ExplainedOperationKind::Share if !cfg!(feature = "ots-sharing") => {
            Some("compiled out in this build")
        }
        ExplainedOperationKind::CredentialHelper if !cfg!(feature = "git-helpers") => {
            Some("compiled out in this build")
        }
        _ => None,
    }
}

fn explained_kind_display(k: ExplainedOperationKind) -> String {
    let label = explained_kind_label(k);
    match explained_kind_build_note(k) {
        Some(note) => format!("{label} ({note})"),
        None => label.to_string(),
    }
}

fn target_decision_label(d: AuthorityTargetDecision) -> &'static str {
    match d {
        AuthorityTargetDecision::Unconstrained => "unconstrained",
        AuthorityTargetDecision::AllowedExact => "allowed_exact",
        AuthorityTargetDecision::AllowedBasename => "allowed_basename",
        AuthorityTargetDecision::MissingTarget => "missing_target",
        AuthorityTargetDecision::Denied => "denied",
    }
}

fn gap_label(g: ExecutionGap) -> &'static str {
    match g {
        ExecutionGap::MissingExecContext => "missing_exec_context",
        ExecutionGap::MissingContractName => "missing_contract_name",
        ExecutionGap::MissingTarget => "missing_target",
        ExecutionGap::MissingInjectedSecretSet => "missing_injected_secret_set",
        ExecutionGap::MissingTargetDecision => "missing_target_decision",
    }
}

/// Result of scanning an audit log file for HMAC chain coverage.
///
/// Used by both `cmd_audit_verify` and `cmd_doctor` (EC-5) to share a single
/// scan implementation.
///
/// `#[allow(dead_code)]` — `cmd_audit_rotate` and this struct are dispatched from
/// main.rs once the `AuditAction::Rotate` arm is wired by another agent.
#[allow(dead_code)]
pub(crate) struct ChainCoverage {
    pub total: usize,
    pub chained: usize,
    pub unchained: usize,
    pub malformed: usize,
    /// Integer percentage truncated toward zero, e.g. 83 for 83.4%.
    /// `None` when the log file does not exist.
    pub coverage_pct: Option<u8>,
}

/// Scan the audit log at `log_path` and compute chain-coverage statistics.
///
/// Counts entries that carry `prev_entry_hmac` (chained) versus those that
/// do not (pre-chain or session-boundary anchors). Returns `coverage_pct = None`
/// when the file does not exist, indicating no audit log has been written yet.
pub(crate) fn compute_chain_coverage(log_path: &Path) -> ChainCoverage {
    use tsafe_core::audit::AuditEntry;

    if !log_path.exists() {
        return ChainCoverage {
            total: 0,
            chained: 0,
            unchained: 0,
            malformed: 0,
            coverage_pct: None,
        };
    }

    let content = match std::fs::read_to_string(log_path) {
        Ok(c) => c,
        Err(_) => {
            return ChainCoverage {
                total: 0,
                chained: 0,
                unchained: 0,
                malformed: 0,
                coverage_pct: None,
            };
        }
    };

    let mut total: usize = 0;
    let mut chained: usize = 0;
    let mut malformed: usize = 0;

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        match serde_json::from_str::<AuditEntry>(trimmed) {
            Ok(entry) => {
                total += 1;
                if entry.prev_entry_hmac.is_some() {
                    chained += 1;
                }
            }
            Err(_) => {
                malformed += 1;
            }
        }
    }

    let unchained = total - chained;
    let coverage_pct = Some(if total == 0 {
        0u8
    } else {
        (chained as f64 / total as f64 * 100.0) as u8
    });

    ChainCoverage {
        total,
        chained,
        unchained,
        malformed,
        coverage_pct,
    }
}

/// Report HMAC chain coverage for a profile's audit log file.
///
/// Reads every JSON line from the log and counts entries that carry
/// `prev_entry_hmac` (post-C8) versus those that do not (pre-C8 or written
/// at a session boundary where the chain intentionally resets to `None`).
///
/// Cryptographic verification is not possible here: the HMAC key is ephemeral
/// (held only in memory during the session that wrote those entries) and is
/// never persisted.  What this command can assert is *coverage* — what fraction
/// of entries opted into chain linking.
///
/// Exit codes:
///   0 — log is structurally valid (all lines parsed successfully) or empty.
///   2 — at least one line could not be parsed as a JSON audit entry.
pub(crate) fn cmd_audit_verify(profile: &str, json: bool) -> Result<()> {
    use tsafe_core::profile;

    let log_path = profile::audit_log_path(profile);
    let cov = compute_chain_coverage(&log_path);

    if cov.coverage_pct.is_none() {
        // Log file does not exist.
        if json {
            println!(
                "{}",
                serde_json::to_string_pretty(&serde_json::json!({
                    "total": 0,
                    "chained": 0,
                    "unchained": 0,
                    "chain_coverage_pct": 0.0
                }))?
            );
        } else {
            println!(
                "{} Audit log: 0 entries, 0 chained (0%), 0 unchained (pre-C8 or session boundary)",
                "i".blue()
            );
        }
        return Ok(());
    }

    let coverage_float = if cov.total == 0 {
        0.0_f64
    } else {
        cov.chained as f64 / cov.total as f64 * 100.0
    };

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "total": cov.total,
                "chained": cov.chained,
                "unchained": cov.unchained,
                "chain_coverage_pct": (coverage_float * 10.0).round() / 10.0
            }))?
        );
    } else {
        println!(
            "{} Audit log: {} entries, {} chained ({:.0}%), {} unchained (pre-C8 or session boundary)",
            "i".blue(),
            cov.total,
            cov.chained,
            coverage_float,
            cov.unchained
        );
    }

    if cov.malformed > 0 {
        eprintln!(
            "{} {} malformed line(s) could not be parsed — audit log may be corrupted",
            "warn:".yellow().bold(),
            cov.malformed
        );
        std::process::exit(2);
    }

    Ok(())
}

/// Rotate the audit log for `profile`.
///
/// When the log file exceeds `max_size_mb` megabytes:
/// - Existing archives are shifted: `.N.gz` → `.(N+1).gz`, dropping any
///   beyond `keep`.
/// - The live log is gzip-compressed into `.1.gz` (suffixed onto the log
///   path, e.g. `dev.audit.jsonl.1.gz`).
/// - A fresh, empty log file replaces the original.
///
/// When the file is at or below the threshold the command prints a status line
/// and exits with code 0.
///
/// Dispatched from `main.rs` once the `AuditAction::Rotate` arm is wired (the
/// clap definition in cli.rs is already present, added by another agent).
#[allow(dead_code)]
pub(crate) fn cmd_audit_rotate(profile: &str, max_size_mb: u64, keep: u32) -> Result<()> {
    use flate2::write::GzEncoder;
    use flate2::Compression;
    use std::io::Write;
    use tsafe_core::audit::audit_log_size_bytes;
    use tsafe_core::profile;

    let log_path = profile::audit_log_path(profile);
    let size_bytes = audit_log_size_bytes(&log_path)?;
    let size_mb = size_bytes as f64 / 1_048_576.0;
    let threshold_bytes = max_size_mb * 1_048_576;

    if size_bytes <= threshold_bytes {
        println!(
            "{} Audit log is {:.2} MB, below threshold (max: {} MB). No rotation needed.",
            "i".blue(),
            size_mb,
            max_size_mb
        );
        return Ok(());
    }

    // Shift existing archives: .3.gz is deleted (if keep=3), .2.gz → .3.gz, etc.
    // Work from the highest index down to 1 to avoid clobbering a source before it
    // has been moved.
    for n in (1..=keep).rev() {
        let src = archive_path(&log_path, n);
        if !src.exists() {
            continue;
        }
        if n >= keep {
            std::fs::remove_file(&src)?;
        } else {
            let dst = archive_path(&log_path, n + 1);
            std::fs::rename(&src, &dst)?;
        }
    }

    // Compress the current log into .1.gz.
    let archive = archive_path(&log_path, 1);
    {
        let raw = std::fs::read(&log_path)?;
        let archive_file = std::fs::File::create(&archive)?;
        let mut encoder = GzEncoder::new(archive_file, Compression::default());
        encoder.write_all(&raw)?;
        encoder.finish()?;
    }

    // Truncate the live log to zero bytes so a fresh log begins.
    std::fs::write(&log_path, b"")?;

    println!(
        "{} Audit log rotated: {:.2} MB → {}",
        "".green(),
        size_mb,
        archive.display(),
    );

    Ok(())
}

/// Build the path for archive number `n`.
///
/// Given `/path/to/dev.audit.jsonl`, archive 1 is `/path/to/dev.audit.jsonl.1.gz`.
fn archive_path(log_path: &Path, n: u32) -> std::path::PathBuf {
    let mut s = log_path.as_os_str().to_os_string();
    s.push(format!(".{n}.gz"));
    std::path::PathBuf::from(s)
}

/// Check all secret values against Have I Been Pwned using k-anonymity.
/// Only the first 5 chars of the SHA-1 hash are sent — no full hashes or values leave the machine.
fn cmd_audit_hibp(profile: &str) -> Result<()> {
    use sha1::{Digest, Sha1};

    let vault = open_vault(profile)?;
    let all = vault.export_all()?;
    let mut compromised = 0u32;
    let total = all.len();
    let agent = build_http_agent();

    println!("Checking {total} secrets against Have I Been Pwned...\n");

    for (key, value) in &all {
        let mut hasher = Sha1::new();
        hasher.update(value.as_bytes());
        let hash = format!("{:X}", hasher.finalize());
        let prefix = &hash[..5];
        let suffix = &hash[5..];

        let url = format!("https://api.pwnedpasswords.com/range/{prefix}");
        let resp = agent.get(&url).set("User-Agent", "tsafe-HIBP-Check").call();

        match resp {
            Ok(r) => {
                let body = r.into_string().unwrap_or_default();
                let found = body.lines().any(|line| {
                    line.split(':')
                        .next()
                        .map(|s| s.eq_ignore_ascii_case(suffix))
                        .unwrap_or(false)
                });
                if found {
                    println!(
                        "  {} {}: {}",
                        "".red().bold(),
                        key,
                        "COMPROMISED — value found in breach database".red()
                    );
                    compromised += 1;
                }
            }
            Err(e) => {
                eprintln!("  {} {}: HIBP check failed: {}", "?".yellow(), key, e);
            }
        }
    }

    println!();
    if compromised > 0 {
        println!(
            "{} {}/{} secrets found in breach databases — rotate them immediately",
            "".red().bold(),
            compromised,
            total
        );
        std::process::exit(1);
    } else {
        println!(
            "{} {}/{} secrets checked — none found in breach databases",
            "".green(),
            total,
            total
        );
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{explained_kind_build_note, explained_kind_display};
    use tsafe_core::audit_explain::ExplainedOperationKind;

    #[test]
    fn share_kind_reports_when_compiled_out() {
        let note = explained_kind_build_note(ExplainedOperationKind::Share);
        assert_eq!(note.is_some(), !cfg!(feature = "ots-sharing"));
        if !cfg!(feature = "ots-sharing") {
            assert!(explained_kind_display(ExplainedOperationKind::Share).contains("compiled out"));
        }
    }

    #[test]
    fn credential_helper_kind_reports_when_compiled_out() {
        let note = explained_kind_build_note(ExplainedOperationKind::CredentialHelper);
        assert_eq!(note.is_some(), !cfg!(feature = "git-helpers"));
        if !cfg!(feature = "git-helpers") {
            assert!(
                explained_kind_display(ExplainedOperationKind::CredentialHelper)
                    .contains("compiled out")
            );
        }
    }

    // ── HR-5 rotation tests ───────────────────────────────────────────────────

    /// File is 1 KB, threshold is 100 MB → no archive created, original unchanged.
    #[test]
    fn rotate_below_threshold_does_nothing() {
        use super::cmd_audit_rotate;
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        let vault_dir = dir.path().join("vaults");
        std::fs::create_dir_all(&vault_dir).unwrap();

        temp_env::with_var("TSAFE_VAULT_DIR", Some(vault_dir.as_os_str()), || {
            let log_path = tsafe_core::profile::audit_log_path("test");
            if let Some(parent) = log_path.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }
            // Write a small log — well under 100 MB.
            std::fs::write(&log_path, b"small content").unwrap();

            cmd_audit_rotate("test", 100, 3).expect("rotate should succeed");

            // No archive should have been created.
            let archive = super::archive_path(&log_path, 1);
            assert!(
                !archive.exists(),
                "no archive should be created below threshold"
            );

            // Original file is unchanged.
            let content = std::fs::read(&log_path).unwrap();
            assert_eq!(content, b"small content");
        });
    }

    /// File exceeds threshold → `.1.gz` archive created, original emptied.
    #[test]
    fn rotate_above_threshold_creates_archive() {
        use super::cmd_audit_rotate;
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        let vault_dir = dir.path().join("vaults");
        std::fs::create_dir_all(&vault_dir).unwrap();

        temp_env::with_var("TSAFE_VAULT_DIR", Some(vault_dir.as_os_str()), || {
            let log_path = tsafe_core::profile::audit_log_path("test");
            if let Some(parent) = log_path.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }

            // Write any non-empty content; use threshold=0 MB so any non-empty file triggers.
            let payload = b"some audit content";
            std::fs::write(&log_path, payload).unwrap();

            cmd_audit_rotate("test", 0, 3).expect("rotate should succeed");

            let archive = super::archive_path(&log_path, 1);
            assert!(archive.exists(), ".1.gz archive must be created");

            // Original must be empty after rotation.
            let content = std::fs::read(&log_path).unwrap();
            assert!(
                content.is_empty(),
                "original log must be emptied after rotation"
            );

            // Archive must begin with the gzip magic bytes 0x1f 0x8b.
            let gz_bytes = std::fs::read(&archive).unwrap();
            assert!(gz_bytes.len() >= 2, "archive must not be trivially empty");
            assert_eq!(
                &gz_bytes[..2],
                &[0x1f, 0x8b],
                "archive must start with gzip magic"
            );
        });
    }

    /// Run rotation 5 times with keep=3 → only 3 archives exist.
    #[test]
    fn rotate_respects_keep_count() {
        use super::cmd_audit_rotate;
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        let vault_dir = dir.path().join("vaults");
        std::fs::create_dir_all(&vault_dir).unwrap();

        temp_env::with_var("TSAFE_VAULT_DIR", Some(vault_dir.as_os_str()), || {
            let log_path = tsafe_core::profile::audit_log_path("test");
            if let Some(parent) = log_path.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }

            for i in 0..5u8 {
                // Write unique non-empty content each time so rotation triggers.
                std::fs::write(&log_path, format!("content {i}").as_bytes()).unwrap();
                cmd_audit_rotate("test", 0, 3).expect("rotate should succeed");
            }

            // Archives 1, 2, and 3 must exist.
            for n in 1u32..=3 {
                let p = super::archive_path(&log_path, n);
                assert!(
                    p.exists(),
                    "archive .{n}.gz must exist after 5 rotations with keep=3"
                );
            }
            // Archives 4 and 5 must not exist.
            for n in 4u32..=5 {
                let p = super::archive_path(&log_path, n);
                assert!(!p.exists(), "archive .{n}.gz must not exist (keep=3)");
            }
        });
    }

    /// compute_chain_coverage returns None coverage_pct when the log does not exist.
    #[test]
    fn compute_chain_coverage_absent_log_returns_none() {
        use super::compute_chain_coverage;
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        let missing = dir.path().join("missing.jsonl");
        let cov = compute_chain_coverage(&missing);
        assert!(cov.coverage_pct.is_none());
        assert_eq!(cov.total, 0);
    }
}