axess-core 0.2.0

Core implementation for the axess library. Session state machine, multi-factor authentication engine, Cedar Policy evaluation, and pluggable storage backends. Use the `axess` facade crate unless you need direct access to internals.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! [`AuthzStore`] and [`AuthzSession`]: the runtime authorization layer.
//!
//! # Overview
//!
//! [`AuthzStore`] is the Arc-able, application-scoped component held in Axum
//! state. It owns the policy evaluator, the entity provider, and the namespace.
//! It builds [`AuthzSession`] values per request.
//!
//! [`AuthzSession`] is the per-request handle. Calling `.require()` on it
//! builds the Cedar entity set (using the provider), evaluates the policy,
//! and returns `Ok(())` or `Err(`[`AuthzDenied`]`)`.
//!
//! # Typical handler usage
//!
//! ```rust,ignore
//! async fn view_ledger(
//!     State(state): State<AppState>,
//!     session: AuthSession<OurBackend, OurRegistry, SystemRng>,
//!     Path(ledger_id): Path<Uuid>,
//! ) -> Result<impl IntoResponse, AppError> {
//!     let user_id = session.get_user_id().ok_or(AuthzDenied)?;
//!
//!     let authz = state.authz.for_user_id(&user_id.to_string())?;
//!     authz.require("ViewLedger", &ledger_id).await?;
//!
//!     // ...handler body
//! }
//! ```
//!
//! # With ABAC context
//!
//! ```rust,ignore
//! use axess_core::authz::context::StandardRequestContext;
//!
//! let ctx = StandardRequestContext::new(
//!     session.is_mfa_complete(),
//!     ip_from_headers(request.headers()),
//! );
//! let authz = state.authz.for_user_id_with_context(&user_id, ctx)?;
//! authz.require("PostJournalEntry", &ledger_id).await?;
//! ```

use cedar_policy::{Context, Entities, EntityUid};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tracing::warn;

use super::{
    context::{BuildRequestContext, NoContext},
    error::{AuthzDenied, AuthzError},
    provider::AuthzEntityProvider,
    store::{AuthzDecision, PolicyEvaluator, make_uid},
};

// ── AuthzStore ────────────────────────────────────────────────────────────────

/// Application-scoped authorization configuration.
///
/// Holds the policy evaluator, entity provider, and Cedar namespace. Construct
/// once at startup and store in `Arc<AuthzStore<P>>` inside your Axum state.
///
/// Wiring an `AuthzStore` requires both a [`PolicyEvaluator`] (production:
/// `PolicyStore::from_text(...)`) and an adopter-supplied
/// [`AuthzEntityProvider`] impl; the moving parts are non-trivial to set up
/// inside a single doc-test, so a runnable end-to-end example lives in
/// `examples/authz/` and the module-level rustdoc above shows the
/// handler-side usage.
pub struct AuthzStore<P: AuthzEntityProvider> {
    pub(super) evaluator: Arc<dyn PolicyEvaluator>,
    pub(super) provider: Arc<P>,
    pub(super) namespace: Arc<str>,
}

impl<P: AuthzEntityProvider> AuthzStore<P> {
    /// Create a new `AuthzStore`.
    ///
    /// - `evaluator`: production: `Arc::new(PolicyStore::from_text(...)?)`.
    ///   Tests: `Arc::new(MockPolicyEvaluator::new())`.
    /// - `provider`: your [`AuthzEntityProvider`] implementation.
    /// - `namespace`: the Cedar entity namespace used in your schema and
    ///   policy files (e.g. `"MyApp"`). All UID builders on this store use it.
    pub fn new(
        evaluator: Arc<dyn PolicyEvaluator>,
        provider: Arc<P>,
        namespace: impl Into<Arc<str>>,
    ) -> Self {
        Self {
            evaluator,
            provider,
            namespace: namespace.into(),
        }
    }

    /// Optional startup check: validate the entity provider against the Cedar schema.
    ///
    /// Call this after constructing the store to catch type mismatches between
    /// your provider and the compiled policy schema before accepting traffic.
    pub fn validate(&self) -> Result<(), AuthzError> {
        if let Some(schema) = self.evaluator.schema() {
            self.provider.validate_against_schema(schema)?;
        }
        Ok(())
    }

    // ── UID builders ──────────────────────────────────────────────────────────

    /// Build a Cedar `User` entity UID in this store's namespace.
    pub fn user_uid(&self, id: &str) -> Result<EntityUid, AuthzError> {
        make_uid(&self.namespace, "User", id)
    }

    /// Build a Cedar `Role` entity UID in this store's namespace.
    pub fn role_uid(&self, name: &str) -> Result<EntityUid, AuthzError> {
        make_uid(&self.namespace, "Role", name)
    }

    /// Build a Cedar `Action` entity UID in this store's namespace.
    pub fn action_uid(&self, name: &str) -> Result<EntityUid, AuthzError> {
        make_uid(&self.namespace, "Action", name)
    }

    /// Build a Cedar `Tenant` entity UID in this store's namespace.
    pub fn tenant_uid(&self, id: &str) -> Result<EntityUid, AuthzError> {
        make_uid(&self.namespace, "Tenant", id)
    }

    /// Build a Cedar `Platform` entity UID in this store's namespace.
    pub fn platform_uid(&self, id: &str) -> Result<EntityUid, AuthzError> {
        make_uid(&self.namespace, "Platform", id)
    }

    /// Build a Cedar entity UID for an arbitrary type in this store's namespace.
    ///
    /// Use this for application-specific entity types not covered by the
    /// named builder methods above.
    pub fn entity_uid(&self, type_name: &str, id: &str) -> Result<EntityUid, AuthzError> {
        make_uid(&self.namespace, type_name, id)
    }

    // ── Session builders ──────────────────────────────────────────────────────

    /// Begin a per-request authz session for the given user ID.
    ///
    /// The session uses an empty Cedar `Context`: suitable when all access
    /// control is role-based or relationship-based only.
    ///
    /// For ABAC policies (IP checks, MFA requirements, etc.) use
    /// [`for_user_id_with_context`][Self::for_user_id_with_context].
    pub fn for_user_id(
        self: &Arc<Self>,
        user_id: &str,
    ) -> Result<AuthzSession<P, NoContext>, AuthzError> {
        let principal = self.user_uid(user_id)?;
        Ok(AuthzSession {
            store: Arc::clone(self),
            principal,
            context: Context::empty(),
            cache: Mutex::new(HashMap::new()),
            _ctx: std::marker::PhantomData,
        })
    }

    /// Begin a per-request authz session with an ABAC context.
    ///
    /// The context is built immediately and stored for the lifetime of the
    /// session; it is not rebuilt per check.
    pub fn for_user_id_with_context<Ctx: BuildRequestContext>(
        self: &Arc<Self>,
        user_id: &str,
        ctx: Ctx,
    ) -> Result<AuthzSession<P, Ctx>, AuthzError> {
        let principal = self.user_uid(user_id)?;
        let context = ctx.to_cedar_context()?;
        Ok(AuthzSession {
            store: Arc::clone(self),
            principal,
            context,
            cache: Mutex::new(HashMap::new()),
            _ctx: std::marker::PhantomData,
        })
    }
}

// ── AuthzSession ──────────────────────────────────────────────────────────────

/// Per-request authorization session.
///
/// Created by [`AuthzStore::for_user_id`] or [`AuthzStore::for_user_id_with_context`].
/// `Send`: safe to hold across `.await` in Axum handlers.
pub struct AuthzSession<P: AuthzEntityProvider, Ctx = NoContext> {
    store: Arc<AuthzStore<P>>,
    principal: EntityUid,
    context: Context,
    // Per-request entity cache: (action_uid_str, resource_uid_str) → entities.
    // Deduplicates repeated identical checks within one request.
    // Uses Mutex (not RefCell) so the session is Send for Axum handlers.
    // The lock is never held across .await points.
    cache: Mutex<HashMap<(String, String), Arc<Entities>>>,
    _ctx: std::marker::PhantomData<Ctx>,
}

impl<P: AuthzEntityProvider, Ctx> AuthzSession<P, Ctx> {
    /// Check access and return an error on denial.
    ///
    /// Returns `Ok(())` if Cedar permits, `Err(AuthzDenied)` otherwise.
    /// `Err(AuthzDenied)` implements [`IntoResponse`][axum::response::IntoResponse]
    /// and converts to a 403 JSON response; handlers can propagate it directly
    /// with `?`.
    ///
    /// Fail-closed: any error in entity building or evaluation returns `Deny`.
    #[tracing::instrument(skip(self, resource))]
    pub async fn require(&self, action: &str, resource: &P::ResourceId) -> Result<(), AuthzDenied> {
        match self.check(action, resource).await {
            AuthzDecision::Allow => Ok(()),
            AuthzDecision::Deny => Err(AuthzDenied),
        }
    }

    /// Check access and return a boolean.
    ///
    /// Returns `true` if Cedar permits, `false` on denial or any error.
    /// Use this for UI capability hints (which buttons to show) where a hard
    /// 403 is not wanted.
    #[tracing::instrument(skip(self, resource))]
    pub async fn is_permitted(&self, action: &str, resource: &P::ResourceId) -> bool {
        matches!(self.check(action, resource).await, AuthzDecision::Allow)
    }

    /// Check multiple (action, resource) pairs in sequence.
    ///
    /// Returns a vec of `(action_name, decision)` in the same order as `checks`.
    /// Entity results are cached across the batch, so repeated resource loads
    /// within the batch are deduplicated.
    ///
    /// Useful for computing per-resource capability sets (which toolbar buttons
    /// are enabled) without N separate handler round-trips.
    #[tracing::instrument(skip(self, checks))]
    pub async fn batch_check(
        &self,
        checks: &[(&str, &P::ResourceId)],
    ) -> Vec<(String, AuthzDecision)> {
        let mut results = Vec::with_capacity(checks.len());
        for (action, resource) in checks {
            let decision = self.check(action, resource).await;
            results.push(((*action).to_string(), decision));
        }
        results
    }

    /// Return the principal [`EntityUid`] for this session.
    pub fn principal(&self) -> &EntityUid {
        &self.principal
    }

    // ── Internal evaluation ───────────────────────────────────────────────────

    async fn check(&self, action: &str, resource: &P::ResourceId) -> AuthzDecision {
        // 1. Build action UID.
        let action_uid = match self.store.action_uid(action) {
            Ok(uid) => uid,
            Err(e) => {
                warn!("authz: invalid action UID '{}': {e}", action);
                return AuthzDecision::Deny;
            }
        };

        // 2. Build resource UID.
        let resource_uid = match self.store.provider.resource_uid(resource) {
            Ok(uid) => uid,
            Err(e) => {
                warn!("authz: invalid resource UID: {e}");
                return AuthzDecision::Deny;
            }
        };

        // 3. Check per-request entity cache.
        let cache_key = (action_uid.to_string(), resource_uid.to_string());
        let entities = {
            let cached = self
                .cache
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .get(&cache_key)
                .cloned();
            if let Some(arc) = cached {
                arc
            } else {
                // 4. Build entities via the provider.
                match self
                    .store
                    .provider
                    .entities_for(&self.principal, resource, &action_uid)
                    .await
                {
                    Ok(ent) => {
                        let arc = Arc::new(ent);
                        self.cache
                            .lock()
                            .unwrap_or_else(|e| e.into_inner())
                            .insert(cache_key, Arc::clone(&arc));
                        arc
                    }
                    Err(e) => {
                        warn!("authz: entity provider error: {e}");
                        return AuthzDecision::Deny;
                    }
                }
            }
        };

        // 5. Evaluate Cedar policy.
        self.store.evaluator.is_authorized(
            &entities,
            self.principal.clone(),
            action_uid,
            resource_uid,
            self.context.clone(),
        )
    }
}

#[cfg(test)]
mod authz_session_tests {
    use super::*;
    use crate::authz::store::PolicyStore;
    use cedar_policy::{Entities, EntityUid, Schema};

    const SCHEMA_JSON: &str = r#"{
        "TestApp": {
            "entityTypes": {
                "User": { "memberOfTypes": [] },
                "Resource": { "memberOfTypes": [] }
            },
            "actions": {
                "View": {
                    "appliesTo": {
                        "principalTypes": ["User"],
                        "resourceTypes": ["Resource"]
                    }
                }
            }
        }
    }"#;

    const POLICY_TEXT: &str = r#"permit(
        principal == TestApp::User::"alice",
        action == TestApp::Action::"View",
        resource == TestApp::Resource::"doc1"
    );"#;

    struct ErroringProvider;

    impl AuthzEntityProvider for ErroringProvider {
        type ResourceId = String;
        type Error = std::convert::Infallible;

        async fn entities_for(
            &self,
            principal: &EntityUid,
            resource_id: &Self::ResourceId,
            action: &EntityUid,
        ) -> Result<Entities, Self::Error> {
            tracing::trace!(
                target: "axess::authz::test_stub",
                ?principal,
                ?resource_id,
                ?action,
                "ErroringProvider::entities_for: returning empty entities",
            );
            Ok(Entities::empty())
        }

        fn resource_uid(&self, id: &Self::ResourceId) -> Result<EntityUid, AuthzError> {
            super::super::store::make_uid("TestApp", "Resource", id)
        }

        fn validate_against_schema(&self, schema: &Schema) -> Result<(), AuthzError> {
            tracing::trace!(
                target: "axess::authz::test_stub",
                ?schema,
                "ErroringProvider::validate_against_schema: synthetic failure",
            );
            Err(AuthzError::SchemaParse(
                "synthetic schema validation failure".to_string(),
            ))
        }
    }

    #[test]
    fn validate_propagates_provider_validation_error() {
        // Pins `AuthzStore::validate -> Ok(())` mutation. The
        // mutation skips the inner `provider.validate_against_schema`
        // call. With a provider that errors, the genuine path returns
        // `Err`; the mutation would silently return `Ok(())` and
        // mask startup-time schema mismatches.
        let evaluator: Arc<dyn PolicyEvaluator> =
            Arc::new(PolicyStore::from_text(POLICY_TEXT, SCHEMA_JSON).unwrap());
        let store = AuthzStore::new(evaluator, Arc::new(ErroringProvider), "TestApp");
        let result = store.validate();
        assert!(
            matches!(result, Err(AuthzError::SchemaParse(_))),
            "validate() must propagate provider's validate_against_schema error, got {result:?}"
        );
    }
}