Skip to main content

varve_core/
selfverify.rs

1//! Self-verification (REQ-SELF-001, DD-009) — the tool that gates the
2//! toolchain clears its own gate.
3//!
4//! varve releases carry a varve-native signature: a DSSE envelope over the
5//! release's SHA256SUMS.txt, signed with the same root key deposits use.
6//! `varve self-verify` checks a candidate archive against that envelope with
7//! the pinned trust root, fully offline, failing closed — including when the
8//! envelope is absent, because "unsigned" is a verdict, not a shrug.
9
10use crate::install::VerifyError;
11use crate::store::manifest_digest;
12use crate::verify::dsse_sign_typed;
13
14/// The authenticated payload type for release checksum envelopes.
15pub const RELEASE_SUMS_PAYLOAD_TYPE: &str =
16    "application/vnd.pulseengine.varve.release-sums.v1+json";
17
18#[derive(Debug, thiserror::Error)]
19pub enum SelfVerifyError {
20    #[error(transparent)]
21    Verify(#[from] VerifyError),
22    #[error("SHA256SUMS payload is not UTF-8 text")]
23    NotText,
24    #[error("'{name}' has no entry in the signed SHA256SUMS — refusing to trust it")]
25    NoEntry { name: String },
26    #[error(
27        "'{name}' does not match its signed digest — expected {expected}, the file hashes to {actual}"
28    )]
29    DigestMismatch {
30        name: String,
31        expected: String,
32        actual: String,
33    },
34}
35
36/// Verify one release file against the signed sums envelope. Returns the
37/// verified digest on success.
38pub fn verify_release_file(
39    file_name: &str,
40    file_bytes: &[u8],
41    sums_envelope: &[u8],
42    trust: &crate::keyroles::RealmTrust,
43) -> Result<String, SelfVerifyError> {
44    let payload = trust.verify_bytes(sums_envelope, RELEASE_SUMS_PAYLOAD_TYPE)?;
45    let text = std::str::from_utf8(&payload).map_err(|_| SelfVerifyError::NotText)?;
46    // sha256sum format: "<hex>  <name>" (name possibly ./-prefixed).
47    let expected = text
48        .lines()
49        .filter_map(|line| {
50            let (hex, name) = line.split_once("  ")?;
51            let name = name.trim().trim_start_matches("./");
52            (name == file_name).then(|| hex.trim().to_string())
53        })
54        .next()
55        .ok_or_else(|| SelfVerifyError::NoEntry {
56            name: file_name.to_string(),
57        })?;
58    let actual = manifest_digest(file_bytes);
59    let actual_hex = actual
60        .strip_prefix("sha256:")
61        .expect("digest shape")
62        .to_string();
63    if actual_hex != expected {
64        return Err(SelfVerifyError::DigestMismatch {
65            name: file_name.to_string(),
66            expected,
67            actual: actual_hex,
68        });
69    }
70    Ok(actual)
71}
72
73/// Sign a SHA256SUMS.txt into the release envelope (the CI side).
74pub fn sign_release_sums(
75    sums: &[u8],
76    secret_key: &[u8],
77    key_id: &str,
78) -> Result<String, VerifyError> {
79    dsse_sign_typed(sums, RELEASE_SUMS_PAYLOAD_TYPE, secret_key, key_id)
80}
81
82/// [`sign_release_sums`] with any [`crate::verify::RealmSigner`].
83pub fn sign_release_sums_with(
84    sums: &[u8],
85    signer: &dyn crate::verify::RealmSigner,
86) -> Result<String, VerifyError> {
87    crate::verify::dsse_sign_with(sums, RELEASE_SUMS_PAYLOAD_TYPE, signer)
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93    use crate::verify::generate_root_keypair;
94
95    fn fixture() -> (Vec<u8>, String, Vec<u8>, Vec<u8>) {
96        let (sk, pk) = generate_root_keypair();
97        let archive = b"pretend-tarball-bytes".to_vec();
98        let digest = manifest_digest(&archive);
99        let hex = digest.strip_prefix("sha256:").unwrap();
100        let sums = format!(
101            "{hex}  ./varve-v9.9.9-aarch64-apple-darwin.tar.gz\n\
102             0000000000000000000000000000000000000000000000000000000000000000  ./other.txt\n"
103        );
104        let envelope = sign_release_sums(sums.as_bytes(), &sk, "varve-root-1").unwrap();
105        (archive, envelope, pk, sk)
106    }
107
108    // rivet: verifies REQ-SELF-001
109    #[test]
110    fn a_release_archive_verifies_against_the_signed_sums() {
111        let (archive, envelope, pk, _) = fixture();
112        let digest = verify_release_file(
113            "varve-v9.9.9-aarch64-apple-darwin.tar.gz",
114            &archive,
115            envelope.as_bytes(),
116            &crate::keyroles::test_support::rt(&pk),
117        )
118        .unwrap();
119        assert!(digest.starts_with("sha256:"));
120    }
121
122    // rivet: verifies REQ-SELF-001
123    #[test]
124    fn a_tampered_archive_is_refused() {
125        let (mut archive, envelope, pk, _) = fixture();
126        archive.push(b'!');
127        let err = verify_release_file(
128            "varve-v9.9.9-aarch64-apple-darwin.tar.gz",
129            &archive,
130            envelope.as_bytes(),
131            &crate::keyroles::test_support::rt(&pk),
132        )
133        .unwrap_err();
134        assert!(
135            matches!(err, SelfVerifyError::DigestMismatch { .. }),
136            "got: {err}"
137        );
138    }
139
140    // rivet: verifies REQ-SELF-001
141    #[test]
142    fn a_file_outside_the_signed_sums_is_refused() {
143        let (archive, envelope, pk, _) = fixture();
144        let err = verify_release_file(
145            "sneaky.tar.gz",
146            &archive,
147            envelope.as_bytes(),
148            &crate::keyroles::test_support::rt(&pk),
149        )
150        .unwrap_err();
151        assert!(matches!(err, SelfVerifyError::NoEntry { .. }), "got: {err}");
152    }
153
154    // rivet: verifies REQ-SELF-001
155    #[test]
156    fn sums_signed_by_an_untrusted_key_are_refused() {
157        let (archive, _, _, _) = fixture();
158        let (other_sk, other_pk) = generate_root_keypair();
159        let _ = other_pk;
160        let digest = manifest_digest(&archive);
161        let hex = digest.strip_prefix("sha256:").unwrap();
162        let sums = format!("{hex}  ./x.tar.gz\n");
163        let impostor = sign_release_sums(sums.as_bytes(), &other_sk, "evil").unwrap();
164        let (_, _, pk, _) = fixture();
165        assert!(
166            verify_release_file(
167                "x.tar.gz",
168                &archive,
169                impostor.as_bytes(),
170                &crate::keyroles::test_support::rt(&pk)
171            )
172            .is_err(),
173            "impostor sums must not verify"
174        );
175    }
176
177    // rivet: verifies REQ-SELF-001
178    #[test]
179    fn a_layer_manifest_envelope_cannot_pose_as_release_sums() {
180        let (archive, _, pk, sk) = fixture();
181        let not_sums = crate::verify::sign_layer_manifest(b"{}", &sk, "k");
182        // sign_layer_manifest refuses nothing here — it signs any payload —
183        // but its payload TYPE differs, so verification must refuse it.
184        let envelope = not_sums.unwrap();
185        let err = verify_release_file(
186            "x.tar.gz",
187            &archive,
188            envelope.as_bytes(),
189            &crate::keyroles::test_support::rt(&pk),
190        )
191        .unwrap_err();
192        assert!(err.to_string().contains("payload type"), "got: {err}");
193    }
194}