Skip to main content

webx_core/
auth.rs

1//! Authentication and authorization traits for the rust-webx framework.
2//!
3//! Provides:
4//! - `IClaims`: Extracted auth claims (JWT or other token types).
5//! - `IAuthenticationHandler`: Authenticate an HTTP request and produce claims.
6//! - `IAuthorizationPolicy`: Check if authenticated claims can access a resource.
7
8use crate::error::{Error, Result};
9use crate::http::IHttpContext;
10use std::collections::HashMap;
11
12/// Claims extracted from an authentication token (JWT, etc.).
13///
14/// Stored in `IHttpContext` extensions via `IClaimsExt`.
15pub trait IClaims: Send + Sync {
16    /// The user / subject identifier.
17    fn subject(&self) -> &str;
18
19    /// Roles assigned to the user.
20    fn roles(&self) -> &[String];
21
22    /// Permissions assigned to the user.
23    fn permissions(&self) -> &[String];
24
25    /// Raw claims map (key-value pairs from the token).
26    fn claims(&self) -> &HashMap<String, String>;
27
28    /// Clone the claims into a new boxed trait object.
29    fn clone_box(&self) -> Box<dyn IClaims>;
30
31    // ── Convenience helpers (default implementations) ──
32
33    /// Check whether a specific role is assigned.
34    ///
35    /// ```ignore
36    /// if claims.has_role("admin") { ... }
37    /// ```
38    fn has_role(&self, role: &str) -> bool {
39        self.roles().iter().any(|r| r == role)
40    }
41
42    /// Alias for `subject()` — returns the user identifier.
43    fn get_userid(&self) -> &str {
44        self.subject()
45    }
46
47    /// Read the display name from the raw claims map (key `"name"`).
48    /// Returns `None` when absent.
49    fn get_username(&self) -> Option<&str> {
50        self.claims().get("name").map(|s| s.as_str())
51    }
52
53    /// Read the tenant identifier from the raw claims map (key `"tenant_id"`).
54    /// Returns `None` when absent.
55    fn get_tenantid(&self) -> Option<&str> {
56        self.claims()
57            .get("tenant_id")
58            .or_else(|| self.claims().get("tenant"))
59            .map(|s| s.as_str())
60    }
61
62    /// Read the email address from the raw claims map (key `"email"`).
63    /// Returns `None` when absent.
64    fn get_email(&self) -> Option<&str> {
65        self.claims().get("email").map(|s| s.as_str())
66    }
67}
68
69impl Clone for Box<dyn IClaims> {
70    fn clone(&self) -> Self {
71        self.clone_box()
72    }
73}
74
75/// Authentication scheme interface.
76///
77/// Implementations read credentials from the HTTP context (e.g., JWT bearer token,
78/// API key header, cookie) and return claims or `None` if unauthenticated.
79#[async_trait::async_trait]
80pub trait IAuthenticationHandler: Send + Sync {
81    /// Authenticate the request and return claims, or `None` if not authenticated.
82    ///
83    /// Uses `&mut dyn IHttpContext` so the returned future is `Send`
84    /// (required by `tokio::spawn` — `&dyn IHttpContext` is `!Send`
85    /// because `IHttpContext` is not `Sync`).
86    async fn authenticate(&self, ctx: &mut dyn IHttpContext) -> Result<Option<Box<dyn IClaims>>>;
87}
88
89/// Authorization policy that checks whether an authenticated user
90/// can access a given resource.
91///
92/// The `resource_key` is the original route pattern string (e.g., `"/api/users/{id}"`),
93/// enabling dynamic identity-authorization-data systems to match routes directly.
94#[async_trait::async_trait]
95pub trait IAuthorizationPolicy: Send + Sync {
96    /// Check if the authenticated user can access the resource.
97    ///
98    /// * `claims`  — the user's authentication claims.
99    /// * `resource_key` — the original route pattern string.
100    /// * `method` — the HTTP method.
101    ///
102    /// Returns `Ok(())` if authorized, or an `Err` if forbidden.
103    async fn authorize(&self, claims: &dyn IClaims, resource_key: &str, method: &str)
104        -> Result<()>;
105}
106
107/// Dynamic authorizer interface — pluggable authorization for protected routes.
108///
109/// Implement this trait and register it in the DI container:
110///
111/// ```ignore
112/// svc.singleton::<dyn IDynamicAuthorizer>(|_| Arc::new(MyAuthorizer::default()))
113/// ```
114///
115/// The framework automatically detects registered `IDynamicAuthorizer` implementations
116/// and invokes them on every route that has `#[authorize]`.
117/// If no implementations are registered, authorization is pass-through (no dynamic checks).
118///
119/// # Method
120///
121/// * `authorize` — receives the user's claims, matched route pattern, and HTTP method.
122///   Returns `Ok(())` if allowed, or `Err` with details if denied.
123#[async_trait::async_trait]
124pub trait IDynamicAuthorizer: Send + Sync {
125    /// Validate whether the authenticated user can access the resource.
126    async fn authorize(
127        &self,
128        claims: &dyn IClaims,
129        route_pattern: &str,
130        method: &str,
131    ) -> Result<()>;
132}
133
134/// The standard identity a request can carry.
135///
136/// `IdentityUser` is a **read-only projection of [`IClaims`]** for request
137/// handling — not a persistence entity. When an endpoint needs the raw claim
138/// map, read it through [`IClaimsExt`](crate::http::IClaimsExt) in middleware or
139/// infrastructure code; `IdentityUser` covers the identity fields almost every
140/// handler needs.
141///
142/// Put it in a request with `#[fromclaim]` and the binder fills it from the
143/// authenticated principal:
144///
145/// ```ignore
146/// #[derive(WebxRequestMeta)]
147/// pub struct CreateOrderRequest {
148///     #[fromclaim]
149///     pub user: IdentityUser,
150///     pub sku: String,
151/// }
152/// ```
153///
154/// The handler then reads `req.user.id`, `req.user.tenant_id` or
155/// `req.user.is_in_role("admin")` without touching the token or the context.
156/// `Option<IdentityUser>` makes the endpoint work for anonymous callers too.
157#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
158pub struct IdentityUser {
159    /// The subject (`sub`) — the stable user identifier.
160    pub id: String,
161    /// Display name (`name` claim), empty when the token has none.
162    pub name: String,
163    /// Email address (`email` claim), empty when the token has none.
164    pub email: String,
165    /// Tenant identifier (`tenant_id` / `tenant`), empty for single-tenant apps.
166    pub tenant_id: String,
167    /// Roles assigned to the user.
168    pub roles: Vec<String>,
169    /// Fine-grained permissions assigned to the user.
170    pub permissions: Vec<String>,
171}
172
173impl IdentityUser {
174    /// Build the identity from an authenticated principal.
175    pub fn from_claims(claims: &dyn IClaims) -> Self {
176        Self {
177            id: claims.subject().to_string(),
178            name: claims.get_username().unwrap_or_default().to_string(),
179            email: claims.get_email().unwrap_or_default().to_string(),
180            tenant_id: claims.get_tenantid().unwrap_or_default().to_string(),
181            roles: claims.roles().to_vec(),
182            permissions: claims.permissions().to_vec(),
183        }
184    }
185
186    /// Whether the user has `role`.
187    pub fn is_in_role(&self, role: &str) -> bool {
188        self.roles.iter().any(|assigned| assigned == role)
189    }
190
191    /// Whether the user has `permission`.
192    pub fn has_permission(&self, permission: &str) -> bool {
193        self.permissions
194            .iter()
195            .any(|assigned| assigned == permission)
196    }
197
198    /// The display name, falling back to the identifier.
199    pub fn display_name(&self) -> &str {
200        if self.name.is_empty() {
201            &self.id
202        } else {
203            &self.name
204        }
205    }
206}
207
208/// Convenience accessors for a request that carries an [`IdentityUser`].
209///
210/// `#[derive(WebxRequestMeta)]` implements this automatically when the struct
211/// has a `#[fromclaim]` field of type `IdentityUser` or `Option<IdentityUser>`.
212pub trait RequestUser {
213    /// The authenticated identity, or `None` for an anonymous request.
214    fn current_user(&self) -> Option<&IdentityUser>;
215
216    /// The subject identifier, or `None` when anonymous.
217    fn user_id(&self) -> Option<&str> {
218        self.current_user().map(|user| user.id.as_str())
219    }
220
221    /// The display name, or `None` when anonymous.
222    fn user_name(&self) -> Option<&str> {
223        self.current_user().map(|user| user.name.as_str())
224    }
225
226    /// The email address, or `None` when anonymous.
227    fn user_email(&self) -> Option<&str> {
228        self.current_user().map(|user| user.email.as_str())
229    }
230
231    /// The tenant identifier, or `None` when anonymous.
232    fn tenant_id(&self) -> Option<&str> {
233        self.current_user().map(|user| user.tenant_id.as_str())
234    }
235
236    /// The roles of the authenticated user (empty when anonymous).
237    fn roles(&self) -> &[String] {
238        match self.current_user() {
239            Some(user) => &user.roles,
240            None => &[],
241        }
242    }
243
244    /// Whether the authenticated user has `role`.
245    fn is_in_role(&self, role: &str) -> bool {
246        self.current_user()
247            .map(|user| user.is_in_role(role))
248            .unwrap_or(false)
249    }
250
251    /// The identity, or `401 Unauthorized` when the request is anonymous.
252    fn require_user(&self) -> Result<&IdentityUser> {
253        self.current_user().ok_or_else(|| {
254            Error::Unauthorized("authentication required for this endpoint".to_string())
255        })
256    }
257}