csaf-core 1.4.8

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
// 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 — without ever reaching the branch that actually replaces the
/// running executable. Passing a canned transport here is safe; the install
/// step is only entered when a genuinely newer release is served, which the
/// offline tests deliberately never do.
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) {
        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(bin_name, current_version, &latest, triple)
}

/// 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))
}

/// Resolve the digest and drive the `self_update` install pipeline.
fn install(
    bin_name: &str,
    current_version: &str,
    latest: &str,
    triple: &str,
) -> Result<UpdateOutcome, UpdateError> {
    let (tag, asset) = prepare_install(bin_name, latest, triple)?;
    let digest = fetch_digest(&tag, &asset)?;

    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.
///
/// Fetching this from a different tag, or from "latest", would defeat the
/// point — the manifest must describe the exact artifact being installed.
fn fetch_digest(tag: &str, asset: &str) -> Result<String, UpdateError> {
    fetch_digest_with(tag, asset, None)
}

/// [`fetch_digest`], with an explicit transport.
///
/// 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(),
    })
}