polyc-crypto 2026.9.0

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! Canonical signing for an approval's asserted responder (`#1553`).
//!
//! An [`AssertedApproval`] is the edge's signed statement of *which human*
//! resolved a pending approval. It rides inside the
//! [`ApprovalResponseRequest`] it describes, and it commits to that whole
//! request: this module's [`APPROVAL_ASSERTION_DOMAIN_PREFIX`] followed by
//! the buffa encoding of the request with the assertion's `signature_hex`
//! cleared. Both signer and verifier clear that one field before encoding, so
//! the signature covers every other field of the request — including the
//! `turn_id`, the `decision` oneof, an `Approve`'s `modified_args_json` and
//! `injected_context`, the `resolve_token`, and the asserted `responder` — but
//! not itself.
//!
//! Signing the whole request rather than just the identity is the point.
//! An assertion over `(turn_id, request_id, conversation_id, responder)` alone would
//! leave a validly-signed envelope replayable with approve swapped for deny,
//! or with the arguments that actually execute rewritten
//! (`docs/reference/verified-approver.md`, decision 3). [`canonical_bytes`]
//! clones the whole request and clears only that one field, so any field
//! later added to either message is covered without further change here.
//!
//! The domain prefix is a sibling of
//! [`crate::edge_identity`]'s `EDGE_IDENTITY_DOMAIN_PREFIX`: a signature
//! minted as an edge-identity envelope never verifies as an approval
//! assertion, and the reverse (INV-A4, proven by
//! `edge_identity_signature_never_verifies_as_an_approval_assertion` and its
//! mirror rather than assumed from the two constants differing).
//!
//! Use [`attach_approval_assertion`] to put a signed assertion on a request,
//! or [`sign_approval_assertion`] for the signature alone;
//! [`verify_approval_assertion`] checks it against the candidate signing keys
//! the caller resolved for the asserting edge. The verifier never panics — a
//! malformed `signature_hex` surfaces as `false`.

use buffa::Message as _;
use polyc_proto::proto::polychrome::approval::v1::{ApprovalResponseRequest, AssertedApproval};

use crate::{Signer, verify};

/// Domain-separation prefix prepended to an approval assertion's signed bytes
/// (trailing NUL, exactly like `edge_identity`'s own prefix, so no legal
/// buffa encoding can extend it into a prefix collision).
///
/// The exact bytes are load-bearing: changing them invalidates every
/// currently-live approval assertion. Pinned in
/// `polyc-conformance-vectors::APPROVAL_ASSERTION` (`crates/conformance-vectors/vectors/approval-assertion.json`).
pub const APPROVAL_ASSERTION_DOMAIN_PREFIX: &[u8] = b"polychrome.approval-assertion.v1\0";

/// Canonical bytes for the assertion carried on `request`.
///
/// [`APPROVAL_ASSERTION_DOMAIN_PREFIX`] followed by the encoding of the whole
/// request with the assertion's `signature_hex` cleared, so the signature
/// commits to everything *except* itself.
///
/// A request carrying no assertion still has canonical bytes — they simply
/// describe a request with an absent assertion. That case is never signed in
/// practice; [`verify_approval_assertion`] refuses it before reaching here.
#[must_use]
pub fn canonical_bytes(request: &ApprovalResponseRequest) -> Vec<u8> {
    let mut canonical = request.clone();
    if let Some(assertion) = canonical.asserted_approval.as_option_mut() {
        assertion.signature_hex.clear();
    }
    let encoded = canonical.encode_to_vec();
    let mut bytes = Vec::with_capacity(APPROVAL_ASSERTION_DOMAIN_PREFIX.len() + encoded.len());
    bytes.extend_from_slice(APPROVAL_ASSERTION_DOMAIN_PREFIX);
    bytes.extend_from_slice(&encoded);
    bytes
}

/// Sign the canonical bytes of `request`; returns the lowercase-hex signature
/// suitable for [`AssertedApproval::signature_hex`].
///
/// The request must already carry the assertion being signed — the signature
/// covers the asserted `edge_id` and `responder` too. Prefer
/// [`attach_approval_assertion`], which makes that ordering impossible to get
/// wrong.
#[must_use]
pub fn sign_approval_assertion(signer: &Signer, request: &ApprovalResponseRequest) -> String {
    crate::hex::lower(&signer.sign(&canonical_bytes(request)))
}

/// Put `assertion` on `request` and sign it in place.
///
/// Whatever `signature_hex` `assertion` arrives with is irrelevant:
/// [`canonical_bytes`] clears the field before encoding, and the minted
/// signature then replaces it.
pub fn attach_approval_assertion(
    signer: &Signer,
    request: &mut ApprovalResponseRequest,
    assertion: AssertedApproval,
) {
    request.asserted_approval = buffa::MessageField::some(assertion);
    let signature = sign_approval_assertion(signer, request);
    if let Some(attached) = request.asserted_approval.as_option_mut() {
        attached.signature_hex = signature;
    }
}

/// Verify the assertion carried on `request`.
///
/// `candidate_public_keys` are the enrolled signing keys the caller resolved
/// for the asserting `AssertedApproval::edge_id`, encoded the way [`verify`]
/// expects.
///
/// Returns `false` when the request carries no assertion, when its
/// `signature_hex` is not valid hex, or when no candidate key verifies the
/// signature — never panics. Every candidate is checked with no early exit,
/// mirroring `ingest_gate`'s edge-envelope scan, so the number of candidates
/// examined does not become a signal for which key matched.
///
/// A caller that needs to know *which* key matched (to prefer an `Active` key
/// over a `Retiring` one, as edge-envelope verification does) calls this once
/// per candidate instead.
#[must_use]
pub fn verify_approval_assertion<'a, K>(
    candidate_public_keys: K,
    request: &ApprovalResponseRequest,
) -> bool
where
    K: IntoIterator<Item = &'a [u8]>,
{
    let Some(assertion) = request.asserted_approval.as_option() else {
        return false;
    };
    let Some(signature) = crate::hex::decode(&assertion.signature_hex) else {
        return false;
    };
    let bytes = canonical_bytes(request);
    let mut verified = false;
    for public_key in candidate_public_keys {
        if verify(public_key, &bytes, &signature) {
            verified = true;
        }
    }
    verified
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use polyc_proto::proto::polychrome::approval::v1::{
        Approve, Deny, approval_response_request::Decision,
    };
    use polyc_proto::proto::polychrome::persona::v1::ExternalIdentity;

    use super::*;

    fn sample_responder() -> ExternalIdentity {
        ExternalIdentity {
            provider: "chat".to_owned(),
            scope: "team-1".to_owned(),
            external_id: "U123".to_owned(),
            display_name: "Ada".to_owned(),
            ..Default::default()
        }
    }

    fn sample_assertion() -> AssertedApproval {
        AssertedApproval {
            edge_id: "chat".to_owned(),
            responder: buffa::MessageField::some(sample_responder()),
            ..Default::default()
        }
    }

    fn sample_request() -> ApprovalResponseRequest {
        ApprovalResponseRequest {
            turn_id: "018f47f0-5f70-7cc5-98df-123456789abc".to_owned(),
            request_id: "req-1".to_owned(),
            conversation_id: "chat:team-1:general".to_owned(),
            resolve_token: "token-1".to_owned(),
            decision: Some(Decision::Approve(Box::new(Approve {
                reason: "looks right".to_owned(),
                ..Default::default()
            }))),
            ..Default::default()
        }
    }

    fn signed_request(signer: &Signer) -> ApprovalResponseRequest {
        let mut request = sample_request();
        attach_approval_assertion(signer, &mut request, sample_assertion());
        request
    }

    /// Candidate-key list of one, the shape every test below verifies with.
    fn keys(public_key: &[u8]) -> [&[u8]; 1] {
        [public_key]
    }

    #[test]
    fn round_trips() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let request = signed_request(&signer);
        assert!(
            !request
                .asserted_approval
                .as_option()
                .unwrap()
                .signature_hex
                .is_empty()
        );
        assert!(verify_approval_assertion(keys(&pk), &request));
    }

    #[test]
    fn tampered_responder_fails() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = signed_request(&signer);
        request.asserted_approval.as_option_mut().unwrap().responder =
            buffa::MessageField::some(ExternalIdentity {
                external_id: "U999".to_owned(),
                ..sample_responder()
            });
        assert!(
            !verify_approval_assertion(keys(&pk), &request),
            "swapping the asserted responder must invalidate the signature (INV-A3)"
        );
    }

    #[test]
    fn tampered_decision_fails() {
        // Decision 3: an assertion that covered only the identity would stay
        // valid with approve swapped for deny. The canonical bytes are the
        // whole request, so it does not.
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = signed_request(&signer);
        request.decision = Some(Decision::Deny(Box::new(Deny {
            reason: "looks right".to_owned(),
            ..Default::default()
        })));
        assert!(
            !verify_approval_assertion(keys(&pk), &request),
            "swapping approve for deny must invalidate the signature (INV-A5)"
        );
    }

    #[test]
    fn tampered_modified_args_fails() {
        // The other half of decision 3: the decision variant is unchanged,
        // but what actually executes is not.
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = signed_request(&signer);
        request.decision = Some(Decision::Approve(Box::new(Approve {
            modified_args_json: r#"{"path":"/"}"#.to_owned(),
            reason: "looks right".to_owned(),
            ..Default::default()
        })));
        assert!(!verify_approval_assertion(keys(&pk), &request));
    }

    #[test]
    fn tampered_occurrence_identity_fails() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = signed_request(&signer);
        request.turn_id = "018f47f0-5f70-7cc5-98df-123456789abd".to_owned();
        assert!(
            !verify_approval_assertion(keys(&pk), &request),
            "an assertion is bound to one approval occurrence's turn (INV-A5)"
        );

        let mut request = signed_request(&signer);
        request.request_id = "req-2".to_owned();
        assert!(
            !verify_approval_assertion(keys(&pk), &request),
            "an assertion is bound to one request_id (INV-A5)"
        );
    }

    #[test]
    fn tampered_conversation_id_fails() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = signed_request(&signer);
        request.conversation_id = "chat:team-1:secrets".to_owned();
        assert!(
            !verify_approval_assertion(keys(&pk), &request),
            "an assertion is bound to one conversation_id (INV-A5)"
        );
    }

    #[test]
    fn tampered_resolve_token_fails() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = signed_request(&signer);
        request.resolve_token = "token-2".to_owned();
        assert!(!verify_approval_assertion(keys(&pk), &request));
    }

    #[test]
    fn tampered_edge_id_fails() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = signed_request(&signer);
        request.asserted_approval.as_option_mut().unwrap().edge_id = "messaging".to_owned();
        assert!(!verify_approval_assertion(keys(&pk), &request));
    }

    #[test]
    fn wrong_key_fails() {
        let signer = Signer::from_seed(41);
        let other = Signer::from_seed(42);
        let request = signed_request(&signer);
        assert!(!verify_approval_assertion(
            keys(&other.public_key_bytes()),
            &request
        ));
    }

    #[test]
    fn verifies_against_any_candidate_key() {
        // Rotation overlap: the caller hands over every candidate key and one
        // of them is the signer's.
        let signer = Signer::from_seed(41);
        let retiring = Signer::from_seed(42);
        let retiring_pk = retiring.public_key_bytes();
        let active_pk = signer.public_key_bytes();
        let request = signed_request(&signer);
        let candidates: [&[u8]; 2] = [&retiring_pk, &active_pk];
        assert!(verify_approval_assertion(candidates, &request));
    }

    #[test]
    fn no_candidate_keys_fails() {
        let signer = Signer::from_seed(41);
        let request = signed_request(&signer);
        let candidates: [&[u8]; 0] = [];
        assert!(!verify_approval_assertion(candidates, &request));
    }

    #[test]
    fn absent_assertion_fails() {
        // Decision 4: no assertion is not an error here, just "unverified".
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let request = sample_request();
        assert!(!verify_approval_assertion(keys(&pk), &request));
    }

    #[test]
    fn unsigned_assertion_fails() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = sample_request();
        request.asserted_approval = buffa::MessageField::some(sample_assertion());
        assert!(!verify_approval_assertion(keys(&pk), &request));
    }

    #[test]
    fn garbage_signature_hex_returns_false_not_panic() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = signed_request(&signer);
        for garbage in ["not-hex!", "abc", "", "zz", &"ab".repeat(4096)] {
            request
                .asserted_approval
                .as_option_mut()
                .unwrap()
                .signature_hex = garbage.to_owned();
            assert!(
                !verify_approval_assertion(keys(&pk), &request),
                "malformed signature_hex {garbage:?} must return false, not panic"
            );
        }
    }

    #[test]
    fn a_stale_signature_does_not_change_the_minted_one() {
        // `canonical_bytes` clears `signature_hex` before encoding, so an
        // assertion arriving with a leftover (or attacker-chosen) signature
        // mints the identical signature one arriving clean does. Without that
        // clear, the signature would depend on the value it replaces and no
        // two signers would agree on the same request.
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();

        let mut clean = sample_request();
        attach_approval_assertion(&signer, &mut clean, sample_assertion());

        let mut stale = sample_request();
        attach_approval_assertion(
            &signer,
            &mut stale,
            AssertedApproval {
                signature_hex: "deadbeef".to_owned(),
                ..sample_assertion()
            },
        );

        assert_eq!(
            clean.asserted_approval.as_option().unwrap().signature_hex,
            stale.asserted_approval.as_option().unwrap().signature_hex
        );
        assert!(verify_approval_assertion(keys(&pk), &stale));
    }

    #[test]
    fn undomained_signature_is_rejected() {
        // A signature the SAME signer minted over the RAW request encoding
        // (no domain prefix at all) must never verify.
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = sample_request();
        request.asserted_approval = buffa::MessageField::some(sample_assertion());
        let raw = request.encode_to_vec();
        request
            .asserted_approval
            .as_option_mut()
            .unwrap()
            .signature_hex = crate::hex::lower(&signer.sign(&raw));
        assert!(!verify_approval_assertion(keys(&pk), &request));
    }

    #[test]
    fn edge_identity_signature_never_verifies_as_an_approval_assertion() {
        // INV-A4, forward direction. The signer mints a signature over this
        // request's canonical payload but under the EDGE-IDENTITY domain
        // prefix — the exact confusion a shared prefix would allow. Uses the
        // real `edge_identity` constant, not a copy.
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = sample_request();
        request.asserted_approval = buffa::MessageField::some(sample_assertion());
        let encoded = request.encode_to_vec();

        let mut cross_domain = Vec::new();
        cross_domain.extend_from_slice(crate::edge_identity::EDGE_IDENTITY_DOMAIN_PREFIX);
        cross_domain.extend_from_slice(&encoded);
        request
            .asserted_approval
            .as_option_mut()
            .unwrap()
            .signature_hex = crate::hex::lower(&signer.sign(&cross_domain));

        assert!(
            !verify_approval_assertion(keys(&pk), &request),
            "a signature minted under the edge-identity prefix must not verify as an approval \
             assertion (INV-A4)"
        );

        // The same signer over the SAME payload under the approval prefix
        // does verify — proving the rejection above is the prefix doing the
        // work, not an unrelated mismatch.
        let mut same_domain = Vec::new();
        same_domain.extend_from_slice(APPROVAL_ASSERTION_DOMAIN_PREFIX);
        same_domain.extend_from_slice(&encoded);
        request
            .asserted_approval
            .as_option_mut()
            .unwrap()
            .signature_hex = crate::hex::lower(&signer.sign(&same_domain));
        assert!(verify_approval_assertion(keys(&pk), &request));
    }

    #[test]
    fn approval_assertion_signature_never_verifies_as_an_edge_identity_envelope() {
        // INV-A4, reverse direction: a signature minted under the APPROVAL
        // prefix must not verify as an edge-identity envelope.
        use polyc_proto::proto::polychrome::agent::v1::AssertedAttribution;

        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut envelope = AssertedAttribution {
            edge_id: "chat".to_owned(),
            conversation_id: "chat:team-1:general".to_owned(),
            nonce: "nonce-1".to_owned(),
            issued_unix_ms: 1_700_000_000_000,
            caller: buffa::MessageField::some(sample_responder()),
            exec_id: "exec-1".to_owned(),
            content_hash: crate::edge_identity::content_hash_hex(b"messages-bytes"),
            ..Default::default()
        };
        let encoded = envelope.encode_to_vec();

        let mut cross_domain = Vec::new();
        cross_domain.extend_from_slice(APPROVAL_ASSERTION_DOMAIN_PREFIX);
        cross_domain.extend_from_slice(&encoded);
        envelope.signature_hex = crate::hex::lower(&signer.sign(&cross_domain));
        assert!(
            !crate::edge_identity::verify_edge_assertion(&pk, &envelope),
            "a signature minted under the approval-assertion prefix must not verify as an \
             edge-identity envelope (INV-A4)"
        );

        // Same signer, same payload, correct prefix: verifies. Isolates the
        // rejection above to the domain separation.
        crate::edge_identity::sign_edge_assertion_into(&signer, &mut envelope);
        assert!(crate::edge_identity::verify_edge_assertion(&pk, &envelope));
    }

    #[test]
    fn the_two_domain_prefixes_are_distinct_and_nul_terminated() {
        assert_ne!(
            APPROVAL_ASSERTION_DOMAIN_PREFIX,
            crate::edge_identity::EDGE_IDENTITY_DOMAIN_PREFIX
        );
        assert_eq!(APPROVAL_ASSERTION_DOMAIN_PREFIX.last(), Some(&0u8));
    }
}

/// Drives `polyc-conformance-vectors::APPROVAL_ASSERTION` (`crates/conformance-vectors/vectors/approval-assertion.json`) — the pinned,
/// implementation-independent vectors for this artifact, so a future port in
/// another language cannot silently disagree about the canonical bytes, the
/// domain prefix, or which mutations must break a signature.
#[cfg(test)]
mod conformance {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use buffa::Message as _;
    use polyc_proto::proto::polychrome::approval::v1::{
        Approve, Deny, approval_response_request::Decision,
    };
    use polyc_proto::proto::polychrome::persona::v1::ExternalIdentity;
    use serde_json::Value;

    use super::*;

    const VECTORS: &str = polyc_conformance_vectors::APPROVAL_ASSERTION;

    fn vectors() -> Value {
        serde_json::from_str(VECTORS).expect("the conformance vector file is valid JSON")
    }

    fn hex_of(v: &Value, path: &[&str]) -> Vec<u8> {
        let mut node = v;
        for key in path {
            node = &node[*key];
        }
        crate::hex::decode(node.as_str().expect("a hex string")).expect("valid hex")
    }

    /// The vector's request, rebuilt field by field from the JSON — so the
    /// test proves the encoder agrees with the vector, not merely that the
    /// vector agrees with itself.
    fn vector_request(v: &Value) -> ApprovalResponseRequest {
        let r = &v["vector"]["request"];
        let approve = &r["decision"]["Approve"];
        let responder = &r["asserted_approval"]["responder"];
        ApprovalResponseRequest {
            request_id: r["request_id"].as_str().unwrap().to_owned(),
            conversation_id: r["conversation_id"].as_str().unwrap().to_owned(),
            resolve_token: r["resolve_token"].as_str().unwrap().to_owned(),
            decision: Some(Decision::Approve(Box::new(Approve {
                modified_args_json: approve["modified_args_json"].as_str().unwrap().to_owned(),
                injected_context: approve["injected_context"].as_str().unwrap().to_owned(),
                reason: approve["reason"].as_str().unwrap().to_owned(),
                approved_for_session: approve["approved_for_session"].as_bool().unwrap(),
                ..Default::default()
            }))),
            asserted_approval: buffa::MessageField::some(AssertedApproval {
                edge_id: r["asserted_approval"]["edge_id"]
                    .as_str()
                    .unwrap()
                    .to_owned(),
                responder: buffa::MessageField::some(ExternalIdentity {
                    provider: responder["provider"].as_str().unwrap().to_owned(),
                    scope: responder["scope"].as_str().unwrap().to_owned(),
                    external_id: responder["external_id"].as_str().unwrap().to_owned(),
                    display_name: responder["display_name"].as_str().unwrap().to_owned(),
                    time_zone: responder["time_zone"].as_str().unwrap().to_owned(),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    #[test]
    fn the_pinned_domain_prefix_is_the_one_this_crate_uses() {
        let v = vectors();
        assert_eq!(
            v["domain_separation"]["approval_assertion_prefix_ascii"]
                .as_str()
                .unwrap()
                .as_bytes(),
            APPROVAL_ASSERTION_DOMAIN_PREFIX
        );
        assert_eq!(
            hex_of(&v, &["domain_separation", "approval_assertion_prefix_hex"]),
            APPROVAL_ASSERTION_DOMAIN_PREFIX
        );
        assert_eq!(
            v["domain_separation"]["edge_identity_prefix_ascii"]
                .as_str()
                .unwrap()
                .as_bytes(),
            crate::edge_identity::EDGE_IDENTITY_DOMAIN_PREFIX
        );
        assert_eq!(
            v["signature_scheme"]["namespace_ascii"]
                .as_str()
                .unwrap()
                .as_bytes(),
            crate::NAMESPACE
        );
    }

    #[test]
    fn the_known_good_vector_reproduces_its_bytes_and_signature() {
        let v = vectors();
        let request = vector_request(&v);

        assert_eq!(
            request.encode_to_vec(),
            hex_of(&v, &["vector", "expected_request_encoding_hex"]),
            "the buffa encoding of the vector's request must match the pinned bytes"
        );

        let canonical = canonical_bytes(&request);
        assert_eq!(
            canonical,
            hex_of(&v, &["vector", "expected_canonical_bytes_hex"]),
            "canonical bytes must be the domain prefix followed by that encoding"
        );

        // The exact ed25519 preimage: commonware's union_unique, whose
        // namespace length varint is a single byte at this length.
        let mut preimage = vec![u8::try_from(crate::NAMESPACE.len()).unwrap()];
        preimage.extend_from_slice(crate::NAMESPACE);
        preimage.extend_from_slice(&canonical);
        assert_eq!(
            preimage,
            hex_of(&v, &["vector", "expected_ed25519_message_hex"])
        );

        let private_key = hex_of(&v, &["signer", "ed25519_private_key_hex"]);
        let signer = Signer::from_key_bytes(&private_key).expect("valid key material");
        let public_key = signer.public_key_bytes();
        assert_eq!(
            public_key,
            hex_of(&v, &["signer", "ed25519_public_key_hex"]),
            "the pinned public key must be the one the pinned private key derives"
        );

        let expected_signature = v["vector"]["expected_signature_hex"].as_str().unwrap();
        assert_eq!(
            sign_approval_assertion(&signer, &request),
            expected_signature,
            "signing the vector's request must reproduce the pinned signature"
        );

        let mut signed = request;
        signed
            .asserted_approval
            .as_option_mut()
            .unwrap()
            .signature_hex = expected_signature.to_owned();
        assert!(
            verify_approval_assertion([public_key.as_slice()], &signed),
            "the known-good vector must verify"
        );
    }

    /// Applies each `must_not_verify` mutation to the known-good request,
    /// checks the mutated request encodes to the bytes the vector pinned for
    /// it (so the vector and this code describe the same mutation), and then
    /// checks the pinned signature no longer verifies.
    #[test]
    fn every_pinned_mutation_breaks_verification() {
        let v = vectors();
        let private_key = hex_of(&v, &["signer", "ed25519_private_key_hex"]);
        let signer = Signer::from_key_bytes(&private_key).expect("valid key material");
        let public_key = signer.public_key_bytes();
        let good_signature = v["vector"]["expected_signature_hex"].as_str().unwrap();

        let base = {
            let mut base = vector_request(&v);
            base.asserted_approval
                .as_option_mut()
                .unwrap()
                .signature_hex = good_signature.to_owned();
            base
        };

        let cases = v["must_not_verify"].as_array().expect("a list of cases");
        assert_eq!(cases.len(), 6, "every pinned case must be exercised");

        for case in cases {
            let id = case["id"].as_str().unwrap();
            let mut request = base.clone();

            match id {
                "tampered-responder" => {
                    request
                        .asserted_approval
                        .as_option_mut()
                        .unwrap()
                        .responder
                        .as_option_mut()
                        .unwrap()
                        .external_id = "U0EVE".to_owned();
                }
                "tampered-decision" => {
                    request.decision = Some(Decision::Deny(Box::new(Deny {
                        reason: "approved by Ada".to_owned(),
                        ..Default::default()
                    })));
                }
                "tampered-modified-args" => {
                    let Some(Decision::Approve(approve)) = request.decision.as_mut() else {
                        panic!("the vector's decision is an Approve");
                    };
                    approve.modified_args_json = r#"{"path":"/etc/shadow"}"#.to_owned();
                }
                "tampered-resolve-token" => {
                    request.resolve_token = "resolve-token-conformance-2".to_owned();
                }
                "cross-domain-edge-identity" | "malformed-signature-hex" => {
                    // These leave the request alone and change only the
                    // signature; handled below.
                }
                other => panic!("unhandled conformance case {other}"),
            }

            assert_eq!(
                crate::hex::lower(&canonical_bytes(&request)),
                case["canonical_bytes_hex"].as_str().unwrap(),
                "case {id}: the mutation applied here must be the one the vector pinned"
            );

            let signatures: Vec<String> = case["signature_hex"].as_str().map_or_else(
                || {
                    case["signature_hex_values"]
                        .as_array()
                        .expect("one of signature_hex / signature_hex_values")
                        .iter()
                        .map(|s| s.as_str().unwrap().to_owned())
                        .collect()
                },
                |s| vec![s.to_owned()],
            );

            for signature in signatures {
                request
                    .asserted_approval
                    .as_option_mut()
                    .unwrap()
                    .signature_hex = signature.clone();
                assert!(
                    !verify_approval_assertion([public_key.as_slice()], &request),
                    "case {id}: signature {signature:?} must not verify"
                );
            }
        }
    }
}