Skip to main content

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
51/// A pure decision gate over an ordered list of checks.
52pub struct Gate {
53    checks: Vec<Box<dyn Check>>,
54}
55
56impl Gate {
57    /// Start building a gate.
58    pub fn builder() -> GateBuilder {
59        GateBuilder::new()
60    }
61
62    /// Evaluate `ctx` against the checks in order. The first check to return
63    /// `Some` wins; if none does, the gate allows.
64    pub fn evaluate(&self, ctx: &ActionContext) -> Decision {
65        for check in &self.checks {
66            if let Some(decision) = check.evaluate(ctx) {
67                return decision;
68            }
69        }
70        Decision::allow()
71    }
72
73    /// The ids of the registered checks, in evaluation order.
74    pub fn check_ids(&self) -> Vec<&str> {
75        self.checks.iter().map(|c| c.id()).collect()
76    }
77
78    /// A stable `sha256:<hex>` hash of the gate's configuration: the ordered
79    /// list of each check's [`config_fingerprint`](Check::config_fingerprint).
80    ///
81    /// Record this in a ledger alongside a decision to prove the decision came
82    /// from exactly this gate configuration. Because it is order-sensitive and
83    /// folds in each check's parameters, a reordered or reconfigured gate hashes
84    /// differently.
85    pub fn config_hash(&self) -> String {
86        let fingerprints: Vec<String> =
87            self.checks.iter().map(|c| c.config_fingerprint()).collect();
88        let value = serde_json::to_value(&fingerprints).expect("fingerprints serialise to JSON");
89        sha256_hex(canonical_keysort_json::to_canonical_string(&value).as_bytes())
90    }
91}
92
93/// Builds a [`Gate`] by registering checks in evaluation order.
94#[derive(Default)]
95pub struct GateBuilder {
96    checks: Vec<Box<dyn Check>>,
97}
98
99impl GateBuilder {
100    /// A builder with no checks.
101    pub fn new() -> Self {
102        Self { checks: Vec::new() }
103    }
104
105    /// Register a check. Checks evaluate in the order they are registered.
106    #[must_use]
107    pub fn check<C: Check + 'static>(mut self, check: C) -> Self {
108        self.checks.push(Box::new(check));
109        self
110    }
111
112    /// Register a pre-boxed check (for dynamically-assembled check sets).
113    #[must_use]
114    pub fn check_boxed(mut self, check: Box<dyn Check>) -> Self {
115        self.checks.push(check);
116        self
117    }
118
119    /// Finish building.
120    pub fn build(self) -> Gate {
121        Gate {
122            checks: self.checks,
123        }
124    }
125}
126
127/// Serialize a decision to canonical (key-sorted) JSON, for byte-stable hashing
128/// and comparison. Two producers serializing the same logical decision produce
129/// the same bytes regardless of `serde_json`'s `preserve_order` state.
130pub fn decision_to_canonical_json(decision: &Decision) -> String {
131    canonical_keysort_json::to_canonical_string(
132        &serde_json::to_value(decision).expect("decision serialises to JSON"),
133    )
134}
135
136/// `sha256:<hex>` over `bytes`. The `sha256:` prefix keeps the hash
137/// self-describing, matching the ledger primitive in `attest-ledger`.
138pub fn sha256_hex(bytes: &[u8]) -> String {
139    let mut hasher = Sha256::new();
140    hasher.update(bytes);
141    format!("sha256:{}", hex::encode(hasher.finalize()))
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    struct DenyOn {
149        id: String,
150        action: String,
151    }
152    impl Check for DenyOn {
153        fn id(&self) -> &str {
154            &self.id
155        }
156        fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
157            if ctx.action == self.action {
158                Some(Decision::deny(
159                    format!("gate:deny:{}", self.id),
160                    vec![self.id.clone()],
161                ))
162            } else {
163                None
164            }
165        }
166    }
167
168    fn deny_on(id: &str, action: &str) -> DenyOn {
169        DenyOn {
170            id: id.into(),
171            action: action.into(),
172        }
173    }
174
175    #[test]
176    fn empty_gate_allows() {
177        let gate = Gate::builder().build();
178        assert!(gate.evaluate(&ActionContext::new("anything")).is_allow());
179    }
180
181    #[test]
182    fn first_matching_check_wins() {
183        let gate = Gate::builder()
184            .check(deny_on("a", "x"))
185            .check(deny_on("b", "x"))
186            .build();
187        let d = gate.evaluate(&ActionContext::new("x"));
188        assert_eq!(d.outcome, Outcome::Deny);
189        assert_eq!(d.check_ids, vec!["a"], "first check short-circuits");
190    }
191
192    #[test]
193    fn non_matching_checks_pass_through_to_allow() {
194        let gate = Gate::builder()
195            .check(deny_on("a", "x"))
196            .check(deny_on("b", "y"))
197            .build();
198        assert!(gate.evaluate(&ActionContext::new("z")).is_allow());
199    }
200
201    #[test]
202    fn config_hash_is_stable_and_order_sensitive() {
203        let g1 = Gate::builder()
204            .check(deny_on("a", "x"))
205            .check(deny_on("b", "y"))
206            .build();
207        let g2 = Gate::builder()
208            .check(deny_on("a", "x"))
209            .check(deny_on("b", "y"))
210            .build();
211        assert_eq!(g1.config_hash(), g2.config_hash(), "same config, same hash");
212        assert!(g1.config_hash().starts_with("sha256:"));
213
214        let reordered = Gate::builder()
215            .check(deny_on("b", "y"))
216            .check(deny_on("a", "x"))
217            .build();
218        assert_ne!(
219            g1.config_hash(),
220            reordered.config_hash(),
221            "order changes the hash"
222        );
223    }
224
225    #[test]
226    fn decision_canonical_json_is_byte_stable() {
227        let d = Decision::deny("gate:deny:x", vec!["x".into()]).blocking();
228        assert_eq!(
229            decision_to_canonical_json(&d),
230            decision_to_canonical_json(&d.clone())
231        );
232        // Keys are sorted regardless of struct field order.
233        assert!(decision_to_canonical_json(&d).starts_with("{\"blocking\":true"));
234    }
235}