Skip to main content

varve_core/
reverify.rs

1//! Re-verification of an installed layer (REQ-VERIFY-001) — `varve verify`.
2//!
3//! The install-time verdict, repeatable forever after: the retained envelope
4//! must verify against the trust root, its payload must be byte-identical to
5//! the layer.json in the core, and every tool binary must match its digest in
6//! the signed manifest. Corruption, tampering, and bit-rot all surface as the
7//! same loud failure — and "I cannot check" (no envelope retained) is its own
8//! distinct verdict, never silently treated as success.
9
10use crate::install::{ManifestVerifier, VerifyError};
11use crate::manifest::{LayerManifest, ManifestError};
12use crate::store::{InstalledLayer, Store, StoreError};
13
14/// The file the install pipeline retains alongside `layer.json` so the
15/// signature verdict stays reproducible offline.
16pub const ENVELOPE_FILE: &str = "layer.dsse.json";
17
18#[derive(Debug, thiserror::Error)]
19pub enum ReverifyError {
20    #[error(
21        "layer {digest} has no retained signature envelope ({ENVELOPE_FILE}) — cannot re-verify \
22         its signature; reinstall from a signed source"
23    )]
24    NoEnvelope { digest: String },
25    #[error(transparent)]
26    Verify(#[from] VerifyError),
27    #[error(
28        "retained envelope verifies, but its payload does not match layer.json — the core entry \
29         was modified after install"
30    )]
31    PayloadMismatch,
32    #[error(transparent)]
33    Manifest(#[from] ManifestError),
34    #[error("payload '{tool}' is missing from the installed layer")]
35    MissingTool { tool: String },
36    /// The platform filter matched nothing, so nothing was checked.
37    ///
38    /// Reported as a REFUSAL because the alternative is that "this layer
39    /// carries no payload for your platform" and "every payload of this layer
40    /// is intact" are the same answer. A verification that checked nothing is
41    /// not a verification, and it is the cheapest thing to arrange: it needs
42    /// no altered bytes, only a platform nothing matches (varve#189).
43    #[error(
44        "verified nothing: layer {layer} carries {available} payload(s), none of them for \
45         platform '{platform}'. It carries: {carried}. If this layer was installed for \
46         another platform, verify it for that one."
47    )]
48    NothingToVerify {
49        layer: String,
50        platform: String,
51        available: usize,
52        carried: String,
53    },
54    #[error("payload '{tool}' does not match its signed digest {digest} — its bytes were altered")]
55    ToolDigestMismatch { tool: String, digest: String },
56    #[error(transparent)]
57    Store(#[from] StoreError),
58    #[error("io error at {path}: {source}")]
59    Io {
60        path: String,
61        #[source]
62        source: std::io::Error,
63    },
64}
65
66/// How to name a payload in a verdict. A layer may hold several versions of one
67/// name, so the bare name no longer identifies WHICH payload failed — and a
68/// verification tool that cannot say which artifact is wrong has not reported
69/// the fault (REQ-STORE-002 clause 4).
70fn named(entry: &crate::manifest::ManifestEntry, name: &str) -> String {
71    match crate::store::entry_version(entry) {
72        Some(version) => format!("{name}@{version}"),
73        None => name.to_string(),
74    }
75}
76
77/// Where `verify` spent its time (REQ-VERIFYSTREAM-001 clause 2).
78///
79/// Attributed by stage so the NEXT change is chosen from a measurement. The
80/// report that started this (varve#141: ~9 s on a layer with a 2 GB SDK) was
81/// answered once with a guess about parallelising the hash, and the arithmetic
82/// said the hash could not be the cost. This is what settles such a question.
83///
84/// No `decompress` stage exists because verify does not decompress: a payload
85/// is hashed exactly as signed, which is what keeps the digest re-derivable.
86#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
87pub struct VerifyTiming {
88    /// Verifying the retained DSSE envelope against the trust root.
89    pub signature: std::time::Duration,
90    /// Reading and parsing `layer.json`, and comparing it with the payload.
91    pub manifest: std::time::Duration,
92    /// The payloads: read and hash, summed, with the total bytes.
93    pub payloads: crate::store::StageTiming,
94    /// How many payloads were digested — the denominator for a per-payload rate.
95    pub checked: usize,
96}
97
98/// Re-verify one installed layer against the trust root. Returns the number
99/// of tool binaries checked.
100pub fn verify_installed(
101    store: &Store,
102    layer: &InstalledLayer,
103    verifier: &dyn ManifestVerifier,
104    platform: &str,
105) -> Result<usize, ReverifyError> {
106    verify_installed_timed(store, layer, verifier, platform).map(|(checked, _)| checked)
107}
108
109/// Steps 1 and 2 of [`verify_installed`] and nothing else: the layer's
110/// retained envelope verifies against `verifier`, and its payload is the
111/// manifest the store holds. No payload is hashed, so it costs one signature
112/// check and one small read — cheap enough to run on every dispatch, which is
113/// where a realmless pin uses it (REQ-NOPINNOTOOL-001 clause 2: a configured
114/// root that signed nothing in the store vouches for nothing).
115pub fn verify_retained_envelope(
116    layer: &InstalledLayer,
117    verifier: &dyn ManifestVerifier,
118) -> Result<(), ReverifyError> {
119    retained_payload(layer, verifier, &mut VerifyTiming::default()).map(|_| ())
120}
121
122fn retained_payload(
123    layer: &InstalledLayer,
124    verifier: &dyn ManifestVerifier,
125    timing: &mut VerifyTiming,
126) -> Result<Vec<u8>, ReverifyError> {
127    let io = |path: &std::path::Path, source: std::io::Error| ReverifyError::Io {
128        path: path.display().to_string(),
129        source,
130    };
131    // 1. The retained envelope must exist and verify against the trust root.
132    let envelope_path = layer.root.join(ENVELOPE_FILE);
133    let envelope = match std::fs::read(&envelope_path) {
134        Ok(bytes) => bytes,
135        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
136            return Err(ReverifyError::NoEnvelope {
137                digest: layer.digest.clone(),
138            });
139        }
140        Err(e) => return Err(io(&envelope_path, e)),
141    };
142    let t = std::time::Instant::now();
143    let payload = verifier.verify(&envelope)?;
144    timing.signature = t.elapsed();
145
146    // 2. The verified payload must be byte-identical to the stored manifest.
147    let manifest_path = layer.root.join("layer.json");
148    let stored = std::fs::read(&manifest_path).map_err(|e| io(&manifest_path, e))?;
149    if payload != stored {
150        return Err(ReverifyError::PayloadMismatch);
151    }
152    Ok(payload)
153}
154
155/// [`verify_installed`], reporting where the time went.
156///
157/// The timing rides on the real verification path — the same function every
158/// caller uses — because a number measured by a separate copy of the code is a
159/// number about the copy.
160pub fn verify_installed_timed(
161    store: &Store,
162    layer: &InstalledLayer,
163    verifier: &dyn ManifestVerifier,
164    platform: &str,
165) -> Result<(usize, VerifyTiming), ReverifyError> {
166    let mut timing = VerifyTiming::default();
167    let io = |path: &std::path::Path, source: std::io::Error| ReverifyError::Io {
168        path: path.display().to_string(),
169        source,
170    };
171
172    // 1 and 2: the retained envelope verifies, and says what the store holds.
173    let payload = retained_payload(layer, verifier, &mut timing)?;
174    let t = std::time::Instant::now();
175
176    // 3. Every tool the signed manifest names must be present and unaltered.
177    let manifest = LayerManifest::parse(&payload)?;
178    timing.manifest = t.elapsed();
179    let mut checked = 0;
180    for entry in &manifest.entries {
181        if !crate::platform::entry_matches(
182            entry
183                .annotations
184                .get(crate::platform::ANN_PLATFORM)
185                .map(String::as_str),
186            platform,
187        ) {
188            continue;
189        }
190        // A composed layer is a REFERENCE to another layer's manifest, not a
191        // blob laid down here; install skips it and so must re-verification.
192        if entry.kind() == Ok(crate::kind::PayloadKind::Layer) {
193            continue;
194        }
195        let Some(tool) = entry.annotations.get("eu.pulseengine.tool") else {
196            continue;
197        };
198        // Locate by ENTRY, not by name: several versions of one name coexist,
199        // and each must be checked against its own signed digest
200        // (REQ-STORE-002 clause 4).
201        let Some(path) = store.entry_path(layer, entry) else {
202            return Err(ReverifyError::MissingTool {
203                tool: named(entry, tool),
204            });
205        };
206        // Streamed, in bounded memory (REQ-VERIFYSTREAM-001). The bytes are
207        // only ever needed to HASH here, so reading a 2 GB SDK whole to do it
208        // was a 2 GB allocation per payload for nothing (varve#141).
209        let (found, stage) = crate::store::digest_file_timed(&path).map_err(|e| io(&path, e))?;
210        timing.payloads.add(stage);
211        if found != entry.digest {
212            return Err(ReverifyError::ToolDigestMismatch {
213                tool: named(entry, tool),
214                digest: entry.digest.clone(),
215            });
216        }
217        checked += 1;
218    }
219    // A platform filter that matched nothing must not read as success.
220    // `checked == 0` is only acceptable when the layer genuinely has no
221    // payloads at all — a composition-only layer, which install already
222    // learned to accept (REQ-COMPOSE-001).
223    let payload_entries = manifest
224        .entries
225        .iter()
226        .filter(|e| e.kind() != Ok(crate::kind::PayloadKind::Layer))
227        .count();
228    if checked == 0 && payload_entries > 0 {
229        let mut carried: Vec<&str> = manifest
230            .entries
231            .iter()
232            .filter(|e| e.kind() != Ok(crate::kind::PayloadKind::Layer))
233            .map(|e| {
234                e.annotations
235                    .get(crate::platform::ANN_PLATFORM)
236                    .map(String::as_str)
237                    .unwrap_or("any")
238            })
239            .collect();
240        carried.sort_unstable();
241        carried.dedup();
242        return Err(ReverifyError::NothingToVerify {
243            layer: layer.layer.to_string(),
244            platform: platform.to_string(),
245            available: payload_entries,
246            carried: carried.join(", "),
247        });
248    }
249    timing.checked = checked;
250    Ok((checked, timing))
251}
252
253#[cfg(test)]
254mod tests {
255    /// True when mode 000 does not actually deny a read here (running as root,
256    /// or a filesystem that ignores permission bits) — so the unreadable-file
257    /// tests cannot hold their premise and must skip rather than fail.
258    #[cfg(unix)]
259    fn premise_unavailable() -> bool {
260        use std::os::unix::fs::PermissionsExt;
261        let Ok(dir) = tempfile::tempdir() else {
262            return true;
263        };
264        let probe = dir.path().join("probe");
265        if std::fs::write(&probe, b"x").is_err() {
266            return true;
267        }
268        if std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o000)).is_err() {
269            return true;
270        }
271        let readable = std::fs::read(&probe).is_ok();
272        let _ = std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o644));
273        readable
274    }
275
276    use super::*;
277    use crate::install::{InstallPolicy, install};
278    use crate::manifest::fixtures::manifest_with_tools;
279    use crate::pin::Pin;
280    use crate::rollback::HighWaterMarks;
281    use crate::source::MemorySource;
282    use crate::store::manifest_digest;
283    use crate::verify::{PinnedKeyVerifier, generate_root_keypair, sign_layer_manifest};
284
285    struct Installed {
286        _tmp: tempfile::TempDir,
287        store: Store,
288        layer: InstalledLayer,
289        verifier: PinnedKeyVerifier,
290    }
291
292    fn installed_layer() -> Installed {
293        let (sk, pk) = generate_root_keypair();
294        let synth = b"synth-bytes".to_vec();
295        let blob_digest = manifest_digest(&synth);
296        let payload = manifest_with_tools(
297            "2026.07.0",
298            "qualified",
299            1,
300            "2026-07-31T09:14:00Z",
301            &[("synth", &blob_digest)],
302        );
303        let envelope = sign_layer_manifest(&payload, &sk, "varve-root-1").unwrap();
304        let source = MemorySource::new()
305            .with_manifest(envelope.as_bytes())
306            .with_blob(&blob_digest, &synth);
307        let pin = Pin::parse(
308            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\n",
309            "varve.toml",
310        )
311        .unwrap();
312        let tmp = tempfile::tempdir().unwrap();
313        let root = tmp.path().join("root");
314        let store = Store::at(&root);
315        let mut marks = HighWaterMarks::load(&root).unwrap();
316        let verifier = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
317        let policy = InstallPolicy {
318            index: None,
319            now: "2026-08-07T00:00:00Z",
320            staleness_threshold_days: 90,
321            platform: "test-platform",
322        };
323        let outcome = install(&pin, &source, &verifier, &store, &mut marks, &policy).unwrap();
324        let layer = store.get(&outcome.digest).unwrap().unwrap();
325        Installed {
326            _tmp: tmp,
327            store,
328            layer,
329            verifier,
330        }
331    }
332
333    /// A layer installed FOR one platform, as `--platform` produces.
334    fn installed_for(install_platform: &str) -> Installed {
335        let (sk, pk) = generate_root_keypair();
336        let linux = b"wac-linux-bytes".to_vec();
337        let mac = b"wac-darwin-bytes".to_vec();
338        let (dl, dm) = (manifest_digest(&linux), manifest_digest(&mac));
339        let payload = crate::manifest::fixtures::manifest_with_platform_tools(
340            "2026.07.0",
341            "qualified",
342            1,
343            "2026-07-31T09:14:00Z",
344            &[
345                ("wac", &dl, Some("x86_64-unknown-linux-gnu")),
346                ("wac", &dm, Some("aarch64-apple-darwin")),
347            ],
348        );
349        let envelope = sign_layer_manifest(&payload, &sk, "varve-root-1").unwrap();
350        let source = MemorySource::new()
351            .with_manifest(envelope.as_bytes())
352            .with_blob(&dl, &linux)
353            .with_blob(&dm, &mac);
354        let pin = Pin::parse(
355            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\n",
356            "varve.toml",
357        )
358        .unwrap();
359        let tmp = tempfile::tempdir().unwrap();
360        let root = tmp.path().join("root");
361        let store = Store::at(&root);
362        let mut marks = HighWaterMarks::load(&root).unwrap();
363        let verifier = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
364        let policy = InstallPolicy {
365            index: None,
366            now: "2026-08-07T00:00:00Z",
367            staleness_threshold_days: 90,
368            platform: install_platform,
369        };
370        let outcome = install(&pin, &source, &verifier, &store, &mut marks, &policy).unwrap();
371        let layer = store.get(&outcome.digest).unwrap().unwrap();
372        Installed {
373            _tmp: tmp,
374            store,
375            layer,
376            verifier,
377        }
378    }
379
380    /// A composition-only layer checks zero payloads and that is CORRECT.
381    ///
382    /// The refusal added for varve#189 keys on `payload_entries > 0`, and a
383    /// mutant weakening that to `>= 0` survived: nothing distinguished "this
384    /// layer has payloads and none matched" from "this layer has no payloads
385    /// at all". The second is a whole supported layer kind — `install`
386    /// learned it at REQ-COMPOSE-001 and refusing it here would break every
387    /// composition-only pin.
388    // rivet: verifies REQ-COMPOSE-001
389    #[test]
390    fn a_composition_only_layer_verifies_although_it_checks_nothing() {
391        let (sk, pk) = generate_root_keypair();
392        let payload = format!(
393            r#"{{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json",
394 "artifactType":"application/vnd.pulseengine.varve.layer.v1+json",
395 "annotations":{{"eu.pulseengine.varve.layer":"2026.07.0",
396 "eu.pulseengine.varve.line":"2026.07","eu.pulseengine.varve.channel":"qualified",
397 "eu.pulseengine.varve.counter":"1",
398 "org.opencontainers.image.created":"2026-07-31T09:14:00Z"}},
399 "manifests":[{{"digest":"sha256:{d}","size":0,
400 "annotations":{{"{k}":"layer","eu.pulseengine.varve.include.realm":"other"}}}}]}}"#,
401            d = "0".repeat(64),
402            k = crate::kind::ANN_KIND,
403        )
404        .into_bytes();
405        let envelope = sign_layer_manifest(&payload, &sk, "varve-root-1").unwrap();
406        let source = MemorySource::new().with_manifest(envelope.as_bytes());
407        let pin = Pin::parse(
408            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\n",
409            "varve.toml",
410        )
411        .unwrap();
412        let tmp = tempfile::tempdir().unwrap();
413        let root = tmp.path().join("root");
414        let store = Store::at(&root);
415        let mut marks = HighWaterMarks::load(&root).unwrap();
416        let verifier = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
417        let policy = InstallPolicy {
418            index: None,
419            now: "2026-08-07T00:00:00Z",
420            staleness_threshold_days: 90,
421            platform: "x86_64-unknown-linux-gnu",
422        };
423        let outcome = install(&pin, &source, &verifier, &store, &mut marks, &policy).unwrap();
424        let layer = store.get(&outcome.digest).unwrap().unwrap();
425        let checked = verify_installed(&store, &layer, &verifier, "x86_64-unknown-linux-gnu")
426            .expect("a composition-only layer must verify, not be refused for checking nothing");
427        assert_eq!(checked, 0, "it has no payloads of its own to check");
428    }
429
430    /// The dispatch-time check: the retained envelope must verify against the
431    /// root in scope — and against THAT root, not any key. FOUND by the second
432    /// v0.43.0 clean-room review: a realmless pin dispatched a layer under an
433    /// unrelated VARVE_TRUST_ROOT that `verify` refused.
434    // rivet: verifies REQ-NOPINNOTOOL-001
435    #[test]
436    fn the_retained_envelope_vouches_only_under_the_root_that_signed_it() {
437        let (sk, pk) = generate_root_keypair();
438        let (_, stranger) = generate_root_keypair();
439        let payload = format!(
440            r#"{{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json",
441 "artifactType":"application/vnd.pulseengine.varve.layer.v1+json",
442 "annotations":{{"eu.pulseengine.varve.layer":"2026.07.0",
443 "eu.pulseengine.varve.line":"2026.07","eu.pulseengine.varve.channel":"qualified",
444 "eu.pulseengine.varve.counter":"1",
445 "org.opencontainers.image.created":"2026-07-31T09:14:00Z"}},
446 "manifests":[{{"digest":"sha256:{d}","size":0,
447 "annotations":{{"{k}":"layer","eu.pulseengine.varve.include.realm":"other"}}}}]}}"#,
448            d = "0".repeat(64),
449            k = crate::kind::ANN_KIND,
450        )
451        .into_bytes();
452        let envelope = sign_layer_manifest(&payload, &sk, "varve-root-1").unwrap();
453        let source = MemorySource::new().with_manifest(envelope.as_bytes());
454        let pin = Pin::parse(
455            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\n",
456            "varve.toml",
457        )
458        .unwrap();
459        let tmp = tempfile::tempdir().unwrap();
460        let root = tmp.path().join("root");
461        let store = Store::at(&root);
462        let mut marks = HighWaterMarks::load(&root).unwrap();
463        let verifier = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
464        let policy = InstallPolicy {
465            index: None,
466            now: "2026-08-07T00:00:00Z",
467            staleness_threshold_days: 90,
468            platform: "x86_64-unknown-linux-gnu",
469        };
470        let outcome = install(&pin, &source, &verifier, &store, &mut marks, &policy).unwrap();
471        let layer = store.get(&outcome.digest).unwrap().unwrap();
472
473        verify_retained_envelope(&layer, &verifier).expect("the signing root vouches");
474        let other = PinnedKeyVerifier::from_public_key_bytes(&stranger).unwrap();
475        assert!(
476            verify_retained_envelope(&layer, &other).is_err(),
477            "a root that signed nothing here must not vouch for it"
478        );
479        std::fs::write(layer.root.join("layer.json"), b"{}").unwrap();
480        assert!(
481            matches!(
482                verify_retained_envelope(&layer, &verifier),
483                Err(ReverifyError::PayloadMismatch)
484            ),
485            "a manifest that differs from what was signed must not vouch"
486        );
487        std::fs::remove_file(layer.root.join(ENVELOPE_FILE)).unwrap();
488        assert!(
489            matches!(
490                verify_retained_envelope(&layer, &verifier),
491                Err(ReverifyError::NoEnvelope { .. })
492            ),
493            "no retained envelope, nothing to vouch with"
494        );
495    }
496
497    /// The refusal has to name the platforms the layer ACTUALLY carries.
498    ///
499    /// Without this, a mutant inverting the filter that builds that list
500    /// survived: the message would have listed the composition edges instead
501    /// of the payloads, and an operator would be told to try a platform the
502    /// layer has nothing for.
503    // rivet: verifies REQ-VERIFY-001
504    #[test]
505    fn the_refusal_names_the_platforms_the_layer_does_carry() {
506        let i = installed_for("x86_64-unknown-linux-gnu");
507        let err = verify_installed(
508            &i.store,
509            &i.layer,
510            &i.verifier,
511            "riscv64gc-unknown-linux-gnu",
512        )
513        .unwrap_err();
514        let msg = err.to_string();
515        for expected in ["x86_64-unknown-linux-gnu", "aarch64-apple-darwin"] {
516            assert!(
517                msg.contains(expected),
518                "the refusal does not name {expected}, which this layer carries: {msg}"
519            );
520        }
521        assert!(msg.contains("riscv64gc-unknown-linux-gnu"), "{msg}");
522    }
523
524    /// varve#189: a layer installed FOR another platform verifies, and is
525    /// not accused of tampering.
526    ///
527    /// Reported from a Mac installing a Linux toolchain — legitimate, and the
528    /// thing `--platform` exists for. `verify` resolved the HOST, matched the
529    /// darwin entry, hashed the linux bytes that were actually laid down, and
530    /// said "its bytes were altered". The bytes were exactly what was signed;
531    /// the platform was the wrong question. Install records which platform it
532    /// chose, and verify asks that instead of the host.
533    // rivet: verifies REQ-VERIFY-001
534    #[test]
535    fn a_layer_installed_for_another_platform_verifies_against_that_platform() {
536        let i = installed_for("x86_64-unknown-linux-gnu");
537        assert_eq!(
538            i.layer.platform.as_deref(),
539            Some("x86_64-unknown-linux-gnu"),
540            "install did not record the platform it selected payloads for"
541        );
542        let plat = i.layer.platform.clone().unwrap();
543        let checked = verify_installed(&i.store, &i.layer, &i.verifier, &plat)
544            .expect("a layer installed for another platform must verify");
545        assert_eq!(checked, 1, "the linux payload was not the one checked");
546    }
547
548    /// The exact false accusation varve#189 reported, pinned so it cannot
549    /// come back: asking about the HOST names bytes that were never there.
550    // rivet: verifies REQ-VERIFY-001
551    #[test]
552    fn asking_the_wrong_platform_is_what_produced_the_false_tamper_claim() {
553        let i = installed_for("x86_64-unknown-linux-gnu");
554        let out = verify_installed(&i.store, &i.layer, &i.verifier, "aarch64-apple-darwin");
555        assert!(
556            matches!(out, Err(ReverifyError::MissingTool { .. }))
557                || matches!(out, Err(ReverifyError::ToolDigestMismatch { .. })),
558            "expected the host-platform question to fail; got {out:?}"
559        );
560        // …and the recorded platform is what saves the caller from asking it.
561        assert_eq!(
562            i.layer.platform.as_deref(),
563            Some("x86_64-unknown-linux-gnu")
564        );
565    }
566
567    /// Verifying against a platform the layer carries NOTHING for must refuse.
568    ///
569    /// Found while fixing varve#189. `verify_installed` filters entries by
570    /// platform and counts what it checked; nothing anywhere refused a count
571    /// of zero, so "this layer has no payload for your platform" and "every
572    /// payload of this layer is intact" were the same answer — `Ok`. A
573    /// verification that checked nothing is not a verification, and it is the
574    /// shape an attacker would pick: it needs no bad bytes, only a platform
575    /// nothing matches.
576    // rivet: verifies REQ-VERIFY-001
577    #[test]
578    fn verifying_against_a_platform_the_layer_carries_nothing_for_is_refused() {
579        let i = installed_for("x86_64-unknown-linux-gnu");
580        let out = verify_installed(
581            &i.store,
582            &i.layer,
583            &i.verifier,
584            "riscv64gc-unknown-linux-gnu",
585        );
586        assert!(
587            matches!(out, Err(ReverifyError::NothingToVerify { .. })),
588            "verifying a layer for a platform it carries nothing for did not refuse: {out:?}"
589        );
590    }
591
592    // rivet: verifies REQ-VERIFY-001
593    #[test]
594    fn a_freshly_installed_layer_reverifies() {
595        let ctx = installed_layer();
596        let checked =
597            verify_installed(&ctx.store, &ctx.layer, &ctx.verifier, "test-platform").unwrap();
598        assert_eq!(checked, 1);
599    }
600
601    /// A signed layer holding TWO versions of one crate, installed.
602    fn installed_two_versions() -> (Installed, Vec<u8>, Vec<u8>) {
603        use crate::manifest::fixtures::manifest_with_payloads;
604        let (sk, pk) = generate_root_keypair();
605        let a = b"serde-1.0.200-crate".to_vec();
606        let b = b"serde-1.0.210-crate".to_vec();
607        let (da, db) = (manifest_digest(&a), manifest_digest(&b));
608        let payload = manifest_with_payloads(
609            "2026.07.0",
610            "qualified",
611            1,
612            "2026-07-31T09:14:00Z",
613            &[
614                ("serde", "1.0.200", "crate", &da),
615                ("serde", "1.0.210", "crate", &db),
616            ],
617        );
618        let envelope = sign_layer_manifest(&payload, &sk, "varve-root-1").unwrap();
619        let source = MemorySource::new()
620            .with_manifest(envelope.as_bytes())
621            .with_blob(&da, &a)
622            .with_blob(&db, &b);
623        let pin = Pin::parse(
624            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\n",
625            "varve.toml",
626        )
627        .unwrap();
628        let tmp = tempfile::tempdir().unwrap();
629        let root = tmp.path().join("root");
630        let store = Store::at(&root);
631        let mut marks = HighWaterMarks::load(&root).unwrap();
632        let verifier = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
633        let policy = InstallPolicy {
634            index: None,
635            now: "2026-08-07T00:00:00Z",
636            staleness_threshold_days: 90,
637            platform: "test-platform",
638        };
639        let outcome = install(&pin, &source, &verifier, &store, &mut marks, &policy).unwrap();
640        let layer = store.get(&outcome.digest).unwrap().unwrap();
641        (
642            Installed {
643                _tmp: tmp,
644                store,
645                layer,
646                verifier,
647            },
648            a,
649            b,
650        )
651    }
652
653    // rivet: verifies REQ-STORE-002
654    #[test]
655    fn each_version_of_one_name_is_checked_against_its_own_signed_digest() {
656        // Clause 4, verification half. `verify_installed` looked payloads up by
657        // NAME, so with two versions present it would have hashed one file
658        // twice — passing the entry whose bytes happened to land and failing
659        // the other, with a verdict that named only "serde" and could not say
660        // which. Both are checked here, and tampering with EITHER is caught and
661        // named with its version.
662        let (ctx, a, b) = installed_two_versions();
663        assert_eq!(
664            verify_installed(&ctx.store, &ctx.layer, &ctx.verifier, "test-platform").unwrap(),
665            2,
666            "both versions must be checked, not one file twice"
667        );
668        // The bytes on disk really are each version's own.
669        assert_eq!(
670            std::fs::read(ctx.layer.root.join("payloads/serde/1.0.200")).unwrap(),
671            a
672        );
673        assert_eq!(
674            std::fs::read(ctx.layer.root.join("payloads/serde/1.0.210")).unwrap(),
675            b
676        );
677
678        for (version, path) in [
679            ("1.0.200", "payloads/serde/1.0.200"),
680            ("1.0.210", "payloads/serde/1.0.210"),
681        ] {
682            let (ctx, ..) = installed_two_versions();
683            std::fs::write(ctx.layer.root.join(path), b"EVIL").unwrap();
684            let err = verify_installed(&ctx.store, &ctx.layer, &ctx.verifier, "test-platform")
685                .unwrap_err();
686            assert!(
687                matches!(&err, ReverifyError::ToolDigestMismatch { tool, .. }
688                    if tool == &format!("serde@{version}")),
689                "tampering with {version} must be caught AND named: {err}"
690            );
691        }
692
693        // A payload that is simply gone is named with its version too — with
694        // two versions present, "serde is missing" would not say which.
695        let (ctx, ..) = installed_two_versions();
696        std::fs::remove_file(ctx.layer.root.join("payloads/serde/1.0.210")).unwrap();
697        let err =
698            verify_installed(&ctx.store, &ctx.layer, &ctx.verifier, "test-platform").unwrap_err();
699        assert!(
700            matches!(&err, ReverifyError::MissingTool { tool } if tool == "serde@1.0.210"),
701            "got: {err}"
702        );
703    }
704
705    // rivet: verifies REQ-VERIFY-001
706    #[test]
707    fn install_retains_the_envelope_for_offline_reverification() {
708        let ctx = installed_layer();
709        assert!(
710            ctx.layer.root.join(ENVELOPE_FILE).is_file(),
711            "install must retain the signature envelope"
712        );
713    }
714
715    // rivet: verifies REQ-VERIFY-001
716    #[test]
717    fn an_altered_tool_binary_is_detected() {
718        let ctx = installed_layer();
719        std::fs::write(ctx.layer.root.join("bin/synth"), b"EVIL").unwrap();
720        let err =
721            verify_installed(&ctx.store, &ctx.layer, &ctx.verifier, "test-platform").unwrap_err();
722        assert!(
723            matches!(err, ReverifyError::ToolDigestMismatch { ref tool, .. } if tool == "synth"),
724            "got: {err}"
725        );
726    }
727
728    // rivet: verifies REQ-VERIFY-001
729    #[test]
730    fn an_altered_manifest_payload_is_detected() {
731        let ctx = installed_layer();
732        let path = ctx.layer.root.join("layer.json");
733        let mut bytes = std::fs::read(&path).unwrap();
734        bytes.extend_from_slice(b" ");
735        std::fs::write(&path, bytes).unwrap();
736        let err =
737            verify_installed(&ctx.store, &ctx.layer, &ctx.verifier, "test-platform").unwrap_err();
738        assert!(matches!(err, ReverifyError::PayloadMismatch), "got: {err}");
739    }
740
741    // rivet: verifies REQ-PROOF-001
742    #[cfg(unix)]
743    #[test]
744    fn an_unreadable_envelope_is_an_io_error_not_a_missing_one() {
745        // An envelope that EXISTS but cannot be read is not a layer installed
746        // without one. Collapsing the two would report "no retained envelope"
747        // for what is really a permissions fault — a verification tool must
748        // name the fault it actually hit. (Found by cargo-mutants: the
749        // NotFound guard survived being replaced with `true`.)
750        // chmod(000) does not stop root, and some filesystems ignore modes, so
751        // this case cannot always be exercised. Test the PREMISE directly
752        // rather than guessing at uid: if an unreadable file is still readable
753        // here, skip. A test that cannot hold its premise should say so, not go
754        // red for the wrong reason.
755        if premise_unavailable() {
756            eprintln!("skipping: this environment does not deny reads on mode 000");
757            return;
758        }
759        use std::os::unix::fs::PermissionsExt;
760        let ctx = installed_layer();
761        let path = ctx.layer.root.join(ENVELOPE_FILE);
762        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();
763        let err =
764            verify_installed(&ctx.store, &ctx.layer, &ctx.verifier, "test-platform").unwrap_err();
765        let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644));
766        assert!(
767            matches!(err, ReverifyError::Io { .. }),
768            "an unreadable envelope must be an Io error, got: {err}"
769        );
770    }
771
772    // rivet: verifies REQ-VERIFY-001
773    #[test]
774    fn a_missing_envelope_is_its_own_loud_verdict() {
775        let ctx = installed_layer();
776        std::fs::remove_file(ctx.layer.root.join(ENVELOPE_FILE)).unwrap();
777        let err =
778            verify_installed(&ctx.store, &ctx.layer, &ctx.verifier, "test-platform").unwrap_err();
779        assert!(
780            matches!(err, ReverifyError::NoEnvelope { .. }),
781            "got: {err}"
782        );
783    }
784}