autumn-cli 0.10.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
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
//! Turning a set of findings into something a reviewer reads on the pull
//! request — and into JSON for anything downstream.
//!
//! Two rules the shape of this module exists to keep:
//!
//! 1. **Silence is a feature.** A PR with no posture change renders to nothing,
//!    so the workflow has nothing to post.
//! 2. **The reviewer must never have to compute anything.** The report carries
//!    the exact acknowledgment line to paste, already filled in.

use std::fmt::Write as _;

use serde::Serialize;

use super::ack::{ACK_PHRASE, Acknowledgment, CEILING_KEY, short};
use super::diff::{Finding, Severity};

/// HTML marker the workflow greps for so it can *update* its comment instead of
/// appending a new one on every push.
pub const COMMENT_MARKER: &str = "<!-- autumn-posture-gate -->";

/// Longest table this renders per severity section before collapsing the tail
/// into a count. A 200-row table is a table nobody reads.
pub const MAX_ROWS: usize = 25;

/// Everything a report needs to know, assembled by [`super::run_diff`].
#[derive(Debug)]
pub struct Report<'a> {
    pub findings: &'a [Finding],
    /// Digest of the widening findings. A bare marker carries it.
    pub ack_digest: String,
    /// What follows the phrase in the line a reviewer pastes.
    pub marker: String,
    /// Posture digest of the head manifest (what a release would record).
    pub head_posture_digest: String,
    /// The acknowledgment that unblocked this run, when one did.
    pub acknowledged: Option<Acknowledgment>,
    /// No base manifest existed: this is the first run, nothing to compare.
    pub bootstrap: bool,
}

impl Report<'_> {
    /// The findings that block.
    #[must_use]
    pub fn widening(&self) -> Vec<&Finding> {
        self.findings
            .iter()
            .filter(|f| f.severity == Severity::Widening)
            .collect()
    }

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

/// The machine-readable report.
#[derive(Debug, Serialize)]
struct JsonReport<'a> {
    schema: &'static str,
    blocked: bool,
    bootstrap: bool,
    ack_digest: String,
    ack_phrase: Option<String>,
    head_posture_digest: &'a str,
    acknowledged_by_digest: Option<&'a str>,
    acknowledgment_reason: Option<&'a str>,
    counts: Counts,
    findings: Vec<JsonFinding<'a>>,
}

#[derive(Debug, Serialize)]
struct Counts {
    widening: usize,
    neutral: usize,
    narrowing: usize,
}

#[derive(Debug, Serialize)]
struct JsonFinding<'a> {
    kind: &'a str,
    severity: &'a str,
    method: &'a str,
    path: &'a str,
    before: &'a str,
    after: &'a str,
    detail: &'a str,
}

/// The markdown a reviewer reads on the pull request.
///
/// Empty when there is nothing to say — the caller posts nothing rather than
/// posting "no changes".
#[must_use]
pub fn markdown(report: &Report<'_>) -> String {
    if report.findings.is_empty() && !report.bootstrap {
        return String::new();
    }
    let mut out = String::from("### \u{1F6E1}\u{FE0F} Security posture diff\n\n");

    if report.bootstrap {
        out.push_str(
            "No posture baseline was found for the base branch, so there is nothing to \
             compare against yet. Commit the manifest this run produced and the next pull \
             request will be diffed against it.\n\n",
        );
    }

    let widening = report.widening();
    if !widening.is_empty() {
        match &report.acknowledged {
            Some(ack) => {
                let _ = write!(
                    out,
                    "**{} widening change{} \u{2014} acknowledged**",
                    widening.len(),
                    plural(widening.len())
                );
                if let Some(reason) = &ack.reason {
                    let _ = write!(out, " \u{2014} \u{201C}{}\u{201D}", escape(reason));
                }
                out.push_str("\n\n");
            }
            None => {
                let _ = write!(
                    out,
                    "**{} widening change{} \u{2014} acknowledgment required.** This pull \
                     request makes part of the app reachable by more callers than before.\n\n",
                    widening.len(),
                    plural(widening.len())
                );
            }
        }
        // Never truncated. Findings sort by path within a severity, so a capped
        // widening table would let an author bury the real one under
        // twenty-five harmless additions — while the acknowledgment digest
        // still covered it.
        table_all(&mut out, &widening);
    }

    section(
        &mut out,
        "Other changes",
        &by_severity(report.findings, Severity::Neutral),
    );
    section(
        &mut out,
        "Narrowing",
        &by_severity(report.findings, Severity::Narrowing),
    );

    if !widening.is_empty() && report.acknowledged.is_none() {
        let _ = write!(
            out,
            "To acknowledge these changes, comment on this pull request with:\n\n\
             ```\n{ACK_PHRASE} {}\n```\n\n",
            report.marker
        );
        if report.marker.contains(CEILING_KEY) {
            let _ = write!(
                out,
                "This comment approves these findings. It also approves any narrower posture \
                 on these routes. Unrelated pushes keep it valid. A new widening, or a wider \
                 route, needs a new comment.\n\n\
                 For an exact match, use this line instead. Any later change asks again:\n\n\
                 ```\n{ACK_PHRASE} {}\n```\n\n",
                short(&report.ack_digest)
            );
        } else {
            let _ = write!(
                out,
                "The digest names this set of widenings. Unrelated pushes keep it valid. A new \
                 widening needs a new acknowledgment.\n\n"
            );
        }
    }

    let _ = write!(
        out,
        "<sub>posture digest `{}` \u{2022} generated by `autumn routes posture diff`</sub>\
         \n\n{COMMENT_MARKER}\n",
        report.head_posture_digest
    );
    out
}

/// One severity section, omitted entirely when empty.
fn section(out: &mut String, title: &str, findings: &[&Finding]) {
    if findings.is_empty() {
        return;
    }
    let _ = write!(out, "**{title} ({})**\n\n", findings.len());
    table(out, findings);
}

fn by_severity(findings: &[Finding], severity: Severity) -> Vec<&Finding> {
    findings.iter().filter(|f| f.severity == severity).collect()
}

/// Every row, no cap. Used for the widening table, which a reviewer must see
/// in full.
fn table_all(out: &mut String, findings: &[&Finding]) {
    table_capped(out, findings, usize::MAX);
}

/// A markdown table, capped at [`MAX_ROWS`] with the tail collapsed to a count.
fn table(out: &mut String, findings: &[&Finding]) {
    table_capped(out, findings, MAX_ROWS);
}

fn table_capped(out: &mut String, findings: &[&Finding], cap: usize) {
    out.push_str("| Change | Method | Path | Before | After |\n|---|---|---|---|---|\n");
    for f in findings.iter().take(cap) {
        let _ = writeln!(
            out,
            "| {} | `{}` | `{}` | {} | {} |",
            escape(&f.detail),
            escape(&f.method),
            escape(&f.path),
            code(&f.before),
            code(&f.after)
        );
    }
    if findings.len() > cap {
        let _ = write!(out, "\n\u{2026} and {} more.\n", findings.len() - cap);
    }
    out.push('\n');
}

/// Wrap a posture label in code ticks, leaving the "absent"/"none" sentinels
/// as plain words so the table reads as prose where there is no value.
fn code(value: &str) -> String {
    if matches!(value, "absent" | "none" | "not emitted") {
        format!("_{value}_")
    } else {
        format!("`{}`", escape(value))
    }
}

/// Neutralize what would break out of a markdown table cell.
///
/// Manifest values are machine-generated, but a route path, a role name or a
/// CSP value is still app-controlled text landing in a rendered PR comment:
/// a `|` would forge a column and a newline would forge a row. Backticks are
/// stripped rather than escaped, since a value carrying one would otherwise
/// close the code span it is rendered inside.
fn escape(value: &str) -> String {
    // Backslashes first: escaping `|` into `\|` after a literal `\` would
    // produce `\\|`, which GFM renders as a backslash followed by a LIVE cell
    // delimiter — the very breakout this is here to prevent.
    value
        .replace('\\', "\\\\")
        .replace('|', "\\|")
        .replace(['\r', '\n'], " ")
        .replace('`', "'")
}

/// Collapse anything that could start a new line into spaces.
fn one_line(value: &str) -> String {
    value.replace(['\r', '\n'], " ")
}

const fn plural(n: usize) -> &'static str {
    if n == 1 { "" } else { "s" }
}

/// The plain-text rendering for a terminal.
#[must_use]
pub fn text(report: &Report<'_>) -> String {
    if report.findings.is_empty() && !report.bootstrap {
        return String::new();
    }
    let mut out = String::new();
    if report.bootstrap {
        out.push_str("no posture baseline to compare against yet\n");
    }
    for f in report.findings {
        // Same newline stripping as the markdown path. A manifest value that
        // can start a line on stdout can forge a GitHub workflow command
        // (`::error::`, `::add-mask::`) in any job that runs `--format text`.
        let _ = writeln!(
            out,
            "{:<10} {:<7} {}  {} \u{2192} {}  ({})",
            f.severity.as_str(),
            one_line(&f.method),
            one_line(&f.path),
            one_line(&f.before),
            one_line(&f.after),
            one_line(&f.detail)
        );
    }
    if !report.widening().is_empty() {
        out.push('\n');
        match &report.acknowledged {
            Some(ack) => {
                let _ = writeln!(out, "acknowledged: {ACK_PHRASE} {}", ack.digest);
            }
            None => {
                let _ = writeln!(
                    out,
                    "blocked: acknowledge with `{ACK_PHRASE} {}`",
                    report.marker
                );
            }
        }
    }
    out
}

/// The JSON rendering, for anything that wants to consume findings directly.
#[must_use]
pub fn json(report: &Report<'_>) -> String {
    let counts = Counts {
        widening: by_severity(report.findings, Severity::Widening).len(),
        neutral: by_severity(report.findings, Severity::Neutral).len(),
        narrowing: by_severity(report.findings, Severity::Narrowing).len(),
    };
    let document = JsonReport {
        schema: "autumn.posture-diff.v1",
        blocked: report.blocked(),
        bootstrap: report.bootstrap,
        ack_digest: report.ack_digest.clone(),
        // Only meaningful when something is actually waiting to be
        // acknowledged; on a clean run it would be the digest of the empty set.
        ack_phrase: (counts.widening > 0).then(|| format!("{ACK_PHRASE} {}", report.marker)),
        head_posture_digest: &report.head_posture_digest,
        acknowledged_by_digest: report.acknowledged.as_ref().map(|a| a.digest.as_str()),
        acknowledgment_reason: report
            .acknowledged
            .as_ref()
            .and_then(|a| a.reason.as_deref()),
        counts,
        findings: report
            .findings
            .iter()
            .map(|f| JsonFinding {
                kind: f.kind,
                severity: f.severity.as_str(),
                method: &f.method,
                path: &f.path,
                before: &f.before,
                after: &f.after,
                detail: &f.detail,
            })
            .collect(),
    };
    serde_json::to_string_pretty(&document)
        .unwrap_or_else(|e| format!("{{\"error\":\"cannot serialize report: {e}\"}}"))
}

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

    fn finding(kind: &'static str, severity: Severity, path: &str) -> Finding {
        Finding {
            kind,
            severity,
            method: "GET".to_owned(),
            path: path.to_owned(),
            before: "gated (roles: admin)".to_owned(),
            after: "public".to_owned(),
            fingerprint: "class:gated->public".to_owned(),
            detail: "guard removed: gated \u{2192} public".to_owned(),
        }
    }

    fn report(findings: &[Finding], acknowledged: Option<Acknowledgment>) -> Report<'_> {
        Report {
            findings,
            ack_digest: "0123456789abcdef0123".to_owned(),
            marker: short("0123456789abcdef0123"),
            head_posture_digest: "deadbeef".to_owned(),
            acknowledged,
            bootstrap: false,
        }
    }

    #[test]
    fn no_findings_renders_no_markdown_at_all() {
        assert_eq!(markdown(&report(&[], None)), "");
    }

    #[test]
    fn a_widening_finding_names_the_route_and_the_transition() {
        let findings = vec![finding(
            "classification_downgraded",
            Severity::Widening,
            "/admin/users",
        )];
        let md = markdown(&report(&findings, None));
        assert!(md.contains("/admin/users"), "{md}");
        assert!(md.contains("GET"), "{md}");
        assert!(md.contains("gated (roles: admin)"), "{md}");
        assert!(md.contains("public"), "{md}");
        assert!(
            md.contains(COMMENT_MARKER),
            "carries the update marker: {md}"
        );
    }

    #[test]
    fn a_widening_report_prints_the_exact_acknowledgment_line() {
        let findings = vec![finding(
            "classification_downgraded",
            Severity::Widening,
            "/admin/users",
        )];
        let md = markdown(&report(&findings, None));
        assert!(
            md.contains(&format!("{ACK_PHRASE} {}", short("0123456789abcdef0123"))),
            "the reviewer must be able to paste it verbatim: {md}"
        );
    }

    #[test]
    fn an_acknowledged_report_says_so_and_does_not_ask_again() {
        let findings = vec![finding(
            "classification_downgraded",
            Severity::Widening,
            "/admin/users",
        )];
        let ack = Acknowledgment {
            digest: short("0123456789abcdef0123"),
            reason: Some("launch week".to_owned()),
            ceiling: None,
        };
        let md = markdown(&report(&findings, Some(ack)));
        assert!(md.to_lowercase().contains("acknowledged"), "{md}");
        assert!(md.contains("launch week"), "{md}");
        assert!(
            !md.contains("comment on this pull request"),
            "no second ask once acknowledged: {md}"
        );
    }

    #[test]
    fn narrowing_only_changes_render_without_asking_for_acknowledgment() {
        let findings = vec![finding("route_removed", Severity::Narrowing, "/old")];
        let md = markdown(&report(&findings, None));
        assert!(md.contains("/old"), "{md}");
        assert!(
            !md.contains(ACK_PHRASE),
            "nothing to acknowledge, so nothing is asked: {md}"
        );
    }

    #[test]
    fn a_long_annotation_list_is_capped_with_a_tail_count() {
        let findings: Vec<Finding> = (0..MAX_ROWS + 7)
            .map(|i| finding("route_removed", Severity::Narrowing, &format!("/r{i:03}")))
            .collect();
        let md = markdown(&report(&findings, None));
        assert!(md.contains("7 more"), "{md}");
        assert!(md.contains("/r000"), "{md}");
        assert!(!md.contains("/r031"), "beyond the cap: {md}");
    }

    /// The widening table is the one a reviewer is being asked to approve, and
    /// findings sort by path — so a cap would let an author bury the real
    /// widening under twenty-five harmless ones while the acknowledgment digest
    /// still covered it.
    #[test]
    fn the_widening_table_is_never_capped() {
        let mut findings: Vec<Finding> = (0..MAX_ROWS + 5)
            .map(|i| {
                finding(
                    "route_added_open",
                    Severity::Widening,
                    &format!("/aaa{i:03}"),
                )
            })
            .collect();
        findings.push(finding(
            "classification_downgraded",
            Severity::Widening,
            "/zzz-admin",
        ));
        let md = markdown(&report(&findings, None));
        assert!(
            md.contains("/zzz-admin"),
            "the last widening row must survive: {md}"
        );
        assert!(!md.contains("more."), "no tail collapse on widening: {md}");
    }

    #[test]
    fn bootstrap_says_there_is_no_baseline_and_asks_for_nothing() {
        let mut r = report(&[], None);
        r.bootstrap = true;
        let md = markdown(&r);
        assert!(md.to_lowercase().contains("baseline"), "{md}");
        assert!(!md.contains(ACK_PHRASE), "{md}");
    }

    /// Route paths and role names are app-controlled text landing in a rendered
    /// PR comment. A `|` would forge a column, a newline a row, and a backtick
    /// would close the code span it sits inside.
    #[test]
    fn manifest_values_cannot_break_out_of_a_table_cell() {
        let mut f = finding("route_added_open", Severity::Widening, "/a|b");
        f.before = "gated (roles: ad\\min)".to_owned();
        f.after = "pub`lic".to_owned();
        f.detail = "line one\nline two".to_owned();
        let findings = vec![f];
        let md = markdown(&report(&findings, None));

        for line in md.lines().filter(|l| l.starts_with("| ")) {
            // Header, separator and the one data row: five columns each.
            assert_eq!(
                line.matches('|').count() - line.matches("\\|").count(),
                6,
                "a value forged a column: {line}"
            );
        }
        assert!(!md.contains("pub`lic"), "backticks are neutralized: {md}");
        assert!(!md.contains("line one\nline two"), "no forged row: {md}");
    }

    /// The text rendering feeds job logs, where a line starting with `::` is a
    /// GitHub workflow command.
    #[test]
    fn text_rendering_cannot_forge_a_workflow_command() {
        let mut f = finding("route_added_open", Severity::Widening, "/a\n::error::pwned");
        f.detail = "x\n::add-mask::y".to_owned();
        let findings = vec![f];
        let out = text(&report(&findings, None));
        assert!(
            !out.lines().any(|l| l.trim_start().starts_with("::")),
            "no line may start a workflow command: {out}"
        );
    }

    #[test]
    fn json_report_carries_findings_counts_and_the_ack_digest() {
        let findings = vec![
            finding("classification_downgraded", Severity::Widening, "/a"),
            finding("route_removed", Severity::Narrowing, "/b"),
        ];
        let out = json(&report(&findings, None));
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(v["blocked"], true);
        assert_eq!(v["counts"]["widening"], 1);
        assert_eq!(v["counts"]["narrowing"], 1);
        assert_eq!(v["findings"][0]["path"], "/a");
        assert_eq!(v["findings"][0]["severity"], "widening");
        assert_eq!(v["ack_digest"], "0123456789abcdef0123");
        assert!(
            v["ack_phrase"]
                .as_str()
                .unwrap()
                .starts_with("/ack-posture ")
        );
    }

    #[test]
    fn json_report_of_a_clean_run_is_still_valid_json() {
        let out = json(&report(&[], None));
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(v["blocked"], false);
        assert_eq!(v["counts"]["widening"], 0);
        assert!(v["findings"].as_array().unwrap().is_empty());
        assert!(
            v["ack_phrase"].is_null(),
            "nothing is waiting to be acknowledged, so no marker is advertised"
        );
    }

    #[test]
    fn text_rendering_states_the_verdict_in_one_line() {
        let findings = vec![finding(
            "classification_downgraded",
            Severity::Widening,
            "/admin",
        )];
        let out = text(&report(&findings, None));
        assert!(out.contains("/admin"), "{out}");
        assert!(out.to_lowercase().contains("widening"), "{out}");
        assert_eq!(text(&report(&[], None)), "", "silence when nothing changed");
    }

    #[test]
    fn the_report_prints_the_marker_it_was_given() {
        let findings = vec![finding(
            "classification_downgraded",
            Severity::Widening,
            "/admin/users",
        )];
        let mut r = report(&findings, None);
        r.marker = "0123456789abcdef ceiling=GET|%2Fa".to_owned();
        let line = format!("{ACK_PHRASE} {}", r.marker);
        assert!(markdown(&r).contains(&line));
        assert!(text(&r).contains(&line));
        assert!(json(&r).contains("ceiling=GET|%2Fa"));
    }
}