1use crate::error::BoxError;
5use crate::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex};
8
9pub trait TokenStore: WasmCompatSend + WasmCompatSync {
32 fn load<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<Option<String>, BoxError>>;
35
36 fn save<'a>(
38 &'a self,
39 key: &'a str,
40 record: &'a str,
41 ) -> WasmBoxedFuture<'a, Result<(), BoxError>>;
42
43 fn delete<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<(), BoxError>>;
45
46 fn lock<'a>(&'a self, _key: &'a str) -> WasmBoxedFuture<'a, Result<StoreLock, BoxError>> {
52 Box::pin(async { Ok(StoreLock::new(())) })
53 }
54}
55
56pub struct StoreLock {
59 _guard: Mutex<Box<dyn WasmCompatSend>>,
62}
63
64impl StoreLock {
65 pub fn new(guard: impl WasmCompatSend + 'static) -> Self {
74 Self {
75 _guard: Mutex::new(Box::new(guard)),
76 }
77 }
78}
79
80impl std::fmt::Debug for StoreLock {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 f.debug_struct("StoreLock").finish_non_exhaustive()
83 }
84}
85
86impl<T: TokenStore + ?Sized> TokenStore for Arc<T> {
87 fn load<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<Option<String>, BoxError>> {
88 (**self).load(key)
89 }
90
91 fn save<'a>(
92 &'a self,
93 key: &'a str,
94 record: &'a str,
95 ) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
96 (**self).save(key, record)
97 }
98
99 fn delete<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
100 (**self).delete(key)
101 }
102
103 fn lock<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<StoreLock, BoxError>> {
104 (**self).lock(key)
105 }
106}
107
108#[derive(Default)]
110pub struct MemoryTokenStore(Mutex<HashMap<String, String>>);
111
112impl std::fmt::Debug for MemoryTokenStore {
113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 f.debug_struct("MemoryTokenStore").finish_non_exhaustive()
115 }
116}
117
118impl MemoryTokenStore {
119 fn records(&self) -> std::sync::MutexGuard<'_, HashMap<String, String>> {
120 crate::lock(&self.0)
121 }
122}
123
124impl TokenStore for MemoryTokenStore {
125 fn load<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<Option<String>, BoxError>> {
126 Box::pin(async move { Ok(self.records().get(key).cloned()) })
127 }
128
129 fn save<'a>(
130 &'a self,
131 key: &'a str,
132 record: &'a str,
133 ) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
134 Box::pin(async move {
135 self.records().insert(key.to_owned(), record.to_owned());
136 Ok(())
137 })
138 }
139
140 fn delete<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
141 Box::pin(async move {
142 self.records().remove(key);
143 Ok(())
144 })
145 }
146}
147
148#[cfg(not(target_family = "wasm"))]
159#[derive(Debug, Clone)]
160pub struct FileTokenStore {
161 dir: std::path::PathBuf,
162 lock_wait: std::time::Duration,
163}
164
165#[cfg(not(target_family = "wasm"))]
166impl FileTokenStore {
167 pub fn new(dir: impl Into<std::path::PathBuf>) -> Self {
169 Self {
170 dir: dir.into(),
171 lock_wait: LOCK_WAIT,
172 }
173 }
174
175 pub fn with_lock_wait(self, wait: std::time::Duration) -> Self {
179 Self {
180 lock_wait: wait,
181 ..self
182 }
183 }
184
185 pub fn path(&self, key: &str) -> std::path::PathBuf {
187 self.dir.join(format!("{key}.json"))
188 }
189}
190
191#[cfg(not(target_family = "wasm"))]
192impl TokenStore for FileTokenStore {
193 fn load<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<Option<String>, BoxError>> {
194 Box::pin(async move { read_private(&self.path(key)) })
195 }
196
197 fn save<'a>(
198 &'a self,
199 key: &'a str,
200 record: &'a str,
201 ) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
202 Box::pin(async move { Ok(write_private(&self.path(key), record.as_bytes())?) })
203 }
204
205 fn delete<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<(), BoxError>> {
206 Box::pin(async move {
207 let path = self.path(key);
208 match std::fs::remove_file(&path) {
209 Ok(()) => Ok(sync_parent(&path)?),
210 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
211 Err(error) => Err(error.into()),
212 }
213 })
214 }
215
216 fn lock<'a>(&'a self, key: &'a str) -> WasmBoxedFuture<'a, Result<StoreLock, BoxError>> {
222 Box::pin(async move {
223 let path = self.dir.join(format!("{key}.lock"));
224 create_private_dir(&path)?;
225 let mut options = std::fs::OpenOptions::new();
226 options.read(true).write(true).create(true).truncate(false);
227 #[cfg(unix)]
228 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
229 let file = options.open(&path)?;
230 let started = std::time::Instant::now();
231 loop {
232 match file.try_lock() {
233 Ok(()) => return Ok(StoreLock::new(file)),
234 Err(std::fs::TryLockError::WouldBlock)
235 if started.elapsed() < self.lock_wait =>
236 {
237 crate::wasm_compat::sleep(std::time::Duration::from_millis(50)).await;
238 }
239 Err(std::fs::TryLockError::WouldBlock) => {
240 return Err(FileStoreError::Busy {
241 path,
242 waited: self.lock_wait,
243 }
244 .into());
245 }
246 Err(std::fs::TryLockError::Error(error)) => return Err(error.into()),
247 }
248 }
249 })
250 }
251}
252
253#[cfg(not(target_family = "wasm"))]
256#[derive(Debug, thiserror::Error)]
257#[non_exhaustive]
258pub enum FileStoreError {
259 #[error("{} is a symlink or not a regular file; a credential is read only from a regular file", path.display())]
262 NotAFile {
263 path: std::path::PathBuf,
265 },
266 #[error("{} is larger than {limit} bytes", path.display())]
268 TooLarge {
269 path: std::path::PathBuf,
271 limit: u64,
273 },
274 #[error("{} is open to group or others and could not be made owner-only", path.display())]
277 NotNarrowed {
278 path: std::path::PathBuf,
280 #[source]
282 source: std::io::Error,
283 },
284 #[error("another holder kept {} locked for {waited:?}", path.display())]
287 Busy {
288 path: std::path::PathBuf,
290 waited: std::time::Duration,
292 },
293}
294
295#[cfg(not(target_family = "wasm"))]
297const RECORD_LIMIT: u64 = 64 * 1024;
298
299#[cfg(not(target_family = "wasm"))]
305fn read_private(path: &std::path::Path) -> Result<Option<String>, BoxError> {
306 use std::io::Read;
307
308 let not_a_file = || FileStoreError::NotAFile {
309 path: path.to_owned(),
310 };
311 let linked = match std::fs::symlink_metadata(path) {
312 Ok(linked) => linked,
313 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
314 Err(error) => return Err(error.into()),
315 };
316 if !linked.file_type().is_file() {
317 return Err(not_a_file().into());
318 }
319 let mut options = std::fs::OpenOptions::new();
320 options.read(true);
321 #[cfg(windows)]
324 std::os::windows::fs::OpenOptionsExt::custom_flags(&mut options, 0x0020_0000);
325 let file = options.open(path)?;
326 let opened = file.metadata()?;
327 if !opened.is_file() {
328 return Err(not_a_file().into());
329 }
330 #[cfg(unix)]
331 {
332 use std::os::unix::fs::{MetadataExt, PermissionsExt};
333 if (opened.dev(), opened.ino()) != (linked.dev(), linked.ino()) {
334 return Err(not_a_file().into());
335 }
336 if opened.mode() & 0o077 != 0 {
337 file.set_permissions(std::fs::Permissions::from_mode(0o600))
338 .map_err(|source| FileStoreError::NotNarrowed {
339 path: path.to_owned(),
340 source,
341 })?;
342 }
343 }
344 let mut record = Vec::new();
345 file.take(RECORD_LIMIT + 1).read_to_end(&mut record)?;
346 if record.len() as u64 > RECORD_LIMIT {
347 return Err(FileStoreError::TooLarge {
348 path: path.to_owned(),
349 limit: RECORD_LIMIT,
350 }
351 .into());
352 }
353 Ok(Some(String::from_utf8(record)?))
354}
355
356#[cfg(not(target_family = "wasm"))]
359const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(120);
360
361#[cfg(not(target_family = "wasm"))]
363fn create_private_dir(path: &std::path::Path) -> Result<(), std::io::Error> {
364 let Some(parent) = path.parent() else {
365 return Ok(());
366 };
367 let mut builder = std::fs::DirBuilder::new();
368 builder.recursive(true);
369 #[cfg(unix)]
370 std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
371 builder.create(parent)
372}
373
374#[cfg(not(target_family = "wasm"))]
382fn write_private(path: &std::path::Path, bytes: &[u8]) -> Result<(), std::io::Error> {
383 use std::io::Write;
384 use std::sync::atomic::{AtomicU64, Ordering};
385
386 static WRITES: AtomicU64 = AtomicU64::new(0);
387 create_private_dir(path)?;
388 let mut temp = path.as_os_str().to_owned();
389 temp.push(format!(
390 ".tmp-{}-{}",
391 std::process::id(),
392 WRITES.fetch_add(1, Ordering::Relaxed)
393 ));
394 let temp = std::path::PathBuf::from(temp);
395 let write = || {
396 let mut options = std::fs::OpenOptions::new();
397 options.write(true).create_new(true);
398 #[cfg(unix)]
399 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
400 let mut file = options.open(&temp)?;
401 #[cfg(unix)]
402 file.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(0o600))?;
403 file.write_all(bytes)?;
404 file.sync_all()?;
405 std::fs::rename(&temp, path)
406 };
407 let written = write();
408 if written.is_err() {
409 std::fs::remove_file(&temp).ok();
410 }
411 written?;
412 sync_parent(path)
413}
414
415#[cfg(not(target_family = "wasm"))]
419fn sync_parent(path: &std::path::Path) -> Result<(), std::io::Error> {
420 #[cfg(unix)]
421 if let Some(parent) = path.parent() {
422 std::fs::File::open(parent)?.sync_all()?;
423 }
424 #[cfg(not(unix))]
425 let _ = path;
426 Ok(())
427}
428
429pub(crate) async fn load_record<T: Default + serde::de::DeserializeOwned>(
431 store: &dyn TokenStore,
432 key: &str,
433) -> Result<T, super::AuthError> {
434 match store.load(key).await.map_err(super::AuthError::Store)? {
435 Some(record) => Ok(serde_json::from_str(&record)?),
436 None => Ok(T::default()),
437 }
438}
439
440pub(crate) async fn save_record<T: serde::Serialize>(
442 store: &dyn TokenStore,
443 key: &str,
444 record: &T,
445) -> Result<(), super::AuthError> {
446 let text = serde_json::to_string_pretty(record)?;
447 store
448 .save(key, &text)
449 .await
450 .map_err(super::AuthError::Store)
451}
452
453#[cfg(test)]
454mod tests;