fraiseql_core/security/security_context.rs
1//! Security context for runtime authorization
2//!
3//! This module provides the `SecurityContext` struct that flows through the executor,
4//! carrying information about the authenticated user and their permissions.
5//!
6//! The security context is extracted from:
7//! - JWT claims (`user_id` from 'sub', roles from 'roles', etc.)
8//! - HTTP headers (`request_id`, `tenant_id`, etc.)
9//! - Configuration (OAuth provider, scopes, etc.)
10//!
11//! # Architecture
12//!
13//! ```text
14//! HTTP Request with Authorization header
15//! ↓
16//! AuthMiddleware → AuthenticatedUser
17//! ↓
18//! SecurityContext (created from AuthenticatedUser + request metadata)
19//! ↓
20//! Executor (with context available for RLS policy evaluation)
21//! ```
22//!
23//! # RLS Integration
24//!
25//! The `SecurityContext` is passed to `RLSPolicy::evaluate()` to determine what
26//! rows a user can access. Policies are compiled into schema.compiled.json
27//! and evaluated at runtime with the `SecurityContext`.
28
29use std::collections::HashMap;
30
31use chrono::{DateTime, Utc};
32use serde::{Deserialize, Serialize};
33use uuid::Uuid;
34
35use crate::{
36 security::{ActorType, AuthenticatedUser, derive_actor},
37 types::{TenantId, UserId},
38};
39
40/// Extract the user's roles from the (signature-verified) JWT custom claims.
41///
42/// Reads, in order, the scalar `role` claim, the `roles` array, and the
43/// `fraiseql_roles` array, then sorts and de-duplicates. This mirrors the
44/// claim names honoured by `fraiseql_auth::operation_rbac` so the GraphQL
45/// `requires_role` gate and the observer-admin RBAC engine agree on what a
46/// token grants. Without this, `SecurityContext.roles` was always empty and
47/// every `requires_role` operation was unreachable over HTTP (#503).
48fn roles_from_claims(extra_claims: &HashMap<String, serde_json::Value>) -> Vec<String> {
49 let mut roles = Vec::new();
50
51 if let Some(serde_json::Value::String(role)) = extra_claims.get("role") {
52 roles.push(role.clone());
53 }
54
55 for key in ["roles", "fraiseql_roles"] {
56 if let Some(serde_json::Value::Array(values)) = extra_claims.get(key) {
57 roles.extend(values.iter().filter_map(|v| match v {
58 serde_json::Value::String(role) => Some(role.clone()),
59 _ => None,
60 }));
61 }
62 }
63
64 roles.sort();
65 roles.dedup();
66 roles
67}
68
69/// Security context for authorization evaluation.
70///
71/// Carries information about the authenticated user and their permissions
72/// throughout the request lifecycle.
73///
74/// # Fields
75///
76/// - `user_id`: Unique identifier for the authenticated user (from JWT 'sub' claim)
77/// - `roles`: User's roles (e.g., `["admin", "moderator"]`, from JWT 'roles' claim)
78/// - `tenant_id`: Organization/tenant identifier for multi-tenant systems
79/// - `scopes`: OAuth/permission scopes (e.g., `["read:user", "write:post"]`)
80/// - `attributes`: Custom claims from JWT (e.g., department, region, tier)
81/// - `request_id`: Correlation ID for audit logging and tracing
82/// - `ip_address`: Client IP address for geolocation and fraud detection
83/// - `authenticated_at`: When the JWT was issued
84/// - `expires_at`: When the JWT expires
85/// - `issuer`: Token issuer for multi-issuer systems
86/// - `audience`: Token audience for validation
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct SecurityContext {
89 /// User ID (from JWT 'sub' claim)
90 pub user_id: UserId,
91
92 /// User's roles (e.g., `["admin", "moderator"]`)
93 ///
94 /// Extracted from JWT 'roles' claim or derived from other claims.
95 /// Used for role-based access control (RBAC) decisions.
96 pub roles: Vec<String>,
97
98 /// Tenant/organization ID (for multi-tenancy)
99 ///
100 /// When present, RLS policies can enforce tenant isolation.
101 /// Extracted from JWT '`tenant_id`' or X-Tenant-Id header.
102 pub tenant_id: Option<TenantId>,
103
104 /// OAuth/permission scopes
105 ///
106 /// Format: `{action}:{resource}` or `{action}:{type}.{field}`
107 /// Examples:
108 /// - `read:user`
109 /// - `write:post`
110 /// - `read:User.email`
111 /// - `admin:*`
112 ///
113 /// Extracted from JWT 'scope' claim.
114 pub scopes: Vec<String>,
115
116 /// Custom attributes from JWT claims
117 ///
118 /// Arbitrary key-value pairs from JWT payload.
119 /// Examples: "department", "region", "tier", "country"
120 ///
121 /// Used by custom RLS policies that need domain-specific attributes.
122 pub attributes: HashMap<String, serde_json::Value>,
123
124 /// Request correlation ID for audit trails
125 ///
126 /// Extracted from X-Request-Id header or generated.
127 /// Used for tracing and audit logging across services.
128 pub request_id: String,
129
130 /// Client IP address
131 ///
132 /// Extracted from X-Forwarded-For or connection socket.
133 /// Used for geolocation and fraud detection in RLS policies.
134 pub ip_address: Option<String>,
135
136 /// When the JWT was issued
137 pub authenticated_at: DateTime<Utc>,
138
139 /// When the JWT expires
140 pub expires_at: DateTime<Utc>,
141
142 /// Token issuer (for multi-issuer systems)
143 pub issuer: Option<String>,
144
145 /// Token audience (for audience validation)
146 pub audience: Option<String>,
147
148 /// Normalised email address from the JWT `email` claim.
149 ///
150 /// Available as `jwt:email` in session variable mappings for RLS policies.
151 pub email: Option<String>,
152
153 /// Normalised display name from the JWT `name` claim.
154 ///
155 /// Available as `jwt:name` or `jwt:display_name` in session variable mappings.
156 pub display_name: Option<String>,
157}
158
159impl SecurityContext {
160 /// Attribute key under which the delegated user's UUID is carried (string
161 /// form), for an agent request acting on behalf of a human. Read back via
162 /// [`acting_for`](Self::acting_for) (#390).
163 pub const ACTING_FOR_ATTRIBUTE: &'static str = "fraiseql.acting_for";
164 /// Attribute key under which the request's [`ActorType`] is carried (the
165 /// `snake_case` token), derived at [`from_user`](Self::from_user) and read
166 /// back via [`actor_type`](Self::actor_type) (#390).
167 pub const ACTOR_TYPE_ATTRIBUTE: &'static str = "fraiseql.actor_type";
168 /// Attribute key under which the originating request's full W3C trace context
169 /// is carried (a JSON object), used to populate the change-log `trace_context`
170 /// JSONB column (#375).
171 pub const TRACE_CONTEXT_ATTRIBUTE: &'static str = "fraiseql.trace_context";
172 /// Attribute key under which the originating request's W3C trace id is
173 /// stamped. Set by the server's request pipeline from the inbound
174 /// `traceparent` header; read back via [`trace_id`](Self::trace_id).
175 pub const TRACE_ID_ATTRIBUTE: &'static str = "fraiseql.trace_id";
176
177 /// Create a security context from an authenticated user and request metadata.
178 ///
179 /// # Arguments
180 ///
181 /// * `user` - Authenticated user from JWT validation
182 /// * `request_id` - Correlation ID for this request
183 ///
184 /// # Example
185 ///
186 /// ```no_run
187 /// // Requires: a live AuthenticatedUser from JWT validation.
188 /// // See: tests/integration/ for runnable examples.
189 /// # use fraiseql_core::security::SecurityContext;
190 /// # use fraiseql_core::security::AuthenticatedUser;
191 /// # let authenticated_user: AuthenticatedUser = panic!("example");
192 /// let context = SecurityContext::from_user(&authenticated_user, "req-123".to_string());
193 /// ```
194 #[must_use]
195 pub fn from_user(user: &AuthenticatedUser, request_id: String) -> Self {
196 // Classify the actor from the (signature-verified) JWT material at
197 // construction time, so every auth path (OIDC, HS256, gRPC, MCP) that
198 // builds a context from a user gets it. The API-key path overrides to
199 // ServiceAccount at its own construction site (#390).
200 let (actor_type, acting_for) =
201 derive_actor(user.user_id.as_str(), &user.scopes, &user.extra_claims);
202 SecurityContext {
203 user_id: user.user_id.clone(),
204 roles: roles_from_claims(&user.extra_claims),
205 tenant_id: None,
206 scopes: user.scopes.clone(),
207 attributes: HashMap::new(),
208 request_id,
209 ip_address: None,
210 authenticated_at: Utc::now(),
211 expires_at: user.expires_at,
212 issuer: None,
213 audience: None,
214 email: user.email.clone(),
215 display_name: user.display_name.clone(),
216 }
217 .with_actor_type(actor_type)
218 .with_acting_for(acting_for)
219 }
220
221 /// Check if the user has a specific role.
222 ///
223 /// # Arguments
224 ///
225 /// * `role` - Role name to check (e.g., "admin", "moderator")
226 ///
227 /// # Returns
228 ///
229 /// `true` if the user has the specified role, `false` otherwise.
230 #[must_use]
231 pub fn has_role(&self, role: &str) -> bool {
232 self.roles.iter().any(|r| r == role)
233 }
234
235 /// Check if the user has a specific scope.
236 ///
237 /// Supports wildcards: `admin:*` matches any admin scope.
238 ///
239 /// # Arguments
240 ///
241 /// * `scope` - Scope to check (e.g., "read:user", "write:post")
242 ///
243 /// # Returns
244 ///
245 /// `true` if the user has the specified scope, `false` otherwise.
246 #[must_use]
247 pub fn has_scope(&self, scope: &str) -> bool {
248 self.scopes.iter().any(|s| {
249 if s == scope {
250 return true;
251 }
252 // Support wildcard matching: "admin:*" matches "admin:read"
253 if s.ends_with(':') {
254 scope.starts_with(s)
255 } else if s.ends_with('*') {
256 let prefix = &s[..s.len() - 1];
257 scope.starts_with(prefix)
258 } else {
259 false
260 }
261 })
262 }
263
264 /// Get a custom attribute from the JWT claims.
265 ///
266 /// # Arguments
267 ///
268 /// * `key` - Attribute name
269 ///
270 /// # Returns
271 ///
272 /// The attribute value if present, `None` otherwise.
273 #[must_use]
274 pub fn get_attribute(&self, key: &str) -> Option<&serde_json::Value> {
275 self.attributes.get(key)
276 }
277
278 /// The originating request's W3C trace id, when the server stamped one from
279 /// the inbound `traceparent` header.
280 ///
281 /// Used to populate the change-log `trace_id` column so an outbox row links
282 /// back to its distributed trace (#375); the #392 perf tooling surfaces it as
283 /// the investigation handle. `None` when the request carried no trace context.
284 #[must_use]
285 pub fn trace_id(&self) -> Option<&str> {
286 self.attributes
287 .get(Self::TRACE_ID_ATTRIBUTE)
288 .and_then(serde_json::Value::as_str)
289 }
290
291 /// Stamp the originating request's W3C trace id onto the context (carried in
292 /// `attributes`). Read back via [`trace_id`](Self::trace_id).
293 #[must_use]
294 pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
295 self.attributes.insert(
296 Self::TRACE_ID_ATTRIBUTE.to_string(),
297 serde_json::Value::String(trace_id.into()),
298 );
299 self
300 }
301
302 /// The originating request's full W3C trace context (a JSON object), when the
303 /// server stamped one from the inbound `traceparent`/`tracestate` headers.
304 ///
305 /// Used to populate the change-log `trace_context` JSONB column so an outbox
306 /// row carries enough to re-propagate the distributed trace (#375). `None` when
307 /// the request carried no valid trace context.
308 #[must_use]
309 pub fn trace_context(&self) -> Option<&serde_json::Value> {
310 self.attributes.get(Self::TRACE_CONTEXT_ATTRIBUTE)
311 }
312
313 /// Stamp the originating request's full W3C trace context (a JSON object) onto
314 /// the context (carried in `attributes`). Read back via
315 /// [`trace_context`](Self::trace_context).
316 #[must_use]
317 pub fn with_trace_context(mut self, trace_context: serde_json::Value) -> Self {
318 self.attributes.insert(Self::TRACE_CONTEXT_ATTRIBUTE.to_string(), trace_context);
319 self
320 }
321
322 /// The request's actor classification (#390). Derived at
323 /// [`from_user`](Self::from_user); [`ActorType::HumanUser`] when unset (e.g. a
324 /// context built directly without derivation).
325 #[must_use]
326 pub fn actor_type(&self) -> ActorType {
327 self.attributes
328 .get(Self::ACTOR_TYPE_ATTRIBUTE)
329 .and_then(serde_json::Value::as_str)
330 .and_then(ActorType::from_token)
331 .unwrap_or_default()
332 }
333
334 /// Stamp the request's [`ActorType`] onto the context (carried in
335 /// `attributes`). Read back via [`actor_type`](Self::actor_type).
336 #[must_use]
337 pub fn with_actor_type(mut self, actor_type: ActorType) -> Self {
338 self.attributes.insert(
339 Self::ACTOR_TYPE_ATTRIBUTE.to_string(),
340 serde_json::Value::String(actor_type.as_str().to_string()),
341 );
342 self
343 }
344
345 /// The delegated user (the human a delegated agent acts for), when the request
346 /// carried an RFC 8693 `act` claim (#390). `None` for a non-delegated request,
347 /// or when the underlying subject was not UUID-shaped.
348 #[must_use]
349 pub fn acting_for(&self) -> Option<Uuid> {
350 self.attributes
351 .get(Self::ACTING_FOR_ATTRIBUTE)
352 .and_then(serde_json::Value::as_str)
353 .and_then(|s| Uuid::parse_str(s).ok())
354 }
355
356 /// Stamp the delegated user's UUID onto the context (carried in `attributes`).
357 /// `None` removes any prior stamp. Read back via [`acting_for`](Self::acting_for).
358 #[must_use]
359 pub fn with_acting_for(mut self, acting_for: Option<Uuid>) -> Self {
360 match acting_for {
361 Some(uuid) => {
362 self.attributes.insert(
363 Self::ACTING_FOR_ATTRIBUTE.to_string(),
364 serde_json::Value::String(uuid.to_string()),
365 );
366 },
367 None => {
368 self.attributes.remove(Self::ACTING_FOR_ATTRIBUTE);
369 },
370 }
371 self
372 }
373
374 /// Check if the token has expired.
375 ///
376 /// # Returns
377 ///
378 /// `true` if the JWT has expired, `false` otherwise.
379 #[must_use]
380 pub fn is_expired(&self) -> bool {
381 self.expires_at <= Utc::now()
382 }
383
384 /// Get time until expiry in seconds.
385 ///
386 /// # Returns
387 ///
388 /// Seconds until JWT expiry, negative if already expired.
389 #[must_use]
390 pub fn ttl_secs(&self) -> i64 {
391 (self.expires_at - Utc::now()).num_seconds()
392 }
393
394 /// Check if the user is an admin.
395 ///
396 /// # Returns
397 ///
398 /// `true` if the user has the "admin" role, `false` otherwise.
399 #[must_use]
400 pub fn is_admin(&self) -> bool {
401 self.has_role("admin")
402 }
403
404 /// Check if the context has a tenant ID (multi-tenancy enabled).
405 ///
406 /// # Returns
407 ///
408 /// `true` if `tenant_id` is present, `false` otherwise.
409 #[must_use]
410 pub const fn is_multi_tenant(&self) -> bool {
411 self.tenant_id.is_some()
412 }
413
414 /// Set or override a role (for testing or runtime role modification).
415 #[must_use]
416 pub fn with_role(mut self, role: String) -> Self {
417 self.roles.push(role);
418 self
419 }
420
421 /// Set or override scopes (for testing or runtime permission modification).
422 #[must_use]
423 pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
424 self.scopes = scopes;
425 self
426 }
427
428 /// Set tenant ID (for multi-tenancy).
429 pub fn with_tenant(mut self, tenant_id: impl Into<TenantId>) -> Self {
430 self.tenant_id = Some(tenant_id.into());
431 self
432 }
433
434 /// Set a custom attribute (for testing or runtime attribute addition).
435 #[must_use]
436 pub fn with_attribute(mut self, key: String, value: serde_json::Value) -> Self {
437 self.attributes.insert(key, value);
438 self
439 }
440
441 /// Check if user can access a field based on role definitions.
442 ///
443 /// Takes a required scope and checks if any of the user's roles grant that scope.
444 ///
445 /// # Arguments
446 ///
447 /// * `security_config` - Security config from compiled schema with role definitions
448 /// * `required_scope` - Scope required to access the field (e.g., "read:User.email")
449 ///
450 /// # Returns
451 ///
452 /// `true` if user's roles grant the required scope, `false` otherwise.
453 ///
454 /// # Example
455 ///
456 /// ```no_run
457 /// // Requires: a SecurityConfig from a compiled schema.
458 /// // See: tests/integration/ for runnable examples.
459 /// # use fraiseql_core::security::SecurityContext;
460 /// # use fraiseql_core::schema::SecurityConfig;
461 /// # let context: SecurityContext = panic!("example");
462 /// # let config: SecurityConfig = panic!("example");
463 /// let can_access = context.can_access_scope(&config, "read:User.email");
464 /// ```
465 #[must_use]
466 pub fn can_access_scope(
467 &self,
468 security_config: &crate::schema::SecurityConfig,
469 required_scope: &str,
470 ) -> bool {
471 // Check if any of user's roles grant this scope
472 self.roles
473 .iter()
474 .any(|role_name| security_config.role_has_scope(role_name, required_scope))
475 }
476}
477
478impl std::fmt::Display for SecurityContext {
479 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
480 write!(
481 f,
482 "SecurityContext(user_id={}, roles={:?}, scopes={}, tenant={:?})",
483 self.user_id,
484 self.roles,
485 self.scopes.len(),
486 self.tenant_id
487 )
488 }
489}