static_authz_plugin/domain/service.rs
1// Updated: 2026-04-14 by Constructor Tech
2//! Service implementation for the static `AuthZ` resolver plugin.
3
4use std::sync::Arc;
5
6use authz_resolver_sdk::plugin_api::BatchConcurrency;
7use authz_resolver_sdk::{
8 Capability, Constraint, DenyReason, EvaluationRequest, EvaluationResponse,
9 EvaluationResponseContext, InPredicate, InTenantSubtreePredicate, Predicate,
10};
11use toolkit_macros::domain_model;
12use toolkit_security::pep_properties;
13use uuid::Uuid;
14
15/// Static `AuthZ` resolver service.
16///
17/// - Returns `decision: true` with an `in` predicate on `pep_properties::OWNER_TENANT_ID`
18/// scoped to the context tenant from the request (for all operations including CREATE),
19/// when the PEP declares that property in `context.supported_properties`.
20/// - Additionally emits parallel `InTenantSubtree(<prop>, tid)` constraints (one per
21/// tenant-shaped supported property) when the PEP advertises
22/// [`Capability::TenantHierarchy`]. This lets entities whose `Scopable` declaration
23/// is `no_tenant, resource_col = "..."` (e.g. AM's `tenants`) bind via
24/// `InTenantSubtree(RESOURCE_ID, tid)`, and entities declared `tenant_col = "..."`
25/// that opt-in to subtree access (e.g. AM's `tenant_metadata` / `conversion_requests`)
26/// bind via `InTenantSubtree(OWNER_TENANT_ID, tid)` -- without that addition the
27/// `In(OWNER_TENANT_ID)` clamp restricts visibility to the caller's own tenant row,
28/// hiding direct-child writes the test fixtures exercise.
29/// - Constraints are OR-ed, and a constraint whose property is unusable fails on its
30/// own: the PEP compiler fails it when the property is outside
31/// `supported_properties`, and `SecureORM` drops it when the property doesn't
32/// resolve to a column (all failing → deny) -- so the addition is invisible to PEPs
33/// that don't advertise the capability and to entities that don't expose the property.
34/// - Emits an empty constraint set when the PEP declares none of the properties above.
35/// The PEP compiler turns that into `allow_all()`, or a deny under
36/// `require_constraints` -- this service does not repeat that matrix. Such a permit
37/// means "no row filter", never "the caller owns this row".
38/// - Denies access (`decision: false`) when no valid tenant can be resolved, before any
39/// constraint is built.
40#[domain_model]
41#[derive(Default)]
42pub struct Service {
43 /// Bounds of batch fan-out (the config's `batch` section).
44 pub(super) batch_concurrency: Arc<BatchConcurrency>,
45}
46
47impl Service {
48 #[must_use]
49 pub fn new() -> Self {
50 Self::default()
51 }
52
53 /// Use `limits` to bound batch fan-out instead of the defaults.
54 #[must_use]
55 pub fn with_batch_concurrency(mut self, limits: BatchConcurrency) -> Self {
56 self.batch_concurrency = Arc::new(limits);
57 self
58 }
59
60 /// Evaluate an authorization request.
61 #[must_use]
62 #[allow(clippy::unused_self)] // &self reserved for future config/state
63 pub fn evaluate(&self, request: &EvaluationRequest) -> EvaluationResponse {
64 // Always scope to context tenant (all CRUD operations get constraints)
65 let tenant_id = request
66 .context
67 .tenant_context
68 .as_ref()
69 .and_then(|t| t.root_id)
70 .or_else(|| {
71 // Fallback: extract tenant_id from subject properties
72 request
73 .subject
74 .properties
75 .get("tenant_id")
76 .and_then(|v| v.as_str())
77 .and_then(|s| Uuid::parse_str(s).ok())
78 });
79
80 let Some(tid) = tenant_id else {
81 // No tenant resolvable from context or subject - deny access.
82 return Self::deny(DenyReason::INVALID_REQUEST);
83 };
84
85 if tid == Uuid::default() {
86 // Nil UUID tenant - deny rather than grant unrestricted access.
87 return Self::deny(DenyReason::INVALID_REQUEST);
88 }
89
90 // This static PDP has no RG client and therefore cannot resolve group
91 // selectors to explicit resource IDs. Ignoring a selector would widen
92 // it to tenant-wide access, so deny whenever group scoping is requested.
93 if request.resource.properties.contains_key("group_ids")
94 || request
95 .resource
96 .properties
97 .contains_key("ancestor_group_ids")
98 {
99 return Self::deny(DenyReason::INVALID_REQUEST);
100 }
101
102 // Baseline OWNER_TENANT_ID clamp -- the universal shape a PEP binds when its
103 // entity declares `tenant_col`. Emitted only when the PEP declares that property:
104 // the compiler fails any constraint naming something outside
105 // `context.supported_properties` (`authz-resolver-sdk/src/pep/compiler.rs`), so an
106 // undeclared clamp is dead on arrival -- and as the only constraint it failed the
107 // whole set (`AllConstraintsFailed`, a deny), losing every request for a
108 // platform-global resource that declares no property at all.
109 let mut constraints = Vec::new();
110 if supports_property(request, pep_properties::OWNER_TENANT_ID) {
111 constraints.push(Constraint {
112 predicates: vec![Predicate::In(InPredicate::new(
113 pep_properties::OWNER_TENANT_ID,
114 [tid],
115 ))],
116 });
117 }
118
119 // Closes the gap from `gears-rust#1813` (plugin half) for the dev stack:
120 // PEPs that advertise `Capability::TenantHierarchy` get an
121 // `InTenantSubtree(<prop>, tid)` constraint for each
122 // tenant-shaped property they declare as supported
123 // (`OWNER_TENANT_ID` and `RESOURCE_ID`). The two predicates target
124 // different entity shapes:
125 //
126 // * `InTenantSubtree(OWNER_TENANT_ID, tid)` binds against entities
127 // declared with `tenant_col` (e.g. AM's `tenant_metadata` /
128 // `conversion_requests`) and clamps to the caller's subtree --
129 // the contract the test fixtures exercise when a caller in the
130 // root tenant writes metadata on a direct child.
131 // * `InTenantSubtree(RESOURCE_ID, tid)` binds against entities
132 // declared with `resource_col` (e.g. AM's `tenants` itself,
133 // `no_tenant`) and clamps via the resource id.
134 //
135 // The constraints are OR-ed, and a constraint whose property is
136 // unusable fails on its own (the PEP compiler fails it outside
137 // `supported_properties`; SecureORM drops it when the property
138 // doesn't resolve to a column; all failing → deny) -- so the
139 // addition is invisible to PEPs that don't advertise the capability
140 // and to entities that don't expose the property. Gears that do not opt-in to
141 // `Capability::TenantHierarchy` see the baseline shape unchanged.
142 if advertises_tenant_hierarchy(request) {
143 for prop in [pep_properties::OWNER_TENANT_ID, pep_properties::RESOURCE_ID] {
144 if supports_property(request, prop) {
145 constraints.push(Constraint {
146 predicates: vec![Predicate::InTenantSubtree(
147 InTenantSubtreePredicate::new(prop, tid),
148 )],
149 });
150 }
151 }
152 }
153
154 // No constraint means the PEP declared none of the properties above. The compiler
155 // owns what that means -- `allow_all()`, or a deny under `require_constraints`
156 // (`compiler.rs` Step 1, pinned by the composition tests) -- so there is no deny of
157 // our own here. That Step 1 returns without logging, hence the warn.
158 //
159 // Do not narrow the required case with `resource.properties[OWNER_TENANT_ID]`
160 // instead: this plugin has no tenant tree, so it cannot tell an ancestor from a
161 // stranger, and an equality check denies the ancestor-tenant requests the AM e2e
162 // suites exercise.
163 if constraints.is_empty() && request.context.require_constraints {
164 tracing::warn!(
165 resource_type = %request.resource.resource_type,
166 "static-authz: PEP requires constraints but declares none of the properties \
167 this plugin constrains -- the PEP compiler will fail this closed",
168 );
169 }
170
171 EvaluationResponse {
172 decision: true,
173 context: EvaluationResponseContext {
174 constraints,
175 ..Default::default()
176 },
177 }
178 }
179
180 /// A denial carrying `error_code` (a batch denial must carry one).
181 fn deny(error_code: &str) -> EvaluationResponse {
182 EvaluationResponse::deny(DenyReason::new(error_code))
183 }
184}
185
186fn advertises_tenant_hierarchy(request: &EvaluationRequest) -> bool {
187 request
188 .context
189 .capabilities
190 .iter()
191 .any(|c| matches!(c, Capability::TenantHierarchy))
192}
193
194fn supports_property(request: &EvaluationRequest, property: &str) -> bool {
195 request
196 .context
197 .supported_properties
198 .iter()
199 .any(|p| p == property)
200}
201
202#[cfg(test)]
203#[path = "service_tests.rs"]
204mod service_tests;