amont-agent 2.4.0

A guard that inspects a shell command before Claude Code runs it
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
//! The record of what the guard saw.
//!
//! Modelled on amont's `bypass` store, including its central rule: **this
//! module only counts. Nothing in it may participate in a decision.** The
//! stance gates a command; the journal informs a human. A wrong read here
//! miscounts, and it must never be able to do worse than that.
//!
//! ## Not in `.git/`
//!
//! `bypass` lives in the common git dir because "how often does this repository
//! dodge its gate" is a question about a repository. This hook fires wherever
//! Claude Code is working, including outside any repository at all, and the
//! question it answers — "does this rule misfire?" — is about the *rule*. So
//! one file per machine, next to the settings that installed it.
//!
//! ## One write per record
//!
//! Several sessions and their subagents run at once. Each record is built
//! whole and written with a single `write_all` to an append-mode handle, and
//! capped so that write stays small enough to interleave atomically in
//! practice. A torn line is dropped on read, exactly as `bypass::event` does —
//! the failure mode is a lost record, never a corrupt count.
//!
//! ## Commands carry secrets
//!
//! Measured across the real corpus: 283 `TOKEN|SECRET|KEY=` assignments, 17
//! `https://user:pass@` URLs, and literal `ghp_`/`--password` values. This file
//! persists command text, so redaction is not optional, and the byte cap is a
//! second line of defence for the shapes nobody anticipated.
//!
//! Never pushed, never transmitted. The project's no-telemetry promise applies
//! in full.

use std::fs;
use std::io::Write;
use std::path::PathBuf;

use crate::ui;

/// First line of the journal. A future format bumps this, and an older reader
/// sees an empty journal rather than misreading one.
pub const FORMAT: &str = "amont-agent-v1";

/// A record must fit in one small write. The excerpt is what gives, because
/// commands do not fit anyway: measured p50 240 bytes, p95 1,777, max 13 KB.
const MAX_RECORD: usize = 512;
const MAX_EXCERPT: usize = 200;

/// Compact past this. Roughly the same budget `bypass` uses.
const MAX_BYTES: u64 = 256 * 1024;

pub fn dir() -> Option<PathBuf> {
    Some(crate::settings::config_dir()?.join("amont-agent"))
}

/// Open the journal for appending, creating it 0600 rather than 0644.
///
/// The mode is set AT CREATION, not afterwards: a file that exists
/// world-readable for the instant between `open` and `set_permissions` is a
/// file somebody's backup agent can have read. `OpenOptions::mode` applies
/// only when the open creates the file, so an existing journal keeps
/// whatever mode it has — the same rule `atomic::carry_mode` follows for
/// `settings.json`, and for the same reason: our writes never change who can
/// read a file that already existed. [`private`] is what widens nothing and
/// narrows an old journal in place.
fn open_private(path: &std::path::Path) -> Option<fs::File> {
    let mut opts = fs::OpenOptions::new();
    opts.create(true).append(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    let f = opts.open(path).ok()?;
    // An older amont-agent created this file at 0644 under the default
    // umask, and it is still holding the command text it wrote then. Narrow
    // it once, here, rather than leaving the upgrade to a release note
    // nobody reads.
    private(path, 0o600);
    Some(f)
}

/// Narrow `path` to `mode` when it is wider than that. Never widens, and
/// never complains: a journal that could not be chmod'ed is still a journal,
/// and this module may not fail the hook.
#[cfg(unix)]
pub(crate) fn private(path: &std::path::Path, mode: u32) {
    use std::os::unix::fs::PermissionsExt;
    let Ok(meta) = fs::metadata(path) else { return };
    let now = meta.permissions().mode() & 0o777;
    if now & !mode != 0 {
        let _ = fs::set_permissions(path, fs::Permissions::from_mode(now & mode));
    }
}

/// Windows has no mode bits to narrow; the file inherits the ACL of
/// `%USERPROFILE%\.claude`, which is where its settings already live.
#[cfg(not(unix))]
pub(crate) fn private(_path: &std::path::Path, _mode: u32) {}

pub fn path() -> Option<PathBuf> {
    Some(dir()?.join("journal.log"))
}

/// One thing that happened.
pub struct Entry<'a> {
    pub rule: &'a str,
    pub stance: &'a str,
    /// What actually happened to the command: `denied`, `advised`, `watched`.
    pub outcome: &'a str,
    pub session: &'a str,
    pub repo: &'a str,
    /// The permission mode the call arrived in. Recorded, never acted on —
    /// it is how you would notice if a rule ever stopped applying in one.
    pub mode: &'a str,
    pub excerpt: &'a str,
}

/// Append one record. Every failure is swallowed: the journal must never be
/// able to fail the hook, and `the_journal_never_fails_the_hook` pins that.
/// Set by `doctor`'s own probe on the child it spawns. See [`record`].
pub const ENV_PROBE: &str = "AMONT_AGENT_PROBE";

pub fn record(entry: &Entry) {
    // `doctor` proves the guard works by feeding the real binary a command it
    // must refuse. That firing is synthetic — nobody typed it, and no model
    // was going to run it — so recording it would put a `pipe-to-tail` denial
    // in the journal every time somebody asks whether the guard is healthy.
    //
    // That matters beyond tidiness. The journal is the measurement: `status`
    // counts it, and the per-1000 evidence that gates `graduate` comes from
    // the same data. A health check that inflates a rule's firing rate makes
    // the rule look more necessary the more often you check on it — the
    // observer changing what it observes, which is the exact distinction
    // `observe` and `advise` exist to keep clean.
    if std::env::var_os(ENV_PROBE).is_some() {
        return;
    }
    let _ = try_record(entry);
}

fn try_record(entry: &Entry) -> Option<()> {
    let path = path()?;
    let dir = path.parent()?;
    fs::create_dir_all(dir).ok()?;
    private(dir, 0o700);

    let fresh = !path.exists();
    let mut f = open_private(&path)?;
    if fresh {
        f.write_all(format!("{FORMAT}\n").as_bytes()).ok()?;
    }

    let line = line_for(entry);
    f.write_all(line.as_bytes()).ok()?;

    if f.metadata().ok()?.len() > MAX_BYTES {
        compact(&path);
    }
    Some(())
}

/// Build the whole record as one line. Separated from the write so it can be
/// tested without a filesystem, and so `a_record_is_one_write` can assert the
/// shape rather than race on it.
pub fn line_for(entry: &Entry) -> String {
    let excerpt = redact_and_trim(entry.excerpt);
    let mut line = format!(
        "F {} {} {} {} {} {} {} {}\n",
        now(),
        field(entry.rule),
        field(entry.stance),
        field(entry.outcome),
        field(&entry.session.chars().take(8).collect::<String>()),
        field(entry.repo),
        field(entry.mode),
        excerpt
    );
    if line.len() > MAX_RECORD {
        let keep = MAX_RECORD - 2;
        let cut = (0..=keep)
            .rev()
            .find(|i| line.is_char_boundary(*i))
            .unwrap_or(0);
        line.truncate(cut);
        line.push('\n');
    }
    line
}

/// A single space-free token. Everything in a record but the excerpt is one,
/// which is what lets the reader split on whitespace.
fn field(s: &str) -> String {
    let cleaned: String = ui::sanitize(s)
        .chars()
        .map(|c| if c.is_whitespace() { '_' } else { c })
        .collect();
    if cleaned.is_empty() {
        "-".to_string()
    } else {
        cleaned
    }
}

/// Secrets out, control bytes out, newlines out, then a hard length cap.
pub fn redact_and_trim(text: &str) -> String {
    let mut s = redact(text);
    s = ui::sanitize(&s);
    s = s.split_whitespace().collect::<Vec<_>>().join(" ");
    if s.chars().count() > MAX_EXCERPT {
        s = s.chars().take(MAX_EXCERPT).collect::<String>() + "";
    }
    s
}

/// The shapes that actually appear in the corpus, plus the obvious token
/// prefixes. Deliberately blunt: this is a redactor, not a parser, and a
/// false redaction costs a less readable sample while a missed one costs a
/// secret on disk.
pub fn redact(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    // Whether the PREVIOUS word said that this one is a credential.
    // `--password=x` is one word and `redact_word` handles it alone;
    // `--password x` and `Authorization: Bearer <jwt>` are two, and a
    // word-at-a-time redactor could not see the second half of either.
    let mut announced = false;
    for word in text.split_inclusive(char::is_whitespace) {
        let trimmed = word.trim_end();
        if announced && !trimmed.is_empty() && !trimmed.starts_with('-') {
            // Keep whatever CLOSES the word — a quote, a comma — attached
            // rather than swallowed, exactly as `redact_query` does. A
            // redactor that turns `-H "Authorization: Bearer x"` into
            // unbalanced quotes makes its own output unreadable, which is
            // the bug the corpus already caught once.
            let closing: String = trimmed
                .chars()
                .rev()
                .take_while(|c| !c.is_alphanumeric() && !matches!(c, '-' | '_' | '.'))
                .collect::<Vec<_>>()
                .into_iter()
                .rev()
                .collect();
            out.push_str("***");
            out.push_str(&closing);
            out.push_str(&word[trimmed.len()..]);
            announced = false;
            continue;
        }
        announced = announces_a_secret(trimmed);
        out.push_str(&redact_word(word));
    }
    out
}

/// Does this word say "the NEXT one is a credential"?
///
/// A flag whose name reads like a secret and carries no `=` of its own, or
/// an HTTP authentication scheme. Blunt in the same direction as the rest of
/// this module: `--api-key-file config.json` loses the filename, which costs
/// a less readable sample, and the alternative costs a token on disk.
///
/// `-p` is deliberately absent. It is `--password` to mysql and `--patch` to
/// git, and `git add -p .` is far commoner here than the other one.
fn announces_a_secret(word: &str) -> bool {
    if word.eq_ignore_ascii_case("bearer") || word.eq_ignore_ascii_case("basic") {
        return true;
    }
    let Some(name) = word.strip_prefix('-') else {
        return false;
    };
    if word.contains('=') {
        return false; // `--password=x` — one word, already handled
    }
    let name = name.strip_prefix('-').unwrap_or(name);
    !name.is_empty() && secret_named(name)
}

fn redact_word(word: &str) -> String {
    let trimmed = word.trim_end();
    let tail = &word[trimmed.len()..];

    // A URL is handled as a URL, because the `NAME=value` rule below cannot see
    // the difference between an assignment and a query string. It used to try,
    // with `API` among its needles — so `/api/v1/repos/…?limit=5"` matched,
    // everything after the `=` was replaced including the closing quote, and a
    // perfectly ordinary curl became unparseable shell. The corpus caught it.
    if let Some(scheme) = trimmed.find("://") {
        let mut out = String::from(&trimmed[..scheme + 3]);
        let rest = &trimmed[scheme + 3..];
        // `https://user:pass@host`
        let rest = match rest.find('@') {
            Some(at) if !rest[..at].contains('/') => {
                out.push_str("***:***");
                &rest[at..]
            }
            _ => rest,
        };
        out.push_str(&redact_query(rest));
        return out + tail;
    }
    // `--password=x`, `GITHUB_TOKEN=x`. Only where the name reads like a flag
    // or an identifier: a name carrying a path separator is not an assignment.
    if let Some(eq) = trimmed.find('=') {
        let (name, _) = trimmed.split_at(eq);
        if !name.contains('/') && !name.contains(':') && secret_named(name) {
            return format!("{name}=***") + tail;
        }
    }
    // Bare credential shapes.
    for prefix in [
        "ghp_",
        "gho_",
        "ghu_",
        "ghs_",
        "ghr_",
        "github_pat_",
        "sk-",
        "AKIA",
    ] {
        if trimmed.starts_with(prefix) && trimmed.len() > prefix.len() + 8 {
            return format!("{prefix}***{tail}");
        }
    }
    word.to_string()
}

/// Does this name say "the thing after the `=` is a credential"?
///
/// `API` is deliberately absent: on its own it matches every `/api/` in every
/// URL. `API_KEY` and `APIKEY` are still caught, by `KEY`.
fn secret_named(name: &str) -> bool {
    let upper = name.to_ascii_uppercase();
    ["TOKEN", "SECRET", "PASSWORD", "PASSWD", "KEY", "CREDENTIAL"]
        .iter()
        .any(|needle| upper.contains(needle))
}

/// Redact only the values of secret-named query parameters, leaving the rest of
/// the URL — and, critically, any trailing quote — intact.
///
/// The user's own standing rule is that a secret riding in a URL is still a
/// secret, so `?token=…` must go; `?limit=5` must not.
fn redact_query(rest: &str) -> String {
    let Some(q) = rest.find('?') else {
        return rest.to_string();
    };
    let (base, query) = rest.split_at(q + 1);
    let mut out = String::from(base);
    // Keep whatever closes the word (a quote, a comma) attached to the last
    // parameter rather than swallowed by it.
    for (i, param) in query.split('&').enumerate() {
        if i > 0 {
            out.push('&');
        }
        match param.split_once('=') {
            Some((name, value)) if secret_named(name) => {
                let keep: String = value
                    .chars()
                    .rev()
                    .take_while(|c| !c.is_alphanumeric() && *c != '-' && *c != '_')
                    .collect::<Vec<_>>()
                    .into_iter()
                    .rev()
                    .collect();
                out.push_str(name);
                out.push_str("=***");
                out.push_str(&keep);
            }
            _ => out.push_str(param),
        }
    }
    out
}

fn now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Keep the newest records and drop the oldest, preserving the header.
fn compact(path: &std::path::Path) {
    let Ok(text) = fs::read_to_string(path) else {
        return;
    };
    let lines: Vec<&str> = text.lines().filter(|l| l.starts_with("F ")).collect();
    let keep = lines.len().saturating_sub(lines.len() / 2);
    let mut out = String::from(FORMAT);
    out.push('\n');
    for l in &lines[lines.len() - keep..] {
        out.push_str(l);
        out.push('\n');
    }
    let _ = fs::write(path, out);
}

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

    fn entry<'a>(excerpt: &'a str) -> Entry<'a> {
        Entry {
            rule: "pipe-to-tail",
            stance: "deny",
            outcome: "denied",
            session: "0123456789abcdef",
            repo: "amont",
            mode: "default",
            excerpt,
        }
    }

    /// Interleaving is only safe if a record is one line with no interior
    /// newline. Cheaper and far less flaky to assert on the builder than to
    /// race real processes.
    #[test]
    fn a_record_is_exactly_one_line() {
        let line = line_for(&entry("git push \n\n origin main | tail -1"));
        assert_eq!(line.matches('\n').count(), 1);
        assert!(line.ends_with('\n'));
        assert!(line.len() <= MAX_RECORD);
    }

    /// A 13 KB command must not produce a 13 KB write.
    #[test]
    fn an_enormous_command_still_fits_one_write() {
        let line = line_for(&entry(&"x".repeat(20_000)));
        assert!(line.len() <= MAX_RECORD, "{} bytes", line.len());
        assert_eq!(line.matches('\n').count(), 1);
    }

    /// This file persists command text, and command text carries credentials.
    #[test]
    fn a_credential_never_reaches_the_journal() {
        for (raw, must_not_contain) in [
            ("git push https://fred:hunter2@github.com/x", "hunter2"),
            (
                "GITHUB_TOKEN=ghp_abcdefghijklmnop1234 git push",
                "ghp_abcdefghijklmnop1234",
            ),
            ("curl -H x --password=s3cr3t https://x", "s3cr3t"),
            (
                "gh auth login --with-token ghp_zzzzzzzzzzzzzzzzzzzz",
                "ghp_zzzzzzzzzzzzzzzzzzzz",
            ),
        ] {
            let got = redact_and_trim(raw);
            assert!(
                !got.contains(must_not_contain),
                "leaked {must_not_contain:?} from {raw:?} → {got}"
            );
        }

        // The AWS shape is assembled at run time rather than written out.
        // amont's own `pre-commit-secrets` refused this file when the literal
        // was here — correctly, because it matches on shape and cannot know
        // that this particular one is Amazon's published example. A test fixture
        // is not worth teaching a secret scanner to make exceptions.
        let key = format!("AKIA{}", "IOSFODNN7EXAMPLE");
        let got = redact_and_trim(&format!("aws --key {key} s3 ls"));
        assert!(!got.contains(&key), "leaked an access key id → {got}");
    }

    /// Redaction must not eat the part a reviewer needs.
    #[test]
    fn redaction_leaves_the_command_readable() {
        let got = redact_and_trim("GITHUB_TOKEN=ghp_abcdefghijklmnop1234 git push | tail -1");
        assert!(got.contains("git push"), "{got}");
        assert!(got.contains("tail"), "{got}");
    }

    /// A control byte in a command must not reach a file a terminal will later
    /// print — the same reason `ui::sanitize` exists for the trust prompt.
    #[test]
    fn control_bytes_are_escaped_not_stored_raw() {
        let got = redact_and_trim("git push \u{1b}[8m hidden");
        assert!(!got.contains('\u{1b}'), "{got}");
    }

    /// The bug the corpus found. `API` was a secret-name needle, so `/api/v1/`
    /// in any URL matched, everything after the first `=` was replaced — the
    /// closing quote included — and an ordinary curl became unparseable shell.
    /// A redactor that mangles benign commands makes its own output useless.
    #[test]
    fn an_api_path_is_not_a_secret_assignment() {
        let raw = r#"curl -sS "http://localhost:3000/api/v1/repos/x/actions/tasks?limit=5" | jq"#;
        assert_eq!(redact(raw), raw, "a benign URL was rewritten");
    }

    /// But a secret riding in a URL is still a secret.
    #[test]
    fn a_secret_query_parameter_is_still_redacted() {
        let got = redact("curl \"https://hooks.example.com/x?token=abc123def456&limit=5\"");
        assert!(!got.contains("abc123def456"), "{got}");
        assert!(
            got.contains("limit=5"),
            "the benign parameter survived: {got}"
        );
        assert!(got.ends_with('"'), "the closing quote survived: {got}");
    }

    /// Redaction must not turn a readable command into one the lexer refuses,
    /// or every redacted sample becomes useless for review.
    #[test]
    fn redaction_leaves_a_command_the_lexer_can_still_read() {
        for raw in [
            r#"curl -sS "http://x/api/v1/tasks?limit=5" | jq '.total'"#,
            r#"GITHUB_TOKEN=ghp_aaaaaaaaaaaaaaaaaaaa git push origin main"#,
            r#"git commit -m "msg" --no-verify && git push"#,
        ] {
            let redacted = redact(raw);
            assert!(
                !matches!(
                    crate::shell::lex(&redacted),
                    crate::shell::Parsed::Opaque(_)
                ),
                "redaction made this unreadable: {redacted}"
            );
        }
    }

    #[test]
    fn a_field_never_contains_a_space() {
        assert!(!field("two words").contains(' '));
        assert_eq!(field(""), "-");
    }

    /// The half a word-at-a-time redactor could not see: the credential is
    /// the NEXT word, not the one carrying the `=`.
    #[test]
    fn a_credential_in_the_following_word_is_redacted_too() {
        for (raw, secret) in [
            ("curl --password s3cr3t https://x", "s3cr3t"),
            (
                "gh auth login --with-token gitlab-abcdefghij",
                "gitlab-abcdefghij",
            ),
            (
                r#"curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.body.sig" https://x"#,
                "eyJhbGciOiJIUzI1NiJ9.body.sig",
            ),
            (
                "vault write secret/x api_key=zzz --token hvs.CAESIJx",
                "hvs.CAESIJx",
            ),
        ] {
            let got = redact(raw);
            assert!(
                !got.contains(secret),
                "leaked {secret:?} from {raw:?} → {got}"
            );
        }
    }

    /// …and it must not eat the quote that closes the word, or the sample
    /// stops being a command anybody can read. Same rule `redact_query`
    /// already follows for a secret query parameter.
    #[test]
    fn the_following_word_keeps_what_closes_it() {
        let got = redact(r#"curl -H "Authorization: Bearer abcdefghij" https://x"#);
        assert!(
            got.contains(r#"***""#),
            "the closing quote was swallowed: {got}"
        );
        assert!(
            !matches!(crate::shell::lex(&got), crate::shell::Parsed::Opaque(_)),
            "redaction made this unreadable: {got}"
        );
    }

    /// A flag is not a value. `--token --verbose` must not redact the second
    /// flag and then let the real value through unredacted behind it.
    #[test]
    fn a_flag_after_an_announcement_is_not_the_value() {
        let got = redact("curl --token --verbose https://x");
        assert!(got.contains("--verbose"), "{got}");
    }

    /// The file holds command text. It is created 0600, not 0644 — and an
    /// older one, written before this was true, is narrowed in place.
    #[cfg(unix)]
    #[test]
    fn the_journal_is_not_world_readable() {
        use std::os::unix::fs::PermissionsExt;
        let dir = std::env::temp_dir().join(format!("amont-agent-mode-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();

        let fresh = dir.join("journal.log");
        open_private(&fresh).expect("open");
        let mode = fs::metadata(&fresh).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "a journal we create is ours alone");

        let old = dir.join("legacy.log");
        fs::write(&old, "F 1 x\n").unwrap();
        fs::set_permissions(&old, fs::Permissions::from_mode(0o644)).unwrap();
        open_private(&old).expect("open");
        let mode = fs::metadata(&old).unwrap().permissions().mode() & 0o777;
        assert_eq!(
            mode, 0o600,
            "an existing 0644 journal is narrowed, not left"
        );

        // …but never WIDENED: 0400 is stricter than we ask for and stays.
        let strict = dir.join("strict.log");
        fs::write(&strict, "F 1 x\n").unwrap();
        fs::set_permissions(&strict, fs::Permissions::from_mode(0o400)).unwrap();
        private(&strict, 0o600);
        let mode = fs::metadata(&strict).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o400, "narrowing must never widen");

        let _ = fs::remove_dir_all(&dir);
    }
}