1use std::collections::BTreeMap;
4use std::fs;
5use std::io::Write;
6use std::path::{Path, PathBuf};
7
8use super::{AuthError, AuthStore};
9
10impl AuthStore {
11 pub fn load(path: &Path) -> Result<Self, AuthError> {
17 let content = match fs::read_to_string(path) {
18 Ok(content) => content,
19 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::new()),
20 Err(err) => return Err(AuthError::Read(path.to_path_buf(), err)),
21 };
22 toml::from_str(&content)
23 .map_err(|err: toml::de::Error| AuthError::Parse(path.to_path_buf(), err.to_string()))
24 }
25
26 pub fn save(&self, path: &Path) -> Result<(), AuthError> {
31 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
32 ensure_dir_private(parent)?;
33 }
34
35 let lock_path = lock_path(path);
36 let _lock = crate::file_lock::exclusive(&lock_path)
37 .map_err(|err| AuthError::Lock(lock_path.clone(), err))?;
38
39 let mut pending = self
40 .pending
41 .lock()
42 .unwrap_or_else(std::sync::PoisonError::into_inner);
43 let mut keys = Self::load(path)?.keys;
44 for endpoint in pending.iter() {
45 if let Some(key) = self.keys.get(endpoint) {
46 keys.insert(endpoint.clone(), key.clone());
47 } else {
48 keys.remove(endpoint);
49 }
50 }
51 let body = serialize_keys(keys)?;
52 write_private(path, &body)?;
53 pending.clear();
54 Ok(())
55 }
56}
57
58fn serialize_keys(keys: BTreeMap<String, String>) -> Result<String, AuthError> {
59 let store = AuthStore {
60 keys,
61 ..AuthStore::default()
62 };
63 toml::to_string_pretty(&store).map_err(|err| AuthError::Serialize(err.to_string()))
64}
65
66fn lock_path(path: &Path) -> PathBuf {
67 let mut name = path
68 .file_name()
69 .unwrap_or_else(|| std::ffi::OsStr::new("auth.toml"))
70 .to_os_string();
71 name.push(".lock");
72 path.with_file_name(name)
73}
74
75pub(crate) fn ensure_dir_private(dir: &Path) -> Result<(), AuthError> {
81 ensure_dir_private_with(dir, create_private_dir, sync_directory)
82}
83
84fn ensure_dir_private_with(
85 dir: &Path,
86 create_component: impl FnMut(&Path) -> std::io::Result<()>,
87 sync_directory: impl FnMut(&Path) -> std::io::Result<()>,
88) -> Result<(), AuthError> {
89 ensure_dir_private_with_metadata(
90 dir,
91 |path| fs::symlink_metadata(path),
92 create_component,
93 sync_directory,
94 )
95}
96
97fn ensure_dir_private_with_metadata(
98 dir: &Path,
99 mut metadata: impl FnMut(&Path) -> std::io::Result<fs::Metadata>,
100 mut create_component: impl FnMut(&Path) -> std::io::Result<()>,
101 mut sync_directory: impl FnMut(&Path) -> std::io::Result<()>,
102) -> Result<(), AuthError> {
103 let mut missing = Vec::new();
104 let mut cursor = dir;
105 loop {
106 match metadata(cursor) {
107 Ok(_) => break,
108 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
109 missing.push(cursor.to_path_buf());
110 }
111 Err(err) => return Err(AuthError::Write(dir.to_path_buf(), err)),
112 }
113 let Some(parent) = cursor
114 .parent()
115 .filter(|parent| !parent.as_os_str().is_empty())
116 else {
117 break;
118 };
119 cursor = parent;
120 }
121
122 for created in missing.iter().rev() {
123 match create_component(created) {
124 Ok(()) => {
125 restrict(created, 0o700)?;
126 sync_directory(created)
127 .map_err(|err| AuthError::Write(created.to_path_buf(), err))?;
128 sync_directory(temporary_parent(created))
129 .map_err(|err| AuthError::Write(created.to_path_buf(), err))?;
130 }
131 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
132 require_directory(created)?;
133 }
134 Err(err) => return Err(AuthError::Write(created.to_path_buf(), err)),
135 }
136 }
137 require_directory(dir)
138}
139
140fn create_private_dir(path: &Path) -> std::io::Result<()> {
141 #[cfg(unix)]
142 {
143 use std::os::unix::fs::DirBuilderExt;
144
145 let mut builder = fs::DirBuilder::new();
146 builder.mode(0o700).create(path)
147 }
148
149 #[cfg(not(unix))]
150 {
151 fs::create_dir(path)
152 }
153}
154
155fn require_directory(path: &Path) -> Result<(), AuthError> {
156 match fs::metadata(path) {
157 Ok(metadata) if metadata.is_dir() => Ok(()),
158 Ok(_) => Err(AuthError::Write(
159 path.to_path_buf(),
160 std::io::Error::from(std::io::ErrorKind::NotADirectory),
161 )),
162 Err(err) => Err(AuthError::Write(path.to_path_buf(), err)),
163 }
164}
165
166fn write_private(path: &Path, body: &str) -> Result<(), AuthError> {
172 write_private_with(path, body, sync_directory)
173}
174
175fn write_private_with(
176 path: &Path,
177 body: &str,
178 sync_parent: impl FnOnce(&Path) -> std::io::Result<()>,
179) -> Result<(), AuthError> {
180 let parent = temporary_parent(path);
181 let mut temporary = tempfile::NamedTempFile::new_in(parent)
182 .map_err(|err| AuthError::Write(path.to_path_buf(), err))?;
183 temporary
184 .write_all(body.as_bytes())
185 .map_err(|err| AuthError::Write(path.to_path_buf(), err))?;
186 temporary
187 .as_file()
188 .sync_all()
189 .map_err(|err| AuthError::Write(path.to_path_buf(), err))?;
190 restrict(temporary.path(), 0o600)?;
191 temporary
192 .persist(path)
193 .map_err(|err| AuthError::Write(path.to_path_buf(), err.error))?;
194 sync_parent(parent).map_err(|err| AuthError::Write(path.to_path_buf(), err))
195}
196
197#[cfg(unix)]
198fn sync_directory(path: &Path) -> std::io::Result<()> {
199 fs::File::open(path)?.sync_all()
200}
201
202#[cfg(not(unix))]
203fn sync_directory(_path: &Path) -> std::io::Result<()> {
204 Ok(())
205}
206
207pub(crate) fn temporary_parent(path: &Path) -> &Path {
208 path.parent()
209 .filter(|parent| !parent.as_os_str().is_empty())
210 .unwrap_or_else(|| Path::new("."))
211}
212
213#[cfg(unix)]
214pub(crate) fn restrict(path: &Path, mode: u32) -> Result<(), AuthError> {
215 use std::os::unix::fs::PermissionsExt;
216 fs::set_permissions(path, fs::Permissions::from_mode(mode))
217 .map_err(|err| AuthError::Write(path.to_path_buf(), err))
218}
219
220#[cfg(not(unix))]
221pub(crate) fn restrict(_path: &Path, _mode: u32) -> Result<(), AuthError> {
225 Ok(())
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231 #[cfg(unix)]
232 use crate::test_support::assert_mode;
233
234 fn assert_write_error(error: AuthError, path: &Path, kind: std::io::ErrorKind) {
235 match error {
236 AuthError::Write(actual_path, source) => {
237 assert_eq!(actual_path, path);
238 assert_eq!(source.kind(), kind);
239 }
240 other => panic!("expected write error, got {other:?}"),
241 }
242 }
243
244 #[test]
245 fn metadata_errors_are_not_treated_as_missing_directories() {
246 let dir = Path::new("denied");
247 let error = ensure_dir_private_with_metadata(
248 dir,
249 |_| Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
250 |_| panic!("metadata failure must not attempt directory creation"),
251 |_| panic!("metadata failure must not attempt directory sync"),
252 )
253 .expect_err("metadata failure must remain fatal");
254
255 assert_write_error(error, dir, std::io::ErrorKind::PermissionDenied);
256 }
257
258 #[test]
259 fn creation_errors_are_not_treated_as_races() {
260 let base = tempfile::tempdir().expect("tempdir");
261 let dir = base.path().join("denied");
262 let error = ensure_dir_private_with(
263 &dir,
264 |_| Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
265 |_| panic!("failed directory creation must not be synced"),
266 )
267 .expect_err("creation failure must remain fatal");
268
269 assert_write_error(error, &dir, std::io::ErrorKind::PermissionDenied);
270 }
271
272 #[test]
273 fn a_store_parent_must_be_a_directory() {
274 let base = tempfile::tempdir().expect("tempdir");
275 let file = base.path().join("not-a-directory");
276 std::fs::write(&file, "data").expect("fixture file");
277
278 let error = require_directory(&file).expect_err("file must not pass as directory");
279
280 assert_write_error(error, &file, std::io::ErrorKind::NotADirectory);
281 }
282
283 #[test]
284 fn private_directory_creation_creates_the_requested_path() {
285 let base = tempfile::tempdir().expect("tempdir");
286 let dir = base.path().join("private");
287
288 create_private_dir(&dir).expect("create private directory");
289
290 assert!(dir.is_dir());
291 #[cfg(unix)]
292 assert_mode(&dir, 0o700);
293 }
294
295 #[cfg(unix)]
296 #[test]
297 fn syncing_a_missing_directory_reports_not_found() {
298 let base = tempfile::tempdir().expect("tempdir");
299 let missing = base.path().join("missing");
300
301 let error = sync_directory(&missing).expect_err("missing directory cannot be synced");
302
303 assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
304 }
305
306 #[test]
307 fn publication_syncs_the_parent_after_the_store_is_visible() {
308 let dir = tempfile::tempdir().expect("tempdir");
309 let path = dir.path().join("auth.toml");
310 let mut called = false;
311
312 write_private_with(&path, "[keys]\n", |parent| {
313 assert_eq!(parent, dir.path());
314 assert_eq!(
315 std::fs::read_to_string(&path).expect("published store"),
316 "[keys]\n"
317 );
318 called = true;
319 Ok(())
320 })
321 .expect("publish and sync");
322
323 assert!(called, "the containing directory was not synced");
324 }
325
326 #[test]
327 fn creating_nested_store_directories_syncs_each_new_link() {
328 let base = tempfile::tempdir().expect("tempdir");
329 let dir = base.path().join("first").join("second");
330 let mut seen = Vec::new();
331
332 ensure_dir_private_with(
333 &dir,
334 |component| {
335 std::fs::create_dir(component)?;
336 #[cfg(unix)]
337 {
338 use std::os::unix::fs::PermissionsExt;
339 std::fs::set_permissions(component, std::fs::Permissions::from_mode(0o755))?;
340 }
341 Ok(())
342 },
343 |directory| {
344 assert!(directory.exists(), "directory was not visible before sync");
345 seen.push(directory.to_path_buf());
346 Ok(())
347 },
348 )
349 .expect("create and sync directory tree");
350
351 assert_eq!(
352 seen,
353 vec![
354 base.path().join("first"),
355 base.path().to_path_buf(),
356 dir.clone(),
357 base.path().join("first"),
358 ]
359 );
360 #[cfg(unix)]
361 {
362 for created in [base.path().join("first"), dir] {
363 assert_mode(&created, 0o700);
364 }
365 }
366 }
367
368 #[cfg(unix)]
369 #[test]
370 fn a_directory_created_by_a_racing_process_is_not_claimed() {
371 use std::os::unix::fs::PermissionsExt;
372
373 let base = tempfile::tempdir().expect("tempdir");
374 let dir = base.path().join("raced");
375
376 ensure_dir_private_with(
377 &dir,
378 |component| {
379 std::fs::create_dir(component)?;
380 std::fs::set_permissions(component, std::fs::Permissions::from_mode(0o755))?;
381 Err(std::io::Error::from(std::io::ErrorKind::AlreadyExists))
382 },
383 |_| panic!("a directory drep did not create must not be synced as its own"),
384 )
385 .expect("accept raced directory");
386
387 assert_mode(&dir, 0o755);
388 }
389}