1use crate::cert::CertPair;
10use crate::{Error, Result};
11use serde::Serialize;
12use serde::de::DeserializeOwned;
13use std::collections::HashMap;
14use std::path::{Path, PathBuf};
15use std::sync::Mutex;
16
17pub trait CertStore: Send + Sync {
19 fn get(&self, key: &str) -> Result<Option<Vec<u8>>>;
21 fn put(&self, key: &str, value: &[u8]) -> Result<()>;
23 fn delete(&self, key: &str) -> Result<()>;
25}
26
27pub fn check_key(key: &str) -> Result<()> {
29 let ok = !key.is_empty()
30 && key.len() <= 200
31 && !key.starts_with('/')
32 && key.split('/').all(|p| !p.is_empty() && p != "." && p != "..")
33 && key.bytes().all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'.' | b'_' | b'-' | b'/'));
34 if ok { Ok(()) } else { Err(Error::Store(format!("bad store key {key:?}"))) }
35}
36
37pub fn get_json<T: DeserializeOwned>(s: &dyn CertStore, key: &str) -> Result<Option<T>> {
39 match s.get(key)? {
40 Some(b) => Ok(Some(serde_json::from_slice(&b)?)),
41 None => Ok(None),
42 }
43}
44
45pub fn put_json<T: Serialize>(s: &dyn CertStore, key: &str, value: &T) -> Result<()> {
47 s.put(key, &serde_json::to_vec_pretty(value)?)
48}
49
50pub fn cert_key(set: &str) -> String {
52 format!("cert/{set}.json")
53}
54
55pub fn state_key(set: &str) -> String {
57 format!("state/{set}.json")
58}
59
60pub fn account_key(dir: &str) -> String {
62 use sha2::Digest;
63 let tag: String = sha2::Sha256::digest(dir.as_bytes())[..8].iter().map(|b| format!("{b:02x}")).collect();
64 format!("account/{tag}.json")
65}
66
67pub fn load_cert(s: &dyn CertStore, set: &str) -> Result<Option<CertPair>> {
69 get_json(s, &cert_key(set))
70}
71
72pub fn save_cert(s: &dyn CertStore, set: &str, pair: &CertPair) -> Result<()> {
74 put_json(s, &cert_key(set), pair)
75}
76
77#[derive(Clone, Default)]
80#[non_exhaustive]
81pub struct Legacy {
82 pub account: Option<Vec<u8>>,
84 pub cert: Option<CertPair>,
86 pub state: Option<crate::renew::Persisted>,
88}
89
90impl std::fmt::Debug for Legacy {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 f.debug_struct("Legacy")
93 .field("account", &self.account.as_ref().map(|_| "<redacted>"))
94 .field("cert", &self.cert)
95 .field("state", &self.state)
96 .finish()
97 }
98}
99
100fn read_opt(p: Option<&Path>) -> Result<Option<Vec<u8>>> {
101 match p.map(std::fs::read) {
102 None => Ok(None),
103 Some(Ok(b)) => Ok(Some(b)),
104 Some(Err(e)) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
105 Some(Err(e)) => Err(e.into()),
106 }
107}
108
109impl Legacy {
110 pub fn new() -> Self {
112 Self::default()
113 }
114
115 pub fn from_files(account: Option<&Path>, chain_pem: Option<&Path>, key_pem: Option<&Path>) -> Result<Self> {
118 let text = |b: Vec<u8>| String::from_utf8(b).map_err(|_| Error::Store("a legacy PEM file is not text".into()));
119 let cert = match (read_opt(chain_pem)?, read_opt(key_pem)?) {
120 (Some(c), Some(k)) => Some(CertPair { chain_pem: text(c)?, key_pem: text(k)? }),
121 _ => None,
122 };
123 Ok(Self { account: read_opt(account)?, cert, state: None })
124 }
125
126 pub fn with_state(mut self, state: crate::renew::Persisted) -> Self {
128 self.state = Some(state);
129 self
130 }
131}
132
133#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
135#[non_exhaustive]
136pub struct Imported {
137 pub account: bool,
139 pub cert: bool,
141 pub state: bool,
143}
144
145impl Imported {
146 pub fn any(&self) -> bool {
148 self.account || self.cert || self.state
149 }
150}
151
152pub fn import(store: &dyn CertStore, set: &str, directory: &str, legacy: &Legacy) -> Result<Imported> {
159 if let Some(a) = &legacy.account {
160 let _creds: instant_acme::AccountCredentials =
161 serde_json::from_slice(a).map_err(|_| Error::Store("the legacy ACME account is not account credentials".into()))?;
162 }
163 if let Some(p) = &legacy.cert {
164 crate::cert::certified_key(p)?;
165 }
166 let mut done = Imported::default();
167 let akey = account_key(directory);
168 if let Some(a) = &legacy.account
169 && store.get(&akey)?.is_none()
170 {
171 store.put(&akey, a)?;
172 done.account = true;
173 }
174 if let Some(p) = &legacy.cert
175 && load_cert(store, set)?.is_none()
176 {
177 save_cert(store, set, p)?;
178 done.cert = true;
179 let skey = state_key(set);
180 if let Some(st) = &legacy.state
181 && store.get(&skey)?.is_none()
182 {
183 put_json(store, &skey, st)?;
184 done.state = true;
185 }
186 }
187 Ok(done)
188}
189
190#[derive(Default)]
192pub struct MemoryStore(Mutex<HashMap<String, Vec<u8>>>);
193
194impl MemoryStore {
195 pub fn new() -> Self {
197 Self::default()
198 }
199
200 pub fn keys(&self) -> Vec<String> {
202 let mut k: Vec<String> = self.0.lock().unwrap().keys().cloned().collect();
203 k.sort();
204 k
205 }
206}
207
208impl CertStore for MemoryStore {
209 fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {
210 check_key(key)?;
211 Ok(self.0.lock().unwrap().get(key).cloned())
212 }
213 fn put(&self, key: &str, value: &[u8]) -> Result<()> {
214 check_key(key)?;
215 self.0.lock().unwrap().insert(key.to_string(), value.to_vec());
216 Ok(())
217 }
218 fn delete(&self, key: &str) -> Result<()> {
219 check_key(key)?;
220 self.0.lock().unwrap().remove(key);
221 Ok(())
222 }
223}
224
225#[derive(Debug, Clone)]
228pub struct FileStore {
229 root: PathBuf,
230}
231
232impl FileStore {
233 pub fn new(root: impl Into<PathBuf>) -> Self {
235 Self { root: root.into() }
236 }
237
238 pub fn root(&self) -> &Path {
240 &self.root
241 }
242
243 fn path(&self, key: &str) -> Result<PathBuf> {
244 check_key(key)?;
245 Ok(self.root.join(key))
246 }
247}
248
249fn private_dir(dir: &Path) -> Result<()> {
250 let mut b = std::fs::DirBuilder::new();
251 b.recursive(true);
252 #[cfg(unix)]
253 {
254 use std::os::unix::fs::DirBuilderExt;
255 b.mode(0o700);
256 }
257 b.create(dir)?;
258 Ok(())
259}
260
261pub fn write_private(path: &Path, data: &[u8]) -> Result<()> {
263 use std::io::Write;
264 let dir = path.parent().ok_or_else(|| Error::Store("no parent directory".into()))?;
265 private_dir(dir)?;
266 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("x");
267 let tmp = dir.join(format!(".{name}.{}.tmp", std::process::id()));
268 let mut o = std::fs::OpenOptions::new();
269 o.write(true).create(true).truncate(true);
270 #[cfg(unix)]
271 {
272 use std::os::unix::fs::OpenOptionsExt;
273 o.mode(0o600);
274 }
275 let res = (|| {
276 let mut f = o.open(&tmp)?;
277 f.write_all(data)?;
278 f.sync_all()?;
279 std::fs::rename(&tmp, path)
280 })();
281 if res.is_err() {
282 let _ = std::fs::remove_file(&tmp);
283 }
284 Ok(res?)
285}
286
287impl CertStore for FileStore {
288 fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {
289 match std::fs::read(self.path(key)?) {
290 Ok(b) => Ok(Some(b)),
291 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
292 Err(e) => Err(e.into()),
293 }
294 }
295 fn put(&self, key: &str, value: &[u8]) -> Result<()> {
296 write_private(&self.path(key)?, value)
297 }
298 fn delete(&self, key: &str) -> Result<()> {
299 match std::fs::remove_file(self.path(key)?) {
300 Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),
301 _ => Ok(()),
302 }
303 }
304}
305
306#[cfg(feature = "storage")]
307pub use sql::SqlStore;
308
309#[cfg(feature = "storage")]
310mod sql {
311 use super::{CertStore, check_key};
312 use crate::{Error, Result};
313 use std::sync::{Arc, Mutex};
314 use weirdnet_storage::rusqlite::{self, OptionalExtension};
315
316 pub struct SqlStore {
319 conn: Arc<Mutex<rusqlite::Connection>>,
320 table: String,
321 }
322
323 fn db(e: rusqlite::Error) -> Error {
324 Error::Store(e.to_string())
325 }
326
327 impl SqlStore {
328 pub fn new(conn: Arc<Mutex<rusqlite::Connection>>) -> Result<Self> {
330 Self::with_table(conn, "weirdnet_tls")
331 }
332
333 pub fn with_table(conn: Arc<Mutex<rusqlite::Connection>>, table: &str) -> Result<Self> {
335 let table = weirdnet_storage::quote_ident(table);
336 conn.lock()
337 .unwrap()
338 .execute_batch(&format!("CREATE TABLE IF NOT EXISTS {table} (k TEXT PRIMARY KEY NOT NULL, v BLOB NOT NULL)"))
339 .map_err(db)?;
340 Ok(Self { conn, table })
341 }
342 }
343
344 impl CertStore for SqlStore {
345 fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {
346 check_key(key)?;
347 let c = self.conn.lock().unwrap();
348 c.query_row(&format!("SELECT v FROM {} WHERE k = ?1", self.table), [key], |r| r.get(0)).optional().map_err(db)
349 }
350 fn put(&self, key: &str, value: &[u8]) -> Result<()> {
351 check_key(key)?;
352 let c = self.conn.lock().unwrap();
353 c.execute(
354 &format!("INSERT INTO {} (k, v) VALUES (?1, ?2) ON CONFLICT(k) DO UPDATE SET v = excluded.v", self.table),
355 rusqlite::params![key, value],
356 )
357 .map_err(db)?;
358 Ok(())
359 }
360 fn delete(&self, key: &str) -> Result<()> {
361 check_key(key)?;
362 let c = self.conn.lock().unwrap();
363 c.execute(&format!("DELETE FROM {} WHERE k = ?1", self.table), [key]).map_err(db)?;
364 Ok(())
365 }
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 #[test]
374 fn keys_are_checked() {
375 for bad in ["", "/a", "a/../b", "a//b", "A", "a b", "./a"] {
376 assert!(check_key(bad).is_err(), "{bad:?}");
377 }
378 check_key("cert/main.json").unwrap();
379 assert!(account_key("https://acme-v02.api.letsencrypt.org/directory").starts_with("account/"));
380 }
381
382 #[test]
383 fn file_store_is_private_and_atomic() {
384 let d = tempfile::tempdir().unwrap();
385 let s = FileStore::new(d.path().join("tls"));
386 assert_eq!(s.get("cert/a.json").unwrap(), None);
387 s.put("cert/a.json", b"one").unwrap();
388 s.put("cert/a.json", b"two").unwrap();
389 assert_eq!(s.get("cert/a.json").unwrap().as_deref(), Some(&b"two"[..]));
390 #[cfg(unix)]
391 {
392 use std::os::unix::fs::PermissionsExt;
393 let m = std::fs::metadata(d.path().join("tls/cert/a.json")).unwrap().permissions().mode();
394 assert_eq!(m & 0o777, 0o600);
395 let m = std::fs::metadata(d.path().join("tls/cert")).unwrap().permissions().mode();
396 assert_eq!(m & 0o777, 0o700);
397 }
398 assert_eq!(std::fs::read_dir(d.path().join("tls/cert")).unwrap().count(), 1, "no temp files left");
399 s.delete("cert/a.json").unwrap();
400 s.delete("cert/a.json").unwrap();
401 assert_eq!(s.get("cert/a.json").unwrap(), None);
402 }
403
404 #[cfg(feature = "storage")]
405 #[test]
406 fn sql_store_round_trip() {
407 use std::sync::{Arc, Mutex};
408 let conn = weirdnet_storage::rusqlite::Connection::open_in_memory().unwrap();
409 let s = SqlStore::new(Arc::new(Mutex::new(conn))).unwrap();
410 assert_eq!(s.get("cert/a.json").unwrap(), None);
411 s.put("cert/a.json", b"one").unwrap();
412 s.put("cert/a.json", b"two").unwrap();
413 assert_eq!(s.get("cert/a.json").unwrap().as_deref(), Some(&b"two"[..]));
414 s.delete("cert/a.json").unwrap();
415 assert_eq!(s.get("cert/a.json").unwrap(), None);
416 assert!(s.put("../x", b"").is_err());
417 }
418
419 #[test]
420 fn json_round_trip() {
421 let s = MemoryStore::new();
422 let p = CertPair { chain_pem: "c".into(), key_pem: "k".into() };
423 save_cert(&s, "main", &p).unwrap();
424 assert_eq!(load_cert(&s, "main").unwrap(), Some(p));
425 assert_eq!(s.keys(), vec!["cert/main.json"]);
426 }
427}