csaf-core 1.4.11

CSAF storage, validation, sidecar generation, import/export
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2026 ndaal Gesellschaft für Sicherheit in der Informationstechnik mbH & Co KG, Cologne
// SPDX-FileCopyrightText: Author: Pierre Gronau <Pierre.Gronau@ndaal.eu>

//! In-place self-update against the project's GitLab releases.
//!
//! Backs the `--check-update` / `--self-update` / `--no-self-update` CLI
//! contract that every binary in this workspace exposes (`csaf-crud` and
//! `ndaal-csaf-cli`). See `skills/rust-self-update`.
//!
//! # The capability is mandatory
//!
//! `self_update` is a plain, always-compiled dependency: there is no cargo
//! feature guarding it and no `#[cfg(feature = ...)]` around this module. One
//! binary shape exists, and opting out is a **runtime** policy decision
//! (`--no-self-update` / `CSAF_NO_SELF_UPDATE`), never a build-time one.
//! `tests/self_update_is_mandatory.rs` fails to compile if that regresses.
//!
//! # Trust model — read this before claiming more than it does
//!
//! A downloaded archive is verified against the `SHA256SUMS` manifest
//! published **in the same release**. That proves the artifact matches the
//! manifest and was neither corrupted in transit nor swapped for a different
//! asset *within* the release.
//!
//! It is **not a signature**. Whoever can rewrite the release archive at the
//! source can rewrite `SHA256SUMS` alongside it. This is integrity, not
//! authenticity. Detached signing (`self_update`'s `signatures` feature, via
//! zipsign) is the next step up and is deliberately *not* enabled today,
//! because this project's release pipeline does not sign. Do not imply
//! otherwise in docs or UI.
//!
//! GitLab's releases API publishes no per-asset digest, so `self_update`'s
//! automatic release-digest check is a silent no-op on this backend. The
//! `SHA256SUMS` manifest is therefore the only integrity check that actually
//! runs, which is why it is fetched explicitly here rather than relied upon
//! implicitly.

use std::time::Duration;

use self_update::backends::gitlab;
use self_update::http_client::{HeaderMap, UreqClient};

/// GitLab instance hosting the releases.
pub const GITLAB_HOST: &str = "https://gitlab.com";
/// GitLab namespace owning the project.
pub const REPO_OWNER: &str = "vPierre";
/// GitLab project name.
pub const REPO_NAME: &str = "ndaal_public_csaf_crud";
/// Name of the checksum manifest published inside every release.
pub const SHA256SUMS_ASSET: &str = "SHA256SUMS";
/// Environment fallback for `--no-self-update`.
pub const NO_SELF_UPDATE_ENV: &str = "CSAF_NO_SELF_UPDATE";

/// Network timeout for every updater request.
const HTTP_TIMEOUT: Duration = Duration::from_secs(30);

/// Target triples this project actually publishes release assets for.
///
/// Deliberately asymmetric on Windows — the pipeline ships
/// `x86_64-pc-windows-gnu` but `aarch64-pc-windows-msvc`. Anything not in
/// this list has no asset and must produce a "no asset for this triple"
/// message naming the triple, not a bare 404.
pub const KNOWN_TARGETS: [&str; 6] = [
    "aarch64-apple-darwin",
    "aarch64-pc-windows-msvc",
    "aarch64-unknown-linux-gnu",
    "x86_64-apple-darwin",
    "x86_64-pc-windows-gnu",
    "x86_64-unknown-linux-gnu",
];

/// Errors that make `--self-update` fail. `--check-update` never surfaces
/// these: a transport failure there becomes [`UpdateOutcome::Unreachable`].
#[derive(Debug, thiserror::Error)]
pub enum UpdateError {
    /// The release carries no asset for the running target triple.
    #[error("no release asset for target triple `{triple}` (this build ships: {known})")]
    NoAssetForTarget {
        /// The running target triple.
        triple: String,
        /// Comma-separated [`KNOWN_TARGETS`].
        known: String,
    },
    /// `SHA256SUMS` was fetched but carries no line for our asset.
    #[error(
        "`{SHA256SUMS_ASSET}` in release {tag} has no entry for `{asset}` — refusing to install an unverified artifact"
    )]
    ChecksumMissing {
        /// Release tag the manifest came from.
        tag: String,
        /// Asset the manifest should have listed.
        asset: String,
    },
    /// A remote asset name failed the safety screen (Rule 5).
    #[error(
        "refusing to use remote asset name `{0}`: contains a path separator, `..`, a NUL byte, or is absolute"
    )]
    UnsafeAssetName(String),
    /// The checksum manifest was reachable but its body could not be read.
    #[error("could not read `{SHA256SUMS_ASSET}` from {url}: {source}")]
    ManifestRead {
        /// URL the manifest was fetched from.
        url: String,
        /// Underlying IO failure while streaming the body.
        source: std::io::Error,
    },
    /// Anything the `self_update` crate itself reported.
    #[error(transparent)]
    SelfUpdate(#[from] self_update::errors::Error),
}

/// What an update check or install concluded.
///
/// Modelled as an enum so the CLI printing, the exit codes and the tests all
/// read from one source of truth.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UpdateOutcome {
    /// Already running the newest release.
    UpToDate {
        /// The running version.
        current: String,
    },
    /// A newer release exists (`--check-update` only; nothing was installed).
    Available {
        /// The running version.
        current: String,
        /// The newest published version.
        latest: String,
    },
    /// A newer release was downloaded, verified and installed.
    Updated {
        /// The version that was running.
        from: String,
        /// The version now installed.
        to: String,
    },
    /// The update host could not be reached. **Not an error.**
    Unreachable {
        /// Human-readable cause.
        reason: String,
    },
    /// `--self-update` was refused by policy.
    DisabledByPolicy,
}

impl UpdateOutcome {
    /// Process exit code for this outcome.
    ///
    /// `10` for "a newer release exists" is what lets a wrapper script branch
    /// on `if binary --check-update; then ...` without parsing text.
    /// `Unreachable` is deliberately `0`: checking must never break a boot
    /// path or a cron job.
    #[must_use]
    pub const fn exit_code(&self) -> i32 {
        match *self {
            Self::UpToDate { .. } | Self::Updated { .. } | Self::Unreachable { .. } => 0,
            Self::DisabledByPolicy => 3,
            Self::Available { .. } => 10,
        }
    }

    /// One-line, colour-free, emoji-free report naming the binary and triple.
    #[must_use]
    pub fn message(&self, bin_name: &str, triple: &str) -> String {
        match *self {
            Self::UpToDate { ref current } => {
                format!("{bin_name} {current} ({triple}): up to date")
            },
            Self::Available {
                ref current,
                ref latest,
            } => format!("{bin_name} {current} ({triple}): update available -> {latest}"),
            Self::Updated { ref from, ref to } => {
                format!("{bin_name} ({triple}): updated {from} -> {to}")
            },
            Self::Unreachable { ref reason } => {
                format!("could not reach the update host ({reason}); nothing was changed")
            },
            Self::DisabledByPolicy => format!(
                "self-update is disabled by policy (--no-self-update / {NO_SELF_UPDATE_ENV})"
            ),
        }
    }
}

// ---------------------------------------------------------------------------
// Pure helpers — no IO, so they carry unit tests, proptest invariants and
// fuzz targets (see fuzz/fuzz_targets/fuzz_sha256sums_parse.rs and friends).
// ---------------------------------------------------------------------------

/// Exact release asset file name for `bin_name` at `version` on `triple`.
///
/// The version segment always carries a leading `v`, matching both
/// `release/create_release.sh` and the `[package.metadata.binstall]` blocks.
/// Every shipped triple uses `.tar.gz`, including the Windows ones — this
/// project publishes no `.zip`, which is why no `archive-zip` feature is
/// enabled.
#[must_use]
pub fn asset_name(bin_name: &str, version: &str, triple: &str) -> String {
    format!("{bin_name}-v{version}-{triple}.tar.gz")
}

/// Path of the executable *inside* the archive.
///
/// Must stay character-for-character in step with the `bin-dir` key of the
/// `[package.metadata.binstall]` blocks, or `cargo binstall` and the updater
/// disagree about where the binary lives.
#[must_use]
pub fn bin_path_in_archive(bin_name: &str, version: &str, triple: &str) -> String {
    format!("{bin_name}-v{version}-{triple}/{bin_name}")
}

/// Screen a file name that arrived over the network before it is used.
///
/// Names from a remote API are never path-joined (Rule 5); this is the
/// belt-and-braces check applied before an exact-equality comparison against
/// [`asset_name`]. Rejects path separators, `..`, NUL bytes, absolute paths
/// and the empty string.
#[must_use]
pub fn is_safe_asset_name(name: &str) -> bool {
    !name.is_empty()
        && !name.contains('/')
        && !name.contains('\\')
        && !name.contains('\0')
        && !name.contains("..")
}

/// Extract the SHA-256 digest for exactly `asset` from a `SHA256SUMS` body.
///
/// Total: no panics on any input. Accepts the `shasum -a 256` shape
/// (`<64 hex>  <name>`), one or more spaces as the separator, and the GNU
/// binary marker (`*name`). Digests are normalised to lowercase and must be
/// exactly 64 hex characters. Matching is on the **whole** name — a line for
/// `foo.tar.gz.sha-256` never satisfies a request for `foo.tar.gz`.
#[must_use]
pub fn parse_sha256sums(body: &str, asset: &str) -> Option<String> {
    if asset.is_empty() {
        return None;
    }
    body.lines()
        .filter_map(|line| split_sums_line(line.trim()))
        .find(|&(_, name)| name == asset)
        .map(|(digest, _)| digest.to_ascii_lowercase())
}

/// Split one `SHA256SUMS` line into `(digest, name)`, or `None` if malformed.
fn split_sums_line(line: &str) -> Option<(&str, &str)> {
    if line.is_empty() || line.starts_with('#') {
        return None;
    }
    let (digest, rest) = line.split_once(char::is_whitespace)?;
    if digest.len() != 64 || !digest.chars().all(|c| c.is_ascii_hexdigit()) {
        return None;
    }
    let rest = rest.trim_start();
    let name = rest.strip_prefix('*').unwrap_or(rest);
    if name.is_empty() {
        None
    } else {
        Some((digest, name))
    }
}

/// Download URL for `asset` in release `tag`, on this project's GitLab.
#[must_use]
pub fn download_url(tag: &str, asset: &str) -> String {
    format!("{GITLAB_HOST}/{REPO_OWNER}/{REPO_NAME}/-/releases/{tag}/downloads/{asset}")
}

/// Is `latest` newer than `current`? `false` on any unparseable version.
#[must_use]
pub fn is_newer(current: &str, latest: &str) -> bool {
    self_update::version::bump_is_greater(current, latest).unwrap_or(false)
}

/// Has the operator disabled self-update through the environment?
///
/// Accepts `1`, `true`, `yes`, `on` (case-insensitive); everything else,
/// including empty, is false. The CLI flag always wins over this.
#[must_use]
pub fn env_opt_out() -> bool {
    std::env::var(NO_SELF_UPDATE_ENV).is_ok_and(|v| env_flag_on(&v))
}

/// Shared truthiness rule for boolean environment variables.
#[must_use]
pub fn env_flag_on(value: &str) -> bool {
    matches!(
        value.trim().to_ascii_lowercase().as_str(),
        "1" | "true" | "yes" | "on"
    )
}

/// The target triple this binary was built for.
#[must_use]
pub fn target_triple() -> &'static str {
    self_update::get_target()
}

// ---------------------------------------------------------------------------
// IO
// ---------------------------------------------------------------------------

/// An injectable HTTP transport, used to drive the updater without a network
/// in tests. `None` means "use the crate's default client".
///
/// This is `self_update`'s object-safe seam (`http_client::HttpClient`),
/// which exists precisely so the whole state space — up to date, newer,
/// unreachable, rate-limited, digest missing — can be exercised offline.
pub type Transport = Option<std::sync::Arc<dyn self_update::http_client::HttpClient>>;

/// Report whether a newer release exists, without installing anything.
///
/// **Never returns an error.** Any transport failure — including a rate-limit
/// 403 — becomes [`UpdateOutcome::Unreachable`], so `--check-update` cannot
/// break a boot path or a script.
#[must_use]
pub fn check(current_version: &str) -> UpdateOutcome {
    check_with(current_version, None)
}

/// [`check`], with an explicit transport. Exposed so the offline test suite
/// can drive every outcome through the same code path production uses.
#[must_use]
pub fn check_with(current_version: &str, transport: Transport) -> UpdateOutcome {
    let releases = match fetch_release_list(current_version, transport) {
        Ok(r) => r,
        Err(e) => {
            return UpdateOutcome::Unreachable {
                reason: e.to_string(),
            };
        },
    };
    let Some(latest) = releases.latest().map(|r| r.version().to_owned()) else {
        return UpdateOutcome::Unreachable {
            reason: "the project has published no releases".to_owned(),
        };
    };
    if is_newer(current_version, &latest) {
        UpdateOutcome::Available {
            current: current_version.to_owned(),
            latest,
        }
    } else {
        UpdateOutcome::UpToDate {
            current: current_version.to_owned(),
        }
    }
}

/// Fetch the published release list from GitLab.
///
/// Routed through `Update` rather than `ReleaseList` because only
/// `UpdateBuilder` carries the `http_client` setter in rc.6 — so this is the
/// only shape of the call that the transport seam can reach.
fn fetch_release_list(
    current_version: &str,
    transport: Transport,
) -> self_update::errors::Result<self_update::Releases> {
    let mut builder = gitlab::Update::configure();
    builder
        .host(GITLAB_HOST)
        .repo_owner(REPO_OWNER)
        .repo_name(REPO_NAME)
        .bin_name(REPO_NAME)
        .current_version(current_version)
        .timeout(HTTP_TIMEOUT);
    if let Some(client) = transport {
        builder.http_client(client);
    }
    builder.build()?.get_latest_release()
}

/// Download, verify and install the newest release over the running binary.
///
/// Runs unattended: no stdin prompt, no progress chatter. The download is
/// verified against the release's own `SHA256SUMS` before it replaces
/// anything; a missing or mismatched digest is fatal and the artifact is
/// discarded.
pub fn perform(bin_name: &str, current_version: &str) -> Result<UpdateOutcome, UpdateError> {
    perform_with(bin_name, current_version, target_triple(), None)
}

/// [`perform`], with the target triple and transport supplied explicitly.
///
/// Exposed so the offline suite can drive every branch that decides *whether*
/// to install — unknown triple, unreachable host, no releases, already
/// current — and, since the transport now reaches [`install`], the integrity
/// check as well.
///
/// Passing a canned transport is safe even when a newer release is served:
/// the digest is fetched through that same transport, so a manifest that does
/// not list the asset stops the run at [`UpdateError::ChecksumMissing`],
/// which is *before* any download is attempted. Only a transport that serves
/// both a newer release **and** a matching digest line would proceed to
/// replace the running executable.
pub fn perform_with(
    bin_name: &str,
    current_version: &str,
    triple: &str,
    transport: Transport,
) -> Result<UpdateOutcome, UpdateError> {
    if !KNOWN_TARGETS.contains(&triple) {
        return Err(UpdateError::NoAssetForTarget {
            triple: triple.to_owned(),
            known: KNOWN_TARGETS.join(", "),
        });
    }
    let releases = match fetch_release_list(current_version, transport.clone()) {
        Ok(r) => r,
        Err(e) => {
            return Ok(UpdateOutcome::Unreachable {
                reason: e.to_string(),
            });
        },
    };
    let Some(latest) = releases.latest().map(|r| r.version().to_owned()) else {
        return Ok(UpdateOutcome::Unreachable {
            reason: "the project has published no releases".to_owned(),
        });
    };
    if !is_newer(current_version, &latest) {
        return Ok(UpdateOutcome::UpToDate {
            current: current_version.to_owned(),
        });
    }
    install(
        InstallRequest {
            bin_name,
            current_version,
            latest: &latest,
            triple,
        },
        transport,
    )
}

/// Compute the release tag and asset name for an install, screening the
/// asset name before it is used.
///
/// Pure, and public so the safety screen is directly testable. It used to be
/// inlined in [`install`], which meant the `UnsafeAssetName` branch — a
/// security guard — could only be reached by performing a real download, so
/// nothing exercised it. Returns `(tag, asset)`.
///
/// # Errors
///
/// [`UpdateError::UnsafeAssetName`] if the computed name carries a path
/// separator, `..`, a NUL byte, or is otherwise unusable.
pub fn prepare_install(
    bin_name: &str,
    latest: &str,
    triple: &str,
) -> Result<(String, String), UpdateError> {
    let asset = asset_name(bin_name, latest, triple);
    if !is_safe_asset_name(&asset) {
        return Err(UpdateError::UnsafeAssetName(asset));
    }
    Ok((format!("v{latest}"), asset))
}

/// What [`install`] needs to know, grouped so that threading the transport
/// through keeps the function within the four-parameter limit.
#[derive(Clone, Copy)]
struct InstallRequest<'a> {
    bin_name: &'a str,
    current_version: &'a str,
    latest: &'a str,
    triple: &'a str,
}

/// Resolve the digest and drive the `self_update` install pipeline.
///
/// `transport` is threaded in rather than defaulted here. It used to be
/// defaulted, which meant the digest fetch — the only integrity check on this
/// backend — always built a real network client and so could not be reached
/// by the offline suite at all. Worse, it made any test that served a
/// genuinely newer release stop being offline: it left the seam and hung on
/// gitlab.com. Mutation testing surfaced this as a surviving `fetch_digest`
/// mutant plus two timeouts.
fn install(req: InstallRequest<'_>, transport: Transport) -> Result<UpdateOutcome, UpdateError> {
    let InstallRequest {
        bin_name,
        current_version,
        latest,
        triple,
    } = req;
    let (tag, asset) = prepare_install(bin_name, latest, triple)?;
    // Deliberately the SAME tag as the artifact: fetching the manifest from a
    // different tag, or from "latest", would defeat the point — it must
    // describe the exact artifact being installed.
    let digest = fetch_digest_with(&tag, &asset, transport)?;

    gitlab::Update::configure()
        .host(GITLAB_HOST)
        .repo_owner(REPO_OWNER)
        .repo_name(REPO_NAME)
        .bin_name(bin_name)
        .target(triple)
        .bin_path_in_archive(bin_path_in_archive(bin_name, latest, triple))
        .current_version(current_version)
        .verify_checksum(self_update::Checksum::Sha256(digest))
        .unattended()
        .show_download_progress(false)
        .timeout(HTTP_TIMEOUT)
        .build()?
        .update()?;

    Ok(UpdateOutcome::Updated {
        from: current_version.to_owned(),
        to: latest.to_owned(),
    })
}

/// Fetch `SHA256SUMS` from the same release tag and read our asset's digest.
///
/// This is the ONLY integrity check that runs on this backend (GitLab
/// publishes no per-asset digest), so it is exposed for offline testing
/// rather than left reachable only through a real download. A bug here means
/// either a refused good update or — far worse — an accepted bad one.
pub fn fetch_digest_with(
    tag: &str,
    asset: &str,
    transport: Transport,
) -> Result<String, UpdateError> {
    let url = download_url(tag, SHA256SUMS_ASSET);
    let client = transport.unwrap_or_else(|| std::sync::Arc::new(UreqClient::default()));
    let response = client.get(&url, &HeaderMap::new(), Some(HTTP_TIMEOUT))?;
    let mut body = String::new();
    std::io::Read::read_to_string(&mut response.body(), &mut body).map_err(|source| {
        UpdateError::ManifestRead {
            url: url.clone(),
            source,
        }
    })?;
    parse_sha256sums(&body, asset).ok_or_else(|| UpdateError::ChecksumMissing {
        tag: tag.to_owned(),
        asset: asset.to_owned(),
    })
}

// ---------------------------------------------------------------------------
// Kani proof harnesses
// ---------------------------------------------------------------------------
//
// Compiled only under `cargo kani`, so an ordinary build pays nothing.
//
// SCOPE — deliberately just ONE function.
//
// `skills/rust-kani` Rule 10: Kani's return is highest on low-level
// invariants, and "pure business logic is usually better served by property
// tests". `is_newer` (semver parsing) and `env_flag_on` (case folding) are
// exactly that business logic and are already covered by proptest in
// `tests/updater_pure.rs`; earlier harnesses over them ran for hours and
// segfaulted CBMC without proving anything. They were removed rather than
// left running as decoration.
//
// What is left is the one property worth a proof rather than a sample:
// `is_safe_asset_name` is the path-traversal guard applied to asset names
// derived from a release tag served by a remote API. Mutation testing showed
// how fragile it is -- flipping its first `&&` to `||` yields
// `!name.is_empty() || (...)`, because `&&` binds tighter, so EVERY non-empty
// name passes as safe, traversal included. A sampler can miss that; an
// exhaustive check over the bounded space cannot.
//
// THE BOUND (Rule 2 -- a result without its bound is not a claim):
//   Names of exactly 4 characters, each drawn from {'a', '/', '\\', '.', NUL},
//   with `#[kani::unwind(6)]`. That is 5^4 = 625 concrete names. It is NOT a
//   proof for arbitrary-length or arbitrary-Unicode names.
//
// Why that alphabet: cost grows sharply with symbolic size (Rule 6), so the
// space is collapsed to the characters that can actually change the answer --
// one ordinary character plus every forbidden one. Length 4 is the shortest
// that can still contain ".." with context on both sides. Every member is
// ASCII, which makes `from_utf8` total and removes the early-return branch
// that would otherwise let a vacuous proof pass silently.
#[cfg(kani)]
mod proofs {
    use super::is_safe_asset_name;

    /// Characters that can change the verdict, and nothing else.
    const ALPHABET: [u8; 5] = [b'a', b'/', b'\\', b'.', 0];

    /// Length of every symbolic name. See THE BOUND above.
    const LEN: usize = 4;

    /// A symbolic `LEN`-byte name drawn from [`ALPHABET`].
    fn symbolic_name(buf: &mut [u8; LEN]) {
        let mut i = 0;
        while i < LEN {
            let pick: usize = kani::any();
            kani::assume(pick < ALPHABET.len());
            buf[i] = ALPHABET[pick];
            i += 1;
        }
    }

    /// Decode, asserting totality rather than returning early.
    ///
    /// A `let ... else { return }` here would be the classic vacuity hole:
    /// if the solver seldom reached valid UTF-8 the harness would pass having
    /// checked nothing, and look identical to a real result.
    fn decode(buf: &[u8; LEN]) -> &str {
        match core::str::from_utf8(buf) {
            Ok(s) => s,
            Err(_) => unreachable!("ALPHABET is ASCII-only, so decoding is total"),
        }
    }

    /// If a name is accepted as safe, it really carries nothing forbidden.
    #[kani::proof]
    #[kani::unwind(6)]
    fn accepting_a_name_implies_it_is_clean() {
        let mut buf = [0_u8; LEN];
        symbolic_name(&mut buf);
        let name = decode(&buf);

        // Rule 1: prove the interesting states are REACHABLE, so the
        // assertions below cannot be true merely because nothing got here.
        kani::cover!(is_safe_asset_name(name), "a clean name is reachable");
        kani::cover!(!is_safe_asset_name(name), "a rejected name is reachable");
        kani::cover!(name.contains(".."), "the traversal case is reachable");
        kani::cover!(name.contains('/'), "the separator case is reachable");

        if is_safe_asset_name(name) {
            assert!(!name.is_empty(), "empty name accepted as safe");
            assert!(!name.contains('/'), "unix separator accepted as safe");
            assert!(!name.contains('\\'), "windows separator accepted as safe");
            assert!(!name.contains('\0'), "NUL accepted as safe");
            assert!(!name.contains(".."), "parent traversal accepted as safe");
        }
    }

    /// The converse: anything carrying a forbidden pattern is rejected.
    ///
    /// Needed because the postcondition above would also be satisfied by a
    /// function that rejects everything -- the two together pin the guard.
    #[kani::proof]
    #[kani::unwind(6)]
    fn a_forbidden_name_is_always_rejected() {
        let mut buf = [0_u8; LEN];
        symbolic_name(&mut buf);
        let name = decode(&buf);

        let forbidden = name.is_empty()
            || name.contains('/')
            || name.contains('\\')
            || name.contains('\0')
            || name.contains("..");

        kani::cover!(forbidden, "a forbidden name is reachable");
        kani::cover!(!forbidden, "a permitted name is reachable");

        if forbidden {
            assert!(
                !is_safe_asset_name(name),
                "a name carrying a forbidden pattern was accepted",
            );
        }
    }
}