polyc-crypto 2026.8.0

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
Documentation
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
//! Compile-time separated platform signing roles and public identities.
//!
//! Domain prefixes keep signatures for two artifact shapes from verifying as
//! one another. They do not limit what a stolen private key can mint. These
//! role types close that larger blast radius: approval, browser-session,
//! turn-read, web-session-grant, and journal-attestation keys are different
//! types loaded from different custody references.

use std::{marker::PhantomData, sync::Arc};

use sha2::{Digest as _, Sha256};

use crate::{Signer, verify};

mod private {
    pub trait Sealed {}
}

/// A stable signing-role identity.
pub trait SigningRole: private::Sealed + Send + Sync + 'static {
    /// Stable issuer string recorded beside this role's trust history.
    const ISSUER: &'static str;
}

macro_rules! role {
    ($(#[$meta:meta])* $name:ident, $issuer:literal) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub struct $name;
        impl private::Sealed for $name {}
        impl SigningRole for $name {
            const ISSUER: &'static str = $issuer;
        }
    };
}

role!(
    /// Human and policy approval decisions and their durable markers.
    ApprovalRole,
    "polychrome.control.approval"
);
role!(
    /// State-authorized browser-session bearer tokens.
    SessionRole,
    "polychrome.control.session"
);
role!(
    /// Conversation-scoped query capability grants.
    TurnReadRole,
    "polychrome.control.turn-read"
);
role!(
    /// Deterministic web-session-family rotation grants.
    WebSessionGrantRole,
    "polychrome.control.web-session-grant"
);
role!(
    /// Tamper-evident journal-root attestations.
    JournalAttestationRole,
    "polychrome.state.journal-attestation"
);

/// Stable secret-manager reference for Control's approval-role private key.
pub const CONTROL_APPROVAL_KEY_REF: &str = "control-plane/approval-signer";
/// Stable secret-manager reference for Control's approval public history.
pub const CONTROL_APPROVAL_HISTORY_REF: &str = "control-plane/approval-signer-history";
/// Stable secret-manager reference for Control's session-role private key.
pub const CONTROL_SESSION_KEY_REF: &str = "control-plane/session-signer";
/// Stable secret-manager reference for Control's session public history.
pub const CONTROL_SESSION_HISTORY_REF: &str = "control-plane/session-signer-history";
/// Stable secret-manager reference for Control's turn-read private key.
pub const CONTROL_TURN_READ_KEY_REF: &str = "control-plane/turn-read-signer";
/// Stable secret-manager reference for Control's turn-read public history.
pub const CONTROL_TURN_READ_HISTORY_REF: &str = "control-plane/turn-read-signer-history";
/// Stable secret-manager reference for Control's web-session-grant private key.
pub const CONTROL_WEB_SESSION_GRANT_KEY_REF: &str = "control-plane/web-session-grant-signer";
/// Stable secret-manager reference for Control's web-session-grant history.
pub const CONTROL_WEB_SESSION_GRANT_HISTORY_REF: &str =
    "control-plane/web-session-grant-signer-history";
/// Stable reference for Control's temporary memory-journal private key.
pub const CONTROL_MEMORY_JOURNAL_KEY_REF: &str = "control-plane/memory-journal-attestation-signer";
/// Stable reference for Control's temporary memory-journal public history.
pub const CONTROL_MEMORY_JOURNAL_HISTORY_REF: &str =
    "control-plane/memory-journal-attestation-signer-history";

/// Public identity of one signing key within one role.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SigningKeyIdentity {
    issuer: String,
    key_id: String,
    public_key: Vec<u8>,
}

impl SigningKeyIdentity {
    /// Derives the canonical identity for a trusted role public key.
    ///
    /// # Errors
    ///
    /// Refuses a value that is not an encoded ed25519 public key.
    pub fn for_public_key<R: SigningRole>(
        public_key: Vec<u8>,
    ) -> Result<Self, SigningIdentityError> {
        if public_key.len() != 32 {
            return Err(SigningIdentityError::InvalidPublicKey);
        }
        Ok(Self {
            issuer: R::ISSUER.to_owned(),
            key_id: key_id(R::ISSUER, &public_key),
            public_key,
        })
    }

    /// Reconstructs a public identity read from trusted custody metadata.
    ///
    /// # Errors
    ///
    /// Refuses an issuer mismatch, malformed key, or key id not derived from
    /// the exact issuer and public key.
    pub fn checked<R: SigningRole>(
        issuer: impl Into<String>,
        claimed_key_id: impl Into<String>,
        public_key: Vec<u8>,
    ) -> Result<Self, SigningIdentityError> {
        let identity = Self {
            issuer: issuer.into(),
            key_id: claimed_key_id.into(),
            public_key,
        };
        if identity.issuer != R::ISSUER {
            return Err(SigningIdentityError::WrongIssuer);
        }
        if identity.public_key.len() != 32 {
            return Err(SigningIdentityError::InvalidPublicKey);
        }
        if identity.key_id != key_id(R::ISSUER, &identity.public_key) {
            return Err(SigningIdentityError::WrongKeyId);
        }
        Ok(identity)
    }

    /// Stable role issuer.
    #[must_use]
    pub fn issuer(&self) -> &str {
        &self.issuer
    }

    /// Deterministic identifier for this issuer/public-key pair.
    #[must_use]
    pub fn key_id(&self) -> &str {
        &self.key_id
    }

    /// Encoded ed25519 public key.
    #[must_use]
    pub fn public_key(&self) -> &[u8] {
        &self.public_key
    }
}

/// Invalid public signing-key identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum SigningIdentityError {
    /// The record belongs to another signing role.
    #[error("signing-key issuer does not match its role")]
    WrongIssuer,
    /// The ed25519 public key is not 32 bytes.
    #[error("signing public key is not an encoded ed25519 key")]
    InvalidPublicKey,
    /// The claimed key id does not cover the issuer and public key.
    #[error("signing key id does not match its issuer and public key")]
    WrongKeyId,
}

/// One role's private signer.
pub struct RoleSigner<R: SigningRole> {
    inner: Arc<Signer>,
    role: PhantomData<R>,
}

impl<R: SigningRole> Clone for RoleSigner<R> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
            role: PhantomData,
        }
    }
}

impl<R: SigningRole> std::fmt::Debug for RoleSigner<R> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("RoleSigner")
            .field("identity", &self.identity())
            .finish_non_exhaustive()
    }
}

impl<R: SigningRole> RoleSigner<R> {
    /// Builds a signer from an insecure deterministic test seed.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub fn from_seed(seed: u64) -> Self {
        Self {
            inner: Arc::new(Signer::from_seed(seed)),
            role: PhantomData,
        }
    }

    /// Builds this role from raw ed25519 private-key bytes held by custody.
    ///
    /// # Errors
    ///
    /// Returns [`crate::SignerError`] for malformed private-key material.
    pub fn from_key_bytes(bytes: &[u8]) -> Result<Self, crate::SignerError> {
        Ok(Self {
            inner: Arc::new(Signer::from_key_bytes(bytes)?),
            role: PhantomData,
        })
    }

    /// Encoded public key.
    #[must_use]
    pub fn public_key_bytes(&self) -> Vec<u8> {
        self.inner.public_key_bytes()
    }

    /// Explicit issuer and deterministic key identity.
    #[must_use]
    pub fn identity(&self) -> SigningKeyIdentity {
        let public_key = self.public_key_bytes();
        SigningKeyIdentity {
            issuer: R::ISSUER.to_owned(),
            key_id: key_id(R::ISSUER, &public_key),
            public_key,
        }
    }

    /// Signs bytes inside this crate's role-specific protocol builders.
    ///
    /// Kept crate-private so holding one role never exposes a generic signing
    /// oracle that can manufacture another role's canonical artifact.
    #[must_use]
    pub(crate) fn sign(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner.sign(canonical_bytes)
    }

    /// Borrows the primitive for this crate's role-specific envelope builders.
    ///
    /// Kept crate-private so an external caller holding one role cannot erase
    /// its type and pass the same private key to another signing protocol.
    #[must_use]
    pub(crate) fn as_signer(&self) -> &Signer {
        &self.inner
    }

    /// Re-labels deterministic fixture material for a different role.
    ///
    /// Production builds cannot convert one signing role into another;
    /// callers must load independent custody records instead.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub fn relabel_for_test<S: SigningRole>(&self) -> RoleSigner<S> {
        RoleSigner {
            inner: Arc::clone(&self.inner),
            role: PhantomData,
        }
    }
}

impl RoleSigner<TurnReadRole> {
    /// Signs a canonical conversation-scoped turn-read capability.
    ///
    /// This named role operation avoids exposing the underlying signer or a
    /// generic cross-protocol signing method to query-layer callers.
    #[must_use]
    pub fn sign_turn_read_capability(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner
            .sign(&role_scoped_message::<TurnReadRole>(canonical_bytes))
    }
}

impl RoleSigner<JournalAttestationRole> {
    /// Signs a canonical Merkle Mountain Range journal-root attestation.
    ///
    /// This named role operation avoids exposing the underlying signer or a
    /// generic cross-protocol signing method to journal callers.
    #[must_use]
    pub fn sign_journal_root(&self, canonical_bytes: &[u8]) -> Vec<u8> {
        self.inner
            .sign(&role_scoped_message::<JournalAttestationRole>(
                canonical_bytes,
            ))
    }
}

/// Public trust set for exactly one signing role.
#[derive(Debug, Clone)]
pub struct RoleTrustSet<R: SigningRole> {
    keys: Vec<SigningKeyIdentity>,
    role: PhantomData<R>,
}

/// Append-only public-key history for one signing role.
///
/// The record contains public identities only. Custody persists the current
/// private key under a separate secret reference and stores this record as the
/// durable verification history.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SigningKeyHistory {
    current: SigningKeyIdentity,
    retired: Vec<SigningKeyIdentity>,
}

impl SigningKeyHistory {
    /// Starts a history at one role's current signer.
    #[must_use]
    pub fn current<R: SigningRole>(signer: &RoleSigner<R>) -> Self {
        Self {
            current: signer.identity(),
            retired: Vec::new(),
        }
    }

    /// Public identity recorded as current.
    #[must_use]
    pub const fn current_identity(&self) -> &SigningKeyIdentity {
        &self.current
    }

    /// Append-only public identities recorded as retired.
    #[must_use]
    pub fn retired_identities(&self) -> &[SigningKeyIdentity] {
        &self.retired
    }

    /// Reconciles a stored history with the current signer identity.
    ///
    /// A rotation appends the previous current identity to `retired`. Cycling
    /// back to an earlier key never removes it from the stored retired set,
    /// while the returned trust set lists each identity once with current
    /// first.
    ///
    /// # Errors
    ///
    /// Refuses a malformed identity, an identity from another role, or a
    /// duplicate retired identity.
    pub fn reconcile<R: SigningRole>(
        &mut self,
        current: &SigningKeyIdentity,
    ) -> Result<(RoleTrustSet<R>, bool), SigningIdentityError> {
        let current = SigningKeyIdentity::checked::<R>(
            current.issuer.clone(),
            current.key_id.clone(),
            current.public_key.clone(),
        )?;
        let prior_current = SigningKeyIdentity::checked::<R>(
            self.current.issuer.clone(),
            self.current.key_id.clone(),
            self.current.public_key.clone(),
        )?;
        let mut retired = self
            .retired
            .iter()
            .map(|identity| {
                SigningKeyIdentity::checked::<R>(
                    identity.issuer.clone(),
                    identity.key_id.clone(),
                    identity.public_key.clone(),
                )
            })
            .collect::<Result<Vec<_>, _>>()?;
        for (index, identity) in retired.iter().enumerate() {
            if retired[..index]
                .iter()
                .any(|prior| prior.key_id == identity.key_id)
            {
                return Err(SigningIdentityError::WrongKeyId);
            }
        }

        let rotated = prior_current != current;
        if rotated
            && !retired
                .iter()
                .any(|identity| identity.key_id == prior_current.key_id)
        {
            retired.push(prior_current);
        }
        self.current = current.clone();
        self.retired.clone_from(&retired);

        let mut identities = vec![current.clone()];
        identities.extend(
            retired
                .into_iter()
                .filter(|identity| identity.key_id != current.key_id),
        );
        Ok((RoleTrustSet::checked(identities)?, rotated))
    }
}

impl<R: SigningRole> RoleTrustSet<R> {
    /// Derives canonical identities for a non-empty list of trusted keys.
    ///
    /// # Errors
    ///
    /// Refuses empty, duplicate, or malformed public keys.
    pub fn from_public_keys(keys: Vec<Vec<u8>>) -> Result<Self, SigningIdentityError> {
        let identities = keys
            .into_iter()
            .map(SigningKeyIdentity::for_public_key::<R>)
            .collect::<Result<Vec<_>, _>>()?;
        Self::checked(identities)
    }

    /// Validates and canonicalizes a non-empty role trust set.
    ///
    /// # Errors
    ///
    /// Refuses empty, duplicate, malformed, or cross-role identities.
    pub fn checked(keys: Vec<SigningKeyIdentity>) -> Result<Self, SigningIdentityError> {
        if keys.is_empty() {
            return Err(SigningIdentityError::InvalidPublicKey);
        }
        let mut checked = Vec::with_capacity(keys.len());
        for key in keys {
            let key = SigningKeyIdentity::checked::<R>(key.issuer, key.key_id, key.public_key)?;
            if checked
                .iter()
                .any(|known: &SigningKeyIdentity| known.key_id == key.key_id)
            {
                return Err(SigningIdentityError::WrongKeyId);
            }
            checked.push(key);
        }
        Ok(Self {
            keys: checked,
            role: PhantomData,
        })
    }

    /// Trusts only the current signer.
    #[must_use]
    pub fn current(signer: &RoleSigner<R>) -> Self {
        Self {
            keys: vec![signer.identity()],
            role: PhantomData,
        }
    }

    /// Public identities, current first and retired afterward.
    #[must_use]
    pub fn keys(&self) -> &[SigningKeyIdentity] {
        &self.keys
    }

    /// Verifies against the explicitly named key in this role.
    #[must_use]
    pub(crate) fn verify(&self, key_id: &str, message: &[u8], signature: &[u8]) -> bool {
        self.keys
            .iter()
            .find(|key| key.key_id == key_id)
            .is_some_and(|key| verify(&key.public_key, message, signature))
    }
}

impl RoleTrustSet<TurnReadRole> {
    /// Verifies a canonical conversation-scoped turn-read capability.
    #[must_use]
    pub fn verify_turn_read_capability(
        &self,
        key_id: &str,
        canonical_bytes: &[u8],
        signature: &[u8],
    ) -> bool {
        self.verify(
            key_id,
            &role_scoped_message::<TurnReadRole>(canonical_bytes),
            signature,
        )
    }
}

impl RoleTrustSet<JournalAttestationRole> {
    /// Verifies a canonical Merkle Mountain Range journal-root attestation.
    #[must_use]
    pub fn verify_journal_root(
        &self,
        key_id: &str,
        canonical_bytes: &[u8],
        signature: &[u8],
    ) -> bool {
        self.verify(
            key_id,
            &role_scoped_message::<JournalAttestationRole>(canonical_bytes),
            signature,
        )
    }
}

/// Approval signer type retained at its established public path.
pub type ApprovalSigner = RoleSigner<ApprovalRole>;
/// Browser-session signer.
pub type SessionSigner = RoleSigner<SessionRole>;
/// Conversation turn-read capability signer.
pub type TurnReadSigner = RoleSigner<TurnReadRole>;
/// Web-session-family grant signer.
pub type WebSessionGrantSigner = RoleSigner<WebSessionGrantRole>;
/// Journal-root attestation signer.
pub type JournalAttestationSigner = RoleSigner<JournalAttestationRole>;

fn key_id(issuer: &str, public_key: &[u8]) -> String {
    let mut hash = Sha256::new();
    hash.update(b"polychrome.signing-key-id.v1\0");
    hash.update(
        u64::try_from(issuer.len())
            .unwrap_or(u64::MAX)
            .to_be_bytes(),
    );
    hash.update(issuer.as_bytes());
    hash.update(public_key);
    crate::hex::lower(&hash.finalize())
}

fn role_scoped_message<R: SigningRole>(canonical_bytes: &[u8]) -> Vec<u8> {
    let mut message = Vec::with_capacity(40 + R::ISSUER.len() + canonical_bytes.len());
    message.extend_from_slice(b"polychrome.signing-role.v1\0");
    message.extend_from_slice(
        &u64::try_from(R::ISSUER.len())
            .unwrap_or(u64::MAX)
            .to_be_bytes(),
    );
    message.extend_from_slice(R::ISSUER.as_bytes());
    message.extend_from_slice(canonical_bytes);
    message
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn roles_have_distinct_issuers_and_key_ids() {
        let approval = ApprovalSigner::from_seed(7);
        let session = SessionSigner::from_seed(7);
        assert_ne!(approval.identity().issuer(), session.identity().issuer());
        assert_ne!(approval.identity().key_id(), session.identity().key_id());
        assert_eq!(approval.public_key_bytes(), session.public_key_bytes());
    }

    #[test]
    fn a_cross_role_identity_is_refused() {
        let identity = ApprovalSigner::from_seed(7).identity();
        assert_eq!(
            SigningKeyIdentity::checked::<SessionRole>(
                identity.issuer,
                identity.key_id,
                identity.public_key,
            ),
            Err(SigningIdentityError::WrongIssuer)
        );
    }

    #[test]
    fn role_trust_requires_the_named_key() {
        let current = SessionSigner::from_seed(7);
        let retired = SessionSigner::from_seed(8);
        let trust =
            RoleTrustSet::<SessionRole>::checked(vec![current.identity(), retired.identity()])
                .expect("valid role history");
        let message = b"session";
        assert!(trust.verify(current.identity().key_id(), message, &current.sign(message)));
        assert!(trust.verify(retired.identity().key_id(), message, &retired.sign(message)));
        assert!(!trust.verify("unknown", message, &current.sign(message)));
    }

    #[test]
    fn role_trust_survives_key_cycling_without_cross_role_acceptance() {
        let first = SessionSigner::from_seed(7);
        let second = SessionSigner::from_seed(8);
        let third = SessionSigner::from_seed(9);
        let trust = RoleTrustSet::<SessionRole>::checked(vec![
            third.identity(),
            second.identity(),
            first.identity(),
        ])
        .expect("valid cycled history");
        let message = b"session";

        for signer in [&first, &second, &third] {
            assert!(trust.verify(signer.identity().key_id(), message, &signer.sign(message)));
        }

        let approval = ApprovalSigner::from_seed(7);
        assert!(!trust.verify(
            approval.identity().key_id(),
            message,
            &approval.sign(message),
        ));
    }

    #[test]
    fn history_rotation_and_cycling_preserve_each_public_identity_once() {
        let first = SessionSigner::from_seed(7);
        let second = SessionSigner::from_seed(8);
        let mut history = SigningKeyHistory::current(&first);

        let (trust, rotated) = history
            .reconcile::<SessionRole>(&second.identity())
            .expect("first rotation is valid");
        assert!(rotated);
        assert_eq!(trust.keys(), &[second.identity(), first.identity()]);

        let (trust, rotated) = history
            .reconcile::<SessionRole>(&first.identity())
            .expect("cycling back is valid");
        assert!(rotated);
        assert_eq!(trust.keys(), &[first.identity(), second.identity()]);

        let (trust, rotated) = history
            .reconcile::<SessionRole>(&second.identity())
            .expect("cycling forward is valid");
        assert!(rotated);
        assert_eq!(trust.keys(), &[second.identity(), first.identity()]);
        assert_eq!(
            history.retired_identities(),
            &[first.identity(), second.identity()]
        );
    }

    #[test]
    fn history_rejects_duplicate_retired_identity() {
        let first = SessionSigner::from_seed(7);
        let second = SessionSigner::from_seed(8);
        let mut history = SigningKeyHistory {
            current: second.identity(),
            retired: vec![first.identity(), first.identity()],
        };

        assert!(matches!(
            history.reconcile::<SessionRole>(&second.identity()),
            Err(SigningIdentityError::WrongKeyId)
        ));
    }

    #[test]
    fn history_schema_rejects_unrecognized_fields() {
        let signer = SessionSigner::from_seed(7);
        let mut value =
            serde_json::to_value(SigningKeyHistory::current(&signer)).expect("history serializes");
        value
            .as_object_mut()
            .expect("history is an object")
            .insert("private_key".to_owned(), serde_json::json!("must-not-pass"));

        assert!(serde_json::from_value::<SigningKeyHistory>(value).is_err());
    }

    #[test]
    fn public_role_protocols_reject_the_same_key_under_the_wrong_role() {
        let turn_read = TurnReadSigner::from_seed(17);
        let journal: JournalAttestationSigner = turn_read.relabel_for_test();
        let turn_read_trust = RoleTrustSet::<TurnReadRole>::current(&turn_read);
        let journal_trust = RoleTrustSet::<JournalAttestationRole>::current(&journal);
        let canonical = b"same canonical bytes";
        let turn_read_signature = turn_read.sign_turn_read_capability(canonical);
        let journal_signature = journal.sign_journal_root(canonical);

        assert!(turn_read_trust.verify_turn_read_capability(
            turn_read.identity().key_id(),
            canonical,
            &turn_read_signature,
        ));
        assert!(journal_trust.verify_journal_root(
            journal.identity().key_id(),
            canonical,
            &journal_signature,
        ));
        assert!(!turn_read_trust.verify_turn_read_capability(
            turn_read.identity().key_id(),
            canonical,
            &journal_signature,
        ));
        assert!(!journal_trust.verify_journal_root(
            journal.identity().key_id(),
            canonical,
            &turn_read_signature,
        ));
    }

    #[test]
    fn signer_debug_never_prints_private_material() {
        let signer = SessionSigner::from_key_bytes(&[0x0cu8; 32]).expect("valid seed");
        let debug = format!("{signer:?}");
        assert!(debug.contains(SessionRole::ISSUER));
        assert!(!debug.contains("0c0c0c0c"));
    }

    #[test]
    fn native_smoke_bootstrap_vectors_are_stable() {
        fn assert_identity<R: SigningRole>(
            seed: u8,
            expected_public_key: &str,
            expected_key_id: &str,
        ) {
            let signer = RoleSigner::<R>::from_key_bytes(&[seed; 32]).expect("valid seed");
            assert_eq!(
                crate::hex::lower(&signer.public_key_bytes()),
                expected_public_key
            );
            assert_eq!(signer.identity().key_id(), expected_key_id);
        }

        assert_identity::<ApprovalRole>(
            0x0b,
            "66be7e332c7a453332bd9d0a7f7db055f5c5ef1a06ada66d98b39fb6810c473a",
            "3957902d0fa1c0870ea038f7a4b11e3285138f241eb25ca7461252ffa32302dd",
        );
        assert_identity::<SessionRole>(
            0x0c,
            "0b513ad9b4924015ca0902ed079044d3ac5dbec2306f06948c10da8eb6e39f2d",
            "b8123f51278253aa6f42d45c176c5dbcc28de411185c4c4cf3a37b09be8afacc",
        );
        assert_identity::<TurnReadRole>(
            0x0d,
            "91a28a0b74381593a4d9469579208926afc8ad82c8839b7644359b9eba9a4b3a",
            "5f9b2a2076cbde4a81150c4d8b164b95053f35bcaae5780310a2936590e44672",
        );
        assert_identity::<WebSessionGrantRole>(
            0x0e,
            "0beef5a9e679e6a3e134fe27837bff32c7cb5f5d44ea09bcb0e542bad6a4c0cc",
            "69650566262e58960bc2aa618913468aed27aa5e60d0badb3906935065ba63d6",
        );
        assert_identity::<JournalAttestationRole>(
            0x0f,
            "d9bf2148748a85c89da5aad8ee0b0fc2d105fd39d41a4c796536354f0ae2900c",
            "430dad21c1b44d5872905d82907089116378d6866bb7ac5858c96090d7314435",
        );
    }
}