Skip to main content

schedr_bin/
secrets.rs

1//! `schedr secrets ...`: the `db` secret storage, straight in the database as `schedr db` is
2//! (see archive/PROJECT.md, Secret storage). Values are encrypted under `SCHEDR_SECRET_KEY`; only
3//! `get` prints one, `list` shows paths and key names, `export` writes files for Vault
4//! (decision 170) and prints none.
5
6use std::collections::BTreeMap;
7use std::fs::{self, DirBuilder, OpenOptions};
8use std::io::{self, Read, Write};
9use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _};
10use std::path::{Path, PathBuf};
11
12use jiff::Timestamp;
13use schedr_config::config::Config;
14use schedr_db::secrets::{SecretKey, SecretsError};
15use schedr_db::{Database, redact_password};
16use schedr_model::SecretName;
17
18use crate::app::{AppError, describe_status};
19use crate::cli::SecretsCommand;
20
21#[cfg(test)]
22mod tests;
23
24/// Runs a `schedr secrets` command; `stdin` gives a `key=-` value.
25///
26/// # Errors
27///
28/// [`AppError::BadArgument`] for a bad path, key or value, or a missing key;
29/// [`AppError::Failed`] for a secret that isn't there, or a value that doesn't decrypt;
30/// [`AppError::Db`] when the database fails.
31pub async fn run(
32    command: &SecretsCommand,
33    config: &Config,
34    env: &BTreeMap<String, String>,
35    stdin: &mut impl Read,
36    out: &mut impl Write,
37) -> Result<(), AppError> {
38    if *command == SecretsCommand::NewKey {
39        let key = SecretKey::generate().map_err(secrets_error)?;
40        writeln!(out, "{}", key.to_base64())?;
41        return Ok(());
42    }
43    let db = connect(config, env).await?;
44    match command {
45        SecretsCommand::Set { path, values } => {
46            check_path(path)?;
47            let values = read_values(path, values, stdin)?;
48            let key = SecretKey::from_env(env).map_err(secrets_error)?;
49            db.set_secret(&key, path, &values, Timestamp::now())
50                .await
51                .map_err(secrets_error)?;
52            let keys: Vec<&str> = values.keys().map(String::as_str).collect();
53            writeln!(out, "set `{path}`: {}", keys.join(", "))?;
54        }
55        SecretsCommand::List { prefix } => {
56            for entry in db.secret_entries(prefix.as_deref().unwrap_or("")).await? {
57                writeln!(
58                    out,
59                    "{}\t{}\t{}",
60                    entry.path,
61                    entry.keys.join(","),
62                    entry.updated_at
63                )?;
64            }
65        }
66        SecretsCommand::Get { secret } => {
67            let (path, wanted) = match secret.split_once('#') {
68                Some((path, key)) => (path, Some(key)),
69                None => (secret.as_str(), None),
70            };
71            SecretName::new(path, wanted)
72                .check()
73                .map_err(AppError::BadArgument)?;
74            let key = SecretKey::from_env(env).map_err(secrets_error)?;
75            let data = db
76                .secret(&key, path)
77                .await
78                .map_err(secrets_error)?
79                .ok_or_else(|| AppError::Failed(format!("no secret `{path}`")))?;
80            match wanted {
81                Some(wanted) => {
82                    let value = data.get(wanted).ok_or_else(|| {
83                        AppError::Failed(format!("the secret `{path}` has no key `{wanted}`"))
84                    })?;
85                    writeln!(out, "{value}")?;
86                }
87                None => writeln!(
88                    out,
89                    "{}",
90                    serde_json::to_string_pretty(&data).unwrap_or_default()
91                )?,
92            }
93        }
94        SecretsCommand::Delete { path } => {
95            if !db.delete_secret(path).await? {
96                return Err(AppError::Failed(format!("no secret `{path}`")));
97            }
98            writeln!(out, "deleted `{path}`")?;
99        }
100        SecretsCommand::Export { to } => {
101            let key = SecretKey::from_env(env).map_err(secrets_error)?;
102            let count = export(&db, &key, to).await?;
103            writeln!(
104                out,
105                "exported {count} secret(s) to {dir}: load each with `vault kv put \
106                 secret/<path> @{dir}/<path>.json`, then remove the directory",
107                dir = to.display()
108            )?;
109        }
110        SecretsCommand::NewKey => {}
111    }
112    Ok(())
113}
114
115/// The database the `db` storage is in: `[database] url`, else standalone's own SQLite file
116/// in the data directory; its schema must be up to date.
117async fn connect(config: &Config, env: &BTreeMap<String, String>) -> Result<Database, AppError> {
118    let url = if let Some(url) = &config.database.url {
119        url.clone()
120    } else {
121        let file = crate::standalone::sqlite_file(&crate::roles::data_dir(config, env)?);
122        if !file.exists() {
123            return Err(AppError::BadArgument(format!(
124                "no database: set `SCHEDR_CONFIG__DATABASE__URL` (or [database] url), or \
125                 start `schedr standalone --migrate` once to make {}",
126                file.display()
127            )));
128        }
129        format!("sqlite://{}", file.display())
130    };
131    let db = Database::connect(&url).await?;
132    let status = db.schema_status().await?;
133    if !status.is_usable() {
134        return Err(AppError::Failed(format!(
135            "{}: {}",
136            redact_password(&url),
137            describe_status(&status)
138        )));
139    }
140    Ok(db)
141}
142
143fn secrets_error(error: SecretsError) -> AppError {
144    match error {
145        SecretsError::Db(error) => AppError::Db(error),
146        SecretsError::Key(message) => AppError::BadArgument(message),
147        error @ SecretsError::Decrypt(_) => AppError::Failed(error.to_string()),
148    }
149}
150
151/// A path as a DAG names it, and one `export` can make a file of: no `.` or `..` part.
152fn check_path(path: &str) -> Result<(), AppError> {
153    SecretName::new(path, None)
154        .check()
155        .map_err(AppError::BadArgument)?;
156    if path.split('/').any(|part| part == "." || part == "..") {
157        return Err(AppError::BadArgument(format!(
158            "`{path}`: a path has no `.` or `..` part"
159        )));
160    }
161    no_control(path, "path")
162}
163
164/// A path or key name without control characters: `list` writes one per line, and a file
165/// name is made of it (Grok's finding in M4.6c's review).
166fn no_control(name: &str, what: &str) -> Result<(), AppError> {
167    if name.chars().any(char::is_control) {
168        return Err(AppError::BadArgument(format!(
169            "{name:?}: a {what} has no control characters (a newline, a tab)"
170        )));
171    }
172    Ok(())
173}
174
175/// `key=value`, `key=@FILE` and `key=-` read into the values to set.
176fn read_values(
177    path: &str,
178    args: &[String],
179    stdin: &mut impl Read,
180) -> Result<BTreeMap<String, String>, AppError> {
181    let mut values = BTreeMap::new();
182    let mut stdin_used = false;
183    for arg in args {
184        // Not echoed: it may be a value given without its key.
185        let Some((key, value)) = arg.split_once('=') else {
186            return Err(AppError::BadArgument(
187                "each value is KEY=VALUE, KEY=@FILE or KEY=-".to_owned(),
188            ));
189        };
190        SecretName::new(path, Some(key))
191            .check()
192            .map_err(AppError::BadArgument)?;
193        no_control(key, "key")?;
194        let value = if value == "-" {
195            if stdin_used {
196                return Err(AppError::BadArgument(
197                    "only one value can be read from standard input (`KEY=-`)".to_owned(),
198                ));
199            }
200            stdin_used = true;
201            let mut text = String::new();
202            stdin.read_to_string(&mut text).map_err(|e| {
203                AppError::BadArgument(format!("`{key}`: can't read standard input: {e}"))
204            })?;
205            let trimmed = text
206                .strip_suffix("\r\n")
207                .or_else(|| text.strip_suffix('\n'))
208                .map(str::to_owned);
209            trimmed.unwrap_or(text)
210        } else if let Some(file) = value.strip_prefix('@') {
211            fs::read_to_string(file).map_err(|e| {
212                AppError::BadArgument(format!("`{key}`: can't read `{file}` as text: {e}"))
213            })?
214        } else {
215            value.to_owned()
216        };
217        if values.insert(key.to_owned(), value).is_some() {
218            return Err(AppError::BadArgument(format!("`{key}` is given twice")));
219        }
220    }
221    Ok(values)
222}
223
224/// Writes each secret to `dir/<path>.json` (mode 0600, directories 0700); `dir` must be
225/// empty or missing, so no file of another's is overwritten or followed. Every secret is read
226/// and every path checked first: nothing is written unless all of them can be.
227async fn export(db: &Database, key: &SecretKey, dir: &Path) -> Result<usize, AppError> {
228    let failed = |what: &Path, e: io::Error| {
229        AppError::Failed(format!("can't write `{}`: {e}", what.display()))
230    };
231    let mut secrets = Vec::new();
232    for entry in db.secret_entries("").await? {
233        check_path(&entry.path)?;
234        let data = db
235            .secret(key, &entry.path)
236            .await
237            .map_err(secrets_error)?
238            .unwrap_or_default();
239        secrets.push((entry.path, data));
240    }
241    check_files(secrets.iter().map(|(path, _)| path.as_str()))?;
242    // The directory named, not one a link leads to.
243    if fs::symlink_metadata(dir).is_ok_and(|m| m.file_type().is_symlink()) {
244        return Err(AppError::BadArgument(format!(
245            "`{}` is a symbolic link: export writes to a directory of its own",
246            dir.display()
247        )));
248    }
249    match fs::read_dir(dir) {
250        Ok(mut entries) => {
251            if entries.next().is_some() {
252                return Err(AppError::BadArgument(format!(
253                    "`{}` isn't empty: export writes to an empty or new directory",
254                    dir.display()
255                )));
256            }
257        }
258        Err(e) if e.kind() == io::ErrorKind::NotFound => {
259            private_dirs().create(dir).map_err(|e| failed(dir, e))?;
260        }
261        Err(e) => return Err(failed(dir, e)),
262    }
263    // A write that fails (a full disk) removes the files written before it: no export is
264    // left half done (Grok's finding in M4.6c's review).
265    let mut written = Vec::new();
266    for (path, data) in &secrets {
267        let file: PathBuf = dir.join(format!("{path}.json"));
268        if let Err(error) = write_secret(&file, data, &mut written) {
269            for file in &written {
270                let _ = fs::remove_file(file);
271            }
272            return Err(failed(&file, error));
273        }
274    }
275    Ok(secrets.len())
276}
277
278/// Refuses two paths export can't write side by side: `a` (the file `a.json`) and `a.json/b`
279/// (in the directory `a.json`), found by Codex in M4.6c's review.
280fn check_files<'a>(paths: impl Iterator<Item = &'a str> + Clone) -> Result<(), AppError> {
281    let files: BTreeMap<String, &str> = paths.clone().map(|p| (format!("{p}.json"), p)).collect();
282    for path in paths {
283        let mut prefix = String::new();
284        let parts: Vec<&str> = path.split('/').collect();
285        for part in &parts[..parts.len() - 1] {
286            if !prefix.is_empty() {
287                prefix.push('/');
288            }
289            prefix.push_str(part);
290            if let Some(other) = files.get(&prefix) {
291                return Err(AppError::BadArgument(format!(
292                    "`{other}` and `{path}` can't both be exported: `{prefix}` would be its \
293                     file and a directory (rename one with `set` and `delete`)"
294                )));
295            }
296        }
297    }
298    Ok(())
299}
300
301/// Writes one secret's file (its directories first), noting it in `written` once it exists.
302fn write_secret(
303    file: &Path,
304    data: &BTreeMap<String, String>,
305    written: &mut Vec<PathBuf>,
306) -> io::Result<()> {
307    if let Some(parent) = file.parent() {
308        private_dirs().create(parent)?;
309    }
310    let mut handle = OpenOptions::new()
311        .write(true)
312        .create_new(true)
313        .mode(0o600)
314        .open(file)?;
315    written.push(file.to_path_buf());
316    let text = serde_json::to_string_pretty(data).unwrap_or_default();
317    handle.write_all(format!("{text}\n").as_bytes())
318}
319
320fn private_dirs() -> DirBuilder {
321    let mut builder = DirBuilder::new();
322    builder.recursive(true).mode(0o700);
323    builder
324}