1use std::{
12 fmt, fs,
13 io::Write,
14 path::{Path, PathBuf},
15};
16
17const TOKEN_BYTES: usize = 32;
19
20const TOKEN_FILENAME: &str = ".dora-token";
22
23#[derive(Clone)]
28pub struct AuthToken(String);
29
30impl AuthToken {
31 pub fn from_hex(hex: impl Into<String>) -> Self {
33 Self(hex.into())
34 }
35
36 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
48pub 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
60pub 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
68pub fn token_path(working_dir: &Path) -> PathBuf {
70 working_dir.join(TOKEN_FILENAME)
71}
72
73pub fn config_token_path() -> Option<PathBuf> {
78 dirs::config_dir().map(|d| d.join("dora").join(TOKEN_FILENAME))
79}
80
81pub 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 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 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 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
159pub 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 #[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
209pub fn discover_token() -> Option<AuthToken> {
216 if let Ok(val) = std::env::var("DORA_AUTH_TOKEN")
218 && !val.is_empty()
219 {
220 return Some(AuthToken(val));
221 }
222
223 if let Ok(cwd) = std::env::current_dir()
225 && let Ok(Some(token)) = read_token(&cwd)
226 {
227 return Some(token);
228 }
229
230 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#[cfg(kani)]
243mod verification {
244 use super::constant_time_eq;
245
246 const MAX_LEN: usize = 8;
251
252 #[kani::proof]
256 #[kani::unwind(9)] 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 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 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 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}