Skip to main content

second_brain_core/
api_token.rs

1use std::fs::OpenOptions;
2use std::io::Write;
3use std::os::unix::fs::OpenOptionsExt;
4use std::path::{Path, PathBuf};
5
6use anyhow::{Context, Result};
7use fs4::fs_std::FileExt;
8use rand::TryRngCore;
9
10const FILE_NAME: &str = "api.token";
11const LOCK_NAME: &str = ".api.token.lock";
12
13pub fn path(data_dir: &Path) -> PathBuf {
14    data_dir.join(FILE_NAME)
15}
16
17pub fn ensure(data_dir: &Path) -> Result<String> {
18    std::fs::create_dir_all(data_dir)
19        .with_context(|| format!("creating {}", data_dir.display()))?;
20    let lock_path = data_dir.join(LOCK_NAME);
21    let lock = OpenOptions::new()
22        .create(true)
23        .truncate(false)
24        .write(true)
25        .mode(0o600)
26        .open(&lock_path)
27        .with_context(|| format!("opening {}", lock_path.display()))?;
28    lock.lock_exclusive()
29        .with_context(|| format!("locking {}", lock_path.display()))?;
30
31    let target = path(data_dir);
32    match std::fs::read_to_string(&target) {
33        Ok(content) if !content.trim().is_empty() => return Ok(content.trim().to_string()),
34        Ok(_) => {}
35        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
36        Err(e) => return Err(e).with_context(|| format!("reading {}", target.display())),
37    }
38
39    let token = hex(&random_bytes::<32>()?);
40    let tmp = data_dir.join(format!(".{FILE_NAME}.{}", hex(&random_bytes::<8>()?)));
41    if let Err(e) = write_private(&tmp, &token) {
42        if let Err(cleanup) = std::fs::remove_file(&tmp) {
43            tracing::warn!("could not remove {}: {cleanup}", tmp.display());
44        }
45        return Err(e);
46    }
47    std::fs::rename(&tmp, &target).with_context(|| format!("creating {}", target.display()))?;
48    Ok(token)
49}
50
51pub fn read(data_dir: &Path) -> Result<String> {
52    let path = path(data_dir);
53    let content = std::fs::read_to_string(&path).with_context(|| {
54        format!(
55            "cannot read the daemon API token at {}; the daemon creates it when it starts, \
56             so start the daemon as this user or run as the user the daemon runs as",
57            path.display()
58        )
59    })?;
60    let token = content.trim();
61    if token.is_empty() {
62        anyhow::bail!(
63            "the daemon API token at {} is empty; restart the daemon to regenerate it",
64            path.display()
65        );
66    }
67    Ok(token.to_string())
68}
69
70fn write_private(path: &Path, token: &str) -> Result<()> {
71    let mut file = OpenOptions::new()
72        .write(true)
73        .create_new(true)
74        .mode(0o600)
75        .open(path)
76        .with_context(|| format!("creating {}", path.display()))?;
77    file.write_all(format!("{token}\n").as_bytes())?;
78    file.sync_all()?;
79    Ok(())
80}
81
82fn random_bytes<const N: usize>() -> Result<[u8; N]> {
83    let mut bytes = [0u8; N];
84    rand::rngs::OsRng
85        .try_fill_bytes(&mut bytes)
86        .map_err(|e| anyhow::anyhow!("reading OS randomness: {e}"))?;
87    Ok(bytes)
88}
89
90fn hex(bytes: &[u8]) -> String {
91    bytes.iter().map(|b| format!("{b:02x}")).collect()
92}
93
94#[cfg(test)]
95mod tests {
96    use std::os::unix::fs::PermissionsExt;
97
98    use super::*;
99
100    fn mode(p: &Path) -> u32 {
101        std::fs::metadata(p).unwrap().permissions().mode() & 0o777
102    }
103
104    #[test]
105    fn ensure_creates_a_private_64_hex_char_token() {
106        let dir = tempfile::tempdir().unwrap();
107        let token = ensure(dir.path()).unwrap();
108        assert_eq!(token.len(), 64);
109        assert!(token.bytes().all(|b| b.is_ascii_hexdigit()));
110        assert_eq!(mode(&path(dir.path())), 0o600);
111        assert_eq!(read(dir.path()).unwrap(), token);
112    }
113
114    #[test]
115    fn ensure_creates_a_missing_data_dir() {
116        let dir = tempfile::tempdir().unwrap();
117        let nested = dir.path().join("a/b");
118        let token = ensure(&nested).unwrap();
119        assert_eq!(read(&nested).unwrap(), token);
120    }
121
122    #[test]
123    fn ensure_keeps_an_existing_token() {
124        let dir = tempfile::tempdir().unwrap();
125        let first = ensure(dir.path()).unwrap();
126        assert_eq!(ensure(dir.path()).unwrap(), first);
127    }
128
129    #[test]
130    fn ensure_replaces_an_empty_token_file() {
131        let dir = tempfile::tempdir().unwrap();
132        std::fs::write(path(dir.path()), "\n").unwrap();
133        let token = ensure(dir.path()).unwrap();
134        assert_eq!(token.len(), 64);
135        assert_eq!(read(dir.path()).unwrap(), token);
136        assert_eq!(mode(&path(dir.path())), 0o600);
137    }
138
139    #[test]
140    fn tokens_differ_between_installs() {
141        let a = tempfile::tempdir().unwrap();
142        let b = tempfile::tempdir().unwrap();
143        assert_ne!(ensure(a.path()).unwrap(), ensure(b.path()).unwrap());
144    }
145
146    #[test]
147    fn racing_creators_all_get_the_same_complete_token() {
148        let dir = tempfile::tempdir().unwrap();
149        let tokens: Vec<String> = std::thread::scope(|s| {
150            let handles: Vec<_> = (0..16)
151                .map(|_| s.spawn(|| ensure(dir.path()).unwrap()))
152                .collect();
153            handles.into_iter().map(|h| h.join().unwrap()).collect()
154        });
155        assert!(tokens.iter().all(|t| t == &tokens[0]), "{tokens:?}");
156        assert_eq!(read(dir.path()).unwrap(), tokens[0]);
157        let mut leftovers: Vec<_> = std::fs::read_dir(dir.path())
158            .unwrap()
159            .map(|e| e.unwrap().file_name())
160            .collect();
161        leftovers.sort();
162        assert_eq!(leftovers, [LOCK_NAME, FILE_NAME]);
163    }
164
165    #[test]
166    fn racing_repairs_of_an_empty_token_agree() {
167        let dir = tempfile::tempdir().unwrap();
168        std::fs::write(path(dir.path()), "").unwrap();
169        let tokens: Vec<String> = std::thread::scope(|s| {
170            let handles: Vec<_> = (0..16)
171                .map(|_| s.spawn(|| ensure(dir.path()).unwrap()))
172                .collect();
173            handles.into_iter().map(|h| h.join().unwrap()).collect()
174        });
175        assert!(tokens.iter().all(|t| t == &tokens[0]), "{tokens:?}");
176        assert_eq!(read(dir.path()).unwrap(), tokens[0]);
177    }
178
179    #[test]
180    fn read_errors_name_the_path_when_missing() {
181        let dir = tempfile::tempdir().unwrap();
182        let err = format!("{:#}", read(dir.path()).unwrap_err());
183        assert!(
184            err.contains(&path(dir.path()).display().to_string()),
185            "{err}"
186        );
187    }
188
189    #[test]
190    fn read_rejects_an_empty_token() {
191        let dir = tempfile::tempdir().unwrap();
192        std::fs::write(path(dir.path()), "").unwrap();
193        let err = format!("{:#}", read(dir.path()).unwrap_err());
194        assert!(err.contains("api.token"), "{err}");
195    }
196}