cant-launch 0.0.22

Sandbox setup (Landlock, seccomp) and exec for Cantainer capsules.
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
//! Can this system make a user + network namespace? (Phase 6.2; docs/NETWORK-ALLOWLIST.md
//! ยง10.) Host allowlists need one: the can gets a network with only `lo`, and a filtering
//! proxy outside is its only way out (Phase 6.4). Until then this only *reports*: `cant check`
//! and `--explain` say whether host enforcement will be possible here, and if not, the step
//! that failed and the fix.
//!
//! [`enter`] changes the calling process for good, so it runs in a short-lived child (`cant
//! __probe-netns`). [`facts`] and [`hint`] are plain functions of what `/proc` says.

use std::fmt;

/// A step of entering the namespace, in order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
    Unshare,
    Setgroups,
    UidMap,
    GidMap,
    /// Bringing the namespace's loopback interface up.
    LoUp,
    /// Binding the proxy's listener inside the namespace.
    Bind,
    /// Making the mount namespace's mounts private, or a mount there.
    Mount,
}

impl Step {
    /// The short code `cant __probe-netns` prints.
    pub fn code(self) -> &'static str {
        match self {
            Step::Unshare => "unshare",
            Step::Setgroups => "setgroups",
            Step::UidMap => "uid_map",
            Step::GidMap => "gid_map",
            Step::LoUp => "lo_up",
            Step::Bind => "bind",
            Step::Mount => "mount",
        }
    }

    /// The step with this [`Step::code`].
    pub fn from_code(code: &str) -> Option<Step> {
        [
            Step::Unshare,
            Step::Setgroups,
            Step::UidMap,
            Step::GidMap,
            Step::LoUp,
            Step::Bind,
            Step::Mount,
        ]
        .into_iter()
        .find(|s| s.code() == code)
    }
}

impl fmt::Display for Step {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Step::Unshare => "unshare(CLONE_NEWUSER)",
            Step::Setgroups => "writing /proc/self/setgroups",
            Step::UidMap => "writing /proc/self/uid_map",
            Step::GidMap => "writing /proc/self/gid_map",
            Step::LoUp => "bringing up lo",
            Step::Bind => "binding the proxy's listener",
            Step::Mount => "mounting a directory read-only",
        })
    }
}

/// The step that failed, and its errno.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Failure {
    pub step: Step,
    pub errno: i32,
}

impl fmt::Display for Failure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let e = std::io::Error::from_raw_os_error(self.errno);
        write!(f, "{}: {e}", self.step)
    }
}

/// What explains a failure: the sysctls that turn user namespaces off, Ubuntu's AppArmor
/// restriction, and whether this looks like a container.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Facts {
    /// `kernel.apparmor_restrict_unprivileged_userns` (Ubuntu 24.04+).
    pub apparmor_restrict: Option<u32>,
    /// `user.max_user_namespaces`.
    pub max_user_namespaces: Option<u64>,
    /// `kernel.unprivileged_userns_clone` (Debian's patch).
    pub unprivileged_userns_clone: Option<u32>,
    /// `/proc/self/attr/apparmor/current`, e.g. `docker-default (enforce)`.
    pub apparmor_label: Option<String>,
    /// `/.dockerenv`, `/run/.containerenv`, `$container`, or a container AppArmor label.
    pub in_container: bool,
    /// This `cant`'s executable, canonical.
    pub exe: Option<std::path::PathBuf>,
    /// Why [`root_owned`] fails for it, if it does: only a root-owned binary can safely get an
    /// AppArmor profile.
    pub exe_writable: Option<String>,
}

/// Whether `path` and every directory above it belong to root and can't be written by group
/// or others: only such a binary can safely get an AppArmor profile (anyone who can replace it
/// would get the profile's rights). The error names the first path that fails.
pub fn root_owned(path: &std::path::Path) -> Result<(), String> {
    use std::os::unix::fs::MetadataExt;
    for p in path.ancestors() {
        let m = std::fs::metadata(p).map_err(|e| format!("{}: {e}", p.display()))?;
        if m.uid() != 0 {
            return Err(format!(
                "{} belongs to uid {}, not root",
                p.display(),
                m.uid()
            ));
        }
        if m.mode() & 0o022 != 0 {
            return Err(format!(
                "{} can be written by its group or others",
                p.display()
            ));
        }
    }
    Ok(())
}

/// Reads [`Facts`] from `/proc` and the root directory.
pub fn facts() -> Facts {
    let read = |p: &str| {
        std::fs::read_to_string(p)
            .ok()
            .map(|s| s.trim().to_string())
    };
    let label = read("/proc/self/attr/apparmor/current");
    let exe = std::env::current_exe().and_then(std::fs::canonicalize).ok();
    let in_container = std::path::Path::new("/.dockerenv").exists()
        || std::path::Path::new("/run/.containerenv").exists()
        || std::env::var_os("container").is_some()
        || label.as_deref().is_some_and(|l| {
            l.starts_with("docker-default") || l.starts_with("containers-default")
        });
    Facts {
        apparmor_restrict: read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
            .and_then(|s| s.parse().ok()),
        max_user_namespaces: read("/proc/sys/user/max_user_namespaces")
            .and_then(|s| s.parse().ok()),
        unprivileged_userns_clone: read("/proc/sys/kernel/unprivileged_userns_clone")
            .and_then(|s| s.parse().ok()),
        apparmor_label: label,
        in_container,
        exe_writable: exe.as_deref().and_then(|e| root_owned(e).err()),
        exe,
    }
}

/// Why the namespace can't be made here and what would fix it, in a sentence.
pub fn hint(f: &Failure, facts: &Facts) -> String {
    const EPERM: i32 = 1;
    const EACCES: i32 = 13;
    if facts.max_user_namespaces == Some(0) {
        return "user namespaces are turned off (user.max_user_namespaces = 0)".into();
    }
    if facts.unprivileged_userns_clone == Some(0) {
        return "unprivileged user namespaces are turned off \
                (kernel.unprivileged_userns_clone = 0)"
            .into();
    }
    match (f.step, f.errno) {
        (Step::Unshare, EPERM) if facts.in_container => "this container's seccomp profile \
             refuses user namespaces; start it with `--security-opt \
             seccomp=cant-seccomp.json` (in Cantainer's release files), not with \
             `apparmor=unconfined`, `seccomp=unconfined` or `--privileged`"
            .into(),
        (Step::Setgroups, EACCES) if facts.apparmor_restrict == Some(1) => {
            let why = "Ubuntu's AppArmor restricts user namespaces for programs without a \
                       profile (kernel.apparmor_restrict_unprivileged_userns = 1)";
            let fix = match &facts.exe {
                Some(e) if e == std::path::Path::new("/usr/bin/cant") => {
                    "the package's profile isn't loaded: `sudo apparmor_parser -r \
                     /etc/apparmor.d/cant`, or reinstall the package"
                        .to_string()
                }
                Some(e) => match &facts.exe_writable {
                    None => format!("give {0} one with `sudo {0} setup apparmor`", e.display()),
                    Some(why) => format!(
                        "no profile can safely cover {} ({why}): install the .deb, or put cant \
                         in a directory only root can write and run `sudo <that path> setup \
                         apparmor` there",
                        e.display()
                    ),
                },
                None => "install Cantainer's .deb, which has one".to_string(),
            };
            format!("{why}; {fix}")
        }
        _ => "user namespaces aren't available to this user here".into(),
    }
}

/// Enters a new user + network namespace and maps this user to itself: the steps that fail
/// where namespaces are restricted. Changes the calling process for good, and must run while
/// it has a single thread (`cant __probe-netns` calls it first thing).
#[cfg(target_os = "linux")]
pub fn enter() -> Result<(), Failure> {
    enter_with(rustix::thread::UnshareFlags::NEWNET)
}

/// Like [`enter`], with a new mount namespace instead of a network one (read-only package
/// trees for a cant that writes the project, without changing its network).
#[cfg(target_os = "linux")]
pub fn enter_for_mounts() -> Result<(), Failure> {
    enter_with(rustix::thread::UnshareFlags::NEWNS)
}

/// A new user namespace plus `also`, with this user mapped to itself.
#[cfg(target_os = "linux")]
fn enter_with(also: rustix::thread::UnshareFlags) -> Result<(), Failure> {
    use rustix::thread::UnshareFlags;
    let uid = rustix::process::getuid().as_raw();
    let gid = rustix::process::getgid().as_raw();
    let fail = |step| {
        move |e: std::io::Error| Failure {
            step,
            errno: e.raw_os_error().unwrap_or(0),
        }
    };
    // rustix deprecates the safe `unshare` in favour of an `unsafe` one, because unsharing in a
    // process with several threads leaves them in different namespaces. This process has one
    // thread, and the crates forbid `unsafe`.
    #[allow(deprecated)]
    rustix::thread::unshare(UnshareFlags::NEWUSER | also)
        .map_err(std::io::Error::from)
        .map_err(fail(Step::Unshare))?;
    std::fs::write("/proc/self/setgroups", "deny").map_err(fail(Step::Setgroups))?;
    std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1")).map_err(fail(Step::UidMap))?;
    std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1")).map_err(fail(Step::GidMap))?;
    Ok(())
}

/// Not Linux: no namespaces.
#[cfg(not(target_os = "linux"))]
pub fn enter() -> Result<(), Failure> {
    Err(Failure {
        step: Step::Unshare,
        errno: 38, // ENOSYS
    })
}

/// `RTM_NEWLINK` for interface index 1 (`lo` in a new namespace) with `IFF_UP`, asking for an
/// acknowledgement: a 16-byte `nlmsghdr` and a 16-byte `ifinfomsg`, in this machine's byte order.
pub fn lo_up_message() -> Vec<u8> {
    const RTM_NEWLINK: u16 = 16;
    const NLM_F_REQUEST: u16 = 1;
    const NLM_F_ACK: u16 = 4;
    const IFF_UP: u32 = 1;
    let mut m = Vec::with_capacity(32);
    m.extend_from_slice(&32u32.to_ne_bytes()); // nlmsg_len
    m.extend_from_slice(&RTM_NEWLINK.to_ne_bytes()); // nlmsg_type
    m.extend_from_slice(&(NLM_F_REQUEST | NLM_F_ACK).to_ne_bytes()); // nlmsg_flags
    m.extend_from_slice(&1u32.to_ne_bytes()); // nlmsg_seq
    m.extend_from_slice(&0u32.to_ne_bytes()); // nlmsg_pid: the kernel fills it in
    m.extend_from_slice(&[0, 0]); // ifi_family AF_UNSPEC, padding
    m.extend_from_slice(&0u16.to_ne_bytes()); // ifi_type
    m.extend_from_slice(&1i32.to_ne_bytes()); // ifi_index: lo
    m.extend_from_slice(&IFF_UP.to_ne_bytes()); // ifi_flags
    m.extend_from_slice(&IFF_UP.to_ne_bytes()); // ifi_change
    m
}

/// The errno in the kernel's answer to [`lo_up_message`]: `Ok(())` for an acknowledgement
/// (`NLMSG_ERROR` with error 0), `Err(errno)` otherwise (`EPROTO` for an unexpected answer).
pub fn lo_up_answer(reply: &[u8]) -> Result<(), i32> {
    const NLMSG_ERROR: u16 = 2;
    const EPROTO: i32 = 71;
    if reply.len() < 20 || u16::from_ne_bytes([reply[4], reply[5]]) != NLMSG_ERROR {
        return Err(EPROTO);
    }
    match i32::from_ne_bytes([reply[16], reply[17], reply[18], reply[19]]) {
        0 => Ok(()),
        e => Err(-e),
    }
}

/// Brings the namespace's `lo` up over netlink (no `ioctl`, so no `unsafe`).
#[cfg(target_os = "linux")]
fn lo_up() -> Result<(), i32> {
    use rustix::net::{AddressFamily, RecvFlags, SendFlags, SocketType};
    let errno = |e: rustix::io::Errno| e.raw_os_error();
    let s = rustix::net::socket(AddressFamily::NETLINK, SocketType::RAW, None).map_err(errno)?;
    rustix::net::send(&s, &lo_up_message(), SendFlags::empty()).map_err(errno)?;
    let mut buf = [0u8; 256];
    let (_, n) = rustix::net::recv(&s, &mut buf, RecvFlags::empty()).map_err(errno)?;
    lo_up_answer(&buf[..n.min(buf.len())])
}

/// Not Linux: never reached ([`enter`] fails first).
#[cfg(not(target_os = "linux"))]
fn lo_up() -> Result<(), i32> {
    Err(38) // ENOSYS
}

/// Enters the namespace ([`enter`]), brings `lo` up and binds the proxy's listener on
/// 127.0.0.1 inside it. The same single-thread rule as [`enter`] applies.
pub fn enter_with_listener() -> Result<std::net::TcpListener, Failure> {
    enter()?;
    lo_up().map_err(|errno| Failure {
        step: Step::LoUp,
        errno,
    })?;
    std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| Failure {
        step: Step::Bind,
        errno: e.raw_os_error().unwrap_or(0),
    })
}

/// Sends the listener (and nothing else) over the socketpair to the supervisor.
#[cfg(target_os = "linux")]
pub fn send_listener(
    sock: impl std::os::fd::AsFd,
    listener: &std::net::TcpListener,
) -> std::io::Result<()> {
    use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags};
    use std::os::fd::AsFd;
    let mut space = [std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
    let mut cmsg = SendAncillaryBuffer::new(&mut space);
    let fds = [listener.as_fd()];
    cmsg.push(SendAncillaryMessage::ScmRights(&fds));
    rustix::net::sendmsg(
        sock,
        &[std::io::IoSlice::new(b"L")],
        &mut cmsg,
        SendFlags::empty(),
    )?;
    Ok(())
}

/// Ends the listeners the child sends after the proxy's (the forwarded loopback ports): a
/// message with no descriptor, which [`recv_listener`] reads as `None`.
#[cfg(target_os = "linux")]
pub fn send_end(sock: impl std::os::fd::AsFd) -> std::io::Result<()> {
    rustix::net::send(sock, b"E", rustix::net::SendFlags::empty())?;
    Ok(())
}

/// What the child sent: the listener, or (`None`) no descriptor, in which case it writes a
/// [`report`] line next.
#[cfg(target_os = "linux")]
pub fn recv_listener(
    sock: impl std::os::fd::AsFd,
) -> std::io::Result<Option<std::net::TcpListener>> {
    use rustix::net::{RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags};
    let mut space = [std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
    let mut cmsg = RecvAncillaryBuffer::new(&mut space);
    let mut byte = [0u8; 1];
    rustix::net::recvmsg(
        sock,
        &mut [std::io::IoSliceMut::new(&mut byte)],
        &mut cmsg,
        RecvFlags::CMSG_CLOEXEC,
    )?;
    for m in cmsg.drain() {
        if let RecvAncillaryMessage::ScmRights(mut fds) = m
            && let Some(fd) = fds.next()
        {
            return Ok(Some(std::net::TcpListener::from(fd)));
        }
    }
    Ok(None)
}

/// The line `cant __probe-netns` prints for a result.
pub fn report(result: &Result<(), Failure>) -> String {
    match result {
        Ok(()) => "ok".into(),
        Err(f) => format!("failed {} {}", f.step.code(), f.errno),
    }
}

/// Reads a [`report`] line back; anything else is `None`.
pub fn parse_report(line: &str) -> Option<Result<(), Failure>> {
    let line = line.trim();
    if line == "ok" {
        return Some(Ok(()));
    }
    let mut w = line.strip_prefix("failed ")?.split(' ');
    let step = Step::from_code(w.next()?)?;
    let errno = w.next()?.parse().ok()?;
    w.next().is_none().then_some(Err(Failure { step, errno }))
}

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

    #[test]
    fn reports_round_trip() {
        for r in [
            Ok(()),
            Err(Failure {
                step: Step::Unshare,
                errno: 1,
            }),
            Err(Failure {
                step: Step::Setgroups,
                errno: 13,
            }),
            Err(Failure {
                step: Step::UidMap,
                errno: 1,
            }),
            Err(Failure {
                step: Step::GidMap,
                errno: 22,
            }),
            Err(Failure {
                step: Step::Mount,
                errno: 1,
            }),
        ] {
            assert_eq!(parse_report(&report(&r)), Some(r));
        }
        for junk in [
            "",
            "OK",
            "failed",
            "failed unshare",
            "failed nope 1",
            "failed unshare x",
            "failed unshare 1 2",
        ] {
            assert_eq!(parse_report(junk), None, "{junk}");
        }
        assert_eq!(Step::from_code("nope"), None);
    }

    #[test]
    fn hints_name_the_cause_and_the_fix() {
        let f = |step, errno| Failure { step, errno };
        let ubuntu = Facts {
            apparmor_restrict: Some(1),
            max_user_namespaces: Some(64279),
            apparmor_label: Some("unconfined".into()),
            ..Facts::default()
        };
        assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("Ubuntu's AppArmor"));
        assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("install Cantainer's .deb"));
        let at = |path: &str, root: bool| Facts {
            exe: Some(path.into()),
            exe_writable: (!root).then(|| format!("{path} belongs to uid 1000, not root")),
            ..ubuntu.clone()
        };
        let h = hint(&f(Step::Setgroups, 13), &at("/usr/bin/cant", true));
        assert!(
            h.contains("sudo apparmor_parser -r /etc/apparmor.d/cant"),
            "{h}"
        );
        let h = hint(&f(Step::Setgroups, 13), &at("/usr/local/bin/cant", true));
        assert!(
            h.contains("`sudo /usr/local/bin/cant setup apparmor`"),
            "{h}"
        );
        let h = hint(
            &f(Step::Setgroups, 13),
            &at("/home/u/.cargo/bin/cant", false),
        );
        assert!(h.contains("a directory only root can write"), "{h}");
        assert!(
            h.contains(
                "no profile can safely cover /home/u/.cargo/bin/cant (/home/u/.cargo/bin/cant \
                 belongs to uid 1000, not root)"
            ),
            "{h}"
        );
        let docker = Facts {
            apparmor_label: Some("docker-default (enforce)".into()),
            in_container: true,
            ..Facts::default()
        };
        let h = hint(&f(Step::Unshare, 1), &docker);
        assert!(
            h.contains("seccomp=cant-seccomp.json") && h.contains("not with"),
            "{h}"
        );
        let off = Facts {
            max_user_namespaces: Some(0),
            ..Facts::default()
        };
        assert!(hint(&f(Step::Unshare, 28), &off).contains("max_user_namespaces = 0"));
        let debian = Facts {
            unprivileged_userns_clone: Some(0),
            ..Facts::default()
        };
        assert!(hint(&f(Step::Unshare, 1), &debian).contains("unprivileged_userns_clone = 0"));
        // The same errno without the explaining fact: the plain sentence.
        assert!(hint(&f(Step::Setgroups, 13), &Facts::default()).contains("aren't available"));
        assert!(hint(&f(Step::Unshare, 1), &Facts::default()).contains("aren't available"));
        assert_eq!(
            f(Step::Setgroups, 13).to_string(),
            format!(
                "writing /proc/self/setgroups: {}",
                std::io::Error::from_raw_os_error(13)
            )
        );
        for s in [Step::Unshare, Step::UidMap, Step::GidMap] {
            assert!(!s.to_string().is_empty());
        }
    }

    #[test]
    fn the_lo_up_message_and_its_answers() {
        let m = lo_up_message();
        assert_eq!(m.len(), 32);
        assert_eq!(u32::from_ne_bytes([m[0], m[1], m[2], m[3]]), 32);
        assert_eq!(u16::from_ne_bytes([m[4], m[5]]), 16, "RTM_NEWLINK");
        assert_eq!(
            u16::from_ne_bytes([m[6], m[7]]),
            5,
            "NLM_F_REQUEST | NLM_F_ACK"
        );
        assert_eq!(
            i32::from_ne_bytes([m[20], m[21], m[22], m[23]]),
            1,
            "index of lo"
        );
        assert_eq!(
            u32::from_ne_bytes([m[24], m[25], m[26], m[27]]),
            1,
            "IFF_UP"
        );
        assert_eq!(
            u32::from_ne_bytes([m[28], m[29], m[30], m[31]]),
            1,
            "change IFF_UP"
        );
        let answer = |kind: u16, err: i32| {
            let mut a = vec![0u8; 36];
            a[4..6].copy_from_slice(&kind.to_ne_bytes());
            a[16..20].copy_from_slice(&err.to_ne_bytes());
            a
        };
        assert_eq!(lo_up_answer(&answer(2, 0)), Ok(()));
        assert_eq!(lo_up_answer(&answer(2, -1)), Err(1), "EPERM");
        assert_eq!(lo_up_answer(&answer(16, 0)), Err(71), "not an ack");
        assert_eq!(lo_up_answer(&[0; 8]), Err(71), "too short");
        for s in [Step::LoUp, Step::Bind] {
            assert_eq!(Step::from_code(s.code()), Some(s));
            assert!(!s.to_string().is_empty());
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn a_listener_crosses_a_unix_socket() {
        let (a, b) = std::os::unix::net::UnixStream::pair().expect("pair");
        let l = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
        send_listener(&a, &l).expect("send");
        let got = recv_listener(&b).expect("recv").expect("a listener");
        assert_eq!(
            got.local_addr().expect("addr"),
            l.local_addr().expect("addr")
        );
        // A plain byte carries no descriptor.
        use std::io::Write as _;
        (&a).write_all(b"x").expect("write");
        assert!(recv_listener(&b).expect("recv").is_none());
        // This test process has several threads: unshare refuses, nothing changes.
        let f = enter_with_listener().expect_err("threads");
        assert_eq!(f.step, Step::Unshare);
    }

    #[test]
    fn only_root_owned_paths_can_get_a_profile() {
        let dir = tempfile::tempdir().expect("tempdir");
        let file = dir.path().join("cant");
        std::fs::write(&file, "").expect("write");
        use std::os::unix::fs::MetadataExt;
        if std::fs::metadata(&file).expect("meta").uid() == 0 {
            return; // running as root: everything here belongs to root
        }
        let e = root_owned(&file).expect_err("ours");
        assert!(e.contains("not root"), "{e}");
        assert!(
            root_owned(std::path::Path::new("/no/such"))
                .expect_err("missing")
                .contains("/no/such")
        );
        // /tmp is writable by everyone (sticky): refused even when owned by root.
        let e = root_owned(std::path::Path::new("/tmp")).expect_err("tmp");
        assert!(
            e.contains("/tmp can be written by its group or others"),
            "{e}"
        );
        root_owned(std::path::Path::new("/usr/bin")).expect("system directories");
    }

    #[test]
    fn facts_read_without_failing() {
        let f = facts();
        // Whatever this machine is, the label (when there is one) has no newline.
        assert!(
            f.apparmor_label
                .as_deref()
                .is_none_or(|l| !l.contains('\n'))
        );
    }
}