Skip to main content

systemprompt_security/authz/
rule_based.rs

1//! Core `AuthzDecisionHook` wrapping the in-process [`super::resolver`].
2//!
3//! `RuleBasedHook` is the canonical RBAC layer: it loads
4//! `access_control_rules` for the request's entity, resolves them through the
5//! entity's plugin and marketplace parent chain, and emits an
6//! `AuthzDecision`. The chain's membership is supplied at construction,
7//! because this crate cannot load the services configuration itself, and is
8//! fixed for the process lifetime; the loaded chain index is held in a
9//! [`ChainIndexCache`] and revalidated against a table fingerprint. Exposed as
10//! a hook so extensions can compose it explicitly with their own ABAC
11//! predicates via [`super::CompositeAuthzHook`]:
12//!
13//! ```ignore
14//! let composite = CompositeAuthzHook::new(vec![
15//!     Arc::new(RuleBasedHook::new(pool.clone(), sink.clone())),
16//!     Arc::new(MyAbacHook::new(...)),
17//! ]);
18//! ```
19//!
20//! Put `RuleBasedHook` first so a coarse-grained RBAC reject short-circuits
21//! the chain before any per-attribute lookup runs.
22//!
23//! Copyright (c) systemprompt.io — Business Source License 1.1.
24//! See <https://systemprompt.io> for licensing details.
25
26use std::sync::Arc;
27
28use async_trait::async_trait;
29use sqlx::PgPool;
30
31use super::audit::{AuthzAuditSink, AuthzSource};
32use super::error::{AuthzError, AuthzResult};
33use super::hook::AuthzDecisionHook;
34use super::parent_chain::{ChainIndexCache, ChainSources, ParentChainIndex, ResolveBase};
35use super::registry::AuthzHookContext;
36use super::repository::AccessControlRepository;
37use super::subject::{
38    SharedSubjectAttributeProvider, SubjectDimension, dimensions_of, discover_subject_providers,
39    gather_subject_attributes,
40};
41use super::types::{AuthzDecision, AuthzRequest, Decision, DenyReason};
42
43#[derive(Clone)]
44pub struct RuleBasedHook {
45    repo: AccessControlRepository,
46    sink: Arc<dyn AuthzAuditSink>,
47    providers: Vec<SharedSubjectAttributeProvider>,
48    dimensions: Vec<SubjectDimension>,
49    sources: Arc<ChainSources>,
50    cache: Arc<ChainIndexCache>,
51}
52
53impl std::fmt::Debug for RuleBasedHook {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        f.debug_struct("RuleBasedHook")
56            .field("repo", &self.repo)
57            .field("sink", &self.sink)
58            .field("providers", &self.providers)
59            .field("dimensions", &self.dimensions)
60            .finish_non_exhaustive()
61    }
62}
63
64impl RuleBasedHook {
65    #[must_use]
66    pub fn new(pool: Arc<PgPool>, sink: Arc<dyn AuthzAuditSink>, sources: ChainSources) -> Self {
67        let providers = discover_subject_providers(&AuthzHookContext {
68            pool: Arc::clone(&pool),
69            sink: Arc::clone(&sink),
70        });
71        Self {
72            repo: AccessControlRepository::from_pool(pool),
73            sink,
74            dimensions: dimensions_of(&providers),
75            providers,
76            sources: Arc::new(sources),
77            cache: Arc::new(ChainIndexCache::default()),
78        }
79    }
80
81    async fn chain_index(&self) -> AuthzResult<Arc<ParentChainIndex>> {
82        self.cache.get(&self.repo, Arc::clone(&self.sources)).await
83    }
84
85    async fn fault(&self, req: &AuthzRequest, error: &AuthzError) -> AuthzDecision {
86        let policy = AuthzSource::RuleBased.policy().to_owned();
87        let detail = error.to_string();
88        let decision = AuthzDecision::Deny {
89            reason: DenyReason::HookUnavailable {
90                policy: policy.clone(),
91                detail: detail.clone(),
92            },
93            policy,
94        };
95        tracing::warn!(
96            entity = %req.entity,
97            user_id = %req.user_id,
98            error = %detail,
99            "rule-based authz hook fault",
100        );
101        self.sink
102            .record(req, &decision, AuthzSource::RuleBased)
103            .await;
104        decision
105    }
106}
107
108#[async_trait]
109impl AuthzDecisionHook for RuleBasedHook {
110    async fn evaluate(&self, req: AuthzRequest) -> AuthzDecision {
111        let kind = req.entity.kind();
112        let id = req.entity.id_str();
113
114        let entity = match self.repo.get_entity(kind, id).await {
115            Ok(row) => row,
116            Err(err) => return self.fault(&req, &err).await,
117        };
118        let rules = match self.repo.list_rules_for_entity(kind, id).await {
119            Ok(rules) => rules,
120            Err(err) => return self.fault(&req, &err).await,
121        };
122
123        let index = match self.chain_index().await {
124            Ok(index) => index,
125            Err(err) => return self.fault(&req, &err).await,
126        };
127
128        let attributes = match gather_subject_attributes(&self.providers, &req.user_id).await {
129            Ok(attributes) => attributes,
130            Err(error) => return self.fault(&req, &error).await,
131        };
132        let decision = index.resolve(
133            kind,
134            id,
135            ResolveBase {
136                rules: &rules,
137                user_id: &req.user_id,
138                user_roles: &req.roles,
139                default_included: entity.map(|e| e.default_included),
140                attributes: &attributes,
141                dimensions: &self.dimensions,
142            },
143        );
144
145        let policy = AuthzSource::RuleBased.policy().to_owned();
146        let authz_decision = match decision {
147            Decision::Allow { .. } => AuthzDecision::Allow,
148            Decision::Warn { reason } => {
149                tracing::warn!(
150                    entity = %req.entity,
151                    user_id = %req.user_id,
152                    %reason,
153                    "access rule evaluated to warn; allowing the request"
154                );
155                AuthzDecision::Allow
156            },
157            Decision::Deny { reason } => AuthzDecision::Deny { reason, policy },
158            Decision::Pending { reason } => {
159                tracing::error!(
160                    %reason,
161                    "a governance hold reached the rule-based resolver, which cannot park a \
162                     request; refusing it"
163                );
164                AuthzDecision::Deny {
165                    reason: DenyReason::PolicyViolation {
166                        policy: "require_approval".to_owned(),
167                        detail: std::borrow::Cow::Borrowed(
168                            "approval required, but this enforcement point cannot hold a request",
169                        ),
170                    },
171                    policy,
172                }
173            },
174        };
175        self.sink
176            .record(&req, &authz_decision, AuthzSource::RuleBased)
177            .await;
178        authz_decision
179    }
180}