返回 CodeWhale
file_lock.rs
根目录 / crates / secrets / src / file_lock.rs
1 //! Shared file-store write lock. Native uses the same fd-lock 4.0.4 and
2 //! persistent `<filename>.lock` protocol. Never delete or replace that inode.
3 //! Older writers bypassing this protocol cannot participate safely.
4 use crate::SecretsError;
5 use std::{fs, path::Path};
6
7 pub(crate) fn open_private(
8 path: &Path,
9 create: bool,
10 role: StoreFile,
11 ) -> Result<fs::File, SecretsError> {
12 match fs::symlink_metadata(path) {
13 Ok(meta) if meta.file_type().is_symlink() || !meta.is_file() => {
14 return Err(std::io::Error::other("The secret store must be a regular file.").into());
15 }
16 Ok(_) => {}
17 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
18 Err(error) => return Err(error.into()),
19 }
20 let mut options = fs::OpenOptions::new();
21 options
22 .read(true)
23 .write(create)
24 .create(create)
25 .truncate(false);
26 #[cfg(unix)]
27 {
28 use std::os::unix::fs::OpenOptionsExt;
29 options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
30 }
31 #[cfg(windows)]
32 {
33 use std::os::windows::fs::OpenOptionsExt;
34 options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
35 }
36 let file = options.open(path)?;
37 let meta = file.metadata()?;
38 if !meta.is_file() {
39 return Err(std::io::Error::other("The secret store must be a regular file.").into());
40 }
41 #[cfg(unix)]
42 require_private_mode(&file, path, role)?;
43 #[cfg(not(unix))]
44 let _ = role;
45 #[cfg(windows)]
46 {
47 use std::os::windows::fs::MetadataExt;
48 if meta.file_attributes() & 0x400 != 0 {
49 return Err(
50 std::io::Error::other("The secret store cannot be a reparse point.").into(),
51 );
52 }
53 }
54 Ok(file)
55 }
56
57 /// Which of the store's two files is being opened.
58 ///
59 /// The distinction decides whether a wider-than-`0600` mode is repaired or
60 /// refused, and it is not cosmetic: one file carries the secret and the other
61 /// carries nothing.
62 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
63 pub(crate) enum StoreFile {
64 /// `secrets.json`. A mode that let another user in means the bytes may no
65 /// longer be ours, so the file is refused rather than quietly re-narrowed —
66 /// repairing the mode would hide exactly the question the caller must
67 /// answer. The refusal names the mode it saw.
68 Content,
69 /// The `<store>.lock` sibling. It holds no secret and exists only to
70 /// serialise writers, so a wider mode is hygiene: it is narrowed in place
71 /// before use, and only a filesystem that cannot hold modes is accepted as
72 /// it is.
73 Lock,
74 }
75
76 /// Make sure a secret-store file is readable by its owner only.
77 ///
78 /// 1. Already `0o600` or narrower: done, no syscall and no probe.
79 /// 2. A lock file that is wider: narrow it through the handle that was opened
80 /// and look again. A repair that does not take effect falls through.
81 /// 3. Still wider, and the mount cannot apply Unix mode bits — HarmonyOS hmdfs
82 /// reports the logged-in user as the owner of every object, so a process is
83 /// never the owner of what it creates and `chmod` answers `EPERM`; FUSE and
84 /// some network mounts refuse it too: accept with a warning, because
85 /// refusing leaves that platform with no store at all and the fallback is a
86 /// plaintext key in `config.toml`, a wider exposure.
87 /// 4. Still wider on a filesystem that does store modes: a real exposure, and
88 /// still refused.
89 #[cfg(unix)]
90 pub(crate) fn require_private_mode(
91 file: &fs::File,
92 path: &Path,
93 role: StoreFile,
94 ) -> Result<(), SecretsError> {
95 use std::os::unix::fs::PermissionsExt;
96
97 let observed = file.metadata()?.permissions().mode() & 0o777;
98 if observed & 0o077 == 0 {
99 return Ok(());
100 }
101 // Narrowing through the handle keeps it on the object that was opened, so a
102 // substituted path cannot be the thing that gets changed. Only the lock is
103 // repaired; see [`StoreFile`] for why the content is not.
104 let narrowed = match role {
105 StoreFile::Lock => file
106 .set_permissions(fs::Permissions::from_mode(0o600))
107 .and_then(|()| file.metadata())
108 .map(|metadata| metadata.permissions().mode() & 0o777)
109 .ok(),
110 StoreFile::Content => None,
111 };
112 // The probe costs a create, a stat and an unlink, so it runs only when the
113 // mode is still wide after any repair.
114 let mount_cannot_hold_modes = match narrowed {
115 Some(mode) if mode & 0o077 == 0 => false,
116 _ => mount_ignores_unix_modes(path),
117 };
118 match classify_store_mode(observed, narrowed, mount_cannot_hold_modes) {
119 StoreMode::Narrowed => Ok(()),
120 StoreMode::Unavoidable { mode } => {
121 tracing::warn!(
122 "{} has mode {mode:o} and its filesystem does not apply Unix mode bits; \
123 relying on the mount's own access control for the secret store",
124 path.display()
125 );
126 Ok(())
127 }
128 StoreMode::Exposed { mode } => Err(SecretsError::InsecurePermissions {
129 path: path.into(),
130 mode,
131 }),
132 }
133 }
134
135 /// What a store file's mode turned out to be worth, given what the mount did
136 /// when asked for `0o600`.
137 ///
138 /// Separated from the syscalls so every branch is testable: the interesting
139 /// cases need a mount that either refuses `chmod` or accepts it without
140 /// applying it, which no portable filesystem produces.
141 #[cfg(unix)]
142 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
143 enum StoreMode {
144 /// Narrower than `0o600` after the repair.
145 Narrowed,
146 /// Wider, and this filesystem cannot represent the mode at all.
147 Unavoidable { mode: u32 },
148 /// Wider, on a filesystem that does store modes: still a refusal.
149 Exposed { mode: u32 },
150 }
151
152 #[cfg(unix)]
153 fn classify_store_mode(
154 observed: u32,
155 narrowed: Option<u32>,
156 mount_cannot_hold_modes: bool,
157 ) -> StoreMode {
158 if narrowed.is_some_and(|mode| mode & 0o077 == 0) {
159 return StoreMode::Narrowed;
160 }
161 let mode = narrowed.unwrap_or(observed);
162 if mount_cannot_hold_modes {
163 StoreMode::Unavoidable { mode }
164 } else {
165 StoreMode::Exposed { mode }
166 }
167 }
168
169 /// Whether `path`'s directory refuses the mode a file is created with *and* the
170 /// one it is then asked for.
171 ///
172 /// Creates one probe file beside `path`, the same way the store creates its
173 /// own, at `0o600`, and reads back the mode the mount stored. A filesystem that
174 /// keeps mode bits reports `0o600` or narrower. A wider mode alone is not
175 /// enough to blame the mount — a default ACL or a setgid parent widens a new
176 /// file on a filesystem that stores modes perfectly well — so the probe asks
177 /// the mount to narrow it and looks again; only a refusal, or a mode that stays
178 /// wide, means the mode says nothing about who may read the file. Any failure
179 /// to run the probe answers `false`, so a directory we cannot create files in
180 /// keeps the strict check instead of widening it.
181 ///
182 /// Only a store file whose mode is wider than `0o600` reaches this, so a
183 /// filesystem that stores modes never pays for it; on the mounts that do reach
184 /// it, the cost is one create, one stat, at most one `chmod` and one unlink.
185 ///
186 /// The same rule, with the same reasoning, lives in
187 /// `codewhale_config::private_directory::private_footing`. This crate is below
188 /// `codewhale-config` in the graph, so it cannot call it; the probe is a dozen
189 /// lines and the alternative is a dependency cycle. `scripts/ohos/ohos-secrets-store-smoke.sh`
190 /// covers the synthesising branch end to end against a real mount; the tests
191 /// here cover everything a portable filesystem can produce.
192 #[cfg(unix)]
193 fn mount_ignores_unix_modes(path: &Path) -> bool {
194 use std::os::unix::fs::PermissionsExt;
195
196 let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) else {
197 return false;
198 };
199 let Ok(probe) = tempfile::Builder::new()
200 .prefix(".codewhale-mode-probe-")
201 .tempfile_in(parent)
202 else {
203 return false;
204 };
205 let narrows = |file: &fs::File| {
206 file.set_permissions(fs::Permissions::from_mode(0o600))
207 .is_ok_and(|()| {
208 file.metadata()
209 .is_ok_and(|meta| meta.permissions().mode() & 0o077 == 0)
210 })
211 };
212 match probe.as_file().metadata() {
213 // `0o077` clear means the mount stored the `0o600` we created with.
214 Ok(meta) if meta.permissions().mode() & 0o077 == 0 => false,
215 Ok(_) => !narrows(probe.as_file()),
216 Err(_) => false,
217 }
218 }
219
220 pub(crate) fn with_write_lock<T>(
221 path: &Path,
222 operation: impl FnOnce(&Path) -> Result<T, SecretsError>,
223 ) -> Result<T, SecretsError> {
224 let parent = path
225 .parent()
226 .filter(|p| !p.as_os_str().is_empty())
227 .unwrap_or(Path::new("."));
228 let mut directory = fs::DirBuilder::new();
229 directory.recursive(true);
230 #[cfg(unix)]
231 {
232 use std::os::unix::fs::DirBuilderExt;
233 directory.mode(0o700);
234 }
235 directory.create(parent)?;
236 let filename = path
237 .file_name()
238 .ok_or_else(|| std::io::Error::other("Invalid secret store path."))?;
239 let path = parent.canonicalize()?.join(filename);
240 let mut lock_name = path.as_os_str().to_os_string();
241 lock_name.push(".lock");
242 let mut lock =
243 fd_lock::RwLock::new(open_private(Path::new(&lock_name), true, StoreFile::Lock)?);
244 match lock.write() {
245 Ok(_guard) => operation(&path),
246 // HarmonyOS hmdfs refuses `flock` and `fcntl(F_SETLK)` with EPERM for
247 // every file, so the cross-process guard cannot be taken there. Fall
248 // back to serialising this process's own writers and say so: refusing
249 // outright would leave no way to store a credential on that mount at
250 // all. The tradeoff is real and narrow — two Codewhale processes whose
251 // snapshots of `secrets.json` overlap can lose one of the two writes,
252 // which needs both to rewrite the same store in the same instant.
253 Err(error) if advisory_locking_unavailable(&error) => {
254 tracing::warn!(
255 "{} cannot take a file lock ({error}); serialising secret-store writes \
256 within this process only",
257 lock_name.to_string_lossy()
258 );
259 let _guard = in_process_write_guard();
260 operation(&path)
261 }
262 Err(error) => Err(error.into()),
263 }
264 }
265
266 /// Whether a failed advisory lock means the filesystem has none at all, as
267 /// opposed to a lock that is genuinely held by someone else.
268 ///
269 /// `EWOULDBLOCK` is deliberately absent: a held lock must still wait or fail
270 /// rather than fall back. The rest are the mount saying "no locking here".
271 #[cfg(unix)]
272 fn advisory_locking_unavailable(error: &std::io::Error) -> bool {
273 matches!(
274 error.raw_os_error(),
275 Some(libc::EPERM)
276 | Some(libc::EACCES)
277 | Some(libc::ENOTSUP)
278 | Some(libc::EINVAL)
279 | Some(libc::ENOSYS)
280 )
281 }
282
283 /// Windows always offers `LockFileEx` through `fd-lock`, so a failed write
284 /// lock there is genuine contention, never an absent advisory lock.
285 #[cfg(not(unix))]
286 fn advisory_locking_unavailable(_error: &std::io::Error) -> bool {
287 false
288 }
289
290 /// Serialises secret-store writers inside this process when the filesystem
291 /// offers no advisory lock. Coarse on purpose: store writes are rare and short.
292 fn in_process_write_guard() -> std::sync::MutexGuard<'static, ()> {
293 static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
294 WRITE_LOCK
295 .lock()
296 .unwrap_or_else(|poisoned| poisoned.into_inner())
297 }
298
299 #[cfg(all(test, unix))]
300 mod tests {
301 use super::*;
302 use std::os::unix::fs::PermissionsExt;
303 use std::path::PathBuf;
304
305 /// Put a store file on disk with exactly `mode`, the way a user running
306 /// `chmod` on an existing `secrets.json` leaves it.
307 fn store_at(dir: &Path, mode: u32) -> PathBuf {
308 let path = dir.join("secrets.json");
309 fs::write(&path, "{\"entries\":{}}").unwrap();
310 fs::set_permissions(&path, fs::Permissions::from_mode(mode)).unwrap();
311 assert_eq!(
312 fs::metadata(&path).unwrap().permissions().mode() & 0o777,
313 mode,
314 "the test filesystem did not store {mode:o} verbatim"
315 );
316 path
317 }
318
319 fn names_in(dir: &Path) -> Vec<String> {
320 fs::read_dir(dir)
321 .unwrap()
322 .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
323 .collect()
324 }
325
326 #[test]
327 fn owner_only_store_opens() {
328 let tmp = tempfile::tempdir().unwrap();
329 let path = store_at(tmp.path(), 0o600);
330 open_private(&path, false, StoreFile::Content).expect("an 0600 store must open");
331 assert_eq!(
332 names_in(tmp.path()),
333 vec!["secrets.json".to_string()],
334 "an 0600 store must be accepted without writing a probe file"
335 );
336 }
337
338 #[test]
339 fn store_created_on_first_write_is_owner_only() {
340 let tmp = tempfile::tempdir().unwrap();
341 let path = tmp.path().join("secrets.json");
342 open_private(&path, true, StoreFile::Content).expect("create must succeed");
343 assert_eq!(
344 fs::metadata(&path).unwrap().permissions().mode() & 0o777,
345 0o600,
346 "a freshly created store must be owner-only"
347 );
348 }
349
350 /// Every wider mode on a filesystem that stores mode bits is a real
351 /// exposure and must stay refused. The probe runs here for real, against
352 /// this directory, and has to answer "this mount stores modes".
353 #[test]
354 fn wider_store_is_refused_with_its_observed_mode() {
355 for mode in [0o660, 0o640, 0o644, 0o666, 0o606] {
356 let tmp = tempfile::tempdir().unwrap();
357 let path = store_at(tmp.path(), mode);
358 let err = open_private(&path, false, StoreFile::Content).unwrap_err();
359 match err {
360 SecretsError::InsecurePermissions {
361 path: seen,
362 mode: seen_mode,
363 } => {
364 assert_eq!(seen, path);
365 assert_eq!(seen_mode, mode);
366 }
367 other => panic!("mode {mode:o} must be refused; got: {other}"),
368 }
369 assert_eq!(
370 fs::metadata(&path).unwrap().permissions().mode() & 0o777,
371 mode,
372 "a refused store is left exactly as it was found"
373 );
374 }
375 }
376
377 /// The lock file carries no secret, so a wide mode on it is hygiene rather
378 /// than evidence, and the "narrow what can be narrowed" rule applies: the
379 /// store opens and the file ends up `0600`. This is the case a user hits
380 /// after restoring a backup, and the one whose refusal read as "your secret
381 /// backend is broken".
382 #[test]
383 fn wide_lock_file_is_repaired_in_place() {
384 let tmp = tempfile::tempdir().unwrap();
385 let lock = tmp.path().join("secrets.json.lock");
386 fs::write(&lock, b"").unwrap();
387 fs::set_permissions(&lock, fs::Permissions::from_mode(0o660)).unwrap();
388 open_private(&lock, false, StoreFile::Lock)
389 .expect("a wide lock must be repaired, not refused");
390 assert_eq!(
391 fs::metadata(&lock).unwrap().permissions().mode() & 0o777,
392 0o600,
393 "the repair must actually be applied"
394 );
395 assert_eq!(
396 names_in(tmp.path()),
397 vec!["secrets.json.lock".to_string()],
398 "a repair must not need the probe"
399 );
400 }
401
402 /// The classification is the whole decision, and the cases that matter need
403 /// a mount that refuses `chmod` or accepts it without applying it, which no
404 /// portable
405 /// filesystem produces. They are pinned here instead.
406 #[test]
407 fn store_mode_classification_covers_every_outcome() {
408 // The mount stored the narrowing we asked for.
409 assert_eq!(
410 classify_store_mode(0o660, Some(0o600), false),
411 StoreMode::Narrowed
412 );
413 // hmdfs: the call is accepted and the mount keeps its own mode.
414 assert_eq!(
415 classify_store_mode(0o660, Some(0o660), true),
416 StoreMode::Unavoidable { mode: 0o660 }
417 );
418 // hmdfs/POSIX-less mount: the call is refused.
419 assert_eq!(
420 classify_store_mode(0o660, None, true),
421 StoreMode::Unavoidable { mode: 0o660 }
422 );
423 // A mode-storing mount that accepted the call and ignored it is a real
424 // exposure, and the observed mode is what the caller is told about.
425 assert_eq!(
426 classify_store_mode(0o660, Some(0o660), false),
427 StoreMode::Exposed { mode: 0o660 }
428 );
429 assert_eq!(
430 classify_store_mode(0o660, None, false),
431 StoreMode::Exposed { mode: 0o660 }
432 );
433 // A successful narrowing to something still wider is not a repair.
434 assert_eq!(
435 classify_store_mode(0o666, Some(0o660), false),
436 StoreMode::Exposed { mode: 0o660 }
437 );
438 }
439
440 #[test]
441 fn probe_reports_a_mode_storing_filesystem() {
442 let tmp = tempfile::tempdir().unwrap();
443 assert!(
444 !mount_ignores_unix_modes(&tmp.path().join("secrets.json")),
445 "a local filesystem stores the 0600 a file is created with"
446 );
447 }
448
449 #[test]
450 fn probe_leaves_nothing_behind() {
451 let tmp = tempfile::tempdir().unwrap();
452 let before = names_in(tmp.path());
453 assert!(!mount_ignores_unix_modes(&tmp.path().join("secrets.json")));
454 assert_eq!(names_in(tmp.path()), before);
455 }
456
457 #[test]
458 fn probe_answers_false_without_a_parent_directory() {
459 assert!(!mount_ignores_unix_modes(Path::new("secrets.json")));
460 }
461
462 #[test]
463 fn a_held_lock_is_not_mistaken_for_a_missing_one() {
464 // EWOULDBLOCK is what a lock held by another process reports; treating
465 // it as "no locking on this mount" would silently drop serialisation.
466 assert!(!advisory_locking_unavailable(
467 &std::io::Error::from_raw_os_error(libc::EWOULDBLOCK)
468 ));
469 assert!(!advisory_locking_unavailable(
470 &std::io::Error::from_raw_os_error(libc::EINTR)
471 ));
472 for errno in [libc::EPERM, libc::EACCES, libc::ENOTSUP, libc::EINVAL] {
473 assert!(
474 advisory_locking_unavailable(&std::io::Error::from_raw_os_error(errno)),
475 "errno {errno} means the filesystem has no advisory locks"
476 );
477 }
478 }
479 }
480
480 lines RUST