Skip to main content

scyph_core/
traits.rs

1//! Core traits and types for authentication, authorization, and permission enforcement.
2//!
3//! This module defines:
4//! - [`Authorizable`]: Marker trait for user role identifiers.
5//! - [`Claims`]: Trait for parsing and validating JWT claims payloads.
6//! - [`Action`]: Standard enumeration of CRUD and custom actions used in policy evaluation.
7//!
8//! # Design Philosophy
9//!
10//! These traits form the type-level contract between the authentication layer (`scyph-auth`)
11//! and the authorization layer (`scyph-abac`). By parameterizing over `Claims` everywhere,
12//! the framework remains fully generic — applications define their own role enums and claims
13//! structs without any hard-coded types in library code.
14//!
15//! The typical dependency graph looks like:
16//!
17//! ```text
18//! Your App
19//!   ├── defines MyClaims (implements Claims)
20//!   ├── defines MyRole   (implements Authorizable automatically)
21//!   ├── scyph-auth  uses Claims + Authorizable for JWT extraction / RBAC
22//!   └── scyph-abac  uses Claims + Action for policy evaluation / SQL filtering
23//! ```
24//!
25//! # Quick Start
26//!
27//! Define your role enum and claims struct, implement [`Claims`], and plug them into
28//! the Scyph middleware:
29//!
30//! ```rust
31//! use scyph_core::{Claims, Action};
32//! use uuid::Uuid;
33//! use serde::{Serialize, Deserialize};
34//!
35//! #[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
36//! enum UserRole { Guest, User, Moderator, Admin }
37//!
38//! #[derive(Clone, Serialize, Deserialize)]
39//! struct AppClaims {
40//!     sub: Uuid,
41//!     exp: i64,
42//!     jti: String,
43//!     role: UserRole,
44//!     // application-specific fields:
45//!     email: String,
46//!     tenant_id: Uuid,
47//! }
48//!
49//! impl Claims for AppClaims {
50//!     type Role = UserRole;
51//!     fn subject(&self) -> Uuid     { self.sub }
52//!     fn expiry(&self) -> i64       { self.exp }
53//!     fn jti(&self) -> &str         { &self.jti }
54//!     fn role(&self) -> &UserRole   { &self.role }
55//! }
56//! ```
57
58use serde::{Deserialize, Serialize};
59use std::borrow::Cow;
60use uuid::Uuid;
61
62/// Marker trait representing a role or permission identifier usable for authorization.
63///
64/// Automatically implemented for any type that satisfies `Copy + Eq + Send + Sync + 'static`.
65pub trait Authorizable: Copy + Eq + Send + Sync + 'static {}
66impl<T> Authorizable for T where T: Copy + Eq + Send + Sync + 'static {}
67
68/// Core trait to implement on your application's custom JWT claims struct.
69///
70/// Implementing `Claims` allows Scyph's authentication middleware and extractors
71/// to read the user subject ID (`sub`), expiration timestamp (`exp`), unique JWT ID (`jti`),
72/// and role type (`Role`).
73///
74/// # Examples
75///
76/// A minimal realistic implementation with application-specific fields:
77///
78/// ```rust
79/// use scyph_core::Claims;
80/// use uuid::Uuid;
81/// use serde::{Serialize, Deserialize};
82///
83/// /// Application role enum. Implements [`scyph_core::Authorizable`] automatically
84/// /// because it is `Copy + Eq + Send + Sync + 'static`.
85/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
86/// enum UserRole { Guest, User, Moderator, Admin }
87///
88/// /// Full JWT claims payload embedded in every access token.
89/// ///
90/// /// Fields `sub`, `exp`, and `jti` are standard JWT registered claims.
91/// /// `role`, `email`, and `tenant_id` are application-specific private claims.
92/// #[derive(Clone, Serialize, Deserialize)]
93/// struct AppClaims {
94///     /// Subject — the authenticated user's UUID.
95///     sub: Uuid,
96///     /// Expiration — Unix timestamp (seconds since epoch).
97///     exp: i64,
98///     /// JWT ID — unique per-token identifier for revocation support.
99///     jti: String,
100///     /// Role — controls RBAC and ABAC policy decisions.
101///     role: UserRole,
102///     /// Application-specific: user's email address.
103///     email: String,
104///     /// Application-specific: tenant scope for multi-tenant APIs.
105///     tenant_id: Uuid,
106/// }
107///
108/// impl Claims for AppClaims {
109///     type Role = UserRole;
110///
111///     fn subject(&self) -> Uuid       { self.sub }
112///     fn expiry(&self) -> i64         { self.exp }
113///     fn jti(&self) -> &str           { &self.jti }
114///     fn role(&self) -> &UserRole     { &self.role }
115///
116///     // Optional: override is_expired if you use millisecond timestamps
117///     // fn is_expired(&self) -> bool { self.exp < chrono::Utc::now().timestamp_millis() }
118/// }
119///
120/// // Construct claims for testing
121/// let claims = AppClaims {
122///     sub: Uuid::now_v7(),
123///     exp: chrono::Utc::now().timestamp() + 3600,
124///     jti: "unique-token-id-001".into(),
125///     role: UserRole::Admin,
126///     email: "alice@example.com".into(),
127///     tenant_id: Uuid::now_v7(),
128/// };
129///
130/// assert_eq!(*claims.role(), UserRole::Admin);
131/// assert!(!claims.is_expired());
132/// ```
133pub trait Claims: serde::de::DeserializeOwned + Serialize + Send + Sync + Clone + 'static {
134    /// The associated role type used by your application for access control.
135    type Role: Authorizable;
136
137    /// Returns the unique subject identifier (e.g. User UUID) for the token holder.
138    fn subject(&self) -> Uuid;
139
140    /// Returns the token expiration time as a Unix timestamp (in seconds).
141    fn expiry(&self) -> i64;
142
143    /// Returns the unique JWT identifier string (`jti`) used for revocation checking.
144    fn jti(&self) -> &str;
145
146    /// Returns a reference to the user's role.
147    fn role(&self) -> &Self::Role;
148
149    /// Returns `true` if the token's expiration timestamp is in the past relative to UTC now.
150    ///
151    /// Defaults to checking if `chrono::Utc::now().timestamp() > self.expiry()`.
152    /// Override this method if your claims use non-standard epoch representations.
153    ///
154    /// # Notes
155    ///
156    /// - The default implementation uses **second-precision** Unix timestamps. If your JWT
157    ///   library stores `exp` in milliseconds, override this method accordingly.
158    /// - This method is intentionally a fallback. Scyph's JWT verification layer
159    ///   (`scyph_auth::verify_token`) performs expiry validation during decoding via the
160    ///   `jsonwebtoken` crate. `is_expired` is provided for secondary in-process checks
161    ///   (e.g. guarding cached claims that may have been stored before the token expired).
162    /// - Clock skew between services is not compensated. Add a small leeway at the token
163    ///   issuance layer if needed (e.g. set `exp = now + ttl + 30` seconds).
164    fn is_expired(&self) -> bool {
165        chrono::Utc::now().timestamp() > self.expiry()
166    }
167}
168
169/// Authorization actions used in Attribute-Based Access Control (ABAC) or Policy evaluation.
170///
171/// `Action` represents the **operation** a subject is attempting on a resource. It is the
172/// central axis of ABAC policy decisions, alongside the subject (who) and resource (what).
173///
174/// Marked as `#[non_exhaustive]` to allow future action extensions via [`Action::Custom`]
175/// without breaking existing match patterns in downstream crates.
176///
177/// # ABAC Usage Context
178///
179/// In `scyph-abac`, actions are passed to `AbacPolicy::check` to determine whether a
180/// subject may perform a given operation:
181///
182/// ```rust,ignore
183/// use scyph_core::Action;
184/// use scyph_abac::AbacPolicy;
185///
186/// impl AbacPolicy for DocumentPolicy {
187///     type Resource = Document;
188///     type Claims = AppClaims;
189///
190///     fn check(subject: &AuthUser<AppClaims>, doc: &Document, action: Action)
191///         -> Result<(), AbacError>
192///     {
193///         match action {
194///             Action::Read   => check_read_permission(subject, doc),
195///             Action::Update => check_ownership(subject, doc),
196///             Action::Delete => check_admin_or_owner(subject, doc),
197///             Action::Custom(ref name) if name == "publish" => check_publish(subject, doc),
198///             _ => Ok(()), // allow by default for unhandled actions
199///         }
200///     }
201/// }
202/// ```
203///
204/// # Custom Actions
205///
206/// Use [`Action::Custom`] for domain-specific operations that don't map to standard CRUD:
207///
208/// ```rust
209/// use scyph_core::Action;
210/// use std::borrow::Cow;
211///
212/// let publish = Action::Custom(Cow::Borrowed("publish"));
213/// let export  = Action::Custom(Cow::Borrowed("export"));
214/// let approve = Action::Custom(Cow::Borrowed("approve"));
215///
216/// assert_ne!(publish, Action::Create);
217/// assert_eq!(publish, Action::Custom(Cow::Borrowed("publish")));
218/// ```
219#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
220#[non_exhaustive]
221pub enum Action {
222    /// Create a new entity or resource.
223    Create,
224    /// Read or view an existing entity or resource.
225    Read,
226    /// Update or modify an existing entity or resource.
227    Update,
228    /// Delete or remove an existing entity or resource.
229    Delete,
230    /// List or search collections of resources.
231    List,
232    /// Custom domain-specific action identified by a static string slice.
233    Custom(Cow<'static, str>),
234}