Skip to main content

varve_core/
verify.rs

1//! Manifest signature verification against the PulseEngine trust root
2//! (REQ-VERIFY-001, DD-003).
3//!
4//! Layer manifests travel as DSSE envelopes (payload = the OCI image index
5//! JSON), signed with the PulseEngine root ed25519 key via sigil's `wsc`
6//! library. The envelope authenticates both the payload bytes and the
7//! payload *type* (DSSE PAE), so a signed something-else cannot be replayed
8//! as a layer manifest.
9//!
10//! The verifier holds the trust root; sources cannot see it, supply it, or
11//! relax it. Keyless/Fulcio verification via sigil's airgapped module is the
12//! intended future — blocked on sigil#219 — and slots in behind the same
13//! [`crate::install::ManifestVerifier`] trait when it lands.
14
15use wsc::dsse::{DsseEnvelope, DsseError, DsseSigner, Ed25519DsseSigner, Ed25519DsseVerifier};
16
17use crate::install::{ManifestVerifier, VerifyError};
18use crate::keyroles::RealmTrust;
19
20/// The authenticated payload type for a layer manifest envelope.
21pub const LAYER_PAYLOAD_TYPE: &str = "application/vnd.pulseengine.varve.layer.v1+json";
22
23/// Verifies layer-manifest envelopes against a realm's pinned trust.
24///
25/// Built from a bare root key it is the flat verifier that predates roles;
26/// built from a [`RealmTrust`] (`from_trust`) a layer manifest is judged under
27/// the realm's LAYER keys when the realm declares roles (REQ-KEYROLES-001).
28pub struct PinnedKeyVerifier {
29    trust: RealmTrust,
30}
31
32impl PinnedKeyVerifier {
33    pub fn from_public_key_bytes(public_key: &[u8]) -> Result<Self, VerifyError> {
34        Ok(PinnedKeyVerifier {
35            trust: RealmTrust::root_only(public_key)?,
36        })
37    }
38
39    /// A verifier for a realm's trust: a roles realm accepts a layer manifest
40    /// only from its LAYER keys, a realm declaring no roles only from its root.
41    pub fn from_trust(trust: RealmTrust) -> Self {
42        PinnedKeyVerifier { trust }
43    }
44
45    /// The realm ROOT — what a document that must name the signer (the SBOM's
46    /// author) names it by, and what the store partitions on. In a roles realm
47    /// this is NOT the key that signs layer manifests.
48    pub fn public_key(&self) -> &[u8] {
49        self.trust.root()
50    }
51}
52
53impl ManifestVerifier for PinnedKeyVerifier {
54    fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
55        self.trust.verify_bytes(fetched, LAYER_PAYLOAD_TYPE)
56    }
57
58    fn trust(&self) -> Option<&RealmTrust> {
59        Some(&self.trust)
60    }
61}
62
63/// Verify a DSSE envelope of a specific payload type against a pinned root
64/// public key, returning the authenticated payload. The one verification
65/// path shared by layer manifests, line-status documents (DD-008) and
66/// release sums (DD-009) — different payload types, one trust root, so the
67/// type check is what keeps signed documents from posing as each other.
68pub fn dsse_verify_typed(
69    envelope: &[u8],
70    expected_payload_type: &str,
71    root_public_key: &[u8],
72) -> Result<Vec<u8>, VerifyError> {
73    crate::keyroles::RealmTrust::root_only(root_public_key)?
74        .verify_bytes(envelope, expected_payload_type)
75}
76
77pub(crate) fn verify_with(
78    verifier: &Ed25519DsseVerifier,
79    envelope: &[u8],
80    expected_payload_type: &str,
81) -> Result<Vec<u8>, VerifyError> {
82    let text = std::str::from_utf8(envelope)
83        .map_err(|_| VerifyError("fetched bytes are not UTF-8 DSSE JSON".into()))?;
84    let envelope = DsseEnvelope::from_json(text)
85        .map_err(|e| VerifyError(format!("not a DSSE envelope: {e}")))?;
86    if envelope.payload_type != expected_payload_type {
87        return Err(VerifyError(format!(
88            "envelope payload type is '{}', expected '{expected_payload_type}' — refusing to \
89             accept a signed document as something it is not",
90            envelope.payload_type
91        )));
92    }
93    envelope.verify_all(verifier).map_err(|e| {
94        VerifyError(format!(
95            "signature does not verify against the trust root: {e}"
96        ))
97    })
98}
99
100/// A key that signs for a realm, wherever it lives (REQ-SIGNERSEAM-001).
101///
102/// It IS a [`DsseSigner`] (so it feeds `DsseEnvelope::sign` directly) plus the
103/// public half, which a producer needs to read its own work back before
104/// publishing it. The id is `realm_key_id` rather than `key_id`: the supertrait
105/// already has a `key_id() -> Option<String>`, and two methods of one name on
106/// one object make every call ambiguous.
107pub trait RealmSigner: DsseSigner {
108    /// The 32 raw bytes of the ed25519 public key this signer signs as.
109    fn public_key(&self) -> Vec<u8>;
110    /// The key id written into every envelope this signer produces.
111    fn realm_key_id(&self) -> String;
112}
113
114/// A [`RealmSigner`] backed by raw key bytes — today's `--key <FILE>` path,
115/// kept exactly, as one implementation of the seam.
116pub struct FileSigner {
117    inner: Ed25519DsseSigner,
118    public: Vec<u8>,
119    key_id: String,
120}
121
122impl FileSigner {
123    /// A signer whose 64-byte secret is checked to carry its own public half
124    /// (`keys::check_keypair`'s probe), so a mismatched pair is refused here
125    /// and not after a signature nobody can verify exists.
126    pub fn new(secret_key: &[u8], key_id: &str) -> Result<Self, VerifyError> {
127        crate::keys::check_keypair_bytes(secret_key, "signing key")
128            .map_err(|e| VerifyError(format!("invalid signing key: {e}")))?;
129        Self::new_unchecked(secret_key, key_id)
130    }
131
132    /// As [`FileSigner::new`], without the consistency probe: the behaviour of
133    /// the pre-seam entry points, which signed with whatever bytes they were
134    /// handed. The wrappers keep that so the refactor changes nothing; new
135    /// code should use [`FileSigner::new`].
136    pub fn new_unchecked(secret_key: &[u8], key_id: &str) -> Result<Self, VerifyError> {
137        let inner = Ed25519DsseSigner::from_bytes(secret_key, Some(key_id.to_string()))
138            .map_err(|e| VerifyError(format!("invalid signing key: {e}")))?;
139        Ok(Self {
140            inner,
141            public: secret_key[32..].to_vec(),
142            key_id: key_id.to_string(),
143        })
144    }
145}
146
147impl DsseSigner for FileSigner {
148    fn sign(&self, pae: &[u8]) -> Result<Vec<u8>, DsseError> {
149        self.inner.sign(pae)
150    }
151    fn key_id(&self) -> Option<String> {
152        Some(self.key_id.clone())
153    }
154}
155
156impl RealmSigner for FileSigner {
157    fn public_key(&self) -> Vec<u8> {
158        self.public.clone()
159    }
160    fn realm_key_id(&self) -> String {
161        self.key_id.clone()
162    }
163}
164
165/// Sign a payload of a given type into a DSSE envelope (JSON) with any
166/// [`RealmSigner`] — the one place an envelope is made.
167pub fn dsse_sign_with(
168    payload: &[u8],
169    payload_type: &str,
170    signer: &dyn RealmSigner,
171) -> Result<String, VerifyError> {
172    let envelope = DsseEnvelope::sign(payload, payload_type, signer)
173        .map_err(|e| VerifyError(format!("signing failed: {e}")))?;
174    envelope
175        .to_json_pretty()
176        .map_err(|e| VerifyError(format!("envelope serialization failed: {e}")))
177}
178
179/// Sign a payload of a given type into a DSSE envelope (JSON) — the
180/// producing half, shared by deposit, line-status and release-sums signing
181/// so the two sides can never drift apart. A thin wrapper over
182/// [`dsse_sign_with`] with a file-backed key.
183pub fn dsse_sign_typed(
184    payload: &[u8],
185    payload_type: &str,
186    secret_key: &[u8],
187    key_id: &str,
188) -> Result<String, VerifyError> {
189    let signer = FileSigner::new_unchecked(secret_key, key_id)?;
190    dsse_sign_with(payload, payload_type, &signer)
191}
192
193/// Sign layer-manifest payload bytes into a DSSE envelope (JSON).
194pub fn sign_layer_manifest(
195    payload: &[u8],
196    secret_key: &[u8],
197    key_id: &str,
198) -> Result<String, VerifyError> {
199    dsse_sign_typed(payload, LAYER_PAYLOAD_TYPE, secret_key, key_id)
200}
201
202/// [`sign_layer_manifest`] with any [`RealmSigner`].
203pub fn sign_layer_manifest_with(
204    payload: &[u8],
205    signer: &dyn RealmSigner,
206) -> Result<String, VerifyError> {
207    dsse_sign_with(payload, LAYER_PAYLOAD_TYPE, signer)
208}
209
210/// Generate an ed25519 root keypair: (secret 64 bytes, public 32 bytes).
211/// Test and provisioning helper — real roots are generated in a key
212/// ceremony, not on a build machine.
213pub fn generate_root_keypair() -> (Vec<u8>, Vec<u8>) {
214    let kp = wsc::KeyPair::generate();
215    (kp.sk.sk.to_vec(), kp.pk.pk.to_vec())
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use crate::install::{InstallError, InstallPolicy, install};
222    use crate::manifest::fixtures::manifest_with_tools;
223    use crate::pin::Pin;
224    use crate::rollback::HighWaterMarks;
225    use crate::source::MemorySource;
226    use crate::store::{Store, manifest_digest};
227
228    fn keys() -> (Vec<u8>, Vec<u8>) {
229        generate_root_keypair()
230    }
231
232    /// The SBOM names its author by this key (REQ-SBOMFIELDS-001 clause 2), so
233    /// it must be the key the verifier accepts, not any stand-in bytes.
234    // rivet: verifies REQ-SBOMFIELDS-001
235    #[test]
236    fn the_verifier_reports_exactly_the_root_it_was_pinned_to() {
237        let (_, pk) = keys();
238        let (_, other) = keys();
239        let a = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
240        let b = PinnedKeyVerifier::from_public_key_bytes(&other).unwrap();
241        assert_eq!(a.public_key(), pk.as_slice());
242        assert_eq!(b.public_key(), other.as_slice());
243        assert_ne!(a.public_key(), b.public_key());
244    }
245
246    // rivet: verifies REQ-ROLLBACK-002
247    #[test]
248    fn the_verifier_names_its_root_through_the_trait_so_a_status_is_checked_against_it() {
249        use crate::install::ManifestVerifier as _;
250        let (sk, pk) = keys();
251        let (_, other) = keys();
252        let v = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
253        assert_eq!(v.trust().map(|t| t.root()), Some(pk.as_slice()));
254        // The document digest consent rests on verifies under that root and
255        // only that root.
256        let status = crate::linestatus::LineStatus {
257            line: "2026.07".into(),
258            counter: 1,
259            issued_at: "2026-08-01T00:00:00Z".into(),
260            support_until: None,
261            min_counter: None,
262            yanked: Default::default(),
263            known_problems: Vec::new(),
264        }
265        .sign(&sk, "root-1")
266        .unwrap();
267        assert!(
268            crate::linestatus::LineStatus::verify_and_parse(status.as_bytes(), v.trust().unwrap())
269                .is_ok()
270        );
271        assert!(
272            crate::linestatus::LineStatus::verify_and_parse(
273                status.as_bytes(),
274                &crate::keyroles::test_support::rt(&other)
275            )
276            .is_err()
277        );
278    }
279
280    // rivet: verifies REQ-VERIFY-001
281    #[test]
282    fn a_signed_manifest_verifies_and_yields_its_payload() {
283        let (sk, pk) = keys();
284        let payload = manifest_with_tools("2026.07.0", "qualified", 1, "2026-07-31T09:14:00Z", &[]);
285        let envelope = sign_layer_manifest(&payload, &sk, "varve-root-1").unwrap();
286        let verifier = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
287        use crate::install::ManifestVerifier as _;
288        assert_eq!(verifier.verify(envelope.as_bytes()).unwrap(), payload);
289    }
290
291    // rivet: verifies REQ-VERIFY-001
292    #[test]
293    fn a_signature_from_an_untrusted_key_is_rejected() {
294        let (sk, _) = keys();
295        let (_, other_pk) = keys();
296        let payload = manifest_with_tools("2026.07.0", "qualified", 1, "2026-07-31T09:14:00Z", &[]);
297        let envelope = sign_layer_manifest(&payload, &sk, "varve-root-1").unwrap();
298        let verifier = PinnedKeyVerifier::from_public_key_bytes(&other_pk).unwrap();
299        use crate::install::ManifestVerifier as _;
300        assert!(verifier.verify(envelope.as_bytes()).is_err());
301    }
302
303    // rivet: verifies REQ-VERIFY-001
304    #[test]
305    fn a_tampered_payload_is_rejected() {
306        let (sk, pk) = keys();
307        let payload = manifest_with_tools("2026.07.0", "qualified", 1, "2026-07-31T09:14:00Z", &[]);
308        let envelope = sign_layer_manifest(&payload, &sk, "varve-root-1").unwrap();
309        // Flip the counter inside the base64 payload by re-signing... no —
310        // tamper the envelope JSON's payload field directly.
311        let mut parsed: serde_json::Value = serde_json::from_str(&envelope).unwrap();
312        let b64 = parsed["payload"].as_str().unwrap().to_string();
313        let mut chars: Vec<char> = b64.chars().collect();
314        chars[0] = if chars[0] == 'A' { 'B' } else { 'A' };
315        parsed["payload"] = serde_json::Value::String(chars.into_iter().collect());
316        let tampered = serde_json::to_string(&parsed).unwrap();
317        let verifier = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
318        use crate::install::ManifestVerifier as _;
319        assert!(verifier.verify(tampered.as_bytes()).is_err());
320    }
321
322    // rivet: verifies REQ-VERIFY-001
323    #[test]
324    fn a_signed_envelope_of_the_wrong_payload_type_is_rejected() {
325        let (sk, pk) = keys();
326        let payload = b"some signed but non-manifest content";
327        let signer = wsc::dsse::Ed25519DsseSigner::from_bytes(&sk, None).unwrap();
328        let envelope = wsc::dsse::DsseEnvelope::sign(payload, "application/other", &signer)
329            .unwrap()
330            .to_json()
331            .unwrap();
332        let verifier = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
333        use crate::install::ManifestVerifier as _;
334        let err = verifier.verify(envelope.as_bytes()).unwrap_err();
335        assert!(err.to_string().contains("payload type"), "got: {err}");
336    }
337
338    // rivet: verifies REQ-VERIFY-001
339    #[test]
340    fn install_accepts_a_properly_signed_layer_and_rejects_the_same_bytes_resigned_by_an_impostor()
341    {
342        let (sk, pk) = keys();
343        let (impostor_sk, _) = keys();
344        let synth = b"tool-bytes".to_vec();
345        let blob_digest = manifest_digest(&synth);
346        let payload = manifest_with_tools(
347            "2026.07.0",
348            "qualified",
349            1,
350            "2026-07-31T09:14:00Z",
351            &[("synth", &blob_digest)],
352        );
353        let pin = Pin::parse(
354            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\n",
355            "varve.toml",
356        )
357        .unwrap();
358        let policy = InstallPolicy {
359            index: None,
360            now: "2026-08-07T00:00:00Z",
361            staleness_threshold_days: 90,
362            platform: "test-platform",
363        };
364        let verifier = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
365
366        // Properly signed: accepted, and the *payload* is what lands.
367        let good = sign_layer_manifest(&payload, &sk, "varve-root-1").unwrap();
368        let source = MemorySource::new()
369            .with_manifest(good.as_bytes())
370            .with_blob(&blob_digest, &synth);
371        let tmp = tempfile::tempdir().unwrap();
372        let store = Store::at(tmp.path().join("root"));
373        let mut marks = HighWaterMarks::load(&tmp.path().join("root")).unwrap();
374        let outcome = install(&pin, &source, &verifier, &store, &mut marks, &policy).unwrap();
375        assert_eq!(outcome.digest, manifest_digest(&payload));
376        let entry = store.get(&outcome.digest).unwrap().unwrap();
377        assert_eq!(
378            std::fs::read(entry.root.join("layer.json")).unwrap(),
379            payload,
380            "the core stores the verified payload, not the envelope"
381        );
382
383        // Same payload, impostor signature: rejected before anything lands.
384        let evil = sign_layer_manifest(&payload, &impostor_sk, "varve-root-1").unwrap();
385        let evil_source = MemorySource::new()
386            .with_manifest(evil.as_bytes())
387            .with_blob(&blob_digest, &synth);
388        let tmp2 = tempfile::tempdir().unwrap();
389        let store2 = Store::at(tmp2.path().join("root"));
390        let mut marks2 = HighWaterMarks::load(&tmp2.path().join("root")).unwrap();
391        let err =
392            install(&pin, &evil_source, &verifier, &store2, &mut marks2, &policy).unwrap_err();
393        assert!(matches!(err, InstallError::Verify(_)), "got: {err}");
394        assert!(store2.list().unwrap().is_empty());
395    }
396}
397
398/// A signer that is not a file: it keeps a key in memory and counts how often
399/// it is asked to sign. Stands in for a hardware or KMS-backed implementation
400/// (REQ-SIGNERSEAM-001 clause 3).
401#[cfg(test)]
402pub(crate) mod testsigner {
403    use std::sync::atomic::{AtomicUsize, Ordering};
404    use wsc::dsse::{DsseError, DsseSigner, Ed25519DsseSigner};
405
406    pub(crate) struct CountingSigner {
407        inner: Ed25519DsseSigner,
408        public: Vec<u8>,
409        pub(crate) calls: AtomicUsize,
410    }
411
412    impl CountingSigner {
413        pub(crate) fn new(secret: &[u8]) -> Self {
414            Self {
415                inner: Ed25519DsseSigner::from_bytes(secret, None).unwrap(),
416                public: secret[32..].to_vec(),
417                calls: AtomicUsize::new(0),
418            }
419        }
420        pub(crate) fn calls(&self) -> usize {
421            self.calls.load(Ordering::SeqCst)
422        }
423    }
424
425    impl DsseSigner for CountingSigner {
426        fn sign(&self, pae: &[u8]) -> Result<Vec<u8>, DsseError> {
427            self.calls.fetch_add(1, Ordering::SeqCst);
428            self.inner.sign(pae)
429        }
430        fn key_id(&self) -> Option<String> {
431            Some("mock-1".into())
432        }
433    }
434
435    impl super::RealmSigner for CountingSigner {
436        fn public_key(&self) -> Vec<u8> {
437            self.public.clone()
438        }
439        fn realm_key_id(&self) -> String {
440            "mock-1".into()
441        }
442    }
443}
444
445#[cfg(test)]
446mod seam_tests {
447    use super::testsigner::CountingSigner;
448    use super::*;
449
450    // GOLDEN VALUES. Captured by running the PRE-REFACTOR code (main at
451    // 709056b: `dsse_sign_typed` building `Ed25519DsseSigner::from_bytes`
452    // inline) on this fixed key and these payloads. Ed25519 is deterministic,
453    // so any change to the envelope bytes the seam produces is a regression.
454    const SK: &str = "0d9437caa6c957a81613b1ba3c9dccceadfceed45a2c1a33a1e8018faa3dc5f369fdee54295697e20ae454e441ca9df08ded1856047024c05b54696bbeff2f69";
455    const LAYER_SIG: &str =
456        "nWOkRNIIjavcK4TeRGv/anydt/nVbsuQqdYuPTIfcMdPkpePMwNEE70qmKQHEJbt0+RBgNwtalea33gr0FUQAg==";
457    const SUMS_SIG: &str =
458        "gGBevxrM3BJSOC7z/R3TNOOz+vjmRlCA8X7FWk8y2aWbtVs6i0R1B4/ar6hvqrDK7QJDZBfxV99LybulMRioAg==";
459    const STATUS_SIG: &str =
460        "jJGBhhz1hL7DkUBKfb0LOFHnPbMEhWummWVXyskmJOMPN3ZtS5NYxRKUTpTsruDhwYEd4k7EJxmwoSzNDIMkAA==";
461    const INDEX_SIG: &str =
462        "zsQzudE5hon3HEHJsKmcLtCQ+8UMeaG63Niedgzk3I7U5wlSFqGPcIwgawmcgQB97D8N70+7K4kdMicErSkEDQ==";
463    const ATTEST_PAYLOAD: &str = "eyJsYXllciI6IjIwMjYuMDguMCIsImxheWVyX21hbmlmZXN0X2RpZ2VzdCI6InNoYTI1NjphYSIsImtpbmQiOiJzYm9tIiwiZGlnZXN0Ijoic2hhMjU2OmJiIiwicHJvZHVjZXIiOiJ2YXJ2ZSJ9";
464    const ATTEST_SIG: &str =
465        "azGa/8Hxb0GE8hOd+8AGdUWNNb6JuXZMy8X++/wGtfwEQwW+Y+uxcvCQAUgeX2y2+QJZyynF9I1IzhxyNGWUDg==";
466
467    fn sk() -> Vec<u8> {
468        (0..SK.len() / 2)
469            .map(|i| u8::from_str_radix(&SK[2 * i..2 * i + 2], 16).unwrap())
470            .collect()
471    }
472
473    /// The exact pretty-JSON shape the pre-refactor code emitted.
474    fn golden(payload_b64: &str, ty: &str, sig: &str) -> String {
475        format!(
476            "{{\n  \"payload\": \"{payload_b64}\",\n  \"payloadType\": \"{ty}\",\n  \"signatures\": [\n    {{\n      \"keyid\": \"k1\",\n      \"sig\": \"{sig}\"\n    }}\n  ]\n}}"
477        )
478    }
479
480    fn statement() -> crate::attest::AttestationStatement {
481        crate::attest::AttestationStatement {
482            layer: "2026.08.0".into(),
483            layer_manifest_digest: "sha256:aa".into(),
484            kind: crate::attest::AttestationKind::Sbom,
485            digest: "sha256:bb".into(),
486            producer: "varve".into(),
487            ambient_tools: Vec::new(),
488        }
489    }
490
491    // rivet: verifies REQ-SIGNERSEAM-001
492    #[test]
493    fn every_signing_entry_point_still_emits_the_pre_seam_bytes() {
494        let sk = sk();
495        let want = [
496            golden("eyJsYXllciI6MX0=", LAYER_PAYLOAD_TYPE, LAYER_SIG),
497            golden(
498                "YWJjICBmaWxlCg==",
499                crate::selfverify::RELEASE_SUMS_PAYLOAD_TYPE,
500                SUMS_SIG,
501            ),
502            golden(
503                "eyJzIjoxfQ==",
504                crate::linestatus::LINE_STATUS_PAYLOAD_TYPE,
505                STATUS_SIG,
506            ),
507            golden(
508                "eyJpIjoxfQ==",
509                crate::lineindex::LINE_INDEX_PAYLOAD_TYPE,
510                INDEX_SIG,
511            ),
512            golden(ATTEST_PAYLOAD, crate::attest::PAYLOAD_TYPE, ATTEST_SIG),
513        ];
514        let signer = FileSigner::new(&sk, "k1").unwrap();
515        // The wrappers (the old call shape) and the `_with` variants must both
516        // equal the golden — which also makes them equal each other.
517        let old = [
518            sign_layer_manifest(b"{\"layer\":1}", &sk, "k1").unwrap(),
519            crate::selfverify::sign_release_sums(b"abc  file\n", &sk, "k1").unwrap(),
520            dsse_sign_typed(
521                b"{\"s\":1}",
522                crate::linestatus::LINE_STATUS_PAYLOAD_TYPE,
523                &sk,
524                "k1",
525            )
526            .unwrap(),
527            dsse_sign_typed(
528                b"{\"i\":1}",
529                crate::lineindex::LINE_INDEX_PAYLOAD_TYPE,
530                &sk,
531                "k1",
532            )
533            .unwrap(),
534            crate::attest::sign(&statement(), &sk, "k1").unwrap(),
535        ];
536        let new = [
537            sign_layer_manifest_with(b"{\"layer\":1}", &signer).unwrap(),
538            crate::selfverify::sign_release_sums_with(b"abc  file\n", &signer).unwrap(),
539            dsse_sign_with(
540                b"{\"s\":1}",
541                crate::linestatus::LINE_STATUS_PAYLOAD_TYPE,
542                &signer,
543            )
544            .unwrap(),
545            dsse_sign_with(
546                b"{\"i\":1}",
547                crate::lineindex::LINE_INDEX_PAYLOAD_TYPE,
548                &signer,
549            )
550            .unwrap(),
551            crate::attest::sign_with(&statement(), &signer).unwrap(),
552        ];
553        for i in 0..want.len() {
554            assert_eq!(old[i], want[i], "wrapper {i} drifted from the golden");
555            assert_eq!(new[i], want[i], "_with variant {i} drifted from the golden");
556        }
557    }
558
559    // rivet: verifies REQ-SIGNERSEAM-001
560    #[test]
561    fn a_non_file_signer_is_accepted_by_every_with_call_site_and_its_envelopes_verify() {
562        let (secret, public) = generate_root_keypair();
563        let mock = CountingSigner::new(&secret);
564
565        let layer = sign_layer_manifest_with(b"{}", &mock).unwrap();
566        assert_eq!(mock.calls(), 1);
567        assert_eq!(
568            dsse_verify_typed(layer.as_bytes(), LAYER_PAYLOAD_TYPE, &public).unwrap(),
569            b"{}"
570        );
571
572        let att = crate::attest::sign_with(&statement(), &mock).unwrap();
573        assert_eq!(mock.calls(), 2);
574        assert_eq!(
575            crate::attest::verify_statement(
576                att.as_bytes(),
577                &crate::keyroles::test_support::rt(&public)
578            )
579            .unwrap(),
580            statement()
581        );
582
583        let sums = crate::selfverify::sign_release_sums_with(b"x  y\n", &mock).unwrap();
584        assert_eq!(mock.calls(), 3);
585        assert_eq!(
586            dsse_verify_typed(
587                sums.as_bytes(),
588                crate::selfverify::RELEASE_SUMS_PAYLOAD_TYPE,
589                &public
590            )
591            .unwrap(),
592            b"x  y\n"
593        );
594
595        let any = dsse_sign_with(b"{}", "application/x.test", &mock).unwrap();
596        assert_eq!(mock.calls(), 4);
597        dsse_verify_typed(any.as_bytes(), "application/x.test", &public).unwrap();
598    }
599
600    // rivet: verifies REQ-SIGNERSEAM-001
601    #[test]
602    fn a_file_signer_refuses_a_mismatched_keypair() {
603        let (mut secret, _) = generate_root_keypair();
604        let (_, other_public) = generate_root_keypair();
605        secret[32..].copy_from_slice(&other_public);
606        let err = FileSigner::new(&secret, "k").err().expect("must refuse");
607        assert!(err.to_string().contains("invalid signing key"), "{err}");
608        // and a consistent pair is accepted, reporting its own public half
609        let (ok_secret, ok_public) = generate_root_keypair();
610        let s = FileSigner::new(&ok_secret, "k").unwrap();
611        assert_eq!(s.public_key(), ok_public);
612        assert_eq!(s.realm_key_id(), "k");
613        assert_eq!(DsseSigner::key_id(&s), Some("k".to_string()));
614    }
615}