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)]
181 pub(crate) fn first_mismatch_for_test(&self, cap: &Capability, deny_role: bool) -> Option<FacetMismatch> {
182 self.first_mismatch(cap, if deny_role { Role::Deny } else { Role::Allow })
183 }
184
185 #[cfg(test)]
186 pub(crate) fn matches_as_deny_for_test(&self, cap: &Capability) -> bool {
187 self.matches_as_deny(cap)
188 }
189
190 fn first_mismatch(&self, cap: &Capability, role: Role) -> Option<FacetMismatch> {
191 set_mismatch("operation", self.operation.as_deref(), cap.operation)
192 .or_else(|| ord_mismatch("locus.local", self.local_locus, cap.locus.local))
193 .or_else(|| ord_mismatch("locus.remote", self.remote_reach, cap.locus.remote))
194 .or_else(|| set_mismatch("locus.binding", self.remote_binding.as_deref(), cap.locus.binding))
195 .or_else(|| ord_mismatch("locus.provenance", self.provenance, cap.locus.provenance))
196 .or_else(|| ord_mismatch("scale", self.scale, cap.scale))
197 .or_else(|| ord_mismatch("retrieval", self.retrieval, cap.retrieval))
198 .or_else(|| ord_mismatch("authority", self.authority, cap.authority))
199 .or_else(|| ord_mismatch("isolation", self.isolation, cap.isolation))
200 .or_else(|| ord_mismatch("reversibility", self.reversibility, cap.reversibility))
201 .or_else(|| ord_mismatch("persistence.level", self.persistence_level, cap.persistence.level))
202 .or_else(|| ord_mismatch("persistence.trigger.escape", self.trigger_escape, cap.persistence.trigger.escape))
203 .or_else(|| set_mismatch("persistence.trigger.kind", self.trigger_kind.as_deref(), cap.persistence.trigger.kind))
204 .or_else(|| ord_mismatch("disclosure.audience", self.disclosure_audience, cap.disclosure.audience))
205 .or_else(|| set_mismatch("disclosure.channel", self.disclosure_channel.as_deref(), cap.disclosure.channel))
206 .or_else(|| set_mismatch("disclosure.principal", self.disclosure_principal.as_deref(), cap.disclosure.principal))
207 .or_else(|| ord_mismatch("secret.level", self.secret_level, cap.secret.level))
208 .or_else(|| set_mismatch("secret.channel", self.secret_channel.as_deref(), cap.secret.channel))
209 .or_else(|| set_mismatch("secret.principal", self.secret_principal.as_deref(), cap.secret.principal))
210 .or_else(|| ord_mismatch("network.direction", self.net_direction, cap.network.direction))
211 .or_else(|| ord_mismatch("network.destination", self.net_destination, cap.network.destination))
212 .or_else(|| ord_mismatch("network.payload", self.net_payload, cap.network.payload))
213 .or_else(|| ord_mismatch("execution.trust", self.execution_trust, cap.execution.trust))
214 .or_else(|| self.supply_chain_mismatch(cap.execution.supply_chain, role))
215 .or_else(|| ord_mismatch("cost", self.cost, cap.cost))
216 }
217
218 fn supply_chain_mismatch(&self, sc: Option<SupplyChain>, role: Role) -> Option<FacetMismatch> {
223 if self.supply_chain_admits(sc, role) {
224 return None;
225 }
226 let Some(sc) = sc else {
227 return Some(FacetMismatch {
231 facet: "execution.supply_chain",
232 actual: "absent",
233 bound: "this clause constrains the supply chain, which this capability has none of".to_string(),
234 plain_bound: None,
235 admits_count: 0,
236 });
237 };
238 set_mismatch("supply_chain.source", self.supply_source.as_deref(), sc.source)
239 .or_else(|| ord_mismatch("supply_chain.pinning", self.pinning, sc.pinning))
240 .or_else(|| set_mismatch("supply_chain.exec_surface", self.exec_surface.as_deref(), sc.exec_surface))
241 }
242
243 fn supply_chain_admits(&self, sc: Option<SupplyChain>, role: Role) -> bool {
244 match sc {
245 None => match role {
246 Role::Allow => true,
247 Role::Deny => self.supply_source.is_none() && self.pinning.is_none() && self.exec_surface.is_none(),
248 },
249 Some(sc) => {
250 set_admits(self.supply_source.as_deref(), sc.source)
251 && ord_admits(self.pinning, sc.pinning)
252 && set_admits(self.exec_surface.as_deref(), sc.exec_surface)
253 }
254 }
255 }
256}
257
258#[derive(Copy, Clone, PartialEq, Eq)]
260enum Role {
261 Allow,
262 Deny,
263}
264
265#[derive(Clone, Debug, Default, PartialEq, Eq)]
268pub struct Level {
269 pub name: String,
270 pub allow: Vec<Clause>,
271 pub deny: Vec<Clause>,
272}
273
274impl Level {
275 pub fn new(name: impl Into<String>) -> Self {
278 Self { name: name.into(), allow: Vec::new(), deny: Vec::new() }
279 }
280
281 #[must_use]
283 pub fn allowing(mut self, clause: Clause) -> Self {
284 self.allow.push(clause);
285 self
286 }
287
288 #[must_use]
290 pub fn denying(mut self, clause: Clause) -> Self {
291 self.deny.push(clause);
292 self
293 }
294
295 pub fn nearest_miss(&self, cap: &Capability) -> Option<FacetMismatch> {
306 if self.allow.iter().any(|c| c.admits(cap)) {
307 return self.deny.iter().find(|c| c.matches_as_deny(cap)).map(|_| FacetMismatch {
309 facet: "deny-clause",
310 actual: "matched",
311 bound: "removed by an explicit deny clause".to_string(),
312 plain_bound: None,
313 admits_count: 0,
314 });
315 }
316 if self.allow.is_empty() {
317 return Some(FacetMismatch {
318 facet: "level",
319 actual: "any capability",
320 bound: "nothing — this level declares no allow clause".to_string(),
321 plain_bound: None,
322 admits_count: 0,
323 });
324 }
325 let on_topic = |c: &&Clause| c.operation.as_ref().is_none_or(|ops| ops.contains(&cap.operation));
326 let mut candidates: Vec<FacetMismatch> =
331 self.allow.iter().filter(on_topic).filter_map(|c| c.first_mismatch(cap, Role::Allow)).collect();
332 if candidates.is_empty() {
333 candidates = self.allow.iter().filter_map(|c| c.first_mismatch(cap, Role::Allow)).collect();
334 }
335 candidates.into_iter().max_by_key(|m| m.admits_count)
336 }
337
338 pub fn admits_capability(&self, cap: &Capability) -> bool {
339 self.allow.iter().any(|c| c.admits(cap)) && !self.deny.iter().any(|c| c.matches_as_deny(cap))
340 }
341
342 pub fn admits(&self, profile: &Profile) -> bool {
345 profile.capabilities.iter().all(|c| self.admits_capability(c))
346 }
347
348 #[must_use]
354 pub fn extend(base: &Level, name: impl Into<String>, extra_allow: Vec<Clause>) -> Level {
355 let mut allow = base.allow.clone();
356 allow.extend(extra_allow);
357 Level { name: name.into(), allow, deny: base.deny.clone() }
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364 use proptest::prelude::*;
365
366 fn cap(op: Operation) -> Capability {
367 Capability::new(op)
368 }
369
370 #[test]
371 fn empty_clause_admits_everything_empty_allow_admits_nothing() {
372 let all = Level::new("all").allowing(Clause::default());
373 let nothing = Level::new("nothing");
374 let destroy = Profile::of(vec![cap(Operation::Destroy)]);
375 assert!(all.admits(&destroy));
376 assert!(!nothing.admits(&destroy));
377 assert!(all.admits(&Profile::default()));
379 assert!(nothing.admits(&Profile::default()));
380 }
381
382 #[test]
388 fn nearest_miss_reports_the_clause_that_came_closest_not_the_first() {
389 let strict = Clause {
390 operation: Some(vec![Operation::Observe]),
391 local_locus: Some(OrdBound::at_most(LocalLocus::Temp)),
392 ..Default::default()
393 };
394 let loose = Clause {
395 operation: Some(vec![Operation::Observe]),
396 local_locus: Some(OrdBound::at_most(LocalLocus::WorktreeTrusted)),
397 ..Default::default()
398 };
399 let level = Level::new("two-reads").allowing(strict).allowing(loose);
401 let mut cap = Capability::new(Operation::Observe);
402 cap.locus.local = LocalLocus::Machine;
403
404 let m = level.nearest_miss(&cap).expect("machine locus exceeds both clauses");
405 assert_eq!(m.facet, "locus.local");
406 assert!(
407 m.bound.contains("worktree-trusted"),
408 "named the strictest clause (`{}`); the closest one allows <= worktree-trusted",
409 m.bound,
410 );
411 }
412
413 #[test]
414 fn read_local_admits_a_read_rejects_a_secret_and_a_destroy() {
415 let read_local = Level::new("read-local").allowing(Clause {
416 operation: Some(vec![Operation::Observe]),
417 local_locus: Some(OrdBound::at_most(LocalLocus::User)),
418 secret_level: Some(OrdBound::at_most(SecretLevel::UsesAmbient)),
419 net_direction: Some(OrdBound::at_most(NetDirection::Loopback)),
420 ..Default::default()
421 });
422
423 let plain_read = Profile::of(vec![{
424 let mut c = cap(Operation::Observe);
425 c.locus.local = LocalLocus::Worktree;
426 c
427 }]);
428 assert!(read_local.admits(&plain_read));
429
430 let secret_read = Profile::of(vec![{
431 let mut c = cap(Operation::Observe);
432 c.locus.local = LocalLocus::User;
433 c.secret.level = SecretLevel::Reads;
434 c
435 }]);
436 assert!(!read_local.admits(&secret_read), "cat ~/.ssh/id_rsa must not pass read-local");
437
438 let destroy = Profile::of(vec![cap(Operation::Destroy)]);
439 assert!(!read_local.admits(&destroy));
440 }
441
442 #[test]
443 fn yolo_deny_carves_out_the_catastrophe_corner() {
444 let yolo = Level::new("yolo").allowing(Clause::default()).denying(Clause {
445 operation: Some(vec![Operation::Destroy]),
446 reversibility: Some(OrdBound::at_least(Reversibility::Irreversible)),
447 scale: Some(OrdBound::at_least(Scale::Unbounded)),
448 ..Default::default()
449 });
450
451 let bounded = Profile::of(vec![{
453 let mut c = cap(Operation::Destroy);
454 c.scale = Scale::Bounded;
455 c.reversibility = Reversibility::Recoverable;
456 c
457 }]);
458 assert!(yolo.admits(&bounded));
459
460 let wipe = Profile::of(vec![{
462 let mut c = cap(Operation::Destroy);
463 c.scale = Scale::Unbounded;
464 c.reversibility = Reversibility::Irreversible;
465 c
466 }]);
467 assert!(!yolo.admits(&wipe));
468 }
469
470 #[test]
471 fn supply_chain_gates_network_sourced_code_and_is_vacuous_otherwise() {
472 let dev = Level::new("dev").allowing(Clause {
475 execution_trust: Some(OrdBound::at_most(ExecutionTrust::NetworkSourced)),
476 supply_source: Some(vec![
477 SupplySource::PublicRegistry,
478 SupplySource::SignedRepo,
479 SupplySource::PrivateRegistry,
480 SupplySource::Vendored,
481 ]),
482 ..Default::default()
483 });
484
485 let build = Profile::of(vec![{
487 let mut c = cap(Operation::Execute);
488 c.execution = Execution {
489 trust: ExecutionTrust::NetworkSourced,
490 supply_chain: Some(SupplyChain {
491 source: SupplySource::PublicRegistry,
492 pinning: Pinning::HashVerified,
493 exec_surface: ExecSurface::BuildScript,
494 }),
495 };
496 c
497 }]);
498 assert!(dev.admits(&build), "cargo build from a registry");
499
500 let curl_sh = Profile::of(vec![{
502 let mut c = cap(Operation::Execute);
503 c.execution = Execution {
504 trust: ExecutionTrust::NetworkSourced,
505 supply_chain: Some(SupplyChain {
506 source: SupplySource::UnverifiedUrl,
507 pinning: Pinning::Floating,
508 exec_surface: ExecSurface::RunArtifact,
509 }),
510 };
511 c
512 }]);
513 assert!(!dev.admits(&curl_sh), "curl | sh is an unverified-url source");
514
515 let plain = Profile::of(vec![cap(Operation::Observe)]);
517 assert!(dev.admits(&plain), "a command with no supply chain passes vacuously");
518 }
519
520 #[test]
521 fn a_supply_chain_deny_does_not_match_a_capability_without_one() {
522 let level = Level::new("x")
525 .allowing(Clause::default())
526 .denying(Clause { supply_source: Some(vec![SupplySource::UnverifiedUrl]), ..Default::default() });
527
528 let plain = Profile::of(vec![cap(Operation::Observe)]);
529 assert!(level.admits(&plain), "a supply-chain deny must not match a no-supply-chain cap");
530
531 let curl_sh = Profile::of(vec![{
533 let mut c = cap(Operation::Execute);
534 c.execution = Execution {
535 trust: ExecutionTrust::NetworkSourced,
536 supply_chain: Some(SupplyChain {
537 source: SupplySource::UnverifiedUrl,
538 pinning: Pinning::Floating,
539 exec_surface: ExecSurface::RunArtifact,
540 }),
541 };
542 c
543 }]);
544 assert!(!level.admits(&curl_sh), "the deny corner still catches the unverified-url source");
545 }
546
547 #[test]
548 fn extend_inherits_deny_and_adds_allow() {
549 let base = Level::new("base")
550 .allowing(Clause { operation: Some(vec![Operation::Observe]), ..Default::default() })
551 .denying(Clause { local_locus: Some(OrdBound::at_least(LocalLocus::Device)), ..Default::default() });
552 let child = Level::extend(
553 &base,
554 "child",
555 vec![Clause { operation: Some(vec![Operation::Create, Operation::Mutate]), ..Default::default() }],
556 );
557
558 assert!(child.admits(&Profile::of(vec![cap(Operation::Create)])), "added allow");
559 assert!(child.admits(&Profile::of(vec![cap(Operation::Observe)])), "inherited allow");
560
561 let device = Profile::of(vec![{
562 let mut c = cap(Operation::Mutate);
563 c.locus.local = LocalLocus::Device;
564 c
565 }]);
566 assert!(!child.admits(&device), "inherited deny still bites");
567 }
568
569 use crate::engine::testgen::{arb_clause, arb_level, arb_profile};
573
574 proptest! {
575 #[test]
578 fn totality(level in arb_level(), profile in arb_profile()) {
579 let first = level.admits(&profile);
580 prop_assert_eq!(first, level.admits(&profile));
581 }
582
583 #[test]
586 fn extends_is_a_superset(
587 base in arb_level(),
588 extra in prop::collection::vec(arb_clause(), 0..3),
589 profile in arb_profile(),
590 ) {
591 let extended = Level::extend(&base, "child", extra);
592 prop_assert!(!base.admits(&profile) || extended.admits(&profile));
593 }
594
595 #[test]
598 fn deny_only_shrinks(
599 level in arb_level(),
600 extra_deny in arb_clause(),
601 profile in arb_profile(),
602 ) {
603 let stricter = level.clone().denying(extra_deny);
604 prop_assert!(!stricter.admits(&profile) || level.admits(&profile));
605 }
606 }
607}