blivet 0.5.0

A correct, full-featured Unix daemon library and CLI for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! Daemon configuration with builder pattern and pre-fork validation.

use std::path::PathBuf;

use nix::sys::stat::Mode;

use crate::error::DaemonizeError;
use crate::util::paths_same;

/// Configuration for the daemonization process.
///
/// All fields are private; use builder methods to configure.
/// All builder methods are infallible; validation is centralized in [`validate`](DaemonConfig::validate).
///
/// # Example
///
/// ```
/// use blivet::DaemonConfig;
///
/// let mut config = DaemonConfig::new();
/// config.pidfile("/var/run/foo.pid").chdir("/tmp");
/// ```
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct DaemonConfig {
    pub(crate) pidfile: Option<PathBuf>,
    pub(crate) chdir: PathBuf,
    pub(crate) umask: Mode,
    pub(crate) stdout: Option<PathBuf>,
    pub(crate) stderr: Option<PathBuf>,
    pub(crate) append: bool,
    pub(crate) lockfile: Option<PathBuf>,
    pub(crate) user: Option<String>,
    pub(crate) group: Option<String>,
    pub(crate) foreground: bool,
    pub(crate) close_fds: bool,
    pub(crate) cleanup_on_drop: bool,
    pub(crate) env: Vec<(String, String)>,
}

impl Default for DaemonConfig {
    fn default() -> Self {
        Self {
            pidfile: None,
            chdir: PathBuf::from("/"),
            umask: Mode::empty(),
            stdout: None,
            stderr: None,
            append: false,
            lockfile: None,
            user: None,
            group: None,
            foreground: false,
            close_fds: true,
            cleanup_on_drop: true,
            env: Vec::new(),
        }
    }
}

impl DaemonConfig {
    /// Creates a new `DaemonConfig` with default values.
    ///
    /// Equivalent to [`Default::default()`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the pidfile path. Default: none.
    pub fn pidfile(&mut self, path: impl Into<PathBuf>) -> &mut Self {
        self.pidfile = Some(path.into());
        self
    }

    /// Sets the working directory. Default: `/`.
    pub fn chdir(&mut self, path: impl Into<PathBuf>) -> &mut Self {
        self.chdir = path.into();
        self
    }

    /// Sets the process umask. Default: `Mode::empty()` (0).
    pub fn umask(&mut self, mode: Mode) -> &mut Self {
        self.umask = mode;
        self
    }

    /// Sets the stdout redirect file path. Default: none (stays `/dev/null`).
    pub fn stdout(&mut self, path: impl Into<PathBuf>) -> &mut Self {
        self.stdout = Some(path.into());
        self
    }

    /// Sets the stderr redirect file path. Default: none (stays `/dev/null`).
    pub fn stderr(&mut self, path: impl Into<PathBuf>) -> &mut Self {
        self.stderr = Some(path.into());
        self
    }

    /// Sets whether to append to stdout/stderr files. Default: `false`.
    pub fn append(&mut self, append: bool) -> &mut Self {
        self.append = append;
        self
    }

    /// Sets the lockfile path. Default: none.
    pub fn lockfile(&mut self, path: impl Into<PathBuf>) -> &mut Self {
        self.lockfile = Some(path.into());
        self
    }

    /// Sets the user to run the daemon as. Default: none (no user switch).
    ///
    /// Accepts a username string or a numeric UID (as a string, e.g. `"1000"`).
    /// Resolution happens at runtime in [`DaemonContext::drop_privileges`](crate::DaemonContext::drop_privileges).
    pub fn user(&mut self, name: impl Into<String>) -> &mut Self {
        self.user = Some(name.into());
        self
    }

    /// Sets the group to run the daemon as. Default: none (use user's primary group).
    ///
    /// Accepts a group name string or a numeric GID (as a string, e.g. `"1000"`).
    /// Resolution happens at runtime in [`DaemonContext::drop_privileges`](crate::DaemonContext::drop_privileges).
    pub fn group(&mut self, name: impl Into<String>) -> &mut Self {
        self.group = Some(name.into());
        self
    }

    /// Sets foreground mode. Default: `false`.
    ///
    /// When `true`, daemonization skips both forks, `setsid`, and the
    /// notification pipe. Stdout and stderr are left inherited (not
    /// redirected to `/dev/null`) unless explicitly configured with
    /// [`stdout`](DaemonConfig::stdout)/[`stderr`](DaemonConfig::stderr).
    /// All other steps (umask, chdir, signal reset, etc.) still execute.
    pub fn foreground(&mut self, foreground: bool) -> &mut Self {
        self.foreground = foreground;
        self
    }

    /// Sets whether to close inherited file descriptors. Default: `true`.
    ///
    /// When `false`, file descriptors 3+ are left open. Useful in
    /// foreground mode when running under a supervisor that passes
    /// file descriptors.
    pub fn close_fds(&mut self, close_fds: bool) -> &mut Self {
        self.close_fds = close_fds;
        self
    }

    /// Sets whether to remove the pidfile on drop. Default: `true`.
    ///
    /// When `true`, dropping [`DaemonContext`](crate::DaemonContext) removes
    /// the pidfile from disk. Can be overridden at runtime via
    /// [`DaemonContext::set_cleanup_on_drop`](crate::DaemonContext::set_cleanup_on_drop).
    pub fn cleanup_on_drop(&mut self, cleanup: bool) -> &mut Self {
        self.cleanup_on_drop = cleanup;
        self
    }

    /// Adds an environment variable. Each call accumulates; last-write-wins
    /// for duplicate keys at application time.
    pub fn env(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.env.push((key.into(), value.into()));
        self
    }

    /// Validates the configuration.
    ///
    /// Performs minimal I/O: checks path existence, directory writability
    /// (via `faccessat(AT_EACCESS)`), and queries the effective UID when a
    /// user switch is configured. No files are created or modified.
    ///
    /// # Errors
    ///
    /// Returns `DaemonizeError::ValidationError` if:
    /// - Any configured path (pidfile, stdout, stderr, lockfile) is not absolute
    /// - The chdir path is not absolute, does not exist, or is not a directory
    /// - The pidfile path is a directory
    /// - Parent directories of configured paths are not writable
    /// - Lockfile or pidfile overlaps with stdout or stderr
    /// - An environment key is empty or contains `=`
    /// - A user is configured but the effective UID is not 0
    #[must_use = "validate() returns a Result that must be checked"]
    pub fn validate(&self) -> Result<(), DaemonizeError> {
        // Check chdir is absolute, exists, and is a directory
        if !self.chdir.is_absolute() {
            return Err(DaemonizeError::ValidationError(
                "chdir path must be absolute".into(),
            ));
        }
        if !self.chdir.exists() {
            return Err(DaemonizeError::ValidationError(
                "chdir path does not exist".into(),
            ));
        }
        if !self.chdir.is_dir() {
            return Err(DaemonizeError::ValidationError(
                "chdir path is not a directory".into(),
            ));
        }

        // Check pidfile
        if let Some(ref p) = self.pidfile {
            validate_absolute(p, "pidfile")?;
            if p.is_dir() {
                return Err(DaemonizeError::ValidationError(
                    "pidfile path is a directory".into(),
                ));
            }
            validate_parent_writable(p, "pidfile")?;
        }

        // Check stdout
        if let Some(ref p) = self.stdout {
            validate_absolute(p, "stdout")?;
            validate_parent_writable(p, "stdout")?;
        }

        // Check stderr
        if let Some(ref p) = self.stderr {
            validate_absolute(p, "stderr")?;
            validate_parent_writable(p, "stderr")?;
        }

        // Check lockfile
        if let Some(ref p) = self.lockfile {
            validate_absolute(p, "lockfile")?;
            validate_parent_writable(p, "lockfile")?;
        }

        // Path overlap checks: lockfile/pidfile must not equal stdout/stderr
        if let Some(ref lockfile) = self.lockfile {
            if let Some(ref stdout) = self.stdout {
                if paths_same(lockfile, stdout) {
                    return Err(DaemonizeError::ValidationError(
                        "lockfile and stdout must not be the same path".into(),
                    ));
                }
            }
            if let Some(ref stderr) = self.stderr {
                if paths_same(lockfile, stderr) {
                    return Err(DaemonizeError::ValidationError(
                        "lockfile and stderr must not be the same path".into(),
                    ));
                }
            }
        }
        if let Some(ref pidfile) = self.pidfile {
            if let Some(ref stdout) = self.stdout {
                if paths_same(pidfile, stdout) {
                    return Err(DaemonizeError::ValidationError(
                        "pidfile and stdout must not be the same path".into(),
                    ));
                }
            }
            if let Some(ref stderr) = self.stderr {
                if paths_same(pidfile, stderr) {
                    return Err(DaemonizeError::ValidationError(
                        "pidfile and stderr must not be the same path".into(),
                    ));
                }
            }
        }

        // Environment key validation
        for (key, _) in &self.env {
            if key.is_empty() {
                return Err(DaemonizeError::ValidationError(
                    "environment key must not be empty".into(),
                ));
            }
            if key.contains('=') {
                return Err(DaemonizeError::ValidationError(format!(
                    "environment key must not contain '=': {key}"
                )));
            }
        }

        // User/group validation: must be root to switch users or groups
        if (self.user.is_some() || self.group.is_some()) && nix::unistd::geteuid().as_raw() != 0 {
            return Err(DaemonizeError::PermissionDenied(
                "must be root to switch users or groups".into(),
            ));
        }

        Ok(())
    }
}

fn validate_absolute(path: &std::path::Path, name: &str) -> Result<(), DaemonizeError> {
    if !path.is_absolute() {
        return Err(DaemonizeError::ValidationError(format!(
            "{name} path must be absolute"
        )));
    }
    Ok(())
}

fn validate_parent_writable(path: &std::path::Path, name: &str) -> Result<(), DaemonizeError> {
    use nix::fcntl::AtFlags;
    use nix::unistd::AccessFlags;

    let parent = path.parent().ok_or_else(|| {
        DaemonizeError::ValidationError(format!("{name} path has no parent directory"))
    })?;
    if !parent.exists() {
        return Err(DaemonizeError::ValidationError(format!(
            "{name} parent directory does not exist"
        )));
    }
    // Check writability using faccessat(AT_EACCESS) which tests against the
    // effective UID/GID rather than the real UID (important for setuid binaries).
    match nix::unistd::faccessat(
        crate::unsafe_ops::at_fdcwd(),
        parent,
        AccessFlags::W_OK,
        AtFlags::AT_EACCESS,
    ) {
        Ok(()) => Ok(()),
        Err(_) => Err(DaemonizeError::ValidationError(format!(
            "{name} parent directory is not writable"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_equals_default() {
        assert_eq!(DaemonConfig::new(), DaemonConfig::default());
    }

    #[test]
    fn default_values() {
        let config = DaemonConfig::default();
        assert_eq!(config.pidfile, None);
        assert_eq!(config.chdir, PathBuf::from("/"));
        assert_eq!(config.umask, Mode::empty());
        assert_eq!(config.stdout, None);
        assert_eq!(config.stderr, None);
        assert!(!config.append);
        assert_eq!(config.lockfile, None);
        assert_eq!(config.user, None);
        assert_eq!(config.group, None);
        assert!(!config.foreground);
        assert!(config.close_fds);
        assert!(config.env.is_empty());
    }

    #[test]
    fn builder_setters_replace() {
        let mut config = DaemonConfig::new();
        config.pidfile("/a").pidfile("/b");
        assert_eq!(config.pidfile, Some(PathBuf::from("/b")));
    }

    #[test]
    fn env_accumulates() {
        let mut config = DaemonConfig::new();
        config.env("A", "1").env("B", "2").env("A", "3");
        assert_eq!(
            config.env,
            vec![
                ("A".into(), "1".into()),
                ("B".into(), "2".into()),
                ("A".into(), "3".into()),
            ]
        );
    }

    #[test]
    fn validate_chdir_must_be_absolute() {
        let mut config = DaemonConfig::new();
        config.chdir("relative/path");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_chdir_must_exist() {
        let mut config = DaemonConfig::new();
        config.chdir("/nonexistent_daemonize_test_dir");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_pidfile_must_be_absolute() {
        let mut config = DaemonConfig::new();
        config.pidfile("relative.pid");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_pidfile_not_directory() {
        let mut config = DaemonConfig::new();
        config.pidfile("/tmp");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_stdout_must_be_absolute() {
        let mut config = DaemonConfig::new();
        config.stdout("relative.log");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_stderr_must_be_absolute() {
        let mut config = DaemonConfig::new();
        config.stderr("relative.log");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_lockfile_must_be_absolute() {
        let mut config = DaemonConfig::new();
        config.lockfile("relative.lock");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_lockfile_pidfile_same_ok() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("combined.pid");
        let path_str = path.to_str().unwrap();
        let mut config = DaemonConfig::new();
        config.lockfile(path_str).pidfile(path_str);
        // Should not fail on overlap between lockfile and pidfile
        // (may fail for other reasons like non-root user, but not overlap)
        let result = config.validate();
        assert!(
            !matches!(&result, Err(DaemonizeError::ValidationError(msg)) if msg.contains("same path"))
        );
    }

    #[test]
    fn validate_lockfile_stdout_overlap_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("file.log");
        let path_str = path.to_str().unwrap();
        let mut config = DaemonConfig::new();
        config.lockfile(path_str).stdout(path_str);
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_pidfile_stderr_overlap_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("file.log");
        let path_str = path.to_str().unwrap();
        let mut config = DaemonConfig::new();
        config.pidfile(path_str).stderr(path_str);
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_env_key_empty_rejected() {
        let mut config = DaemonConfig::new();
        config.env("", "value");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_env_key_with_equals_rejected() {
        let mut config = DaemonConfig::new();
        config.env("KEY=BAD", "value");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_default_config_ok() {
        // Default config should validate (we're not root, no user switch)
        assert!(DaemonConfig::new().validate().is_ok());
    }

    #[test]
    fn exit_codes() {
        assert_eq!(
            DaemonizeError::ValidationError(String::new()).exit_code(),
            64
        );
        assert_eq!(
            DaemonizeError::ProgramNotFound(String::new()).exit_code(),
            66
        );
        assert_eq!(DaemonizeError::UserNotFound(String::new()).exit_code(), 67);
        assert_eq!(DaemonizeError::GroupNotFound(String::new()).exit_code(), 67);
        assert_eq!(DaemonizeError::LockConflict(String::new()).exit_code(), 69);
        assert_eq!(DaemonizeError::LockfileError(String::new()).exit_code(), 73);
        assert_eq!(DaemonizeError::ForkFailed(String::new()).exit_code(), 71);
        assert_eq!(DaemonizeError::SetsidFailed(String::new()).exit_code(), 71);
        assert_eq!(DaemonizeError::ChdirFailed(String::new()).exit_code(), 71);
        assert_eq!(
            DaemonizeError::PermissionDenied(String::new()).exit_code(),
            77
        );
        assert_eq!(DaemonizeError::PidfileError(String::new()).exit_code(), 73);
        assert_eq!(
            DaemonizeError::OutputFileError(String::new()).exit_code(),
            73
        );
        assert_eq!(DaemonizeError::ChownError(String::new()).exit_code(), 73);
        assert_eq!(DaemonizeError::ExecFailed(String::new()).exit_code(), 71);
    }

    #[test]
    fn send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<DaemonConfig>();
        assert_send_sync::<crate::DaemonContext>();
        assert_send_sync::<DaemonizeError>();
    }

    #[test]
    fn validate_chdir_must_be_directory() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("not_a_dir");
        std::fs::write(&file, "").unwrap();
        let mut config = DaemonConfig::new();
        config.chdir(&file);
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(msg)) if msg.contains("not a directory")
        ));
    }

    #[test]
    fn validate_lockfile_stderr_overlap_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("file.log");
        let path_str = path.to_str().unwrap();
        let mut config = DaemonConfig::new();
        config.lockfile(path_str).stderr(path_str);
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_pidfile_stdout_overlap_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("file.log");
        let path_str = path.to_str().unwrap();
        let mut config = DaemonConfig::new();
        config.pidfile(path_str).stdout(path_str);
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(_))
        ));
    }

    #[test]
    fn validate_pidfile_parent_nonwritable() {
        let mut config = DaemonConfig::new();
        config.pidfile("/nonexistent_parent_dir_xyz/test.pid");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(msg)) if msg.contains("parent")
        ));
    }

    #[test]
    fn validate_stdout_parent_nonwritable() {
        let mut config = DaemonConfig::new();
        config.stdout("/nonexistent_parent_dir_xyz/test.log");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(msg)) if msg.contains("parent")
        ));
    }

    #[test]
    fn validate_stderr_parent_nonwritable() {
        let mut config = DaemonConfig::new();
        config.stderr("/nonexistent_parent_dir_xyz/test.log");
        assert!(matches!(
            config.validate(),
            Err(DaemonizeError::ValidationError(msg)) if msg.contains("parent")
        ));
    }

    #[test]
    fn paths_same_canonicalize_fallback() {
        // Paths that don't exist — canonicalize will fail, should fall back to byte comparison
        assert!(paths_same(
            std::path::Path::new("/nonexistent/a"),
            std::path::Path::new("/nonexistent/a"),
        ));
        assert!(!paths_same(
            std::path::Path::new("/nonexistent/a"),
            std::path::Path::new("/nonexistent/b"),
        ));
    }

    #[test]
    fn display_includes_prefix() {
        let err = DaemonizeError::ValidationError("test message".into());
        assert_eq!(err.to_string(), "validation error: test message");
    }

    #[test]
    fn validate_rejects_invalid_config_before_fork() {
        // Verify validate() catches errors that would otherwise only surface post-fork
        let mut config = DaemonConfig::new();
        config.pidfile("relative.pid");
        let result = config.validate();
        assert!(result.is_err());
        // The important thing: this was checked without forking
    }

    #[test]
    fn group_builder_sets_field() {
        let mut config = DaemonConfig::new();
        config.group("wheel");
        assert_eq!(config.group, Some("wheel".into()));
    }

    #[test]
    fn foreground_builder_sets_field() {
        let mut config = DaemonConfig::new();
        config.foreground(true);
        assert!(config.foreground);
    }

    #[test]
    fn close_fds_builder_sets_field() {
        let mut config = DaemonConfig::new();
        config.close_fds(false);
        assert!(!config.close_fds);
    }

    #[test]
    fn validate_group_requires_root() {
        // Non-root with group should fail validation
        if nix::unistd::geteuid().as_raw() != 0 {
            let mut config = DaemonConfig::new();
            config.group("wheel");
            assert!(matches!(
                config.validate(),
                Err(DaemonizeError::PermissionDenied(_))
            ));
        }
    }

    #[test]
    fn validate_user_or_group_requires_root() {
        // Non-root with user should fail validation (existing behavior)
        if nix::unistd::geteuid().as_raw() != 0 {
            let mut config = DaemonConfig::new();
            config.user("nobody");
            assert!(matches!(
                config.validate(),
                Err(DaemonizeError::PermissionDenied(_))
            ));
        }
    }
}