polyc-crypto 2026.8.3

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
//! Canonical signing for `RoutineGrantService`'s asserted actor (POLY-34).
//!
//! Mirrors [`crate::approval_assertion`]'s mechanism — an edge's signed
//! statement of which human is acting, covering the whole enclosing
//! request — but for the ten `RoutineGrantService` RPCs instead of
//! `ApprovalService.Respond`. It reuses [`AssertedApproval`], the SAME wire
//! message `ApprovalResponseRequest` carries, rather than a new one: no new
//! auth scheme, one shared envelope shape for "an edge asserts who is
//! acting." One deliberate difference from the sibling: this module has no
//! pinned `polyc-conformance-vectors` entry (`crate::approval_assertion`'s
//! own `mod conformance` does) — its unit tests below cover the same
//! properties (rotation overlap, malformed hex, cross-domain rejection, a
//! NUL-terminated prefix per request type) directly instead, and a future
//! port to another language would need to derive its own vectors from this
//! module rather than reuse a pinned file.
//!
//! Domain separation is per REQUEST TYPE, not shared with
//! [`crate::approval_assertion`] or across the ten RPCs: [`AssertsActor`]
//! ties each implementor to its own [`AssertsActor::DOMAIN_PREFIX`], so a
//! signature minted for one RPC's request can never verify as another's —
//! including a same-shaped one, since two of these requests could otherwise
//! encode to identical bytes for the same `routine`/`tool` values (mirrors
//! `edge_identity`/`approval_assertion`'s own INV-A4 reasoning).
//!
//! Every request also carries a `nonce` and `issued_at_unix_ms`, both
//! covered by the same signature (they ride inside the same message the
//! actor assertion signs). This module only signs and verifies them as
//! ordinary fields of the request — it mints neither: the caller (the
//! rpc-client dialer) supplies both, keeping this module free of ambient
//! wall-clock reads or RNG, same as every other signing module here. Freshness
//! (rejecting a stale `issued_at_unix_ms`) and single-use consumption
//! (rejecting an already-seen `nonce`) are the SERVER's job (the control
//! plane's `RoutineGrantService` handler) — mirroring
//! [`crate::approval::verify_capability`]'s nonce/consumed-set check for an
//! approval's `resolve_token`. Without this, a captured signed request would
//! verify forever; `RefireAttended` in particular is an unbounded
//! attended-dispatch lever against the harness on replay, not a harmless
//! idempotent re-write like the other three.

use polyc_proto::proto::polychrome::approval::v1::AssertedApproval;
use polyc_proto::proto::polychrome::routine::v1::{
    AllowDenialRequest, DeleteRoutineRequest, GetRoutineFireRequest, ListRoutineFiresRequest,
    ListRoutineGrantsRequest, ListRoutinesRequest, PauseRoutineRequest, RefireAttendedRequest,
    ResumeRoutineRequest, RevokeGrantRequest,
};

use crate::{Signer, verify};

/// A `RoutineGrantService` request carrying an [`AssertedApproval`] actor
/// field plus a `nonce`/`issued_at_unix_ms` freshness pair, with its own
/// domain-separation prefix.
///
/// Deliberately READ-ONLY: there is no `&mut` accessor for `actor`/`nonce`/
/// `issued_at_unix_ms`. Mutating one of these fields in place on an
/// already-signed request would silently invalidate the signature with no
/// compiler help catching it — [`AssertsActor::stamped`] is the one way to
/// set them, and it consumes `self` and hands back a new, still-UNSIGNED
/// value, which [`attach_actor_assertion`] alone turns into a signed one.
pub trait AssertsActor: buffa::Message + Clone {
    /// Domain-separation prefix unique to this request's message type
    /// (trailing NUL, mirroring [`crate::approval_assertion::APPROVAL_ASSERTION_DOMAIN_PREFIX`]).
    const DOMAIN_PREFIX: &'static [u8];

    /// Read-only access to the `actor` field's inner message, when set.
    fn actor(&self) -> Option<&AssertedApproval>;

    /// The single-use `nonce` this request carries.
    fn nonce(&self) -> &str;

    /// When the caller signed this request, Unix milliseconds.
    fn issued_at_unix_ms(&self) -> u64;

    /// Consume `self` and return a copy with `actor`/`nonce`/
    /// `issued_at_unix_ms` set to the given values — the only way this
    /// trait lets a caller change them. Not meant for use outside this
    /// module's own [`canonical_bytes`]/[`attach_actor_assertion`].
    #[doc(hidden)]
    #[must_use]
    fn stamped(self, actor: AssertedApproval, nonce: String, issued_at_unix_ms: u64) -> Self;
}

/// Canonical bytes for `request`'s assertion.
///
/// [`AssertsActor::DOMAIN_PREFIX`] followed by the encoding of the whole
/// request with the actor's `signature_hex` cleared, so the signature
/// commits to everything except itself — including `routine` and any other
/// RPC-specific field.
///
/// # Panics
///
/// Never on a request built by [`attach_actor_assertion`]/
/// [`verify_actor_assertion`] (both call this only once `request.actor()` is
/// known `Some`); a request with no actor at all has nothing meaningful to
/// clear a signature from, so this treats that as `signature_hex` already
/// empty rather than panicking.
#[must_use]
pub fn canonical_bytes<M: AssertsActor>(request: &M) -> Vec<u8> {
    let mut cleared_actor = request.actor().cloned().unwrap_or_default();
    cleared_actor.signature_hex.clear();
    let canonical = request.clone().stamped(
        cleared_actor,
        request.nonce().to_owned(),
        request.issued_at_unix_ms(),
    );
    let encoded = canonical.encode_to_vec();
    let mut bytes = Vec::with_capacity(M::DOMAIN_PREFIX.len() + encoded.len());
    bytes.extend_from_slice(M::DOMAIN_PREFIX);
    bytes.extend_from_slice(&encoded);
    bytes
}

/// Sign the canonical bytes of `request`; returns the lowercase-hex
/// signature suitable for [`AssertedApproval::signature_hex`].
///
/// `request` must already carry the actor being signed — prefer
/// [`attach_actor_assertion`], which makes that ordering impossible to get
/// wrong.
#[must_use]
pub fn sign_actor_assertion<M: AssertsActor>(signer: &Signer, request: &M) -> String {
    crate::hex::lower(&signer.sign(&canonical_bytes(request)))
}

/// Set `actor`, `nonce`, and `issued_at_unix_ms` on `request` and sign it,
/// returning the final, signed request.
///
/// `nonce` and `issued_at_unix_ms` are the caller's own to mint (this
/// function does not generate either — see the module doc for why); a
/// dialer mints a fresh nonce and reads the wall clock once per call, never
/// reusing either across two requests.
#[must_use]
pub fn attach_actor_assertion<M: AssertsActor>(
    signer: &Signer,
    request: M,
    actor: AssertedApproval,
    nonce: impl Into<String>,
    issued_at_unix_ms: u64,
) -> M {
    let nonce = nonce.into();
    let unsigned = request.stamped(actor.clone(), nonce.clone(), issued_at_unix_ms);
    let signature_hex = sign_actor_assertion(signer, &unsigned);
    let signed_actor = AssertedApproval {
        signature_hex,
        ..actor
    };
    unsigned.stamped(signed_actor, nonce, issued_at_unix_ms)
}

/// Verify the actor assertion carried on `request`.
///
/// Returns `false` when the request carries no actor, when its
/// `signature_hex` isn't valid hex, or when no candidate key verifies the
/// signature — never panics. Every candidate is checked with no early exit,
/// mirroring [`crate::approval_assertion::verify_approval_assertion`].
#[must_use]
pub fn verify_actor_assertion<'a, K, M>(candidate_public_keys: K, request: &M) -> bool
where
    K: IntoIterator<Item = &'a [u8]>,
    M: AssertsActor,
{
    let Some(actor) = request.actor() else {
        return false;
    };
    let Some(signature) = crate::hex::decode(&actor.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
}

/// Implements [`AssertsActor`] for one `RoutineGrantService` request type —
/// every implementor has the identical `actor`/`nonce`/`issued_at_unix_ms`
/// fields, so this is the one place that shape is written rather than ten
/// hand-copied `impl` blocks.
macro_rules! impl_asserts_actor {
    ($ty:ty, $domain_prefix:expr) => {
        impl AssertsActor for $ty {
            const DOMAIN_PREFIX: &'static [u8] = $domain_prefix;

            fn actor(&self) -> Option<&AssertedApproval> {
                self.actor.as_option()
            }

            fn nonce(&self) -> &str {
                &self.nonce
            }

            fn issued_at_unix_ms(&self) -> u64 {
                self.issued_at_unix_ms
            }

            fn stamped(
                mut self,
                actor: AssertedApproval,
                nonce: String,
                issued_at_unix_ms: u64,
            ) -> Self {
                self.actor = buffa::MessageField::some(actor);
                self.nonce = nonce;
                self.issued_at_unix_ms = issued_at_unix_ms;
                self
            }
        }
    };
}

impl_asserts_actor!(
    AllowDenialRequest,
    b"polychrome.routine-grant-assertion.allow-denial.v1\0"
);
impl_asserts_actor!(
    RevokeGrantRequest,
    b"polychrome.routine-grant-assertion.revoke-grant.v1\0"
);
impl_asserts_actor!(
    RefireAttendedRequest,
    b"polychrome.routine-grant-assertion.refire-attended.v1\0"
);
impl_asserts_actor!(
    ListRoutineGrantsRequest,
    b"polychrome.routine-grant-assertion.list-routine-grants.v1\0"
);
impl_asserts_actor!(
    ListRoutinesRequest,
    b"polychrome.routine-grant-assertion.list-routines.v1\0"
);
impl_asserts_actor!(
    PauseRoutineRequest,
    b"polychrome.routine-grant-assertion.pause-routine.v1\0"
);
impl_asserts_actor!(
    ResumeRoutineRequest,
    b"polychrome.routine-grant-assertion.resume-routine.v1\0"
);
impl_asserts_actor!(
    DeleteRoutineRequest,
    b"polychrome.routine-grant-assertion.delete-routine.v1\0"
);
impl_asserts_actor!(
    ListRoutineFiresRequest,
    b"polychrome.routine-grant-assertion.list-routine-fires.v1\0"
);
impl_asserts_actor!(
    GetRoutineFireRequest,
    b"polychrome.routine-grant-assertion.get-routine-fire.v1\0"
);

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

    use buffa::Message as _;
    use polyc_proto::proto::polychrome::persona::v1::ExternalIdentity;

    use super::*;

    fn sample_actor() -> AssertedApproval {
        AssertedApproval {
            edge_id: "chat".to_owned(),
            responder: buffa::MessageField::some(ExternalIdentity {
                provider: "chat".to_owned(),
                scope: "team-1".to_owned(),
                external_id: "U123".to_owned(),
                display_name: "Ada".to_owned(),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    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 mut request = AllowDenialRequest {
            routine: "standup".to_owned(),
            tool: "send_email".to_owned(),
            ..Default::default()
        };
        request = attach_actor_assertion(&signer, request, sample_actor(), "nonce-1", 1_000);
        assert!(!request.actor.as_option().unwrap().signature_hex.is_empty());
        assert!(verify_actor_assertion(keys(&pk), &request));
    }

    #[test]
    fn tampered_routine_fails() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = AllowDenialRequest {
            routine: "standup".to_owned(),
            tool: "send_email".to_owned(),
            ..Default::default()
        };
        request = attach_actor_assertion(&signer, request, sample_actor(), "nonce-1", 1_000);
        request.routine = "payroll".to_owned();
        assert!(
            !verify_actor_assertion(keys(&pk), &request),
            "swapping the routine after signing must invalidate the signature"
        );
    }

    #[test]
    fn tampered_actor_fails() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = AllowDenialRequest {
            routine: "standup".to_owned(),
            tool: "send_email".to_owned(),
            ..Default::default()
        };
        request = attach_actor_assertion(&signer, request, sample_actor(), "nonce-1", 1_000);
        request.actor.as_option_mut().unwrap().responder =
            buffa::MessageField::some(ExternalIdentity {
                external_id: "U999".to_owned(),
                ..Default::default()
            });
        assert!(!verify_actor_assertion(keys(&pk), &request));
    }

    #[test]
    fn wrong_key_fails() {
        let signer = Signer::from_seed(41);
        let other = Signer::from_seed(42);
        let mut request = AllowDenialRequest {
            routine: "standup".to_owned(),
            tool: "send_email".to_owned(),
            ..Default::default()
        };
        request = attach_actor_assertion(&signer, request, sample_actor(), "nonce-1", 1_000);
        assert!(!verify_actor_assertion(
            keys(&other.public_key_bytes()),
            &request
        ));
    }

    /// One signed `AllowDenialRequest`, plus its `actor`/`nonce`/
    /// `issued_at_unix_ms` fields lifted onto the OTHER three request types —
    /// the shape a captured signed request would take if replayed against a
    /// different RPC. `pk` is `signer`'s public key, the one candidate every
    /// assertion in this matrix is checked against.
    struct CrossTypeFixture {
        pk: Vec<u8>,
        allow: AllowDenialRequest,
        revoke: RevokeGrantRequest,
        refire: RefireAttendedRequest,
        list: ListRoutineGrantsRequest,
        list_routines: ListRoutinesRequest,
        pause: PauseRoutineRequest,
        resume: ResumeRoutineRequest,
        delete: DeleteRoutineRequest,
        list_fires: ListRoutineFiresRequest,
        get_fire: GetRoutineFireRequest,
    }

    fn cross_type_fixture() -> CrossTypeFixture {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut allow = AllowDenialRequest {
            routine: "standup".to_owned(),
            tool: "send_email".to_owned(),
            ..Default::default()
        };
        allow = attach_actor_assertion(&signer, allow, sample_actor(), "nonce-1", 1_000);
        let revoke = RevokeGrantRequest {
            routine: allow.routine.clone(),
            tool: allow.tool.clone(),
            actor: allow.actor.clone(),
            nonce: allow.nonce.clone(),
            issued_at_unix_ms: allow.issued_at_unix_ms,
            ..Default::default()
        };
        let refire = RefireAttendedRequest {
            routine: allow.routine.clone(),
            actor: allow.actor.clone(),
            nonce: allow.nonce.clone(),
            issued_at_unix_ms: allow.issued_at_unix_ms,
            ..Default::default()
        };
        let list = ListRoutineGrantsRequest {
            routine: allow.routine.clone(),
            actor: allow.actor.clone(),
            nonce: allow.nonce.clone(),
            issued_at_unix_ms: allow.issued_at_unix_ms,
            ..Default::default()
        };
        let list_routines = ListRoutinesRequest {
            actor: allow.actor.clone(),
            nonce: allow.nonce.clone(),
            issued_at_unix_ms: allow.issued_at_unix_ms,
            ..Default::default()
        };
        let pause = PauseRoutineRequest {
            routine: allow.routine.clone(),
            actor: allow.actor.clone(),
            nonce: allow.nonce.clone(),
            issued_at_unix_ms: allow.issued_at_unix_ms,
            ..Default::default()
        };
        let resume = ResumeRoutineRequest {
            routine: allow.routine.clone(),
            actor: allow.actor.clone(),
            nonce: allow.nonce.clone(),
            issued_at_unix_ms: allow.issued_at_unix_ms,
            ..Default::default()
        };
        let delete = DeleteRoutineRequest {
            routine: allow.routine.clone(),
            actor: allow.actor.clone(),
            nonce: allow.nonce.clone(),
            issued_at_unix_ms: allow.issued_at_unix_ms,
            ..Default::default()
        };
        let list_fires = ListRoutineFiresRequest {
            routine: allow.routine.clone(),
            actor: allow.actor.clone(),
            nonce: allow.nonce.clone(),
            issued_at_unix_ms: allow.issued_at_unix_ms,
            ..Default::default()
        };
        let get_fire = GetRoutineFireRequest {
            routine: allow.routine.clone(),
            actor: allow.actor.clone(),
            nonce: allow.nonce.clone(),
            issued_at_unix_ms: allow.issued_at_unix_ms,
            ..Default::default()
        };
        CrossTypeFixture {
            pk,
            allow,
            revoke,
            refire,
            list,
            list_routines,
            pause,
            resume,
            delete,
            list_fires,
            get_fire,
        }
    }

    /// INV-A4-class, the full matrix: every one of the
    /// ten `RoutineGrantService` request types shares a field shape close
    /// enough (`routine`/`actor`/`nonce`/`issued_at_unix_ms`, `tool` on two
    /// of them) that a signature minted for one must never verify against
    /// any of the other three, even carrying identical values — a captured
    /// signed `AllowDenial` request must not replay as a `RevokeGrant`,
    /// `RefireAttended`, or `ListRoutineGrants` call, and so on for every
    /// other type this signature was never minted under.
    #[test]
    fn a_signature_never_verifies_across_any_request_type() {
        let fixture = cross_type_fixture();
        let keys = keys(&fixture.pk);
        assert!(
            !verify_actor_assertion(keys, &fixture.revoke),
            "AllowDenialRequest's signature must not verify as RevokeGrantRequest"
        );
        assert!(
            !verify_actor_assertion(keys, &fixture.refire),
            "AllowDenialRequest's signature must not verify as RefireAttendedRequest"
        );
        assert!(
            !verify_actor_assertion(keys, &fixture.list),
            "AllowDenialRequest's signature must not verify as ListRoutineGrantsRequest"
        );
        assert!(
            !verify_actor_assertion(keys, &fixture.list_routines),
            "AllowDenialRequest's signature must not verify as ListRoutinesRequest"
        );
        assert!(
            !verify_actor_assertion(keys, &fixture.pause),
            "AllowDenialRequest's signature must not verify as PauseRoutineRequest"
        );
        assert!(
            !verify_actor_assertion(keys, &fixture.resume),
            "AllowDenialRequest's signature must not verify as ResumeRoutineRequest"
        );
        assert!(
            !verify_actor_assertion(keys, &fixture.delete),
            "AllowDenialRequest's signature must not verify as DeleteRoutineRequest"
        );
        assert!(
            !verify_actor_assertion(keys, &fixture.list_fires),
            "AllowDenialRequest's signature must not verify as ListRoutineFiresRequest"
        );
        assert!(
            !verify_actor_assertion(keys, &fixture.get_fire),
            "AllowDenialRequest's signature must not verify as GetRoutineFireRequest"
        );
        // And the fixture's own AllowDenialRequest still verifies as itself —
        // proof the matrix above fails on domain separation, not on a
        // decode/field mismatch that would make every check above vacuous.
        assert!(verify_actor_assertion(keys, &fixture.allow));
    }

    #[test]
    fn absent_actor_never_verifies() {
        let request = AllowDenialRequest {
            routine: "standup".to_owned(),
            ..Default::default()
        };
        assert!(!verify_actor_assertion(
            keys(&Signer::from_seed(1).public_key_bytes()),
            &request
        ));
    }

    #[test]
    fn tampered_nonce_fails() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = AllowDenialRequest {
            routine: "standup".to_owned(),
            tool: "send_email".to_owned(),
            ..Default::default()
        };
        request = attach_actor_assertion(&signer, request, sample_actor(), "nonce-1", 1_000);
        request.nonce = "nonce-2".to_owned();
        assert!(
            !verify_actor_assertion(keys(&pk), &request),
            "swapping the nonce after signing must invalidate the signature"
        );
    }

    #[test]
    fn tampered_issued_at_fails() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let mut request = AllowDenialRequest {
            routine: "standup".to_owned(),
            tool: "send_email".to_owned(),
            ..Default::default()
        };
        request = attach_actor_assertion(&signer, request, sample_actor(), "nonce-1", 1_000);
        request.issued_at_unix_ms = 999_999;
        assert!(
            !verify_actor_assertion(keys(&pk), &request),
            "backdating the timestamp after signing must invalidate the signature"
        );
    }

    #[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 = AllowDenialRequest {
            routine: "standup".to_owned(),
            tool: "send_email".to_owned(),
            ..Default::default()
        };
        let request = attach_actor_assertion(&signer, request, sample_actor(), "nonce-1", 1_000);
        let candidates: [&[u8]; 2] = [&retiring_pk, &active_pk];
        assert!(verify_actor_assertion(candidates, &request));
    }

    #[test]
    fn garbage_signature_hex_returns_false_not_panic() {
        let signer = Signer::from_seed(41);
        let pk = signer.public_key_bytes();
        let request = AllowDenialRequest {
            routine: "standup".to_owned(),
            tool: "send_email".to_owned(),
            ..Default::default()
        };
        let mut request =
            attach_actor_assertion(&signer, request, sample_actor(), "nonce-1", 1_000);
        for garbage in ["not-hex!", "abc", "", "zz", &"ab".repeat(4096)] {
            request.actor.as_option_mut().unwrap().signature_hex = garbage.to_owned();
            assert!(
                !verify_actor_assertion(keys(&pk), &request),
                "malformed signature_hex {garbage:?} must return false, not panic"
            );
        }
    }

    #[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 = AllowDenialRequest {
            routine: "standup".to_owned(),
            tool: "send_email".to_owned(),
            actor: buffa::MessageField::some(sample_actor()),
            nonce: "nonce-1".to_owned(),
            issued_at_unix_ms: 1_000,
            ..Default::default()
        };
        let raw = request.encode_to_vec();
        request.actor.as_option_mut().unwrap().signature_hex =
            crate::hex::lower(&signer.sign(&raw));
        assert!(!verify_actor_assertion(keys(&pk), &request));
    }

    #[test]
    fn domain_prefixes_are_distinct_and_nul_terminated() {
        let prefixes: [&[u8]; 10] = [
            AllowDenialRequest::DOMAIN_PREFIX,
            RevokeGrantRequest::DOMAIN_PREFIX,
            RefireAttendedRequest::DOMAIN_PREFIX,
            ListRoutineGrantsRequest::DOMAIN_PREFIX,
            ListRoutinesRequest::DOMAIN_PREFIX,
            PauseRoutineRequest::DOMAIN_PREFIX,
            ResumeRoutineRequest::DOMAIN_PREFIX,
            DeleteRoutineRequest::DOMAIN_PREFIX,
            ListRoutineFiresRequest::DOMAIN_PREFIX,
            GetRoutineFireRequest::DOMAIN_PREFIX,
        ];
        for prefix in prefixes {
            assert_eq!(
                prefix.last(),
                Some(&0u8),
                "{prefix:?} must be NUL-terminated"
            );
        }
        for (i, a) in prefixes.iter().enumerate() {
            for b in &prefixes[i + 1..] {
                assert_ne!(a, b, "every domain prefix must be pairwise distinct");
            }
        }
    }
}