1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "camelCase")]
15pub struct Pin {
16 pub root_kid: String,
18 pub root_thumbprint: String,
20 pub tree_size: u64,
22 pub root_hash: String,
24 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
26 pub revoked: BTreeSet<String>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
31#[error("the verifier's pinned state failed: {0}")]
32pub struct PinError(pub String);
33
34#[async_trait]
36pub trait PinStore: Send + Sync {
37 async fn get(&self, domain: &str) -> Result<Option<Pin>, PinError>;
39 async fn put(&self, domain: &str, pin: Pin) -> Result<(), PinError>;
41}
42
43#[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#[derive(Debug)]
63pub struct FilePinStore {
64 path: PathBuf,
65 lock: tokio::sync::Mutex<()>,
66}
67
68impl FilePinStore {
69 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}