1use crate::auth::types::TokenSet;
14use crate::shared::errors::{Error, Result};
15use async_trait::async_trait;
16use std::path::PathBuf;
17use std::time::{Duration, SystemTime};
18
19#[derive(Debug, Clone, Copy)]
21pub struct FileLockDefaults {
22 pub acquire_timeout_ms: u64,
24 pub stale_ms: u64,
26 pub retry_base_ms: u64,
28 pub retry_jitter_ms: u64,
30}
31
32pub const FILE_LOCK_DEFAULTS: FileLockDefaults = FileLockDefaults {
34 acquire_timeout_ms: 30_000,
35 stale_ms: 60_000,
36 retry_base_ms: 30,
37 retry_jitter_ms: 70,
38};
39
40#[async_trait]
48pub trait TokenStore: Send + Sync {
49 async fn save(&self, tokens: &TokenSet) -> Result<()>;
50 async fn load(&self) -> Result<Option<TokenSet>>;
51 async fn clear(&self) -> Result<()>;
52
53 async fn lock(&self) -> Result<Box<dyn Send>> {
56 Ok(Box::new(()))
57 }
58}
59
60pub struct FileTokenStore {
66 path: Option<PathBuf>,
68 chain: tokio::sync::Mutex<()>,
70}
71
72impl FileTokenStore {
73 pub fn new(path: Option<PathBuf>) -> Self {
75 Self {
76 path,
77 chain: tokio::sync::Mutex::new(()),
78 }
79 }
80
81 fn resolve_path(&self) -> Result<PathBuf> {
82 if let Some(p) = &self.path {
83 if !p.as_os_str().is_empty() {
84 return Ok(p.clone());
85 }
86 }
87 let home = home_dir()
88 .ok_or_else(|| Error::other("FileTokenStore: cannot resolve home directory"))?;
89 Ok(home.join(".acosmi").join("tokens.json"))
90 }
91}
92
93struct FileLockGuard {
95 lock_path: PathBuf,
96}
97
98impl Drop for FileLockGuard {
99 fn drop(&mut self) {
100 let _ = std::fs::remove_file(&self.lock_path);
102 }
103}
104
105#[async_trait]
106impl TokenStore for FileTokenStore {
107 async fn save(&self, tokens: &TokenSet) -> Result<()> {
108 let _chain = self.chain.lock().await;
109 let p = self.resolve_path()?;
110 let dir = p
111 .parent()
112 .ok_or_else(|| Error::other("token path has no parent dir"))?
113 .to_path_buf();
114 let data = zeroize::Zeroizing::new(serde_json::to_vec_pretty(tokens)?);
115 let p2 = p.clone();
116 tokio::task::spawn_blocking(move || -> Result<()> {
118 use std::io::Write;
119 create_private_dir(&dir)?;
120 let tmp = dir.join(format!(
121 "tokens.json.tmp.{}.{}",
122 std::process::id(),
123 now_nanos()
124 ));
125 {
132 let mut fh = create_private_file(&tmp)?;
133 fh.write_all(&data)?;
134 fh.sync_all()?; }
136 if let Err(e) = std::fs::rename(&tmp, &p2) {
138 let _ = std::fs::remove_file(&tmp);
139 return Err(e.into());
140 }
141 if let Ok(dh) = std::fs::File::open(&dir) {
143 let _ = dh.sync_all();
144 }
145 Ok(())
146 })
147 .await
148 .map_err(|e| Error::other(format!("join save task: {e}")))?
149 }
150
151 async fn load(&self) -> Result<Option<TokenSet>> {
152 let _chain = self.chain.lock().await;
153 let p = self.resolve_path()?;
154 let data = match tokio::fs::read(&p).await {
155 Ok(d) => d,
156 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
157 Err(e) => return Err(Error::other(format!("read token file: {e}"))),
158 };
159 let data = zeroize::Zeroizing::new(data);
162 Ok(serde_json::from_slice::<TokenSet>(&data).ok())
163 }
164
165 async fn clear(&self) -> Result<()> {
166 let _chain = self.chain.lock().await;
167 let p = self.resolve_path()?;
168 match tokio::fs::remove_file(&p).await {
169 Ok(()) => Ok(()),
170 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
171 Err(e) => Err(e.into()),
172 }
173 }
174
175 async fn lock(&self) -> Result<Box<dyn Send>> {
176 let p = self.resolve_path()?;
177 let lock_path = PathBuf::from(format!("{}.lock", p.display()));
178 let dir = p
179 .parent()
180 .ok_or_else(|| Error::other("token path has no parent dir"))?
181 .to_path_buf();
182 tokio::fs::create_dir_all(&dir).await?;
183
184 let start = SystemTime::now();
185 loop {
186 match std::fs::OpenOptions::new()
188 .write(true)
189 .create_new(true)
190 .open(&lock_path)
191 {
192 Ok(mut fh) => {
193 use std::io::Write;
194 let _ = write!(fh, "{}\n{}\n", std::process::id(), now_millis());
195 return Ok(Box::new(FileLockGuard { lock_path }));
196 }
197 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
198 if let Ok(meta) = std::fs::metadata(&lock_path) {
200 if let Ok(modified) = meta.modified() {
201 if let Ok(age) = SystemTime::now().duration_since(modified) {
202 if age.as_millis() as u64 > FILE_LOCK_DEFAULTS.stale_ms {
203 let _ = std::fs::remove_file(&lock_path);
204 continue;
205 }
206 }
207 }
208 } else {
209 continue;
211 }
212 if elapsed_ms(start) > FILE_LOCK_DEFAULTS.acquire_timeout_ms {
213 return Err(Error::other(format!(
214 "acquire token file lock timeout ({}ms): {}",
215 FILE_LOCK_DEFAULTS.acquire_timeout_ms,
216 lock_path.display()
217 )));
218 }
219 let jitter = now_nanos() % FILE_LOCK_DEFAULTS.retry_jitter_ms.max(1);
220 let wait = FILE_LOCK_DEFAULTS.retry_base_ms + jitter;
221 tokio::time::sleep(Duration::from_millis(wait)).await;
222 }
223 Err(e) => return Err(e.into()),
224 }
225 }
226 }
227}
228
229pub fn new_file_token_store(path: Option<PathBuf>) -> FileTokenStore {
231 FileTokenStore::new(path)
232}
233
234fn create_private_dir(dir: &std::path::Path) -> std::io::Result<()> {
236 #[cfg(unix)]
237 {
238 use std::os::unix::fs::DirBuilderExt;
239 match std::fs::DirBuilder::new()
240 .recursive(true)
241 .mode(0o700)
242 .create(dir)
243 {
244 Ok(()) => Ok(()),
247 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
248 Err(e) => Err(e),
249 }
250 }
251 #[cfg(not(unix))]
252 {
253 std::fs::create_dir_all(dir)
254 }
255}
256
257fn create_private_file(path: &std::path::Path) -> std::io::Result<std::fs::File> {
262 #[cfg(unix)]
263 {
264 use std::os::unix::fs::OpenOptionsExt;
265 std::fs::OpenOptions::new()
266 .write(true)
267 .create(true)
268 .truncate(true)
269 .mode(0o600)
270 .open(path)
271 }
272 #[cfg(not(unix))]
273 {
274 std::fs::File::create(path)
275 }
276}
277
278#[derive(Default)]
284pub struct InMemoryTokenStore {
285 tokens: std::sync::Mutex<Option<zeroize::Zeroizing<TokenSet>>>,
286}
287
288impl InMemoryTokenStore {
289 pub fn new() -> Self {
290 Self::default()
291 }
292}
293
294#[async_trait]
295impl TokenStore for InMemoryTokenStore {
296 async fn save(&self, tokens: &TokenSet) -> Result<()> {
297 *self.tokens.lock().unwrap() = Some(zeroize::Zeroizing::new(tokens.clone()));
298 Ok(())
299 }
300 async fn load(&self) -> Result<Option<TokenSet>> {
301 Ok(self.tokens.lock().unwrap().as_ref().map(|t| (**t).clone()))
302 }
303 async fn clear(&self) -> Result<()> {
304 *self.tokens.lock().unwrap() = None;
305 Ok(())
306 }
307}
308
309fn home_dir() -> Option<PathBuf> {
314 std::env::var_os("HOME")
316 .or_else(|| std::env::var_os("USERPROFILE"))
317 .map(PathBuf::from)
318 .filter(|p| !p.as_os_str().is_empty())
319}
320
321fn now_nanos() -> u64 {
322 SystemTime::now()
323 .duration_since(SystemTime::UNIX_EPOCH)
324 .map(|d| d.subsec_nanos() as u64)
325 .unwrap_or(0)
326}
327
328fn now_millis() -> u128 {
329 SystemTime::now()
330 .duration_since(SystemTime::UNIX_EPOCH)
331 .map(|d| d.as_millis())
332 .unwrap_or(0)
333}
334
335fn elapsed_ms(start: SystemTime) -> u64 {
336 SystemTime::now()
337 .duration_since(start)
338 .map(|d| d.as_millis() as u64)
339 .unwrap_or(0)
340}