1use crate::cap_from_name;
12use std::collections::BTreeSet;
13
14pub const UNKNOWN: &str = "Unknown";
16
17#[derive(Debug, Clone)]
20pub struct PolicyRule {
21 pub effects: BTreeSet<&'static str>,
22 pub scope: Option<String>,
23 pub raw: String,
24}
25
26#[derive(Debug, Clone)]
31pub struct AllowRule {
32 pub effect: &'static str,
33 pub scope: Option<String>,
34 pub literals: BTreeSet<String>,
35 pub raw: String,
36}
37
38#[derive(Debug, Clone)]
41pub struct LayerRule {
42 pub from: String,
43 pub to: String,
44 pub raw: String,
45}
46
47#[derive(Default, Debug)]
49pub struct ParsedPolicy {
50 pub rules: Vec<PolicyRule>,
51 pub allow_rules: Vec<AllowRule>,
52 pub layer_rules: Vec<LayerRule>,
53}
54
55pub fn host_part(h: &str) -> &str {
61 if let Some(rest) = h.strip_prefix('[') {
62 return rest.split(']').next().unwrap_or(rest);
64 }
65 if h.matches(':').count() > 1 {
66 return h; }
68 h.split(':').next().unwrap_or(h)
69}
70
71pub fn cmd_base(c: &str) -> &str {
73 c.rsplit(['/', '\\']).next().unwrap_or(c)
74}
75
76pub fn fs_path_covered(a: &str, r: &str) -> bool {
81 if r.split(['/', '\\']).any(|c| c == "..") {
82 return false;
83 }
84 let absolute = |s: &str| s.starts_with('/') || s.starts_with('\\');
85 if absolute(a) != absolute(r) {
86 return false;
87 }
88 let norm = |s: &str| -> Vec<String> {
89 s.split(['/', '\\'])
90 .filter(|c| !c.is_empty() && *c != ".")
91 .map(|c| c.to_string())
92 .collect()
93 };
94 let (ac, rc) = (norm(a), norm(r));
95 ac.len() <= rc.len() && ac.iter().zip(&rc).all(|(x, y)| x == y)
96}
97
98pub fn db_table_covered(a: &str, r: &str) -> bool {
104 let (a, r) = (a.to_lowercase(), r.to_lowercase());
105 if let Some(schema) = a.strip_suffix(".*") {
106 return r.strip_prefix(schema).is_some_and(|rest| rest.starts_with('.'));
107 }
108 a == r
109}
110
111pub fn literal_allowed(effect: &str, reached: &str, allow: &BTreeSet<String>) -> bool {
115 match effect {
116 "Net" => allow.iter().any(|a| host_part(a) == host_part(reached)),
117 "Exec" => allow.iter().any(|a| cmd_base(a) == cmd_base(reached)),
118 "Fs" => allow.iter().any(|a| fs_path_covered(a, reached)),
119 "Db" => allow.iter().any(|a| db_table_covered(a, reached)),
120 _ => allow.contains(reached),
121 }
122}
123
124fn name_segments(s: &str) -> Vec<&str> {
132 s.split(|c| c == '.' || c == ':').filter(|p| !p.is_empty()).collect()
133}
134
135pub fn scope_matches(name: &str, scope: &str) -> bool {
140 let segs = name_segments(name);
141 let parts = name_segments(scope);
142 if parts.is_empty() || parts.len() > segs.len() {
143 return false;
144 }
145 let (last, init) = parts.split_last().unwrap();
146 segs.windows(parts.len()).any(|w| {
147 let (w_last, w_init) = w.split_last().unwrap();
148 w_init == init && w_last.starts_with(last)
149 })
150}
151
152fn is_ascii_ws(c: char) -> bool {
171 matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
172}
173
174pub fn parse_policy(text: &str) -> ParsedPolicy {
175 let mut out = ParsedPolicy::default();
176 for raw_line in text.lines() {
177 let line = raw_line.split('#').next().unwrap_or("").trim_matches(is_ascii_ws);
178 if line.is_empty() {
179 continue;
180 }
181 let mut toks = line.split(is_ascii_ws).filter(|s| !s.is_empty());
182 match toks.next().unwrap_or("") {
183 "allow" => {
184 let effect = match toks.next().unwrap_or("") {
185 "Net" => "Net",
186 "Exec" => "Exec",
187 "Fs" => "Fs",
188 "Db" => "Db",
189 _ => {
190 eprintln!(
191 "candor: ignoring policy rule (allow supports only Net hosts / Exec commands / Fs paths / Db tables): {line}"
192 );
193 continue;
194 }
195 };
196 let mut rest: Vec<&str> = toks.collect();
197 let scope = if rest.first() == Some(&"in") {
198 let s = rest.get(1).map(|s| s.to_string());
199 rest.drain(..2.min(rest.len()));
200 s
201 } else {
202 None
203 };
204 let literals: BTreeSet<String> = rest.iter().map(|h| h.to_string()).collect();
205 if literals.is_empty() {
206 eprintln!("candor: ignoring policy rule (allow {effect} names no values): {line}");
207 continue;
208 }
209 out.allow_rules.push(AllowRule { effect, scope, literals, raw: line.to_string() });
210 }
211 "deny" => {
212 let mut effects = BTreeSet::new();
213 let mut scope = None;
214 for t in toks {
215 let e = if t == UNKNOWN { Some(UNKNOWN) } else { cap_from_name(t) };
216 match e {
217 Some(e) => {
218 effects.insert(e);
219 }
220 None => {
221 scope = Some(t.to_string());
222 break;
223 }
224 }
225 }
226 if effects.is_empty() {
227 eprintln!("candor: ignoring policy rule (no known effect named): {line}");
228 continue;
229 }
230 out.rules.push(PolicyRule { effects, scope, raw: line.to_string() });
231 }
232 "pure" => out.rules.push(PolicyRule {
233 effects: BTreeSet::new(),
234 scope: toks.next().map(str::to_string),
235 raw: line.to_string(),
236 }),
237 "forbid" => {
238 let a = toks.next().unwrap_or("");
239 let arrow = toks.next().unwrap_or("");
240 let b = toks.next().unwrap_or("");
241 if a.is_empty() || arrow != "->" || b.is_empty() {
242 eprintln!("candor: ignoring layering rule (want `forbid <scope> -> <scope>`): {line}");
243 continue;
244 }
245 out.layer_rules.push(LayerRule {
246 from: a.to_string(),
247 to: b.to_string(),
248 raw: line.to_string(),
249 });
250 }
251 other => eprintln!("candor: ignoring policy rule (unknown kind `{other}`): {line}"),
252 }
253 }
254 out
255}
256
257#[cfg(test)]
258mod tests {
259 #[test]
260 fn db_table_covering_is_strict() {
261 use super::db_table_covered as c;
262 assert!(c("ledger.entries", "Ledger.Entries")); assert!(c("ledger.*", "ledger.entries")); assert!(!c("ledger.*", "ledgerx.entries")); assert!(!c("entries", "ledger.entries")); assert!(c("entries", "entries"));
267 }
268
269 #[test]
270 fn allow_db_parses_and_gates() {
271 let p = super::parse_policy("allow Db in billing ledger.* customers\n");
272 assert_eq!(p.allow_rules.len(), 1);
273 assert_eq!(p.allow_rules[0].effect, "Db");
274 assert!(super::literal_allowed("Db", "ledger.entries", &p.allow_rules[0].literals));
275 assert!(super::literal_allowed("Db", "customers", &p.allow_rules[0].literals));
276 assert!(!super::literal_allowed("Db", "audit.log", &p.allow_rules[0].literals));
277 }
278
279 use super::*;
280
281 #[test]
282 fn policy_parses() {
283 let p = parse_policy(
284 "# the domain layer must stay pure of I/O\n\
285 deny Net Db domain\n\
286 deny Exec\n\
287 pure parse\n\
288 nonsense line\n\
289 deny notaneffect\n",
290 );
291 let rules = &p.rules;
292 assert_eq!(rules.len(), 3);
293 assert_eq!(rules[0].effects, ["Db", "Net"].into_iter().collect::<BTreeSet<_>>());
294 assert_eq!(rules[0].scope.as_deref(), Some("domain"));
295 assert!(rules[1].effects.contains("Exec") && rules[1].scope.is_none());
296 assert!(rules[2].effects.is_empty() && rules[2].scope.as_deref() == Some("parse"));
297 assert_eq!(parse_policy("deny Unknown core").rules[0].effects, ["Unknown"].into_iter().collect());
299 assert!(parse_policy("deny\ndeny \n").rules.is_empty());
300 assert!(parse_policy("deny notaneffect scope").rules.is_empty());
302 let p2 = parse_policy("deny Net foo Db");
304 assert_eq!(p2.rules[0].effects, ["Net"].into_iter().collect::<BTreeSet<_>>());
305 assert_eq!(p2.rules[0].scope.as_deref(), Some("foo"));
306 }
307
308 #[test]
309 fn allowlist_parses() {
310 let p = parse_policy(
311 "allow Net in billing api.stripe.com hooks.stripe.com\n\
312 allow Exec in ci git\n\
313 allow Fs in config /etc/app\n\
314 allow Net github.com\n\
315 allow Clock whatever\n\
316 allow Net in nohosts\n\
317 allow\n",
318 );
319 assert_eq!(p.allow_rules.len(), 4); assert_eq!((p.allow_rules[0].effect, p.allow_rules[0].scope.as_deref()), ("Net", Some("billing")));
321 assert_eq!(
322 p.allow_rules[0].literals,
323 ["api.stripe.com", "hooks.stripe.com"].iter().map(|s| s.to_string()).collect()
324 );
325 assert_eq!((p.allow_rules[1].effect, p.allow_rules[1].scope.as_deref()), ("Exec", Some("ci")));
326 assert!(p.allow_rules[1].literals.contains("git"));
327 assert_eq!((p.allow_rules[2].effect, p.allow_rules[2].scope.as_deref()), ("Fs", Some("config")));
328 assert_eq!((p.allow_rules[3].effect, p.allow_rules[3].scope.is_none()), ("Net", true));
329
330 let set = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<BTreeSet<_>>();
331 assert!(literal_allowed("Net", "api.stripe.com:443", &set(&["api.stripe.com"])));
332 assert!(literal_allowed("Net", "2001:db8::aa", &set(&["2001:db8::aa"])));
335 assert!(!literal_allowed("Net", "2001:db8::ff", &set(&["2001:db8::aa"])));
336 assert!(!literal_allowed("Net", "2001:dead::1", &set(&["2001:db8::aa"])));
337 assert!(literal_allowed("Net", "[2001:db8::aa]:443", &set(&["2001:db8::aa"])));
338 assert_eq!(host_part("2001:db8::aa"), "2001:db8::aa");
339 assert_eq!(host_part("[2001:db8::aa]:443"), "2001:db8::aa");
340 assert_eq!(host_part("api.stripe.com:443"), "api.stripe.com");
341 assert!(literal_allowed("Exec", "/usr/bin/git", &set(&["git"])));
342 assert!(!literal_allowed("Exec", "/usr/bin/curl", &set(&["git"])));
343 assert!(literal_allowed("Fs", "/etc/app/conf.toml", &set(&["/etc/app"])));
344 assert!(!literal_allowed("Fs", "/etc/shadow", &set(&["/etc/app"])));
345 assert_eq!(cmd_base("/usr/bin/git"), "git");
346 }
347
348 #[test]
349 fn layering_rule_parses() {
350 let p = parse_policy(
351 "forbid domain -> infra\n\
352 forbid app::web -> app::db \n\
353 forbid domain infra\n\
354 forbid domain ->\n\
355 forbid\n",
356 );
357 assert_eq!(p.layer_rules.len(), 2);
358 assert_eq!((p.layer_rules[0].from.as_str(), p.layer_rules[0].to.as_str()), ("domain", "infra"));
359 assert_eq!((p.layer_rules[1].from.as_str(), p.layer_rules[1].to.as_str()), ("app::web", "app::db"));
360 }
361
362 #[test]
363 fn scope_matches_by_segment_not_substring() {
364 assert!(scope_matches("app::domain::handle", "domain"));
365 assert!(scope_matches("domain::handle", "domain"));
366 assert!(scope_matches("app::domain", "domain"));
367 assert!(scope_matches("crate::domain_logic", "domain"));
368 assert!(!scope_matches("app::subdomain::handle", "domain"));
369 assert!(!scope_matches("app::not_my_domain::f", "domain"));
370 assert!(scope_matches("crate::net::client::send", "net::client"));
372 assert!(scope_matches("crate::net::client_pool::get", "net::client"));
373 assert!(!scope_matches("crate::net::server::send", "net::client"));
374 assert!(!scope_matches("crate::network::client::send", "net::client"));
375 assert!(!scope_matches("crate::net::x::client", "net::client"));
376 assert!(!scope_matches("net", "net::client"));
377 assert!(scope_matches("com.acme.domain.Pricing.quote", "domain"));
381 assert!(scope_matches("com.acme.domain.Pricing.quote", "acme.domain"));
382 assert!(scope_matches("com.acme.domain.Pricing.quote", "acme::domain"));
383 assert!(scope_matches("com.acme.infra.Net.fetch", "infra.Net"));
384 assert!(!scope_matches("com.acme.subdomain.h", "domain"));
385 assert!(!scope_matches("com.acme.domain.h", "infra"));
386 }
387
388 #[test]
389 fn fs_path_covered_respects_boundaries() {
390 assert!(fs_path_covered("/etc/app", "/etc/app"));
391 assert!(fs_path_covered("/etc/app", "/etc/app/cfg.toml"));
392 assert!(fs_path_covered("/etc/app/", "/etc/app/cfg"));
393 assert!(!fs_path_covered("/etc/app", "/etc/apppwned"));
394 assert!(!fs_path_covered("/etc/app", "/etc/application/x"));
395 assert!(!fs_path_covered("/etc/app/cfg", "/etc/app"));
396 assert!(!fs_path_covered("/etc/app", "/etc/app/../passwd"));
397 assert!(fs_path_covered("/", "/etc/app/x"));
398 assert!(!fs_path_covered("etc/app", "/etc/app/cfg"));
399 assert!(!fs_path_covered("/etc/app", "etc/app/cfg"));
400 assert!(fs_path_covered("etc/app", "etc/app/cfg"));
401 }
402}