Skip to main content

cant_launch/
netns.rs

1//! Can this system make a user + network namespace? (Phase 6.2; docs/NETWORK-ALLOWLIST.md
2//! ยง10.) Host allowlists need one: the can gets a network with only `lo`, and a filtering
3//! proxy outside is its only way out (Phase 6.4). Until then this only *reports*: `cant check`
4//! and `--explain` say whether host enforcement will be possible here, and if not, the step
5//! that failed and the fix.
6//!
7//! [`enter`] changes the calling process for good, so it runs in a short-lived child (`cant
8//! __probe-netns`). [`facts`] and [`hint`] are plain functions of what `/proc` says.
9
10use std::fmt;
11
12/// A step of entering the namespace, in order.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Step {
15    Unshare,
16    Setgroups,
17    UidMap,
18    GidMap,
19    /// Bringing the namespace's loopback interface up.
20    LoUp,
21    /// Binding the proxy's listener inside the namespace.
22    Bind,
23    /// Making the mount namespace's mounts private, or a mount there.
24    Mount,
25}
26
27impl Step {
28    /// The short code `cant __probe-netns` prints.
29    pub fn code(self) -> &'static str {
30        match self {
31            Step::Unshare => "unshare",
32            Step::Setgroups => "setgroups",
33            Step::UidMap => "uid_map",
34            Step::GidMap => "gid_map",
35            Step::LoUp => "lo_up",
36            Step::Bind => "bind",
37            Step::Mount => "mount",
38        }
39    }
40
41    /// The step with this [`Step::code`].
42    pub fn from_code(code: &str) -> Option<Step> {
43        [
44            Step::Unshare,
45            Step::Setgroups,
46            Step::UidMap,
47            Step::GidMap,
48            Step::LoUp,
49            Step::Bind,
50            Step::Mount,
51        ]
52        .into_iter()
53        .find(|s| s.code() == code)
54    }
55}
56
57impl fmt::Display for Step {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        f.write_str(match self {
60            Step::Unshare => "unshare(CLONE_NEWUSER)",
61            Step::Setgroups => "writing /proc/self/setgroups",
62            Step::UidMap => "writing /proc/self/uid_map",
63            Step::GidMap => "writing /proc/self/gid_map",
64            Step::LoUp => "bringing up lo",
65            Step::Bind => "binding the proxy's listener",
66            Step::Mount => "mounting a directory read-only",
67        })
68    }
69}
70
71/// The step that failed, and its errno.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct Failure {
74    pub step: Step,
75    pub errno: i32,
76}
77
78impl fmt::Display for Failure {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        let e = std::io::Error::from_raw_os_error(self.errno);
81        write!(f, "{}: {e}", self.step)
82    }
83}
84
85/// What explains a failure: the sysctls that turn user namespaces off, Ubuntu's AppArmor
86/// restriction, and whether this looks like a container.
87#[derive(Debug, Clone, Default, PartialEq, Eq)]
88pub struct Facts {
89    /// `kernel.apparmor_restrict_unprivileged_userns` (Ubuntu 24.04+).
90    pub apparmor_restrict: Option<u32>,
91    /// `user.max_user_namespaces`.
92    pub max_user_namespaces: Option<u64>,
93    /// `kernel.unprivileged_userns_clone` (Debian's patch).
94    pub unprivileged_userns_clone: Option<u32>,
95    /// `/proc/self/attr/apparmor/current`, e.g. `docker-default (enforce)`.
96    pub apparmor_label: Option<String>,
97    /// `/.dockerenv`, `/run/.containerenv`, `$container`, or a container AppArmor label.
98    pub in_container: bool,
99    /// This `cant`'s executable, canonical.
100    pub exe: Option<std::path::PathBuf>,
101    /// Why [`root_owned`] fails for it, if it does: only a root-owned binary can safely get an
102    /// AppArmor profile.
103    pub exe_writable: Option<String>,
104}
105
106/// Whether `path` and every directory above it belong to root and can't be written by group
107/// or others: only such a binary can safely get an AppArmor profile (anyone who can replace it
108/// would get the profile's rights). The error names the first path that fails.
109pub fn root_owned(path: &std::path::Path) -> Result<(), String> {
110    use std::os::unix::fs::MetadataExt;
111    for p in path.ancestors() {
112        let m = std::fs::metadata(p).map_err(|e| format!("{}: {e}", p.display()))?;
113        if m.uid() != 0 {
114            return Err(format!(
115                "{} belongs to uid {}, not root",
116                p.display(),
117                m.uid()
118            ));
119        }
120        if m.mode() & 0o022 != 0 {
121            return Err(format!(
122                "{} can be written by its group or others",
123                p.display()
124            ));
125        }
126    }
127    Ok(())
128}
129
130/// Reads [`Facts`] from `/proc` and the root directory.
131pub fn facts() -> Facts {
132    let read = |p: &str| {
133        std::fs::read_to_string(p)
134            .ok()
135            .map(|s| s.trim().to_string())
136    };
137    let label = read("/proc/self/attr/apparmor/current");
138    let exe = std::env::current_exe().and_then(std::fs::canonicalize).ok();
139    let in_container = std::path::Path::new("/.dockerenv").exists()
140        || std::path::Path::new("/run/.containerenv").exists()
141        || std::env::var_os("container").is_some()
142        || label.as_deref().is_some_and(|l| {
143            l.starts_with("docker-default") || l.starts_with("containers-default")
144        });
145    Facts {
146        apparmor_restrict: read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
147            .and_then(|s| s.parse().ok()),
148        max_user_namespaces: read("/proc/sys/user/max_user_namespaces")
149            .and_then(|s| s.parse().ok()),
150        unprivileged_userns_clone: read("/proc/sys/kernel/unprivileged_userns_clone")
151            .and_then(|s| s.parse().ok()),
152        apparmor_label: label,
153        in_container,
154        exe_writable: exe.as_deref().and_then(|e| root_owned(e).err()),
155        exe,
156    }
157}
158
159/// Why the namespace can't be made here and what would fix it, in a sentence.
160pub fn hint(f: &Failure, facts: &Facts) -> String {
161    const EPERM: i32 = 1;
162    const EACCES: i32 = 13;
163    if facts.max_user_namespaces == Some(0) {
164        return "user namespaces are turned off (user.max_user_namespaces = 0)".into();
165    }
166    if facts.unprivileged_userns_clone == Some(0) {
167        return "unprivileged user namespaces are turned off \
168                (kernel.unprivileged_userns_clone = 0)"
169            .into();
170    }
171    match (f.step, f.errno) {
172        (Step::Unshare, EPERM) if facts.in_container => "this container's seccomp profile \
173             refuses user namespaces; start it with `--security-opt \
174             seccomp=cant-seccomp.json` (in Cantainer's release files), not with \
175             `apparmor=unconfined`, `seccomp=unconfined` or `--privileged`"
176            .into(),
177        (Step::Setgroups, EACCES) if facts.apparmor_restrict == Some(1) => {
178            let why = "Ubuntu's AppArmor restricts user namespaces for programs without a \
179                       profile (kernel.apparmor_restrict_unprivileged_userns = 1)";
180            let fix = match &facts.exe {
181                Some(e) if e == std::path::Path::new("/usr/bin/cant") => {
182                    "the package's profile isn't loaded: `sudo apparmor_parser -r \
183                     /etc/apparmor.d/cant`, or reinstall the package"
184                        .to_string()
185                }
186                Some(e) => match &facts.exe_writable {
187                    None => format!("give {0} one with `sudo {0} setup apparmor`", e.display()),
188                    Some(why) => format!(
189                        "no profile can safely cover {} ({why}): install the .deb, or put cant \
190                         in a directory only root can write and run `sudo <that path> setup \
191                         apparmor` there",
192                        e.display()
193                    ),
194                },
195                None => "install Cantainer's .deb, which has one".to_string(),
196            };
197            format!("{why}; {fix}")
198        }
199        _ => "user namespaces aren't available to this user here".into(),
200    }
201}
202
203/// Enters a new user + network namespace and maps this user to itself: the steps that fail
204/// where namespaces are restricted. Changes the calling process for good, and must run while
205/// it has a single thread (`cant __probe-netns` calls it first thing).
206#[cfg(target_os = "linux")]
207pub fn enter() -> Result<(), Failure> {
208    enter_with(rustix::thread::UnshareFlags::NEWNET)
209}
210
211/// Like [`enter`], with a new mount namespace instead of a network one (read-only package
212/// trees for a cant that writes the project, without changing its network).
213#[cfg(target_os = "linux")]
214pub fn enter_for_mounts() -> Result<(), Failure> {
215    enter_with(rustix::thread::UnshareFlags::NEWNS)
216}
217
218/// A new user namespace plus `also`, with this user mapped to itself.
219#[cfg(target_os = "linux")]
220fn enter_with(also: rustix::thread::UnshareFlags) -> Result<(), Failure> {
221    use rustix::thread::UnshareFlags;
222    let uid = rustix::process::getuid().as_raw();
223    let gid = rustix::process::getgid().as_raw();
224    let fail = |step| {
225        move |e: std::io::Error| Failure {
226            step,
227            errno: e.raw_os_error().unwrap_or(0),
228        }
229    };
230    // rustix deprecates the safe `unshare` in favour of an `unsafe` one, because unsharing in a
231    // process with several threads leaves them in different namespaces. This process has one
232    // thread, and the crates forbid `unsafe`.
233    #[allow(deprecated)]
234    rustix::thread::unshare(UnshareFlags::NEWUSER | also)
235        .map_err(std::io::Error::from)
236        .map_err(fail(Step::Unshare))?;
237    std::fs::write("/proc/self/setgroups", "deny").map_err(fail(Step::Setgroups))?;
238    std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1")).map_err(fail(Step::UidMap))?;
239    std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1")).map_err(fail(Step::GidMap))?;
240    Ok(())
241}
242
243/// Not Linux: no namespaces.
244#[cfg(not(target_os = "linux"))]
245pub fn enter() -> Result<(), Failure> {
246    Err(Failure {
247        step: Step::Unshare,
248        errno: 38, // ENOSYS
249    })
250}
251
252/// `RTM_NEWLINK` for interface index 1 (`lo` in a new namespace) with `IFF_UP`, asking for an
253/// acknowledgement: a 16-byte `nlmsghdr` and a 16-byte `ifinfomsg`, in this machine's byte order.
254pub fn lo_up_message() -> Vec<u8> {
255    const RTM_NEWLINK: u16 = 16;
256    const NLM_F_REQUEST: u16 = 1;
257    const NLM_F_ACK: u16 = 4;
258    const IFF_UP: u32 = 1;
259    let mut m = Vec::with_capacity(32);
260    m.extend_from_slice(&32u32.to_ne_bytes()); // nlmsg_len
261    m.extend_from_slice(&RTM_NEWLINK.to_ne_bytes()); // nlmsg_type
262    m.extend_from_slice(&(NLM_F_REQUEST | NLM_F_ACK).to_ne_bytes()); // nlmsg_flags
263    m.extend_from_slice(&1u32.to_ne_bytes()); // nlmsg_seq
264    m.extend_from_slice(&0u32.to_ne_bytes()); // nlmsg_pid: the kernel fills it in
265    m.extend_from_slice(&[0, 0]); // ifi_family AF_UNSPEC, padding
266    m.extend_from_slice(&0u16.to_ne_bytes()); // ifi_type
267    m.extend_from_slice(&1i32.to_ne_bytes()); // ifi_index: lo
268    m.extend_from_slice(&IFF_UP.to_ne_bytes()); // ifi_flags
269    m.extend_from_slice(&IFF_UP.to_ne_bytes()); // ifi_change
270    m
271}
272
273/// The errno in the kernel's answer to [`lo_up_message`]: `Ok(())` for an acknowledgement
274/// (`NLMSG_ERROR` with error 0), `Err(errno)` otherwise (`EPROTO` for an unexpected answer).
275pub fn lo_up_answer(reply: &[u8]) -> Result<(), i32> {
276    const NLMSG_ERROR: u16 = 2;
277    const EPROTO: i32 = 71;
278    if reply.len() < 20 || u16::from_ne_bytes([reply[4], reply[5]]) != NLMSG_ERROR {
279        return Err(EPROTO);
280    }
281    match i32::from_ne_bytes([reply[16], reply[17], reply[18], reply[19]]) {
282        0 => Ok(()),
283        e => Err(-e),
284    }
285}
286
287/// Brings the namespace's `lo` up over netlink (no `ioctl`, so no `unsafe`).
288#[cfg(target_os = "linux")]
289fn lo_up() -> Result<(), i32> {
290    use rustix::net::{AddressFamily, RecvFlags, SendFlags, SocketType};
291    let errno = |e: rustix::io::Errno| e.raw_os_error();
292    let s = rustix::net::socket(AddressFamily::NETLINK, SocketType::RAW, None).map_err(errno)?;
293    rustix::net::send(&s, &lo_up_message(), SendFlags::empty()).map_err(errno)?;
294    let mut buf = [0u8; 256];
295    let (_, n) = rustix::net::recv(&s, &mut buf, RecvFlags::empty()).map_err(errno)?;
296    lo_up_answer(&buf[..n.min(buf.len())])
297}
298
299/// Not Linux: never reached ([`enter`] fails first).
300#[cfg(not(target_os = "linux"))]
301fn lo_up() -> Result<(), i32> {
302    Err(38) // ENOSYS
303}
304
305/// Enters the namespace ([`enter`]), brings `lo` up and binds the proxy's listener on
306/// 127.0.0.1 inside it. The same single-thread rule as [`enter`] applies.
307pub fn enter_with_listener() -> Result<std::net::TcpListener, Failure> {
308    enter()?;
309    lo_up().map_err(|errno| Failure {
310        step: Step::LoUp,
311        errno,
312    })?;
313    std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| Failure {
314        step: Step::Bind,
315        errno: e.raw_os_error().unwrap_or(0),
316    })
317}
318
319/// Sends the listener (and nothing else) over the socketpair to the supervisor.
320#[cfg(target_os = "linux")]
321pub fn send_listener(
322    sock: impl std::os::fd::AsFd,
323    listener: &std::net::TcpListener,
324) -> std::io::Result<()> {
325    use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags};
326    use std::os::fd::AsFd;
327    let mut space = [std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
328    let mut cmsg = SendAncillaryBuffer::new(&mut space);
329    let fds = [listener.as_fd()];
330    cmsg.push(SendAncillaryMessage::ScmRights(&fds));
331    rustix::net::sendmsg(
332        sock,
333        &[std::io::IoSlice::new(b"L")],
334        &mut cmsg,
335        SendFlags::empty(),
336    )?;
337    Ok(())
338}
339
340/// Ends the listeners the child sends after the proxy's (the forwarded loopback ports): a
341/// message with no descriptor, which [`recv_listener`] reads as `None`.
342#[cfg(target_os = "linux")]
343pub fn send_end(sock: impl std::os::fd::AsFd) -> std::io::Result<()> {
344    rustix::net::send(sock, b"E", rustix::net::SendFlags::empty())?;
345    Ok(())
346}
347
348/// What the child sent: the listener, or (`None`) no descriptor, in which case it writes a
349/// [`report`] line next.
350#[cfg(target_os = "linux")]
351pub fn recv_listener(
352    sock: impl std::os::fd::AsFd,
353) -> std::io::Result<Option<std::net::TcpListener>> {
354    use rustix::net::{RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags};
355    let mut space = [std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
356    let mut cmsg = RecvAncillaryBuffer::new(&mut space);
357    let mut byte = [0u8; 1];
358    rustix::net::recvmsg(
359        sock,
360        &mut [std::io::IoSliceMut::new(&mut byte)],
361        &mut cmsg,
362        RecvFlags::CMSG_CLOEXEC,
363    )?;
364    for m in cmsg.drain() {
365        if let RecvAncillaryMessage::ScmRights(mut fds) = m
366            && let Some(fd) = fds.next()
367        {
368            return Ok(Some(std::net::TcpListener::from(fd)));
369        }
370    }
371    Ok(None)
372}
373
374/// The line `cant __probe-netns` prints for a result.
375pub fn report(result: &Result<(), Failure>) -> String {
376    match result {
377        Ok(()) => "ok".into(),
378        Err(f) => format!("failed {} {}", f.step.code(), f.errno),
379    }
380}
381
382/// Reads a [`report`] line back; anything else is `None`.
383pub fn parse_report(line: &str) -> Option<Result<(), Failure>> {
384    let line = line.trim();
385    if line == "ok" {
386        return Some(Ok(()));
387    }
388    let mut w = line.strip_prefix("failed ")?.split(' ');
389    let step = Step::from_code(w.next()?)?;
390    let errno = w.next()?.parse().ok()?;
391    w.next().is_none().then_some(Err(Failure { step, errno }))
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    #[test]
399    fn reports_round_trip() {
400        for r in [
401            Ok(()),
402            Err(Failure {
403                step: Step::Unshare,
404                errno: 1,
405            }),
406            Err(Failure {
407                step: Step::Setgroups,
408                errno: 13,
409            }),
410            Err(Failure {
411                step: Step::UidMap,
412                errno: 1,
413            }),
414            Err(Failure {
415                step: Step::GidMap,
416                errno: 22,
417            }),
418            Err(Failure {
419                step: Step::Mount,
420                errno: 1,
421            }),
422        ] {
423            assert_eq!(parse_report(&report(&r)), Some(r));
424        }
425        for junk in [
426            "",
427            "OK",
428            "failed",
429            "failed unshare",
430            "failed nope 1",
431            "failed unshare x",
432            "failed unshare 1 2",
433        ] {
434            assert_eq!(parse_report(junk), None, "{junk}");
435        }
436        assert_eq!(Step::from_code("nope"), None);
437    }
438
439    #[test]
440    fn hints_name_the_cause_and_the_fix() {
441        let f = |step, errno| Failure { step, errno };
442        let ubuntu = Facts {
443            apparmor_restrict: Some(1),
444            max_user_namespaces: Some(64279),
445            apparmor_label: Some("unconfined".into()),
446            ..Facts::default()
447        };
448        assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("Ubuntu's AppArmor"));
449        assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("install Cantainer's .deb"));
450        let at = |path: &str, root: bool| Facts {
451            exe: Some(path.into()),
452            exe_writable: (!root).then(|| format!("{path} belongs to uid 1000, not root")),
453            ..ubuntu.clone()
454        };
455        let h = hint(&f(Step::Setgroups, 13), &at("/usr/bin/cant", true));
456        assert!(
457            h.contains("sudo apparmor_parser -r /etc/apparmor.d/cant"),
458            "{h}"
459        );
460        let h = hint(&f(Step::Setgroups, 13), &at("/usr/local/bin/cant", true));
461        assert!(
462            h.contains("`sudo /usr/local/bin/cant setup apparmor`"),
463            "{h}"
464        );
465        let h = hint(
466            &f(Step::Setgroups, 13),
467            &at("/home/u/.cargo/bin/cant", false),
468        );
469        assert!(h.contains("a directory only root can write"), "{h}");
470        assert!(
471            h.contains(
472                "no profile can safely cover /home/u/.cargo/bin/cant (/home/u/.cargo/bin/cant \
473                 belongs to uid 1000, not root)"
474            ),
475            "{h}"
476        );
477        let docker = Facts {
478            apparmor_label: Some("docker-default (enforce)".into()),
479            in_container: true,
480            ..Facts::default()
481        };
482        let h = hint(&f(Step::Unshare, 1), &docker);
483        assert!(
484            h.contains("seccomp=cant-seccomp.json") && h.contains("not with"),
485            "{h}"
486        );
487        let off = Facts {
488            max_user_namespaces: Some(0),
489            ..Facts::default()
490        };
491        assert!(hint(&f(Step::Unshare, 28), &off).contains("max_user_namespaces = 0"));
492        let debian = Facts {
493            unprivileged_userns_clone: Some(0),
494            ..Facts::default()
495        };
496        assert!(hint(&f(Step::Unshare, 1), &debian).contains("unprivileged_userns_clone = 0"));
497        // The same errno without the explaining fact: the plain sentence.
498        assert!(hint(&f(Step::Setgroups, 13), &Facts::default()).contains("aren't available"));
499        assert!(hint(&f(Step::Unshare, 1), &Facts::default()).contains("aren't available"));
500        assert_eq!(
501            f(Step::Setgroups, 13).to_string(),
502            format!(
503                "writing /proc/self/setgroups: {}",
504                std::io::Error::from_raw_os_error(13)
505            )
506        );
507        for s in [Step::Unshare, Step::UidMap, Step::GidMap] {
508            assert!(!s.to_string().is_empty());
509        }
510    }
511
512    #[test]
513    fn the_lo_up_message_and_its_answers() {
514        let m = lo_up_message();
515        assert_eq!(m.len(), 32);
516        assert_eq!(u32::from_ne_bytes([m[0], m[1], m[2], m[3]]), 32);
517        assert_eq!(u16::from_ne_bytes([m[4], m[5]]), 16, "RTM_NEWLINK");
518        assert_eq!(
519            u16::from_ne_bytes([m[6], m[7]]),
520            5,
521            "NLM_F_REQUEST | NLM_F_ACK"
522        );
523        assert_eq!(
524            i32::from_ne_bytes([m[20], m[21], m[22], m[23]]),
525            1,
526            "index of lo"
527        );
528        assert_eq!(
529            u32::from_ne_bytes([m[24], m[25], m[26], m[27]]),
530            1,
531            "IFF_UP"
532        );
533        assert_eq!(
534            u32::from_ne_bytes([m[28], m[29], m[30], m[31]]),
535            1,
536            "change IFF_UP"
537        );
538        let answer = |kind: u16, err: i32| {
539            let mut a = vec![0u8; 36];
540            a[4..6].copy_from_slice(&kind.to_ne_bytes());
541            a[16..20].copy_from_slice(&err.to_ne_bytes());
542            a
543        };
544        assert_eq!(lo_up_answer(&answer(2, 0)), Ok(()));
545        assert_eq!(lo_up_answer(&answer(2, -1)), Err(1), "EPERM");
546        assert_eq!(lo_up_answer(&answer(16, 0)), Err(71), "not an ack");
547        assert_eq!(lo_up_answer(&[0; 8]), Err(71), "too short");
548        for s in [Step::LoUp, Step::Bind] {
549            assert_eq!(Step::from_code(s.code()), Some(s));
550            assert!(!s.to_string().is_empty());
551        }
552    }
553
554    #[cfg(target_os = "linux")]
555    #[test]
556    fn a_listener_crosses_a_unix_socket() {
557        let (a, b) = std::os::unix::net::UnixStream::pair().expect("pair");
558        let l = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
559        send_listener(&a, &l).expect("send");
560        let got = recv_listener(&b).expect("recv").expect("a listener");
561        assert_eq!(
562            got.local_addr().expect("addr"),
563            l.local_addr().expect("addr")
564        );
565        // A plain byte carries no descriptor.
566        use std::io::Write as _;
567        (&a).write_all(b"x").expect("write");
568        assert!(recv_listener(&b).expect("recv").is_none());
569        // This test process has several threads: unshare refuses, nothing changes.
570        let f = enter_with_listener().expect_err("threads");
571        assert_eq!(f.step, Step::Unshare);
572    }
573
574    #[test]
575    fn only_root_owned_paths_can_get_a_profile() {
576        let dir = tempfile::tempdir().expect("tempdir");
577        let file = dir.path().join("cant");
578        std::fs::write(&file, "").expect("write");
579        use std::os::unix::fs::MetadataExt;
580        if std::fs::metadata(&file).expect("meta").uid() == 0 {
581            return; // running as root: everything here belongs to root
582        }
583        let e = root_owned(&file).expect_err("ours");
584        assert!(e.contains("not root"), "{e}");
585        assert!(
586            root_owned(std::path::Path::new("/no/such"))
587                .expect_err("missing")
588                .contains("/no/such")
589        );
590        // /tmp is writable by everyone (sticky): refused even when owned by root.
591        let e = root_owned(std::path::Path::new("/tmp")).expect_err("tmp");
592        assert!(
593            e.contains("/tmp can be written by its group or others"),
594            "{e}"
595        );
596        root_owned(std::path::Path::new("/usr/bin")).expect("system directories");
597    }
598
599    #[test]
600    fn facts_read_without_failing() {
601        let f = facts();
602        // Whatever this machine is, the label (when there is one) has no newline.
603        assert!(
604            f.apparmor_label
605                .as_deref()
606                .is_none_or(|l| !l.contains('\n'))
607        );
608    }
609}