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//! # Config is in the checks, not a global bundle
18//!
19//! There is no global policy-bundle type here. Each check owns its parameters
20//! (a secrets check owns its regex set, an allowlist owns its list). The
21//! consumer assembles the gate:
22//!
23//! ```
24//! # #[cfg(feature = "checks-common")] {
25//! use action_gate_core::{Gate, checks::{AllowlistCheck, SecretsCheck}};
26//! use action_gate_types::ActionContext;
27//!
28//! let gate = Gate::builder()
29//! .check(SecretsCheck::default())
30//! .check(AllowlistCheck::new(["email.send", "email.draft"]))
31//! .build();
32//!
33//! let decision = gate.evaluate(&ActionContext::new("email.send"));
34//! assert!(decision.is_allow());
35//! # }
36//! ```
37//!
38//! # Degrade is a signal, not an action
39//!
40//! [`Outcome::Degrade`] does not perform a degraded action. The gate returns it;
41//! the consumer decides its meaning (route to a human, require confirmation).
42//! The gate never touches the world.
43
44pub use action_gate_types::{ActionContext, Check, Decision, Outcome};
45
46use sha2::{Digest, Sha256};
47
48#[cfg(feature = "checks-common")]
49pub mod checks;
50
51pub mod secrets;
52
53/// A pure decision gate over an ordered list of checks.
54pub struct Gate {
55 checks: Vec<Box<dyn Check>>,
56}
57
58impl Gate {
59 /// Start building a gate.
60 pub fn builder() -> GateBuilder {
61 GateBuilder::new()
62 }
63
64 /// Evaluate `ctx` against the checks in order. The first check to return
65 /// `Some` wins; if none does, the gate allows.
66 pub fn evaluate(&self, ctx: &ActionContext) -> Decision {
67 for check in &self.checks {
68 if let Some(decision) = check.evaluate(ctx) {
69 return decision;
70 }
71 }
72 Decision::allow()
73 }
74
75 /// The ids of the registered checks, in evaluation order.
76 pub fn check_ids(&self) -> Vec<&str> {
77 self.checks.iter().map(|c| c.id()).collect()
78 }
79
80 /// A stable `sha256:<hex>` hash of the gate's configuration: the ordered
81 /// list of each check's [`config_fingerprint`](Check::config_fingerprint).
82 ///
83 /// Record this in a ledger alongside a decision to prove the decision came
84 /// from exactly this gate configuration. Because it is order-sensitive and
85 /// folds in each check's parameters, a reordered or reconfigured gate hashes
86 /// differently.
87 pub fn config_hash(&self) -> String {
88 let fingerprints: Vec<String> =
89 self.checks.iter().map(|c| c.config_fingerprint()).collect();
90 let value = serde_json::to_value(&fingerprints).expect("fingerprints serialise to JSON");
91 sha256_hex(canonical_keysort_json::to_canonical_string(&value).as_bytes())
92 }
93}
94
95/// A terminal check that denies whatever reached it (spec 001 B-14).
96///
97/// The gate's published default is to allow when no check returns `Some`.
98/// Registering `DenyByDefault` last closes it instead: an action passes only if
99/// an earlier check returns `Some(Decision::allow())`. Checks registered after
100/// it never run. It is never added implicitly; see also
101/// [`GateBuilder::build_deny_by_default`].
102///
103/// The deny is blocking, so a trust layer downstream cannot reopen a gate its
104/// operator explicitly closed.
105///
106/// ```
107/// use action_gate_core::{ActionContext, Check, Decision, Gate};
108///
109/// struct AllowRead;
110/// impl Check for AllowRead {
111/// fn id(&self) -> &str { "allow-read" }
112/// fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
113/// (ctx.action == "read").then(Decision::allow)
114/// }
115/// }
116///
117/// let gate = Gate::builder().check(AllowRead).build_deny_by_default();
118/// assert!(gate.evaluate(&ActionContext::new("read")).is_allow());
119/// assert!(!gate.evaluate(&ActionContext::new("write")).is_allow());
120/// ```
121#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
122pub struct DenyByDefault;
123
124impl DenyByDefault {
125 /// The check id, as it appears in a decision's `check_ids`.
126 pub const ID: &'static str = "deny-by-default";
127 /// The reason of every decision this check returns.
128 pub const REASON: &'static str = "gate:deny:default:no_check_decided";
129}
130
131impl Check for DenyByDefault {
132 fn id(&self) -> &str {
133 Self::ID
134 }
135
136 fn evaluate(&self, _ctx: &ActionContext) -> Option<Decision> {
137 Some(Decision::deny(Self::REASON, vec![Self::ID.into()]).blocking())
138 }
139}
140
141/// Builds a [`Gate`] by registering checks in evaluation order.
142#[derive(Default)]
143pub struct GateBuilder {
144 checks: Vec<Box<dyn Check>>,
145}
146
147impl GateBuilder {
148 /// A builder with no checks.
149 pub fn new() -> Self {
150 Self { checks: Vec::new() }
151 }
152
153 /// Register a check. Checks evaluate in the order they are registered.
154 #[must_use]
155 pub fn check<C: Check + 'static>(mut self, check: C) -> Self {
156 self.checks.push(Box::new(check));
157 self
158 }
159
160 /// Register a pre-boxed check (for dynamically-assembled check sets).
161 #[must_use]
162 pub fn check_boxed(mut self, check: Box<dyn Check>) -> Self {
163 self.checks.push(check);
164 self
165 }
166
167 /// Finish building.
168 pub fn build(self) -> Gate {
169 Gate {
170 checks: self.checks,
171 }
172 }
173
174 /// Register [`DenyByDefault`] as the terminal check and finish building:
175 /// the gate denies any action no earlier check decides.
176 pub fn build_deny_by_default(self) -> Gate {
177 self.check(DenyByDefault).build()
178 }
179}
180
181/// Serialize a decision to canonical (key-sorted) JSON, for byte-stable hashing
182/// and comparison. Two producers serializing the same logical decision produce
183/// the same bytes regardless of `serde_json`'s `preserve_order` state.
184pub fn decision_to_canonical_json(decision: &Decision) -> String {
185 canonical_keysort_json::to_canonical_string(
186 &serde_json::to_value(decision).expect("decision serialises to JSON"),
187 )
188}
189
190/// `sha256:<hex>` over `bytes`. The `sha256:` prefix keeps the hash
191/// self-describing, matching the ledger primitive in `attest-ledger`.
192pub fn sha256_hex(bytes: &[u8]) -> String {
193 let mut hasher = Sha256::new();
194 hasher.update(bytes);
195 format!("sha256:{}", hex::encode(hasher.finalize()))
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201
202 struct DenyOn {
203 id: String,
204 action: String,
205 }
206 impl Check for DenyOn {
207 fn id(&self) -> &str {
208 &self.id
209 }
210 fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
211 if ctx.action == self.action {
212 Some(Decision::deny(
213 format!("gate:deny:{}", self.id),
214 vec![self.id.clone()],
215 ))
216 } else {
217 None
218 }
219 }
220 }
221
222 fn deny_on(id: &str, action: &str) -> DenyOn {
223 DenyOn {
224 id: id.into(),
225 action: action.into(),
226 }
227 }
228
229 #[test]
230 fn empty_gate_allows() {
231 let gate = Gate::builder().build();
232 assert!(gate.evaluate(&ActionContext::new("anything")).is_allow());
233 }
234
235 #[test]
236 fn first_matching_check_wins() {
237 let gate = Gate::builder()
238 .check(deny_on("a", "x"))
239 .check(deny_on("b", "x"))
240 .build();
241 let d = gate.evaluate(&ActionContext::new("x"));
242 assert_eq!(d.outcome, Outcome::Deny);
243 assert_eq!(d.check_ids, vec!["a"], "first check short-circuits");
244 }
245
246 #[test]
247 fn non_matching_checks_pass_through_to_allow() {
248 let gate = Gate::builder()
249 .check(deny_on("a", "x"))
250 .check(deny_on("b", "y"))
251 .build();
252 assert!(gate.evaluate(&ActionContext::new("z")).is_allow());
253 }
254
255 struct AllowOn(&'static str);
256 impl Check for AllowOn {
257 fn id(&self) -> &str {
258 "allow-on"
259 }
260 fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
261 (ctx.action == self.0).then(Decision::allow)
262 }
263 }
264
265 #[test]
266 fn deny_by_default_closes_the_gate() {
267 let gate = Gate::builder()
268 .check(deny_on("a", "x"))
269 .check(AllowOn("read"))
270 .build_deny_by_default();
271 assert!(gate.evaluate(&ActionContext::new("read")).is_allow());
272 let d = gate.evaluate(&ActionContext::new("z"));
273 assert_eq!(d.outcome, Outcome::Deny);
274 assert_eq!(d.reason, DenyByDefault::REASON);
275 assert_eq!(d.check_ids, vec!["deny-by-default"]);
276 assert!(d.blocking);
277 assert_eq!(gate.evaluate(&ActionContext::new("x")).check_ids, vec!["a"]);
278 assert_eq!(gate.check_ids(), vec!["a", "allow-on", "deny-by-default"]);
279 }
280
281 #[test]
282 fn config_hash_is_stable_and_order_sensitive() {
283 let g1 = Gate::builder()
284 .check(deny_on("a", "x"))
285 .check(deny_on("b", "y"))
286 .build();
287 let g2 = Gate::builder()
288 .check(deny_on("a", "x"))
289 .check(deny_on("b", "y"))
290 .build();
291 assert_eq!(g1.config_hash(), g2.config_hash(), "same config, same hash");
292 assert!(g1.config_hash().starts_with("sha256:"));
293
294 let reordered = Gate::builder()
295 .check(deny_on("b", "y"))
296 .check(deny_on("a", "x"))
297 .build();
298 assert_ne!(
299 g1.config_hash(),
300 reordered.config_hash(),
301 "order changes the hash"
302 );
303 }
304
305 #[test]
306 fn decision_canonical_json_is_byte_stable() {
307 let d = Decision::deny("gate:deny:x", vec!["x".into()]).blocking();
308 assert_eq!(
309 decision_to_canonical_json(&d),
310 decision_to_canonical_json(&d.clone())
311 );
312 // Keys are sorted regardless of struct field order.
313 assert!(decision_to_canonical_json(&d).starts_with("{\"blocking\":true"));
314 }
315}