sandlock-cli 0.8.9

CLI for sandlock process sandbox
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Implementation of `sandlock learn -o <output.toml>`.
//!
//! Runs a workload under observation and emits a sandlock profile TOML
//! usable by `sandlock run -p`.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use anyhow::{anyhow, Result};
use sandlock_core::policy_fn::{SyscallEvent, Verdict};
use sandlock_core::profile::{FilesystemSection, ProfileInput};
use sandlock_core::sandbox::BranchAction;
use sandlock_core::Sandbox;


/// Protected: no legitimate sandboxed workload needs a recursive grant here.
/// Write grants on these are skipped + error. Read collapse never fires here.
const PROTECTED_PATHS: &[&[u8]] = &[b"/"];
const PROTECTED_CRED_SUFFIXES: &[&[u8]] = &[b"/.ssh", b"/.aws", b"/.kube", b"/.gnupg"];

/// Guarded: write grants are sometimes necessary but warrant operator awareness.
/// Write grants emit + warning + diff. Read collapse never fires here.
const GUARDED_PATHS: &[&[u8]] = &[b"/etc", b"/proc", b"/sys", b"/dev", b"/boot", b"/run/secrets", b"/root"];

#[derive(PartialEq)]
enum PathTier { Protected, Guarded, Normal }

fn classify_path(p: &std::path::Path) -> PathTier {
    let b = p.as_os_str().as_encoded_bytes();
    if PROTECTED_PATHS.iter().any(|s| b == *s)
        || PROTECTED_CRED_SUFFIXES.iter().any(|suf| b.ends_with(suf))
    {
        return PathTier::Protected;
    }
    if GUARDED_PATHS.iter().any(|s| b == *s) {
        return PathTier::Guarded;
    }
    // $HOME itself is guarded: apps do legitimately write dotfiles there.
    if let Ok(home) = std::env::var("HOME") {
        if b == home.as_bytes() {
            return PathTier::Guarded;
        }
    }
    PathTier::Normal
}

/// Print immediate children of `dir` that the workload did NOT observe writing.
fn print_observed_vs_granted_diff(dir: &std::path::Path, observed: &BTreeSet<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else { return };
    let mut unobserved: Vec<String> = entries
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|p| !observed.contains(p))
        .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
        .collect();
    if unobserved.is_empty() { return }
    unobserved.sort();
    eprintln!(
        "  unobserved siblings now writable under {}: {}",
        dir.display(),
        unobserved.join(", ")
    );
}

/// Turn observed write paths into Landlock grants, with safety guards.
///
/// Landlock needs an existing path, so a COW-created path is granted through
/// its nearest existing ancestor. The grant is recursive either way, so the
/// tier check applies to the granted path, not to how the workload named it.
fn collapse_write_paths(writes: &BTreeSet<PathBuf>) -> Vec<PathBuf> {
    let mut out: BTreeSet<PathBuf> = BTreeSet::new();
    for p in writes {
        if is_junk_path(p) { continue; }
        let p = &fold_session_path(p.clone());
        let Some(grant) = p.ancestors().find(|a| a.exists()) else { continue };
        if is_fs_root(grant) {
            eprintln!(
                "sandlock learn: WARNING: write to '{}' needs a grant on the filesystem root, skipping",
                p.display()
            );
            continue;
        }
        match classify_path(grant) {
            PathTier::Protected => {
                eprintln!(
                    "sandlock learn: WARNING: write to '{}' needs a grant on protected path '{}', skipping",
                    p.display(), grant.display()
                );
                continue;
            }
            PathTier::Guarded => {
                eprintln!(
                    "sandlock learn: WARNING: write to '{}' grants '{}' (guarded directory)",
                    p.display(), grant.display()
                );
                print_observed_vs_granted_diff(grant, writes);
            }
            PathTier::Normal => {}
        }
        out.insert(grant.to_path_buf());
    }
    out.into_iter().collect()
}

/// Remove paths that are already covered by a shorter ancestor in the same list.
/// Landlock PATH_BENEATH grants are recursive, so if /usr/lib is in the list,
/// /usr/lib/x86_64/libfoo.so is redundant and can be dropped.
fn dedup_subsumed(paths: Vec<PathBuf>) -> Vec<PathBuf> {
    let set: std::collections::HashSet<PathBuf> = paths.iter().cloned().collect();
    paths.into_iter()
        .filter(|p| {
            // Keep p unless one of its strict ancestors is already in the set.
            !p.ancestors().skip(1).any(|a| set.contains(a))
        })
        .collect()
}

/// Collapse paths using the N-threshold heuristic and explicit prefixes.
///
/// Protected/guarded directories are never collapsed by the N-threshold.
/// Sensitive --collapse-prefix targets are refused up front in `run`, before
/// the workload executes; prefixes reaching here are already vetted.
fn collapse_by_threshold(
    paths: Vec<PathBuf>,
    n: usize,
    force_prefixes: &[PathBuf],
    observed: &BTreeSet<PathBuf>,
) -> Vec<PathBuf> {
    // Count how many paths share the same parent directory.
    let mut dir_counts: std::collections::HashMap<PathBuf, usize> = Default::default();
    for p in &paths {
        if let Some(parent) = p.parent() {
            *dir_counts.entry(parent.to_path_buf()).or_insert(0) += 1;
        }
    }

    let mut out: BTreeSet<PathBuf> = BTreeSet::new();
    for p in paths {
        let forced = force_prefixes.iter()
            .filter(|prefix| p.starts_with(prefix))
            .max_by_key(|prefix| prefix.as_os_str().len());

        let target: PathBuf = if let Some(prefix) = forced {
            prefix.clone()
        } else if let Some(parent) = p.parent() {
            if dir_counts.get(parent).copied().unwrap_or(0) >= n {
                parent.to_path_buf()
            } else {
                out.insert(p);
                continue;
            }
        } else {
            out.insert(p);
            continue;
        };

        match classify_path(&target) {
            PathTier::Normal => {
                out.insert(target);
            }
            tier => {
                if forced.is_some() {
                    // Explicit --collapse-prefix + --force-sensitive-collapse: emit with warning + diff.
                    let label = if tier == PathTier::Protected { "protected" } else { "guarded" };
                    eprintln!(
                        "sandlock learn: WARNING: collapse '{}' to '{}' ({label} directory)",
                        p.display(), target.display()
                    );
                    print_observed_vs_granted_diff(&target, observed);
                    out.insert(target);
                } else {
                    // N-threshold hit a sensitive dir: keep individual path.
                    out.insert(p);
                }
            }
        }
    }
    out.into_iter().collect()
}

fn is_fs_root(p: &Path) -> bool {
    p == Path::new("/")
}

/// Returns true for pid-specific paths that are meaningless across runs.
fn is_junk_path(p: &std::path::Path) -> bool {
    let b = p.as_os_str().as_encoded_bytes();
    // /proc/<pid>/... are pid-specific across runs.
    let proc_numeric_pid = b.starts_with(b"/proc/")
        && b.get(6).map_or(false, u8::is_ascii_digit);
    // Under /proc/self, only sub-trees with volatile numeric components are
    // junk. Stable entries like /proc/self/maps are legitimately needed
    // across runs (e.g. V8 reads maps on every startup).
    let proc_self_volatile = b.starts_with(b"/proc/self/fd/")
        || b.starts_with(b"/proc/self/fdinfo/")
        || b.starts_with(b"/proc/self/task/")
        || b.starts_with(b"/proc/self/map_files/")
        || b == b"/proc/self/fd"
        || b == b"/proc/self/fdinfo"
        || b == b"/proc/self/task"
        || b == b"/proc/self/map_files";
    proc_numeric_pid || proc_self_volatile
}

/// A pty's number changes between sessions; granting the directory is
/// what lets the next run reopen whichever slave it gets. /dev/tty needs
/// no folding: the path is stable even though the device behind it is not.
fn fold_session_path(p: PathBuf) -> PathBuf {
    if p.starts_with("/dev/pts") { PathBuf::from("/dev/pts") } else { p }
}

use crate::LearnArgs;

/// Fail learn (writing no profile) unless the workload exited cleanly.
fn require_clean_exit(status: &sandlock_core::ExitStatus) -> Result<()> {
    match status {
        sandlock_core::ExitStatus::Code(0) => {
            eprintln!("sandlock learn: done");
            Ok(())
        }
        sandlock_core::ExitStatus::Code(n) => {
            Err(anyhow!("process exited with code {n}, not writing profile"))
        }
        sandlock_core::ExitStatus::Signal(sig) => {
            Err(anyhow!("process killed by signal {sig}, not writing profile"))
        }
        _ => Err(anyhow!("process terminated abnormally, not writing profile")),
    }
}

// openat flags (from fcntl.h)
const O_WRONLY: u64 = 0o1;
const O_RDWR: u64 = 0o2;
const O_CREAT: u64 = 0o100;

fn is_write_open(flags: u64) -> bool {
    // No valid open flag has bits 32+; a value that large is a pointer or
    // garbage (e.g. from a mis-decoded syscall arg). Treat it as read-only
    // so a misdecoded flag never puts a file in writes incorrectly.
    if flags >> 32 != 0 {
        return false;
    }
    flags & (O_WRONLY | O_RDWR | O_CREAT) != 0
}

/// Returns the TGID (thread group leader PID) for a given TID.
fn tgid_of(tid: u32) -> u32 {
    let Ok(s) = std::fs::read_to_string(format!("/proc/{tid}/status")) else {
        return tid;
    };
    for line in s.lines() {
        if let Some(rest) = line.strip_prefix("Tgid:\t") {
            if let Ok(tgid) = rest.trim().parse::<u32>() {
                return tgid;
            }
        }
    }
    tid
}

/// Read all file-backed r-xp (executable) mappings from `/proc/<pid>/maps`.
/// This captures the dynamic linker, all shared libraries, and the main binary
/// as actually mapped by the kernel. 
fn read_rx_mapped_files(pid: u32) -> Vec<PathBuf> {
    use std::io::BufRead;
    let Ok(file) = std::fs::File::open(format!("/proc/{pid}/maps")) else { return vec![] };
    let mut out = Vec::new();
    for line in std::io::BufReader::new(file).lines() {
        let Ok(line) = line else { break };
        // Format: "addr-addr perms offset dev inode pathname"
        let mut parts = line.splitn(6, ' ');
        let perms = parts.nth(1).unwrap_or("");
        let pathname = parts.nth(3).map(str::trim).unwrap_or("");
        if perms.contains('x') && !pathname.is_empty() && !pathname.starts_with('[') {
            out.push(PathBuf::from(pathname));
        }
    }
    out
}


/// Accumulated observations from the policy_fn callback during learn.
#[derive(Clone)]
struct LearnObserver {
    reads: Arc<Mutex<BTreeSet<PathBuf>>>,
    writes: Arc<Mutex<BTreeSet<PathBuf>>>,
    connects: Arc<Mutex<BTreeSet<String>>>,
    binds: Arc<Mutex<BTreeSet<u16>>>,
    /// PIDs with an exec attempt observed but the post-exec maps scan still
    /// pending; the scan runs on the pid's first non-exec event, which is
    /// guaranteed to run under the new image.
    pending_maps: Arc<Mutex<HashSet<u32>>>,
    /// Resolved path of the first binary the workload exec'd, from
    /// /proc/<pid>/exe. Pins [program].exec to an absolute path; argv[0] may
    /// be relative (resolved through $PATH by execvp) and useless to `run`.
    first_exe: Arc<Mutex<Option<PathBuf>>>,
    /// UDP connect() calls pending confirmation by a subsequent send.
    /// Keyed by (TGID, fd) so a connect observed on one thread can be
    /// confirmed by traffic from a sibling thread using the same fd table.
    /// Connected UDP write(2) is deliberately not observed: trapping write
    /// would catch the child bootstrap pipe writes before the parent receives
    /// the seccomp listener fd.
    pending_udp_connects: Arc<Mutex<HashMap<(u32, i64), String>>>,
    /// HTTP requests observed via the transparent proxy (method + host + path).
    /// Format: "METHOD host/path" matching HttpRule::parse input.
    http_requests: Arc<Mutex<BTreeSet<String>>>,
}

impl LearnObserver {
    fn new() -> Self {
        Self {
            reads: Arc::new(Mutex::new(BTreeSet::new())),
            writes: Arc::new(Mutex::new(BTreeSet::new())),
            connects: Arc::new(Mutex::new(BTreeSet::new())),
            binds: Arc::new(Mutex::new(BTreeSet::new())),
            pending_maps: Arc::new(Mutex::new(HashSet::new())),
            first_exe: Arc::new(Mutex::new(None)),
            pending_udp_connects: Arc::new(Mutex::new(HashMap::new())),
            http_requests: Arc::new(Mutex::new(BTreeSet::new())),
        }
    }

    /// The policy_fn callback: classifies each intercepted syscall into
    /// reads, writes, or connects for profile generation.
    fn on_event(&self, event: SyscallEvent) -> Verdict {
        // After a successful execve, the NEXT event from that PID runs under
        // the new image, so /proc/<pid>/maps shows the binary and dynamic
        // linker the kernel loaded (which bypassed seccomp). Another exec
        // event from a pending PID instead means the previous attempt failed
        // (execvp walking $PATH; a successful execve never returns), so keep
        // waiting: scanning then would record the old image, which for the
        // workload's first exec is the sandbox runtime itself.
        let is_exec = matches!(event.syscall.as_str(), "execve" | "execveat");
        if !is_exec && self.pending_maps.lock().unwrap().remove(&event.pid) {
            let mut reads = self.reads.lock().unwrap();
            // /proc/<pid>/exe is the canonical real binary path (symlinks resolved by the kernel),
            // race-free at this point since the new image is already loaded.
            if let Ok(exe) = std::fs::read_link(format!("/proc/{}/exe", event.pid)) {
                let mut first = self.first_exe.lock().unwrap();
                if first.is_none() {
                    *first = Some(exe.clone());
                }
                reads.insert(exe);
            }
            for path in read_rx_mapped_files(event.pid) {
                reads.insert(path);
            }
        }

        match event.syscall.as_str() {
            "execve" | "execveat" => {
                // event.path may be a symlink; canonical real path comes from /proc/<pid>/exe in pending_maps.
                if let Some(path) = event.path {
                    self.reads.lock().unwrap().insert(path);
                }

                // When a non-leader thread calls execve, the new process runs under the TGID,
                // so we must insert the TGID into pending_maps.
                self.pending_maps.lock().unwrap().insert(tgid_of(event.pid));
            }
            "openat" | "open" => {
                if let Some(path) = event.path {
                    let path = canonicalize_or_keep(path, event.pid);
                    if let Some(fl) = event.flags {
                        if is_write_open(fl) {
                            self.writes.lock().unwrap().insert(path);
                        } else {
                            self.reads.lock().unwrap().insert(path);
                        }
                    }
                }
            }
            // mkdir/unlink/rmdir/symlink/mknod: Landlock MAKE_*/REMOVE_* are directory
            // rights, so the parent dir is what sandlock run needs, not the target.
            "mkdirat" | "mknodat" => {
                if let Some(p) = event.path {
                    let p = canonicalize_or_keep(p, event.pid);
                    // If the target already exists the syscall will fail with
                    // EEXIST; no MAKE_DIR right on the parent is needed.
                    if !p.exists() {
                        if let Some(parent) = p.parent() {
                            self.writes.lock().unwrap().insert(parent.to_path_buf());
                        }
                    }
                }
            }
            // unlinkat/symlinkat operate on the link itself, not its target, so
            // only the parent is canonicalized to avoid following the symlink.
            "unlinkat" | "symlinkat" => {
                if let Some(p) = event.path {
                    let p = canonicalize_parent_or_keep(p, event.pid);
                    if let Some(parent) = p.parent() {
                        self.writes.lock().unwrap().insert(parent.to_path_buf());
                    }
                }
            }
            // rename: needs RENAME_OLD on parent of old path + RENAME_NEW on parent of new path.
            // Both operate on the link itself, not its target.
            "renameat2" => {
                for p in [event.path, event.path2].into_iter().flatten() {
                    let p = canonicalize_parent_or_keep(p, event.pid);
                    if let Some(parent) = p.parent() {
                        self.writes.lock().unwrap().insert(parent.to_path_buf());
                    }
                }
            }
            // link: source needs read access (ln doesn't open() it); dst parent needs MAKE_HARDLINK.
            // dst operates on the link itself, so only the parent is canonicalized.
            "linkat" => {
                if let Some(src) = event.path {
                    self.reads.lock().unwrap().insert(canonicalize_or_keep(src, event.pid));
                }
                if let Some(dst) = event.path2 {
                    let dst = canonicalize_parent_or_keep(dst, event.pid);
                    if let Some(parent) = dst.parent() {
                        self.writes.lock().unwrap().insert(parent.to_path_buf());
                    }
                }
            }
            // truncate: LANDLOCK_ACCESS_FS_TRUNCATE applies to the file itself.
            "truncate" => {
                if let Some(p) = event.path {
                    self.writes.lock().unwrap().insert(canonicalize_or_keep(p, event.pid));
                }
            }
            "bind" => {
                if let Some(port) = event.port {
                    if port > 0 {
                        self.binds.lock().unwrap().insert(port);
                    }
                } else if let Some(p) = event.path {
                    // AF_UNIX named bind: Landlock MAKE_SOCK is a directory right,
                    // so the parent dir is what sandlock run needs.
                    let p = canonicalize_or_keep(p, event.pid);
                    if let Some(parent) = p.parent() {
                        self.writes.lock().unwrap().insert(parent.to_path_buf());
                    }
                }
            }
            "connect" | "sendto" | "sendmsg" | "sendmmsg" => {
                // An address-less send on a connected UDP socket is how the
                // glibc resolver talks to its nameserver (connect, then
                // send with no sockaddr): real traffic, so it promotes the
                // parked connect() the same way an addressed send does.
                if event.host.is_none()
                    && event.syscall != "connect"
                    && event.protocol.as_deref() == Some("udp")
                {
                    if let Some(fd) = event.fd {
                        let key = (tgid_of(event.pid), fd);
                        if let Some(pending) = self.pending_udp_connects
                            .lock().unwrap().remove(&key)
                        {
                            self.connects.lock().unwrap().insert(pending);
                        }
                    }
                }
                if let (Some(ip), Some(port), Some(proto)) = (event.host, event.port, event.protocol) {
                    if proto != "icmp" {
                        let host = if ip.is_ipv6() { format!("[{ip}]") } else { ip.to_string() };
                        let entry = format!("{proto}://{host}:{port}");
                        if proto == "udp" && event.syscall == "connect" {
                            // Park UDP connect() in pending: if a send() follows on the
                            // same socket it is real traffic; if not it was an
                            // address-sorting probe (e.g. glibc getaddrinfo) and is
                            // discarded when the workload exits.
                            if let Some(fd) = event.fd {
                                let key = (tgid_of(event.pid), fd);
                                self.pending_udp_connects.lock().unwrap()
                                    .insert(key, entry);
                            }
                        } else {
                            // For UDP send*, promote any pending connect() on the
                            // same process fd to confirmed traffic.
                            if proto == "udp" {
                                if let Some(fd) = event.fd {
                                    let key = (tgid_of(event.pid), fd);
                                    if let Some(pending) = self.pending_udp_connects
                                        .lock().unwrap().remove(&key)
                                    {
                                        self.connects.lock().unwrap().insert(pending);
                                    }
                                }
                            }
                            self.connects.lock().unwrap().insert(entry);
                        }
                    }
                }
            }
            _ => {}
        }
        Verdict::Allow
    }
}


/// Resolve symlinks to get the canonical path. Falls back to the original
/// if the path doesn't exist yet (e.g. COW-intercepted creates).
///
/// /proc/self paths are canonicalized via the event pid so symlinks
/// (e.g. /proc/self/exe) resolve against the workload, not the supervisor.
/// Results still under /proc/<pid> are mapped back to /proc/self.
fn canonicalize_or_keep(p: PathBuf, pid: u32) -> PathBuf {
    let proc_self = Path::new("/proc/self");
    let Ok(rest) = p.strip_prefix(proc_self) else {
        return std::fs::canonicalize(&p).unwrap_or(p);
    };
    let proc_pid = Path::new("/proc").join(pid.to_string());
    let pid_path = join_rest(&proc_pid, rest);
    let resolved = std::fs::canonicalize(&pid_path).unwrap_or(pid_path);
    match resolved.strip_prefix(&proc_pid) {
        Ok(rest) => join_rest(proc_self, rest),
        Err(_) => resolved,
    }
}

/// PathBuf::join appends a separator even for an empty component, which
/// would turn the bare directory into "dir/".
fn join_rest(base: &Path, rest: &Path) -> PathBuf {
    if rest.as_os_str().is_empty() { base.to_path_buf() } else { base.join(rest) }
}

/// Canonicalize only the parent directory and rejoin the final component.
/// Used for syscalls that operate on the link itself (unlink, rename, symlink).
fn canonicalize_parent_or_keep(p: PathBuf, pid: u32) -> PathBuf {
    let file_name = match p.file_name() {
        Some(n) => n.to_owned(),
        None => return p,
    };
    let parent = match p.parent() {
        Some(par) => par,
        None => return p,
    };
    canonicalize_or_keep(parent.to_path_buf(), pid).join(file_name)
}

pub async fn run(args: LearnArgs) -> Result<()> {
    if args.cmd.is_empty() {
        anyhow::bail!("no command given; use: sandlock learn [flags] -- <cmd> [args...]");
    }

    // Refuse bad flag combinations before the workload runs, not after a
    // full observation pass.
    for prefix in &args.collapse_prefix {
        if classify_path(prefix) != PathTier::Normal && !args.force_sensitive_collapse {
            anyhow::bail!(
                "--collapse-prefix '{}' targets a sensitive path; use --force-sensitive-collapse to proceed",
                prefix.display()
            );
        }
    }

    let cmd_str = args.cmd.join(" ");
    let cmd_refs: Vec<&str> = args.cmd.iter().map(String::as_str).collect();

    // COW workdir="/" covers every path: seccomp fires before Landlock, so the
    // supervisor intercepts every write openat and redirects it to an upper layer
    // the real filesystem is untouched and no write is blocked.
    let observer = LearnObserver::new();
    let observer_cb = observer.clone();

    let mut builder = Sandbox::builder()
        // Name + mode mark this as a learning sandbox in `sandlock ps`: the
        // observation policy below (read "/", allow-all network) would
        // otherwise look like a dangerously permissive run. One learn
        // sandbox per CLI process, so the pid keeps names unique.
        .name(format!("learn-{}", std::process::id()))
        .mode("learn")
        .fs_read("/")
        // Device opens bypass COW and land on the real node, so a terminal
        // or `> /dev/null` needs Landlock write on /dev to keep working.
        .fs_write("/dev")
        .workdir("/")
        // Discard all COW changes after observation; learn is read-only from
        // the real filesystem's perspective.
        .on_exit(BranchAction::Abort)
        .on_error(BranchAction::Abort)
        // A scheme-less "*" covers TCP and UDP; ICMP always needs its own rule.
        .net_allow("*")
        .net_allow("icmp://*")
        // Observation must see every bind the program attempts, so nothing
        // may refuse one before it is recorded.
        .net_allow_bind("*")
        .max_memory(sandlock_core::sandbox::ByteSize(1 << 43)) // 8 TiB
        .policy_fn(move |event, _ctx| observer_cb.on_event(event));

    let http_requests_cb = Arc::clone(&observer.http_requests);
    let http_log: Arc<dyn Fn(&str, &str, &str) + Send + Sync> =
        Arc::new(move |method, host, path| {
            http_requests_cb.lock().unwrap().insert(format!("{method} {host}{path}"));
        });
    builder = builder.http_log_fn(http_log);
    for path in &args.http_inject_ca {
        builder = builder.http_inject_ca(path);
    }
    for port in &args.http_port {
        builder = builder.http_port(*port);
    }
    if let Some(ref out) = args.http_ca_out {
        builder = builder.http_ca_out(out);
    }
    for spec in &args.env_vars {
        if let Some((k, v)) = spec.split_once('=') {
            builder = builder.env_var(k, v);
        } else {
            return Err(anyhow!("--env requires KEY=VALUE, got: {}", spec));
        }
    }

    let policy = builder
        .build()
        .map_err(|e| anyhow!("failed to build sandbox policy: {e}"))?;

    eprintln!("sandlock learn: observing {cmd_str} ...");

    // Use the three-step lifecycle (create/start/wait) so we can get the child
    // PID from sandbox.pid() and sample /proc/<pid> for resource peaks.
    let mut sandbox = policy;
    sandbox.create_interactive(&cmd_refs).await
        .map_err(|e| anyhow!("sandbox error: {e}"))?;
    let child_pid = sandbox.pid().expect("child pid after create") as u32;
    sandbox.start()
        .map_err(|e| anyhow!("sandbox error: {e}"))?;

    // Wait for the process, optionally with a timeout.
    let timed_out = if let Some(secs) = args.timeout {
        let deadline = std::time::Duration::from_secs(secs);
        match tokio::time::timeout(deadline, sandbox.wait()).await {
            Ok(r) => {
                let result = r.map_err(|e| anyhow!("sandbox error: {e}"))?;
                require_clean_exit(&result.exit_status)?;
                false
            }
            Err(_elapsed) => {
                // Timeout: kill the child, drain the supervisor, write a partial profile.
                eprintln!("sandlock learn: timeout after {secs}s, killing process");
                unsafe { libc::kill(child_pid as i32, libc::SIGKILL); }
                // Drain without timeout so the supervisor releases its resources cleanly.
                let _ = sandbox.wait().await;
                true
            }
        }
    } else {
        let result = sandbox.wait().await
            .map_err(|e| anyhow!("sandbox error: {e}"))?;
        require_clean_exit(&result.exit_status)?;
        false
    };

    if timed_out {
        eprintln!("sandlock learn: writing partial profile from observations before timeout");
    }

    let (peak_mem_bytes, peak_procs) = sandbox.resource_peaks().await;

    // Build the profile from observations.
    let mut profile_out = ProfileInput::default();

    // Record the observed command so `sandlock run -p profile.toml` works
    // without repeating the command on the CLI. Prefer the observed absolute
    // binary path over argv[0], which may be a bare name resolved via $PATH.
    let first_exe = observer.first_exe.lock().unwrap().clone();
    profile_out.program.exec = first_exe.or_else(|| Some(PathBuf::from(&args.cmd[0])));
    profile_out.program.args = args.cmd[1..].to_vec();
    for spec in &args.env_vars {
        if let Some((k, v)) = spec.split_once('=') {
            profile_out.program.env.insert(k.to_string(), v.to_string());
        }
    }

    let reads_raw: Vec<PathBuf> = observer.reads.lock().unwrap().iter()
        .filter(|p| p.exists() && !is_junk_path(p))
        .map(|p| fold_session_path(p.clone()))
        .filter(|p| {
            // Same guard the write side has: "/" is never a grant. A child
            // whose cwd is the workdir root lists it routinely (python's -c
            // puts the cwd on sys.path), and granting it would subsume every
            // other read in the profile.
            if is_fs_root(p) {
                eprintln!(
                    "sandlock learn: WARNING: observed a direct read of '/', refusing to grant it"
                );
                return false;
            }
            true
        })
        .collect();
    let writes_raw = observer.writes.lock().unwrap();
    let observed_all: BTreeSet<PathBuf> = reads_raw.iter()
        .chain(writes_raw.iter())
        .cloned()
        .collect();

    let reads = if let Some(n) = args.collapse {
        dedup_subsumed(collapse_by_threshold(reads_raw, n, &args.collapse_prefix, &observed_all))
    } else if !args.collapse_prefix.is_empty() {
        dedup_subsumed(collapse_by_threshold(reads_raw, usize::MAX, &args.collapse_prefix, &observed_all))
    } else {
        dedup_subsumed(reads_raw)
    };

    let writes_collapsed = collapse_write_paths(&writes_raw);
    let writes = if let Some(n) = args.collapse {
        dedup_subsumed(collapse_by_threshold(writes_collapsed, n, &args.collapse_prefix, &observed_all))
    } else if !args.collapse_prefix.is_empty() {
        dedup_subsumed(collapse_by_threshold(writes_collapsed, usize::MAX, &args.collapse_prefix, &observed_all))
    } else {
        dedup_subsumed(writes_collapsed)
    };

    profile_out.filesystem = FilesystemSection {
        read: reads,
        write: writes,
        ..Default::default()
    };
    profile_out.network.allow = observer.connects.lock().unwrap().iter().cloned().collect();
    profile_out.network.allow_bind = observer.binds.lock().unwrap().iter()
        .map(|&p| sandlock_core::profile::PortSpec::Port(p))
        .collect();

    let http_reqs: Vec<String> = observer.http_requests.lock().unwrap().iter().cloned().collect();
    if !http_reqs.is_empty() {
        profile_out.http.ports = sandbox.http_ports.clone();
        profile_out.http.allow = http_reqs;
        profile_out.config.http_inject_ca = args.http_inject_ca.clone();
        profile_out.config.http_ca_out = args.http_ca_out.clone();
    }

    // Fill limits with observed peaks + headroom so the profile is usable with sandlock run.
    // Memory: tracked via the sentinel max_memory in the builder, which activates handle_memory
    // so peak_mem_bytes uses the same virtual-anonymous accounting that sandlock run enforces.
    if peak_mem_bytes > 0 {
        let mib = (peak_mem_bytes / (1024 * 1024)).max(1);
        let headroom = (mib * 5 / 4).max(16);
        profile_out.limits.memory = Some(format!("{headroom}M"));
    }
    if peak_procs > 0 {
        profile_out.limits.processes = Some((peak_procs * 2).max(4));
    }
    // TODO: learn limits.open_files via supervisor once open_files enforcement is implemented.

    // --merge: union observed profile into an existing one.
    // Start from the existing profile so all fields we don't observe
    // are preserved. Then union in the observed fields.
    if let Some(ref merge_path) = args.merge {
        let existing_toml = std::fs::read_to_string(merge_path)
            .map_err(|e| anyhow!("failed to read merge file {}: {e}", merge_path.display()))?;
        let existing: ProfileInput = toml::from_str(&existing_toml)
            .map_err(|e| anyhow!("failed to parse merge file {}: {e}", merge_path.display()))?;

        // Base is the existing profile; union observed fields into it.
        let observed = profile_out;
        profile_out = existing.clone();

        // Union filesystem paths, re-run dedup after merging. Dedup keys on
        // the expanded path but writes back the raw entry, so a profile's
        // ${HOME} survives instead of being replaced by this machine's
        // absolute path.
        let mut home: Option<String> = None;
        let mut expand_key = |p: &PathBuf| -> Result<PathBuf> {
            let s = p.to_string_lossy();
            if !s.contains('$') {
                return Ok(p.clone());
            }
            if home.is_none() {
                home = Some(sandlock_core::expand::resolve_home()?);
            }
            // Observed kernel paths can contain a literal $, which the grammar
            // rejects; key them raw so an odd filename cannot abort the merge.
            match sandlock_core::expand::expand(&s, home.as_deref().unwrap()) {
                Ok(e) => Ok(PathBuf::from(e)),
                Err(_) => Ok(p.clone()),
            }
        };
        let mut merge_paths = |observed: &[PathBuf], existing: &[PathBuf]| -> Result<Vec<PathBuf>> {
            let mut by_expanded: BTreeMap<PathBuf, PathBuf> = BTreeMap::new();
            for p in observed {
                by_expanded.insert(expand_key(p)?, p.clone());
            }
            // Existing entries land second so their raw spelling wins.
            for p in existing {
                by_expanded.insert(expand_key(p)?, p.clone());
            }
            let kept = dedup_subsumed(by_expanded.keys().cloned().collect());
            Ok(kept.into_iter().map(|k| by_expanded[&k].clone()).collect())
        };
        profile_out.filesystem.read =
            merge_paths(&observed.filesystem.read, &existing.filesystem.read)?;
        profile_out.filesystem.write =
            merge_paths(&observed.filesystem.write, &existing.filesystem.write)?;

        // Union network.allow.
        let mut allow_set: std::collections::BTreeSet<String> =
            observed.network.allow.iter().cloned().collect();
        allow_set.extend(existing.network.allow.iter().cloned());
        profile_out.network.allow = allow_set.into_iter().collect();

        // Union allow_bind: preserve PortSpec verbatim (ranges, named specs).
        // Dedup by canonical string: Port(n) -> "n", Spec(s) -> s.
        let port_key = |p: &sandlock_core::profile::PortSpec| -> String {
            match p {
                sandlock_core::profile::PortSpec::Port(n) => n.to_string(),
                sandlock_core::profile::PortSpec::Spec(s) => s.clone(),
            }
        };
        let mut seen = std::collections::HashSet::new();
        let mut merged_bind: Vec<sandlock_core::profile::PortSpec> = Vec::new();
        for p in observed.network.allow_bind.iter().chain(existing.network.allow_bind.iter()) {
            if seen.insert(port_key(p)) {
                merged_bind.push(p.clone());
            }
        }
        profile_out.network.allow_bind = merged_bind;

        // Limits: take the max of old vs observed.
        profile_out.limits.memory = max_bytesize(existing.limits.memory.as_deref(), observed.limits.memory.as_deref());
        profile_out.limits.processes = max_opt(existing.limits.processes, observed.limits.processes);
        profile_out.limits.open_files = max_opt(existing.limits.open_files, observed.limits.open_files);

        // Union http.allow, http.ports, and config.http_inject_ca.
        let mut http_allow_set: std::collections::BTreeSet<String> =
            observed.http.allow.iter().cloned().collect();
        http_allow_set.extend(existing.http.allow.iter().cloned());
        profile_out.http.allow = http_allow_set.into_iter().collect();

        let mut http_ports_set: std::collections::BTreeSet<u16> =
            observed.http.ports.iter().cloned().collect();
        http_ports_set.extend(existing.http.ports.iter().cloned());
        profile_out.http.ports = http_ports_set.into_iter().collect();

        let mut ca_set: std::collections::BTreeSet<std::path::PathBuf> =
            observed.config.http_inject_ca.iter().cloned().collect();
        ca_set.extend(existing.config.http_inject_ca.iter().cloned());
        profile_out.config.http_inject_ca = ca_set.into_iter().collect();

        // http_ca_out: take from observed when existing has none.
        if profile_out.config.http_ca_out.is_none() {
            profile_out.config.http_ca_out = observed.config.http_ca_out;
        }

        // env: union observed vars into existing, observed wins on conflict.
        for (k, v) in observed.program.env {
            profile_out.program.env.insert(k, v);
        }
    }

    let kernel = std::fs::read_to_string("/proc/version")
        .unwrap_or_default()
        .split_whitespace()
        .nth(2)
        .unwrap_or("unknown")
        .to_string();
    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs().to_string())
        .unwrap_or_default();
    let header = format!(
        "# generated by sandlock learn\n\
         # command: {}\n\
         # kernel: {kernel}\n\
         # timestamp: {timestamp}\n\n",
        cmd_str.replace('\n', " ")
    );
    let body = profile_out.to_toml()
        .map_err(|e| anyhow!("failed to serialize profile: {e}"))?;
    let toml_out = format!("{header}{body}");

    // Output target: -o overrides --merge's file; --merge writes back in place.
    let output_path = args.output.as_ref().or(args.merge.as_ref());
    match output_path {
        Some(path) => {
            std::fs::write(path, &toml_out)
                .map_err(|e| anyhow!("failed to write {}: {e}", path.display()))?;
            eprintln!("sandlock learn: profile written to {}", path.display());
        }
        None => print!("{toml_out}"),
    }

    Ok(())
}


/// Parse a bytesize string like "128M", "1G", "512K" into bytes.
fn parse_bytesize_bytes(s: &str) -> Option<u64> {
    let s = s.trim();
    let (num, mult) = if let Some(n) = s.strip_suffix('G') {
        (n, 1024 * 1024 * 1024u64)
    } else if let Some(n) = s.strip_suffix('M') {
        (n, 1024 * 1024u64)
    } else if let Some(n) = s.strip_suffix('K') {
        (n, 1024u64)
    } else {
        (s, 1u64)
    };
    num.trim().parse::<u64>().ok().map(|n| n * mult)
}

/// Return the larger of two optional bytesize strings.
fn max_bytesize(a: Option<&str>, b: Option<&str>) -> Option<String> {
    match (a, b) {
        (None, None) => None,
        (Some(s), None) | (None, Some(s)) => Some(s.to_string()),
        (Some(sa), Some(sb)) => {
            let va = parse_bytesize_bytes(sa).unwrap_or(0);
            let vb = parse_bytesize_bytes(sb).unwrap_or(0);
            Some(if va >= vb { sa.to_string() } else { sb.to_string() })
        }
    }
}

/// Return the larger of two optional u32 values.
fn max_opt(a: Option<u32>, b: Option<u32>) -> Option<u32> {
    match (a, b) {
        (None, None) => None,
        (Some(v), None) | (None, Some(v)) => Some(v),
        (Some(va), Some(vb)) => Some(va.max(vb)),
    }
}

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

    /// A slave pty path, guaranteed to exist for the duration of the test.
    fn open_pts() -> (libc::c_int, libc::c_int, PathBuf) {
        let (mut master, mut slave) = (-1, -1);
        let rc = unsafe {
            libc::openpty(&mut master, &mut slave, std::ptr::null_mut(),
                          std::ptr::null_mut(), std::ptr::null_mut())
        };
        assert_eq!(rc, 0, "openpty: {}", std::io::Error::last_os_error());
        let name = unsafe { std::ffi::CStr::from_ptr(libc::ttyname(slave)) };
        (master, slave, PathBuf::from(name.to_str().unwrap()))
    }

    #[test]
    fn controlling_terminal_is_granted_and_pts_folds_to_its_directory() {
        // /dev/tty is a stable path (it always means "my terminal"), so a
        // profile that omits it denies ncurses apps their screen. The pts
        // number is what changes between sessions.
        let (master, slave, pts) = open_pts();
        assert!(pts.starts_with("/dev/pts/"), "unexpected pts name {}", pts.display());
        let writes: BTreeSet<PathBuf> =
            [PathBuf::from("/dev/tty"), pts].into_iter().collect();
        let out = collapse_write_paths(&writes);
        unsafe { libc::close(slave); libc::close(master); }
        assert_eq!(out, vec![PathBuf::from("/dev/pts"), PathBuf::from("/dev/tty")]);
    }
}