Skip to main content

adk_awp/verify/
pins.rs

1//! What a verifier remembers per domain: the pinned root, the last verified checkpoint and
2//! the revocations it has seen (spec 3.5 §7.7; AWP 2.0 §15.3).
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::path::PathBuf;
6use std::sync::Arc;
7
8use async_trait::async_trait;
9use serde::{Deserialize, Serialize};
10use tokio::sync::RwLock;
11
12/// A verifier's pinned state for one domain (AWP 2.0 §15.3).
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "camelCase")]
15pub struct Pin {
16    /// The pinned root key's id.
17    pub root_kid: String,
18    /// The pinned root key's RFC 7638 thumbprint.
19    pub root_thumbprint: String,
20    /// The last verified checkpoint's tree size.
21    pub tree_size: u64,
22    /// The last verified checkpoint's root hash, hex.
23    pub root_hash: String,
24    /// Key ids seen revoked; a later key set that drops a revocation does not revive a key.
25    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
26    pub revoked: BTreeSet<String>,
27}
28
29/// Why pinned state could not be read or written.
30#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
31#[error("the verifier's pinned state failed: {0}")]
32pub struct PinError(pub String);
33
34/// Per-domain pinned state (AWP 2.0 §15.3).
35#[async_trait]
36pub trait PinStore: Send + Sync {
37    /// Returns the pin for `domain`.
38    async fn get(&self, domain: &str) -> Result<Option<Pin>, PinError>;
39    /// Replaces the pin for `domain`.
40    async fn put(&self, domain: &str, pin: Pin) -> Result<(), PinError>;
41}
42
43/// In-memory pins.
44#[derive(Debug, Clone, Default)]
45pub struct InMemoryPinStore {
46    pins: Arc<RwLock<BTreeMap<String, Pin>>>,
47}
48
49#[async_trait]
50impl PinStore for InMemoryPinStore {
51    async fn get(&self, domain: &str) -> Result<Option<Pin>, PinError> {
52        Ok(self.pins.read().await.get(domain).cloned())
53    }
54
55    async fn put(&self, domain: &str, pin: Pin) -> Result<(), PinError> {
56        self.pins.write().await.insert(domain.to_owned(), pin);
57        Ok(())
58    }
59}
60
61/// Pins kept in one JSON file, written atomically: what `adk-rust awp verify` uses.
62#[derive(Debug)]
63pub struct FilePinStore {
64    path: PathBuf,
65    lock: tokio::sync::Mutex<()>,
66}
67
68impl FilePinStore {
69    /// Pins stored at `path`; the file is created on the first write.
70    pub fn new(path: impl Into<PathBuf>) -> Self {
71        Self { path: path.into(), lock: tokio::sync::Mutex::new(()) }
72    }
73
74    async fn read_all(&self) -> Result<BTreeMap<String, Pin>, PinError> {
75        match tokio::fs::read(&self.path).await {
76            Ok(bytes) => {
77                serde_json::from_slice(&bytes).map_err(|error| PinError(error.to_string()))
78            }
79            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()),
80            Err(error) => Err(PinError(error.to_string())),
81        }
82    }
83}
84
85#[async_trait]
86impl PinStore for FilePinStore {
87    async fn get(&self, domain: &str) -> Result<Option<Pin>, PinError> {
88        let _guard = self.lock.lock().await;
89        Ok(self.read_all().await?.remove(domain))
90    }
91
92    async fn put(&self, domain: &str, pin: Pin) -> Result<(), PinError> {
93        let _guard = self.lock.lock().await;
94        let mut pins = self.read_all().await?;
95        pins.insert(domain.to_owned(), pin);
96        let bytes =
97            serde_json::to_vec_pretty(&pins).map_err(|error| PinError(error.to_string()))?;
98        if let Some(parent) = self.path.parent().filter(|parent| !parent.as_os_str().is_empty()) {
99            tokio::fs::create_dir_all(parent).await.map_err(|error| PinError(error.to_string()))?;
100        }
101        let temp = self.path.with_extension("tmp");
102        tokio::fs::write(&temp, bytes).await.map_err(|error| PinError(error.to_string()))?;
103        tokio::fs::rename(&temp, &self.path).await.map_err(|error| PinError(error.to_string()))
104    }
105}