Skip to main content

keel_policy/
narrow.rs

1//! Per-task policy narrowing: a child policy may only *reduce* reach.
2
3use crate::error::{PolicyError, PolicyResult};
4use crate::ids::TaskId;
5use crate::net::{NetworkPolicy, NetworkRule};
6use crate::paths::FsRule;
7use crate::policy::Policy;
8use chrono::{Duration, Utc};
9use std::collections::HashSet;
10use std::path::PathBuf;
11
12/// Requested changes when forking a space for a subtask.
13///
14/// All fields are optional tightenings. Anything that would expand reach
15/// relative to `parent` is rejected.
16#[derive(Debug, Clone, Default)]
17pub struct TaskSpec {
18    pub task_id: TaskId,
19    pub label: Option<String>,
20    /// Optional network override (must be ⊆ parent).
21    pub network: Option<NetworkPolicy>,
22    /// Extra deny paths (always allowed — denies only shrink reach).
23    pub extra_deny: Vec<PathBuf>,
24    /// Optional credential subset (by name). `None` = inherit all; `Some(vec![])` = none.
25    pub credential_names: Option<Vec<String>>,
26    /// Optional shorter TTL from now.
27    pub ttl: Option<Duration>,
28    /// If set, replace workspace root (must be under parent workspace or equal).
29    pub workspace: Option<PathBuf>,
30}
31
32/// Build a child policy from `parent` + `spec`. Fails if the child would expand reach.
33pub fn narrow_policy(parent: &Policy, spec: TaskSpec) -> PolicyResult<Policy> {
34    let mut child = parent.clone();
35    child.id = crate::ids::PolicyId::new();
36    child.task_id = Some(spec.task_id);
37    child.created_at = Utc::now();
38    if let Some(label) = spec.label {
39        child.label = Some(label);
40    }
41
42    if let Some(ws) = spec.workspace {
43        ensure_workspace_under_parent(&parent.workspace, &ws)?;
44        child.workspace = ws;
45    }
46
47    if let Some(net) = spec.network {
48        ensure_network_subseteq(&parent.network, &net)?;
49        child.network = net;
50    }
51
52    for path in spec.extra_deny {
53        child.fs.push(FsRule::deny(path));
54    }
55
56    if let Some(names) = spec.credential_names {
57        let allowed: HashSet<&str> = parent
58            .credentials
59            .iter()
60            .map(|c| c.name.as_str())
61            .collect();
62        let mut next = Vec::new();
63        for name in names {
64            if !allowed.contains(name.as_str()) {
65                return Err(PolicyError::Invalid(format!(
66                    "credential '{name}' is not granted by the parent policy"
67                )));
68            }
69            if let Some(g) = parent.credentials.iter().find(|c| c.name == name) {
70                next.push(g.clone());
71            }
72        }
73        child.credentials = next;
74    }
75
76    if let Some(ttl) = spec.ttl {
77        let expires = Utc::now() + ttl;
78        match parent.expires_at {
79            Some(parent_exp) if expires > parent_exp => {
80                return Err(PolicyError::Invalid(
81                    "child TTL cannot expire after the parent policy".into(),
82                ));
83            }
84            _ => child.expires_at = Some(expires),
85        }
86    }
87
88    // Child cannot flip default_read off→on or expand exec.
89    if child.default_read && !parent.default_read {
90        return Err(PolicyError::Invalid(
91            "child cannot enable default_read when parent has it disabled".into(),
92        ));
93    }
94
95    child.validate()?;
96    Ok(child)
97}
98
99fn ensure_workspace_under_parent(parent: &PathBuf, child: &PathBuf) -> PolicyResult<()> {
100    if child == parent {
101        return Ok(());
102    }
103    // Best-effort prefix check (canonicalization is caller's job when possible).
104    if child.starts_with(parent) {
105        return Ok(());
106    }
107    Err(PolicyError::Invalid(format!(
108        "child workspace {} is not under parent workspace {}",
109        child.display(),
110        parent.display()
111    )))
112}
113
114fn ensure_network_subseteq(parent: &NetworkPolicy, child: &NetworkPolicy) -> PolicyResult<()> {
115    match (parent, child) {
116        (NetworkPolicy::Unrestricted, _) => Ok(()),
117        (NetworkPolicy::DenyAll, NetworkPolicy::DenyAll) => Ok(()),
118        (NetworkPolicy::DenyAll, _) => Err(PolicyError::Invalid(
119            "child cannot expand network beyond parent DenyAll".into(),
120        )),
121        (NetworkPolicy::Allowlist(_), NetworkPolicy::DenyAll) => Ok(()),
122        (NetworkPolicy::Allowlist(p_rules), NetworkPolicy::Allowlist(c_rules)) => {
123            for r in c_rules {
124                if !allowlist_covers(p_rules, r) {
125                    return Err(PolicyError::Invalid(format!(
126                        "child allowlist rule {}:{} is not covered by parent",
127                        r.host,
128                        r.port.map(|p| p.to_string()).unwrap_or_else(|| "*".into())
129                    )));
130                }
131            }
132            Ok(())
133        }
134        (NetworkPolicy::Allowlist(_), NetworkPolicy::Unrestricted) => Err(PolicyError::Invalid(
135            "child cannot expand network to Unrestricted".into(),
136        )),
137    }
138}
139
140fn allowlist_covers(parent_rules: &[NetworkRule], child: &NetworkRule) -> bool {
141    parent_rules.iter().any(|p| {
142        // Parent host must match child host (parent can be broader wildcard).
143        let host_ok = crate::egress::host_matches(&p.host, &child.host)
144            || (p.host == child.host)
145            || (p.host == "*");
146        // Also allow parent wildcard covering child exact.
147        let host_ok = host_ok || host_pattern_covers(&p.host, &child.host);
148        if !host_ok {
149            return false;
150        }
151        match (p.port, child.port) {
152            (_, None) => p.port.is_none(), // child any-port needs parent any-port
153            (None, Some(_)) => true,       // parent any-port covers specific
154            (Some(pp), Some(cp)) => pp == cp,
155        }
156    })
157}
158
159fn host_pattern_covers(parent_pat: &str, child_host: &str) -> bool {
160    crate::egress::host_matches(parent_pat, child_host)
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use crate::net::{NetworkPolicy, NetworkRule};
167    use crate::policy::{CredentialGrant, Policy};
168
169    #[test]
170    fn can_narrow_network() {
171        let parent = Policy::builder("/tmp/ws")
172            .network(NetworkPolicy::Allowlist(vec![
173                NetworkRule::host_port("api.x.ai", 443),
174                NetworkRule::host_port("example.com", 443),
175            ]))
176            .build()
177            .unwrap();
178        let child = narrow_policy(
179            &parent,
180            TaskSpec {
181                task_id: TaskId::from_string("tsk-1"),
182                network: Some(NetworkPolicy::Allowlist(vec![NetworkRule::host_port(
183                    "api.x.ai",
184                    443,
185                )])),
186                ..Default::default()
187            },
188        )
189        .unwrap();
190        assert!(matches!(child.network, NetworkPolicy::Allowlist(ref r) if r.len() == 1));
191    }
192
193    #[test]
194    fn cannot_expand_network() {
195        let parent = Policy::builder("/tmp/ws")
196            .network(NetworkPolicy::DenyAll)
197            .build()
198            .unwrap();
199        let err = narrow_policy(
200            &parent,
201            TaskSpec {
202                task_id: TaskId::from_string("tsk-1"),
203                network: Some(NetworkPolicy::Unrestricted),
204                ..Default::default()
205            },
206        )
207        .unwrap_err();
208        assert!(matches!(err, PolicyError::Invalid(_)));
209    }
210
211    #[test]
212    fn extra_deny_ok() {
213        let parent = Policy::builder("/tmp/ws").build().unwrap();
214        let child = narrow_policy(
215            &parent,
216            TaskSpec {
217                task_id: TaskId::from_string("tsk-1"),
218                extra_deny: vec![PathBuf::from("/tmp/ws/secrets")],
219                ..Default::default()
220            },
221        )
222        .unwrap();
223        assert!(child.deny_paths().any(|r| r.path.ends_with("secrets")));
224    }
225
226    #[test]
227    fn credential_subset() {
228        let parent = Policy::builder("/tmp/ws")
229            .credential(CredentialGrant {
230                name: "a".into(),
231                source: "env:A".into(),
232                inject_as_env: None,
233            })
234            .credential(CredentialGrant {
235                name: "b".into(),
236                source: "env:B".into(),
237                inject_as_env: None,
238            })
239            .build()
240            .unwrap();
241        let child = narrow_policy(
242            &parent,
243            TaskSpec {
244                task_id: TaskId::from_string("tsk-1"),
245                credential_names: Some(vec!["a".into()]),
246                ..Default::default()
247            },
248        )
249        .unwrap();
250        assert_eq!(child.credentials.len(), 1);
251        assert_eq!(child.credentials[0].name, "a");
252    }
253}