fraiseql-auth 2.3.2

Authentication, authorization, and session management for FraiseQL
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
406
407
408
409
//! Audit logging for security-critical authentication operations.
//!
//! Tracks all secret access, authentication events, and security decisions.
//! See the [`AuditLogger`] trait and [`StructuredAuditLogger`] for usage.
// # Bounds Documentation
//
// This module enforces strict size bounds on all audit log entries to prevent
// memory exhaustion attacks and ensure predictable performance.
//
// ## Field Size Limits
//
// | Field | Max Size | Reason |
// |-------|----------|--------|
// | subject (user ID) | 256 bytes | User IDs rarely exceed this; prevents allocation bloat |
// | operation | 50 bytes | Fixed set of operations (validate, create, refresh, revoke, etc.) |
// | error_message | 1 KB (1024 bytes) | Error messages should be brief; prevents log spam |
// | context | 2 KB (2048 bytes) | Additional context data; rarely needed for detailed info |
// | **Total per entry** | **~4 KB** | Reasonable memory footprint for audit trail |
//
// ## In-Memory Bounds
//
// - **Maximum audit entries in memory**: 10,000 entries (safe for servers with 2GB+ RAM)
// - **Memory per entry**: ~4 KB (structured data + strings)
// - **Total memory for full buffer**: ~40 MB (acceptable overhead)
//
// ## Thread Safety
//
// All audit logger implementations MUST be `Send + Sync` and handle concurrent
// access safely. The `OnceLock` pattern for global logger ensures thread-safe
// initialization.
//
// ## Production Recommendations
//
// 1. **Database-Backed Logging**: Deploy with database-backed audit logger for production to avoid
//    memory limits entirely.
// 2. **Retention Policies**: Implement automated cleanup of old entries in in-memory loggers (e.g.,
//    entries older than 24 hours).
// 3. **Sampling**: For high-throughput environments, consider sampling less critical events.
// 4. **Monitoring**: Alert if audit log buffer reaches 80% capacity.
//
// See also: `crate::security::ComplianceAuditLogger` for database-backed logging.

use std::sync::Arc;

use serde::{Deserialize, Serialize};
use tracing::{info, warn};

/// Bounds constants for audit log entries
pub mod bounds {
    /// Maximum length for subject (user ID) field
    pub const MAX_SUBJECT_LEN: usize = 256;

    /// Maximum length for operation field
    pub const MAX_OPERATION_LEN: usize = 50;

    /// Maximum length for error message field
    pub const MAX_ERROR_MESSAGE_LEN: usize = 1024;

    /// Maximum length for context field
    pub const MAX_CONTEXT_LEN: usize = 2048;

    /// Maximum number of audit entries to keep in memory
    pub const MAX_ENTRIES_IN_MEMORY: usize = 10_000;

    /// Estimated memory per entry (used for capacity planning)
    pub const BYTES_PER_ENTRY: usize = 4096;
}

/// Discriminates the kind of security event recorded in an [`AuditEntry`].
///
/// Each variant maps directly to one of the operations performed by the auth layer.
/// String representations (via [`AuditEventType::as_str`]) are stable across releases
/// and are the values written to log sinks and compliance audit trails.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AuditEventType {
    /// A JWT was checked for validity (signature, expiry, claims).
    JwtValidation,
    /// A JWT access token was refreshed using a refresh token.
    JwtRefresh,
    /// OIDC client credentials were accessed from the secret store.
    OidcCredentialAccess,
    /// An authorization code was exchanged for OIDC tokens.
    OidcTokenExchange,
    /// A new session token pair (access + refresh) was issued.
    SessionTokenCreated,
    /// A session token was validated against the session store.
    SessionTokenValidation,
    /// A session token was explicitly revoked (logout).
    SessionTokenRevoked,
    /// An OAuth CSRF state token was generated for a new authorization flow.
    CsrfStateGenerated,
    /// An incoming OAuth callback's `state` parameter was validated.
    CsrfStateValidated,
    /// An OAuth authorization flow was initiated (`/auth/start`).
    OauthStart,
    /// The OAuth provider redirected back (`/auth/callback`).
    OauthCallback,
    /// An authentication flow completed successfully.
    AuthSuccess,
    /// An authentication attempt failed.
    AuthFailure,
    /// An authorization check denied access (RLS block, RBAC field denial, scope mismatch).
    ///
    /// Authentication succeeded, but the authenticated principal lacks the
    /// required permissions for the requested resource.  This event is emitted
    /// for compliance (SOC 2) audit trails and is distinct from `AuthFailure`,
    /// which covers failed authentication.
    AuthorizationDenied,
}

impl AuditEventType {
    /// Return a stable, lowercase snake_case string representation of this event type.
    ///
    /// These strings are written to log sinks and compliance systems and will not
    /// change between releases.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            AuditEventType::JwtValidation => "jwt_validation",
            AuditEventType::JwtRefresh => "jwt_refresh",
            AuditEventType::OidcCredentialAccess => "oidc_credential_access",
            AuditEventType::OidcTokenExchange => "oidc_token_exchange",
            AuditEventType::SessionTokenCreated => "session_token_created",
            AuditEventType::SessionTokenValidation => "session_token_validation",
            AuditEventType::SessionTokenRevoked => "session_token_revoked",
            AuditEventType::CsrfStateGenerated => "csrf_state_generated",
            AuditEventType::CsrfStateValidated => "csrf_state_validated",
            AuditEventType::OauthStart => "oauth_start",
            AuditEventType::OauthCallback => "oauth_callback",
            AuditEventType::AuthSuccess => "auth_success",
            AuditEventType::AuthFailure => "auth_failure",
            AuditEventType::AuthorizationDenied => "authorization_denied",
        }
    }
}

/// Classifies the secret credential that was accessed or operated on.
///
/// Used in [`AuditEntry`] to identify the category of credential involved in a
/// security event.  This enables compliance queries such as "show all events
/// involving client secrets" or "which refresh tokens were revoked today".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum SecretType {
    /// A JWT access token (short-lived bearer credential).
    JwtToken,
    /// A session token issued by FraiseQL's session store.
    SessionToken,
    /// An OAuth 2.0 client secret used for provider authentication.
    ClientSecret,
    /// A long-lived refresh token used to obtain new access tokens.
    RefreshToken,
    /// A one-time authorization code returned by the OAuth provider.
    AuthorizationCode,
    /// An OAuth `state` token used to carry CSRF and flow metadata.
    StateToken,
    /// A CSRF token used to bind a user-agent session to an OAuth flow.
    CsrfToken,
}

impl SecretType {
    /// Return a stable, lowercase snake_case string representation of this secret type.
    ///
    /// Written to log sinks and compliance systems; will not change between releases.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            SecretType::JwtToken => "jwt_token",
            SecretType::SessionToken => "session_token",
            SecretType::ClientSecret => "client_secret",
            SecretType::RefreshToken => "refresh_token",
            SecretType::AuthorizationCode => "authorization_code",
            SecretType::StateToken => "state_token",
            SecretType::CsrfToken => "csrf_token",
        }
    }
}

/// Audit log entry
///
/// # Size Bounds
///
/// To prevent memory exhaustion and ensure predictable performance, each field
/// is bounded in size:
///
/// - `subject`: Max 256 bytes (see `bounds::MAX_SUBJECT_LEN`)
/// - `operation`: Max 50 bytes (see `bounds::MAX_OPERATION_LEN`)
/// - `error_message`: Max 1 KB (see `bounds::MAX_ERROR_MESSAGE_LEN`)
/// - `context`: Max 2 KB (see `bounds::MAX_CONTEXT_LEN`)
/// - **Total per entry**: ~4 KB
///
/// # Thread Safety
///
/// This struct is immutable once created and `Send + Sync`, making it safe to
/// pass between threads. Audit loggers that implement `AuditLogger` trait are
/// responsible for thread-safe storage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    /// Event type (jwt_validation, oauth_callback, etc.)
    pub event_type:    AuditEventType,
    /// Type of secret accessed (jwt_token, session_token, etc.)
    pub secret_type:   SecretType,
    /// Subject (user ID, service account, etc.) - None for anonymous
    /// Max 256 bytes per `bounds::MAX_SUBJECT_LEN`
    pub subject:       Option<String>,
    /// Operation performed (validate, create, revoke, etc.)
    /// Max 50 bytes per `bounds::MAX_OPERATION_LEN`
    pub operation:     String,
    /// Whether the operation succeeded
    pub success:       bool,
    /// Error message if operation failed (user-safe message)
    /// Max 1 KB per `bounds::MAX_ERROR_MESSAGE_LEN`
    pub error_message: Option<String>,
    /// Additional context
    /// Max 2 KB per `bounds::MAX_CONTEXT_LEN`
    pub context:       Option<String>,
    /// HMAC-SHA256 chain hash for tamper detection (64 hex chars).
    ///
    /// Each entry's hash depends on all previous entries, making retroactive
    /// tampering detectable. `None` when tamper-evident logging is disabled.
    /// Verify with [`crate::audit::chain::verify_chain`].
    pub chain_hash:    Option<String>,
}

/// Audit logger trait - allows different implementations (structured logs, database, syslog, etc.)
///
/// # Implementation Requirements
///
/// - **Thread Safety**: All implementations must be `Send + Sync` and safe for concurrent access
///   from multiple threads.
/// - **Bounds Enforcement**: Implementations MAY enforce the bounds defined in this module, or
///   delegate to a database backend that handles large-scale logging.
/// - **Availability**: Should not block request handling; consider async/buffered implementations
///   for performance.
/// - **Error Handling**: Should never panic; swallow errors and log them via tracing instead.
///
/// # Memory Considerations
///
/// - **In-memory implementations**: Should limit to `bounds::MAX_ENTRIES_IN_MEMORY` to prevent
///   unbounded growth.
/// - **Production deployments**: Should use database-backed implementations
///   (`ComplianceAuditLogger`) for scalability and retention.
pub trait AuditLogger: Send + Sync {
    /// Log an audit entry
    ///
    /// Implementations should ensure:
    /// - No panics (errors logged via tracing)
    /// - Thread-safe access to backing storage
    /// - Bounded memory usage (for in-memory implementations)
    fn log_entry(&self, entry: AuditEntry);

    /// Convenience method for successful operations
    fn log_success(
        &self,
        event_type: AuditEventType,
        secret_type: SecretType,
        subject: Option<String>,
        operation: &str,
    ) {
        self.log_entry(AuditEntry {
            event_type,
            secret_type,
            subject,
            operation: operation.to_string(),
            success: true,
            error_message: None,
            context: None,
            chain_hash: None,
        });
    }

    /// Convenience method for failed operations
    fn log_failure(
        &self,
        event_type: AuditEventType,
        secret_type: SecretType,
        subject: Option<String>,
        operation: &str,
        error: &str,
    ) {
        self.log_entry(AuditEntry {
            event_type,
            secret_type,
            subject,
            operation: operation.to_string(),
            success: false,
            error_message: Some(error.to_string()),
            context: None,
            chain_hash: None,
        });
    }
}

/// Audit logger that emits structured log records via [`tracing`].
///
/// Successful operations are logged at `INFO` level; failures at `WARN` level.
/// All fields of the [`AuditEntry`] are included as tracing fields so that
/// log aggregators (Loki, Elasticsearch, Splunk, etc.) can filter and query them.
///
/// This is the default logger used when [`init_audit_logger`] is never called.
/// For production compliance requirements, consider a database-backed logger.
pub struct StructuredAuditLogger;

impl StructuredAuditLogger {
    /// Create a new `StructuredAuditLogger`.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl Default for StructuredAuditLogger {
    fn default() -> Self {
        Self::new()
    }
}

impl AuditLogger for StructuredAuditLogger {
    fn log_entry(&self, entry: AuditEntry) {
        if entry.success {
            info!(
                event_type = entry.event_type.as_str(),
                secret_type = entry.secret_type.as_str(),
                subject = ?entry.subject,
                operation = entry.operation,
                context = ?entry.context,
                "Security event: successful operation"
            );
        } else {
            warn!(
                event_type = entry.event_type.as_str(),
                secret_type = entry.secret_type.as_str(),
                subject = ?entry.subject,
                operation = entry.operation,
                error = ?entry.error_message,
                context = ?entry.context,
                "Security event: failed operation"
            );
        }
    }
}

/// Global audit logger instance.
///
/// Initialized once per process via [`init_audit_logger`]. Subsequent calls to
/// `init_audit_logger` are silently ignored — the first caller wins.
///
/// **Test isolation**: In a test binary all tests share this singleton. The first
/// test that calls `init_audit_logger` sets the logger for the entire process; later
/// tests see that logger regardless of what they pass. Do not assert on specific
/// logger state across test functions in the same binary. Use
/// [`get_audit_logger`] to read the current value.
pub static AUDIT_LOGGER: std::sync::OnceLock<Arc<dyn AuditLogger>> = std::sync::OnceLock::new();

/// Initialize the global audit logger
pub fn init_audit_logger(logger: Arc<dyn AuditLogger>) {
    let _ = AUDIT_LOGGER.set(logger);
}

/// Get the global audit logger (defaults to structured logging if not initialized)
pub fn get_audit_logger() -> Arc<dyn AuditLogger> {
    AUDIT_LOGGER.get_or_init(|| Arc::new(StructuredAuditLogger::new())).clone()
}

/// Extension trait that adds audit logging to any `Result<T, E>`.
///
/// Calling `.audit_log(...)` on a result logs the success or failure via the
/// global [`AuditLogger`] and then returns the result unchanged.  This allows
/// audit logging to be inserted into call chains without altering the return type:
///
/// ```ignore
/// let claims = validator
///     .validate(token, &public_key)
///     .audit_log(AuditEventType::JwtValidation, SecretType::JwtToken, None, "validate")?;
/// ```
pub trait AuditExt<T, E> {
    /// Log success or failure of a result
    ///
    /// # Errors
    ///
    /// Returns the original error `E` unchanged after logging the failure.
    fn audit_log(
        self,
        event_type: AuditEventType,
        secret_type: SecretType,
        subject: Option<String>,
        operation: &str,
    ) -> Result<T, E>;
}

impl<T, E: std::fmt::Display> AuditExt<T, E> for Result<T, E> {
    fn audit_log(
        self,
        event_type: AuditEventType,
        secret_type: SecretType,
        subject: Option<String>,
        operation: &str,
    ) -> Result<T, E> {
        let logger = get_audit_logger();
        match &self {
            Ok(_) => logger.log_success(event_type, secret_type, subject, operation),
            Err(e) => {
                logger.log_failure(event_type, secret_type, subject, operation, &e.to_string());
            },
        }
        self
    }
}