Skip to main content

dora_message/
auth.rs

1//! Shared-token authentication for coordinator connections.
2//!
3//! Authentication is opt-in. With `--auth` (`dora up --auth` or
4//! `dora coordinator --auth`) the coordinator generates a random hex token on
5//! startup and writes it to a well-known file. The CLI and daemons read this
6//! file before connecting and send the token in an `Authorization: Bearer
7//! <hex>` header on the WebSocket upgrade request. The coordinator ignores a
8//! `?token=<hex>` query parameter, so a client that passes the token only in
9//! the URL cannot authenticate against a coordinator that has auth enabled.
10
11use std::{
12    fmt, fs,
13    io::Write,
14    path::{Path, PathBuf},
15};
16
17/// Length of the raw token in bytes (32 bytes = 64 hex chars).
18const TOKEN_BYTES: usize = 32;
19
20/// File name used for storing the auth token.
21const TOKEN_FILENAME: &str = ".dora-token";
22
23/// Opaque authentication token.
24///
25/// `PartialEq`/`Eq` are intentionally not derived to prevent accidental
26/// non-constant-time comparisons. Use [`constant_time_eq`] instead.
27#[derive(Clone)]
28pub struct AuthToken(String);
29
30impl AuthToken {
31    /// Create a token from a hex string (e.g. read from file or env var).
32    pub fn from_hex(hex: impl Into<String>) -> Self {
33        Self(hex.into())
34    }
35
36    /// Return the hex representation.
37    pub fn as_hex(&self) -> &str {
38        &self.0
39    }
40}
41
42impl fmt::Debug for AuthToken {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(f, "AuthToken(***)")
45    }
46}
47
48/// Constant-time byte comparison to prevent timing side-channel attacks.
49pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
50    if a.len() != b.len() {
51        return false;
52    }
53    let mut diff = 0u8;
54    for (x, y) in a.iter().zip(b.iter()) {
55        diff |= x ^ y;
56    }
57    diff == 0
58}
59
60/// Generate a cryptographically random 32-byte token.
61pub fn generate_token() -> AuthToken {
62    let mut buf = [0u8; TOKEN_BYTES];
63    getrandom::fill(&mut buf).expect("failed to generate random bytes");
64    let hex: String = buf.iter().map(|b| format!("{b:02x}")).collect();
65    AuthToken(hex)
66}
67
68/// Compute the token file path for a given working directory.
69pub fn token_path(working_dir: &Path) -> PathBuf {
70    working_dir.join(TOKEN_FILENAME)
71}
72
73/// Return the token path inside the user's config directory
74/// (e.g. `~/.config/dora/.dora-token` on Linux).
75///
76/// Returns `None` if no config directory can be determined.
77pub fn config_token_path() -> Option<PathBuf> {
78    dirs::config_dir().map(|d| d.join("dora").join(TOKEN_FILENAME))
79}
80
81/// Write the token to `<working_dir>/.dora-token` **and** to the user config
82/// directory (e.g. `~/.config/dora/.dora-token`).
83///
84/// On Unix, each file is written to a fresh `0o600` inode that replaces the
85/// old one, so the secret is never readable by other users.
86pub fn write_token(working_dir: &Path, token: &AuthToken) -> std::io::Result<()> {
87    write_token_with_config_copy(
88        &token_path(working_dir),
89        config_token_path().as_deref(),
90        token,
91    )
92}
93
94fn write_token_with_config_copy(
95    path: &Path,
96    config_path: Option<&Path>,
97    token: &AuthToken,
98) -> std::io::Result<()> {
99    let result = write_token_to(path, token);
100
101    // Best-effort write to config dir so CLIs in other directories can find
102    // it — attempted even if the working-dir write failed.
103    if let Some(config_path) = config_path {
104        if let Some(parent) = config_path.parent() {
105            let _ = fs::create_dir_all(parent);
106        }
107        if let Err(e) = write_token_to(config_path, token) {
108            log::warn!("failed to write token to config dir: {e}");
109        }
110    }
111
112    result
113}
114
115fn write_token_to(path: &Path, token: &AuthToken) -> std::io::Result<()> {
116    #[cfg(unix)]
117    {
118        use std::os::unix::fs::OpenOptionsExt;
119        // Write a fresh 0600 inode and rename it over `path` instead of
120        // reusing an existing file: `mode` only applies on creation, and
121        // tightening an existing file's mode does not revoke descriptors
122        // other users already hold on it. `create_new` (O_EXCL) also refuses
123        // to follow a symlink planted at the temporary path, and the rename
124        // replaces a symlink at `path` rather than writing through it.
125        let file_name = path
126            .file_name()
127            .ok_or_else(|| std::io::Error::other("token path has no file name"))?;
128        let mut tmp_name = std::ffi::OsString::from(".");
129        tmp_name.push(file_name);
130        tmp_name.push(format!(".tmp-{}", std::process::id()));
131        let tmp = path.with_file_name(tmp_name);
132        // A leftover from a crashed write by this pid would block `create_new`.
133        let _ = fs::remove_file(&tmp);
134
135        let written = (|| {
136            let mut file = fs::OpenOptions::new()
137                .write(true)
138                .create_new(true)
139                .mode(0o600)
140                .open(&tmp)?;
141            file.write_all(token.as_hex().as_bytes())?;
142            file.write_all(b"\n")?;
143            fs::rename(&tmp, path)
144        })();
145        if written.is_err() {
146            let _ = fs::remove_file(&tmp);
147        }
148        written?;
149    }
150    #[cfg(not(unix))]
151    {
152        let mut file = fs::File::create(path)?;
153        file.write_all(token.as_hex().as_bytes())?;
154        file.write_all(b"\n")?;
155    }
156    Ok(())
157}
158
159/// Read the token from `<working_dir>/.dora-token`.
160///
161/// Returns `None` if the file does not exist.
162pub fn read_token(working_dir: &Path) -> std::io::Result<Option<AuthToken>> {
163    read_token_from_path(&token_path(working_dir))
164}
165
166fn read_token_from_path(path: &Path) -> std::io::Result<Option<AuthToken>> {
167    let file = match fs::File::open(path) {
168        Ok(f) => f,
169        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
170        Err(e) => return Err(e),
171    };
172
173    // On Unix, verify ownership/permissions on the *open* fd (fstat) to
174    // avoid a TOCTOU race between read and metadata check.
175    #[cfg(unix)]
176    {
177        use std::os::unix::fs::MetadataExt;
178        if let Ok(meta) = file.metadata() {
179            let uid = unsafe { libc::geteuid() };
180            if meta.uid() != uid {
181                log::warn!(
182                    "ignoring token file {} (owned by uid {}, expected {})",
183                    path.display(),
184                    meta.uid(),
185                    uid
186                );
187                return Ok(None);
188            }
189            if meta.mode() & 0o077 != 0 {
190                log::warn!(
191                    "ignoring token file {} (mode {:o} is too permissive, expected 0600)",
192                    path.display(),
193                    meta.mode() & 0o777
194                );
195                return Ok(None);
196            }
197        }
198    }
199
200    let content = std::io::read_to_string(file)?;
201    let trimmed = content.trim();
202    if trimmed.is_empty() {
203        Ok(None)
204    } else {
205        Ok(Some(AuthToken(trimmed.to_string())))
206    }
207}
208
209/// Attempt to read the auth token from (in order):
210/// 1. `DORA_AUTH_TOKEN` environment variable
211/// 2. `<cwd>/.dora-token` file
212/// 3. User config directory (e.g. `~/.config/dora/.dora-token`)
213///
214/// Returns `None` if no token is found.
215pub fn discover_token() -> Option<AuthToken> {
216    // 1. Environment variable override
217    if let Ok(val) = std::env::var("DORA_AUTH_TOKEN")
218        && !val.is_empty()
219    {
220        return Some(AuthToken(val));
221    }
222
223    // 2. Token file in current working directory
224    if let Ok(cwd) = std::env::current_dir()
225        && let Ok(Some(token)) = read_token(&cwd)
226    {
227        return Some(token);
228    }
229
230    // 3. Token file in user config directory
231    if let Some(config_path) = config_token_path()
232        && let Ok(Some(token)) = read_token_from_path(&config_path)
233    {
234        return Some(token);
235    }
236
237    None
238}
239
240/// Kani proof harnesses (`make qa-kani`). Compiled only under `cargo kani`,
241/// never in normal builds or tests. See `docs/formal-verification.md`.
242#[cfg(kani)]
243mod verification {
244    use super::constant_time_eq;
245
246    /// Maximum slice length explored by the proofs. Token comparison inputs
247    /// are attacker-controlled strings of arbitrary length, but the loop
248    /// body is length-uniform, so a small bound suffices to cover all
249    /// control-flow paths (equal/unequal lengths, differing byte positions).
250    const MAX_LEN: usize = 8;
251
252    /// Functional correctness: `constant_time_eq` agrees with `==` on all
253    /// slice pairs up to `MAX_LEN`, including length mismatches and the
254    /// empty slice. Also proves the function never panics on these inputs.
255    #[kani::proof]
256    #[kani::unwind(9)] // MAX_LEN + 1
257    fn constant_time_eq_matches_slice_equality() {
258        let a: [u8; MAX_LEN] = kani::any();
259        let b: [u8; MAX_LEN] = kani::any();
260        let a_len: usize = kani::any();
261        let b_len: usize = kani::any();
262        kani::assume(a_len <= MAX_LEN);
263        kani::assume(b_len <= MAX_LEN);
264        assert_eq!(
265            constant_time_eq(&a[..a_len], &b[..b_len]),
266            a[..a_len] == b[..b_len]
267        );
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[test]
276    fn generate_token_is_64_hex_chars() {
277        let token = generate_token();
278        assert_eq!(token.as_hex().len(), 64);
279        assert!(token.as_hex().chars().all(|c| c.is_ascii_hexdigit()));
280    }
281
282    #[test]
283    fn generate_tokens_are_unique() {
284        let a = generate_token();
285        let b = generate_token();
286        assert_ne!(a.as_hex(), b.as_hex());
287    }
288
289    #[test]
290    fn write_and_read_token() {
291        let dir = tempfile::tempdir().unwrap();
292
293        let token = generate_token();
294        write_token(dir.path(), &token).unwrap();
295
296        let read_back = read_token(dir.path()).unwrap().unwrap();
297        assert_eq!(token.as_hex(), read_back.as_hex());
298    }
299
300    #[cfg(unix)]
301    #[test]
302    fn write_token_tightens_an_existing_permissive_file() {
303        use std::os::unix::fs::PermissionsExt;
304
305        let dir = tempfile::tempdir().unwrap();
306        let path = dir.path().join(".dora-token");
307        std::fs::write(&path, "stale token that is longer than the new one\n").unwrap();
308        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
309
310        // Another user who opened the loose file earlier keeps their fd.
311        let mut early_reader = std::fs::File::open(&path).unwrap();
312
313        let token = generate_token();
314        write_token_to(&path, &token).unwrap();
315
316        let mut seen = String::new();
317        std::io::Read::read_to_string(&mut early_reader, &mut seen).unwrap();
318        assert!(
319            !seen.contains(token.as_hex()),
320            "a descriptor opened before the write must not see the new secret"
321        );
322
323        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
324        assert_eq!(mode, 0o600, "the secret must not stay world-readable");
325        let read_back = read_token_from_path(&path).unwrap();
326        assert_eq!(
327            read_back.map(|t| t.as_hex().to_owned()),
328            Some(token.as_hex().to_owned())
329        );
330    }
331
332    #[test]
333    fn config_token_path_returns_some() {
334        // Should return a path on any system with a home directory
335        let path = config_token_path();
336        if let Some(p) = &path {
337            assert!(p.ends_with("dora/.dora-token"));
338        }
339    }
340
341    #[test]
342    fn write_token_creates_config_dir_copy() {
343        let dir = tempfile::tempdir().unwrap();
344        let token = generate_token();
345        write_token(dir.path(), &token).unwrap();
346
347        // Config dir copy is best-effort; just verify the working-dir copy works
348        let read_back = read_token(dir.path()).unwrap().unwrap();
349        assert_eq!(token.as_hex(), read_back.as_hex());
350    }
351
352    #[test]
353    fn config_copy_is_written_even_if_the_working_dir_write_fails() {
354        let dir = tempfile::tempdir().unwrap();
355        let unwritable = dir.path().join("missing-dir").join(".dora-token");
356        let config = dir.path().join("config").join(".dora-token");
357
358        let token = generate_token();
359        assert!(write_token_with_config_copy(&unwritable, Some(&config), &token).is_err());
360        let read_back = read_token_from_path(&config).unwrap().unwrap();
361        assert_eq!(read_back.as_hex(), token.as_hex());
362    }
363
364    #[test]
365    fn constant_time_eq_works() {
366        assert!(constant_time_eq(b"hello", b"hello"));
367        assert!(!constant_time_eq(b"hello", b"world"));
368        assert!(!constant_time_eq(b"hello", b"hell"));
369        assert!(!constant_time_eq(b"", b"x"));
370        assert!(constant_time_eq(b"", b""));
371    }
372}