Skip to main content

systemprompt_security/policy/
engine.rs

1//! Traced first-deny-wins evaluation of the configured policy chain.
2//!
3//! [`GovernanceEngine`] owns the instantiated chain: policies resolved from
4//! the inventory registry against a [`GovernanceConfig`], in declaration
5//! order. [`GovernanceEngine::evaluate`] records a per-entry
6//! [`ChainEntryOutcome`] — including disabled and skipped-after-deny entries —
7//! so the audit row preserves the full evaluation order, not just the first
8//! deny.
9//!
10//! Policies that accumulate state (the rate limiter) scope it to their
11//! instance, so two engines never share buckets — a second engine would
12//! silently double every budget. [`GovernanceEngine::global`] is therefore the
13//! way every enforcement point in a process reaches the chain: the MCP
14//! governance webhook and the `/v1/messages` gateway must charge the same
15//! limiter, not one each. [`GovernanceEngine::from_config`] remains available
16//! for tests and for callers that genuinely want an isolated chain.
17//!
18//! Copyright (c) systemprompt.io — Business Source License 1.1.
19//! See <https://systemprompt.io> for licensing details.
20
21use std::collections::{HashMap, HashSet};
22use std::path::PathBuf;
23use std::sync::LazyLock;
24
25use systemprompt_config::ProfileBootstrap;
26use systemprompt_identifiers::PolicyId;
27
28use super::audit::{ChainEntryOutcome, ChainEntryResult};
29use super::config::{GovernanceConfig, PolicyConfig};
30use super::registry::{PolicyFactory, PolicyRegistration};
31use super::types::{GovernancePolicy, PolicyContext};
32use crate::authz::types::{Decision, MatchedBy};
33
34/// The outcome of one traced chain run: the first-deny-wins [`Decision`] and
35/// the ordered per-entry trace destined for the audit row.
36#[derive(Debug)]
37pub struct Evaluation {
38    pub decision: Decision,
39    pub chain: Vec<ChainEntryOutcome>,
40}
41
42struct ChainEntry {
43    config: PolicyConfig,
44    instance: Box<dyn GovernancePolicy>,
45}
46
47pub struct GovernanceEngine {
48    enabled: bool,
49    entries: Vec<ChainEntry>,
50}
51
52impl std::fmt::Debug for GovernanceEngine {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("GovernanceEngine")
55            .field("enabled", &self.enabled)
56            .field(
57                "policies",
58                &self
59                    .entries
60                    .iter()
61                    .map(|e| e.config.id.as_str())
62                    .collect::<Vec<_>>(),
63            )
64            .finish()
65    }
66}
67
68impl GovernanceEngine {
69    pub fn global() -> &'static Self {
70        static ENGINE: LazyLock<GovernanceEngine> = LazyLock::new(|| {
71            let config = governance_config_path()
72                .map_or_else(GovernanceConfig::defaults, |p| GovernanceConfig::load(&p));
73            GovernanceEngine::from_config(&config)
74        });
75        &ENGINE
76    }
77
78    #[must_use]
79    pub fn from_config(config: &GovernanceConfig) -> Self {
80        if !config.enabled {
81            tracing::warn!(
82                "governance is DISABLED by config: no scope, secret, blocklist or rate-limit \
83                 check will run on any request"
84            );
85        }
86        let factories: HashMap<&'static str, PolicyFactory> =
87            inventory::iter::<PolicyRegistration>()
88                .map(|r| (r.id, r.factory))
89                .collect();
90
91        let mut entries = Vec::with_capacity(config.policies.len());
92        for cfg in &config.policies {
93            let Some(factory) = factories.get(cfg.id.as_str()) else {
94                tracing::warn!(
95                    policy = %cfg.id,
96                    "governance policy in config has no registered impl — skipping"
97                );
98                continue;
99            };
100            entries.push(ChainEntry {
101                config: cfg.clone(),
102                instance: factory(&cfg.params),
103            });
104        }
105
106        let mentioned: HashSet<&str> = entries.iter().map(|e| e.config.id.as_str()).collect();
107        let unmentioned: Vec<&PolicyRegistration> = inventory::iter::<PolicyRegistration>()
108            .filter(|r| !mentioned.contains(r.id))
109            .collect();
110        for r in unmentioned {
111            let cfg = PolicyConfig {
112                id: r.id.to_owned(),
113                enabled: false,
114                params: serde_yaml::Value::Null,
115            };
116            let instance = (r.factory)(&cfg.params);
117            entries.push(ChainEntry {
118                config: cfg,
119                instance,
120            });
121        }
122
123        Self {
124            enabled: config.enabled,
125            entries,
126        }
127    }
128
129    pub fn policies(&self) -> impl Iterator<Item = (&PolicyConfig, &dyn GovernancePolicy)> {
130        self.entries
131            .iter()
132            .map(|e| (&e.config, e.instance.as_ref()))
133    }
134
135    #[must_use]
136    pub fn evaluate(&self, ctx: &PolicyContext<'_>) -> Evaluation {
137        if !self.enabled {
138            return Evaluation {
139                decision: Decision::Allow {
140                    matched_by: MatchedBy::DefaultIncluded,
141                },
142                chain: self
143                    .entries
144                    .iter()
145                    .map(|entry| {
146                        chain_entry(
147                            &entry.config,
148                            ChainEntryResult::Disabled,
149                            "Governance disabled by master switch",
150                        )
151                    })
152                    .collect(),
153            };
154        }
155
156        let mut chain: Vec<ChainEntryOutcome> = Vec::with_capacity(self.entries.len());
157        // Why: `Pending` halts the chain for the same reason `Deny` does — a
158        // later policy cannot un-hold a call, and running it would charge the
159        // rate limiter for a call that has not been authorised yet.
160        let mut halted: Option<Decision> = None;
161
162        for entry in &self.entries {
163            if !entry.config.enabled {
164                chain.push(chain_entry(
165                    &entry.config,
166                    ChainEntryResult::Disabled,
167                    "Policy disabled in governance config",
168                ));
169                continue;
170            }
171            if halted.is_some() {
172                chain.push(chain_entry(
173                    &entry.config,
174                    ChainEntryResult::Skip,
175                    "Skipped — already halted by an earlier policy",
176                ));
177                continue;
178            }
179            let started = std::time::Instant::now();
180            let decision = entry.instance.evaluate(ctx);
181            let duration_ms = started.elapsed().as_secs_f64() * 1000.0;
182            match &decision {
183                Decision::Allow { matched_by } => chain.push(ChainEntryOutcome {
184                    policy_id: entry.instance.id(),
185                    result: ChainEntryResult::Pass,
186                    detail: allow_detail(matched_by),
187                    duration_ms,
188                }),
189                Decision::Deny { reason } => {
190                    chain.push(ChainEntryOutcome {
191                        policy_id: entry.instance.id(),
192                        result: ChainEntryResult::Fail,
193                        detail: reason.to_string(),
194                        duration_ms,
195                    });
196                    halted = Some(decision);
197                },
198                Decision::Pending { reason } => {
199                    chain.push(ChainEntryOutcome {
200                        policy_id: entry.instance.id(),
201                        result: ChainEntryResult::Hold,
202                        detail: reason.to_string(),
203                        duration_ms,
204                    });
205                    halted = Some(decision);
206                },
207            }
208        }
209
210        Evaluation {
211            decision: halted.unwrap_or(Decision::Allow {
212                matched_by: MatchedBy::DefaultIncluded,
213            }),
214            chain,
215        }
216    }
217}
218
219fn governance_config_path() -> Option<PathBuf> {
220    let profile = ProfileBootstrap::get()
221        .inspect_err(|e| {
222            tracing::error!(
223                error = %e,
224                "governance profile bootstrap failed; policies fall back to built-in defaults"
225            );
226        })
227        .ok()?;
228    Some(PathBuf::from(&profile.paths.services).join("governance/config.yaml"))
229}
230
231fn chain_entry(cfg: &PolicyConfig, result: ChainEntryResult, detail: &str) -> ChainEntryOutcome {
232    ChainEntryOutcome {
233        policy_id: PolicyId::new(cfg.id.clone()),
234        result,
235        detail: detail.to_owned(),
236        duration_ms: 0.0,
237    }
238}
239
240fn allow_detail(matched_by: &MatchedBy) -> String {
241    match matched_by {
242        MatchedBy::PolicyAllow { detail, .. } => detail.to_string(),
243        MatchedBy::UserAllow => "user allow".to_owned(),
244        MatchedBy::RoleAllow { role } => format!("role allow: {role}"),
245        MatchedBy::AttributeAllow { rule_type, value } => format!("{rule_type} allow: {value}"),
246        MatchedBy::DefaultIncluded => "default included".to_owned(),
247    }
248}