Skip to main content

subc_daemon/config_store/
writer_lock.rs

1//! A service store has one live writer, independent of daemon discovery paths.
2
3use fs4::{FileExt, TryLockError};
4use std::{
5    fs::{self, File},
6    io,
7    path::{Component, Path, PathBuf},
8};
9
10#[derive(Debug)]
11pub enum WriterLockError {
12    Busy { root: PathBuf },
13    Invalid { root: PathBuf, source: io::Error },
14}
15
16impl std::fmt::Display for WriterLockError {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        match self {
19            Self::Busy { root } => write!(
20                f,
21                "config_store_busy: configuration store {} already has a live owner",
22                root.display()
23            ),
24            Self::Invalid { root, source } => write!(
25                f,
26                "config_store_lock_invalid: configuration store {}: {source}",
27                root.display()
28            ),
29        }
30    }
31}
32impl std::error::Error for WriterLockError {
33    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
34        match self {
35            Self::Invalid { source, .. } => Some(source),
36            _ => None,
37        }
38    }
39}
40
41/// An OS lock held until the store owner exits. The sibling file is never
42/// deleted: removing a locked inode would let another daemon lock its replacement.
43#[derive(Debug)]
44pub struct StoreWriterLock {
45    file: File,
46}
47
48impl StoreWriterLock {
49    #[cfg(any(target_os = "linux", target_os = "macos"))]
50    pub(crate) fn from_inherited(file: File) -> Self {
51        Self { file }
52    }
53
54    #[cfg(any(target_os = "linux", target_os = "macos"))]
55    pub(crate) fn inherited_layout(
56        root: &Path,
57    ) -> Result<(super::StoreRoot, PathBuf), WriterLockError> {
58        writer_layout(root, verify_directory)
59    }
60
61    #[cfg(any(target_os = "linux", target_os = "macos"))]
62    pub(crate) fn file(&self) -> &File {
63        &self.file
64    }
65    /// Canonicalize the owned parent and lock a sibling without creating the
66    /// store root. This preserves the store's read-only startup contract.
67    pub fn acquire(root: &Path) -> Result<(super::StoreRoot, Self), WriterLockError> {
68        let invalid = |source| WriterLockError::Invalid {
69            root: root.into(),
70            source,
71        };
72        let (canonical_root, path) = writer_layout(root, ensure_parent)?;
73        let file = match create_lock(&path) {
74            Ok(file) => file,
75            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
76                subc_os::open_regular_nofollow(&path)
77                    .map_err(|error| invalid(io::Error::other(error)))?
78            }
79            Err(error) => return Err(invalid(error)),
80        };
81        verify_file(&file).map_err(invalid)?;
82        match FileExt::try_lock(&file) {
83            Ok(()) => {}
84            Err(TryLockError::WouldBlock) => {
85                return Err(WriterLockError::Busy {
86                    root: canonical_root.path().to_path_buf(),
87                })
88            }
89            Err(TryLockError::Error(error)) => return Err(invalid(error)),
90        }
91        Ok((canonical_root, Self { file }))
92    }
93}
94
95fn writer_layout(
96    root: &Path,
97    check_parent: impl FnOnce(&Path) -> io::Result<()>,
98) -> Result<(super::StoreRoot, PathBuf), WriterLockError> {
99    let invalid = |source| WriterLockError::Invalid {
100        root: root.into(),
101        source,
102    };
103    let leaf = match root.components().next_back() {
104        Some(Component::Normal(leaf)) if root.is_absolute() => leaf,
105        _ => {
106            return Err(invalid(io::Error::other(
107                "store root must have an absolute ordinary name",
108            )))
109        }
110    };
111    let parent = root
112        .parent()
113        .ok_or_else(|| invalid(io::Error::other("store root has no parent")))?;
114    check_parent(parent).map_err(invalid)?;
115    let parent = fs::canonicalize(parent).map_err(invalid)?;
116    verify_directory(&parent).map_err(invalid)?;
117    let canonical_root = parent.join(leaf);
118    match fs::symlink_metadata(&canonical_root) {
119        Ok(_) => verify_directory(&canonical_root).map_err(invalid)?,
120        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
121        Err(error) => return Err(invalid(error)),
122    }
123    let mut name = leaf.to_os_string();
124    name.push(".lock");
125    Ok((
126        super::StoreRoot::from_service_definition(canonical_root).map_err(invalid)?,
127        parent.join(name),
128    ))
129}
130
131impl Drop for StoreWriterLock {
132    fn drop(&mut self) {
133        // Explicit unlock also releases a description briefly inherited by fork
134        // before exec; an unrelated child must not prolong daemon ownership.
135        let _ = FileExt::unlock(&self.file);
136    }
137}
138
139fn ensure_parent(path: &Path) -> io::Result<()> {
140    match fs::symlink_metadata(path) {
141        Ok(_) => verify_directory(path),
142        Err(error) if error.kind() == io::ErrorKind::NotFound => {
143            if let Some(parent) = path.parent() {
144                ensure_parent(parent)?;
145            }
146            #[cfg(unix)]
147            {
148                use std::os::unix::fs::DirBuilderExt;
149                match fs::DirBuilder::new().mode(0o700).create(path) {
150                    Ok(()) => {}
151                    Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
152                    Err(error) => return Err(error),
153                }
154            }
155            #[cfg(windows)]
156            subc_os::windows_acl::create_private_dir(path)?;
157            verify_directory(path)
158        }
159        Err(error) => Err(error),
160    }
161}
162
163fn verify_directory(path: &Path) -> io::Result<()> {
164    let metadata = fs::symlink_metadata(path)?;
165    if !metadata.is_dir() || metadata.file_type().is_symlink() {
166        return Err(io::Error::other(
167            "store parent/root must be an owned non-symlink directory",
168        ));
169    }
170    #[cfg(unix)]
171    {
172        use std::os::unix::fs::MetadataExt;
173        if metadata.uid() != subc_os::effective_uid() || metadata.mode() & 0o022 != 0 {
174            return Err(io::Error::other(
175                "store parent/root must be owned and not writable by other users",
176            ));
177        }
178    }
179    #[cfg(windows)]
180    subc_os::windows_acl::verify_private_dir(path)?;
181    Ok(())
182}
183
184fn create_lock(path: &Path) -> io::Result<File> {
185    #[cfg(windows)]
186    {
187        subc_os::windows_acl::create_private_file(path)
188    }
189    #[cfg(not(windows))]
190    {
191        let mut options = fs::OpenOptions::new();
192        options.read(true).write(true).create_new(true);
193        #[cfg(unix)]
194        {
195            use std::os::unix::fs::OpenOptionsExt;
196            options.mode(0o600);
197        }
198        options.open(path)
199    }
200}
201
202fn verify_file(file: &File) -> io::Result<()> {
203    let metadata = file.metadata()?;
204    if !metadata.is_file() {
205        return Err(io::Error::other("writer lock is not a regular file"));
206    }
207    #[cfg(unix)]
208    {
209        use std::os::unix::fs::MetadataExt;
210        if metadata.uid() != subc_os::effective_uid() || metadata.mode() & 0o077 != 0 {
211            return Err(io::Error::other("writer lock must be owner-only"));
212        }
213    }
214    #[cfg(windows)]
215    subc_os::windows_acl::verify_owner_only(file)?;
216    Ok(())
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use std::{
223        process::{Child, Command, Stdio},
224        time::{Duration, Instant},
225    };
226
227    struct Rig(cortexkit_test_support::ScratchDir);
228    impl Rig {
229        fn new() -> Self {
230            let path = cortexkit_test_support::ScratchDir::new("subc-store-lock");
231            #[cfg(windows)]
232            subc_os::windows_acl::create_private_dir(path.path()).unwrap();
233            Self(path)
234        }
235        fn root(&self) -> PathBuf {
236            self.0.join("authority")
237        }
238    }
239    struct KillOnDrop(Child);
240    impl Drop for KillOnDrop {
241        fn drop(&mut self) {
242            let _ = self.0.kill();
243            let _ = self.0.wait();
244        }
245    }
246
247    #[test]
248    fn config_store_writer_lock_refuses_second_owner_without_creating_root() {
249        let rig = Rig::new();
250        let root = rig.root();
251        let (canonical, first) = StoreWriterLock::acquire(&root).unwrap();
252        assert_eq!(
253            canonical.path(),
254            fs::canonicalize(rig.0.path()).unwrap().join("authority")
255        );
256        assert!(!root.exists());
257        assert!(
258            matches!(StoreWriterLock::acquire(&root),Err(WriterLockError::Busy { root: refused }) if refused == canonical.path())
259        );
260        let text = StoreWriterLock::acquire(&root).err().unwrap().to_string();
261        assert!(text.contains("config_store_busy") && text.contains("authority"));
262        drop(first);
263        let (_, _next) = StoreWriterLock::acquire(&root).unwrap();
264        assert!(!root.exists());
265        #[cfg(unix)]
266        {
267            use std::os::unix::fs::MetadataExt;
268            assert_eq!(
269                fs::metadata(rig.0.join("authority.lock")).unwrap().mode() & 0o777,
270                0o600
271            );
272        }
273    }
274
275    #[test]
276    fn config_store_writer_lock_releases_when_owning_process_exits() {
277        let rig = Rig::new();
278        let root = rig.root();
279        let mut child = KillOnDrop(
280            Command::new(std::env::current_exe().unwrap())
281                .arg("--exact")
282                .arg("config_store::writer_lock::tests::config_store_writer_lock_child_probe")
283                .arg("--ignored")
284                .env("SUBC_WRITER_LOCK_CHILD_ROOT", &root)
285                .stdout(Stdio::null())
286                .stderr(Stdio::null())
287                .spawn()
288                .unwrap(),
289        );
290        let deadline = Instant::now() + Duration::from_secs(5);
291        while !rig.0.join("held").exists() {
292            assert!(
293                child.0.try_wait().unwrap().is_none(),
294                "writer-lock probe exited before acquiring"
295            );
296            assert!(
297                Instant::now() < deadline,
298                "writer-lock probe did not acquire before deadline"
299            );
300            std::thread::sleep(Duration::from_millis(10));
301        }
302        assert!(matches!(
303            StoreWriterLock::acquire(&root),
304            Err(WriterLockError::Busy { .. })
305        ));
306        child.0.kill().unwrap();
307        child.0.wait().unwrap();
308        let (_, _next) = StoreWriterLock::acquire(&root).unwrap();
309        assert!(!root.exists());
310    }
311
312    #[test]
313    #[ignore = "child probe invoked by its bounded parent test"]
314    fn config_store_writer_lock_child_probe() {
315        let root =
316            PathBuf::from(std::env::var_os("SUBC_WRITER_LOCK_CHILD_ROOT").expect("isolated root"));
317        let (_, _lock) = StoreWriterLock::acquire(&root).unwrap();
318        fs::write(root.parent().unwrap().join("held"), b"held").unwrap();
319        loop {
320            std::thread::park();
321        }
322    }
323
324    #[test]
325    fn config_store_writer_lock_creates_only_private_missing_parents() {
326        let rig = Rig::new();
327        let root = rig.0.join("missing/parent/authority");
328        let (_, _lock) = StoreWriterLock::acquire(&root).unwrap();
329        assert!(!root.exists());
330        #[cfg(unix)]
331        {
332            use std::os::unix::fs::MetadataExt;
333            for parent in [rig.0.join("missing"), rig.0.join("missing/parent")] {
334                assert_eq!(fs::metadata(parent).unwrap().mode() & 0o777, 0o700);
335            }
336        }
337    }
338
339    #[cfg(unix)]
340    #[test]
341    fn config_store_writer_lock_refuses_symlink_parent_or_lock_and_broad_lock() {
342        use std::os::unix::fs::{symlink, PermissionsExt};
343        let rig = Rig::new();
344        symlink(&rig.0, rig.0.join("alias")).unwrap();
345        assert!(matches!(
346            StoreWriterLock::acquire(&rig.0.join("alias/authority")),
347            Err(WriterLockError::Invalid { .. })
348        ));
349
350        let ordinary = rig.0.join("ordinary");
351        let lock = rig.0.join("authority.lock");
352        fs::write(&ordinary, b"not a lock").unwrap();
353        fs::set_permissions(&ordinary, fs::Permissions::from_mode(0o600)).unwrap();
354        symlink(&ordinary, &lock).unwrap();
355        assert!(matches!(
356            StoreWriterLock::acquire(&rig.root()),
357            Err(WriterLockError::Invalid { .. })
358        ));
359        fs::remove_file(&lock).unwrap();
360
361        fs::write(&lock, b"broad").unwrap();
362        fs::set_permissions(&lock, fs::Permissions::from_mode(0o644)).unwrap();
363        assert!(matches!(
364            StoreWriterLock::acquire(&rig.root()),
365            Err(WriterLockError::Invalid { .. })
366        ));
367        fs::set_permissions(&lock, fs::Permissions::from_mode(0o600)).unwrap();
368        drop(StoreWriterLock::acquire(&rig.root()).unwrap());
369
370        fs::set_permissions(&rig.0, fs::Permissions::from_mode(0o777)).unwrap();
371        assert!(matches!(
372            StoreWriterLock::acquire(&rig.root()),
373            Err(WriterLockError::Invalid { .. })
374        ));
375        fs::set_permissions(&rig.0, fs::Permissions::from_mode(0o700)).unwrap();
376        drop(StoreWriterLock::acquire(&rig.root()).unwrap());
377    }
378}