Skip to main content

personaldb_protocol/
signing.rs

1use crate::{DatabaseId, LogIndex};
2use ed25519_dalek::{
3    Signature as DalekSignature, Signer as _, SigningKey, VerifyingKey, pkcs8::DecodePrivateKey,
4};
5use prost::Message;
6use serde::{
7    Deserialize, Deserializer, Serialize, Serializer,
8    de::{Error as _, SeqAccess, Visitor},
9};
10use sha2::{Digest, Sha256};
11use std::{
12    collections::{BTreeMap, HashSet},
13    fmt,
14    str::FromStr,
15};
16
17pub const SIGNATURE_ENVELOPE_FORMAT_VERSION_V1: u32 = 1;
18pub const PUBLIC_KEY_TRUST_RECORD_FORMAT_VERSION_V1: u32 = 1;
19pub const PUBLIC_KEY_ENVELOPE_FORMAT_VERSION_V1: u32 = 1;
20pub const ED25519_PUBLIC_KEY_LENGTH: usize = 32;
21pub const ED25519_SIGNATURE_LENGTH: usize = 64;
22pub const SHA256_DIGEST_LENGTH: usize = 32;
23
24const SIGNING_PREIMAGE_PREFIX: &[u8] = b"personaldb\0";
25const PUBLIC_KEY_ENVELOPE_V1_NAME: &str = "PublicKeyEnvelopeV1";
26const SIGNATURE_ENVELOPE_V1_NAME: &str = "SignatureEnvelopeV1";
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
29#[serde(rename_all = "kebab-case")]
30#[repr(u16)]
31pub enum HashAlgorithm {
32    Sha256 = 1,
33}
34
35impl HashAlgorithm {
36    pub const fn as_str(self) -> &'static str {
37        match self {
38            Self::Sha256 => "sha256",
39        }
40    }
41}
42
43impl TryFrom<u16> for HashAlgorithm {
44    type Error = SignatureError;
45
46    fn try_from(value: u16) -> Result<Self, Self::Error> {
47        match value {
48            1 => Ok(Self::Sha256),
49            algorithm => Err(SignatureError::UnsupportedHashAlgorithm { algorithm }),
50        }
51    }
52}
53
54impl HashAlgorithm {
55    fn from_protobuf(value: i32) -> Result<Self, SignatureError> {
56        let value =
57            u16::try_from(value).map_err(|_| SignatureError::UnsupportedProtobufEnumValue {
58                enum_name: "HashAlgorithmV1",
59                value,
60            })?;
61        Self::try_from(value)
62    }
63}
64
65impl fmt::Display for HashAlgorithm {
66    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
67        formatter.write_str(self.as_str())
68    }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
72#[serde(rename_all = "kebab-case")]
73#[repr(u16)]
74pub enum SignatureAlgorithm {
75    Ed25519 = 1,
76}
77
78impl SignatureAlgorithm {
79    pub const fn as_str(self) -> &'static str {
80        match self {
81            Self::Ed25519 => "ed25519",
82        }
83    }
84}
85
86impl TryFrom<u16> for SignatureAlgorithm {
87    type Error = SignatureError;
88
89    fn try_from(value: u16) -> Result<Self, Self::Error> {
90        match value {
91            1 => Ok(Self::Ed25519),
92            algorithm => Err(SignatureError::UnsupportedSignatureAlgorithm { algorithm }),
93        }
94    }
95}
96
97impl SignatureAlgorithm {
98    fn from_protobuf(value: i32) -> Result<Self, SignatureError> {
99        let value =
100            u16::try_from(value).map_err(|_| SignatureError::UnsupportedProtobufEnumValue {
101                enum_name: "SignatureAlgorithmV1",
102                value,
103            })?;
104        Self::try_from(value)
105    }
106}
107
108impl fmt::Display for SignatureAlgorithm {
109    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
110        formatter.write_str(self.as_str())
111    }
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
115#[serde(rename_all = "kebab-case")]
116#[repr(u16)]
117pub enum SignaturePurpose {
118    GroupControl = 1,
119    PlacementAuthority = 2,
120    ProposalAdmission = 3,
121    SourceProposer = 4,
122    ProjectionProposer = 5,
123    StandaloneProposer = 6,
124    Voter = 7,
125    ProjectionBuilder = 8,
126    Witness = 9,
127    Snapshot = 10,
128}
129
130impl SignaturePurpose {
131    pub const fn as_str(self) -> &'static str {
132        match self {
133            Self::GroupControl => "group-control",
134            Self::PlacementAuthority => "placement-authority",
135            Self::ProposalAdmission => "proposal-admission",
136            Self::SourceProposer => "source-proposer",
137            Self::ProjectionProposer => "projection-proposer",
138            Self::StandaloneProposer => "standalone-proposer",
139            Self::Voter => "voter",
140            Self::ProjectionBuilder => "projection-builder",
141            Self::Witness => "witness",
142            Self::Snapshot => "snapshot",
143        }
144    }
145
146    pub const fn allows_domain(self, domain: SignatureDomain) -> bool {
147        match self {
148            Self::GroupControl => matches!(
149                domain,
150                SignatureDomain::GroupManifest
151                    | SignatureDomain::GroupPolicyRevision
152                    | SignatureDomain::ProjectionDefinitionAdmission
153            ),
154            Self::PlacementAuthority => matches!(
155                domain,
156                SignatureDomain::PlacementAssignment
157                    | SignatureDomain::RouteRecord
158                    | SignatureDomain::LeaderLease
159                    | SignatureDomain::GroupActivation
160            ),
161            Self::ProposalAdmission => matches!(domain, SignatureDomain::ProposalAdmission),
162            Self::SourceProposer | Self::ProjectionProposer | Self::StandaloneProposer => {
163                matches!(domain, SignatureDomain::ClientProposal)
164            }
165            Self::Voter => matches!(domain, SignatureDomain::VoterAcknowledgement),
166            Self::ProjectionBuilder => matches!(domain, SignatureDomain::ProjectionDerivation),
167            Self::Witness => matches!(
168                domain,
169                SignatureDomain::CommitCertificate | SignatureDomain::CommittedHead
170            ),
171            Self::Snapshot => matches!(
172                domain,
173                SignatureDomain::SnapshotManifest | SignatureDomain::SnapshotsHead
174            ),
175        }
176    }
177}
178
179impl FromStr for SignaturePurpose {
180    type Err = SignatureError;
181
182    fn from_str(value: &str) -> Result<Self, Self::Err> {
183        match value {
184            "group-control" => Ok(Self::GroupControl),
185            "placement-authority" => Ok(Self::PlacementAuthority),
186            "proposal-admission" => Ok(Self::ProposalAdmission),
187            "source-proposer" => Ok(Self::SourceProposer),
188            "projection-proposer" => Ok(Self::ProjectionProposer),
189            "standalone-proposer" => Ok(Self::StandaloneProposer),
190            "voter" => Ok(Self::Voter),
191            "projection-builder" => Ok(Self::ProjectionBuilder),
192            "witness" => Ok(Self::Witness),
193            "snapshot" => Ok(Self::Snapshot),
194            purpose => Err(SignatureError::UnknownSignaturePurpose {
195                purpose: purpose.to_string(),
196            }),
197        }
198    }
199}
200
201impl TryFrom<u16> for SignaturePurpose {
202    type Error = SignatureError;
203
204    fn try_from(value: u16) -> Result<Self, Self::Error> {
205        match value {
206            1 => Ok(Self::GroupControl),
207            2 => Ok(Self::PlacementAuthority),
208            3 => Ok(Self::ProposalAdmission),
209            4 => Ok(Self::SourceProposer),
210            5 => Ok(Self::ProjectionProposer),
211            6 => Ok(Self::StandaloneProposer),
212            7 => Ok(Self::Voter),
213            8 => Ok(Self::ProjectionBuilder),
214            9 => Ok(Self::Witness),
215            10 => Ok(Self::Snapshot),
216            purpose => Err(SignatureError::UnknownSignaturePurpose {
217                purpose: purpose.to_string(),
218            }),
219        }
220    }
221}
222
223impl fmt::Display for SignaturePurpose {
224    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
225        formatter.write_str(self.as_str())
226    }
227}
228
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
230#[serde(rename_all = "kebab-case")]
231#[repr(u16)]
232pub enum SignatureDomain {
233    GroupManifest = 1,
234    GroupPolicyRevision = 2,
235    ProjectionDefinitionAdmission = 3,
236    PlacementAssignment = 4,
237    RouteRecord = 5,
238    LeaderLease = 6,
239    GroupActivation = 7,
240    ProposalAdmission = 8,
241    ClientProposal = 9,
242    VoterAcknowledgement = 10,
243    ProjectionDerivation = 11,
244    CommitCertificate = 12,
245    CommittedHead = 13,
246    SnapshotManifest = 14,
247    SnapshotsHead = 15,
248}
249
250impl SignatureDomain {
251    pub const fn as_str(self) -> &'static str {
252        match self {
253            Self::GroupManifest => "group-manifest",
254            Self::GroupPolicyRevision => "group-policy-revision",
255            Self::ProjectionDefinitionAdmission => "projection-definition-admission",
256            Self::PlacementAssignment => "placement-assignment",
257            Self::RouteRecord => "route-record",
258            Self::LeaderLease => "leader-lease",
259            Self::GroupActivation => "group-activation",
260            Self::ProposalAdmission => "proposal-admission",
261            Self::ClientProposal => "client-proposal",
262            Self::VoterAcknowledgement => "voter-acknowledgement",
263            Self::ProjectionDerivation => "projection-derivation",
264            Self::CommitCertificate => "commit-certificate",
265            Self::CommittedHead => "committed-head",
266            Self::SnapshotManifest => "snapshot-manifest",
267            Self::SnapshotsHead => "snapshots-head",
268        }
269    }
270
271    pub const fn signed_payload_version(self) -> u32 {
272        match self {
273            Self::GroupManifest
274            | Self::GroupPolicyRevision
275            | Self::PlacementAssignment
276            | Self::RouteRecord
277            | Self::LeaderLease
278            | Self::GroupActivation
279            | Self::ClientProposal
280            | Self::VoterAcknowledgement
281            | Self::CommitCertificate
282            | Self::CommittedHead => 2,
283            Self::ProjectionDefinitionAdmission
284            | Self::ProposalAdmission
285            | Self::ProjectionDerivation
286            | Self::SnapshotManifest
287            | Self::SnapshotsHead => 1,
288        }
289    }
290}
291
292impl FromStr for SignatureDomain {
293    type Err = SignatureError;
294
295    fn from_str(value: &str) -> Result<Self, Self::Err> {
296        match value {
297            "group-manifest" => Ok(Self::GroupManifest),
298            "group-policy-revision" => Ok(Self::GroupPolicyRevision),
299            "projection-definition-admission" => Ok(Self::ProjectionDefinitionAdmission),
300            "placement-assignment" => Ok(Self::PlacementAssignment),
301            "route-record" => Ok(Self::RouteRecord),
302            "leader-lease" => Ok(Self::LeaderLease),
303            "group-activation" => Ok(Self::GroupActivation),
304            "proposal-admission" => Ok(Self::ProposalAdmission),
305            "client-proposal" => Ok(Self::ClientProposal),
306            "voter-acknowledgement" => Ok(Self::VoterAcknowledgement),
307            "projection-derivation" => Ok(Self::ProjectionDerivation),
308            "commit-certificate" => Ok(Self::CommitCertificate),
309            "committed-head" => Ok(Self::CommittedHead),
310            "snapshot-manifest" => Ok(Self::SnapshotManifest),
311            "snapshots-head" => Ok(Self::SnapshotsHead),
312            domain => Err(SignatureError::UnknownSignatureDomain {
313                domain: domain.to_string(),
314            }),
315        }
316    }
317}
318
319impl TryFrom<u16> for SignatureDomain {
320    type Error = SignatureError;
321
322    fn try_from(value: u16) -> Result<Self, Self::Error> {
323        match value {
324            1 => Ok(Self::GroupManifest),
325            2 => Ok(Self::GroupPolicyRevision),
326            3 => Ok(Self::ProjectionDefinitionAdmission),
327            4 => Ok(Self::PlacementAssignment),
328            5 => Ok(Self::RouteRecord),
329            6 => Ok(Self::LeaderLease),
330            7 => Ok(Self::GroupActivation),
331            8 => Ok(Self::ProposalAdmission),
332            9 => Ok(Self::ClientProposal),
333            10 => Ok(Self::VoterAcknowledgement),
334            11 => Ok(Self::ProjectionDerivation),
335            12 => Ok(Self::CommitCertificate),
336            13 => Ok(Self::CommittedHead),
337            14 => Ok(Self::SnapshotManifest),
338            15 => Ok(Self::SnapshotsHead),
339            domain => Err(SignatureError::UnknownSignatureDomain {
340                domain: domain.to_string(),
341            }),
342        }
343    }
344}
345
346impl fmt::Display for SignatureDomain {
347    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
348        formatter.write_str(self.as_str())
349    }
350}
351
352#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
353pub struct KeyGeneration(u64);
354
355impl KeyGeneration {
356    pub fn new(value: u64) -> Result<Self, SignatureError> {
357        Self::try_from(value)
358    }
359
360    pub const fn get(self) -> u64 {
361        self.0
362    }
363}
364
365impl TryFrom<u64> for KeyGeneration {
366    type Error = SignatureError;
367
368    fn try_from(value: u64) -> Result<Self, Self::Error> {
369        if value == 0 {
370            Err(SignatureError::InvalidKeyGeneration { generation: value })
371        } else {
372            Ok(Self(value))
373        }
374    }
375}
376
377impl From<KeyGeneration> for u64 {
378    fn from(value: KeyGeneration) -> Self {
379        value.get()
380    }
381}
382
383impl Serialize for KeyGeneration {
384    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
385    where
386        S: Serializer,
387    {
388        serializer.serialize_u64(self.get())
389    }
390}
391
392impl<'de> Deserialize<'de> for KeyGeneration {
393    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
394    where
395        D: Deserializer<'de>,
396    {
397        Self::try_from(u64::deserialize(deserializer)?).map_err(D::Error::custom)
398    }
399}
400
401impl fmt::Display for KeyGeneration {
402    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
403        self.get().fmt(formatter)
404    }
405}
406
407#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
408pub struct KeyId(String);
409
410impl KeyId {
411    pub fn new(value: impl Into<String>) -> Result<Self, SignatureError> {
412        let value = value.into();
413        let digest =
414            value
415                .strip_prefix("sha256:")
416                .ok_or_else(|| SignatureError::MalformedKeyId {
417                    key_id: value.clone(),
418                })?;
419        let is_canonical = digest.len() == 64
420            && digest
421                .bytes()
422                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
423        if !is_canonical {
424            return Err(SignatureError::MalformedKeyId { key_id: value });
425        }
426        Ok(Self(value))
427    }
428
429    pub fn for_ed25519(public_key: &Ed25519PublicKey) -> Self {
430        let digest = Sha256::digest(ed25519_public_key_envelope_v1_bytes(public_key));
431        Self(format!("sha256:{}", hex::encode(digest)))
432    }
433
434    pub fn as_str(&self) -> &str {
435        &self.0
436    }
437}
438
439impl fmt::Display for KeyId {
440    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
441        formatter.write_str(self.as_str())
442    }
443}
444
445impl FromStr for KeyId {
446    type Err = SignatureError;
447
448    fn from_str(value: &str) -> Result<Self, Self::Err> {
449        Self::new(value)
450    }
451}
452
453impl Serialize for KeyId {
454    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
455    where
456        S: Serializer,
457    {
458        serializer.serialize_str(self.as_str())
459    }
460}
461
462impl<'de> Deserialize<'de> for KeyId {
463    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
464    where
465        D: Deserializer<'de>,
466    {
467        Self::new(String::deserialize(deserializer)?).map_err(D::Error::custom)
468    }
469}
470
471#[derive(Clone, Copy, PartialEq, Eq, Hash)]
472pub struct Ed25519PublicKey([u8; ED25519_PUBLIC_KEY_LENGTH]);
473
474impl Ed25519PublicKey {
475    pub fn from_bytes(bytes: [u8; ED25519_PUBLIC_KEY_LENGTH]) -> Result<Self, SignatureError> {
476        let verifying_key =
477            VerifyingKey::from_bytes(&bytes).map_err(|_| SignatureError::MalformedPublicKey)?;
478        if verifying_key.to_edwards().compress().to_bytes() != bytes {
479            return Err(SignatureError::MalformedPublicKey);
480        }
481        if verifying_key.is_weak() {
482            return Err(SignatureError::WeakPublicKey);
483        }
484        Ok(Self(bytes))
485    }
486
487    pub const fn as_bytes(&self) -> &[u8; ED25519_PUBLIC_KEY_LENGTH] {
488        &self.0
489    }
490
491    pub const fn to_bytes(self) -> [u8; ED25519_PUBLIC_KEY_LENGTH] {
492        self.0
493    }
494
495    fn verifying_key(self) -> Result<VerifyingKey, SignatureError> {
496        VerifyingKey::from_bytes(&self.0).map_err(|_| SignatureError::MalformedPublicKey)
497    }
498}
499
500impl fmt::Debug for Ed25519PublicKey {
501    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
502        formatter
503            .debug_tuple("Ed25519PublicKey")
504            .field(&hex::encode(self.0))
505            .finish()
506    }
507}
508
509impl TryFrom<&[u8]> for Ed25519PublicKey {
510    type Error = SignatureError;
511
512    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
513        let bytes: [u8; ED25519_PUBLIC_KEY_LENGTH] =
514            value
515                .try_into()
516                .map_err(|_| SignatureError::MalformedPublicKeyLength {
517                    actual: value.len(),
518                })?;
519        Self::from_bytes(bytes)
520    }
521}
522
523impl Serialize for Ed25519PublicKey {
524    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
525    where
526        S: Serializer,
527    {
528        serializer.serialize_bytes(&self.0)
529    }
530}
531
532impl<'de> Deserialize<'de> for Ed25519PublicKey {
533    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
534    where
535        D: Deserializer<'de>,
536    {
537        let bytes = deserialize_exact_bytes::<D, ED25519_PUBLIC_KEY_LENGTH>(
538            deserializer,
539            "an exact 32-byte Ed25519 public key",
540        )?;
541        Self::from_bytes(bytes).map_err(D::Error::custom)
542    }
543}
544
545#[derive(Clone, Copy, PartialEq, Eq, Hash)]
546pub struct Ed25519Signature([u8; ED25519_SIGNATURE_LENGTH]);
547
548impl Ed25519Signature {
549    pub const fn from_bytes(bytes: [u8; ED25519_SIGNATURE_LENGTH]) -> Self {
550        Self(bytes)
551    }
552
553    pub const fn as_bytes(&self) -> &[u8; ED25519_SIGNATURE_LENGTH] {
554        &self.0
555    }
556
557    pub const fn to_bytes(self) -> [u8; ED25519_SIGNATURE_LENGTH] {
558        self.0
559    }
560}
561
562impl fmt::Debug for Ed25519Signature {
563    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
564        formatter
565            .debug_tuple("Ed25519Signature")
566            .field(&hex::encode(self.0))
567            .finish()
568    }
569}
570
571impl TryFrom<&[u8]> for Ed25519Signature {
572    type Error = SignatureError;
573
574    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
575        let bytes: [u8; ED25519_SIGNATURE_LENGTH] =
576            value
577                .try_into()
578                .map_err(|_| SignatureError::MalformedSignatureLength {
579                    actual: value.len(),
580                })?;
581        Ok(Self(bytes))
582    }
583}
584
585impl Serialize for Ed25519Signature {
586    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
587    where
588        S: Serializer,
589    {
590        serializer.serialize_bytes(&self.0)
591    }
592}
593
594impl<'de> Deserialize<'de> for Ed25519Signature {
595    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
596    where
597        D: Deserializer<'de>,
598    {
599        deserialize_exact_bytes::<D, ED25519_SIGNATURE_LENGTH>(
600            deserializer,
601            "an exact 64-byte Ed25519 signature",
602        )
603        .map(Self)
604    }
605}
606
607#[derive(Clone, Copy, Debug, PartialEq, Eq, prost::Enumeration)]
608#[repr(i32)]
609enum WireHashAlgorithmV1 {
610    Unspecified = 0,
611    Sha256 = 1,
612}
613
614#[derive(Clone, Copy, Debug, PartialEq, Eq, prost::Enumeration)]
615#[repr(i32)]
616enum WireSignatureAlgorithmV1 {
617    Unspecified = 0,
618    Ed25519 = 1,
619}
620
621#[derive(Clone, PartialEq, Message)]
622struct WirePublicKeyEnvelopeV1 {
623    #[prost(uint32, tag = "1")]
624    format_version: u32,
625    #[prost(enumeration = "WireSignatureAlgorithmV1", tag = "2")]
626    signature_algorithm: i32,
627    #[prost(bytes = "vec", tag = "3")]
628    public_key: Vec<u8>,
629}
630
631#[derive(Clone, PartialEq, Message)]
632struct WireSignatureEnvelopeV1 {
633    #[prost(uint32, tag = "1")]
634    format_version: u32,
635    #[prost(enumeration = "WireHashAlgorithmV1", tag = "2")]
636    hash_algorithm: i32,
637    #[prost(enumeration = "WireSignatureAlgorithmV1", tag = "3")]
638    signature_algorithm: i32,
639    #[prost(string, tag = "4")]
640    key_id: String,
641    #[prost(bytes = "vec", tag = "5")]
642    signature: Vec<u8>,
643}
644
645/// Canonical deterministic-protobuf Ed25519 public-key envelope.
646///
647/// This type deliberately does not implement Serde. Use [`Self::encode_deterministic`] and
648/// [`Self::decode_canonical`] for the protocol wire representation.
649#[derive(Debug, Clone, Copy, PartialEq, Eq)]
650pub struct PublicKeyEnvelopeV1 {
651    pub format_version: u32,
652    pub signature_algorithm: SignatureAlgorithm,
653    pub public_key: Ed25519PublicKey,
654}
655
656impl PublicKeyEnvelopeV1 {
657    pub const fn for_ed25519(public_key: Ed25519PublicKey) -> Self {
658        Self {
659            format_version: PUBLIC_KEY_ENVELOPE_FORMAT_VERSION_V1,
660            signature_algorithm: SignatureAlgorithm::Ed25519,
661            public_key,
662        }
663    }
664
665    pub fn validate_shape(&self) -> Result<(), SignatureError> {
666        if self.format_version != PUBLIC_KEY_ENVELOPE_FORMAT_VERSION_V1 {
667            return Err(SignatureError::UnsupportedPublicKeyEnvelopeVersion {
668                version: self.format_version,
669            });
670        }
671        Ok(())
672    }
673
674    pub fn encode_deterministic(&self) -> Result<Vec<u8>, SignatureError> {
675        self.validate_shape()?;
676        Ok(WirePublicKeyEnvelopeV1 {
677            format_version: self.format_version,
678            signature_algorithm: self.signature_algorithm as i32,
679            public_key: self.public_key.as_bytes().to_vec(),
680        }
681        .encode_to_vec())
682    }
683
684    pub fn decode_canonical(encoded: &[u8]) -> Result<Self, SignatureError> {
685        let wire = WirePublicKeyEnvelopeV1::decode(encoded).map_err(|_| {
686            SignatureError::MalformedProtobuf {
687                message_type: PUBLIC_KEY_ENVELOPE_V1_NAME,
688            }
689        })?;
690        let envelope = Self {
691            format_version: wire.format_version,
692            signature_algorithm: SignatureAlgorithm::from_protobuf(wire.signature_algorithm)?,
693            public_key: Ed25519PublicKey::try_from(wire.public_key.as_slice())?,
694        };
695        envelope.validate_shape()?;
696        if envelope.encode_deterministic()?.as_slice() != encoded {
697            return Err(SignatureError::NonCanonicalProtobuf {
698                message_type: PUBLIC_KEY_ENVELOPE_V1_NAME,
699            });
700        }
701        Ok(envelope)
702    }
703}
704
705impl TryFrom<&[u8]> for PublicKeyEnvelopeV1 {
706    type Error = SignatureError;
707
708    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
709        Self::decode_canonical(value)
710    }
711}
712
713pub fn ed25519_public_key_envelope_v1_bytes(
714    public_key: &Ed25519PublicKey,
715) -> [u8; 6 + ED25519_PUBLIC_KEY_LENGTH] {
716    PublicKeyEnvelopeV1::for_ed25519(*public_key)
717        .encode_deterministic()
718        .expect("built-in Ed25519 public-key envelope must be valid")
719        .try_into()
720        .expect("Ed25519 public-key envelope V1 has a fixed encoded length")
721}
722
723#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
724#[serde(rename_all = "snake_case")]
725pub enum PublicKeyStatus {
726    Active,
727    Retiring,
728    RevokedFuture,
729    Compromised,
730}
731
732impl PublicKeyStatus {
733    pub const fn as_str(self) -> &'static str {
734        match self {
735            Self::Active => "active",
736            Self::Retiring => "retiring",
737            Self::RevokedFuture => "revoked_future",
738            Self::Compromised => "compromised",
739        }
740    }
741}
742
743impl fmt::Display for PublicKeyStatus {
744    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
745        formatter.write_str(self.as_str())
746    }
747}
748
749#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
750#[serde(deny_unknown_fields)]
751pub struct SignatureScope {
752    pub database_id: Option<DatabaseId>,
753    pub group_id: Option<String>,
754}
755
756impl SignatureScope {
757    pub fn for_database(database_id: DatabaseId) -> Self {
758        Self {
759            database_id: Some(database_id),
760            group_id: None,
761        }
762    }
763
764    pub fn for_group(group_id: impl Into<String>) -> Self {
765        Self {
766            database_id: None,
767            group_id: Some(group_id.into()),
768        }
769    }
770
771    pub fn for_database_group(database_id: DatabaseId, group_id: impl Into<String>) -> Self {
772        Self {
773            database_id: Some(database_id),
774            group_id: Some(group_id.into()),
775        }
776    }
777
778    fn validate(&self) -> Result<(), SignatureError> {
779        if self
780            .database_id
781            .as_ref()
782            .is_some_and(|database_id| !valid_scope_value(&database_id.0))
783        {
784            return Err(SignatureError::InvalidDatabaseScope);
785        }
786        if self
787            .group_id
788            .as_ref()
789            .is_some_and(|group_id| !valid_scope_value(group_id))
790        {
791            return Err(SignatureError::InvalidGroupScope);
792        }
793        Ok(())
794    }
795}
796
797#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
798#[serde(deny_unknown_fields)]
799pub struct KeyTrustPolicy {
800    pub key_generation: KeyGeneration,
801    pub purpose: SignaturePurpose,
802    pub database_scopes: Vec<DatabaseId>,
803    pub group_scopes: Vec<String>,
804    pub valid_from_log_index: LogIndex,
805    /// Exclusive upper boundary. A key is not authoritative at this index.
806    pub valid_until_log_index: Option<LogIndex>,
807    pub status: PublicKeyStatus,
808}
809
810impl KeyTrustPolicy {
811    pub fn new(
812        key_generation: KeyGeneration,
813        purpose: SignaturePurpose,
814        valid_from_log_index: LogIndex,
815    ) -> Self {
816        Self {
817            key_generation,
818            purpose,
819            database_scopes: Vec::new(),
820            group_scopes: Vec::new(),
821            valid_from_log_index,
822            valid_until_log_index: None,
823            status: PublicKeyStatus::Active,
824        }
825    }
826
827    pub fn with_database_scopes(mut self, database_scopes: Vec<DatabaseId>) -> Self {
828        self.database_scopes = database_scopes;
829        self
830    }
831
832    pub fn with_group_scopes(mut self, group_scopes: Vec<String>) -> Self {
833        self.group_scopes = group_scopes;
834        self
835    }
836
837    pub fn with_valid_until(mut self, valid_until_log_index: LogIndex) -> Self {
838        self.valid_until_log_index = Some(valid_until_log_index);
839        self
840    }
841
842    pub fn with_status(mut self, status: PublicKeyStatus) -> Self {
843        self.status = status;
844        self
845    }
846
847    pub fn validate(&self) -> Result<(), SignatureError> {
848        if self
849            .valid_until_log_index
850            .is_some_and(|until| until <= self.valid_from_log_index)
851        {
852            return Err(SignatureError::InvalidValidityRange {
853                valid_from: self.valid_from_log_index,
854                valid_until: self.valid_until_log_index,
855            });
856        }
857        if self.status != PublicKeyStatus::Active && self.valid_until_log_index.is_none() {
858            return Err(SignatureError::MissingStatusBoundary {
859                status: self.status,
860            });
861        }
862        validate_scopes(&self.database_scopes, &self.group_scopes)
863    }
864}
865
866#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
867#[serde(deny_unknown_fields)]
868pub struct PublicKeyTrustRecord {
869    pub format_version: u32,
870    pub signature_algorithm: SignatureAlgorithm,
871    pub key_id: KeyId,
872    pub key_generation: KeyGeneration,
873    pub public_key: Ed25519PublicKey,
874    pub purpose: SignaturePurpose,
875    pub database_scopes: Vec<DatabaseId>,
876    pub group_scopes: Vec<String>,
877    pub valid_from_log_index: LogIndex,
878    /// Exclusive upper boundary. Historical signatures below it remain valid.
879    pub valid_until_log_index: Option<LogIndex>,
880    pub status: PublicKeyStatus,
881}
882
883impl PublicKeyTrustRecord {
884    pub fn new(public_key: Ed25519PublicKey, policy: KeyTrustPolicy) -> Self {
885        Self {
886            format_version: PUBLIC_KEY_TRUST_RECORD_FORMAT_VERSION_V1,
887            signature_algorithm: SignatureAlgorithm::Ed25519,
888            key_id: KeyId::for_ed25519(&public_key),
889            key_generation: policy.key_generation,
890            public_key,
891            purpose: policy.purpose,
892            database_scopes: policy.database_scopes,
893            group_scopes: policy.group_scopes,
894            valid_from_log_index: policy.valid_from_log_index,
895            valid_until_log_index: policy.valid_until_log_index,
896            status: policy.status,
897        }
898    }
899
900    pub fn validate(&self) -> Result<(), SignatureError> {
901        if self.format_version != PUBLIC_KEY_TRUST_RECORD_FORMAT_VERSION_V1 {
902            return Err(SignatureError::UnsupportedTrustRecordVersion {
903                version: self.format_version,
904            });
905        }
906        let derived_key_id = KeyId::for_ed25519(&self.public_key);
907        if self.key_id != derived_key_id {
908            return Err(SignatureError::KeyIdMismatch {
909                declared: self.key_id.clone(),
910                derived: derived_key_id,
911            });
912        }
913        KeyTrustPolicy {
914            key_generation: self.key_generation,
915            purpose: self.purpose,
916            database_scopes: self.database_scopes.clone(),
917            group_scopes: self.group_scopes.clone(),
918            valid_from_log_index: self.valid_from_log_index,
919            valid_until_log_index: self.valid_until_log_index,
920            status: self.status,
921        }
922        .validate()
923    }
924
925    fn authorize(&self, metadata: &SignatureMetadata) -> Result<(), SignatureError> {
926        self.validate()?;
927        if self.purpose != metadata.purpose {
928            return Err(SignatureError::PurposeMismatch {
929                expected: self.purpose,
930                actual: metadata.purpose,
931            });
932        }
933        if !self.purpose.allows_domain(metadata.domain) {
934            return Err(SignatureError::PurposeNotAllowedForDomain {
935                purpose: self.purpose,
936                domain: metadata.domain,
937            });
938        }
939        if let Some(required_generation) = metadata.required_key_generation
940            && self.key_generation != required_generation
941        {
942            return Err(SignatureError::RequiredKeyGenerationMismatch {
943                required: required_generation,
944                actual: self.key_generation,
945            });
946        }
947        self.validate_scope(&metadata.scope)?;
948        self.validate_log_boundary(metadata.log_index)
949    }
950
951    fn validate_scope(&self, scope: &SignatureScope) -> Result<(), SignatureError> {
952        scope.validate()?;
953        if !self.database_scopes.is_empty() {
954            let database_id =
955                scope
956                    .database_id
957                    .as_ref()
958                    .ok_or_else(|| SignatureError::MissingDatabaseScope {
959                        key_id: self.key_id.clone(),
960                    })?;
961            if !self
962                .database_scopes
963                .iter()
964                .any(|allowed| allowed == database_id)
965            {
966                return Err(SignatureError::DatabaseScopeMismatch {
967                    key_id: self.key_id.clone(),
968                    database_id: database_id.clone(),
969                });
970            }
971        }
972        if !self.group_scopes.is_empty() {
973            let group_id =
974                scope
975                    .group_id
976                    .as_ref()
977                    .ok_or_else(|| SignatureError::MissingGroupScope {
978                        key_id: self.key_id.clone(),
979                    })?;
980            if !self.group_scopes.iter().any(|allowed| allowed == group_id) {
981                return Err(SignatureError::GroupScopeMismatch {
982                    key_id: self.key_id.clone(),
983                    group_id: group_id.clone(),
984                });
985            }
986        }
987        Ok(())
988    }
989
990    fn validate_log_boundary(&self, log_index: LogIndex) -> Result<(), SignatureError> {
991        if log_index < self.valid_from_log_index {
992            return Err(SignatureError::KeyNotYetValid {
993                key_id: self.key_id.clone(),
994                log_index,
995                valid_from: self.valid_from_log_index,
996            });
997        }
998        let Some(valid_until) = self.valid_until_log_index else {
999            return Ok(());
1000        };
1001        if log_index < valid_until {
1002            return Ok(());
1003        }
1004        match self.status {
1005            PublicKeyStatus::Active => Err(SignatureError::KeyExpired {
1006                key_id: self.key_id.clone(),
1007                log_index,
1008                valid_until,
1009            }),
1010            PublicKeyStatus::Retiring => Err(SignatureError::KeyRetired {
1011                key_id: self.key_id.clone(),
1012                log_index,
1013                valid_until,
1014            }),
1015            PublicKeyStatus::RevokedFuture => Err(SignatureError::KeyRevoked {
1016                key_id: self.key_id.clone(),
1017                log_index,
1018                valid_until,
1019            }),
1020            PublicKeyStatus::Compromised => Err(SignatureError::KeyCompromised {
1021                key_id: self.key_id.clone(),
1022                log_index,
1023                valid_until,
1024            }),
1025        }
1026    }
1027}
1028
1029/// Canonical deterministic-protobuf signature envelope.
1030///
1031/// Purpose, domain, signed-payload version, key generation, scope, and log boundary are not wire
1032/// fields. They are derived from the typed [`ProtocolSignable`] and its trusted key record.
1033/// This type deliberately does not implement Serde; protocol bytes must pass canonical protobuf
1034/// decoding through [`Self::decode_canonical`].
1035#[derive(Debug, Clone, PartialEq, Eq)]
1036pub struct SignatureEnvelopeV1 {
1037    pub format_version: u32,
1038    pub hash_algorithm: HashAlgorithm,
1039    pub signature_algorithm: SignatureAlgorithm,
1040    pub key_id: KeyId,
1041    pub signature: Ed25519Signature,
1042}
1043
1044impl SignatureEnvelopeV1 {
1045    pub fn for_ed25519(key_id: KeyId, signature: Ed25519Signature) -> Self {
1046        Self {
1047            format_version: SIGNATURE_ENVELOPE_FORMAT_VERSION_V1,
1048            hash_algorithm: HashAlgorithm::Sha256,
1049            signature_algorithm: SignatureAlgorithm::Ed25519,
1050            key_id,
1051            signature,
1052        }
1053    }
1054
1055    pub fn validate_shape(&self) -> Result<(), SignatureError> {
1056        if self.format_version != SIGNATURE_ENVELOPE_FORMAT_VERSION_V1 {
1057            return Err(SignatureError::UnsupportedEnvelopeVersion {
1058                version: self.format_version,
1059            });
1060        }
1061        Ok(())
1062    }
1063
1064    pub fn encode_deterministic(&self) -> Result<Vec<u8>, SignatureError> {
1065        self.validate_shape()?;
1066        Ok(WireSignatureEnvelopeV1 {
1067            format_version: self.format_version,
1068            hash_algorithm: self.hash_algorithm as i32,
1069            signature_algorithm: self.signature_algorithm as i32,
1070            key_id: self.key_id.as_str().to_owned(),
1071            signature: self.signature.as_bytes().to_vec(),
1072        }
1073        .encode_to_vec())
1074    }
1075
1076    pub fn decode_canonical(encoded: &[u8]) -> Result<Self, SignatureError> {
1077        let wire = WireSignatureEnvelopeV1::decode(encoded).map_err(|_| {
1078            SignatureError::MalformedProtobuf {
1079                message_type: SIGNATURE_ENVELOPE_V1_NAME,
1080            }
1081        })?;
1082        let envelope = Self {
1083            format_version: wire.format_version,
1084            hash_algorithm: HashAlgorithm::from_protobuf(wire.hash_algorithm)?,
1085            signature_algorithm: SignatureAlgorithm::from_protobuf(wire.signature_algorithm)?,
1086            key_id: KeyId::new(wire.key_id)?,
1087            signature: Ed25519Signature::try_from(wire.signature.as_slice())?,
1088        };
1089        envelope.validate_shape()?;
1090        if envelope.encode_deterministic()?.as_slice() != encoded {
1091            return Err(SignatureError::NonCanonicalProtobuf {
1092                message_type: SIGNATURE_ENVELOPE_V1_NAME,
1093            });
1094        }
1095        Ok(envelope)
1096    }
1097}
1098
1099impl TryFrom<&[u8]> for SignatureEnvelopeV1 {
1100    type Error = SignatureError;
1101
1102    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
1103        Self::decode_canonical(value)
1104    }
1105}
1106
1107#[derive(Debug, Clone, PartialEq, Eq)]
1108pub struct SignatureMetadata {
1109    pub purpose: SignaturePurpose,
1110    pub domain: SignatureDomain,
1111    pub signed_payload_version: u32,
1112    pub scope: SignatureScope,
1113    pub log_index: LogIndex,
1114    pub required_key_generation: Option<KeyGeneration>,
1115}
1116
1117impl SignatureMetadata {
1118    pub fn for_domain(
1119        purpose: SignaturePurpose,
1120        domain: SignatureDomain,
1121        log_index: LogIndex,
1122    ) -> Self {
1123        Self {
1124            purpose,
1125            domain,
1126            signed_payload_version: domain.signed_payload_version(),
1127            scope: SignatureScope::default(),
1128            log_index,
1129            required_key_generation: None,
1130        }
1131    }
1132
1133    pub fn with_scope(mut self, scope: SignatureScope) -> Self {
1134        self.scope = scope;
1135        self
1136    }
1137
1138    pub fn requiring_key_generation(mut self, key_generation: KeyGeneration) -> Self {
1139        self.required_key_generation = Some(key_generation);
1140        self
1141    }
1142
1143    fn validate(&self) -> Result<(), SignatureError> {
1144        if !self.purpose.allows_domain(self.domain) {
1145            return Err(SignatureError::PurposeNotAllowedForDomain {
1146                purpose: self.purpose,
1147                domain: self.domain,
1148            });
1149        }
1150        validate_signed_payload_version(self.domain, self.signed_payload_version)?;
1151        self.scope.validate()
1152    }
1153}
1154
1155#[derive(Debug, Clone, Copy)]
1156pub enum SigningPayload<'a> {
1157    ExactBytes(&'a [u8]),
1158    Sha256Digest([u8; SHA256_DIGEST_LENGTH]),
1159}
1160
1161impl SigningPayload<'_> {
1162    fn sha256(self) -> [u8; SHA256_DIGEST_LENGTH] {
1163        match self {
1164            Self::ExactBytes(bytes) => Sha256::digest(bytes).into(),
1165            Self::Sha256Digest(digest) => digest,
1166        }
1167    }
1168}
1169
1170#[derive(Clone, PartialEq, Eq)]
1171pub struct SigningPreimage {
1172    bytes: Vec<u8>,
1173    payload_sha256: [u8; SHA256_DIGEST_LENGTH],
1174}
1175
1176impl SigningPreimage {
1177    pub fn as_bytes(&self) -> &[u8] {
1178        &self.bytes
1179    }
1180
1181    pub const fn payload_sha256(&self) -> &[u8; SHA256_DIGEST_LENGTH] {
1182        &self.payload_sha256
1183    }
1184}
1185
1186impl fmt::Debug for SigningPreimage {
1187    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1188        formatter
1189            .debug_struct("SigningPreimage")
1190            .field("bytes", &hex::encode(&self.bytes))
1191            .field("payload_sha256", &hex::encode(self.payload_sha256))
1192            .finish()
1193    }
1194}
1195
1196impl AsRef<[u8]> for SigningPreimage {
1197    fn as_ref(&self) -> &[u8] {
1198        self.as_bytes()
1199    }
1200}
1201
1202/// Builds the sole PersonalDB signing preimage from canonical bytes or their exact SHA-256.
1203pub fn signing_preimage(
1204    domain: SignatureDomain,
1205    signed_payload_version: u32,
1206    payload: SigningPayload<'_>,
1207) -> Result<SigningPreimage, SignatureError> {
1208    validate_signed_payload_version(domain, signed_payload_version)?;
1209    let payload_sha256 = payload.sha256();
1210    let domain = domain.as_str().as_bytes();
1211    let mut bytes = Vec::with_capacity(
1212        SIGNING_PREIMAGE_PREFIX.len() + domain.len() + 1 + size_of::<u32>() + payload_sha256.len(),
1213    );
1214    bytes.extend_from_slice(SIGNING_PREIMAGE_PREFIX);
1215    bytes.extend_from_slice(domain);
1216    bytes.push(0);
1217    bytes.extend_from_slice(&signed_payload_version.to_be_bytes());
1218    bytes.extend_from_slice(&payload_sha256);
1219    Ok(SigningPreimage {
1220        bytes,
1221        payload_sha256,
1222    })
1223}
1224
1225/// Implement this on typed canonical protocol objects, never on an arbitrary-byte RPC request.
1226///
1227/// Metadata and bytes must come from the same immutable object. Any scope, generation, and log
1228/// boundary used for authorization must also be bound by that object's canonical bytes.
1229pub trait ProtocolSignable {
1230    fn signature_metadata(&self) -> SignatureMetadata;
1231    fn signing_payload(&self) -> SigningPayload<'_>;
1232}
1233
1234pub trait ProtocolSigner: Send + Sync {
1235    fn trust_record(&self) -> &PublicKeyTrustRecord;
1236
1237    fn sign(&self, signable: &dyn ProtocolSignable) -> Result<SignatureEnvelopeV1, SignatureError>;
1238}
1239
1240pub struct Ed25519ProtocolSigner {
1241    signing_key: SigningKey,
1242    trust_record: PublicKeyTrustRecord,
1243}
1244
1245impl Ed25519ProtocolSigner {
1246    pub fn from_pkcs8_der(
1247        private_key_der: &[u8],
1248        policy: KeyTrustPolicy,
1249    ) -> Result<Self, SignatureError> {
1250        let signing_key = SigningKey::from_pkcs8_der(private_key_der)
1251            .map_err(|_| SignatureError::MalformedPrivateKey)?;
1252        Self::from_signing_key(signing_key, policy)
1253    }
1254
1255    pub fn from_pkcs8_pem(
1256        private_key_pem: &str,
1257        policy: KeyTrustPolicy,
1258    ) -> Result<Self, SignatureError> {
1259        let signing_key = SigningKey::from_pkcs8_pem(private_key_pem)
1260            .map_err(|_| SignatureError::MalformedPrivateKey)?;
1261        Self::from_signing_key(signing_key, policy)
1262    }
1263
1264    pub fn from_pkcs8_der_with_trust_record(
1265        private_key_der: &[u8],
1266        trust_record: PublicKeyTrustRecord,
1267    ) -> Result<Self, SignatureError> {
1268        let signing_key = SigningKey::from_pkcs8_der(private_key_der)
1269            .map_err(|_| SignatureError::MalformedPrivateKey)?;
1270        Self::from_signing_key_with_trust_record(signing_key, trust_record)
1271    }
1272
1273    pub fn from_pkcs8_pem_with_trust_record(
1274        private_key_pem: &str,
1275        trust_record: PublicKeyTrustRecord,
1276    ) -> Result<Self, SignatureError> {
1277        let signing_key = SigningKey::from_pkcs8_pem(private_key_pem)
1278            .map_err(|_| SignatureError::MalformedPrivateKey)?;
1279        Self::from_signing_key_with_trust_record(signing_key, trust_record)
1280    }
1281
1282    fn from_signing_key(
1283        signing_key: SigningKey,
1284        policy: KeyTrustPolicy,
1285    ) -> Result<Self, SignatureError> {
1286        policy.validate()?;
1287        let public_key = Ed25519PublicKey::from_bytes(signing_key.verifying_key().to_bytes())?;
1288        let trust_record = PublicKeyTrustRecord::new(public_key, policy);
1289        Self::from_signing_key_with_trust_record(signing_key, trust_record)
1290    }
1291
1292    fn from_signing_key_with_trust_record(
1293        signing_key: SigningKey,
1294        trust_record: PublicKeyTrustRecord,
1295    ) -> Result<Self, SignatureError> {
1296        trust_record.validate()?;
1297        if signing_key.verifying_key().to_bytes() != trust_record.public_key.to_bytes() {
1298            return Err(SignatureError::SigningKeyDoesNotMatchTrustRecord);
1299        }
1300        Ok(Self {
1301            signing_key,
1302            trust_record,
1303        })
1304    }
1305}
1306
1307impl fmt::Debug for Ed25519ProtocolSigner {
1308    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1309        formatter
1310            .debug_struct("Ed25519ProtocolSigner")
1311            .field("trust_record", &self.trust_record)
1312            .finish_non_exhaustive()
1313    }
1314}
1315
1316impl ProtocolSigner for Ed25519ProtocolSigner {
1317    fn trust_record(&self) -> &PublicKeyTrustRecord {
1318        &self.trust_record
1319    }
1320
1321    fn sign(&self, signable: &dyn ProtocolSignable) -> Result<SignatureEnvelopeV1, SignatureError> {
1322        let metadata = signable.signature_metadata();
1323        metadata.validate()?;
1324        if self.trust_record.status == PublicKeyStatus::Compromised {
1325            return Err(SignatureError::KeyNotUsableForSigning {
1326                key_id: self.trust_record.key_id.clone(),
1327                status: self.trust_record.status,
1328            });
1329        }
1330        self.trust_record.authorize(&metadata)?;
1331        let preimage = signing_preimage(
1332            metadata.domain,
1333            metadata.signed_payload_version,
1334            signable.signing_payload(),
1335        )?;
1336        let signature: DalekSignature = self.signing_key.sign(preimage.as_bytes());
1337        Ok(SignatureEnvelopeV1::for_ed25519(
1338            self.trust_record.key_id.clone(),
1339            Ed25519Signature::from_bytes(signature.to_bytes()),
1340        ))
1341    }
1342}
1343
1344#[derive(Debug, Clone, PartialEq, Eq)]
1345pub struct VerifiedSignature {
1346    pub key_id: KeyId,
1347    pub key_generation: KeyGeneration,
1348    pub purpose: SignaturePurpose,
1349    pub domain: SignatureDomain,
1350    pub signed_payload_version: u32,
1351    pub log_index: LogIndex,
1352}
1353
1354pub trait ProtocolSignatureVerifier {
1355    fn verify_signature(
1356        &self,
1357        signable: &dyn ProtocolSignable,
1358        envelope: &SignatureEnvelopeV1,
1359    ) -> Result<VerifiedSignature, SignatureError>;
1360}
1361
1362#[derive(Debug, Clone, Default)]
1363pub struct PublicKeyTrustStore {
1364    records: BTreeMap<KeyId, PublicKeyTrustRecord>,
1365}
1366
1367impl PublicKeyTrustStore {
1368    pub fn new() -> Self {
1369        Self::default()
1370    }
1371
1372    pub fn from_records(
1373        records: impl IntoIterator<Item = PublicKeyTrustRecord>,
1374    ) -> Result<Self, SignatureError> {
1375        let mut store = Self::new();
1376        for record in records {
1377            store.insert(record)?;
1378        }
1379        Ok(store)
1380    }
1381
1382    pub fn insert(&mut self, record: PublicKeyTrustRecord) -> Result<(), SignatureError> {
1383        record.validate()?;
1384        if self.records.contains_key(&record.key_id) {
1385            return Err(SignatureError::DuplicateKeyId {
1386                key_id: record.key_id,
1387            });
1388        }
1389        self.records.insert(record.key_id.clone(), record);
1390        Ok(())
1391    }
1392
1393    pub fn get(&self, key_id: &KeyId) -> Option<&PublicKeyTrustRecord> {
1394        self.records.get(key_id)
1395    }
1396
1397    pub fn len(&self) -> usize {
1398        self.records.len()
1399    }
1400
1401    pub fn is_empty(&self) -> bool {
1402        self.records.is_empty()
1403    }
1404
1405    pub fn verify(
1406        &self,
1407        signable: &dyn ProtocolSignable,
1408        envelope: &SignatureEnvelopeV1,
1409    ) -> Result<VerifiedSignature, SignatureError> {
1410        envelope.validate_shape()?;
1411        let metadata = signable.signature_metadata();
1412        metadata.validate()?;
1413        let record =
1414            self.records
1415                .get(&envelope.key_id)
1416                .ok_or_else(|| SignatureError::UnknownKeyId {
1417                    key_id: envelope.key_id.clone(),
1418                })?;
1419        if envelope.signature_algorithm != record.signature_algorithm {
1420            return Err(SignatureError::SignatureAlgorithmMismatch {
1421                expected: record.signature_algorithm,
1422                actual: envelope.signature_algorithm,
1423            });
1424        }
1425        record.authorize(&metadata)?;
1426        let preimage = signing_preimage(
1427            metadata.domain,
1428            metadata.signed_payload_version,
1429            signable.signing_payload(),
1430        )?;
1431        let signature = DalekSignature::from_bytes(envelope.signature.as_bytes());
1432        record
1433            .public_key
1434            .verifying_key()?
1435            .verify_strict(preimage.as_bytes(), &signature)
1436            .map_err(|_| SignatureError::InvalidSignature)?;
1437        Ok(VerifiedSignature {
1438            key_id: envelope.key_id.clone(),
1439            key_generation: record.key_generation,
1440            purpose: metadata.purpose,
1441            domain: metadata.domain,
1442            signed_payload_version: metadata.signed_payload_version,
1443            log_index: metadata.log_index,
1444        })
1445    }
1446}
1447
1448impl ProtocolSignatureVerifier for PublicKeyTrustStore {
1449    fn verify_signature(
1450        &self,
1451        signable: &dyn ProtocolSignable,
1452        envelope: &SignatureEnvelopeV1,
1453    ) -> Result<VerifiedSignature, SignatureError> {
1454        self.verify(signable, envelope)
1455    }
1456}
1457
1458#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1459pub enum SignatureError {
1460    #[error("unsupported signature envelope version {version}")]
1461    UnsupportedEnvelopeVersion { version: u32 },
1462    #[error("unsupported public-key envelope version {version}")]
1463    UnsupportedPublicKeyEnvelopeVersion { version: u32 },
1464    #[error("unsupported public-key trust record version {version}")]
1465    UnsupportedTrustRecordVersion { version: u32 },
1466    #[error("unsupported hash algorithm value {algorithm}")]
1467    UnsupportedHashAlgorithm { algorithm: u16 },
1468    #[error("unsupported signature algorithm value {algorithm}")]
1469    UnsupportedSignatureAlgorithm { algorithm: u16 },
1470    #[error("unsupported protobuf enum value {value} for {enum_name}")]
1471    UnsupportedProtobufEnumValue { enum_name: &'static str, value: i32 },
1472    #[error("malformed protobuf bytes for {message_type}")]
1473    MalformedProtobuf { message_type: &'static str },
1474    #[error("non-canonical protobuf bytes for {message_type}")]
1475    NonCanonicalProtobuf { message_type: &'static str },
1476    #[error("unknown signature purpose {purpose}")]
1477    UnknownSignaturePurpose { purpose: String },
1478    #[error("unknown signature domain {domain}")]
1479    UnknownSignatureDomain { domain: String },
1480    #[error(
1481        "unsupported signed payload version {actual} for {domain}; expected exactly {expected}"
1482    )]
1483    UnsupportedSignedPayloadVersion {
1484        domain: SignatureDomain,
1485        actual: u32,
1486        expected: u32,
1487    },
1488    #[error("invalid key generation {generation}; generations start at 1")]
1489    InvalidKeyGeneration { generation: u64 },
1490    #[error("malformed key ID {key_id}; expected lowercase sha256:<64 hex>")]
1491    MalformedKeyId { key_id: String },
1492    #[error("malformed Ed25519 public key length {actual}; expected 32 bytes")]
1493    MalformedPublicKeyLength { actual: usize },
1494    #[error("malformed Ed25519 public key")]
1495    MalformedPublicKey,
1496    #[error("weak Ed25519 public keys are not admitted")]
1497    WeakPublicKey,
1498    #[error("malformed Ed25519 signature length {actual}; expected 64 bytes")]
1499    MalformedSignatureLength { actual: usize },
1500    #[error("malformed PKCS#8 Ed25519 private key")]
1501    MalformedPrivateKey,
1502    #[error("the PKCS#8 signing key does not match the public-key trust record")]
1503    SigningKeyDoesNotMatchTrustRecord,
1504    #[error("key ID mismatch: trust record declares {declared}, derived ID is {derived}")]
1505    KeyIdMismatch { declared: KeyId, derived: KeyId },
1506    #[error("duplicate trust record for key ID {key_id}")]
1507    DuplicateKeyId { key_id: KeyId },
1508    #[error("invalid key validity range {valid_from}..{valid_until:?}")]
1509    InvalidValidityRange {
1510        valid_from: LogIndex,
1511        valid_until: Option<LogIndex>,
1512    },
1513    #[error("{status} keys require an exclusive valid-until log boundary")]
1514    MissingStatusBoundary { status: PublicKeyStatus },
1515    #[error("database scopes must be non-empty and contain no NUL")]
1516    InvalidDatabaseScope,
1517    #[error("group scopes must be non-empty and contain no NUL")]
1518    InvalidGroupScope,
1519    #[error("duplicate database scope {database_id}")]
1520    DuplicateDatabaseScope { database_id: DatabaseId },
1521    #[error("duplicate group scope {group_id}")]
1522    DuplicateGroupScope { group_id: String },
1523    #[error("signature purpose {purpose} is not admitted for domain {domain}")]
1524    PurposeNotAllowedForDomain {
1525        purpose: SignaturePurpose,
1526        domain: SignatureDomain,
1527    },
1528    #[error("unknown signing key ID {key_id}")]
1529    UnknownKeyId { key_id: KeyId },
1530    #[error("signature algorithm mismatch: expected {expected}, got {actual}")]
1531    SignatureAlgorithmMismatch {
1532        expected: SignatureAlgorithm,
1533        actual: SignatureAlgorithm,
1534    },
1535    #[error("key generation mismatch: expected {expected}, got {actual}")]
1536    KeyGenerationMismatch {
1537        expected: KeyGeneration,
1538        actual: KeyGeneration,
1539    },
1540    #[error("required key generation {required}, signer has generation {actual}")]
1541    RequiredKeyGenerationMismatch {
1542        required: KeyGeneration,
1543        actual: KeyGeneration,
1544    },
1545    #[error("signature purpose mismatch: expected {expected}, got {actual}")]
1546    PurposeMismatch {
1547        expected: SignaturePurpose,
1548        actual: SignaturePurpose,
1549    },
1550    #[error("signature domain mismatch: expected {expected}, got {actual}")]
1551    DomainMismatch {
1552        expected: SignatureDomain,
1553        actual: SignatureDomain,
1554    },
1555    #[error("signed payload version mismatch: expected {expected}, got {actual}")]
1556    SignedPayloadVersionMismatch { expected: u32, actual: u32 },
1557    #[error("verification for scoped key {key_id} omitted the database scope")]
1558    MissingDatabaseScope { key_id: KeyId },
1559    #[error("key {key_id} is not trusted for database {database_id}")]
1560    DatabaseScopeMismatch {
1561        key_id: KeyId,
1562        database_id: DatabaseId,
1563    },
1564    #[error("verification for scoped key {key_id} omitted the group scope")]
1565    MissingGroupScope { key_id: KeyId },
1566    #[error("key {key_id} is not trusted for group {group_id}")]
1567    GroupScopeMismatch { key_id: KeyId, group_id: String },
1568    #[error("key {key_id} is not valid at log {log_index}; valid from {valid_from}")]
1569    KeyNotYetValid {
1570        key_id: KeyId,
1571        log_index: LogIndex,
1572        valid_from: LogIndex,
1573    },
1574    #[error("key {key_id} expired before log {valid_until}; requested log {log_index}")]
1575    KeyExpired {
1576        key_id: KeyId,
1577        log_index: LogIndex,
1578        valid_until: LogIndex,
1579    },
1580    #[error("key {key_id} retired before log {valid_until}; requested log {log_index}")]
1581    KeyRetired {
1582        key_id: KeyId,
1583        log_index: LogIndex,
1584        valid_until: LogIndex,
1585    },
1586    #[error("key {key_id} was revoked before log {valid_until}; requested log {log_index}")]
1587    KeyRevoked {
1588        key_id: KeyId,
1589        log_index: LogIndex,
1590        valid_until: LogIndex,
1591    },
1592    #[error("key {key_id} was compromised before log {valid_until}; requested log {log_index}")]
1593    KeyCompromised {
1594        key_id: KeyId,
1595        log_index: LogIndex,
1596        valid_until: LogIndex,
1597    },
1598    #[error("key {key_id} has status {status} and cannot produce new signatures")]
1599    KeyNotUsableForSigning {
1600        key_id: KeyId,
1601        status: PublicKeyStatus,
1602    },
1603    #[error("invalid Ed25519 signature")]
1604    InvalidSignature,
1605}
1606
1607fn validate_signed_payload_version(
1608    domain: SignatureDomain,
1609    signed_payload_version: u32,
1610) -> Result<(), SignatureError> {
1611    let expected = domain.signed_payload_version();
1612    if signed_payload_version != expected {
1613        return Err(SignatureError::UnsupportedSignedPayloadVersion {
1614            domain,
1615            actual: signed_payload_version,
1616            expected,
1617        });
1618    }
1619    Ok(())
1620}
1621
1622fn validate_scopes(
1623    database_scopes: &[DatabaseId],
1624    group_scopes: &[String],
1625) -> Result<(), SignatureError> {
1626    let mut seen_databases = HashSet::with_capacity(database_scopes.len());
1627    for database_id in database_scopes {
1628        if !valid_scope_value(&database_id.0) {
1629            return Err(SignatureError::InvalidDatabaseScope);
1630        }
1631        if !seen_databases.insert(database_id) {
1632            return Err(SignatureError::DuplicateDatabaseScope {
1633                database_id: database_id.clone(),
1634            });
1635        }
1636    }
1637    let mut seen_groups = HashSet::with_capacity(group_scopes.len());
1638    for group_id in group_scopes {
1639        if !valid_scope_value(group_id) {
1640            return Err(SignatureError::InvalidGroupScope);
1641        }
1642        if !seen_groups.insert(group_id) {
1643            return Err(SignatureError::DuplicateGroupScope {
1644                group_id: group_id.clone(),
1645            });
1646        }
1647    }
1648    Ok(())
1649}
1650
1651fn valid_scope_value(value: &str) -> bool {
1652    !value.is_empty() && !value.contains('\0')
1653}
1654
1655fn deserialize_exact_bytes<'de, D, const N: usize>(
1656    deserializer: D,
1657    expected: &'static str,
1658) -> Result<[u8; N], D::Error>
1659where
1660    D: Deserializer<'de>,
1661{
1662    struct ExactBytesVisitor<const N: usize> {
1663        expected: &'static str,
1664    }
1665
1666    impl<'de, const N: usize> Visitor<'de> for ExactBytesVisitor<N> {
1667        type Value = [u8; N];
1668
1669        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1670            formatter.write_str(self.expected)
1671        }
1672
1673        fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
1674        where
1675            E: serde::de::Error,
1676        {
1677            value
1678                .try_into()
1679                .map_err(|_| E::invalid_length(value.len(), &self))
1680        }
1681
1682        fn visit_byte_buf<E>(self, value: Vec<u8>) -> Result<Self::Value, E>
1683        where
1684            E: serde::de::Error,
1685        {
1686            self.visit_bytes(&value)
1687        }
1688
1689        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1690        where
1691            A: SeqAccess<'de>,
1692        {
1693            let mut bytes = [0; N];
1694            for (index, byte) in bytes.iter_mut().enumerate() {
1695                *byte = sequence
1696                    .next_element()?
1697                    .ok_or_else(|| A::Error::invalid_length(index, &self))?;
1698            }
1699            if sequence.next_element::<u8>()?.is_some() {
1700                return Err(A::Error::invalid_length(N + 1, &self));
1701            }
1702            Ok(bytes)
1703        }
1704    }
1705
1706    deserializer.deserialize_bytes(ExactBytesVisitor::<N> { expected })
1707}
1708
1709#[cfg(test)]
1710mod tests;