Skip to main content

schedr_db/
secrets.rs

1//! The `db` secret storage (standalone; see archive/PROJECT.md, Secret storage): one row per secret
2//! path, like a Vault KV v2 secret, its `data` a JSON object of key to value. Each value is
3//! encrypted with XChaCha20-Poly1305 under `SCHEDR_SECRET_KEY`, bound to its `path#key` (the
4//! associated data), so a value can't be moved to another key or path; paths and key names
5//! stay readable, so listing needs no key. A dump, a backup or someone reading the database
6//! sees no value.
7//!
8//! A stored value is `v1:` and the base64 of its 24-byte nonce and the ciphertext with its tag.
9
10use std::collections::BTreeMap;
11use std::fmt;
12
13use base64::Engine as _;
14use base64::engine::general_purpose::STANDARD;
15use chacha20poly1305::aead::{Aead, Generate, KeyInit, Payload};
16use chacha20poly1305::{XChaCha20Poly1305, XNonce};
17use jiff::Timestamp;
18
19use crate::backend::Backend;
20use crate::database::{Database, DbError};
21use crate::query::{db_time, from_json, in_tx, on_pool, sql, sql_text, storable_json};
22
23#[cfg(test)]
24mod tests;
25
26/// The environment variable holding the key.
27pub const SECRET_KEY_ENV: &str = "SCHEDR_SECRET_KEY";
28
29/// The prefix of an encrypted value: the format's version.
30const VERSION: &str = "v1:";
31
32/// The nonce's length (`XChaCha20`'s 192 bits).
33const NONCE_LEN: usize = 24;
34
35/// The key secrets are encrypted under: 32 bytes. Its `Debug` never shows it.
36#[derive(Clone)]
37pub struct SecretKey(chacha20poly1305::Key);
38
39impl fmt::Debug for SecretKey {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        f.write_str("SecretKey(****)")
42    }
43}
44
45/// Why a secret can't be written or read.
46#[derive(Debug, thiserror::Error)]
47pub enum SecretsError {
48    /// No key, or one that isn't 32 bytes of base64.
49    #[error("{0}")]
50    Key(String),
51    /// A value that doesn't decrypt: another key, or a value moved or changed in the table.
52    #[error(
53        "`{0}` can't be decrypted: it was written under another `SCHEDR_SECRET_KEY`, or \
54         changed in the table"
55    )]
56    Decrypt(String),
57    /// The database failed.
58    #[error(transparent)]
59    Db(#[from] DbError),
60}
61
62impl SecretKey {
63    /// A new random key.
64    ///
65    /// # Errors
66    ///
67    /// [`SecretsError::Key`] if the system's random source fails.
68    pub fn generate() -> Result<Self, SecretsError> {
69        chacha20poly1305::Key::try_generate()
70            .map(Self)
71            .map_err(|e| SecretsError::Key(format!("no random bytes for a key: {e}")))
72    }
73
74    /// The key from its base64 text (as `SCHEDR_SECRET_KEY` holds it).
75    ///
76    /// # Errors
77    ///
78    /// [`SecretsError::Key`] if it isn't base64 of 32 bytes (the message never shows it).
79    pub fn from_base64(text: &str) -> Result<Self, SecretsError> {
80        let bytes = STANDARD.decode(text.trim()).map_err(|_| {
81            SecretsError::Key(format!(
82                "`{SECRET_KEY_ENV}` isn't base64 (`schedr secrets new-key` makes one)"
83            ))
84        })?;
85        let key = chacha20poly1305::Key::try_from(bytes.as_slice()).map_err(|_| {
86            SecretsError::Key(format!(
87                "`{SECRET_KEY_ENV}` must be 32 bytes, got {} (`schedr secrets new-key` makes \
88                 one)",
89                bytes.len()
90            ))
91        })?;
92        Ok(Self(key))
93    }
94
95    /// The key from the environment.
96    ///
97    /// # Errors
98    ///
99    /// [`SecretsError::Key`] if it isn't set or isn't a key.
100    pub fn from_env(env: &BTreeMap<String, String>) -> Result<Self, SecretsError> {
101        let text = env.get(SECRET_KEY_ENV).filter(|t| !t.trim().is_empty());
102        let text = text.ok_or_else(|| {
103            SecretsError::Key(format!(
104                "`{SECRET_KEY_ENV}` isn't set: the `db` secret storage encrypts every value \
105                 under it (`schedr secrets new-key` makes one; keep it as you keep the \
106                 database's password)"
107            ))
108        })?;
109        Self::from_base64(text)
110    }
111
112    /// The key as base64, for `schedr secrets new-key`.
113    #[must_use]
114    pub fn to_base64(&self) -> String {
115        STANDARD.encode(self.0.as_slice())
116    }
117
118    fn cipher(&self) -> XChaCha20Poly1305 {
119        XChaCha20Poly1305::new(&self.0)
120    }
121
122    /// `value` encrypted for `path#key`.
123    ///
124    /// # Errors
125    ///
126    /// [`SecretsError::Key`] if the system's random source fails (no nonce).
127    pub fn encrypt(&self, path: &str, key: &str, value: &str) -> Result<String, SecretsError> {
128        let nonce = XNonce::try_generate()
129            .map_err(|e| SecretsError::Key(format!("no random bytes for a nonce: {e}")))?;
130        let aad = format!("{path}#{key}");
131        let sealed = self
132            .cipher()
133            .encrypt(
134                &nonce,
135                Payload {
136                    msg: value.as_bytes(),
137                    aad: aad.as_bytes(),
138                },
139            )
140            .map_err(|_| SecretsError::Key(format!("`{aad}` can't be encrypted")))?;
141        let mut bytes = nonce.to_vec();
142        bytes.extend(sealed);
143        Ok(format!("{VERSION}{}", STANDARD.encode(bytes)))
144    }
145
146    /// The value stored for `path#key`.
147    ///
148    /// # Errors
149    ///
150    /// [`SecretsError::Decrypt`] if it isn't one written under this key for `path#key`.
151    pub fn decrypt(&self, path: &str, key: &str, stored: &str) -> Result<String, SecretsError> {
152        let aad = format!("{path}#{key}");
153        let failed = || SecretsError::Decrypt(aad.clone());
154        let bytes = stored
155            .strip_prefix(VERSION)
156            .and_then(|b64| STANDARD.decode(b64).ok())
157            .filter(|bytes| bytes.len() > NONCE_LEN)
158            .ok_or_else(failed)?;
159        let (nonce, sealed) = bytes.split_at(NONCE_LEN);
160        let nonce = XNonce::try_from(nonce).map_err(|_| failed())?;
161        let plain = self
162            .cipher()
163            .decrypt(
164                &nonce,
165                Payload {
166                    msg: sealed,
167                    aad: aad.as_bytes(),
168                },
169            )
170            .map_err(|_| failed())?;
171        String::from_utf8(plain).map_err(|_| failed())
172    }
173}
174
175/// A secret path and its key names (never the values), for `schedr secrets list`.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct SecretEntry {
178    /// The path.
179    pub path: String,
180    /// Its keys' names.
181    pub keys: Vec<String>,
182    /// When it was last written.
183    pub updated_at: String,
184}
185
186impl Database {
187    /// Sets `values` in the secret at `path`, encrypted under `key`: the given keys are
188    /// written, the others kept (the secret is made if it doesn't exist).
189    ///
190    /// # Errors
191    ///
192    /// [`SecretsError`] if a value can't be encrypted or the database fails.
193    pub async fn set_secret(
194        &self,
195        key: &SecretKey,
196        path: &str,
197        values: &BTreeMap<String, String>,
198        now: Timestamp,
199    ) -> Result<(), SecretsError> {
200        // One statement merging in the database: two writes to one path at once both keep
201        // their keys (a read, a merge here and a write lost one on Postgres; Codex's finding).
202        const UPSERT: &str = "INSERT INTO secrets (path, data, created_at, updated_at) \
203            VALUES ($1, $2{json}, $3{ts}, $3{ts}) \
204            ON CONFLICT (path) DO UPDATE SET data = {merged}, \
205            updated_at = excluded.updated_at";
206        let mut sealed = BTreeMap::new();
207        for (name, value) in values {
208            sealed.insert(name.clone(), key.encrypt(path, name, value)?);
209        }
210        let text = storable_json(serde_json::to_string(&sealed).unwrap_or_default());
211        in_tx!(self, |tx, backend| {
212            // An object's keys given replace the stored ones, the others are kept.
213            let merged = match backend {
214                Backend::Postgres => "secrets.data || excluded.data",
215                Backend::Sqlite => "json_patch(secrets.data, excluded.data)",
216            };
217            let query = UPSERT.replace("{merged}", merged);
218            sqlx::query(sql_text(backend, &query))
219                .bind(path)
220                .bind(&text)
221                .bind(db_time(now))
222                .execute(&mut *tx)
223                .await?;
224        });
225        Ok(())
226    }
227
228    /// The secret at `path`, its values decrypted; `None` if there is none.
229    ///
230    /// # Errors
231    ///
232    /// [`SecretsError`] if a value doesn't decrypt under `key` or the database fails.
233    pub async fn secret(
234        &self,
235        key: &SecretKey,
236        path: &str,
237    ) -> Result<Option<BTreeMap<String, String>>, SecretsError> {
238        const READ: &str = "SELECT data{text} FROM secrets WHERE path = $1";
239        let stored: Option<(String,)> = on_pool!(self, |pool, backend| {
240            sqlx::query_as(sql(backend, READ))
241                .bind(path)
242                .fetch_optional(pool)
243                .await?
244        });
245        let Some((text,)) = stored else {
246            return Ok(None);
247        };
248        let data: BTreeMap<String, String> = from_json("secrets.data", &text)?;
249        data.iter()
250            .map(|(name, sealed)| Ok((name.clone(), key.decrypt(path, name, sealed)?)))
251            .collect::<Result<_, SecretsError>>()
252            .map(Some)
253    }
254
255    /// The secrets whose path starts with `prefix`, by path: their key names, never values.
256    ///
257    /// # Errors
258    ///
259    /// [`DbError`] if the query fails or stored data doesn't read.
260    pub async fn secret_entries(&self, prefix: &str) -> Result<Vec<SecretEntry>, DbError> {
261        const LIST: &str = "SELECT path, data{text}, {ts<}updated_at{>ts} FROM secrets \
262            ORDER BY path";
263        let rows: Vec<(String, String, String)> = on_pool!(self, |pool, backend| {
264            sqlx::query_as(sql(backend, LIST)).fetch_all(pool).await?
265        });
266        rows.into_iter()
267            .filter(|(path, _, _)| path.starts_with(prefix))
268            .map(|(path, text, updated_at)| {
269                let data: BTreeMap<String, String> = from_json("secrets.data", &text)?;
270                Ok(SecretEntry {
271                    path,
272                    keys: data.into_keys().collect(),
273                    updated_at,
274                })
275            })
276            .collect()
277    }
278
279    /// Removes the secret at `path`; `false` if there was none.
280    ///
281    /// # Errors
282    ///
283    /// [`DbError::Sqlx`] if the statement fails.
284    pub async fn delete_secret(&self, path: &str) -> Result<bool, DbError> {
285        const DELETE: &str = "DELETE FROM secrets WHERE path = $1";
286        let mut removed = 0;
287        in_tx!(self, |tx, backend| {
288            removed = sqlx::query(sql(backend, DELETE))
289                .bind(path)
290                .execute(&mut *tx)
291                .await?
292                .rows_affected();
293        });
294        Ok(removed > 0)
295    }
296}