keyhog 0.5.73

GPU-accelerated secret scanner for code, Git history, cloud, containers, browser assets, and live credential verification
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
//! Release resolution, download, and signature verification.
//!
//! This is the NETWORK + TRUST half of the installer: it talks to the GitHub
//! releases API, selects the right asset for this host, compares semver, and -
//! crucially - verifies each downloaded binary against the embedded minisign
//! public key before any byte is handed to the local-install half
//! ([`super`]). It owns no on-disk replace logic; it produces verified bytes.
//!
//! Trust model: every release binary is signed with the keyhog minisign secret
//! key in the `sign` job of `.github/workflows/release.yml`, and
//! [`download_verified_asset`] verifies the downloaded binary against the
//! embedded [`RELEASE_PUBLIC_KEY`] before returning it. A missing `.minisig`
//! fails CLOSED (refuse to install) since a forged 404 would otherwise bypass
//! the whole gate. There is no opt-out: no environment variable can disable the
//! signature gate (config-policy mandate + security).

use anyhow::{anyhow, Context, Result};
use keyhog_core::{Chunk, ChunkMetadata, DetectorFile};
use keyhog_scanner::{hw_probe::ScanBackend, CompiledScanner};
use serde::Deserialize;
use std::time::Duration;

pub(crate) const REPO: &str = "santhreal/keyhog";
const RELEASE_CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
const RELEASE_REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
const MAX_RELEASE_METADATA_BYTES: usize = 8 * 1024 * 1024;
const MAX_RELEASE_ASSET_BYTES: usize = 512 * 1024 * 1024;
const MAX_RELEASE_SIGNATURE_BYTES: usize = 64 * 1024;
const MAX_RELEASE_CHECKSUM_BYTES: usize = 64 * 1024;
const MAX_RESPONSE_PREALLOC_BYTES: usize = 64 * 1024;
const RELEASE_API_BASE: &str = "https://api.github.com";

/// GitHub API base for update/repair release resolution.
///
/// Production resolution has no argv or environment override. Integration
/// tests inject a server only through the crate's explicit library test API.
pub(crate) fn release_api_base() -> &'static str {
    RELEASE_API_BASE
}

/// minisign public key for keyhog release artifacts (key ID `DD4915EBE99F9CCF`).
/// The matching secret signs each release binary in CI. Rotating the key means
/// updating this constant and re-signing; clients keep trusting the old key
/// until they update to a build carrying the new one.
pub(crate) const RELEASE_PUBLIC_KEY: &str =
    "RWTPnJ/p6xVJ3TJIxr+ZVHMD/MTHWZhsdE38Go/oD3DYBoi4bePR55go";

/// Verify `data` against `signature` (the full body of a `.minisig` file)
/// using the embedded release public key. Errors on a malformed key, a
/// malformed signature, or a signature that does not match the data.
pub(crate) fn verify_release_signature(data: &[u8], signature: &str) -> Result<()> {
    use minisign_verify::{PublicKey, Signature};
    let pk = PublicKey::from_base64(RELEASE_PUBLIC_KEY)
        .map_err(|e| anyhow!("embedded release public key is invalid: {e}"))?;
    let sig =
        Signature::decode(signature).map_err(|e| anyhow!("release signature is malformed: {e}"))?;
    pk.verify(data, &sig, false)
        .map_err(|e| anyhow!("release signature verification failed: {e}"))
}

#[derive(Clone, Deserialize)]
pub(crate) struct Release {
    pub tag_name: String,
    #[serde(default)]
    pub draft: bool,
    #[serde(default)]
    pub prerelease: bool,
    #[serde(default)]
    pub assets: Vec<Asset>,
}

#[derive(Clone, Deserialize)]
pub(crate) struct Asset {
    pub name: String,
    pub browser_download_url: String,
}

#[derive(Debug)]
pub(crate) enum ReleaseVersionError {
    InvalidRequested { requested: String },
    InvalidLatestResponse { returned: String },
    InvalidExactResponse { requested: String, returned: String },
    MismatchedExactResponse { requested: String, returned: String },
}

impl std::fmt::Display for ReleaseVersionError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidRequested { requested } => write!(
                formatter,
                "requested release version `{requested}` is not canonical SemVer; pass a tag such as `--version v1.2.3` (valid prereleases such as `v1.2.3-rc.1` are accepted) and retry"
            ),
            Self::InvalidLatestResponse { returned } => write!(
                formatter,
                "GitHub returned malformed release tag `{returned}`; no update was selected. Retry later or pass a trusted exact tag such as `--version v1.2.3`"
            ),
            Self::InvalidExactResponse {
                requested,
                returned,
            } => write!(
                formatter,
                "requested release tag `{requested}`, but GitHub returned malformed tag `{returned}`; refusing release substitution before asset download. Verify the published tag and retry with `--version {requested}`"
            ),
            Self::MismatchedExactResponse {
                requested,
                returned,
            } => write!(
                formatter,
                "requested release tag `{requested}`, but GitHub returned `{returned}`; refusing release substitution before asset download. Verify the published tag and retry with `--version {requested}`"
            ),
        }
    }
}

impl std::error::Error for ReleaseVersionError {}

/// GitHub release-asset name for `keyhog` on a given host. Mirrors the asset
/// naming the release workflow + install.sh use. `None` for platforms without
/// a prebuilt asset.
pub(crate) fn asset_name(os: &str, arch: &str) -> Option<String> {
    match (os, arch) {
        ("linux", "x86_64") => Some("keyhog-linux-x86_64".into()),
        ("macos", "aarch64") => Some("keyhog-macos-aarch64".into()),
        ("macos", "x86_64") => Some("keyhog-macos-x86_64".into()),
        // release.yml uploads keyhog-windows-x86_64.exe; without this arm
        // `select_asset` returned None on Windows and `update`/`repair`
        // could never resolve an asset there.
        ("windows", "x86_64") => Some("keyhog-windows-x86_64.exe".into()),
        _ => None,
    }
}

pub(crate) fn parse_version(tag: &str) -> Option<semver::Version> {
    let value = match tag.strip_prefix('v') {
        Some(value) => value,
        None => tag,
    };
    match semver::Version::parse(value) {
        Ok(version) => Some(version),
        Err(_) => None, // LAW10: resolver validation turns this into a loud error before request/download; comparison returns false and selects no update on malformed input
    }
}

/// Validate an operator-supplied version and bind it to KeyHog's canonical
/// `v`-prefixed GitHub tag spelling before it enters a request URL.
pub(crate) fn normalize_requested_version(
    requested: &str,
) -> std::result::Result<String, ReleaseVersionError> {
    let parsed = parse_version(requested).ok_or_else(|| ReleaseVersionError::InvalidRequested {
        requested: requested.to_owned(),
    })?;
    let bare = parsed.to_string();
    let canonical = format!("v{bare}");
    if requested != bare && requested != canonical {
        return Err(ReleaseVersionError::InvalidRequested {
            requested: requested.to_owned(),
        });
    }
    Ok(canonical)
}

fn validate_latest_response_tag(returned: &str) -> std::result::Result<(), ReleaseVersionError> {
    parse_version(returned)
        .map(|_| ())
        .ok_or_else(|| ReleaseVersionError::InvalidLatestResponse {
            returned: returned.to_owned(),
        })
}

fn validate_exact_response_tag(
    requested: &str,
    returned: &str,
) -> std::result::Result<(), ReleaseVersionError> {
    let parsed =
        parse_version(returned).ok_or_else(|| ReleaseVersionError::InvalidExactResponse {
            requested: requested.to_owned(),
            returned: returned.to_owned(),
        })?;
    let normalized_returned = format!("v{parsed}");
    if returned != normalized_returned || returned != requested {
        return Err(ReleaseVersionError::MismatchedExactResponse {
            requested: requested.to_owned(),
            returned: returned.to_owned(),
        });
    }
    Ok(())
}

/// Parse the numeric core of a strict semantic version. Kept as the compact
/// tuple facade used by existing diagnostics/tests; ordering uses
/// [`parse_version`] so prerelease precedence is never discarded.
pub(crate) fn parse_semver(tag: &str) -> Option<(u64, u64, u64)> {
    let version = parse_version(tag)?;
    Some((version.major, version.minor, version.patch))
}

/// True if `latest` is a strictly newer semver than `current`. Unparseable
/// versions compare as "not newer" (fail safe: never auto-install on garbage).
pub(crate) fn is_newer(current: &str, latest: &str) -> bool {
    match (parse_version(current), parse_version(latest)) {
        (Some(c), Some(l)) => l.cmp_precedence(&c).is_gt(),
        _ => false,
    }
}

/// Where the running build sits relative to the newest tag the GitHub
/// binary-asset channel offers.
///
/// This channel is not the canonical release channel. Automatic releases
/// publish crates.io packages only, so the newest published asset can be many
/// versions behind the newest published KeyHog. Collapsing that state into
/// "already on the latest release" reported a stale install as current and
/// gave a `--check` caller a clean answer the channel could not actually
/// support (Law 10).
pub(crate) enum ReleaseChannelState {
    /// The channel offers a strictly newer tag than the running build.
    UpdateAvailable,
    /// The channel's newest tag is exactly the running build.
    OnNewestAsset,
    /// The running build is newer than anything the channel has published, so
    /// the channel cannot answer whether a newer KeyHog exists.
    ChannelBehind,
}

/// Classify `latest` (a resolved release tag) against the running `current`
/// version. Unparseable input classifies as [`ReleaseChannelState::OnNewestAsset`]
/// so a garbage tag never authorizes an install, matching [`is_newer`].
pub(crate) fn classify_channel(current: &str, latest: &str) -> ReleaseChannelState {
    if is_newer(current, latest) {
        return ReleaseChannelState::UpdateAvailable;
    }
    if is_newer(latest, current) {
        return ReleaseChannelState::ChannelBehind;
    }
    ReleaseChannelState::OnNewestAsset
}

/// Cheap guard against installing a non-executable (404 HTML page, truncated
/// download): check the platform's executable magic bytes.
pub(crate) fn looks_like_native_executable(bytes: &[u8]) -> bool {
    looks_like_native_executable_for_os(bytes, std::env::consts::OS)
}

pub(crate) fn looks_like_native_executable_for_os(bytes: &[u8], os: &str) -> bool {
    if bytes.len() < 4 {
        return false;
    }
    match os {
        "linux" => bytes.starts_with(&[0x7F, b'E', b'L', b'F']),
        "macos" => matches!(
            bytes[..4],
            [0xFE, 0xED, 0xFA, 0xCE]
                | [0xCE, 0xFA, 0xED, 0xFE]
                | [0xFE, 0xED, 0xFA, 0xCF]
                | [0xCF, 0xFA, 0xED, 0xFE]
                | [0xCA, 0xFE, 0xBA, 0xBE]
                | [0xBE, 0xBA, 0xFE, 0xCA]
        ),
        "windows" => bytes.starts_with(b"MZ"),
        _ => false,
    }
}

/// An HTTP client with the keyhog User-Agent GitHub's API requires.
pub(crate) fn http_client() -> Result<reqwest::Client> {
    reqwest::Client::builder()
        .user_agent(format!("keyhog/{}", env!("CARGO_PKG_VERSION")))
        .connect_timeout(RELEASE_CONNECT_TIMEOUT)
        .timeout(RELEASE_REQUEST_TIMEOUT)
        .build()
        .context("build HTTP client")
}

/// Resolve the release to operate on. With `version`, fetch that exact tag;
/// otherwise the most recent release that actually shipped assets (a release
/// can exist with zero assets if the workflow failed mid-upload).
pub(crate) async fn resolve_release(
    client: &reqwest::Client,
    version: Option<&str>,
) -> Result<Release> {
    resolve_release_at(client, version, RELEASE_API_BASE).await
}

pub(crate) async fn resolve_release_at(
    client: &reqwest::Client,
    version: Option<&str>,
    release_api_base: &str,
) -> Result<Release> {
    // Remote release-metadata fetch: source acquisition measured across awaits.
    keyhog_profile::instrument_future(keyhog_profile::Stage::SourceAcquire, async move {
    let api = release_api_base.trim().trim_end_matches('/');
    if api.is_empty() {
        anyhow::bail!("injected release API base is empty");
    }
    if let Some(requested) = version {
        // Validate before constructing or sending a request: untrusted CLI/test
        // input must never become a path or query fragment.
        let tag = normalize_requested_version(requested)?;
        let url = format!("{api}/repos/{REPO}/releases/tags/{tag}");
        let response = client.get(&url).send().await.context("query release tag")?;
        let bytes = read_limited_response(
            response,
            MAX_RELEASE_METADATA_BYTES,
            &format!("release tag {tag}"),
        )
        .await?;
        let release: Release = serde_json::from_slice(&bytes).context("parse release JSON")?;
        if release.draft {
            anyhow::bail!("release tag {tag} is still a draft and cannot be installed");
        }
        validate_exact_response_tag(&tag, &release.tag_name)?;
        Ok(release)
    } else {
    let url = format!("{api}/repos/{REPO}/releases?per_page=10");
    let response = client.get(&url).send().await.context("query releases")?;
    let bytes = read_limited_response(response, MAX_RELEASE_METADATA_BYTES, "release list").await?;
    let releases: Vec<Release> = serde_json::from_slice(&bytes).context("parse releases JSON")?;
    let release = releases
        .into_iter()
        .find(|release| {
            !release.draft && !release.prerelease && release_has_complete_host_bundle(release)
        })
        .ok_or_else(|| {
            anyhow!(
                "no recent stable GitHub release has the complete signed asset bundle for this host; pass --version to diagnose an exact tag"
            )
        })?;
    validate_latest_response_tag(&release.tag_name)?;
    Ok(release)
    }
    })
    .await
}

fn release_has_complete_host_bundle(release: &Release) -> bool {
    let Some(binary) = asset_name(std::env::consts::OS, std::env::consts::ARCH) else {
        return false;
    };
    let required = [
        binary.clone(),
        format!("{binary}.sha256"),
        format!("{binary}.minisig"),
        format!("{binary}.gpu-literals.tar.gz"),
        format!("{binary}.gpu-literals.tar.gz.sha256"),
        format!("{binary}.gpu-literals.tar.gz.minisig"),
    ];
    required
        .iter()
        .all(|name| find_unique_asset(release, name).is_ok())
}

fn find_unique_asset<'a>(release: &'a Release, name: &str) -> Result<&'a Asset> {
    let mut matches = release.assets.iter().filter(|asset| asset.name == name);
    let asset = matches
        .next()
        .ok_or_else(|| anyhow!("release {} has no asset named {name}", release.tag_name))?;
    if matches.next().is_some() {
        anyhow::bail!(
            "release {} contains duplicate assets named {name}; refusing ambiguous release metadata",
            release.tag_name
        );
    }
    Ok(asset)
}

pub(crate) async fn resolve_and_download_verified_payload_at(
    client: &reqwest::Client,
    version: Option<&str>,
    release_api_base: &str,
    asset_name: &str,
) -> Result<Vec<u8>> {
    let release = resolve_release_at(client, version, release_api_base).await?;
    let asset = find_unique_asset(&release, asset_name)?;
    keyhog_profile::instrument_future(
        keyhog_profile::Stage::SourceAcquire,
        download_verified_payload(
            client,
            &release,
            asset,
            MAX_RELEASE_ASSET_BYTES,
            "release test payload",
        ),
    )
    .await
}

/// Pick the one platform asset for this host. Runtime accelerator selection is
/// performed by backend probing and autoroute, not by release filenames.
pub(crate) fn select_asset(release: &Release) -> Result<&Asset> {
    // Host-asset planning, profiled as preprocessing.
    let _plan_span = keyhog_profile::span(keyhog_profile::Stage::Preprocess);
    let target = asset_name(std::env::consts::OS, std::env::consts::ARCH).ok_or_else(|| {
        anyhow!(
            "no prebuilt asset for {}-{} (supported: linux-x86_64, macos-aarch64, macos-x86_64, windows-x86_64)",
            std::env::consts::OS,
            std::env::consts::ARCH
        )
    })?;
    find_unique_asset(release, &target)
}

pub(crate) fn select_gpu_literal_asset<'a>(
    release: &'a Release,
    binary: &Asset,
) -> Result<&'a Asset> {
    find_unique_asset(release, &format!("{}.gpu-literals.tar.gz", binary.name))
}

/// Download an asset over HTTPS, confirm it is a native executable for this
/// platform, and verify both its detached minisign signature and exact
/// release-manifest SHA-256 entry before handing the bytes back.
pub(crate) async fn download_verified_asset(
    client: &reqwest::Client,
    release: &Release,
    asset: &Asset,
) -> Result<Vec<u8>> {
    let bytes = keyhog_profile::instrument_future(
        keyhog_profile::Stage::SourceAcquire,
        download_verified_payload(
            client,
            release,
            asset,
            MAX_RELEASE_ASSET_BYTES,
            "release asset",
        ),
    )
    .await?;
    if !looks_like_native_executable(&bytes) {
        return Err(anyhow!(
            "downloaded asset is not a {} executable ({} bytes) - refusing to install. \
             The release asset may be missing or the download was intercepted.",
            std::env::consts::OS,
            bytes.len()
        ));
    }

    Ok(bytes)
}

pub(crate) async fn download_verified_gpu_literal_asset(
    client: &reqwest::Client,
    release: &Release,
    asset: &Asset,
) -> Result<Vec<u8>> {
    keyhog_profile::instrument_future(
        keyhog_profile::Stage::SourceAcquire,
        download_verified_payload(
            client,
            release,
            asset,
            MAX_RELEASE_ASSET_BYTES,
            "GPU literal sidecar",
        ),
    )
    .await
}

async fn download_verified_payload(
    client: &reqwest::Client,
    release: &Release,
    asset: &Asset,
    max_bytes: usize,
    label: &str,
) -> Result<Vec<u8>> {
    let response = client
        .get(&asset.browser_download_url)
        .send()
        .await
        .with_context(|| format!("download {label} {}", asset.name))?;
    let bytes = read_limited_response(response, max_bytes, label).await?;

    // Signature: the release `sign` job uploads `<asset>.minisig` alongside
    // each binary and sidecar. Fetch and verify it. A 404 is a hard failure.
    let signature_name = format!("{}.minisig", asset.name);
    let signature_asset = find_unique_asset(release, &signature_name)?;
    let sig_resp = client
        .get(&signature_asset.browser_download_url)
        .send()
        .await
        .with_context(|| format!("download release signature {signature_name}"))?;
    if sig_resp.status() == reqwest::StatusCode::NOT_FOUND {
        // Fail CLOSED, unconditionally. A missing .minisig is indistinguishable
        // from an active attacker who serves a tampered binary and returns 404
        // for its signature. Every release is signed by the `sign` job, so a 404
        // here is a downgrade attack or a broken release; refuse either way.
        // There is deliberately NO opt-out: an ambient environment variable must
        // never be able to disable the signature gate that stands between a
        // tampered download and arbitrary code execution (config-policy mandate
        // + security). The minisign signature is the only proof.
        return Err(anyhow!(
            "release asset {} has no .minisig signature - refusing to install. A missing \
             signature can mean a tampered download intercepted the signature fetch, or a \
             broken release. Re-run the update against a properly signed release.",
            asset.name
        ));
    }
    let sig_bytes =
        read_limited_response(sig_resp, MAX_RELEASE_SIGNATURE_BYTES, "release signature").await?;
    let sig_text = std::str::from_utf8(&sig_bytes).context("release signature is not UTF-8")?;
    verify_release_signature(&bytes, &sig_text)
        .with_context(|| format!("verifying release asset {}", asset.name))?;

    let checksum_name = format!("{}.sha256", asset.name);
    let checksum_asset = find_unique_asset(release, &checksum_name)?;
    let checksum_response = client
        .get(&checksum_asset.browser_download_url)
        .send()
        .await
        .with_context(|| format!("download release checksum {checksum_name}"))?;
    let checksum_bytes = read_limited_response(
        checksum_response,
        MAX_RELEASE_CHECKSUM_BYTES,
        "release checksum",
    )
    .await?;
    verify_release_checksum(&bytes, &asset.name, &checksum_bytes)?;
    Ok(bytes)
}

pub(crate) fn verify_release_checksum(
    data: &[u8],
    asset_name: &str,
    checksum_file: &[u8],
) -> Result<()> {
    use sha2::{Digest as _, Sha256};

    // Manifest checksum verification, profiled as preprocessing (check phase).
    let _verify_span = keyhog_profile::span(keyhog_profile::Stage::Preprocess);
    let text = std::str::from_utf8(checksum_file).context("release checksum is not UTF-8")?;
    let mut fields = text.split_whitespace();
    let expected = fields
        .next()
        .ok_or_else(|| anyhow!("release checksum for {asset_name} is empty"))?;
    if expected.len() != 64 || !expected.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        anyhow::bail!("release checksum for {asset_name} is not a 64-digit SHA-256 digest");
    }
    if let Some(label) = fields.next() {
        let label = label.strip_prefix('*').unwrap_or(label); // LAW10: optional binary-mode `*` prefix; the same filename label is validated below
        if label != asset_name {
            anyhow::bail!(
                "release checksum labels `{label}` but payload is `{asset_name}`; refusing mismatched manifest"
            );
        }
    }
    if fields.next().is_some() {
        anyhow::bail!("release checksum for {asset_name} contains unexpected trailing fields");
    }
    let actual = keyhog_core::hex_encode(&Sha256::digest(data));
    if !actual.eq_ignore_ascii_case(expected) {
        anyhow::bail!(
            "release checksum mismatch for {asset_name}: expected {expected}, calculated {actual}"
        );
    }
    Ok(())
}

async fn read_limited_response(
    response: reqwest::Response,
    max_bytes: usize,
    label: &str,
) -> Result<Vec<u8>> {
    use futures_util::StreamExt as _;

    let response = response
        .error_for_status()
        .with_context(|| format!("{label} HTTP status"))?;
    if response
        .content_length()
        .is_some_and(|length| length > max_bytes as u64)
    {
        anyhow::bail!("{label} exceeds the {max_bytes}-byte download limit");
    }
    let capacity = response
        .content_length()
        .and_then(|length| usize::try_from(length).ok()) // LAW10: perf-only allocation hint; streamed byte counting below enforces the hard response limit
        .map_or(0, |length| length.min(MAX_RESPONSE_PREALLOC_BYTES));
    let mut body = Vec::with_capacity(capacity);
    let mut stream = response.bytes_stream();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk.with_context(|| format!("read {label} body"))?;
        if body.len().saturating_add(chunk.len()) > max_bytes {
            anyhow::bail!("{label} exceeds the {max_bytes}-byte download limit");
        }
        body.extend_from_slice(&chunk);
    }
    Ok(body)
}

/// End-to-end CPU/SIMD scan-engine self-test: compile a synthetic one-detector
/// scanner without acquiring GPU drivers, plant a matching secret, and confirm
/// it round-trips through compile -> scan -> extract -> report. GPU health has
/// its own doctor probes. Uses a unique prefix so it neither collides with a
/// real detector nor trips example or placeholder suppression.
pub(crate) fn scan_engine_self_test() -> Result<bool> {
    // Self-test detector compile + scan: doctor's compute phase, profiled as
    // preprocessing.
    let _self_test_span = keyhog_profile::span(keyhog_profile::Stage::Preprocess);
    const PLANTED: &str = "KHDOCTOR_A1b2C3d4E5f6";
    let detector =
        toml::from_str::<DetectorFile>(include_str!("../../data/doctor-self-test-detector.toml"))
            .context("bundled doctor self-test detector TOML is invalid")?
            .detector;
    let scanner = CompiledScanner::compile_with_gpu_policy(
        vec![detector],
        keyhog_scanner::GpuInitPolicy::ForceDisabled,
    )?;
    let chunk = Chunk {
        data: format!("api_secret = {PLANTED}").into(),
        metadata: ChunkMetadata {
            source_type: "doctor".into(),
            path: Some("doctor-selftest.txt".into()),
            ..Default::default()
        },
    };
    let matches = scanner.scan_with_backend(&chunk, ScanBackend::CpuFallback)?;
    Ok(matches.iter().any(|m| m.credential.as_ref() == PLANTED))
}