autumn-cli 0.8.0

CLI tool for the Autumn web framework
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
//! `autumn routes posture` — the review-time gate and the deploy-time proof.
//!
//! [`crate::routes_audit`] (issue #1604) proves *what* an app's security surface
//! is. This module answers the next question: *what did this change do to it,
//! and did a human agree to that?* — plus, at deploy time, *is the manifest in
//! this artifact the one they agreed to?* (issue #1624).
//!
//! Three commands, all pure functions of files on disk:
//!
//! ```text
//! autumn routes posture diff   --base B.json --head H.json   # the PR gate
//! autumn routes posture digest --manifest M.json             # the recorded number
//! autumn routes posture verify --manifest M.json --expect-digest D --repo o/r
//! ```
//!
//! The gate blocks only on *widening*: a new open route, a guard removed or
//! loosened, a classification downgraded. Narrowing and neutral changes
//! annotate and never block, and a pull request that moves nothing renders
//! nothing at all — a gate that cries wolf is a gate that gets turned off.
//!
//! See `docs/guide/posture-gate.md` and `docs/plans/2026-09-03-posture-gate.md`.

use std::fmt::Write as _;

pub mod ack;
pub mod diff;
pub mod model;
pub mod render;
pub mod verify;

use ack::Acknowledgment;
use diff::Finding;
use model::{ManifestError, PostureManifest};
use render::Report;

/// Exit code when a widening posture change is unacknowledged.
pub const EXIT_BLOCKED: i32 = 1;
/// Exit code for a usage or I/O problem — distinct from "the gate blocked" so
/// CI can tell "your PR widens the surface" from "the tool could not run".
pub const EXIT_USAGE: i32 = 2;

/// Options for `autumn routes posture diff`.
#[derive(Debug, Clone)]
pub struct DiffOptions<'a> {
    /// Base (previously accepted) manifest.
    pub base: &'a str,
    /// Head (freshly built) manifest.
    pub head: &'a str,
    /// `markdown` (default), `text`, or `json`.
    pub format: &'a str,
    /// Also write the rendered report here.
    pub output: Option<&'a str>,
    /// Acknowledgment markers passed inline.
    pub acks: &'a [String],
    /// File of harvested pull-request text to scan for acknowledgment markers.
    pub ack_file: Option<&'a str>,
    /// Treat a missing base manifest as "no baseline yet" instead of an error.
    pub allow_missing_base: bool,
}

/// What a diff run concluded, before it is rendered or turned into an exit code.
#[derive(Debug)]
pub struct Evaluation {
    pub findings: Vec<Finding>,
    /// Digest over the widening subset — what an acknowledgment must carry.
    pub ack_digest: String,
    /// Posture digest of the head manifest.
    pub head_posture_digest: String,
    /// The acknowledgment that matched, when one did.
    pub acknowledged: Option<Acknowledgment>,
    /// No base manifest was available.
    pub bootstrap: bool,
}

impl Evaluation {
    /// Whether this run blocks the pull request.
    #[must_use]
    pub fn blocked(&self) -> bool {
        !diff::widening(&self.findings).is_empty() && self.acknowledged.is_none()
    }

    /// The process exit code this evaluation implies.
    #[must_use]
    pub fn exit_code(&self) -> i32 {
        i32::from(self.blocked()) * EXIT_BLOCKED
    }

    fn report(&self) -> Report<'_> {
        Report {
            findings: &self.findings,
            ack_digest: self.ack_digest.clone(),
            head_posture_digest: self.head_posture_digest.clone(),
            acknowledged: self.acknowledged.clone(),
            bootstrap: self.bootstrap,
        }
    }
}

/// Compare two manifests and resolve any acknowledgment against the result.
///
/// `base` is `None` when the project has no accepted baseline yet: the first
/// run on a repository that just enabled the gate reports the posture it found
/// and blocks nothing, because there is no *change* to widen.
#[must_use]
pub fn evaluate(
    base: Option<&PostureManifest>,
    head: &PostureManifest,
    ack_text: &str,
) -> Evaluation {
    let findings = base.map(|b| diff::diff(b, head)).unwrap_or_default();
    let widening = diff::widening(&findings);
    let ack_digest = ack::ack_digest(&widening);
    // Only a widening can be acknowledged. Resolving a marker against a clean
    // run would let a stale comment sit on the pull request claiming to have
    // approved something nobody proposed.
    let acknowledged = if widening.is_empty() {
        None
    } else {
        ack::matching(&ack::parse_acks(ack_text), &ack_digest).cloned()
    };
    Evaluation {
        findings,
        ack_digest,
        head_posture_digest: head.posture_digest(),
        acknowledged,
        bootstrap: base.is_none(),
    }
}

/// Render an evaluation in the requested format.
///
/// Unknown formats are a usage error rather than a silent fallback: a CI job
/// that typos `--format markdwon` must not post a plain-text report and call it
/// a success.
pub fn render(evaluation: &Evaluation, format: &str) -> Result<String, String> {
    let report = evaluation.report();
    match format {
        "markdown" | "md" => Ok(render::markdown(&report)),
        "text" => Ok(render::text(&report)),
        "json" => Ok(render::json(&report)),
        other => Err(format!(
            "unknown --format `{other}` (expected `markdown`, `text`, or `json`)"
        )),
    }
}

/// Collect acknowledgment text from `--ack` values and `--ack-file`.
fn harvested_ack_text(opts: &DiffOptions<'_>) -> Result<String, String> {
    let mut text = String::new();
    for ack in opts.acks {
        // An inline `--ack <digest>` is the phrase, without the ceremony of
        // typing it: normalize it into a marker line so there is exactly one
        // parser for both entry points.
        let _ = writeln!(text, "{} {}", ack::ACK_PHRASE, ack.trim());
    }
    if let Some(path) = opts.ack_file {
        let harvested = std::fs::read_to_string(path)
            .map_err(|e| format!("cannot read acknowledgment file {path}: {e}"))?;
        text.push_str(&harvested);
        text.push('\n');
    }
    Ok(text)
}

/// `autumn routes posture diff`.
#[must_use]
pub fn run_diff(opts: &DiffOptions<'_>) -> i32 {
    let head = match PostureManifest::read(opts.head) {
        Ok(m) => m,
        Err(e) => return fail(&e.to_string()),
    };
    let base = match PostureManifest::read(opts.base) {
        Ok(m) => Some(m),
        // Only a genuinely absent file bootstraps. A base path that exists but
        // cannot be read — a directory, a permissions problem, an interrupted
        // `git show` — is a broken run, and reporting it as the benign
        // "no baseline yet" case would disarm the gate for that run.
        Err(ManifestError::Io { ref source, .. })
            if opts.allow_missing_base && source.kind() == std::io::ErrorKind::NotFound =>
        {
            None
        }
        Err(e) => return fail(&e.to_string()),
    };
    let ack_text = match harvested_ack_text(opts) {
        Ok(t) => t,
        Err(e) => return fail(&e),
    };

    // A head manifest with no routes at all, diffed against a base that had
    // some, scores as a clean surface-*reducing* change — so a partial or
    // failed audit that still wrote a well-formed file would sail through.
    // That is a broken run, not a narrowing.
    if let Some(base_manifest) = &base
        && !base_manifest.dimensions.routes.entries.is_empty()
        && head.dimensions.routes.entries.is_empty()
    {
        return fail(&format!(
            "{} lists no routes at all while {} lists {} \u{2014} refusing to score that as a \
             narrowing. Rebuild the manifest with `autumn routes audit --manifest {}`.",
            opts.head,
            opts.base,
            base_manifest.dimensions.routes.entries.len(),
            opts.head
        ));
    }

    let evaluation = evaluate(base.as_ref(), &head, &ack_text);
    let rendered = match render(&evaluation, opts.format) {
        Ok(r) => r,
        Err(e) => return fail(&e),
    };

    if let Some(path) = opts.output
        && let Err(e) = std::fs::write(path, &rendered)
    {
        return fail(&format!("cannot write report to {path}: {e}"));
    }
    if !rendered.is_empty() {
        println!("{rendered}");
    }

    if evaluation.blocked() {
        eprintln!(
            "\n\u{2717} security posture widened and is not acknowledged.\n  \
             Acknowledge it with this line \u{2014} as a pull-request comment, or \
             locally as `--ack <digest>`:\n\n      {} {}\n",
            ack::ACK_PHRASE,
            ack::short(&evaluation.ack_digest)
        );
    }
    evaluation.exit_code()
}

/// `autumn routes posture digest`.
#[must_use]
pub fn run_digest(manifest: &str, format: &str) -> i32 {
    let digest = match verify::manifest_digest(manifest) {
        Ok(d) => d,
        Err(e) => return fail(&e.to_string()),
    };
    match format {
        "text" => println!("{digest}"),
        "json" => println!(
            "{}",
            serde_json::json!({ "manifest": manifest, "posture_digest": digest })
        ),
        other => {
            return fail(&format!(
                "unknown --format `{other}` (expected `text` or `json`)"
            ));
        }
    }
    0
}

/// `autumn routes posture verify`.
#[must_use]
pub fn run_verify(opts: &verify::VerifyOptions<'_>) -> i32 {
    let report = match verify::verify_with(opts, &verify::GhAttestationVerifier) {
        Ok(r) => r,
        Err(e) => return fail(&e.to_string()),
    };
    println!("\u{1F342} autumn routes posture verify\n");
    println!("  manifest        {}", report.manifest);
    println!("  posture digest  {}", report.posture_digest);
    for check in &report.checks {
        let mark = if check.waived {
            "\u{26A0}"
        } else if check.passed {
            "\u{2713}"
        } else {
            "\u{2717}"
        };
        println!("  {mark} {:<22} {}", check.name, check.detail);
    }
    if report.passed() { 0 } else { EXIT_BLOCKED }
}

/// Print a usage/I/O failure and hand back the exit code for one.
fn fail(message: &str) -> i32 {
    eprintln!("\u{2717} {message}");
    EXIT_USAGE
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(json: &str) -> PostureManifest {
        PostureManifest::parse(json, "test.json").expect("fixture parses")
    }

    fn manifest(routes: &str) -> PostureManifest {
        parse(&format!(
            r#"{{"schema_version":3,"dimensions":{{
                 "routes":{{"provenance":"provable","source":"m","entries":[{routes}]}},
                 "csrf":{{"provenance":"declared","source":"c","exempt_paths":[],"entries":[]}},
                 "security_headers":{{"provenance":"declared","source":"c","entries":[]}},
                 "authorization_policies":{{"provenance":"provable","source":"m","runtime_caveat":"x","entries":[]}}
               }},"excluded":[]}}"#
        ))
    }

    fn route(path: &str, classification: &str, roles: &[&str]) -> String {
        let roles = roles
            .iter()
            .map(|r| format!("\"{r}\""))
            .collect::<Vec<_>>()
            .join(",");
        format!(
            r#"{{"path":"{path}","method":"GET","name":"h","classification":"{classification}",
                 "roles":[{roles}],"scopes":[],"policy":false,"source":"user","provenance":"provable"}}"#
        )
    }

    #[test]
    fn an_unchanged_posture_neither_blocks_nor_says_anything() {
        let base = manifest(&route("/admin", "gated", &["admin"]));
        let head = manifest(&route("/admin", "gated", &["admin"]));
        let e = evaluate(Some(&base), &head, "");
        assert!(!e.blocked());
        assert_eq!(e.exit_code(), 0);
        assert!(e.findings.is_empty());
        assert_eq!(render(&e, "markdown").unwrap(), "");
    }

    #[test]
    fn a_widening_blocks_until_the_matching_marker_is_present() {
        let base = manifest(&route("/admin", "gated", &["admin"]));
        let head = manifest(&route("/admin", "public", &[]));

        let blocked = evaluate(Some(&base), &head, "");
        assert!(blocked.blocked());
        assert_eq!(blocked.exit_code(), EXIT_BLOCKED);

        let comment = format!("{} {}", ack::ACK_PHRASE, ack::short(&blocked.ack_digest));
        let acknowledged = evaluate(Some(&base), &head, &comment);
        assert!(!acknowledged.blocked());
        assert_eq!(acknowledged.exit_code(), 0);
        assert!(acknowledged.acknowledged.is_some());
    }

    /// The acknowledgment is bound to the widening set, so a *later* widening
    /// re-blocks even though the marker is still sitting on the pull request.
    #[test]
    fn re_widening_after_an_acknowledgment_blocks_again() {
        let base = manifest(&route("/admin", "gated", &["admin"]));
        let first = manifest(&route("/admin", "public", &[]));
        let comment = format!(
            "{} {}",
            ack::ACK_PHRASE,
            ack::short(&evaluate(Some(&base), &first, "").ack_digest)
        );
        assert!(!evaluate(Some(&base), &first, &comment).blocked());

        let second = manifest(&format!(
            "{},{}",
            route("/admin", "public", &[]),
            route("/internal", "public", &[])
        ));
        assert!(
            evaluate(Some(&base), &second, &comment).blocked(),
            "a new widening must not inherit the old acknowledgment"
        );
    }

    /// Pushing commits that do not change the widening set keeps the
    /// acknowledgment valid — otherwise every push would re-ask.
    #[test]
    fn an_unrelated_push_keeps_the_acknowledgment_valid() {
        let base = manifest(&route("/admin", "gated", &["admin"]));
        let first = manifest(&route("/admin", "public", &[]));
        let comment = format!(
            "{} {}",
            ack::ACK_PHRASE,
            ack::short(&evaluate(Some(&base), &first, "").ack_digest)
        );

        // A later commit adds a *gated* route: neutral, so the widening set is
        // untouched.
        let later = manifest(&format!(
            "{},{}",
            route("/admin", "public", &[]),
            route("/reports", "gated", &["admin"])
        ));
        let e = evaluate(Some(&base), &later, &comment);
        assert!(!e.blocked());
        assert!(
            e.acknowledged.is_some(),
            "it passes *because* the acknowledgment still matches, not because \
             the widening stopped being detected"
        );
        assert_eq!(diff::widening(&e.findings).len(), 1);
    }

    #[test]
    fn narrowing_only_changes_never_block() {
        let base = manifest(&route("/admin", "public", &[]));
        let head = manifest(&route("/admin", "gated", &["admin"]));
        let e = evaluate(Some(&base), &head, "");
        assert!(!e.blocked());
        assert!(!e.findings.is_empty(), "but they are still reported");
    }

    #[test]
    fn with_no_baseline_nothing_blocks() {
        let head = manifest(&route("/admin", "public", &[]));
        let e = evaluate(None, &head, "");
        assert!(e.bootstrap);
        assert!(!e.blocked());
        assert!(e.findings.is_empty());
        assert_eq!(e.exit_code(), 0);
    }

    #[test]
    fn the_head_posture_digest_is_the_manifests_own() {
        let head = manifest(&route("/admin", "gated", &["admin"]));
        let e = evaluate(None, &head, "");
        assert_eq!(e.head_posture_digest, head.posture_digest());
    }

    #[test]
    fn an_unknown_format_is_a_usage_error_not_a_silent_fallback() {
        let head = manifest(&route("/a", "gated", &["admin"]));
        let e = evaluate(None, &head, "");
        assert!(render(&e, "markdwon").is_err());
    }

    /// A base path that exists but cannot be read is a broken run, not the
    /// benign "no baseline yet" case — reporting it as bootstrap would disarm
    /// the gate for that run, and the scaffolded workflow always passes
    /// `--allow-missing-base`.
    #[test]
    fn an_unreadable_base_is_a_usage_error_even_with_allow_missing_base() {
        let dir = tempfile::tempdir().unwrap();
        let head = dir.path().join("head.json");
        std::fs::write(
            &head,
            serde_json::to_string(&serde_json::json!({
                "schema_version": 3,
                "dimensions": {"routes": {"entries": [
                    {"path": "/a", "method": "GET", "classification": "public"}
                ]}}
            }))
            .unwrap(),
        )
        .unwrap();
        // A directory is present-but-unreadable-as-a-file.
        let base = dir.path().join("base-dir");
        std::fs::create_dir(&base).unwrap();

        let code = run_diff(&DiffOptions {
            base: base.to_str().unwrap(),
            head: head.to_str().unwrap(),
            format: "json",
            output: None,
            acks: &[],
            ack_file: None,
            allow_missing_base: true,
        });
        assert_eq!(code, EXIT_USAGE, "must not be scored as a clean bootstrap");
    }

    /// A head manifest with no routes at all scores as a pure narrowing, so a
    /// partial or failed audit that still wrote a well-formed file would sail
    /// through. Refuse to score it.
    #[test]
    fn an_empty_head_manifest_against_a_populated_base_is_a_usage_error() {
        let dir = tempfile::tempdir().unwrap();
        let base = dir.path().join("base.json");
        let head = dir.path().join("head.json");
        std::fs::write(
            &base,
            serde_json::to_string(&serde_json::json!({
                "schema_version": 3,
                "dimensions": {"routes": {"entries": [
                    {"path": "/a", "method": "GET", "classification": "gated", "roles": ["admin"]}
                ]}}
            }))
            .unwrap(),
        )
        .unwrap();
        std::fs::write(&head, r#"{"schema_version":3}"#).unwrap();

        let code = run_diff(&DiffOptions {
            base: base.to_str().unwrap(),
            head: head.to_str().unwrap(),
            format: "json",
            output: None,
            acks: &[],
            ack_file: None,
            allow_missing_base: true,
        });
        assert_eq!(code, EXIT_USAGE);
    }

    /// `--output` is the flag the scaffolded workflow depends on: it must write
    /// the report, and it must write an *empty* file on a clean run so the
    /// workflow's `[ -s … ]` test decides whether to post.
    #[test]
    fn the_output_flag_writes_the_report_and_writes_nothing_when_clean() {
        let dir = tempfile::tempdir().unwrap();
        let base = dir.path().join("base.json");
        let head = dir.path().join("head.json");
        let report = dir.path().join("report.md");
        let write = |path: &std::path::Path, classification: &str, roles: &str| {
            std::fs::write(
                path,
                format!(
                    r#"{{"schema_version":3,"dimensions":{{"routes":{{"entries":[
                       {{"path":"/admin","method":"GET","classification":"{classification}","roles":[{roles}]}}]}}}}}}"#
                ),
            )
            .unwrap();
        };

        write(&base, "gated", "\"admin\"");
        write(&head, "public", "");
        let opts = DiffOptions {
            base: base.to_str().unwrap(),
            head: head.to_str().unwrap(),
            format: "markdown",
            output: Some(report.to_str().unwrap()),
            acks: &[],
            ack_file: None,
            allow_missing_base: false,
        };
        assert_eq!(run_diff(&opts), EXIT_BLOCKED);
        let written = std::fs::read_to_string(&report).unwrap();
        assert!(written.contains("/admin"), "{written}");
        assert!(written.contains(render::COMMENT_MARKER), "{written}");

        write(&head, "gated", "\"admin\"");
        assert_eq!(run_diff(&opts), 0);
        assert_eq!(
            std::fs::read_to_string(&report).unwrap(),
            "",
            "a clean run leaves nothing for the workflow to post"
        );
    }

    #[test]
    fn an_acknowledgment_for_a_different_digest_does_not_unblock() {
        let base = manifest(&route("/admin", "gated", &["admin"]));
        let head = manifest(&route("/admin", "public", &[]));
        let e = evaluate(Some(&base), &head, "/ack-posture 0000000000000000");
        assert!(e.blocked());
        assert!(e.acknowledged.is_none());
    }
}