Skip to main content

centralcore/trust/
mod.rs

1//! Public-key trust, detached provider signatures, and explicit key rotation.
2
3use std::{
4    collections::BTreeMap,
5    fmt,
6    path::{Path, PathBuf},
7    sync::Arc,
8};
9
10use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
11use ed25519_dalek::{Signature as DalekSignature, Verifier as _, VerifyingKey};
12use serde::{Deserialize, Serialize};
13use sha2::{Digest as _, Sha256};
14use tokio::sync::Mutex;
15
16use crate::{
17    events::{CoreEvent, EventBus},
18    Error, Result,
19};
20
21const TRUST_STORE_FORMAT_VERSION: u32 = 1;
22pub const SIGNATURE_VERSION: u32 = 1;
23pub const KEY_FILE_FORMAT_VERSION: u32 = 1;
24pub const KEY_TRANSITION_VERSION: u32 = 1;
25const PROVIDER_DOMAIN: &[u8] = b"centralcore-provider-signature-v1\0";
26const TRANSITION_DOMAIN: &[u8] = b"centralcore-key-transition-v1\0";
27
28/// Signature algorithms understood by the stable CentralCore API.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "lowercase")]
31#[non_exhaustive]
32pub enum SignatureAlgorithm {
33    Ed25519,
34}
35
36impl fmt::Display for SignatureAlgorithm {
37    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38        formatter.write_str(match self {
39            Self::Ed25519 => "ed25519",
40        })
41    }
42}
43
44/// Deterministic SHA-256 fingerprint of public-key bytes.
45#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
46#[serde(transparent)]
47pub struct KeyId(String);
48
49impl KeyId {
50    pub fn parse(value: impl Into<String>) -> std::result::Result<Self, TrustError> {
51        let value = value.into();
52        let digest = value.strip_prefix("sha256:").ok_or_else(|| {
53            TrustError::InvalidPublicKey("key ID must use the sha256: prefix".into())
54        })?;
55        if digest.len() != 64
56            || !digest
57                .bytes()
58                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
59        {
60            return Err(TrustError::InvalidPublicKey(
61                "key ID must contain 64 lowercase hexadecimal characters".into(),
62            ));
63        }
64        Ok(Self(value))
65    }
66
67    #[must_use]
68    pub fn as_str(&self) -> &str {
69        &self.0
70    }
71}
72
73impl fmt::Display for KeyId {
74    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
75        formatter.write_str(&self.0)
76    }
77}
78
79impl<'de> Deserialize<'de> for KeyId {
80    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
81    where
82        D: serde::Deserializer<'de>,
83    {
84        Self::parse(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
85    }
86}
87
88/// Validated Ed25519 public-key bytes, independent from the crypto crate API.
89#[derive(Clone, PartialEq, Eq)]
90pub struct PublicKey([u8; 32]);
91
92impl fmt::Debug for PublicKey {
93    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94        formatter
95            .debug_tuple("PublicKey")
96            .field(&self.key_id())
97            .finish()
98    }
99}
100
101impl PublicKey {
102    #[must_use]
103    pub fn from_bytes(bytes: [u8; 32]) -> Self {
104        Self(bytes)
105    }
106
107    pub fn from_base64(value: &str) -> std::result::Result<Self, TrustError> {
108        let decoded = BASE64
109            .decode(value)
110            .map_err(|_| TrustError::InvalidPublicKey("public key is not valid base64".into()))?;
111        let bytes: [u8; 32] = decoded.try_into().map_err(|_| {
112            TrustError::InvalidPublicKey("Ed25519 public key must be exactly 32 bytes".into())
113        })?;
114        VerifyingKey::from_bytes(&bytes)
115            .map_err(|_| TrustError::InvalidPublicKey("invalid Ed25519 public key".into()))?;
116        Ok(Self(bytes))
117    }
118
119    #[must_use]
120    pub fn as_bytes(&self) -> &[u8; 32] {
121        &self.0
122    }
123
124    #[must_use]
125    pub fn to_base64(&self) -> String {
126        BASE64.encode(self.0)
127    }
128
129    #[must_use]
130    pub fn key_id(&self) -> KeyId {
131        KeyId(format!("sha256:{:x}", Sha256::digest(self.0)))
132    }
133}
134
135impl Serialize for PublicKey {
136    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
137    where
138        S: serde::Serializer,
139    {
140        serializer.serialize_str(&self.to_base64())
141    }
142}
143
144impl<'de> Deserialize<'de> for PublicKey {
145    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
146    where
147        D: serde::Deserializer<'de>,
148    {
149        Self::from_base64(&String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
150    }
151}
152
153/// Portable public-key file accepted by `ccorp trust add`.
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(deny_unknown_fields)]
156pub struct PublicKeyFile {
157    pub key_format_version: u32,
158    pub algorithm: SignatureAlgorithm,
159    pub public_key: PublicKey,
160    pub key_id: KeyId,
161    pub label: Option<String>,
162}
163
164impl PublicKeyFile {
165    pub fn new(public_key: PublicKey, label: Option<String>) -> Self {
166        let key_id = public_key.key_id();
167        Self {
168            key_format_version: KEY_FILE_FORMAT_VERSION,
169            algorithm: SignatureAlgorithm::Ed25519,
170            public_key,
171            key_id,
172            label,
173        }
174    }
175
176    pub fn validate(&self) -> std::result::Result<(), TrustError> {
177        if self.key_format_version != KEY_FILE_FORMAT_VERSION {
178            return Err(TrustError::UnsupportedKeyFormat(self.key_format_version));
179        }
180        if self.key_id != self.public_key.key_id() {
181            return Err(TrustError::KeyIdMismatch);
182        }
183        Ok(())
184    }
185}
186
187/// One local trust decision. Revoked keys remain recorded to make revocation durable.
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189pub struct TrustedKey {
190    pub id: KeyId,
191    pub algorithm: SignatureAlgorithm,
192    pub public_key: PublicKey,
193    pub label: Option<String>,
194    pub revoked: bool,
195    pub added_unix_seconds: u64,
196}
197
198/// Detached signature stored beside a provider index.
199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200#[serde(deny_unknown_fields)]
201pub struct SignatureEnvelope {
202    pub signature_version: u32,
203    pub algorithm: String,
204    pub key_id: KeyId,
205    pub signature: String,
206}
207
208impl SignatureEnvelope {
209    pub fn ed25519(key_id: KeyId, signature: [u8; 64]) -> Self {
210        Self {
211            signature_version: SIGNATURE_VERSION,
212            algorithm: "ed25519".into(),
213            key_id,
214            signature: BASE64.encode(signature),
215        }
216    }
217}
218
219/// Per-provider signature enforcement policy.
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
221#[serde(rename_all = "snake_case")]
222pub enum SignaturePolicy {
223    Required,
224    #[default]
225    Optional,
226    Disabled,
227}
228
229/// Security state surfaced in snapshots, sync reports, and JSON CLI output.
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(rename_all = "snake_case")]
232pub enum SignatureStatus {
233    Verified,
234    Unsigned,
235    Disabled,
236}
237
238/// Evidence retained with an accepted provider snapshot.
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
240pub struct ProviderVerification {
241    pub signature_status: SignatureStatus,
242    pub algorithm: Option<SignatureAlgorithm>,
243    pub key_id: Option<KeyId>,
244    pub signature: Option<String>,
245    pub content_sha256: String,
246    pub verified_unix_seconds: Option<u64>,
247    pub revision: Option<u64>,
248    /// Exact index bytes cached with the detached envelope for offline audit/revalidation.
249    pub document_base64: String,
250    pub envelope: Option<SignatureEnvelope>,
251}
252
253/// Key transition payload signed by the current key.
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
255#[serde(deny_unknown_fields)]
256pub struct KeyTransitionPayload {
257    pub transition_version: u32,
258    pub provider_id: String,
259    pub from_key_id: KeyId,
260    pub to_key: PublicKeyFile,
261    pub valid_from_revision: u64,
262}
263
264/// Self-contained, old-key-signed rotation declaration.
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266#[serde(deny_unknown_fields)]
267pub struct KeyTransition {
268    #[serde(flatten)]
269    pub payload: KeyTransitionPayload,
270    pub signature: String,
271}
272
273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
274struct StoredTransition {
275    provider_id: String,
276    from_key_id: KeyId,
277    to_key_id: KeyId,
278    valid_from_revision: u64,
279}
280
281#[derive(Debug, Clone, Serialize, Deserialize)]
282struct TrustDocument {
283    format_version: u32,
284    keys: BTreeMap<KeyId, TrustedKey>,
285    transitions: Vec<StoredTransition>,
286}
287
288impl Default for TrustDocument {
289    fn default() -> Self {
290        Self {
291            format_version: TRUST_STORE_FORMAT_VERSION,
292            keys: BTreeMap::new(),
293            transitions: Vec::new(),
294        }
295    }
296}
297
298/// Structured signature/trust failures exposed by the library.
299#[derive(Debug, thiserror::Error)]
300#[non_exhaustive]
301pub enum TrustError {
302    #[error("provider signature is missing")]
303    SignatureMissing,
304    #[error("provider signature is invalid")]
305    SignatureInvalid,
306    #[error("unsupported signature algorithm `{0}`")]
307    UnsupportedSignatureAlgorithm(String),
308    #[error("unsupported signature envelope version {0}")]
309    UnsupportedSignatureVersion(u32),
310    #[error("unsupported public-key file version {0}")]
311    UnsupportedKeyFormat(u32),
312    #[error("signing key `{0}` is not trusted")]
313    UntrustedSigningKey(KeyId),
314    #[error("signing key `{actual}` does not match expected key `{expected}`")]
315    SigningKeyMismatch { expected: KeyId, actual: KeyId },
316    #[error("manifest rollback detected for `{subject}`: received revision {received}, highest trusted revision is {highest}")]
317    ManifestRollbackDetected {
318        subject: String,
319        received: u64,
320        highest: u64,
321    },
322    #[error("invalid key transition: {0}")]
323    InvalidKeyTransition(String),
324    #[error("trust store operation failed: {0}")]
325    TrustStoreError(String),
326    #[error("invalid public key: {0}")]
327    InvalidPublicKey(String),
328    #[error("public key fingerprint does not match its key bytes")]
329    KeyIdMismatch,
330    #[error("JSON canonicalization failed: {0}")]
331    Canonicalization(String),
332}
333
334/// Persistent local store of approved public keys and scoped rotations.
335#[derive(Debug, Clone)]
336pub struct TrustStore {
337    root: PathBuf,
338    events: EventBus,
339    mutex: Arc<Mutex<()>>,
340}
341
342impl TrustStore {
343    pub(crate) fn new(data_directory: &Path, events: EventBus) -> Self {
344        Self {
345            root: data_directory.join("trust"),
346            events,
347            mutex: Arc::new(Mutex::new(())),
348        }
349    }
350
351    #[must_use]
352    pub fn root(&self) -> &Path {
353        &self.root
354    }
355
356    pub async fn add_key(
357        &self,
358        public_key: PublicKey,
359        label: Option<String>,
360    ) -> Result<TrustedKey> {
361        let _guard = self.mutex.lock().await;
362        let mut document = self.load().await?;
363        let id = public_key.key_id();
364        let key = TrustedKey {
365            id: id.clone(),
366            algorithm: SignatureAlgorithm::Ed25519,
367            public_key,
368            label,
369            revoked: false,
370            added_unix_seconds: unix_seconds(),
371        };
372        document.keys.insert(id.clone(), key.clone());
373        self.save(&document).await?;
374        self.events.emit(CoreEvent::SigningKeyTrusted {
375            key_id: id.to_string(),
376        });
377        Ok(key)
378    }
379
380    pub async fn add_key_file(&self, file: PublicKeyFile) -> Result<TrustedKey> {
381        file.validate()?;
382        self.add_key(file.public_key, file.label).await
383    }
384
385    pub async fn list(&self) -> Result<Vec<TrustedKey>> {
386        Ok(self.load().await?.keys.into_values().collect())
387    }
388
389    pub async fn get(&self, id: &KeyId) -> Result<TrustedKey> {
390        let key = self
391            .load()
392            .await?
393            .keys
394            .remove(id)
395            .ok_or_else(|| TrustError::UntrustedSigningKey(id.clone()))?;
396        if key.revoked {
397            return Err(TrustError::UntrustedSigningKey(id.clone()).into());
398        }
399        Ok(key)
400    }
401
402    pub async fn show(&self, id: &KeyId) -> Result<TrustedKey> {
403        self.load()
404            .await?
405            .keys
406            .remove(id)
407            .ok_or_else(|| TrustError::UntrustedSigningKey(id.clone()).into())
408    }
409
410    /// Revokes a key durably without touching snapshots or installed instances.
411    pub async fn remove(&self, id: &KeyId) -> Result<TrustedKey> {
412        let _guard = self.mutex.lock().await;
413        let mut document = self.load().await?;
414        let key = document
415            .keys
416            .get_mut(id)
417            .ok_or_else(|| TrustError::UntrustedSigningKey(id.clone()))?;
418        key.revoked = true;
419        let removed = key.clone();
420        self.save(&document).await?;
421        self.events.emit(CoreEvent::SigningKeyRemoved {
422            key_id: id.to_string(),
423        });
424        Ok(removed)
425    }
426
427    pub async fn apply_transition(&self, transition: KeyTransition) -> Result<TrustedKey> {
428        let _guard = self.mutex.lock().await;
429        let mut document = self.load().await?;
430        validate_transition(&document, &transition)?;
431        let payload = &transition.payload;
432        let id = payload.to_key.key_id.clone();
433        let key = TrustedKey {
434            id: id.clone(),
435            algorithm: payload.to_key.algorithm,
436            public_key: payload.to_key.public_key.clone(),
437            label: payload.to_key.label.clone(),
438            revoked: false,
439            added_unix_seconds: unix_seconds(),
440        };
441        document.keys.insert(id.clone(), key.clone());
442        let stored = StoredTransition {
443            provider_id: payload.provider_id.clone(),
444            from_key_id: payload.from_key_id.clone(),
445            to_key_id: id.clone(),
446            valid_from_revision: payload.valid_from_revision,
447        };
448        if !document.transitions.contains(&stored) {
449            document.transitions.push(stored);
450        }
451        self.save(&document).await?;
452        self.events.emit(CoreEvent::SigningKeyRotated {
453            provider_id: payload.provider_id.clone(),
454            old_key_id: payload.from_key_id.to_string(),
455            new_key_id: id.to_string(),
456        });
457        Ok(key)
458    }
459
460    pub async fn authorize(
461        &self,
462        expected: &KeyId,
463        actual: &KeyId,
464        provider_id: &str,
465        revision: u64,
466    ) -> Result<TrustedKey> {
467        let document = self.load().await?;
468        let key = document
469            .keys
470            .get(actual)
471            .filter(|key| !key.revoked)
472            .cloned()
473            .ok_or_else(|| TrustError::UntrustedSigningKey(actual.clone()))?;
474        if actual == expected {
475            return Ok(key);
476        }
477        let authorized = document.transitions.iter().any(|transition| {
478            transition.provider_id == provider_id
479                && &transition.from_key_id == expected
480                && &transition.to_key_id == actual
481                && revision >= transition.valid_from_revision
482        });
483        if !authorized {
484            return Err(TrustError::SigningKeyMismatch {
485                expected: expected.clone(),
486                actual: actual.clone(),
487            }
488            .into());
489        }
490        Ok(key)
491    }
492
493    async fn load(&self) -> Result<TrustDocument> {
494        let path = self.root.join("trust.json");
495        match tokio::fs::read(&path).await {
496            Ok(bytes) => {
497                let document: TrustDocument = serde_json::from_slice(&bytes)
498                    .map_err(|error| TrustError::TrustStoreError(error.to_string()))?;
499                if document.format_version != TRUST_STORE_FORMAT_VERSION {
500                    return Err(Error::UnsupportedFormat {
501                        kind: "trust store",
502                        version: document.format_version,
503                    });
504                }
505                Ok(document)
506            }
507            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
508                Ok(TrustDocument::default())
509            }
510            Err(error) => Err(TrustError::TrustStoreError(error.to_string()).into()),
511        }
512    }
513
514    async fn save(&self, document: &TrustDocument) -> Result<()> {
515        tokio::fs::create_dir_all(&self.root)
516            .await
517            .map_err(|error| TrustError::TrustStoreError(error.to_string()))?;
518        let path = self.root.join("trust.json");
519        let temporary = self.root.join("trust.json.tmp");
520        let bytes = serde_json::to_vec_pretty(document)
521            .map_err(|error| TrustError::TrustStoreError(error.to_string()))?;
522        tokio::fs::write(&temporary, bytes)
523            .await
524            .map_err(|error| TrustError::TrustStoreError(error.to_string()))?;
525        if tokio::fs::try_exists(&path)
526            .await
527            .map_err(|error| TrustError::TrustStoreError(error.to_string()))?
528        {
529            tokio::fs::remove_file(&path)
530                .await
531                .map_err(|error| TrustError::TrustStoreError(error.to_string()))?;
532        }
533        tokio::fs::rename(temporary, path)
534            .await
535            .map_err(|error| TrustError::TrustStoreError(error.to_string()))?;
536        Ok(())
537    }
538}
539
540/// Verifies detached signatures without exposing crypto-library types.
541#[derive(Debug, Clone)]
542pub struct SignatureVerifier {
543    trust: TrustStore,
544}
545
546impl SignatureVerifier {
547    #[must_use]
548    pub fn new(trust: TrustStore) -> Self {
549        Self { trust }
550    }
551
552    pub async fn verify_provider(
553        &self,
554        document: &[u8],
555        envelope: &SignatureEnvelope,
556        expected_key: &KeyId,
557        provider_id: &str,
558        revision: u64,
559    ) -> Result<()> {
560        validate_envelope(envelope)?;
561        let key = self
562            .trust
563            .authorize(expected_key, &envelope.key_id, provider_id, revision)
564            .await?;
565        verify_signature(
566            &key.public_key,
567            &provider_signing_payload(document)?,
568            &envelope.signature,
569        )
570    }
571}
572
573/// RFC 8785 canonical JSON used by both runtime verification and signing tools.
574pub fn canonicalize_json(document: &[u8]) -> std::result::Result<Vec<u8>, TrustError> {
575    let value: serde_json::Value = serde_json::from_slice(document)
576        .map_err(|error| TrustError::Canonicalization(error.to_string()))?;
577    serde_jcs::to_vec(&value).map_err(|error| TrustError::Canonicalization(error.to_string()))
578}
579
580pub fn provider_signing_payload(document: &[u8]) -> std::result::Result<Vec<u8>, TrustError> {
581    let canonical = canonicalize_json(document)?;
582    let mut payload = Vec::with_capacity(PROVIDER_DOMAIN.len() + canonical.len());
583    payload.extend_from_slice(PROVIDER_DOMAIN);
584    payload.extend_from_slice(&canonical);
585    Ok(payload)
586}
587
588pub fn transition_signing_payload(
589    payload: &KeyTransitionPayload,
590) -> std::result::Result<Vec<u8>, TrustError> {
591    let canonical = serde_jcs::to_vec(payload)
592        .map_err(|error| TrustError::Canonicalization(error.to_string()))?;
593    let mut output = Vec::with_capacity(TRANSITION_DOMAIN.len() + canonical.len());
594    output.extend_from_slice(TRANSITION_DOMAIN);
595    output.extend_from_slice(&canonical);
596    Ok(output)
597}
598
599fn validate_envelope(envelope: &SignatureEnvelope) -> Result<()> {
600    if envelope.signature_version != SIGNATURE_VERSION {
601        return Err(TrustError::UnsupportedSignatureVersion(envelope.signature_version).into());
602    }
603    if envelope.algorithm != "ed25519" {
604        return Err(TrustError::UnsupportedSignatureAlgorithm(envelope.algorithm.clone()).into());
605    }
606    Ok(())
607}
608
609fn validate_transition(document: &TrustDocument, transition: &KeyTransition) -> Result<()> {
610    let payload = &transition.payload;
611    if payload.transition_version != KEY_TRANSITION_VERSION {
612        return Err(TrustError::InvalidKeyTransition(format!(
613            "unsupported version {}",
614            payload.transition_version
615        ))
616        .into());
617    }
618    if payload.provider_id.is_empty() || payload.valid_from_revision == 0 {
619        return Err(TrustError::InvalidKeyTransition(
620            "provider ID and non-zero starting revision are required".into(),
621        )
622        .into());
623    }
624    payload.to_key.validate()?;
625    if payload.from_key_id == payload.to_key.key_id {
626        return Err(
627            TrustError::InvalidKeyTransition("old and new keys are identical".into()).into(),
628        );
629    }
630    let old = document
631        .keys
632        .get(&payload.from_key_id)
633        .filter(|key| !key.revoked)
634        .ok_or_else(|| TrustError::UntrustedSigningKey(payload.from_key_id.clone()))?;
635    verify_signature(
636        &old.public_key,
637        &transition_signing_payload(payload)?,
638        &transition.signature,
639    )
640    .map_err(|_| TrustError::InvalidKeyTransition("transition signature is invalid".into()).into())
641}
642
643fn verify_signature(public_key: &PublicKey, message: &[u8], encoded_signature: &str) -> Result<()> {
644    let bytes = BASE64
645        .decode(encoded_signature)
646        .map_err(|_| TrustError::SignatureInvalid)?;
647    let signature = DalekSignature::from_slice(&bytes).map_err(|_| TrustError::SignatureInvalid)?;
648    let key = VerifyingKey::from_bytes(public_key.as_bytes())
649        .map_err(|_| TrustError::InvalidPublicKey("invalid Ed25519 point".into()))?;
650    key.verify(message, &signature)
651        .map_err(|_| TrustError::SignatureInvalid.into())
652}
653
654fn unix_seconds() -> u64 {
655    std::time::SystemTime::now()
656        .duration_since(std::time::UNIX_EPOCH)
657        .unwrap_or_default()
658        .as_secs()
659}
660
661#[cfg(test)]
662mod tests {
663    use ed25519_dalek::{Signer as _, SigningKey};
664    use rand_core::OsRng;
665
666    use super::*;
667
668    #[test]
669    fn canonicalization_ignores_formatting_and_object_order() {
670        let left = canonicalize_json(br#"{ "b": 2, "a": [true, null] }"#).expect("left");
671        let right = canonicalize_json(b"{\n\"a\":[true,null],\"b\":2}\n").expect("right");
672        assert_eq!(left, right);
673    }
674
675    #[test]
676    fn key_id_is_deterministic() {
677        let key = PublicKey::from_bytes([7; 32]);
678        assert_eq!(key.key_id(), key.key_id());
679        assert_eq!(key.key_id().as_str().len(), 71);
680    }
681
682    #[test]
683    fn deeply_nested_or_truncated_json_is_rejected_without_panicking() {
684        let nested = format!("{}0{}", "[".repeat(256), "]".repeat(256));
685        assert!(canonicalize_json(nested.as_bytes()).is_err());
686        assert!(canonicalize_json(br#"{"revision":1,"provider":"#).is_err());
687    }
688
689    #[tokio::test]
690    async fn valid_signature_is_accepted_and_tampering_is_rejected() {
691        let temporary = tempfile::tempdir().expect("tempdir");
692        let events = EventBus::new(16);
693        let trust = TrustStore::new(temporary.path(), events);
694        let signing = SigningKey::generate(&mut OsRng);
695        let public = PublicKey::from_bytes(signing.verifying_key().to_bytes());
696        let trusted = trust.add_key(public, None).await.expect("trust");
697        let document = br#"{"revision":1,"provider":"demo"}"#;
698        let signature = signing.sign(&provider_signing_payload(document).expect("payload"));
699        let envelope = SignatureEnvelope::ed25519(trusted.id.clone(), signature.to_bytes());
700        let verifier = SignatureVerifier::new(trust);
701        verifier
702            .verify_provider(document, &envelope, &trusted.id, "demo", 1)
703            .await
704            .expect("valid");
705        let error = verifier
706            .verify_provider(
707                br#"{"revision":2,"provider":"demo"}"#,
708                &envelope,
709                &trusted.id,
710                "demo",
711                2,
712            )
713            .await
714            .expect_err("tampered");
715        assert!(matches!(error, Error::Trust(TrustError::SignatureInvalid)));
716    }
717
718    #[tokio::test]
719    async fn unknown_and_wrong_keys_are_rejected() {
720        let temporary = tempfile::tempdir().expect("tempdir");
721        let trust = TrustStore::new(temporary.path(), EventBus::new(16));
722        let expected_signing = SigningKey::generate(&mut OsRng);
723        let expected = trust
724            .add_key(
725                PublicKey::from_bytes(expected_signing.verifying_key().to_bytes()),
726                None,
727            )
728            .await
729            .expect("expected");
730        let other_signing = SigningKey::generate(&mut OsRng);
731        let other_public = PublicKey::from_bytes(other_signing.verifying_key().to_bytes());
732        let document = br#"{"revision":1}"#;
733        let signature = other_signing.sign(&provider_signing_payload(document).expect("payload"));
734        let unknown = SignatureEnvelope::ed25519(other_public.key_id(), signature.to_bytes());
735        let verifier = SignatureVerifier::new(trust.clone());
736        assert!(matches!(
737            verifier
738                .verify_provider(document, &unknown, &expected.id, "demo", 1)
739                .await,
740            Err(Error::Trust(TrustError::UntrustedSigningKey(_)))
741        ));
742        let other = trust.add_key(other_public, None).await.expect("other");
743        let wrong = SignatureEnvelope::ed25519(other.id, signature.to_bytes());
744        assert!(matches!(
745            verifier
746                .verify_provider(document, &wrong, &expected.id, "demo", 1)
747                .await,
748            Err(Error::Trust(TrustError::SigningKeyMismatch { .. }))
749        ));
750    }
751
752    #[tokio::test]
753    async fn valid_rotation_authorizes_only_the_scoped_successor() {
754        let temporary = tempfile::tempdir().expect("tempdir");
755        let trust = TrustStore::new(temporary.path(), EventBus::new(16));
756        let old_signing = SigningKey::generate(&mut OsRng);
757        let old = trust
758            .add_key(
759                PublicKey::from_bytes(old_signing.verifying_key().to_bytes()),
760                None,
761            )
762            .await
763            .expect("old");
764        let new_signing = SigningKey::generate(&mut OsRng);
765        let new_file = PublicKeyFile::new(
766            PublicKey::from_bytes(new_signing.verifying_key().to_bytes()),
767            Some("new".into()),
768        );
769        let payload = KeyTransitionPayload {
770            transition_version: KEY_TRANSITION_VERSION,
771            provider_id: "demo".into(),
772            from_key_id: old.id.clone(),
773            to_key: new_file,
774            valid_from_revision: 2,
775        };
776        let signature =
777            old_signing.sign(&transition_signing_payload(&payload).expect("transition payload"));
778        trust
779            .apply_transition(KeyTransition {
780                payload,
781                signature: BASE64.encode(signature.to_bytes()),
782            })
783            .await
784            .expect("rotation");
785        let document = br#"{"revision":2}"#;
786        let signature =
787            new_signing.sign(&provider_signing_payload(document).expect("provider payload"));
788        let envelope = SignatureEnvelope::ed25519(
789            PublicKey::from_bytes(new_signing.verifying_key().to_bytes()).key_id(),
790            signature.to_bytes(),
791        );
792        SignatureVerifier::new(trust.clone())
793            .verify_provider(document, &envelope, &old.id, "demo", 2)
794            .await
795            .expect("rotated provider");
796        assert!(SignatureVerifier::new(trust)
797            .verify_provider(document, &envelope, &old.id, "other", 2)
798            .await
799            .is_err());
800    }
801
802    #[tokio::test]
803    async fn unknown_algorithm_is_rejected_before_signature_parsing() {
804        let temporary = tempfile::tempdir().expect("tempdir");
805        let trust = TrustStore::new(temporary.path(), EventBus::new(16));
806        let signing = SigningKey::generate(&mut OsRng);
807        let trusted = trust
808            .add_key(
809                PublicKey::from_bytes(signing.verifying_key().to_bytes()),
810                None,
811            )
812            .await
813            .expect("trust");
814        let envelope = SignatureEnvelope {
815            signature_version: SIGNATURE_VERSION,
816            algorithm: "future-signature".into(),
817            key_id: trusted.id.clone(),
818            signature: BASE64.encode([0; 64]),
819        };
820        let error = SignatureVerifier::new(trust)
821            .verify_provider(b"{}", &envelope, &trusted.id, "demo", 1)
822            .await
823            .expect_err("unsupported algorithm");
824        assert!(matches!(
825            error,
826            Error::Trust(TrustError::UnsupportedSignatureAlgorithm(_))
827        ));
828    }
829
830    #[tokio::test]
831    async fn corrupted_rotation_signature_is_rejected() {
832        let temporary = tempfile::tempdir().expect("tempdir");
833        let trust = TrustStore::new(temporary.path(), EventBus::new(16));
834        let old_signing = SigningKey::generate(&mut OsRng);
835        let old = trust
836            .add_key(
837                PublicKey::from_bytes(old_signing.verifying_key().to_bytes()),
838                None,
839            )
840            .await
841            .expect("old");
842        let new_signing = SigningKey::generate(&mut OsRng);
843        let payload = KeyTransitionPayload {
844            transition_version: KEY_TRANSITION_VERSION,
845            provider_id: "demo".into(),
846            from_key_id: old.id,
847            to_key: PublicKeyFile::new(
848                PublicKey::from_bytes(new_signing.verifying_key().to_bytes()),
849                None,
850            ),
851            valid_from_revision: 2,
852        };
853        let error = trust
854            .apply_transition(KeyTransition {
855                payload,
856                signature: BASE64.encode([0; 64]),
857            })
858            .await
859            .expect_err("invalid transition");
860        assert!(matches!(
861            error,
862            Error::Trust(TrustError::InvalidKeyTransition(_))
863        ));
864    }
865}