1use 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
26pub const SECRET_KEY_ENV: &str = "SCHEDR_SECRET_KEY";
28
29const VERSION: &str = "v1:";
31
32const NONCE_LEN: usize = 24;
34
35#[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#[derive(Debug, thiserror::Error)]
47pub enum SecretsError {
48 #[error("{0}")]
50 Key(String),
51 #[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 #[error(transparent)]
59 Db(#[from] DbError),
60}
61
62impl SecretKey {
63 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 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 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 #[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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct SecretEntry {
178 pub path: String,
180 pub keys: Vec<String>,
182 pub updated_at: String,
184}
185
186impl Database {
187 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 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 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 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 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 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}