tsafe-cli 1.2.1

Local-first secrets runtime for developers — inject credentials via exec, never shell history or .env files
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
//! `tsafe attest scan` / `tsafe attest run` / `tsafe attest verify` /
//! `tsafe attest key` — attestation subcommands.
//!
//! Wires the [`tsafe_attest`] crate to the `tsafe attest` CLI surface:
//!
//! - `scan` (Phase 3, default-on) — secret + env-authority scanner.
//! - `run` (Phase 4) — env-injection enforcement + RunEvidence emission.
//! - `verify` (Phase 5) — Ed25519 signature verification on RunEvidence.
//! - `key` (Phase 5) — per-profile signing-key management.
//!
//! Each invocation emits a CloudEvents `tsafe.*` envelope to stderr so
//! downstream consumers can see the operation in the audit stream. Phase 4
//! flipped the schema namespace from `algol.*` to `tsafe.*` — see
//! `CHANGELOG.md` and
//! `ecosystem-catalog/portfolio-algol-tsafe-phase4-attest-run-2026-05-21.md`.

use std::path::PathBuf;

use anyhow::{Context, Result};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use chrono::Utc;
use colored::Colorize;
use ed25519_dalek::SigningKey;
use serde::Serialize;
use tsafe_attest::enforce::{enforce, write_run, EnforceOptions};
use tsafe_attest::{scan_repo, FindingKind, ScanReport, Severity};
use tsafe_core::keyring_store;
use tsafe_core::run_evidence::RunEvidence;
use tsafe_core::sign::{
    decode_verifying_key, sign_evidence, signed_from_run_evidence, verify_evidence,
    verify_signed_evidence, VerifyError,
};
use tsafe_core::trust_store::TrustStore;

use crate::cli::{AttestAction, AttestKeyAction, AttestScanFormat, AttestTrustAction};

/// Exit code returned by `tsafe attest verify` when the artifact has no
/// `signature` field. Distinct from a hard error so monitoring tooling
/// can tell "unsigned" apart from "tampered".
pub const VERIFY_EXIT_SIGNATURE_ABSENT: i32 = 5;

/// Exit code returned by `tsafe attest verify` when the embedded
/// signature does not verify under the supplied / embedded pubkey.
pub const VERIFY_EXIT_SIGNATURE_FAILED: i32 = 6;

/// Exit code returned by `tsafe attest verify --require-pinned` when the
/// signing key is not present in the pinned-pubkey trust store. The
/// cryptographic signature may be perfectly valid (TOFU-verifiable) — this
/// exit code specifically signals "valid signature, but from an UNPINNED /
/// untrusted identity", which is the fail-closed outcome `--require-pinned`
/// exists to produce.
pub const VERIFY_EXIT_NOT_PINNED: i32 = 7;

/// Dispatch `tsafe attest <action>`.
pub(crate) fn cmd_attest(profile: &str, action: AttestAction) -> Result<()> {
    match action {
        AttestAction::Scan {
            path,
            strict,
            extra_paths,
            format,
            output,
        } => cmd_attest_scan(path, strict, extra_paths, format, output),
        AttestAction::Run {
            contract,
            emit_run_evidence,
            audit_trail,
            allow_command_override,
            sign_run_evidence,
            no_sign,
            command,
        } => cmd_attest_run(
            profile,
            contract,
            emit_run_evidence,
            audit_trail,
            allow_command_override,
            sign_run_evidence,
            no_sign,
            command,
        ),
        AttestAction::Verify {
            evidence,
            pubkey,
            require_pinned,
        } => cmd_attest_verify(evidence, pubkey, require_pinned),
        AttestAction::Key { action } => cmd_attest_key(profile, action),
        AttestAction::Trust { action } => cmd_attest_trust(action),
    }
}

/// Resolve the operator's choice of `--sign-run-evidence` / `--no-sign`
/// to a concrete boolean. The CLI uses `overrides_with` so at most one
/// of the two is `true` at any time; the remaining state encodes the
/// "operator did not pass either" branch, which selects the default
/// behaviour ("ON when a keyring entry exists, OFF with stderr warning
/// otherwise").
fn resolve_signing_decision(
    profile: &str,
    sign_run_evidence: bool,
    no_sign: bool,
) -> SigningDecision {
    if no_sign {
        SigningDecision::Disabled
    } else if sign_run_evidence {
        SigningDecision::EnabledExplicit
    } else if keyring_store::has_attest_signing_key(profile) {
        SigningDecision::EnabledDefault
    } else {
        SigningDecision::EnabledAutoGenerate
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SigningDecision {
    /// Operator passed `--no-sign`. Emission skips signing.
    Disabled,
    /// Operator passed `--sign-run-evidence` explicitly.
    EnabledExplicit,
    /// Operator passed neither flag and a keyring entry exists.
    EnabledDefault,
    /// Operator passed neither flag and no keyring entry exists. The
    /// CLI auto-generates a key on first use with a stderr warning.
    EnabledAutoGenerate,
}

impl SigningDecision {
    fn should_sign(self) -> bool {
        !matches!(self, SigningDecision::Disabled)
    }
}

/// Wire `tsafe attest run` to the Phase 4 enforcement harness, then
/// (Phase 5) optionally sign the produced `RunEvidence`.
///
/// Loads the contract from `--contract` (default `tsafe.contract.yaml`),
/// strips parent env, injects declared vars, spawns the child, and
/// emits RunEvidence + CloudEvents audit trail. The signing pass
/// happens after `enforce` returns the artifact in memory and BEFORE
/// `enforce` writes it out — so we re-write the artifact ourselves to
/// install the signature.
#[allow(clippy::too_many_arguments)]
fn cmd_attest_run(
    profile: &str,
    contract: Option<PathBuf>,
    emit_run_evidence: Option<PathBuf>,
    audit_trail: Option<PathBuf>,
    allow_command_override: bool,
    sign_run_evidence: bool,
    no_sign: bool,
    command: Vec<String>,
) -> Result<()> {
    if command.is_empty() {
        anyhow::bail!("tsafe attest run requires a command after `--` (see --help)");
    }

    let contract_path = contract.unwrap_or_else(|| PathBuf::from("tsafe.contract.yaml"));
    let output_path = emit_run_evidence.unwrap_or_else(|| PathBuf::from("tsafe-run.json"));
    let audit_events_path =
        audit_trail.unwrap_or_else(|| PathBuf::from("tsafe-audit-events.ndjson"));

    let decision = resolve_signing_decision(profile, sign_run_evidence, no_sign);
    let signing_key: Option<SigningKey> = if decision.should_sign() {
        Some(resolve_signing_key(profile, decision)?)
    } else {
        None
    };

    let options = EnforceOptions {
        contract_path,
        output_path: output_path.clone(),
        audit_events_path,
        command,
        allow_command_override,
    };
    let (evidence, exit_code) = enforce(options).context("tsafe attest run enforcement failed")?;

    if let Some(key) = signing_key {
        let signed = sign_evidence(&evidence, &key).context("Phase 5: sign emitted RunEvidence")?;
        write_run(&signed.evidence, &output_path)
            .context("Phase 5: re-write signed RunEvidence")?;
    } else {
        // --no-sign branch: re-state in stderr that the artifact is
        // not authorship-attested. enforce() already wrote it; nothing
        // more to do.
        eprintln!(
            "{} RunEvidence emitted without an Ed25519 signature (--no-sign).",
            "note:".yellow()
        );
    }

    if exit_code != 0 {
        std::process::exit(exit_code);
    }
    Ok(())
}

fn resolve_signing_key(profile: &str, decision: SigningDecision) -> Result<SigningKey> {
    match decision {
        SigningDecision::EnabledExplicit | SigningDecision::EnabledDefault => {
            let stored = keyring_store::retrieve_attest_signing_key(profile)
                .context("read tsafe-attest signing key from OS credential store")?;
            match stored {
                Some(b64url) => {
                    decode_signing_key(&b64url).context("decode persisted tsafe-attest signing key")
                }
                None => {
                    // Explicit-on with no key: auto-generate with a louder warning so
                    // the operator hears it once.
                    eprintln!(
                        "{} no tsafe-attest signing key found for profile '{profile}'; \
                         generating one now. To pin out of band, run \
                         `tsafe attest key pubkey` after this command.",
                        "warning:".yellow().bold()
                    );
                    generate_and_persist(profile)
                }
            }
        }
        SigningDecision::EnabledAutoGenerate => {
            eprintln!(
                "{} no tsafe-attest signing key found for profile '{profile}'; \
                 generating one on first use (default-sign behaviour). \
                 Pass --no-sign to skip, or pre-provision via \
                 `tsafe attest key generate`.",
                "warning:".yellow().bold()
            );
            generate_and_persist(profile)
        }
        SigningDecision::Disabled => unreachable!("Disabled is handled by the caller"),
    }
}

fn generate_and_persist(profile: &str) -> Result<SigningKey> {
    use rand::rngs::OsRng;
    let key = SigningKey::generate(&mut OsRng);
    let encoded = URL_SAFE_NO_PAD.encode(key.to_bytes());
    keyring_store::store_attest_signing_key(profile, &encoded)
        .context("store auto-generated tsafe-attest signing key")?;
    Ok(key)
}

fn decode_signing_key(b64url: &str) -> Result<SigningKey> {
    let bytes = URL_SAFE_NO_PAD
        .decode(b64url)
        .context("base64url-decode signing key")?;
    if bytes.len() != ed25519_dalek::SECRET_KEY_LENGTH {
        anyhow::bail!(
            "tsafe-attest signing key length mismatch: expected {} bytes, got {}",
            ed25519_dalek::SECRET_KEY_LENGTH,
            bytes.len()
        );
    }
    let array: [u8; ed25519_dalek::SECRET_KEY_LENGTH] =
        bytes.as_slice().try_into().expect("length-checked above");
    Ok(SigningKey::from_bytes(&array))
}

fn cmd_attest_verify(
    evidence_path: PathBuf,
    pubkey: Option<String>,
    require_pinned: bool,
) -> Result<()> {
    let bytes = std::fs::read(&evidence_path)
        .with_context(|| format!("read RunEvidence artifact: {}", evidence_path.display()))?;
    let evidence: RunEvidence = serde_json::from_slice(&bytes)
        .with_context(|| format!("parse RunEvidence artifact: {}", evidence_path.display()))?;

    let signed = match signed_from_run_evidence(evidence) {
        Some(signed) => signed,
        None => {
            eprintln!(
                "{} {} has no `signature` field (exit code {VERIFY_EXIT_SIGNATURE_ABSENT}).",
                "error:".red().bold(),
                evidence_path.display()
            );
            std::process::exit(VERIFY_EXIT_SIGNATURE_ABSENT);
        }
    };

    let result = match &pubkey {
        Some(operator_pubkey) => {
            let key =
                decode_verifying_key(operator_pubkey).context("decode operator-supplied --pubkey")?;
            verify_evidence(&signed, &key)
        }
        None => {
            if !require_pinned {
                eprintln!(
                    "{} verifying with the pubkey embedded in the artifact (TOFU). \
                     Pass --require-pinned (and pin the key with `tsafe attest trust add`) \
                     for a stronger trust posture.",
                    "note:".yellow()
                );
            }
            verify_signed_evidence(&signed)
        }
    };

    // Fail-closed identity gate. The cryptographic check above proves the
    // artifact was signed by the embedded key; this proves the embedded
    // key is one the operator pinned out of band. Both must hold under
    // --require-pinned. Evaluate it BEFORE reporting crypto success so a
    // valid-but-unpinned artifact never prints "verified".
    if require_pinned && matches!(result, Ok(())) {
        let store = TrustStore::load_default().context("load pinned-pubkey trust store")?;
        match store.identity_for_signature(&signed.signature) {
            Some(pin) => {
                eprintln!(
                    "{} signer matches pinned identity '{}'.",
                    "trust:".green().bold(),
                    pin.name
                );
            }
            None => {
                if store.is_empty() {
                    eprintln!(
                        "{} --require-pinned was set but the trust store is empty. \
                         Pin the expected signer with `tsafe attest trust add <name> <pubkey>` \
                         (exit code {VERIFY_EXIT_NOT_PINNED}).",
                        "error:".red().bold()
                    );
                } else {
                    eprintln!(
                        "{} signature is cryptographically valid but the signing key is NOT a \
                         pinned trusted identity (exit code {VERIFY_EXIT_NOT_PINNED}). \
                         Pin it via `tsafe attest trust add <name> {}` if you trust this producer.",
                        "error:".red().bold(),
                        signed.signature.pubkey
                    );
                }
                std::process::exit(VERIFY_EXIT_NOT_PINNED);
            }
        }
    }

    match result {
        Ok(()) => {
            println!(
                "{} {} verified.",
                "ok:".green().bold(),
                evidence_path.display()
            );
            Ok(())
        }
        Err(VerifyError::SignatureAbsent) => {
            // Should be unreachable because we already split out the
            // None branch above, but treat it defensively.
            eprintln!(
                "{} {} has no `signature` field (exit code {VERIFY_EXIT_SIGNATURE_ABSENT}).",
                "error:".red().bold(),
                evidence_path.display()
            );
            std::process::exit(VERIFY_EXIT_SIGNATURE_ABSENT);
        }
        Err(other) => {
            eprintln!(
                "{} {}: {other} (exit code {VERIFY_EXIT_SIGNATURE_FAILED}).",
                "error:".red().bold(),
                evidence_path.display()
            );
            std::process::exit(VERIFY_EXIT_SIGNATURE_FAILED);
        }
    }
}

fn cmd_attest_key(profile: &str, action: AttestKeyAction) -> Result<()> {
    match action {
        AttestKeyAction::Generate { force } => {
            if keyring_store::has_attest_signing_key(profile) && !force {
                anyhow::bail!(
                    "tsafe attest key generate: profile '{profile}' already has a signing key. \
                     Pass --force to overwrite. (`tsafe attest key pubkey` prints the current one.)"
                );
            }
            let key = generate_and_persist(profile)?;
            let pubkey = URL_SAFE_NO_PAD.encode(key.verifying_key().as_bytes());
            println!("{pubkey}");
            eprintln!(
                "{} generated tsafe-attest signing key for profile '{profile}'. \
                 Pubkey above; pin it out of band for downstream verification.",
                "ok:".green().bold()
            );
            Ok(())
        }
        AttestKeyAction::Pubkey => {
            let stored = keyring_store::retrieve_attest_signing_key(profile)
                .context("read tsafe-attest signing key from OS credential store")?;
            let Some(b64url) = stored else {
                anyhow::bail!(
                    "tsafe attest key pubkey: no signing key for profile '{profile}'. \
                     Generate one with `tsafe attest key generate`."
                );
            };
            let key = decode_signing_key(&b64url)?;
            let pubkey = URL_SAFE_NO_PAD.encode(key.verifying_key().as_bytes());
            println!("{pubkey}");
            Ok(())
        }
        AttestKeyAction::Remove => {
            keyring_store::remove_attest_signing_key(profile)
                .context("remove tsafe-attest signing key from OS credential store")?;
            eprintln!(
                "{} removed tsafe-attest signing key for profile '{profile}'.",
                "ok:".green().bold()
            );
            Ok(())
        }
    }
}

fn cmd_attest_trust(action: AttestTrustAction) -> Result<()> {
    use tsafe_core::sign::SIG_ALGO_ED25519;

    let path = TrustStore::default_path();
    match action {
        AttestTrustAction::Add { name, pubkey } => {
            let mut store = TrustStore::load(&path).context("load trust store")?;
            store
                .add(&name, SIG_ALGO_ED25519, &pubkey)
                .context("pin identity")?;
            store.save(&path).context("persist trust store")?;
            eprintln!(
                "{} pinned identity '{name}' in {}.",
                "ok:".green().bold(),
                path.display()
            );
            Ok(())
        }
        AttestTrustAction::List => {
            let store = TrustStore::load(&path).context("load trust store")?;
            if store.is_empty() {
                eprintln!(
                    "{} no pinned identities (store: {}).",
                    "note:".yellow(),
                    path.display()
                );
            } else {
                for pin in &store.pins {
                    println!("{}\t{}\t{}", pin.name, pin.algo, pin.pubkey);
                }
            }
            Ok(())
        }
        AttestTrustAction::Remove { name } => {
            let mut store = TrustStore::load(&path).context("load trust store")?;
            store.remove(&name).context("unpin identity")?;
            store.save(&path).context("persist trust store")?;
            eprintln!(
                "{} removed pinned identity '{name}'.",
                "ok:".green().bold()
            );
            Ok(())
        }
    }
}

fn cmd_attest_scan(
    path: Option<PathBuf>,
    strict: bool,
    extra_paths: Vec<PathBuf>,
    format: AttestScanFormat,
    output: Option<PathBuf>,
) -> Result<()> {
    // Default: scan current directory (per Phase 3 spec — default-on).
    let primary = path.unwrap_or_else(|| PathBuf::from("."));
    let mut targets = vec![primary];
    targets.extend(extra_paths);

    // Scan each target; merge reports into a single ScanReport for output.
    let mut merged: Option<ScanReport> = None;
    for target in &targets {
        let report = scan_repo(target)
            .with_context(|| format!("scan failed for path {}", target.display()))?;
        merged = Some(match merged {
            None => report,
            Some(mut acc) => {
                acc.findings.extend(report.findings);
                acc.observed_env_reads.extend(report.observed_env_reads);
                acc.ci_secret_references.extend(report.ci_secret_references);
                acc.summary.total_findings = acc.findings.len();
                acc.summary.critical = acc
                    .findings
                    .iter()
                    .filter(|f| matches!(f.severity, Severity::Critical))
                    .count();
                acc.summary.high = acc
                    .findings
                    .iter()
                    .filter(|f| matches!(f.severity, Severity::High))
                    .count();
                acc.summary.medium = acc
                    .findings
                    .iter()
                    .filter(|f| matches!(f.severity, Severity::Medium))
                    .count();
                acc.summary.low = acc
                    .findings
                    .iter()
                    .filter(|f| matches!(f.severity, Severity::Low))
                    .count();
                acc.summary.risk_score = acc
                    .findings
                    .iter()
                    .map(|f| f.severity.weight())
                    .sum::<u32>()
                    .min(100);
                acc
            }
        });
    }

    let report = merged.expect("at least one target was scanned");

    // CloudEvents audit emission (stderr).
    emit_scan_cloudevent(&report);

    // Write artifact + summary.
    match format {
        AttestScanFormat::Json => {
            let json = serde_json::to_string_pretty(&report)?;
            if let Some(out) = output {
                tsafe_attest::write_scan(&report, &out)?;
                println!("Wrote scan report to {}", out.display());
            } else {
                println!("{json}");
            }
        }
        AttestScanFormat::Markdown => {
            let md = render_markdown(&report);
            if let Some(out) = output {
                std::fs::write(&out, &md)?;
                println!("Wrote scan report to {}", out.display());
            } else {
                println!("{md}");
            }
        }
        AttestScanFormat::Text => {
            tsafe_attest::print_summary(&report);
        }
    }

    // `--strict`: exit non-zero if any secret-class finding is present.
    if strict && has_secret_finding(&report) {
        // Exit code 2 distinguishes strict-failure from internal error (1)
        // and success (0).
        std::process::exit(2);
    }

    Ok(())
}

fn has_secret_finding(report: &ScanReport) -> bool {
    report.findings.iter().any(|f| {
        matches!(
            f.kind,
            FindingKind::EnvFile | FindingKind::HardcodedSecret | FindingKind::PrivateKey
        )
    })
}

#[derive(Serialize)]
struct ScanCloudEvent<'a> {
    specversion: &'a str,
    id: String,
    source: &'a str,
    #[serde(rename = "type")]
    event_type: &'a str,
    time: chrono::DateTime<chrono::Utc>,
    datacontenttype: &'a str,
    data: ScanCloudEventData<'a>,
}

#[derive(Serialize)]
struct ScanCloudEventData<'a> {
    repo_path: &'a str,
    repo_commit: Option<&'a str>,
    schema: &'a str,
    scanner_version: &'a str,
    total_findings: usize,
    risk_score: u32,
}

/// Emit a CloudEvents 1.0 envelope describing the scan invocation.
///
/// The envelope `type` is `tsafe.scan.v1` per Phase 4 of the algol→tsafe
/// migration. Body is summary-only — full findings live in the report
/// artifact.
fn emit_scan_cloudevent(report: &ScanReport) {
    let event = ScanCloudEvent {
        specversion: "1.0",
        id: uuid::Uuid::new_v4().to_string(),
        source: "tsafe/attest",
        event_type: tsafe_attest::SCAN_SCHEMA,
        time: Utc::now(),
        datacontenttype: "application/json",
        data: ScanCloudEventData {
            repo_path: &report.repo_path,
            repo_commit: report.repo_commit.as_deref(),
            schema: &report.schema,
            scanner_version: &report.scanner_version,
            total_findings: report.summary.total_findings,
            risk_score: report.summary.risk_score,
        },
    };
    if let Ok(json) = serde_json::to_string(&event) {
        // Stderr keeps stdout clean for pipe consumers.
        eprintln!("{json}");
    }
}

fn render_markdown(report: &ScanReport) -> String {
    let mut out = String::new();
    out.push_str("# tsafe attest scan\n\n");
    out.push_str(&format!("- **Repo**: `{}`\n", report.repo_path));
    out.push_str(&format!(
        "- **Commit**: `{}`\n",
        report.repo_commit.as_deref().unwrap_or("unknown")
    ));
    out.push_str(&format!(
        "- **Scanned at**: {}\n",
        report.scanned_at.to_rfc3339()
    ));
    out.push_str(&format!(
        "- **Scanner version**: `{}`\n",
        report.scanner_version
    ));
    out.push_str(&format!("- **Schema**: `{}`\n", report.schema));
    out.push_str("\n## Summary\n\n");
    out.push_str(&format!(
        "- Total findings: {}\n",
        report.summary.total_findings
    ));
    out.push_str(&format!(
        "- Critical: {} | High: {} | Medium: {} | Low: {}\n",
        report.summary.critical, report.summary.high, report.summary.medium, report.summary.low
    ));
    out.push_str(&format!(
        "- Risk score: {}/100\n",
        report.summary.risk_score
    ));

    if !report.findings.is_empty() {
        out.push_str("\n## Findings\n\n");
        out.push_str("| Severity | Kind | File:Line | Name | Message |\n");
        out.push_str("|----------|------|-----------|------|---------|\n");
        for finding in &report.findings {
            let kind = match finding.kind {
                FindingKind::EnvFile => "ENV_FILE",
                FindingKind::HardcodedSecret => "HARDCODED_SECRET",
                FindingKind::PrivateKey => "PRIVATE_KEY",
                FindingKind::CiSecretReference => "CI_SECRET_REFERENCE",
                FindingKind::RuntimeEnvRead => "RUNTIME_ENV_READ",
                FindingKind::UnsafeExport => "UNSAFE_EXPORT",
                FindingKind::RiskyEnvPropagation => "RISKY_ENV_PROPAGATION",
                FindingKind::SecretPlaceholder => "SECRET_PLACEHOLDER",
            };
            out.push_str(&format!(
                "| {} | `{}` | `{}:{}` | `{}` | {} |\n",
                finding.severity.label(),
                kind,
                finding.file,
                finding.line,
                finding.name.as_deref().unwrap_or("-"),
                finding.message.replace('|', "\\|"),
            ));
        }
    }

    out
}