runner-manager-agent 0.4.63

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

use std::fs;
use std::io;
use std::path::{Component, Path, PathBuf};

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// The label the proxy puts on every container a job creates, naming the job's
/// attempt, so a later request can tell the job's containers from others.
pub const JOB_LABEL: &str = "runner-manager.job";

/// The policy's settings, in the configuration directory.
pub const CONFIG_FILE: &str = "docker-policy.json";

/// Where violations are recorded, under the state directory.
pub const LOG_DIR: &str = "docker-policy";
/// The violation log in [`LOG_DIR`], one JSON object per line.
pub const LOG_FILE: &str = "violations.jsonl";
/// The size at which the log is moved to `violations.jsonl.1`.
const LOG_ROTATE_BYTES: u64 = 1024 * 1024;

/// What the proxy does with a request that breaks a rule.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
    /// No rule is checked.
    Off,
    /// Each violation is recorded, and the request still goes to the engine.
    #[default]
    Audit,
    /// A request with a violation is refused, and the violation recorded.
    Enforce,
}

impl Mode {
    /// The mode as `host docker-policy set-mode` spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Audit => "audit",
            Self::Enforce => "enforce",
        }
    }
}

impl std::str::FromStr for Mode {
    type Err = String;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        [Self::Off, Self::Audit, Self::Enforce]
            .into_iter()
            .find(|mode| mode.as_str() == text)
            .ok_or_else(|| format!("expected off, audit or enforce, not {text}"))
    }
}

/// The operator's settings.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default)]
    pub mode: Mode,
    /// Host directories every job may bind-mount besides its own.
    #[serde(default)]
    pub allow: Vec<PathBuf>,
}

impl Config {
    /// The settings at `path`, or the defaults when there is no file.
    ///
    /// # Errors
    ///
    /// When the file cannot be read or does not parse.
    pub fn load(path: &Path) -> io::Result<Self> {
        runner_manager_platform::settings_file::load(path)
    }

    /// Writes the settings to `path`.
    ///
    /// # Errors
    ///
    /// When the file cannot be written.
    pub fn save(&self, path: &Path) -> io::Result<()> {
        runner_manager_platform::settings_file::save(path, self)
    }
}

/// What one attempt's proxy enforces, fixed when the attempt launches.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Context {
    pub mode: Mode,
    /// The directories a container may bind-mount from, already resolved.
    pub allowed: Vec<PathBuf>,
    /// Host paths the operator protected (`host protect-path`), already
    /// resolved: never mountable, even inside an allowed directory. The
    /// service's own sandbox hides them, but the engine runs outside it.
    #[serde(default)]
    pub protected: Vec<PathBuf>,
    /// The violation log.
    pub log: PathBuf,
}

/// Whether a container may bind-mount a host path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Access {
    Allowed,
    /// Outside the job's own directories and the operator's allowed ones.
    Outside,
    /// A protected path, or one inside or above it.
    Protected,
}

impl Context {
    /// Whether `violation` is recorded: every one unless the policy is off,
    /// and a protected path's always.
    #[must_use]
    pub fn records(&self, violation: &Violation) -> bool {
        self.mode != Mode::Off || violation.rule == PROTECTED_PATH
    }

    /// Whether `violation` refuses its request: every one in
    /// [`Mode::Enforce`], and a protected path's in every mode.
    #[must_use]
    pub fn refuses(&self, violation: &Violation) -> bool {
        self.mode == Mode::Enforce || violation.rule == PROTECTED_PATH
    }

    /// Whether a container may bind-mount `source`.
    ///
    /// A path with `..` is refused outright. Otherwise the longest existing
    /// prefix is resolved through every link on the host, so that a link the
    /// job left in its own directory cannot point a mount anywhere else, and
    /// the rest is appended as written: Docker creates a missing bind source
    /// as a directory.
    #[must_use]
    pub fn access(&self, source: &Path) -> Access {
        let Some(resolved) = (source.is_absolute()
            && !source
                .components()
                .any(|component| matches!(component, Component::ParentDir)))
        .then(|| resolve(source))
        .flatten() else {
            return Access::Outside;
        };
        if self
            .protected
            .iter()
            .any(|protected| resolved.starts_with(protected) || protected.starts_with(&resolved))
        {
            Access::Protected
        } else if self.allowed.iter().any(|root| resolved.starts_with(root)) {
            Access::Allowed
        } else {
            Access::Outside
        }
    }
}

/// The rule a mount of a protected path breaks.
const PROTECTED_PATH: &str = "protected_path";

/// A rule a request broke.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Violation {
    pub rule: String,
    pub detail: String,
}

impl Violation {
    pub(crate) fn new(rule: &str, detail: impl Into<String>) -> Self {
        let mut detail = detail.into();
        if detail.len() > 300 {
            let mut end = 300;
            while !detail.is_char_boundary(end) {
                end -= 1;
            }
            detail.truncate(end);
        }
        Self {
            rule: rule.to_owned(),
            detail,
        }
    }
}

/// One recorded violation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Record {
    pub at: String,
    pub attempt: String,
    pub repository: String,
    pub rule: String,
    pub detail: String,
    /// Whether the request was refused.
    pub refused: bool,
}

/// Appends `records` to the log at `path`, moving a full log aside first.
///
/// # Errors
///
/// When the log cannot be written.
pub fn record(path: &Path, records: &[Record]) -> io::Result<()> {
    use std::io::Write as _;
    if records.is_empty() {
        return Ok(());
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    if fs::metadata(path).is_ok_and(|metadata| metadata.len() > LOG_ROTATE_BYTES) {
        let mut rotated = path.as_os_str().to_owned();
        rotated.push(".1");
        fs::rename(path, rotated)?;
    }
    let mut options = fs::OpenOptions::new();
    options.create(true).append(true);
    #[cfg(unix)]
    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
    let mut file = options.open(path)?;
    for record in records {
        let mut line = serde_json::to_vec(record).map_err(super::invalid)?;
        line.push(b'\n');
        file.write_all(&line)?;
    }
    Ok(())
}

/// Every record in the log at `path` and its rotated predecessor, oldest
/// first. A line that does not parse is skipped.
#[must_use]
pub fn read_records(path: &Path) -> Vec<Record> {
    let mut rotated = path.as_os_str().to_owned();
    rotated.push(".1");
    [PathBuf::from(rotated), path.to_path_buf()]
        .iter()
        .filter_map(|path| fs::read_to_string(path).ok())
        .flat_map(|text| {
            text.lines()
                .filter_map(|line| serde_json::from_str(line).ok())
                .collect::<Vec<_>>()
        })
        .collect()
}

/// The API path without its version prefix: `/v1.47/containers/x/json`
/// becomes `/containers/x/json`.
#[must_use]
pub fn unversioned(endpoint: &str) -> &str {
    let rest = endpoint.strip_prefix('/').unwrap_or(endpoint);
    match rest.split_once('/') {
        Some((version, tail))
            if version.len() > 1
                && version.starts_with('v')
                && version[1..].chars().all(|c| c.is_ascii_digit() || c == '.') =>
        {
            &endpoint[endpoint.len() - tail.len() - 1..]
        }
        _ => endpoint,
    }
}

/// What a request acts on, when it is one container or exec instance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target<'a> {
    Container(&'a str),
    Exec(&'a str),
    None,
}

/// The container or exec instance an unversioned `endpoint` names.
#[must_use]
pub fn target(endpoint: &str) -> Target<'_> {
    let mut parts = endpoint.trim_start_matches('/').split('/');
    match (parts.next(), parts.next()) {
        (Some("containers"), Some(id)) if !matches!(id, "" | "create" | "json" | "prune") => {
            Target::Container(id)
        }
        (Some("exec"), Some(id)) if !id.is_empty() => Target::Exec(id),
        _ => Target::None,
    }
}

/// Rules an unversioned `endpoint` breaks by what it is, whatever its body.
#[must_use]
pub fn check_endpoint(method: &str, endpoint: &str, query: &str) -> Vec<Violation> {
    let mut violations = Vec::new();
    let first = endpoint
        .trim_start_matches('/')
        .split('/')
        .next()
        .unwrap_or("");
    if matches!(
        first,
        "plugins" | "swarm" | "services" | "secrets" | "configs" | "nodes" | "tasks"
    ) {
        violations.push(Violation::new(
            "host_wide_api",
            format!("{method} {endpoint} acts on the engine itself"),
        ));
    }
    // Podman's native API takes the same requests in another shape, which
    // none of the checks below read: a container created through it would
    // pass every rule unseen.
    if first == "libpod" {
        violations.push(Violation::new(
            "unchecked_api",
            format!("{method} {endpoint} is Podman's native API, which this policy cannot check"),
        ));
    }
    if method == "POST"
        && matches!(
            endpoint,
            "/containers/prune"
                | "/volumes/prune"
                | "/networks/prune"
                | "/images/prune"
                | "/build/prune"
        )
    {
        violations.push(Violation::new(
            "host_wide_prune",
            format!("{endpoint} removes what other jobs and the host created"),
        ));
    }
    if method == "POST"
        && endpoint == "/build"
        && query
            .split('&')
            .any(|field| field.eq_ignore_ascii_case("networkmode=host"))
    {
        violations.push(Violation::new(
            "host_network",
            "a build on the host's network",
        ));
    }
    violations
}

/// Rules a container-create `body` breaks. `allowed` says whether a host path
/// may be bind-mounted.
#[must_use]
pub fn check_container_create(body: &Value, allowed: &dyn Fn(&Path) -> Access) -> Vec<Violation> {
    let mut violations = Vec::new();
    let host = body.get("HostConfig").unwrap_or(&Value::Null);
    if host.get("Privileged").and_then(Value::as_bool) == Some(true) {
        violations.push(Violation::new("privileged", "a privileged container"));
    }
    for (key, rule) in [
        ("NetworkMode", "host_network"),
        ("PidMode", "host_pid"),
        ("IpcMode", "host_ipc"),
        ("UTSMode", "host_uts"),
        ("UsernsMode", "host_userns"),
        ("CgroupnsMode", "host_cgroupns"),
    ] {
        if host.get(key).and_then(Value::as_str) == Some("host") {
            violations.push(Violation::new(rule, format!("{key}=host")));
        }
    }
    if let Some(added) = host.get("CapAdd").and_then(Value::as_array)
        && !added.is_empty()
    {
        let names = added
            .iter()
            .filter_map(Value::as_str)
            .collect::<Vec<_>>()
            .join(",");
        violations.push(Violation::new(
            "added_capability",
            format!("CapAdd={names}"),
        ));
    }
    for key in ["Devices", "DeviceCgroupRules", "DeviceRequests"] {
        if host
            .get(key)
            .and_then(Value::as_array)
            .is_some_and(|devices| !devices.is_empty())
        {
            violations.push(Violation::new("host_device", format!("{key} is set")));
        }
    }
    if let Some(options) = host.get("SecurityOpt").and_then(Value::as_array) {
        for option in options.iter().filter_map(Value::as_str) {
            let lowered = option.to_ascii_lowercase();
            if lowered.contains("unconfined")
                || lowered == "label=disable"
                || lowered == "label:disable"
                || lowered.starts_with("no-new-privileges=false")
                || lowered.starts_with("no-new-privileges:false")
            {
                violations.push(Violation::new(
                    "weakened_security",
                    format!("SecurityOpt={option}"),
                ));
            }
        }
    }
    // An array, even an empty one, replaces the engine's defaults: what they
    // mask or keep read-only in `/proc` and `/sys` is then exposed.
    for key in ["MaskedPaths", "ReadonlyPaths"] {
        if host.get(key).is_some_and(Value::is_array) {
            violations.push(Violation::new(
                "weakened_security",
                format!("{key} replaces the engine's defaults"),
            ));
        }
    }
    if let Some(binds) = host.get("Binds").and_then(Value::as_array) {
        for bind in binds.iter().filter_map(Value::as_str) {
            let source = bind.split(':').next().unwrap_or("");
            if source.starts_with('/') {
                check_host_path(Path::new(source), allowed, &mut violations);
            }
        }
    }
    if let Some(mounts) = host.get("Mounts").and_then(Value::as_array) {
        for mount in mounts {
            match mount.get("Type").and_then(Value::as_str) {
                Some("bind") => {
                    if let Some(source) = mount.get("Source").and_then(Value::as_str) {
                        check_host_path(Path::new(source), allowed, &mut violations);
                    }
                }
                Some("volume") => {
                    if let Some(device) = bound_device(
                        mount
                            .pointer("/VolumeOptions/DriverConfig/Options")
                            .unwrap_or(&Value::Null),
                    ) {
                        check_host_path(Path::new(device), allowed, &mut violations);
                    }
                }
                _ => {}
            }
        }
    }
    violations
}

/// The other containers a container-create `body` joins or borrows from:
/// `container:<id>` namespaces and `VolumesFrom`. Whether each is the job's
/// own is for the proxy to ask the engine.
#[must_use]
pub fn referenced_containers(body: &Value) -> Vec<String> {
    let host = body.get("HostConfig").unwrap_or(&Value::Null);
    let mut referenced = Vec::new();
    for key in ["NetworkMode", "PidMode", "IpcMode"] {
        if let Some(other) = host
            .get(key)
            .and_then(Value::as_str)
            .and_then(|mode| mode.strip_prefix("container:"))
        {
            referenced.push(other.to_owned());
        }
    }
    if let Some(sources) = host.get("VolumesFrom").and_then(Value::as_array) {
        referenced.extend(
            sources
                .iter()
                .filter_map(Value::as_str)
                .map(|source| source.split(':').next().unwrap_or(source).to_owned()),
        );
    }
    referenced
}

/// Rules an exec-create `body` breaks.
#[must_use]
pub fn check_exec_create(body: &Value) -> Vec<Violation> {
    if body.get("Privileged").and_then(Value::as_bool) == Some(true) {
        vec![Violation::new("privileged", "a privileged exec")]
    } else {
        Vec::new()
    }
}

/// Rules a volume-create `body` breaks.
#[must_use]
pub fn check_volume_create(body: &Value, allowed: &dyn Fn(&Path) -> Access) -> Vec<Violation> {
    let mut violations = Vec::new();
    if let Some(device) = bound_device(body.get("DriverOpts").unwrap_or(&Value::Null)) {
        check_host_path(Path::new(device), allowed, &mut violations);
    }
    violations
}

/// Rules a network-create `body` breaks.
#[must_use]
pub fn check_network_create(body: &Value) -> Vec<Violation> {
    match body.get("Driver").and_then(Value::as_str) {
        Some(driver @ ("macvlan" | "ipvlan")) => vec![Violation::new(
            "host_network",
            format!("a {driver} network on the host's LAN"),
        )],
        _ => Vec::new(),
    }
}

/// The host path a `local` volume's options mount, if they mount one: a
/// directory bound with `o=bind`, or a block device mounted as a filesystem
/// (`type=ext4,device=/dev/sda1`), which needs no bind option at all.
fn bound_device(options: &Value) -> Option<&str> {
    options
        .get("device")
        .and_then(Value::as_str)
        .filter(|device| device.starts_with('/'))
}

/// The engine sockets a container must never be handed: either one is the
/// whole engine, with none of these rules.
const ENGINE_SOCKETS: [&str; 2] = ["/var/run/docker.sock", "/run/docker.sock"];

/// Points every bind of the engine's own socket in a container-create `body`
/// at `proxy`, the job's proxy socket, and returns how many it changed.
///
/// The GitHub runner mounts `/var/run/docker.sock` into every job container
/// (`container:` jobs and service containers) so steps can use Docker. The
/// raw socket would let those steps reach the engine past this proxy and its
/// rules; the proxy's own socket gives them the same API, through the proxy.
pub fn redirect_engine_socket(body: &mut Value, proxy: &Path) -> usize {
    let is_engine = |source: &str| ENGINE_SOCKETS.contains(&source);
    let proxy = proxy.display().to_string();
    let mut changed = 0;
    let Some(host) = body.get_mut("HostConfig").and_then(Value::as_object_mut) else {
        return 0;
    };
    if let Some(binds) = host.get_mut("Binds").and_then(Value::as_array_mut) {
        for bind in binds {
            let Some(text) = bind.as_str() else { continue };
            let (source, rest) = text.split_once(':').unwrap_or((text, ""));
            if is_engine(source) {
                *bind = Value::String(if rest.is_empty() {
                    proxy.clone()
                } else {
                    format!("{proxy}:{rest}")
                });
                changed += 1;
            }
        }
    }
    if let Some(mounts) = host.get_mut("Mounts").and_then(Value::as_array_mut) {
        for mount in mounts {
            let bind = mount.get("Type").and_then(Value::as_str) == Some("bind");
            if let Some(source) = mount.get_mut("Source")
                && bind
                && source.as_str().is_some_and(is_engine)
            {
                *source = Value::String(proxy.clone());
                changed += 1;
            }
        }
    }
    changed
}

fn check_host_path(
    source: &Path,
    allowed: &dyn Fn(&Path) -> Access,
    violations: &mut Vec<Violation>,
) {
    if ENGINE_SOCKETS
        .iter()
        .any(|socket| source == Path::new(socket))
    {
        violations.push(Violation::new(
            "engine_socket",
            format!("{} is the Docker engine itself", source.display()),
        ));
        return;
    }
    match allowed(source) {
        Access::Allowed => {}
        Access::Protected => violations.push(Violation::new(
            PROTECTED_PATH,
            format!("{} is a protected host path", source.display()),
        )),
        Access::Outside => violations.push(Violation::new(
            "host_path",
            format!("{} is outside the job's own directories", source.display()),
        )),
    }
}

/// `path` with its longest existing prefix resolved through links.
#[must_use]
pub fn resolve(path: &Path) -> Option<PathBuf> {
    let mut existing = path.to_path_buf();
    let mut rest = Vec::new();
    loop {
        match fs::canonicalize(&existing) {
            Ok(mut resolved) => {
                for component in rest.iter().rev() {
                    resolved.push(component);
                }
                return Some(resolved);
            }
            Err(_) => {
                rest.push(existing.file_name()?.to_owned());
                existing = existing.parent()?.to_path_buf();
            }
        }
    }
}

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

    fn rules(violations: &[Violation]) -> Vec<&str> {
        violations
            .iter()
            .map(|violation| violation.rule.as_str())
            .collect()
    }

    #[test]
    fn the_version_prefix_is_dropped_and_targets_are_found() {
        assert_eq!(
            unversioned("/v1.47/containers/abc/json"),
            "/containers/abc/json"
        );
        assert_eq!(unversioned("/containers/abc/json"), "/containers/abc/json");
        assert_eq!(unversioned("/version"), "/version");
        assert_eq!(target("/containers/abc/exec"), Target::Container("abc"));
        assert_eq!(target("/containers/create"), Target::None);
        assert_eq!(target("/containers/json"), Target::None);
        assert_eq!(target("/exec/e1/start"), Target::Exec("e1"));
        assert_eq!(target("/images/json"), Target::None);
    }

    #[test]
    fn host_wide_endpoints_are_violations_and_ordinary_ones_are_not() {
        assert_eq!(
            rules(&check_endpoint("POST", "/swarm/init", "")),
            ["host_wide_api"]
        );
        assert_eq!(
            rules(&check_endpoint("POST", "/plugins/pull", "")),
            ["host_wide_api"]
        );
        assert_eq!(
            rules(&check_endpoint("POST", "/containers/prune", "")),
            ["host_wide_prune"]
        );
        assert_eq!(
            rules(&check_endpoint("POST", "/build", "t=x&networkmode=host")),
            ["host_network"]
        );
        assert!(check_endpoint("POST", "/build", "t=x").is_empty());
        assert_eq!(
            rules(&check_endpoint("POST", "/images/prune", "")),
            ["host_wide_prune"]
        );
        assert_eq!(
            rules(&check_endpoint("POST", "/libpod/containers/create", "")),
            ["unchecked_api"]
        );
        assert!(check_endpoint("GET", "/containers/json", "").is_empty());
        assert!(check_endpoint("POST", "/images/create", "fromImage=x").is_empty());
    }

    #[test]
    fn a_container_that_reaches_for_the_host_breaks_each_rule_it_touches() {
        let body = json!({
            "HostConfig": {
                "Privileged": true,
                "NetworkMode": "host",
                "PidMode": "host",
                "CapAdd": ["SYS_ADMIN"],
                "Devices": [{"PathOnHost": "/dev/sda"}],
                "SecurityOpt": ["seccomp=unconfined"],
                "Binds": ["/etc:/host-etc:ro", "/var/run/docker.sock:/var/run/docker.sock", "named:/data"],
                "Mounts": [{"Type": "bind", "Source": "/root", "Target": "/r"}]
            }
        });
        let found = check_container_create(&body, &|_| Access::Outside);
        assert_eq!(
            rules(&found),
            [
                "privileged",
                "host_network",
                "host_pid",
                "added_capability",
                "host_device",
                "weakened_security",
                "host_path",
                "engine_socket",
                "host_path"
            ]
        );
    }

    #[test]
    fn an_ordinary_job_container_breaks_nothing() {
        let body = json!({
            "Image": "node:22",
            "HostConfig": {
                "NetworkMode": "bridge",
                "Binds": ["/attempt/_work:/__w", "/attempt/externals:/__e:ro", "cache:/cache"],
                "Mounts": [{"Type": "tmpfs", "Target": "/tmp"}]
            }
        });
        let found = check_container_create(&body, &|path| {
            if path.starts_with("/attempt") {
                Access::Allowed
            } else {
                Access::Outside
            }
        });
        assert!(found.is_empty(), "{found:?}");
    }

    #[test]
    fn containers_a_new_one_joins_or_borrows_from_are_named() {
        let body = json!({"HostConfig": {
            "NetworkMode": "container:db",
            "PidMode": "host",
            "VolumesFrom": ["data:ro", "cache"]
        }});
        assert_eq!(referenced_containers(&body), ["db", "data", "cache"]);
    }

    #[test]
    fn volumes_and_networks_that_bind_the_host_are_violations() {
        let bound = json!({"Driver": "local", "DriverOpts": {"type": "none", "o": "bind", "device": "/srv/secret"}});
        assert_eq!(
            rules(&check_volume_create(&bound, &|_| Access::Outside)),
            ["host_path"]
        );
        assert!(check_volume_create(&json!({"Driver": "local"}), &|_| Access::Outside).is_empty());
        let disk =
            json!({"Driver": "local", "DriverOpts": {"type": "ext4", "device": "/dev/sda1"}});
        assert_eq!(
            rules(&check_volume_create(&disk, &|_| Access::Outside)),
            ["host_path"],
            "a host block device is mounted without any bind option"
        );
        assert_eq!(
            rules(&check_container_create(
                &json!({"HostConfig": {"MaskedPaths": [], "ReadonlyPaths": null}}),
                &|_| Access::Outside
            )),
            ["weakened_security"]
        );
        assert_eq!(
            rules(&check_network_create(&json!({"Driver": "macvlan"}))),
            ["host_network"]
        );
        assert!(check_network_create(&json!({"Driver": "bridge"})).is_empty());
        assert_eq!(
            rules(&check_exec_create(&json!({"Privileged": true}))),
            ["privileged"]
        );
        assert!(check_exec_create(&json!({"Cmd": ["sh"]})).is_empty());
    }

    #[cfg(unix)]
    #[test]
    fn a_link_inside_an_allowed_directory_does_not_carry_a_mount_outside_it() {
        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let attempt = root.path().join("attempt");
        fs::create_dir_all(attempt.join("_work")).unwrap();
        std::os::unix::fs::symlink(outside.path(), attempt.join("escape")).unwrap();
        let context = Context {
            mode: Mode::Enforce,
            allowed: vec![fs::canonicalize(&attempt).unwrap()],
            protected: vec![],
            log: root.path().join("log"),
        };
        let inside = |path: &Path| context.access(path) == Access::Allowed;
        assert!(inside(&attempt.join("_work")));
        assert!(inside(&attempt.join("_work/not/yet/created")));
        assert!(!inside(&attempt.join("escape")));
        assert!(!inside(&attempt.join("escape/inner")));
        assert!(!inside(&attempt.join("_work/../../etc")));
        assert!(!inside(Path::new("relative")));
    }

    #[cfg(unix)]
    #[test]
    fn a_protected_path_is_refused_even_inside_an_allowed_directory() {
        let root = tempfile::tempdir().unwrap();
        let shared = root.path().join("shared");
        fs::create_dir_all(shared.join("keys")).unwrap();
        fs::create_dir_all(shared.join("data")).unwrap();
        let context = Context {
            mode: Mode::Enforce,
            allowed: vec![fs::canonicalize(&shared).unwrap()],
            protected: vec![fs::canonicalize(shared.join("keys")).unwrap()],
            log: root.path().join("log"),
        };
        assert_eq!(context.access(&shared.join("data")), Access::Allowed);
        assert_eq!(context.access(&shared.join("keys/id")), Access::Protected);
        assert_eq!(
            context.access(&shared),
            Access::Protected,
            "a parent exposes it too"
        );
        assert_eq!(context.access(Path::new("/etc")), Access::Outside);
        let body =
            json!({"HostConfig": {"Binds": [format!("{}:/k", shared.join("keys").display())]}});
        assert_eq!(
            rules(&check_container_create(&body, &|path| context.access(path))),
            ["protected_path"]
        );
    }

    #[test]
    fn a_protected_path_is_refused_in_every_mode_and_the_rest_only_when_enforced() {
        let protected = Violation::new(PROTECTED_PATH, "/srv/keys");
        let privileged = Violation::new("privileged", "a privileged container");
        for (mode, recorded, refused) in [
            (Mode::Off, false, false),
            (Mode::Audit, true, false),
            (Mode::Enforce, true, true),
        ] {
            let context = Context {
                mode,
                allowed: vec![],
                protected: vec![],
                log: PathBuf::from("log"),
            };
            assert!(context.records(&protected) && context.refuses(&protected));
            assert_eq!(context.records(&privileged), recorded, "{mode:?}");
            assert_eq!(context.refuses(&privileged), refused, "{mode:?}");
        }
    }

    #[test]
    fn the_engine_socket_a_job_container_is_given_becomes_the_proxy() {
        let mut body = json!({"HostConfig": {
            "Binds": ["/var/run/docker.sock:/var/run/docker.sock", "/attempt/_work:/__w"],
            "Mounts": [{"Type": "bind", "Source": "/run/docker.sock", "Target": "/d.sock"}]
        }});
        let proxy = Path::new("/attempt/.docker-proxy/s");
        assert_eq!(redirect_engine_socket(&mut body, proxy), 2);
        assert_eq!(
            body.pointer("/HostConfig/Binds/0").unwrap(),
            "/attempt/.docker-proxy/s:/var/run/docker.sock"
        );
        assert_eq!(
            body.pointer("/HostConfig/Binds/1").unwrap(),
            "/attempt/_work:/__w"
        );
        assert_eq!(
            body.pointer("/HostConfig/Mounts/0/Source").unwrap(),
            "/attempt/.docker-proxy/s"
        );
        let allowed = |path: &Path| {
            if path == proxy || path.starts_with("/attempt") {
                Access::Allowed
            } else {
                Access::Outside
            }
        };
        assert!(check_container_create(&body, &allowed).is_empty());
    }

    #[test]
    fn records_round_trip_through_a_rotating_log() {
        let directory = tempfile::tempdir().unwrap();
        let log = directory.path().join(LOG_DIR).join(LOG_FILE);
        let entry = Record {
            at: "2026-11-10T00:00:00Z".into(),
            attempt: "a".into(),
            repository: "o/r".into(),
            rule: "privileged".into(),
            detail: "a privileged container".into(),
            refused: false,
        };
        record(&log, std::slice::from_ref(&entry)).unwrap();
        record(&log, std::slice::from_ref(&entry)).unwrap();
        assert_eq!(read_records(&log), [entry.clone(), entry]);
    }
}