libcontainer 0.6.0

Library for container control
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
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io::BufReader;
use std::os::fd::{AsRawFd, OwnedFd};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::str::FromStr;

use caps::Capability;
use nix::fcntl::OFlag;
use nix::unistd::{Pid, pipe2, read};
use oci_spec::runtime::{
    Capabilities as SpecCapabilities, Capability as SpecCapability, LinuxBuilder,
    LinuxCapabilities, LinuxCapabilitiesBuilder, LinuxNamespace, LinuxNamespaceBuilder,
    LinuxNamespaceType, LinuxSchedulerPolicy, Process, ProcessBuilder, Spec, UserBuilder,
};
use procfs::process::Namespace;

use super::Container;
use super::builder::ContainerBuilder;
use crate::capabilities::CapabilityExt;
use crate::container::builder_impl::ContainerBuilderImpl;
use crate::error::{ErrInvalidSpec, LibcontainerError, MissingSpecError};
use crate::notify_socket::NotifySocket;
use crate::process::args::ContainerType;
use crate::syscall::syscall::create_syscall;
use crate::user_ns::UserNamespaceConfig;
use crate::{tty, utils};

const NAMESPACE_TYPES: &[&str] = &["ipc", "uts", "net", "pid", "mnt", "cgroup"];
const TENANT_NOTIFY: &str = "tenant-notify-";
const TENANT_TTY: &str = "tenant-tty-";

fn get_path_from_spec(spec: &Spec) -> Option<String> {
    let process = match spec.process() {
        Some(p) => p,
        None => return None,
    };
    let env = match process.env() {
        Some(e) => e,
        None => return None,
    };
    // as per runtime spec, env vars should follow https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_01
    // and that specifies having multiple env with same name is undefined behaviour
    // so we take the last occurrence of PATH as that is somewhat intuitional of last
    // specified value overriding
    env.iter()
        .find(|e| e.starts_with("PATH"))
        .iter()
        .next_back()
        .map(|s| s.to_string())
}

/// Builder that can be used to configure the properties of a process
/// that will join an existing container sandbox
pub struct TenantContainerBuilder {
    base: ContainerBuilder,
    env: HashMap<String, String>,
    cwd: Option<PathBuf>,
    args: Vec<String>,
    no_new_privs: Option<bool>,
    capabilities: Vec<String>,
    process: Option<PathBuf>,
    detached: bool,
    as_sibling: bool,
    additional_gids: Vec<u32>,
    user: Option<u32>,
    group: Option<u32>,
}

/// This is a helper function to get capabilities for tenant container, based on
/// additional capabilities provided by user and capabilities of existing container
/// extracted into separate function for easier testing
fn get_capabilities(
    additional: &[String],
    spec: &Spec,
) -> Result<LinuxCapabilities, LibcontainerError> {
    let mut caps: Vec<Capability> = Vec::with_capacity(additional.len());
    for cap in additional {
        caps.push(Capability::from_str(cap)?);
    }
    let caps: SpecCapabilities = caps.iter().map(|c| SpecCapability::from_cap(*c)).collect();

    if let Some(spec_caps) = spec
        .process()
        .as_ref()
        .ok_or(MissingSpecError::Process)?
        .capabilities()
    {
        let mut capabilities_builder = LinuxCapabilitiesBuilder::default();

        let bounding: SpecCapabilities = match spec_caps.bounding() {
            Some(bounding) => bounding.union(&caps).copied().collect(),
            None => SpecCapabilities::new().union(&caps).copied().collect(),
        };
        capabilities_builder = capabilities_builder.bounding(bounding);

        let effective: SpecCapabilities = match spec_caps.effective() {
            Some(effective) => effective.union(&caps).copied().collect(),
            None => SpecCapabilities::new().union(&caps).copied().collect(),
        };
        capabilities_builder = capabilities_builder.effective(effective);

        let permitted: SpecCapabilities = match spec_caps.permitted() {
            Some(permitted) => permitted.union(&caps).copied().collect(),
            None => SpecCapabilities::new().union(&caps).copied().collect(),
        };
        capabilities_builder = capabilities_builder.permitted(permitted);

        // ambient capabilities are only useful when inherent capabilities
        // are set. Hence we check and set accordingly. Inherent capabilities
        // are never set from user as that can lead to vulnerability like
        // https://github.com/advisories/GHSA-f3fp-gc8g-vw66
        // Hence, we follow runc's code and set things similarly.
        let caps = if let Some(inheritable) = spec_caps.inheritable() {
            let ambient: SpecCapabilities = match spec_caps.ambient() {
                Some(ambient) => ambient.union(&caps).copied().collect(),
                None => SpecCapabilities::new().union(&caps).copied().collect(),
            };
            capabilities_builder = capabilities_builder.ambient(ambient);
            capabilities_builder = capabilities_builder.inheritable(inheritable.clone());
            capabilities_builder.build()?
        } else {
            let mut caps = capabilities_builder.build()?;
            // oci-spec-rs sets these to some default caps, so we reset them here
            caps.set_inheritable(None);
            caps.set_ambient(None);
            caps
        };

        return Ok(caps);
    }

    // If there are no caps in original container's spec,
    // we simply set given caps , excluding the inherent and ambient
    let mut caps = LinuxCapabilitiesBuilder::default()
        .bounding(caps.clone())
        .effective(caps.clone())
        .permitted(caps.clone())
        .build()?;
    caps.set_inheritable(None);
    caps.set_ambient(None);
    Ok(caps)
}

impl TenantContainerBuilder {
    /// Generates the base configuration for a process that will join
    /// an existing container sandbox from which configuration methods
    /// can be chained
    pub(super) fn new(builder: ContainerBuilder) -> Self {
        Self {
            base: builder,
            env: HashMap::new(),
            cwd: None,
            args: Vec::new(),
            no_new_privs: None,
            capabilities: Vec::new(),
            process: None,
            detached: false,
            as_sibling: false,
            additional_gids: vec![],
            user: None,
            group: None,
        }
    }

    /// Sets environment variables for the container
    pub fn with_env(mut self, env: HashMap<String, String>) -> Self {
        self.env = env;
        self
    }

    /// Sets the working directory of the container
    pub fn with_cwd<P: Into<PathBuf>>(mut self, path: Option<P>) -> Self {
        self.cwd = path.map(|p| p.into());
        self
    }

    /// Sets the command the container will be started with
    pub fn with_container_args(mut self, args: Vec<String>) -> Self {
        self.args = args;
        self
    }

    pub fn with_no_new_privs(mut self, no_new_privs: bool) -> Self {
        self.no_new_privs = Some(no_new_privs);
        self
    }

    pub fn with_capabilities(mut self, capabilities: Vec<String>) -> Self {
        self.capabilities = capabilities;
        self
    }

    pub fn with_process<P: Into<PathBuf>>(mut self, path: Option<P>) -> Self {
        self.process = path.map(|p| p.into());
        self
    }

    /// Sets if the init process should be run as a child or a sibling of
    /// the calling process
    pub fn as_sibling(mut self, as_sibling: bool) -> Self {
        self.as_sibling = as_sibling;
        self
    }

    pub fn with_detach(mut self, detached: bool) -> Self {
        self.detached = detached;
        self
    }

    pub fn with_additional_gids(mut self, gids: Vec<u32>) -> Self {
        self.additional_gids = gids;
        self
    }

    pub fn with_user(mut self, user: Option<u32>) -> Self {
        self.user = user;
        self
    }

    pub fn with_group(mut self, group: Option<u32>) -> Self {
        self.group = group;
        self
    }

    /// Joins an existing container
    pub fn build(self) -> Result<Pid, LibcontainerError> {
        let container_dir = self.lookup_container_dir()?;
        let container = self.load_container_state(container_dir.clone())?;
        let mut spec = self.load_init_spec(&container)?;
        self.adapt_spec_for_tenant(&mut spec, &container)?;

        tracing::debug!("{:#?}", spec);

        let notify_path = Self::setup_notify_listener(&container_dir)?;
        // convert path of root file system of the container to absolute path
        let rootfs = fs::canonicalize(spec.root().as_ref().ok_or(MissingSpecError::Root)?.path())
            .map_err(LibcontainerError::OtherIO)?;

        // if socket file path is given in commandline options,
        // get file descriptors of console socket
        let csocketfd = self.setup_tty_socket(&container_dir)?;

        let use_systemd = self.should_use_systemd(&container);
        let user_ns_config = UserNamespaceConfig::new(&spec)?;

        let (read_end, write_end) =
            pipe2(OFlag::O_CLOEXEC).map_err(LibcontainerError::OtherSyscall)?;

        let mut builder_impl = ContainerBuilderImpl {
            container_type: ContainerType::TenantContainer {
                exec_notify_fd: write_end.as_raw_fd(),
            },
            syscall: self.base.syscall,
            container_id: self.base.container_id,
            pid_file: self.base.pid_file,
            console_socket: csocketfd,
            use_systemd,
            spec: Rc::new(spec),
            rootfs,
            user_ns_config,
            notify_path: notify_path.clone(),
            container: None,
            preserve_fds: self.base.preserve_fds,
            detached: self.detached,
            executor: self.base.executor,
            no_pivot: false,
            stdin: self.base.stdin,
            stdout: self.base.stdout,
            stderr: self.base.stderr,
            as_sibling: self.as_sibling,
        };

        let pid = builder_impl.create()?;

        let mut notify_socket = NotifySocket::new(notify_path);
        notify_socket.notify_container_start()?;

        // Explicitly close the write end of the pipe here to notify the
        // `read_end` that the init process is able to move forward. Closing one
        // end of the pipe will immediately signal the other end of the pipe,
        // which we use in the init thread as a form of barrier.  `drop` is used
        // here because `OwnedFd` supports it, so we don't have to use `close`
        // here with `RawFd`.
        drop(write_end);

        let mut err_str_buf = Vec::new();

        loop {
            let mut buf = [0; 3];
            match read(read_end.as_raw_fd(), &mut buf).map_err(LibcontainerError::OtherSyscall)? {
                0 => {
                    if err_str_buf.is_empty() {
                        return Ok(pid);
                    } else {
                        return Err(LibcontainerError::Other(
                            String::from_utf8_lossy(&err_str_buf).to_string(),
                        ));
                    }
                }
                _ => {
                    err_str_buf.extend(buf);
                }
            }
        }
    }

    fn lookup_container_dir(&self) -> Result<PathBuf, LibcontainerError> {
        let container_dir = self.base.root_path.join(&self.base.container_id);
        if !container_dir.exists() {
            tracing::error!(?container_dir, ?self.base.container_id, "container dir does not exist");
            return Err(LibcontainerError::NoDirectory);
        }

        Ok(container_dir)
    }

    fn load_init_spec(&self, container: &Container) -> Result<Spec, LibcontainerError> {
        let spec_path = container.bundle().join("config.json");

        let mut spec = Spec::load(&spec_path).map_err(|err| {
            tracing::error!(path = ?spec_path, ?err, "failed to load spec");
            err
        })?;

        Self::validate_spec(&spec)?;

        spec.canonicalize_rootfs(container.bundle())?;
        Ok(spec)
    }

    fn validate_spec(spec: &Spec) -> Result<(), LibcontainerError> {
        let version = spec.version();
        if !version.starts_with("1.") {
            tracing::error!(
                "runtime spec has incompatible version '{}'. Only 1.X.Y is supported",
                spec.version()
            );
            Err(ErrInvalidSpec::UnsupportedVersion)?;
        }

        if let Some(process) = spec.process() {
            if let Some(io_priority) = process.io_priority() {
                let priority = io_priority.priority();
                let iop_class_res = serde_json::to_string(&io_priority.class());
                match iop_class_res {
                    Ok(iop_class) => {
                        if !(0..=7).contains(&priority) {
                            tracing::error!(
                                ?priority,
                                "io priority '{}' not between 0 and 7 (inclusive), class '{}' not in (IO_PRIO_CLASS_RT,IO_PRIO_CLASS_BE,IO_PRIO_CLASS_IDLE)",
                                priority,
                                iop_class
                            );
                            Err(ErrInvalidSpec::IoPriority)?;
                        }
                    }
                    Err(e) => {
                        tracing::error!(?priority, ?e, "failed to parse io priority class");
                        Err(ErrInvalidSpec::IoPriority)?;
                    }
                }
            }

            if let Some(sc) = process.scheduler() {
                let policy = sc.policy();
                if let Some(nice) = sc.nice() {
                    // https://man7.org/linux/man-pages/man2/sched_setattr.2.html#top_of_page
                    if (*policy == LinuxSchedulerPolicy::SchedBatch
                        || *policy == LinuxSchedulerPolicy::SchedOther)
                        && (*nice < -20 || *nice > 19)
                    {
                        tracing::error!(
                            ?nice,
                            "invalid scheduler.nice: '{}', must be within -20 to 19",
                            nice
                        );
                        Err(ErrInvalidSpec::Scheduler)?;
                    }
                }
                if let Some(priority) = sc.priority() {
                    if *priority != 0
                        && (*policy != LinuxSchedulerPolicy::SchedFifo
                            && *policy != LinuxSchedulerPolicy::SchedRr)
                    {
                        tracing::error!(
                            ?policy,
                            "scheduler.priority can only be specified for SchedFIFO or SchedRR policy"
                        );
                        Err(ErrInvalidSpec::Scheduler)?;
                    }
                }
                if *policy != LinuxSchedulerPolicy::SchedDeadline {
                    if let Some(runtime) = sc.runtime() {
                        if *runtime != 0 {
                            tracing::error!(
                                ?runtime,
                                "scheduler runtime can only be specified for SchedDeadline policy"
                            );
                            Err(ErrInvalidSpec::Scheduler)?;
                        }
                    }
                    if let Some(deadline) = sc.deadline() {
                        if *deadline != 0 {
                            tracing::error!(
                                ?deadline,
                                "scheduler deadline can only be specified for SchedDeadline policy"
                            );
                            Err(ErrInvalidSpec::Scheduler)?;
                        }
                    }
                    if let Some(period) = sc.period() {
                        if *period != 0 {
                            tracing::error!(
                                ?period,
                                "scheduler period can only be specified for SchedDeadline policy"
                            );
                            Err(ErrInvalidSpec::Scheduler)?;
                        }
                    }
                }
            }
        }

        if let Some(mounts) = spec.mounts() {
            utils::validate_mount_options(mounts)?;
        }

        let syscall = create_syscall();
        utils::validate_spec_for_new_user_ns(spec, &*syscall)?;
        utils::validate_spec_for_net_devices(spec, &*syscall)
            .map_err(LibcontainerError::NetDevicesError)?;

        Ok(())
    }

    fn load_container_state(&self, container_dir: PathBuf) -> Result<Container, LibcontainerError> {
        let container = Container::load(container_dir)?;
        if !container.can_exec() {
            tracing::error!(status = ?container.status(), "cannot exec as container");
            return Err(LibcontainerError::IncorrectStatus(container.status()));
        }

        Ok(container)
    }

    fn adapt_spec_for_tenant(
        &self,
        spec: &mut Spec,
        container: &Container,
    ) -> Result<(), LibcontainerError> {
        let process = if let Some(process) = &self.process {
            self.get_process(process)?
        } else {
            let original_path_env = get_path_from_spec(spec);
            let mut process_builder = ProcessBuilder::default()
                .args(self.get_args()?)
                .env(self.get_environment(original_path_env));
            if let Some(cwd) = self.get_working_dir()? {
                process_builder = process_builder.cwd(cwd);
            }

            if let Some(process) = spec.process() {
                if let Some(cpu_affinity) = process.exec_cpu_affinity() {
                    process_builder = process_builder.exec_cpu_affinity(cpu_affinity.clone());
                }
            }

            if let Some(no_new_priv) = self.get_no_new_privileges() {
                process_builder = process_builder.no_new_privileges(no_new_priv);
            }

            let capabilities = get_capabilities(&self.capabilities, spec)?;
            process_builder = process_builder.capabilities(capabilities);

            let mut user_builder = UserBuilder::default();

            if !self.additional_gids.is_empty() {
                user_builder = user_builder.additional_gids(self.additional_gids.clone());
            }

            if let Some(uid) = self.user {
                user_builder = user_builder.uid(uid);
            }

            if let Some(gid) = self.group {
                user_builder = user_builder.gid(gid);
            }

            process_builder = process_builder.user(user_builder.build()?);

            process_builder.build()?
        };

        let container_pid = container.pid().ok_or(LibcontainerError::Other(
            "could not retrieve container init pid".into(),
        ))?;

        let init_process = procfs::process::Process::new(container_pid.as_raw())?;
        let ns = self.get_namespaces(init_process.namespaces()?.0)?;

        // it should never be the case that linux is not present in spec
        let spec_linux = spec.linux().as_ref().unwrap();
        let mut linux_builder = LinuxBuilder::default().namespaces(ns);

        if let Some(cgroup_path) = spec_linux.cgroups_path() {
            linux_builder = linux_builder.cgroups_path(cgroup_path.clone());
        }

        if let Some(personality) = spec_linux.personality() {
            linux_builder = linux_builder.personality(personality.clone());
        }

        let linux = linux_builder.build()?;
        spec.set_process(Some(process)).set_linux(Some(linux));

        Ok(())
    }

    fn get_process(&self, process: &Path) -> Result<Process, LibcontainerError> {
        if !process.exists() {
            tracing::error!(?process, "process.json file does not exist");
            return Err(LibcontainerError::Other(
                "process.json file does not exist".into(),
            ));
        }

        let process = utils::open(process).map_err(LibcontainerError::OtherIO)?;
        let reader = BufReader::new(process);
        let process_spec =
            serde_json::from_reader(reader).map_err(LibcontainerError::OtherSerialization)?;
        Ok(process_spec)
    }

    fn get_working_dir(&self) -> Result<Option<PathBuf>, LibcontainerError> {
        if let Some(cwd) = &self.cwd {
            if cwd.is_relative() {
                tracing::error!(?cwd, "current working directory must be an absolute path");
                return Err(LibcontainerError::Other(
                    "current working directory must be an absolute path".into(),
                ));
            }
            return Ok(Some(cwd.into()));
        }
        Ok(None)
    }

    fn get_args(&self) -> Result<Vec<String>, LibcontainerError> {
        if self.args.is_empty() {
            Err(MissingSpecError::Args)?;
        }

        Ok(self.args.clone())
    }

    fn get_environment(&self, path: Option<String>) -> Vec<String> {
        let mut env_exists = false;
        let mut env: Vec<String> = self
            .env
            .iter()
            .map(|(k, v)| {
                if k == "PATH" {
                    env_exists = true;
                }
                format!("{k}={v}")
            })
            .collect();
        // It is not possible in normal flow that path is None. The original container
        // creation would have failed if path was absent. However we use Option
        // just as a caution, and if neither exec cmd not original spec has PATH,
        // the container creation will fail later which is ok
        if let Some(p) = path {
            if !env_exists {
                env.push(p);
            }
        }
        env
    }

    fn get_no_new_privileges(&self) -> Option<bool> {
        self.no_new_privs
    }

    fn get_namespaces(
        &self,
        init_namespaces: HashMap<OsString, Namespace>,
    ) -> Result<Vec<LinuxNamespace>, LibcontainerError> {
        let mut tenant_namespaces = Vec::with_capacity(init_namespaces.len());

        for &ns_type in NAMESPACE_TYPES {
            if let Some(init_ns) = init_namespaces.get(OsStr::new(ns_type)) {
                let tenant_ns = LinuxNamespaceType::try_from(ns_type)?;
                tenant_namespaces.push(
                    LinuxNamespaceBuilder::default()
                        .typ(tenant_ns)
                        .path(init_ns.path.clone())
                        .build()?,
                )
            }
        }

        Ok(tenant_namespaces)
    }

    fn should_use_systemd(&self, container: &Container) -> bool {
        container.systemd()
    }

    fn setup_notify_listener(container_dir: &Path) -> Result<PathBuf, LibcontainerError> {
        let notify_name = Self::generate_name(container_dir, TENANT_NOTIFY);
        let socket_path = container_dir.join(notify_name);

        Ok(socket_path)
    }

    fn setup_tty_socket(&self, container_dir: &Path) -> Result<Option<OwnedFd>, LibcontainerError> {
        let tty_name = Self::generate_name(container_dir, TENANT_TTY);
        let csocketfd = if let Some(console_socket) = &self.base.console_socket {
            Some(tty::setup_console_socket(
                container_dir,
                console_socket,
                &tty_name,
            )?)
        } else {
            None
        };

        Ok(csocketfd)
    }

    fn generate_name(dir: &Path, prefix: &str) -> String {
        loop {
            let rand = fastrand::i32(..);
            let name = format!("{prefix}{rand:x}.sock");
            if !dir.join(&name).exists() {
                return name;
            }
        }
    }
}

#[cfg(test)]
mod test {

    use caps::Capability as Cap;
    use oci_spec::runtime::{
        Capabilities, Capability as SpecCap, LinuxCapabilities, ProcessBuilder, Spec, SpecBuilder,
    };

    use super::{LibcontainerError, get_capabilities};
    use crate::capabilities::CapabilityExt;

    fn get_spec(caps: LinuxCapabilities) -> Spec {
        SpecBuilder::default()
            .process(
                ProcessBuilder::default()
                    .capabilities(caps)
                    .build()
                    .unwrap(),
            )
            .build()
            .unwrap()
    }

    fn cap_to_string(caps: &[Cap]) -> Vec<String> {
        caps.iter().map(|c| c.to_string()).collect()
    }

    fn caps_to_spec_set(caps: &[Cap]) -> Capabilities {
        caps.iter().map(|c| SpecCap::from_cap(*c)).collect()
    }

    fn empty_caps() -> LinuxCapabilities {
        let mut t = LinuxCapabilities::default();
        t.set_effective(None)
            .set_bounding(None)
            .set_permitted(None)
            .set_inheritable(None)
            .set_ambient(None);
        t
    }

    // if there are no existing capabilities, then tenant can only
    // set effective, bounding and permitted caps ; not inheritable or ambient
    #[test]
    fn test_capabilities_no_existing() -> Result<(), LibcontainerError> {
        let spec = get_spec(empty_caps());

        let extra_caps = &[Cap::CAP_SYS_ADMIN, Cap::CAP_NET_ADMIN, Cap::CAP_AUDIT_READ];

        let additional = cap_to_string(extra_caps);
        let caps = get_capabilities(&additional, &spec)?;

        let expected_caps = empty_caps()
            .set_effective(Some(caps_to_spec_set(extra_caps)))
            .set_bounding(Some(caps_to_spec_set(extra_caps)))
            .set_permitted(Some(caps_to_spec_set(extra_caps)))
            .clone();

        assert_eq!(caps, expected_caps);
        Ok(())
    }

    // If there are existing capabilities, but not inherent, then tenant should union
    // existing and provided caps only for effective, bounding and permitted,
    // inherent and ambient should be explicitly None
    #[test]
    fn test_capabilities_with_existing() -> Result<(), LibcontainerError> {
        let existing_caps = &[Cap::CAP_SYS_ADMIN, Cap::CAP_BPF, Cap::CAP_MKNOD];

        let existing = LinuxCapabilities::default()
            .set_effective(Some(caps_to_spec_set(existing_caps)))
            .set_bounding(Some(caps_to_spec_set(existing_caps)))
            .set_permitted(Some(caps_to_spec_set(existing_caps)))
            .set_inheritable(None)
            .set_ambient(None)
            .clone();

        let spec = get_spec(existing);

        let extra_caps = &[Cap::CAP_SYS_ADMIN, Cap::CAP_NET_ADMIN, Cap::CAP_AUDIT_READ];

        let additional = cap_to_string(extra_caps);
        let caps = get_capabilities(&additional, &spec)?;

        let mut combined_caps = existing_caps.to_vec();
        combined_caps.extend(extra_caps);
        let expected_caps = empty_caps()
            .set_effective(Some(caps_to_spec_set(&combined_caps)))
            .set_bounding(Some(caps_to_spec_set(&combined_caps)))
            .set_permitted(Some(caps_to_spec_set(&combined_caps)))
            .clone();

        assert_eq!(caps, expected_caps);
        Ok(())
    }

    // we check that if inherent capabilities are present, ambient are set correctly
    #[test]
    fn test_capabilities_with_existing_inherent() -> Result<(), LibcontainerError> {
        let existing_caps = &[Cap::CAP_SYS_ADMIN, Cap::CAP_BPF, Cap::CAP_MKNOD];
        let extra_caps = &[Cap::CAP_SYS_ADMIN, Cap::CAP_NET_ADMIN, Cap::CAP_AUDIT_READ];

        let mut combined_caps = existing_caps.to_vec();
        combined_caps.extend(extra_caps);

        // case 1 :  when inheritable are there, but no ambient

        let existing = LinuxCapabilities::default()
            .set_effective(Some(caps_to_spec_set(existing_caps)))
            .set_bounding(Some(caps_to_spec_set(existing_caps)))
            .set_permitted(Some(caps_to_spec_set(existing_caps)))
            .set_inheritable(Some(caps_to_spec_set(existing_caps)))
            .set_ambient(None)
            .clone();
        let spec = get_spec(existing);
        let additional = cap_to_string(extra_caps);
        let caps = get_capabilities(&additional, &spec)?;
        let expected_caps = empty_caps()
            .set_effective(Some(caps_to_spec_set(&combined_caps)))
            .set_bounding(Some(caps_to_spec_set(&combined_caps)))
            .set_permitted(Some(caps_to_spec_set(&combined_caps)))
            // inheritable must not change
            .set_inheritable(Some(caps_to_spec_set(existing_caps)))
            // as there were no existing ambient, only extra will be set
            .set_ambient(Some(caps_to_spec_set(extra_caps)))
            .clone();
        assert_eq!(caps, expected_caps);

        // case 2 :  when inheritable and ambient both are present

        let existing = LinuxCapabilities::default()
            .set_effective(Some(caps_to_spec_set(existing_caps)))
            .set_bounding(Some(caps_to_spec_set(existing_caps)))
            .set_permitted(Some(caps_to_spec_set(existing_caps)))
            .set_inheritable(Some(caps_to_spec_set(existing_caps)))
            .set_ambient(Some(caps_to_spec_set(existing_caps)))
            .clone();
        let spec = get_spec(existing);
        let additional = cap_to_string(extra_caps);
        let caps = get_capabilities(&additional, &spec)?;
        let expected_caps = empty_caps()
            .set_effective(Some(caps_to_spec_set(&combined_caps)))
            .set_bounding(Some(caps_to_spec_set(&combined_caps)))
            .set_permitted(Some(caps_to_spec_set(&combined_caps)))
            // inheritable must not change
            .set_inheritable(Some(caps_to_spec_set(existing_caps)))
            .set_ambient(Some(caps_to_spec_set(&combined_caps)))
            .clone();
        assert_eq!(caps, expected_caps);

        Ok(())
    }
}