Skip to main content

secure_env/
store.rs

1use age::secrecy::SecretString;
2use anyhow::{Context, Result};
3use std::collections::BTreeMap;
4use std::fs;
5use std::path::Path;
6
7use crate::crypto;
8
9pub type Sets = BTreeMap<String, BTreeMap<String, String>>;
10
11/// A valid shell environment variable name: starts with a letter or `_`, then
12/// only letters, digits, or `_`.
13pub fn is_valid_env_name(name: &str) -> bool {
14    let mut chars = name.chars();
15    match chars.next() {
16        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
17        _ => return false,
18    }
19    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
20}
21
22pub fn read_plain(path: &Path, passphrase: SecretString) -> Result<Option<Sets>> {
23    if !path.exists() {
24        return Ok(None);
25    }
26    let ciphertext =
27        fs::read(path).with_context(|| format!("failed to read {}", path.display()))?;
28    let plaintext = crypto::decrypt(&ciphertext, passphrase)?;
29    let sets = from_toml(&plaintext)?;
30    Ok(Some(sets))
31}
32
33pub fn from_toml(bytes: &[u8]) -> Result<Sets> {
34    let text = std::str::from_utf8(bytes).context("decrypted data is not valid UTF-8")?;
35    toml::from_str(text).context("decrypted data is not valid TOML")
36}
37
38pub fn to_toml(sets: &Sets) -> String {
39    toml::to_string_pretty(sets).expect("sets serialize to TOML")
40}
41
42/// Atomically write `bytes` to `path` via a temp file and rename.
43pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
44    let dir = path.parent().unwrap_or_else(|| Path::new("."));
45    fs::create_dir_all(dir).with_context(|| format!("failed to create {}", dir.display()))?;
46    let file_name = path
47        .file_name()
48        .map(|n| n.to_string_lossy().into_owned())
49        .unwrap_or_else(|| "secure-env.enc".to_string());
50    let tmp = dir.join(format!(".{file_name}.tmp.{}", std::process::id()));
51    fs::write(&tmp, bytes).with_context(|| format!("failed to write {}", tmp.display()))?;
52    fs::rename(&tmp, path)
53        .with_context(|| format!("failed to move {} into place", tmp.display()))?;
54    Ok(())
55}