action_gate_core/lib.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Bartek Kus
3//
4// Relicensed from the Open Agentic Platform (crates/policy-kernel/lib.rs,
5// AGPL-3.0-or-later) to Apache-2.0 by the sole copyright holder. See NOTICE.
6
7//! `action-gate-core`: a pure, deterministic decision gate over an ordered
8//! [`Check`] registry.
9//!
10//! [`Gate::evaluate`] runs its checks in registration order and returns the
11//! first check's `Some(decision)`, or an unconditional [`Decision::allow`] if
12//! none triggers. It is a pure function of `(context, checks)`: no host calls,
13//! no clock, unit-testable, and byte-stable via [`decision_to_canonical_json`].
14//! Determinism depends on check ordering being stable, which the builder
15//! guarantees (insertion order).
16//!
17//! That is the default, [`Mode::Open`]. A gate built with
18//! [`GateBuilder::closed`] or [`GateBuilder::require`] evaluates in
19//! [`Mode::Closed`] instead: it denies when no check decides, and every
20//! required check must be registered and must decide. See [`Mode`] and the
21//! [`closed`] module for the rules and reason codes.
22//!
23//! # Config is in the checks, not a global bundle
24//!
25//! There is no global policy-bundle type here. Each check owns its parameters
26//! (a secrets check owns its regex set, an allowlist owns its list). The
27//! consumer assembles the gate:
28//!
29//! ```
30//! # #[cfg(feature = "checks-common")] {
31//! use action_gate_core::{Gate, checks::{AllowlistCheck, SecretsCheck}};
32//! use action_gate_types::ActionContext;
33//!
34//! let gate = Gate::builder()
35//! .check(SecretsCheck::default())
36//! .check(AllowlistCheck::new(["email.send", "email.draft"]))
37//! .build();
38//!
39//! let decision = gate.evaluate(&ActionContext::new("email.send"));
40//! assert!(decision.is_allow());
41//! # }
42//! ```
43//!
44//! # Degrade is a signal, not an action
45//!
46//! [`Outcome::Degrade`] does not perform a degraded action. The gate returns it;
47//! the consumer decides its meaning (route to a human, require confirmation).
48//! The gate never touches the world.
49
50pub use action_gate_types::{ActionContext, Check, Decision, Outcome};
51
52use std::collections::BTreeSet;
53
54use sha2::{Digest, Sha256};
55
56#[cfg(feature = "checks-common")]
57pub mod checks;
58
59pub mod secrets;
60
61/// How a [`Gate`] combines its checks' answers (spec 004).
62///
63/// The mode is part of [`Gate::config_hash`]: a closed gate never hashes the
64/// same as an open one, whatever its checks.
65#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
66#[non_exhaustive]
67pub enum Mode {
68 /// The 0.1.0 and 0.2.0 behaviour, and the default. Checks run in
69 /// registration order; the first `Some` wins, whatever its outcome; when
70 /// no check returns `Some`, the gate allows with
71 /// `gate:allow:no_check_triggered`.
72 #[default]
73 Open,
74 /// Deny by default, with required checks. Before any check runs, every
75 /// required id must name a registered check, or the gate denies with
76 /// [`closed::REQUIRED_UNREGISTERED`]. Checks then run in registration
77 /// order:
78 ///
79 /// - a `Deny` ends the evaluation and is the decision; later checks do
80 /// not run;
81 /// - a required check that returns `None` is a deny,
82 /// [`closed::REQUIRED_UNDECIDED`], and ends the evaluation the same way;
83 /// - an `Allow` or a `Degrade` does **not** end the evaluation, so a later
84 /// check can still deny.
85 ///
86 /// When every check has run without a deny, the decision is the first
87 /// `Degrade` if there was one, else an allow ([`closed::AFFIRMED`]) if at
88 /// least one check returned `Allow`, else a deny
89 /// ([`closed::NO_CHECK_DECIDED`]). Every deny the gate itself produces is
90 /// blocking; a check's own decision is returned unchanged.
91 Closed,
92}
93
94/// The stable reason codes a [`Mode::Closed`] gate produces itself (spec 004
95/// B-6). A check's own decision keeps the check's reason.
96pub mod closed {
97 /// No check returned `Some`. `check_ids` lists every check that ran, in
98 /// order (empty for a gate with no checks).
99 pub const NO_CHECK_DECIDED: &str = "gate:deny:closed:no_check_decided";
100 /// A required id names no registered check. `check_ids` lists every such
101 /// id, sorted; no check ran.
102 pub const REQUIRED_UNREGISTERED: &str = "gate:deny:closed:required_unregistered";
103 /// A required check ran and returned `None`. `check_ids` is that check's
104 /// id.
105 pub const REQUIRED_UNDECIDED: &str = "gate:deny:closed:required_undecided";
106 /// Every check ran; none denied or degraded, at least one allowed, and
107 /// any others abstained.
108 /// `check_ids` lists the checks that allowed, in order.
109 pub const AFFIRMED: &str = "gate:allow:closed:affirmed";
110}
111
112/// Everything [`Gate::evaluate_exhaustive`] found: the decision
113/// [`Gate::evaluate`] returns, and every deny along the way.
114#[derive(Clone, Debug, PartialEq, Eq)]
115#[non_exhaustive]
116pub struct Evaluation {
117 /// Equal to [`Gate::evaluate`] on the same context.
118 pub decision: Decision,
119 /// Every deny, in registration order: each check's own `Deny` and, in
120 /// [`Mode::Closed`], each deny the gate produced (an undecided required
121 /// check at its position, an unregistered requirement or the no-decision
122 /// deny alone). In closed mode the decision is a deny exactly when this is
123 /// non-empty, and is then its first element. In open mode an earlier
124 /// `Some` can decide before a listed deny is reached.
125 pub denials: Vec<Decision>,
126}
127
128/// A pure decision gate over an ordered list of checks.
129pub struct Gate {
130 checks: Vec<Box<dyn Check>>,
131 mode: Mode,
132 required: BTreeSet<String>,
133}
134
135impl Gate {
136 /// Start building a gate.
137 pub fn builder() -> GateBuilder {
138 GateBuilder::new()
139 }
140
141 /// Evaluate `ctx` against the checks in order, under the gate's [`Mode`].
142 ///
143 /// In [`Mode::Open`] (the default) the first check to return `Some` wins;
144 /// if none does, the gate allows. [`Mode::Closed`] is documented on the
145 /// variant.
146 pub fn evaluate(&self, ctx: &ActionContext) -> Decision {
147 match self.mode {
148 Mode::Open => {
149 for check in &self.checks {
150 if let Some(decision) = check.evaluate(ctx) {
151 return decision;
152 }
153 }
154 Decision::allow()
155 }
156 Mode::Closed => self.evaluate_closed(ctx, false).decision,
157 }
158 }
159
160 /// Evaluate `ctx` and also collect every deny (spec 004 B-8).
161 ///
162 /// Every check runs exactly once, including those after the deciding one, so a
163 /// consumer that reports all of its reasons can read them in registration
164 /// order. The decision is the one [`Gate::evaluate`] returns.
165 pub fn evaluate_exhaustive(&self, ctx: &ActionContext) -> Evaluation {
166 match self.mode {
167 Mode::Open => {
168 let mut decision = None;
169 let mut denials = Vec::new();
170 for check in &self.checks {
171 if let Some(d) = check.evaluate(ctx) {
172 if d.outcome == Outcome::Deny {
173 denials.push(d.clone());
174 }
175 decision.get_or_insert(d);
176 }
177 }
178 Evaluation {
179 decision: decision.unwrap_or_else(Decision::allow),
180 denials,
181 }
182 }
183 Mode::Closed => self.evaluate_closed(ctx, true),
184 }
185 }
186
187 /// The closed-mode rules of [`Mode::Closed`]. With `exhaustive`, a deny
188 /// does not stop the walk; the decision is the same either way.
189 fn evaluate_closed(&self, ctx: &ActionContext, exhaustive: bool) -> Evaluation {
190 let missing = self.unregistered_required();
191 if !missing.is_empty() {
192 let deny = Decision::deny(
193 closed::REQUIRED_UNREGISTERED,
194 missing.into_iter().map(String::from).collect(),
195 )
196 .blocking();
197 return Evaluation {
198 decision: deny.clone(),
199 denials: vec![deny],
200 };
201 }
202
203 let mut denials = Vec::new();
204 let mut degrade = None;
205 let mut allowed = Vec::new();
206 let mut ran = Vec::new();
207 for check in &self.checks {
208 let id = check.id();
209 ran.push(id.to_string());
210 match check.evaluate(ctx) {
211 Some(d) if d.outcome == Outcome::Deny => denials.push(d),
212 Some(d) if d.outcome == Outcome::Degrade => {
213 degrade.get_or_insert(d);
214 }
215 Some(_) => allowed.push(id.to_string()),
216 None if self.required.contains(id) => denials.push(
217 Decision::deny(closed::REQUIRED_UNDECIDED, vec![id.to_string()]).blocking(),
218 ),
219 None => {}
220 }
221 if !exhaustive && !denials.is_empty() {
222 break;
223 }
224 }
225
226 let decision = if let Some(first) = denials.first() {
227 first.clone()
228 } else if let Some(d) = degrade {
229 d
230 } else if !allowed.is_empty() {
231 Decision {
232 outcome: Outcome::Allow,
233 reason: closed::AFFIRMED.into(),
234 check_ids: allowed,
235 blocking: false,
236 }
237 } else {
238 let deny = Decision::deny(closed::NO_CHECK_DECIDED, ran).blocking();
239 denials.push(deny.clone());
240 deny
241 };
242 Evaluation { decision, denials }
243 }
244
245 /// The ids of the registered checks, in evaluation order.
246 pub fn check_ids(&self) -> Vec<&str> {
247 self.checks.iter().map(|c| c.id()).collect()
248 }
249
250 /// The gate's evaluation mode.
251 pub fn mode(&self) -> Mode {
252 self.mode
253 }
254
255 /// The required check ids, sorted. Empty for an open gate.
256 pub fn required_ids(&self) -> Vec<&str> {
257 self.required.iter().map(String::as_str).collect()
258 }
259
260 /// The required ids that name no registered check, sorted. A closed gate
261 /// with any denies every action ([`closed::REQUIRED_UNREGISTERED`]); a
262 /// consumer can call this at startup to refuse the configuration early.
263 pub fn unregistered_required(&self) -> Vec<&str> {
264 self.required
265 .iter()
266 .filter(|id| !self.checks.iter().any(|c| c.id() == id.as_str()))
267 .map(String::as_str)
268 .collect()
269 }
270
271 /// A stable `sha256:<hex>` hash of the gate's configuration.
272 ///
273 /// In [`Mode::Open`] it is taken over the canonical JSON array of each
274 /// check's [`config_fingerprint`](Check::config_fingerprint), in order,
275 /// exactly as in 0.1.0 and 0.2.0, so a recorded hash does not move. In
276 /// [`Mode::Closed`] it is taken over the canonical JSON object
277 /// `{"checks": [...], "mode": "closed", "required": [...]}` with the
278 /// required ids sorted. An object never serializes like an array, so a
279 /// closed gate never hashes the same as an open one.
280 ///
281 /// Record this in a ledger alongside a decision to prove the decision came
282 /// from exactly this gate configuration. Because it is order-sensitive and
283 /// folds in each check's parameters, a reordered or reconfigured gate hashes
284 /// differently.
285 pub fn config_hash(&self) -> String {
286 let fingerprints: Vec<String> =
287 self.checks.iter().map(|c| c.config_fingerprint()).collect();
288 let value = match self.mode {
289 Mode::Open => {
290 serde_json::to_value(&fingerprints).expect("fingerprints serialise to JSON")
291 }
292 Mode::Closed => serde_json::json!({
293 "checks": fingerprints,
294 "mode": "closed",
295 "required": self.required,
296 }),
297 };
298 sha256_hex(canonical_keysort_json::to_canonical_string(&value).as_bytes())
299 }
300}
301
302/// A terminal check that denies whatever reached it (spec 001 B-14).
303///
304/// The gate's published default is to allow when no check returns `Some`.
305/// Registering `DenyByDefault` last closes it instead: an action passes only if
306/// an earlier check returns `Some(Decision::allow())`. Checks registered after
307/// it never run. It is never added implicitly; see also
308/// [`GateBuilder::build_deny_by_default`].
309///
310/// It belongs to [`Mode::Open`]. A [`Mode::Closed`] gate does not stop at an
311/// allow, so this check would deny every action there; a closed gate denies
312/// undecided actions by itself.
313///
314/// The deny is blocking, so a trust layer downstream cannot reopen a gate its
315/// operator explicitly closed.
316///
317/// ```
318/// use action_gate_core::{ActionContext, Check, Decision, Gate};
319///
320/// struct AllowRead;
321/// impl Check for AllowRead {
322/// fn id(&self) -> &str { "allow-read" }
323/// fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
324/// (ctx.action == "read").then(Decision::allow)
325/// }
326/// }
327///
328/// let gate = Gate::builder().check(AllowRead).build_deny_by_default();
329/// assert!(gate.evaluate(&ActionContext::new("read")).is_allow());
330/// assert!(!gate.evaluate(&ActionContext::new("write")).is_allow());
331/// ```
332#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
333pub struct DenyByDefault;
334
335impl DenyByDefault {
336 /// The check id, as it appears in a decision's `check_ids`.
337 pub const ID: &'static str = "deny-by-default";
338 /// The reason of every decision this check returns.
339 pub const REASON: &'static str = "gate:deny:default:no_check_decided";
340}
341
342impl Check for DenyByDefault {
343 fn id(&self) -> &str {
344 Self::ID
345 }
346
347 fn evaluate(&self, _ctx: &ActionContext) -> Option<Decision> {
348 Some(Decision::deny(Self::REASON, vec![Self::ID.into()]).blocking())
349 }
350}
351
352/// Builds a [`Gate`] by registering checks in evaluation order.
353#[derive(Default)]
354pub struct GateBuilder {
355 checks: Vec<Box<dyn Check>>,
356 mode: Mode,
357 required: BTreeSet<String>,
358}
359
360impl GateBuilder {
361 /// A builder with no checks, in [`Mode::Open`].
362 pub fn new() -> Self {
363 Self::default()
364 }
365
366 /// Register a check. Checks evaluate in the order they are registered.
367 #[must_use]
368 pub fn check<C: Check + 'static>(mut self, check: C) -> Self {
369 self.checks.push(Box::new(check));
370 self
371 }
372
373 /// Register a pre-boxed check (for dynamically-assembled check sets).
374 #[must_use]
375 pub fn check_boxed(mut self, check: Box<dyn Check>) -> Self {
376 self.checks.push(check);
377 self
378 }
379
380 /// Evaluate in [`Mode::Closed`]: deny when no check decides.
381 ///
382 /// ```
383 /// use action_gate_core::{closed, ActionContext, Check, Decision, Gate};
384 ///
385 /// struct AllowRead;
386 /// impl Check for AllowRead {
387 /// fn id(&self) -> &str { "allow-read" }
388 /// fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
389 /// (ctx.action == "read").then(Decision::allow)
390 /// }
391 /// }
392 ///
393 /// let gate = Gate::builder().check(AllowRead).closed().build();
394 /// assert!(gate.evaluate(&ActionContext::new("read")).is_allow());
395 /// let d = gate.evaluate(&ActionContext::new("write"));
396 /// assert_eq!(d.reason, closed::NO_CHECK_DECIDED);
397 /// assert!(d.blocking);
398 /// ```
399 #[must_use]
400 pub fn closed(mut self) -> Self {
401 self.mode = Mode::Closed;
402 self
403 }
404
405 /// Require the check with `id`: it must be registered and must return
406 /// `Some` on every evaluation, or the gate denies. Requiring a check puts
407 /// the gate in [`Mode::Closed`]; there is no open gate with requirements.
408 /// The requirement may be stated before or after the check is registered.
409 ///
410 /// ```
411 /// use action_gate_core::{closed, ActionContext, Check, Decision, Gate};
412 ///
413 /// struct Scan;
414 /// impl Check for Scan {
415 /// fn id(&self) -> &str { "scan" }
416 /// fn evaluate(&self, _ctx: &ActionContext) -> Option<Decision> {
417 /// Some(Decision::allow())
418 /// }
419 /// }
420 ///
421 /// // Required but never registered: every action is denied.
422 /// let gate = Gate::builder().require("scan").build();
423 /// let d = gate.evaluate(&ActionContext::new("write"));
424 /// assert_eq!(d.reason, closed::REQUIRED_UNREGISTERED);
425 /// assert_eq!(d.check_ids, vec!["scan"]);
426 ///
427 /// let gate = Gate::builder().check(Scan).require("scan").build();
428 /// assert!(gate.evaluate(&ActionContext::new("write")).is_allow());
429 /// ```
430 #[must_use]
431 pub fn require(mut self, id: impl Into<String>) -> Self {
432 self.required.insert(id.into());
433 self.mode = Mode::Closed;
434 self
435 }
436
437 /// Require every id in `ids`; see [`require`](Self::require).
438 #[must_use]
439 pub fn require_all(self, ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
440 ids.into_iter().fold(self, |b, id| b.require(id))
441 }
442
443 /// Finish building.
444 pub fn build(self) -> Gate {
445 Gate {
446 checks: self.checks,
447 mode: self.mode,
448 required: self.required,
449 }
450 }
451
452 /// Register [`DenyByDefault`] as the terminal check and finish building:
453 /// the gate denies any action no earlier check decides. An open-mode
454 /// shorthand; see [`DenyByDefault`] on combining it with [`closed`](Self::closed).
455 pub fn build_deny_by_default(self) -> Gate {
456 self.check(DenyByDefault).build()
457 }
458}
459
460/// Serialize a decision to canonical (key-sorted) JSON, for byte-stable hashing
461/// and comparison. Two producers serializing the same logical decision produce
462/// the same bytes regardless of `serde_json`'s `preserve_order` state.
463pub fn decision_to_canonical_json(decision: &Decision) -> String {
464 canonical_keysort_json::to_canonical_string(
465 &serde_json::to_value(decision).expect("decision serialises to JSON"),
466 )
467}
468
469/// `sha256:<hex>` over `bytes`. The `sha256:` prefix keeps the hash
470/// self-describing, matching the ledger primitive in `attest-ledger`.
471pub fn sha256_hex(bytes: &[u8]) -> String {
472 let mut hasher = Sha256::new();
473 hasher.update(bytes);
474 format!("sha256:{}", hex::encode(hasher.finalize()))
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480
481 struct DenyOn {
482 id: String,
483 action: String,
484 }
485 impl Check for DenyOn {
486 fn id(&self) -> &str {
487 &self.id
488 }
489 fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
490 if ctx.action == self.action {
491 Some(Decision::deny(
492 format!("gate:deny:{}", self.id),
493 vec![self.id.clone()],
494 ))
495 } else {
496 None
497 }
498 }
499 }
500
501 fn deny_on(id: &str, action: &str) -> DenyOn {
502 DenyOn {
503 id: id.into(),
504 action: action.into(),
505 }
506 }
507
508 #[test]
509 fn empty_gate_allows() {
510 let gate = Gate::builder().build();
511 assert!(gate.evaluate(&ActionContext::new("anything")).is_allow());
512 }
513
514 #[test]
515 fn first_matching_check_wins() {
516 let gate = Gate::builder()
517 .check(deny_on("a", "x"))
518 .check(deny_on("b", "x"))
519 .build();
520 let d = gate.evaluate(&ActionContext::new("x"));
521 assert_eq!(d.outcome, Outcome::Deny);
522 assert_eq!(d.check_ids, vec!["a"], "first check short-circuits");
523 }
524
525 #[test]
526 fn non_matching_checks_pass_through_to_allow() {
527 let gate = Gate::builder()
528 .check(deny_on("a", "x"))
529 .check(deny_on("b", "y"))
530 .build();
531 assert!(gate.evaluate(&ActionContext::new("z")).is_allow());
532 }
533
534 struct AllowOn(&'static str);
535 impl Check for AllowOn {
536 fn id(&self) -> &str {
537 "allow-on"
538 }
539 fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
540 (ctx.action == self.0).then(Decision::allow)
541 }
542 }
543
544 #[test]
545 fn deny_by_default_closes_the_gate() {
546 let gate = Gate::builder()
547 .check(deny_on("a", "x"))
548 .check(AllowOn("read"))
549 .build_deny_by_default();
550 assert!(gate.evaluate(&ActionContext::new("read")).is_allow());
551 let d = gate.evaluate(&ActionContext::new("z"));
552 assert_eq!(d.outcome, Outcome::Deny);
553 assert_eq!(d.reason, DenyByDefault::REASON);
554 assert_eq!(d.check_ids, vec!["deny-by-default"]);
555 assert!(d.blocking);
556 assert_eq!(gate.evaluate(&ActionContext::new("x")).check_ids, vec!["a"]);
557 assert_eq!(gate.check_ids(), vec!["a", "allow-on", "deny-by-default"]);
558 }
559
560 #[test]
561 fn config_hash_is_stable_and_order_sensitive() {
562 let g1 = Gate::builder()
563 .check(deny_on("a", "x"))
564 .check(deny_on("b", "y"))
565 .build();
566 let g2 = Gate::builder()
567 .check(deny_on("a", "x"))
568 .check(deny_on("b", "y"))
569 .build();
570 assert_eq!(g1.config_hash(), g2.config_hash(), "same config, same hash");
571 assert!(g1.config_hash().starts_with("sha256:"));
572
573 let reordered = Gate::builder()
574 .check(deny_on("b", "y"))
575 .check(deny_on("a", "x"))
576 .build();
577 assert_ne!(
578 g1.config_hash(),
579 reordered.config_hash(),
580 "order changes the hash"
581 );
582 }
583
584 #[test]
585 fn decision_canonical_json_is_byte_stable() {
586 let d = Decision::deny("gate:deny:x", vec!["x".into()]).blocking();
587 assert_eq!(
588 decision_to_canonical_json(&d),
589 decision_to_canonical_json(&d.clone())
590 );
591 // Keys are sorted regardless of struct field order.
592 assert!(decision_to_canonical_json(&d).starts_with("{\"blocking\":true"));
593 }
594}