1use std::fs;
4use std::path::{Path, PathBuf};
5use std::sync::Mutex;
6use std::time::Instant;
7
8use base32::Alphabet;
9use rand::rngs::OsRng;
10use rand::RngCore;
11
12use krot_proto::consts::{ADMIN_TOKEN_RAW_LEN, ADMIN_TOKEN_TTL};
13
14use crate::error::ServerError;
15
16const HASH_FILE: &str = "admin_token.hash";
17const ALPHABET: Alphabet = Alphabet::Crockford;
19
20#[derive(Debug)]
22pub struct AdminTokenStore {
23 data_dir: PathBuf,
24 state: Mutex<Option<TokenState>>,
25}
26
27#[derive(Debug)]
28struct TokenState {
29 hash: [u8; 32],
30 expires_at: Instant,
31}
32
33impl AdminTokenStore {
34 #[must_use]
35 pub fn new(data_dir: PathBuf) -> Self {
36 Self {
37 data_dir,
38 state: Mutex::new(None),
39 }
40 }
41
42 pub fn issue(&self) -> Result<String, ServerError> {
47 let mut raw = [0u8; ADMIN_TOKEN_RAW_LEN];
48 OsRng.fill_bytes(&mut raw);
49 let token = base32::encode(ALPHABET, &raw);
50 let hash = blake3::hash(token.as_bytes());
51
52 fs::create_dir_all(&self.data_dir)?;
53 let path = self.hash_path();
54 write_secret(&path, hash.as_bytes())?;
55
56 *self.state.lock().unwrap() = Some(TokenState {
57 hash: *hash.as_bytes(),
58 expires_at: Instant::now() + ADMIN_TOKEN_TTL,
59 });
60 Ok(token)
61 }
62
63 pub fn consume(&self, presented: &str) -> Result<(), ServerError> {
68 let mut guard = self.state.lock().unwrap();
69 let Some(state) = guard.as_ref() else {
70 return Err(ServerError::AdminToken("no admin token issued"));
71 };
72 if Instant::now() >= state.expires_at {
73 *guard = None;
74 let _ = fs::remove_file(self.hash_path());
75 return Err(ServerError::AdminToken("admin token expired"));
76 }
77 let candidate = blake3::hash(presented.as_bytes());
78 if !constant_time_eq(candidate.as_bytes(), &state.hash) {
79 return Err(ServerError::AdminToken("admin token mismatch"));
80 }
81 *guard = None;
82 let _ = fs::remove_file(self.hash_path());
83 Ok(())
84 }
85
86 pub fn is_active(&self) -> bool {
87 self.state.lock().unwrap().is_some()
88 }
89
90 fn hash_path(&self) -> PathBuf {
91 self.data_dir.join(HASH_FILE)
92 }
93}
94
95fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
96 constant_time_eq_public(a, b)
97}
98
99pub fn constant_time_eq_public(a: &[u8], b: &[u8]) -> bool {
102 if a.len() != b.len() {
103 return false;
104 }
105 let mut acc: u8 = 0;
106 for (x, y) in a.iter().zip(b.iter()) {
107 acc |= x ^ y;
108 }
109 acc == 0
110}
111
112fn write_secret(path: &Path, contents: &[u8]) -> Result<(), ServerError> {
113 use std::io::Write as _;
114 let mut tmp = path.to_path_buf();
115 tmp.set_extension("tmp");
116 let mut file = fs::OpenOptions::new()
117 .write(true)
118 .create(true)
119 .truncate(true)
120 .open(&tmp)?;
121 file.write_all(contents)?;
122 file.sync_all()?; #[cfg(unix)]
124 {
125 use std::os::unix::fs::PermissionsExt;
126 fs::set_permissions(&tmp, fs::Permissions::from_mode(0o600))?;
127 }
128 fs::rename(&tmp, path)?;
129 crate::fsync::sync_parent(path)?;
130 Ok(())
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136 use tempfile::TempDir;
137
138 #[test]
139 fn issue_and_consume_roundtrip() {
140 let dir = TempDir::new().unwrap();
141 let store = AdminTokenStore::new(dir.path().to_path_buf());
142 let token = store.issue().unwrap();
143 assert!(store.is_active());
144 store.consume(&token).unwrap();
145 assert!(!store.is_active());
146 }
147
148 #[test]
149 fn double_consume_rejected() {
150 let dir = TempDir::new().unwrap();
151 let store = AdminTokenStore::new(dir.path().to_path_buf());
152 let token = store.issue().unwrap();
153 store.consume(&token).unwrap();
154 assert!(store.consume(&token).is_err());
155 }
156
157 #[test]
158 fn wrong_token_rejected() {
159 let dir = TempDir::new().unwrap();
160 let store = AdminTokenStore::new(dir.path().to_path_buf());
161 let _real = store.issue().unwrap();
162 assert!(store.consume("WRONG").is_err());
163 assert!(store.is_active()); }
165}