agcodex_execpolicy/
valid_exec.rs

1use crate::arg_type::ArgType;
2use crate::error::Result;
3use serde::Serialize;
4
5/// exec() invocation that has been accepted by a `Policy`.
6#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
7pub struct ValidExec {
8    pub program: String,
9    pub flags: Vec<MatchedFlag>,
10    pub opts: Vec<MatchedOpt>,
11    pub args: Vec<MatchedArg>,
12
13    /// If non-empty, a prioritized list of paths to try instead of `program`.
14    /// For example, `/bin/ls` is harder to compromise than whatever `ls`
15    /// happens to be in the user's `$PATH`, so `/bin/ls` would be included for
16    /// `ls`. The caller is free to disregard this list and use `program`.
17    pub system_path: Vec<String>,
18}
19
20impl ValidExec {
21    pub fn new(program: &str, args: Vec<MatchedArg>, system_path: &[&str]) -> Self {
22        Self {
23            program: program.to_string(),
24            flags: vec![],
25            opts: vec![],
26            args,
27            system_path: system_path.iter().map(|&s| s.to_string()).collect(),
28        }
29    }
30
31    /// Whether a possible side effect of running this command includes writing
32    /// a file.
33    pub fn might_write_files(&self) -> bool {
34        self.opts.iter().any(|opt| opt.r#type.might_write_file())
35            || self.args.iter().any(|opt| opt.r#type.might_write_file())
36    }
37}
38
39#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
40pub struct MatchedArg {
41    pub index: usize,
42    pub r#type: ArgType,
43    pub value: String,
44}
45
46impl MatchedArg {
47    pub fn new(index: usize, r#type: ArgType, value: &str) -> Result<Self> {
48        r#type.validate(value)?;
49        Ok(Self {
50            index,
51            r#type,
52            value: value.to_string(),
53        })
54    }
55}
56
57/// A match for an option declared with opt() in a .policy file.
58#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
59pub struct MatchedOpt {
60    /// Name of the option that was matched.
61    pub name: String,
62    /// Value supplied for the option.
63    pub value: String,
64    /// Type of the value supplied for the option.
65    pub r#type: ArgType,
66}
67
68impl MatchedOpt {
69    pub fn new(name: &str, value: &str, r#type: ArgType) -> Result<Self> {
70        r#type.validate(value)?;
71        Ok(Self {
72            name: name.to_string(),
73            value: value.to_string(),
74            r#type,
75        })
76    }
77
78    pub fn name(&self) -> &str {
79        &self.name
80    }
81}
82
83#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
84pub struct MatchedFlag {
85    /// Name of the flag that was matched.
86    pub name: String,
87}
88
89impl MatchedFlag {
90    pub fn new(name: &str) -> Self {
91        Self {
92            name: name.to_string(),
93        }
94    }
95}