1use super::facet::*;
14
15#[derive(Copy, Clone, Debug, PartialEq, Eq)]
19pub struct OrdBound<T> {
20 pub min: Option<T>,
21 pub max: Option<T>,
22}
23
24impl<T: Ord + Copy> OrdBound<T> {
25 pub fn at_most(ceiling: T) -> Self {
27 Self { min: None, max: Some(ceiling) }
28 }
29 pub fn at_least(floor: T) -> Self {
31 Self { min: Some(floor), max: None }
32 }
33 pub fn exactly(exact: T) -> Self {
35 Self { min: Some(exact), max: Some(exact) }
36 }
37 pub fn admits(self, term: T) -> bool {
39 self.min.is_none_or(|lo| lo <= term) && self.max.is_none_or(|hi| term <= hi)
40 }
41}
42
43fn ord_admits<T: Ord + Copy>(bound: Option<OrdBound<T>>, term: T) -> bool {
44 bound.is_none_or(|b| b.admits(term))
45}
46
47fn set_admits<T: Eq + Copy>(set: Option<&[T]>, term: T) -> bool {
48 set.is_none_or(|s| s.contains(&term))
49}
50
51#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct FacetMismatch {
59 pub facet: &'static str,
61 pub actual: &'static str,
63 pub bound: String,
65 pub plain_bound: Option<String>,
67 pub admits_count: usize,
75}
76
77impl std::fmt::Display for FacetMismatch {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 write!(f, "{} = {} (allowed: {})", self.facet, self.actual, self.bound)
80 }
81}
82
83fn ord_mismatch<T: Ord + Copy + FacetTerm>(facet: &'static str, bound: Option<OrdBound<T>>, term: T) -> Option<FacetMismatch> {
84 let b = bound?;
85 if b.admits(term) {
86 return None;
87 }
88 let say = |t: T| super::plain::spoken(facet, t.as_str());
89 let (bound, plain_bound) = match (b.min, b.max) {
90 (None, Some(hi)) => (format!("<= {}", hi.as_str()), say(hi).map(|h| format!("allowed up to: {h}"))),
91 (Some(lo), None) => (format!(">= {}", lo.as_str()), say(lo).map(|l| format!("allowed at least: {l}"))),
92 (Some(lo), Some(hi)) if lo == hi => (format!("{}..={}", lo.as_str(), hi.as_str()), say(lo).map(|l| format!("allowed: {l}"))),
93 (Some(lo), Some(hi)) => {
94 (format!("{}..={}", lo.as_str(), hi.as_str()), say(lo).zip(say(hi)).map(|(l, h)| format!("allowed: {l} to {h}")))
95 }
96 (None, None) => ("any".to_string(), Some("allowed: any".to_string())),
97 };
98 let admits_count = T::all().iter().filter(|t| b.admits(**t)).count();
99 Some(FacetMismatch { facet, actual: term.as_str(), bound, plain_bound, admits_count })
100}
101
102fn set_mismatch<T: PartialEq + Copy + FacetTerm>(facet: &'static str, set: Option<&[T]>, term: T) -> Option<FacetMismatch> {
103 let s = set?;
104 if s.contains(&term) {
105 return None;
106 }
107 let bound = format!("one of [{}]", s.iter().map(|t| t.as_str()).collect::<Vec<_>>().join(", "),);
108 let spoken: Option<Vec<&str>> = s.iter().map(|t| super::plain::spoken(facet, t.as_str())).collect();
109 let plain_bound = spoken.map(|p| format!("allowed: one of: {}", p.join(" / ")));
110 Some(FacetMismatch { facet, actual: term.as_str(), bound, plain_bound, admits_count: s.len() })
111}
112
113#[derive(Clone, Debug, Default, PartialEq, Eq)]
118pub struct Clause {
119 pub operation: Option<Vec<Operation>>,
120 pub local_locus: Option<OrdBound<LocalLocus>>,
121 pub remote_reach: Option<OrdBound<RemoteReach>>,
122 pub remote_binding: Option<Vec<RemoteBinding>>,
123 pub provenance: Option<OrdBound<Provenance>>,
124 pub scale: Option<OrdBound<Scale>>,
125 pub retrieval: Option<OrdBound<RetrievalGranularity>>,
126 pub authority: Option<OrdBound<Authority>>,
127 pub isolation: Option<OrdBound<Isolation>>,
128 pub reversibility: Option<OrdBound<Reversibility>>,
129 pub persistence_level: Option<OrdBound<PersistenceLevel>>,
130 pub trigger_escape: Option<OrdBound<TriggerEscape>>,
131 pub trigger_kind: Option<Vec<TriggerKind>>,
132 pub disclosure_audience: Option<OrdBound<DisclosureAudience>>,
133 pub disclosure_channel: Option<Vec<Channel>>,
134 pub disclosure_principal: Option<Vec<Principal>>,
135 pub secret_level: Option<OrdBound<SecretLevel>>,
136 pub secret_channel: Option<Vec<Channel>>,
137 pub secret_principal: Option<Vec<Principal>>,
138 pub net_direction: Option<OrdBound<NetDirection>>,
139 pub net_destination: Option<OrdBound<NetDestination>>,
140 pub net_payload: Option<OrdBound<NetPayload>>,
141 pub execution_trust: Option<OrdBound<ExecutionTrust>>,
142 pub supply_source: Option<Vec<SupplySource>>,
143 pub pinning: Option<OrdBound<Pinning>>,
144 pub exec_surface: Option<Vec<ExecSurface>>,
145 pub cost: Option<OrdBound<Cost>>,
146}
147
148impl Clause {
149 pub fn admits(&self, cap: &Capability) -> bool {
151 self.check(cap, Role::Allow)
152 }
153
154 fn matches_as_deny(&self, cap: &Capability) -> bool {
161 self.check(cap, Role::Deny)
162 }
163
164 fn check(&self, cap: &Capability, role: Role) -> bool {
165 self.first_mismatch(cap, role).is_none()
166 }
167
168 #[cfg(test)]
172 pub(crate) fn first_mismatch_for_test(&self, cap: &Capability, deny_role: bool) -> Option<FacetMismatch> {
173 self.first_mismatch(cap, if deny_role { Role::Deny } else { Role::Allow })
174 }
175
176 #[cfg(test)]
177 pub(crate) fn matches_as_deny_for_test(&self, cap: &Capability) -> bool {
178 self.matches_as_deny(cap)
179 }
180
181 fn first_mismatch(&self, cap: &Capability, role: Role) -> Option<FacetMismatch> {
193 set_mismatch("operation", self.operation.as_deref(), cap.operation)
194 .or_else(|| ord_mismatch("secret.level", self.secret_level, cap.secret.level))
195 .or_else(|| ord_mismatch("locus.local", self.local_locus, cap.locus.local))
196 .or_else(|| ord_mismatch("locus.remote", self.remote_reach, cap.locus.remote))
197 .or_else(|| set_mismatch("locus.binding", self.remote_binding.as_deref(), cap.locus.binding))
198 .or_else(|| ord_mismatch("locus.provenance", self.provenance, cap.locus.provenance))
199 .or_else(|| ord_mismatch("scale", self.scale, cap.scale))
200 .or_else(|| ord_mismatch("retrieval", self.retrieval, cap.retrieval))
201 .or_else(|| ord_mismatch("authority", self.authority, cap.authority))
202 .or_else(|| ord_mismatch("isolation", self.isolation, cap.isolation))
203 .or_else(|| ord_mismatch("reversibility", self.reversibility, cap.reversibility))
204 .or_else(|| ord_mismatch("persistence.level", self.persistence_level, cap.persistence.level))
205 .or_else(|| ord_mismatch("persistence.trigger.escape", self.trigger_escape, cap.persistence.trigger.escape))
206 .or_else(|| set_mismatch("persistence.trigger.kind", self.trigger_kind.as_deref(), cap.persistence.trigger.kind))
207 .or_else(|| ord_mismatch("disclosure.audience", self.disclosure_audience, cap.disclosure.audience))
208 .or_else(|| set_mismatch("disclosure.channel", self.disclosure_channel.as_deref(), cap.disclosure.channel))
209 .or_else(|| set_mismatch("disclosure.principal", self.disclosure_principal.as_deref(), cap.disclosure.principal))
210 .or_else(|| set_mismatch("secret.channel", self.secret_channel.as_deref(), cap.secret.channel))
211 .or_else(|| set_mismatch("secret.principal", self.secret_principal.as_deref(), cap.secret.principal))
212 .or_else(|| ord_mismatch("network.direction", self.net_direction, cap.network.direction))
213 .or_else(|| ord_mismatch("network.destination", self.net_destination, cap.network.destination))
214 .or_else(|| ord_mismatch("network.payload", self.net_payload, cap.network.payload))
215 .or_else(|| ord_mismatch("execution.trust", self.execution_trust, cap.execution.trust))
216 .or_else(|| self.supply_chain_mismatch(cap.execution.supply_chain, role))
217 .or_else(|| ord_mismatch("cost", self.cost, cap.cost))
218 }
219
220 fn supply_chain_mismatch(&self, sc: Option<SupplyChain>, role: Role) -> Option<FacetMismatch> {
225 if self.supply_chain_admits(sc, role) {
226 return None;
227 }
228 let Some(sc) = sc else {
229 return Some(FacetMismatch {
233 facet: "execution.supply_chain",
234 actual: "absent",
235 bound: "this clause constrains the supply chain, which this capability has none of".to_string(),
236 plain_bound: None,
237 admits_count: 0,
238 });
239 };
240 set_mismatch("supply_chain.source", self.supply_source.as_deref(), sc.source)
241 .or_else(|| ord_mismatch("supply_chain.pinning", self.pinning, sc.pinning))
242 .or_else(|| set_mismatch("supply_chain.exec_surface", self.exec_surface.as_deref(), sc.exec_surface))
243 }
244
245 fn supply_chain_admits(&self, sc: Option<SupplyChain>, role: Role) -> bool {
246 match sc {
247 None => match role {
248 Role::Allow => true,
249 Role::Deny => self.supply_source.is_none() && self.pinning.is_none() && self.exec_surface.is_none(),
250 },
251 Some(sc) => {
252 set_admits(self.supply_source.as_deref(), sc.source)
253 && ord_admits(self.pinning, sc.pinning)
254 && set_admits(self.exec_surface.as_deref(), sc.exec_surface)
255 }
256 }
257 }
258}
259
260#[derive(Copy, Clone, PartialEq, Eq)]
262enum Role {
263 Allow,
264 Deny,
265}
266
267#[derive(Clone, Debug, Default, PartialEq, Eq)]
270pub struct Level {
271 pub name: String,
272 pub allow: Vec<Clause>,
273 pub deny: Vec<Clause>,
274}
275
276impl Level {
277 pub fn new(name: impl Into<String>) -> Self {
280 Self { name: name.into(), allow: Vec::new(), deny: Vec::new() }
281 }
282
283 #[must_use]
285 pub fn allowing(mut self, clause: Clause) -> Self {
286 self.allow.push(clause);
287 self
288 }
289
290 #[must_use]
292 pub fn denying(mut self, clause: Clause) -> Self {
293 self.deny.push(clause);
294 self
295 }
296
297 pub fn nearest_miss(&self, cap: &Capability) -> Option<FacetMismatch> {
308 if self.allow.iter().any(|c| c.admits(cap)) {
309 return self.deny.iter().find(|c| c.matches_as_deny(cap)).map(|_| FacetMismatch {
311 facet: "deny-clause",
312 actual: "matched",
313 bound: "removed by an explicit deny clause".to_string(),
314 plain_bound: None,
315 admits_count: 0,
316 });
317 }
318 if self.allow.is_empty() {
319 return Some(FacetMismatch {
320 facet: "level",
321 actual: "any capability",
322 bound: "nothing — this level declares no allow clause".to_string(),
323 plain_bound: None,
324 admits_count: 0,
325 });
326 }
327 let on_topic = |c: &&Clause| c.operation.as_ref().is_none_or(|ops| ops.contains(&cap.operation));
328 let mut candidates: Vec<FacetMismatch> =
333 self.allow.iter().filter(on_topic).filter_map(|c| c.first_mismatch(cap, Role::Allow)).collect();
334 if candidates.is_empty() {
335 candidates = self.allow.iter().filter_map(|c| c.first_mismatch(cap, Role::Allow)).collect();
336 }
337 candidates.into_iter().max_by_key(|m| m.admits_count)
338 }
339
340 pub fn admits_capability(&self, cap: &Capability) -> bool {
341 self.allow.iter().any(|c| c.admits(cap)) && !self.deny.iter().any(|c| c.matches_as_deny(cap))
342 }
343
344 pub fn admits(&self, profile: &Profile) -> bool {
347 profile.capabilities.iter().all(|c| self.admits_capability(c))
348 }
349
350 #[must_use]
356 pub fn extend(base: &Level, name: impl Into<String>, extra_allow: Vec<Clause>) -> Level {
357 let mut allow = base.allow.clone();
358 allow.extend(extra_allow);
359 Level { name: name.into(), allow, deny: base.deny.clone() }
360 }
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366 use proptest::prelude::*;
367
368 fn cap(op: Operation) -> Capability {
369 Capability::new(op)
370 }
371
372 #[test]
373 fn empty_clause_admits_everything_empty_allow_admits_nothing() {
374 let all = Level::new("all").allowing(Clause::default());
375 let nothing = Level::new("nothing");
376 let destroy = Profile::of(vec![cap(Operation::Destroy)]);
377 assert!(all.admits(&destroy));
378 assert!(!nothing.admits(&destroy));
379 assert!(all.admits(&Profile::default()));
381 assert!(nothing.admits(&Profile::default()));
382 }
383
384 #[test]
390 fn nearest_miss_reports_the_clause_that_came_closest_not_the_first() {
391 let strict = Clause {
392 operation: Some(vec![Operation::Observe]),
393 local_locus: Some(OrdBound::at_most(LocalLocus::Temp)),
394 ..Default::default()
395 };
396 let loose = Clause {
397 operation: Some(vec![Operation::Observe]),
398 local_locus: Some(OrdBound::at_most(LocalLocus::WorktreeTrusted)),
399 ..Default::default()
400 };
401 let level = Level::new("two-reads").allowing(strict).allowing(loose);
403 let mut cap = Capability::new(Operation::Observe);
404 cap.locus.local = LocalLocus::Machine;
405
406 let m = level.nearest_miss(&cap).expect("machine locus exceeds both clauses");
407 assert_eq!(m.facet, "locus.local");
408 assert!(
409 m.bound.contains("worktree-trusted"),
410 "named the strictest clause (`{}`); the closest one allows <= worktree-trusted",
411 m.bound,
412 );
413 }
414
415 #[test]
416 fn read_local_admits_a_read_rejects_a_secret_and_a_destroy() {
417 let read_local = Level::new("read-local").allowing(Clause {
418 operation: Some(vec![Operation::Observe]),
419 local_locus: Some(OrdBound::at_most(LocalLocus::User)),
420 secret_level: Some(OrdBound::at_most(SecretLevel::UsesAmbient)),
421 net_direction: Some(OrdBound::at_most(NetDirection::Loopback)),
422 ..Default::default()
423 });
424
425 let plain_read = Profile::of(vec![{
426 let mut c = cap(Operation::Observe);
427 c.locus.local = LocalLocus::Worktree;
428 c
429 }]);
430 assert!(read_local.admits(&plain_read));
431
432 let secret_read = Profile::of(vec![{
433 let mut c = cap(Operation::Observe);
434 c.locus.local = LocalLocus::User;
435 c.secret.level = SecretLevel::Reads;
436 c
437 }]);
438 assert!(!read_local.admits(&secret_read), "cat ~/.ssh/id_rsa must not pass read-local");
439
440 let destroy = Profile::of(vec![cap(Operation::Destroy)]);
441 assert!(!read_local.admits(&destroy));
442 }
443
444 #[test]
445 fn yolo_deny_carves_out_the_catastrophe_corner() {
446 let yolo = Level::new("yolo").allowing(Clause::default()).denying(Clause {
447 operation: Some(vec![Operation::Destroy]),
448 reversibility: Some(OrdBound::at_least(Reversibility::Irreversible)),
449 scale: Some(OrdBound::at_least(Scale::Unbounded)),
450 ..Default::default()
451 });
452
453 let bounded = Profile::of(vec![{
455 let mut c = cap(Operation::Destroy);
456 c.scale = Scale::Bounded;
457 c.reversibility = Reversibility::Recoverable;
458 c
459 }]);
460 assert!(yolo.admits(&bounded));
461
462 let wipe = Profile::of(vec![{
464 let mut c = cap(Operation::Destroy);
465 c.scale = Scale::Unbounded;
466 c.reversibility = Reversibility::Irreversible;
467 c
468 }]);
469 assert!(!yolo.admits(&wipe));
470 }
471
472 #[test]
473 fn supply_chain_gates_network_sourced_code_and_is_vacuous_otherwise() {
474 let dev = Level::new("dev").allowing(Clause {
477 execution_trust: Some(OrdBound::at_most(ExecutionTrust::NetworkSourced)),
478 supply_source: Some(vec![
479 SupplySource::PublicRegistry,
480 SupplySource::SignedRepo,
481 SupplySource::PrivateRegistry,
482 SupplySource::Vendored,
483 ]),
484 ..Default::default()
485 });
486
487 let build = Profile::of(vec![{
489 let mut c = cap(Operation::Execute);
490 c.execution = Execution {
491 trust: ExecutionTrust::NetworkSourced,
492 supply_chain: Some(SupplyChain {
493 source: SupplySource::PublicRegistry,
494 pinning: Pinning::HashVerified,
495 exec_surface: ExecSurface::BuildScript,
496 }),
497 };
498 c
499 }]);
500 assert!(dev.admits(&build), "cargo build from a registry");
501
502 let curl_sh = Profile::of(vec![{
504 let mut c = cap(Operation::Execute);
505 c.execution = Execution {
506 trust: ExecutionTrust::NetworkSourced,
507 supply_chain: Some(SupplyChain {
508 source: SupplySource::UnverifiedUrl,
509 pinning: Pinning::Floating,
510 exec_surface: ExecSurface::RunArtifact,
511 }),
512 };
513 c
514 }]);
515 assert!(!dev.admits(&curl_sh), "curl | sh is an unverified-url source");
516
517 let plain = Profile::of(vec![cap(Operation::Observe)]);
519 assert!(dev.admits(&plain), "a command with no supply chain passes vacuously");
520 }
521
522 #[test]
523 fn a_supply_chain_deny_does_not_match_a_capability_without_one() {
524 let level = Level::new("x")
527 .allowing(Clause::default())
528 .denying(Clause { supply_source: Some(vec![SupplySource::UnverifiedUrl]), ..Default::default() });
529
530 let plain = Profile::of(vec![cap(Operation::Observe)]);
531 assert!(level.admits(&plain), "a supply-chain deny must not match a no-supply-chain cap");
532
533 let curl_sh = Profile::of(vec![{
535 let mut c = cap(Operation::Execute);
536 c.execution = Execution {
537 trust: ExecutionTrust::NetworkSourced,
538 supply_chain: Some(SupplyChain {
539 source: SupplySource::UnverifiedUrl,
540 pinning: Pinning::Floating,
541 exec_surface: ExecSurface::RunArtifact,
542 }),
543 };
544 c
545 }]);
546 assert!(!level.admits(&curl_sh), "the deny corner still catches the unverified-url source");
547 }
548
549 #[test]
550 fn extend_inherits_deny_and_adds_allow() {
551 let base = Level::new("base")
552 .allowing(Clause { operation: Some(vec![Operation::Observe]), ..Default::default() })
553 .denying(Clause { local_locus: Some(OrdBound::at_least(LocalLocus::Device)), ..Default::default() });
554 let child = Level::extend(
555 &base,
556 "child",
557 vec![Clause { operation: Some(vec![Operation::Create, Operation::Mutate]), ..Default::default() }],
558 );
559
560 assert!(child.admits(&Profile::of(vec![cap(Operation::Create)])), "added allow");
561 assert!(child.admits(&Profile::of(vec![cap(Operation::Observe)])), "inherited allow");
562
563 let device = Profile::of(vec![{
564 let mut c = cap(Operation::Mutate);
565 c.locus.local = LocalLocus::Device;
566 c
567 }]);
568 assert!(!child.admits(&device), "inherited deny still bites");
569 }
570
571 use crate::engine::testgen::{arb_clause, arb_level, arb_profile};
575
576 proptest! {
577 #[test]
580 fn totality(level in arb_level(), profile in arb_profile()) {
581 let first = level.admits(&profile);
582 prop_assert_eq!(first, level.admits(&profile));
583 }
584
585 #[test]
588 fn extends_is_a_superset(
589 base in arb_level(),
590 extra in prop::collection::vec(arb_clause(), 0..3),
591 profile in arb_profile(),
592 ) {
593 let extended = Level::extend(&base, "child", extra);
594 prop_assert!(!base.admits(&profile) || extended.admits(&profile));
595 }
596
597 #[test]
600 fn deny_only_shrinks(
601 level in arb_level(),
602 extra_deny in arb_clause(),
603 profile in arb_profile(),
604 ) {
605 let stricter = level.clone().denying(extra_deny);
606 prop_assert!(!stricter.admits(&profile) || level.admits(&profile));
607 }
608 }
609}