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        let mut denied: Option<Decision> = None;
158
159        for entry in &self.entries {
160            if !entry.config.enabled {
161                chain.push(chain_entry(
162                    &entry.config,
163                    ChainEntryResult::Disabled,
164                    "Policy disabled in governance config",
165                ));
166                continue;
167            }
168            if denied.is_some() {
169                chain.push(chain_entry(
170                    &entry.config,
171                    ChainEntryResult::Skip,
172                    "Skipped — already denied by an earlier policy",
173                ));
174                continue;
175            }
176            let started = std::time::Instant::now();
177            let decision = entry.instance.evaluate(ctx);
178            let duration_ms = started.elapsed().as_secs_f64() * 1000.0;
179            match &decision {
180                Decision::Allow { matched_by } => chain.push(ChainEntryOutcome {
181                    policy_id: entry.instance.id(),
182                    result: ChainEntryResult::Pass,
183                    detail: allow_detail(matched_by),
184                    duration_ms,
185                }),
186                Decision::Deny { reason } => {
187                    chain.push(ChainEntryOutcome {
188                        policy_id: entry.instance.id(),
189                        result: ChainEntryResult::Fail,
190                        detail: reason.to_string(),
191                        duration_ms,
192                    });
193                    denied = Some(decision);
194                },
195            }
196        }
197
198        Evaluation {
199            decision: denied.unwrap_or(Decision::Allow {
200                matched_by: MatchedBy::DefaultIncluded,
201            }),
202            chain,
203        }
204    }
205}
206
207fn governance_config_path() -> Option<PathBuf> {
208    let profile = ProfileBootstrap::get()
209        .inspect_err(|e| {
210            tracing::error!(
211                error = %e,
212                "governance profile bootstrap failed; policies fall back to built-in defaults"
213            );
214        })
215        .ok()?;
216    Some(PathBuf::from(&profile.paths.services).join("governance/config.yaml"))
217}
218
219fn chain_entry(cfg: &PolicyConfig, result: ChainEntryResult, detail: &str) -> ChainEntryOutcome {
220    ChainEntryOutcome {
221        policy_id: PolicyId::new(cfg.id.clone()),
222        result,
223        detail: detail.to_owned(),
224        duration_ms: 0.0,
225    }
226}
227
228fn allow_detail(matched_by: &MatchedBy) -> String {
229    match matched_by {
230        MatchedBy::PolicyAllow { detail, .. } => detail.to_string(),
231        MatchedBy::UserAllow => "user allow".to_owned(),
232        MatchedBy::RoleAllow { role } => format!("role allow: {role}"),
233        MatchedBy::AttributeAllow { rule_type, value } => format!("{rule_type} allow: {value}"),
234        MatchedBy::DefaultIncluded => "default included".to_owned(),
235    }
236}