ebman 0.37.0

k9s-style TUI for AWS Elastic Beanstalk
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
//! `ebman <verb>` non-interactive subcommands.
//!
//! Pre-0.15 every `run_*_cli` lived as an inline `async fn` in
//! `src/main.rs`, which ballooned to 2,600+ lines as the CLI surface
//! grew (audit/explain/lint --fix all landed in 0.14). The 0.14
//! architecture review's #1 finding was the resulting grab-bag.
//!
//! Each verb now lives in its own file under `src/cli/`, exposing
//! `pub async fn run(args: &[String]) -> Result<()>`. `main.rs`
//! dispatches by `argv[1]` and calls the matching `cli::<verb>::run`.
//! Shared CLI-only helpers (the `decide_poll` state machine, the
//! `--fix` dispatch-failure flag, the JSON-string escaper, the
//! cli-arg escaper) live here in `mod.rs`.
//!
//! Convention:
//! - Each module is named after the subcommand (`audit.rs`,
//!   `explain.rs`, ...) and exports exactly one public function:
//!   `pub async fn run(args: &[String]) -> Result<()>`. `args` is
//!   the full `std::env::args()` vector so callers can index from
//!   `args[1]` onwards uniformly.
//! - Exit codes follow the 0.13 CLI charter (locked in
//!   `BACKLOG.md`): 0 ok, 1 aws err, 2 usage err, 3 issues / drift,
//!   4 wait-for-green timeout, 5 auto-rollback fired.
//! - No `println!` inside the TUI alternate screen — these
//!   subcommands run before / outside TUI lifecycle, so plain
//!   stdout/stderr is fine.

pub mod action;
pub mod audit;
pub mod audit_replay;
pub mod completions;
pub mod ctl;
pub mod drift;
pub mod envs;
pub mod explain;
pub mod lint;
pub mod mcp;
pub mod versions;

/// The canonical list of top-level `ebman <subcommand>` names — the
/// single source of truth for the CLI-subcommand *name* axis. `main.rs`
/// dispatches these (and lists them on an unknown-subcommand error);
/// `cli::completions` renders them, and a test pins its `SUBS` to this
/// list so the shell-completion subcommand set can't drift from the real
/// CLI. Per-subcommand flags / sub-verbs aren't mechanically derivable
/// and stay hand-maintained in `completions::SUBS`.
pub const SUBCOMMANDS: &[&str] = &[
    "envs",
    "action",
    "ctl",
    "lint",
    "drift",
    "audit",
    "mcp",
    "explain",
    "versions",
    "completions",
];

/// Re-exports from the shared deploy-poll module. CLI subcommand
/// modules import via `crate::cli::{decide_poll, PollDecision}`;
/// the actual implementations live in `src/deploy_poll.rs` and are
/// shared with the TUI's `spawn_rollout_dispatch`.
pub(crate) use crate::deploy_poll::{decide_poll, PollDecision};

/// Re-exports of the canonical JSON helpers from `crate::util`. CLI
/// subcommand modules import these via `crate::cli::{json_string,
/// cli_esc}` so call-site rewrites are unnecessary; the actual
/// implementations live in `util.rs` and are shared across the
/// crate (lib + bin).
pub(crate) use crate::util::{json_escape as cli_esc, json_string};

/// Cross-process freeze gate for CLI write paths (0.28): refuse when
/// a live TUI session holds `:freeze-deploys` / `:incident START`
/// (pid-scoped marker — see `crate::freeze`). Exit 3, same class as
/// the pin refusal. These paths had the same blind spot the MCP
/// write tools would have had: a fleet frozen mid-incident could
/// still be written from a second terminal.
pub(crate) fn refuse_if_frozen(prog: &str, action_label: &str) {
    if let Some(m) = crate::freeze::read_active() {
        // Audited like every other refusal. This was the one CLI
        // refusal path the `stage=refused` work missed: it exits before
        // reaching `write_refusal`, so a fleet-wide freeze stopping a
        // `lint --fix` run left no trace while a per-env pin stopping
        // the same run left one.
        let refusal = crate::write_gate::Refusal::Frozen;
        crate::audit::append_action_refused(
            None,
            std::env::var("AWS_PROFILE").ok().as_deref(),
            "-",
            action_label,
            "-",
            refusal.rule(),
            &refusal.remedy(),
        );
        eprintln!("{prog}: refusing — {}", crate::freeze::refusal_message(&m));
        std::process::exit(3);
    }
}

/// The write gate: freeze first, then the config pin. Returns the
/// refusal message when the write must not proceed, `None` when clear.
///
/// This began life inside the MCP server, which had the right shape
/// already — a verdict over data passed in, "so the gate stays pure +
/// hermetically testable" — while the three other CLI write paths each
/// composed `refuse_if_frozen` and `pin_reason` by hand. All four DID
/// compose both, so there was no live hole; the problem was that
/// nothing made a fifth path do it. 0.14.1 was a same-day patch for
/// exactly that, `lint --fix` checking one and not the other.
///
/// Promoting the best of the four rather than writing a fifth. It takes
/// its inputs rather than reading them so the MCP server can keep
/// testing it hermetically; `refuse_write` below is the CLI's
/// read-the-world-and-exit wrapper.
pub(crate) fn write_refusal(
    safety_cfg: &crate::config::Config,
    env: &str,
    profile: &Option<String>,
    active_freeze: Option<crate::freeze::FreezeMarker>,
    region: Option<&str>,
    action_label: &str,
) -> Option<String> {
    let (refusal, message, pin_profile) =
        write_refusal_unaudited(safety_cfg, env, profile, active_freeze)?;
    // Record the attempt. Every CLI and MCP write path funnels through
    // here, so this is the one place that sees a refusal on this side.
    //
    // The region is whatever the caller could honestly resolve. These
    // refusals happen BEFORE any AWS client is built, and the rules
    // (freeze, env pin, account pin) are region-independent anyway, so
    // an unknown region is recorded as unknown rather than guessed at
    // as home — a line filed against the wrong region is worse than one
    // that admits it does not know.
    crate::audit::append_action_refused(
        None,
        pin_profile.as_deref(),
        region.unwrap_or("-"),
        action_label,
        env,
        refusal.rule(),
        &refusal.remedy(),
    );
    Some(message)
}

/// Decide and render, with NO side effect — **no audit line**.
///
/// Named for what it omits. This is the half a new enforcement path
/// must NOT reach for: a refusal that leaves no `stage=refused` line is
/// a silent regression to the pre-0.37 blind spot, where a blocked
/// write and no attempt at all looked identical. `write_refusal_paths_are_audited`
/// pins the two callers that are legitimately audit-free.
///
/// Split out because `--demo` must reach the same verdict while writing
/// nothing: a demo MCP server still reads the real cross-process freeze
/// marker, so a demo write attempt during a live incident was appending
/// a real line to the real audit log. Demo's contract is that it touches
/// nothing real, and the refusal being genuine does not change that.
///
/// Returns the refusal, its rendered message, and the profile the pin
/// was resolved against.
pub(crate) fn write_refusal_unaudited(
    safety_cfg: &crate::config::Config,
    env: &str,
    profile: &Option<String>,
    active_freeze: Option<crate::freeze::FreezeMarker>,
) -> Option<(crate::write_gate::Refusal, String, Option<String>)> {
    // The profile fallback is resolved HERE rather than inside the
    // decision, which used to read `AWS_PROFILE` itself — an ambient
    // read that made it impossible to test without touching the process
    // environment. `write_gate::decide` now takes values only.
    let pin_profile = profile
        .clone()
        .or_else(|| std::env::var("AWS_PROFILE").ok());

    let refusal = crate::write_gate::decide(&crate::write_gate::WriteContext {
        env,
        profile: pin_profile.as_deref(),
        // The CLI has no session-wide toggle; that rung exists for the
        // TUI. Passing `false` leaves this path's precedence exactly as
        // it was: freeze, then env pin, then account pin.
        safety_parse_errors: &safety_cfg.safety_parse_errors,
        global_read_only: false,
        frozen: active_freeze.is_some(),
        safety_envs: &safety_cfg.safety_envs,
        safety_accounts: &safety_cfg.safety_accounts,
    })?;

    // Wording stays the CLI's own — see `write_gate`'s module docs.
    let message = match &refusal {
        crate::write_gate::Refusal::SafetyConfigUnreadable { problem } => {
            format!("refusing {env} — safety config unreadable: {problem}")
        }
        crate::write_gate::Refusal::Frozen => match active_freeze.as_ref() {
            Some(m) => crate::freeze::refusal_message(m),
            // Unreachable — `frozen` was set from this very `Option` —
            // but `?` here would propagate `None`, and `None` from this
            // function means ALLOW. A fail-open branch in a write gate
            // is not worth the brevity.
            None => format!("refusing {env} — deploys frozen"),
        },
        crate::write_gate::Refusal::EnvPinned { env: e } => {
            format!("refusing {env} — pinned by safety.envs.{e}.read_only")
        }
        crate::write_gate::Refusal::AccountPinned { profile: p } => {
            format!("refusing {env} — pinned by safety.accounts.{p}.read_only")
        }
        // Unreachable: the CLI never sets `global_read_only`. Rendered
        // rather than `unreachable!()` because a panic in a write gate
        // is a worse failure than a slightly odd message.
        crate::write_gate::Refusal::GlobalReadOnly => {
            format!("refusing {env} — read-only mode")
        }
    };
    Some((refusal, message, pin_profile))
}

/// CLI wrapper over [`write_refusal`]: read the world, print, exit 3.
///
/// `subject` is what the message names — usually the env, but
/// `audit replay` says "restart on api-prod", which is more useful and
/// worth keeping.
pub(crate) fn refuse_write(
    prog: &str,
    subject: &str,
    env: &str,
    profile: Option<&str>,
    region: Option<&str>,
    action_label: &str,
) {
    let profile = profile.map(str::to_string);
    if let Some(reason) = write_refusal(
        &crate::config::load(),
        env,
        &profile,
        crate::freeze::read_active(),
        region,
        action_label,
    ) {
        // `write_refusal` phrases the pin case as "refusing ENV — …";
        // for a caller naming something richer, say that instead.
        let reason = reason
            .strip_prefix(&format!("refusing {env}"))
            .map(|r| format!("refusing {subject}{r}"))
            .unwrap_or(reason);
        eprintln!("{prog}: {reason}");
        std::process::exit(3);
    }
}

/// Shared value-flag guard: reject a missing value or a following
/// flag consumed as one. Class fix from the 0.26 max-review — a
/// swallowed value silently changed semantics (`lint --fix --yes
/// --env` widened to the whole fleet; `--rules --json` disabled a CI
/// gate and ate the JSON flag).
pub(crate) fn take_value<'a, I: Iterator<Item = &'a String>>(
    iter: &mut I,
    prog: &str,
    flag: &str,
    what: &str,
) -> Result<String, String> {
    let Some(v) = iter.next() else {
        return Err(format!("{prog}: {flag} expects {what}"));
    };
    if v.starts_with("--") {
        return Err(format!("{prog}: {flag} expects {what}, got flag '{v}'"));
    }
    Ok(v.clone())
}

/// Exit a CLI command after draining in-flight audit-webhook POSTs —
/// `std::process::exit` (and returning from `#[tokio::main]`) cancels
/// spawned tasks, so a fire-and-forget outcome POST written just
/// before exit usually never left the machine. No-op when nothing is
/// in flight; bounded at slightly over the POST timeout.
pub(crate) async fn exit_after_drain(code: i32) -> ! {
    crate::audit::drain_webhooks(std::time::Duration::from_secs(12)).await;
    std::process::exit(code);
}

/// Drain in-flight webhook POSTs before a CLI command's Ok return —
/// same rationale as [`exit_after_drain`], for the success paths.
pub(crate) async fn drain_before_return() {
    crate::audit::drain_webhooks(std::time::Duration::from_secs(12)).await;
}

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

    // decide_poll matrix tests live in `src/deploy_poll.rs`
    // alongside the function itself (0.16 move).

    #[test]
    fn cli_esc_escapes_quotes_and_backslashes() {
        assert_eq!(cli_esc("hello"), "hello");
        assert_eq!(cli_esc("a\"b"), "a\\\"b");
        assert_eq!(cli_esc("a\\b"), "a\\\\b");
        // Newlines + tabs (added in 0.15) are also escaped so the
        // value can land in any JSON context safely.
        assert_eq!(cli_esc("a\nb"), "a\\nb");
        assert_eq!(cli_esc("a\tb"), "a\\tb");
    }

    #[test]
    fn json_string_wraps_in_quotes_and_escapes() {
        assert_eq!(json_string(""), "\"\"");
        assert_eq!(json_string("hello"), "\"hello\"");
        assert_eq!(json_string("a\"b"), "\"a\\\"b\"");
        // Round-trip via the YAML-superset parser.
        let s = "line1\nline2 \"with quotes\"";
        let escaped = json_string(s);
        let parsed: String =
            serde_json::from_str(&escaped).expect("hand-rolled JSON must be valid JSON");
        assert_eq!(parsed, s);
    }
}

#[cfg(test)]
mod write_gate_guard {
    /// No CLI write path may reach for `pin_reason` directly.
    ///
    /// The freeze check and the pin check both existed and all four
    /// write paths called both — but each composed them by hand, and
    /// nothing made the fifth path do it. 0.14.1 was a same-day patch
    /// for exactly that: `lint --fix` checking one and not the other.
    ///
    /// Converging them on `write_refusal` only helps while they stay
    /// converged, and "everyone remembered" is what failed last time.
    /// This is the part that can't be forgotten.
    /// What counts as reaching past the gate: the raw pin maps, or the
    /// decision function directly (which would skip this module's
    /// wording and its freeze composition).
    ///
    /// Extracted so the guard can DEMONSTRATE that it detects, rather
    /// than passing because the tree happens to be clean. Disabling the
    /// scan used to leave the suite green — the guard only ever fired
    /// if someone introduced a violation, which is a guard you are
    /// trusting on assertion.
    fn reaches_past_the_gate(code: &str) -> bool {
        code.contains("safety_envs")
            || code.contains("safety_accounts")
            || code.contains("write_gate::decide")
    }

    #[test]
    fn the_gate_guard_detects_what_it_is_looking_for() {
        // The canary. Runs on every invocation, so a scan that has gone
        // blind fails here rather than passing quietly over a clean
        // tree.
        assert!(reaches_past_the_gate("if cfg.safety_envs.get(env) {"));
        assert!(reaches_past_the_gate("cfg.safety_accounts.contains_key(p)"));
        assert!(reaches_past_the_gate("crate::write_gate::decide(&ctx)"));
        // And does not flag the legitimate route.
        assert!(!reaches_past_the_gate(
            "if let Some(r) = write_refusal(&cfg, env, &p, f) {"
        ));
        assert!(!reaches_past_the_gate(
            "refuse_write(prog, subject, env, profile)"
        ));
    }

    /// The non-auditing half of the gate has exactly two callers.
    ///
    /// Splitting `write_refusal` into a pure half and an auditing funnel
    /// solved a real problem (demo mode was writing real audit lines),
    /// and opened a new one: `cli_write_paths_do_not_reach_past_the_shared_gate`
    /// scans for the pin maps and `decide`, none of which the pure half
    /// mentions — so a future enforcement path could call it, refuse
    /// correctly, and leave no trace, passing every guard. That is the
    /// "nothing made the fifth path do it" shape the sibling guard
    /// exists for, one level down.
    ///
    /// Pinned by COUNT, not just by file, so a second call appearing in
    /// an allowed file still fails. Both legitimate callers are
    /// non-dispatching by construction: a `--fix` preview and a demo
    /// server. If a third appears, the question to answer is why it
    /// refuses without recording, not how to make this list longer.
    #[test]
    fn write_refusal_paths_are_audited() {
        const ALLOWED: &[(&str, usize, &str)] = &[
            (
                "src/cli/lint.rs",
                1,
                "a --fix dry run dispatched nothing; recording refusals \
                 of writes that were never going to happen is noise",
            ),
            (
                "src/cli/mcp/writes.rs",
                1,
                "demo mode reaches the same verdict and writes nothing \
                 real — the refusal is genuine, the fleet is not",
            ),
        ];

        let mut found: Vec<(String, usize)> = Vec::new();
        let mut stack = vec![std::path::PathBuf::from("src/cli")];
        while let Some(dir) = stack.pop() {
            for entry in std::fs::read_dir(&dir).expect("src/cli") {
                let path = entry.expect("entry").path();
                if path.is_dir() {
                    stack.push(path);
                    continue;
                }
                if path.extension().and_then(|e| e.to_str()) != Some("rs") {
                    continue;
                }
                // `mod.rs` declares it.
                if path.file_name().and_then(|f| f.to_str()) == Some("mod.rs") {
                    continue;
                }
                let text = std::fs::read_to_string(&path).expect("read");
                let prod = text.split("#[cfg(test)]").next().unwrap_or("");
                let n = prod.matches("write_refusal_unaudited(").count();
                if n > 0 {
                    found.push((path.display().to_string(), n));
                }
            }
        }
        found.sort();

        let mut expected: Vec<(String, usize)> = ALLOWED
            .iter()
            .map(|(p, n, _)| ((*p).to_string(), *n))
            .collect();
        expected.sort();

        assert_eq!(
            found, expected,
            "the non-auditing gate gained or lost a caller. A refusal that \
             writes no `stage=refused` line is invisible — the exact blind \
             spot 0.37 closed. Justify the new site before listing it."
        );
    }

    /// The canary: this guard must be able to fail.
    ///
    /// It counts occurrences in a clean tree, so without this it would
    /// pass identically if the needle stopped matching anything.
    #[test]
    fn the_unaudited_gate_guard_can_see_its_needle() {
        let sample = "let r = crate::cli::write_refusal_unaudited(&cfg, env, &p, None);";
        assert_eq!(sample.matches("write_refusal_unaudited(").count(), 1);
        assert_eq!(
            "crate::cli::write_refusal(&cfg, env, &p, None, None, \"X\")"
                .matches("write_refusal_unaudited(")
                .count(),
            0,
            "the auditing funnel must not be counted as the unaudited one"
        );
    }

    #[test]
    fn cli_write_paths_do_not_reach_past_the_shared_gate() {
        let mut offenders: Vec<String> = Vec::new();
        let mut stack = vec![std::path::PathBuf::from("src/cli")];
        while let Some(dir) = stack.pop() {
            for entry in std::fs::read_dir(&dir).expect("src/cli") {
                let path = entry.expect("entry").path();
                if path.is_dir() {
                    stack.push(path);
                    continue;
                }
                if path.extension().and_then(|e| e.to_str()) != Some("rs") {
                    continue;
                }
                // `mod.rs` defines the shared gate; it is allowed to
                // reach the safety config because it IS the composition.
                if path.file_name().and_then(|f| f.to_str()) == Some("mod.rs") {
                    continue;
                }
                let text = std::fs::read_to_string(&path).expect("read");
                // Stop at the inline test module — fixtures legitimately
                // exercise `pin_reason` directly.
                let prod = text.split("#[cfg(test)]").next().unwrap_or("");
                for (n, line) in prod.lines().enumerate() {
                    let code = crate::app::tests::scan::strip_line_comment(line);
                    // Widened when `pin_reason` was folded into
                    // `write_gate::decide`. The old form scanned for a
                    // single method name, which would have become
                    // decorative the moment that method was deleted —
                    // a guard that cannot fire reads as coverage.
                    //
                    // These are what a CLI write path must not touch:
                    // the raw pin maps, or the decision function
                    // directly (which would skip this module's wording
                    // and its freeze composition).
                    if reaches_past_the_gate(code) {
                        offenders.push(format!("{}:{}", path.display(), n + 1));
                    }
                }
            }
        }
        assert!(
            offenders.is_empty(),
            "these CLI paths reach the safety config directly instead of going \
             through `cli::write_refusal`, which also checks the freeze — \
             the exact half-composition 0.14.1 shipped: {offenders:?}"
        );
    }
}

#[cfg(test)]
mod write_refusal_tests {
    use super::write_refusal;
    use crate::config::Config;

    #[test]
    fn an_account_pin_is_resolved_against_the_profile_passed_in() {
        // The hole this pins: `ebman action rollout --profile prod-admin`
        // dispatched under `prod-admin` while the gate was handed the
        // ambient `AWS_PROFILE`. With that unset or different, the pin
        // on `prod-admin` was never consulted — on a multi-region deploy
        // fan-out, the biggest write the CLI has.
        //
        // The gate was correct all along; it was being fed the wrong
        // input, which is why the convergence guard could not see it —
        // that guard detects a path *bypassing* the gate, not one
        // calling it with the wrong account.
        let mut cfg = Config::default();
        cfg.safety_accounts.insert("prod-admin".into(), true);

        let refused = write_refusal(
            &cfg,
            "api-prod",
            &Some("prod-admin".into()),
            None,
            None,
            "Test",
        );
        assert!(
            refused.is_some_and(|r| r.contains("prod-admin")),
            "a pinned account must refuse when it is the profile the write runs under"
        );

        // A different profile is not pinned, and must not be refused —
        // over-refusing would be its own bug.
        assert_eq!(
            write_refusal(&cfg, "api-prod", &Some("dev".into()), None, None, "Test"),
            None
        );
    }
}

#[cfg(test)]
mod write_gate_input_guard {
    /// A subcommand that takes `--profile` must feed it to the gate.
    ///
    /// `cli_write_paths_do_not_reach_past_the_shared_gate` catches a
    /// path that skips the gate. It is structurally blind to one that
    /// *calls* the gate with the wrong account — which is how
    /// `action rollout` dispatched under `--profile X` while resolving
    /// `safety.accounts.*.read_only` against the ambient `AWS_PROFILE`.
    /// A pin on X was simply never consulted.
    ///
    /// Scanning is the only way to reach this: the CLI wrapper exits
    /// the process, so its call sites cannot be exercised in-process.
    #[test]
    fn a_subcommand_with_its_own_profile_flag_passes_it_to_the_gate() {
        let src = std::fs::read_to_string("src/cli/action.rs").expect("read action.rs");
        // Split into top-level fn bodies so "does this fn parse
        // --profile" and "what did this fn pass" are asked of the SAME
        // function, not of the file.
        let mut offenders: Vec<String> = Vec::new();
        let mut current_fn = String::new();
        let mut body = String::new();
        let check = |name: &str, body: &str, offenders: &mut Vec<String>| {
            if name.is_empty() || !body.contains("\"--profile\"") {
                return;
            }
            for line in body.lines() {
                let t = line.trim_start();
                if t.starts_with("refuse_write(") && t.contains(", None)") {
                    offenders.push(format!("{name}: {}", t.trim()));
                }
            }
        };
        // A top-level fn, whatever its visibility. The original test was
        // `starts_with("pub ")`, which is FALSE for `pub(crate) fn` — so
        // narrowing one function's visibility would have made this guard
        // merge its body into the previous function's and stop seeing the
        // thing it exists to see, silently and while still passing.
        fn is_top_level_fn(line: &str) -> bool {
            if line.starts_with(char::is_whitespace) {
                return false;
            }
            let rest = match line.find(") ") {
                // strip `pub(crate) ` / `pub(super) ` / `pub(in path) `
                Some(i) if line.starts_with("pub(") => &line[i + 2..],
                _ => line.strip_prefix("pub ").unwrap_or(line),
            };
            rest.starts_with("fn ") || rest.starts_with("async fn ")
        }
        for line in src.lines() {
            if is_top_level_fn(line) {
                check(&current_fn, &body, &mut offenders);
                current_fn = line
                    .split("fn ")
                    .nth(1)
                    .unwrap_or("")
                    .split('(')
                    .next()
                    .unwrap_or("")
                    .to_string();
                body.clear();
            }
            body.push('\n');
            body.push_str(line);
        }
        check(&current_fn, &body, &mut offenders);

        assert!(
            offenders.is_empty(),
            "these subcommands parse `--profile` but hand the write gate \
             `None`, so the account pin is resolved against the ambient \
             AWS_PROFILE instead of the account the write runs under: \
             {offenders:?}"
        );
    }
}