fraiseql-auth 2.6.0

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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! HTTP handlers for the built-in authentication endpoints (`/auth/start`,
//! `/auth/callback`, `/auth/refresh`, `/auth/logout`).
use std::{fmt, net::SocketAddr, sync::Arc};

use axum::{
    Json,
    extract::{ConnectInfo, Query, State},
    http::StatusCode,
    response::IntoResponse,
};
use serde::{Deserialize, Serialize};

use crate::{
    audit::logger::{AuditEventType, SecretType, get_audit_logger},
    error::{AuthError, Result},
    provider::OAuthProvider,
    rate_limiting::RateLimiters,
    session::SessionStore,
    state_store::StateStore,
};

/// AuthState holds the auth configuration and backends
#[derive(Clone)]
pub struct AuthState {
    /// OAuth provider
    pub oauth_provider: Arc<dyn OAuthProvider>,
    /// Session store backend
    pub session_store:  Arc<dyn SessionStore>,
    /// CSRF state store backend (in-memory for single-instance, Redis for distributed)
    pub state_store:    Arc<dyn StateStore>,
    /// Rate limiters for auth endpoints (per-IP based)
    pub rate_limiters:  Arc<RateLimiters>,
}

/// Request body for auth/start endpoint
#[derive(Debug, Deserialize)]
pub struct AuthStartRequest {
    /// Optional provider name (for multi-provider setups)
    pub provider: Option<String>,
}

/// Response body for the `POST /auth/start` endpoint.
#[derive(Debug, Serialize)]
pub struct AuthStartResponse {
    /// Authorization URL to redirect user to
    pub authorization_url: String,
}

/// Query parameters for auth/callback endpoint
#[derive(Debug, Deserialize)]
pub struct AuthCallbackQuery {
    /// Authorization code from provider
    pub code:              String,
    /// State parameter for CSRF protection
    pub state:             String,
    /// Error from provider if present
    pub error:             Option<String>,
    /// Error description from provider
    pub error_description: Option<String>,
}

/// Response body for the `GET /auth/callback` endpoint.
///
/// Returned after a successful OAuth authorization-code exchange.
/// In a production browser-facing flow, the server would instead redirect
/// the user agent to the frontend application with tokens in a URL fragment;
/// this JSON form is suitable for API clients and testing.
///
/// # Debug redaction
///
/// `Debug` is implemented manually so the `access_token` and `refresh_token`
/// fields are never written to logs. Calling `{:?}` yields placeholders
/// (`"<redacted>"` / `Some("<redacted>")` / `None`) for both fields.
#[derive(Serialize)]
#[non_exhaustive]
#[doc(hidden)] // Internal-pub: HTTP response body for /auth/callback; serialized to JSON for clients. Adopters consume the JSON wire format, not the Rust type.
pub struct AuthCallbackResponse {
    /// Access token for API requests
    pub access_token:  String,
    /// Optional refresh token
    pub refresh_token: Option<String>,
    /// Token type (usually "Bearer")
    pub token_type:    String,
    /// Time in seconds until token expires
    pub expires_in:    u64,
}

impl fmt::Debug for AuthCallbackResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // SECURITY: never write the raw access_token/refresh_token to Debug
        // output — they would otherwise leak into structured logs via any
        // `debug!(?resp)` call. See IMPROVEMENTS.md F045.
        f.debug_struct("AuthCallbackResponse")
            .field("access_token", &"<redacted>")
            .field("refresh_token", &self.refresh_token.as_ref().map(|_| "<redacted>"))
            .field("token_type", &self.token_type)
            .field("expires_in", &self.expires_in)
            .finish()
    }
}

impl AuthCallbackResponse {
    /// Creates a new `AuthCallbackResponse`.
    #[must_use]
    pub const fn new(
        access_token: String,
        refresh_token: Option<String>,
        token_type: String,
        expires_in: u64,
    ) -> Self {
        Self {
            access_token,
            refresh_token,
            token_type,
            expires_in,
        }
    }
}

/// Request body for auth/refresh endpoint
#[derive(Debug, Deserialize)]
pub struct AuthRefreshRequest {
    /// Refresh token to exchange for new access token
    pub refresh_token: String,
}

/// Response body for the `POST /auth/refresh` endpoint.
///
/// # Debug redaction
///
/// `Debug` is implemented manually so the `access_token` field is never
/// written to logs. Calling `{:?}` yields `"<redacted>"` for the token value.
#[derive(Serialize)]
pub struct AuthRefreshResponse {
    /// New access token
    pub access_token: String,
    /// Token type
    pub token_type:   String,
    /// Time in seconds until token expires
    pub expires_in:   u64,
}

impl fmt::Debug for AuthRefreshResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // SECURITY: never write the raw access_token to Debug output. See
        // IMPROVEMENTS.md F045.
        f.debug_struct("AuthRefreshResponse")
            .field("access_token", &"<redacted>")
            .field("token_type", &self.token_type)
            .field("expires_in", &self.expires_in)
            .finish()
    }
}

/// Request body for auth/logout endpoint
#[derive(Debug, Deserialize)]
pub struct AuthLogoutRequest {
    /// Refresh token to revoke
    pub refresh_token: Option<String>,
}

/// POST /auth/start - Initiate OAuth flow
///
/// Returns an authorization URL that the client should redirect the user to.
///
/// # Rate Limiting
///
/// This endpoint is rate-limited per IP address to prevent brute-force attacks.
/// The limit is configurable via FRAISEQL_AUTH_START_MAX_REQUESTS and
/// FRAISEQL_AUTH_START_WINDOW_SECS environment variables.
///
/// # Errors
///
/// Returns `AuthError::RateLimited` if the per-IP rate limit is exceeded.
/// Returns `AuthError::SystemTimeError` if the system clock is unavailable.
/// Returns `AuthError` if the state store write fails.
pub async fn auth_start(
    State(state): State<AuthState>,
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    Json(req): Json<AuthStartRequest>,
) -> Result<Json<AuthStartResponse>> {
    // SECURITY: Check rate limiting for auth/start endpoint (per IP)
    let client_ip = addr.ip().to_string();
    if state.rate_limiters.auth_start.check(&client_ip).is_err() {
        return Err(AuthError::RateLimited {
            retry_after_secs: state.rate_limiters.auth_start.clone_config().window_secs,
        });
    }

    // Generate random state for CSRF protection using cryptographically secure RNG
    let state_value = generate_secure_state();

    // Get current time with explicit error handling (not unwrap_or_default)
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|_| AuthError::SystemTimeError {
            message: "Failed to get current system time".to_string(),
        })?
        .as_secs();

    // Store state with expiry (10 minutes)
    let expiry = now + 600;

    // SECURITY: Store state using configurable backend (in-memory or distributed)
    let provider = req.provider.unwrap_or_else(|| "default".to_string());
    state.state_store.store(state_value.clone(), provider, expiry).await?;

    // Generate authorization URL
    let authorization_url = state.oauth_provider.authorization_url(&state_value);

    Ok(Json(AuthStartResponse { authorization_url }))
}

/// GET /auth/callback - OAuth provider redirects here
///
/// Exchanges the authorization code for tokens and creates a session.
///
/// # Rate Limiting
///
/// This endpoint is rate-limited per IP address to prevent brute-force attacks.
/// The limit is configurable via FRAISEQL_AUTH_CALLBACK_MAX_REQUESTS and
/// FRAISEQL_AUTH_CALLBACK_WINDOW_SECS environment variables.
///
/// # Errors
///
/// Returns `AuthError::RateLimited` if the per-IP rate limit is exceeded.
/// Returns `AuthError::OAuthError` if the provider returned an error.
/// Returns `AuthError::InvalidState` if the CSRF state token is expired or invalid.
/// Returns `AuthError` if the token exchange or session creation fails.
pub async fn auth_callback(
    State(state): State<AuthState>,
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    Query(query): Query<AuthCallbackQuery>,
) -> Result<impl IntoResponse> {
    // SECURITY: Check rate limiting for auth/callback endpoint (per IP)
    let client_ip = addr.ip().to_string();
    if state.rate_limiters.auth_callback.check(&client_ip).is_err() {
        return Err(AuthError::RateLimited {
            retry_after_secs: state.rate_limiters.auth_callback.clone_config().window_secs,
        });
    }

    // SECURITY: Reject oversized code/state before any parsing or store access.
    validate_auth_input_len(&query.code, MAX_AUTH_CODE_BYTES, "code")?;
    validate_auth_input_len(&query.state, MAX_STATE_BYTES, "state")?;

    // Check for provider error
    if let Some(error) = query.error {
        let audit_logger = get_audit_logger();
        audit_logger.log_failure(
            AuditEventType::OauthCallback,
            SecretType::AuthorizationCode,
            None,
            "exchange",
            &error,
        );
        return Err(AuthError::OAuthError {
            message: format!("{}: {}", error, query.error_description.unwrap_or_default()),
        });
    }

    // SECURITY: Validate state using configurable backend (distributed-safe)
    let (_provider_name, expiry) = state.state_store.retrieve(&query.state).await?;

    // Check state expiry with explicit error handling
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|_| AuthError::SystemTimeError {
            message: "Failed to get current system time".to_string(),
        })?
        .as_secs();

    if now > expiry {
        let audit_logger = get_audit_logger();
        audit_logger.log_failure(
            AuditEventType::CsrfStateValidated,
            SecretType::StateToken,
            None,
            "validate",
            "State token expired",
        );
        return Err(AuthError::InvalidState);
    }

    // Audit log: CSRF state validation success
    let audit_logger = get_audit_logger();
    audit_logger.log_success(
        AuditEventType::CsrfStateValidated,
        SecretType::StateToken,
        None,
        "validate",
    );

    // Exchange code for tokens
    let token_response = state.oauth_provider.exchange_code(&query.code).await?;

    // Audit log: Token exchange success
    let audit_logger = get_audit_logger();
    audit_logger.log_success(
        AuditEventType::OauthCallback,
        SecretType::AuthorizationCode,
        None,
        "exchange",
    );

    // Get user info
    let user_info = state.oauth_provider.user_info(&token_response.access_token).await?;

    // Create session (expires in 7 days)
    let expires_at = now + (7 * 24 * 60 * 60);
    let session_tokens = state.session_store.create_session(&user_info.id, expires_at).await?;

    // Audit log: Session token created
    let audit_logger = get_audit_logger();
    audit_logger.log_success(
        AuditEventType::SessionTokenCreated,
        SecretType::SessionToken,
        Some(user_info.id.clone()),
        "create",
    );

    // Audit log: Auth success
    let audit_logger = get_audit_logger();
    audit_logger.log_success(
        AuditEventType::AuthSuccess,
        SecretType::SessionToken,
        Some(user_info.id),
        "oauth_flow",
    );

    let response = AuthCallbackResponse {
        access_token:  session_tokens.access_token,
        refresh_token: Some(session_tokens.refresh_token),
        token_type:    "Bearer".to_string(),
        expires_in:    session_tokens.expires_in,
    };

    // In a real app, would redirect to frontend with tokens in URL fragment
    // For now, return JSON
    Ok(Json(response))
}

/// POST /auth/refresh - Refresh access token
///
/// Uses refresh token to obtain a new access token.
///
/// # Rate Limiting
///
/// This endpoint is rate-limited per user ID to prevent token refresh attacks.
/// The limit is configurable via FRAISEQL_AUTH_REFRESH_MAX_REQUESTS and
/// FRAISEQL_AUTH_REFRESH_WINDOW_SECS environment variables.
///
/// # Errors
///
/// Returns `AuthError::TokenExpired` if the session has expired.
/// Returns `AuthError::RateLimited` if the per-user rate limit is exceeded.
/// Returns `AuthError::Internal` if JWT signing is not yet configured.
pub async fn auth_refresh(
    State(state): State<AuthState>,
    Json(req): Json<AuthRefreshRequest>,
) -> Result<Json<AuthRefreshResponse>> {
    use crate::session::hash_token;

    // SECURITY: Reject oversized refresh tokens before hitting the session store.
    validate_auth_input_len(&req.refresh_token, MAX_REFRESH_TOKEN_BYTES, "refresh_token")?;

    // Validate refresh token exists in session store
    let token_hash = hash_token(&req.refresh_token);
    let session = state.session_store.get_session(&token_hash).await?;

    // SECURITY: Reject expired sessions before any further processing.
    // Without this check, a stolen refresh token from an expired session
    // could be used indefinitely to mint new access tokens.
    if session.is_expired() {
        let audit_logger = get_audit_logger();
        audit_logger.log_failure(
            AuditEventType::JwtRefresh,
            SecretType::RefreshToken,
            Some(session.user_id),
            "refresh",
            "Session expired",
        );
        return Err(AuthError::TokenExpired);
    }

    // SECURITY: Check rate limiting for auth/refresh endpoint (per user)
    if state.rate_limiters.auth_refresh.check(&session.user_id).is_err() {
        return Err(AuthError::RateLimited {
            retry_after_secs: state.rate_limiters.auth_refresh.clone_config().window_secs,
        });
    }

    // Audit log: Refresh token validation success
    let audit_logger = get_audit_logger();
    audit_logger.log_success(
        AuditEventType::SessionTokenValidation,
        SecretType::RefreshToken,
        Some(session.user_id),
        "validate",
    );

    // JWT signing requires an RSA/EC private key, which is not yet wired
    // into the auth state. Return an explicit error rather than a fake token.
    Err(AuthError::Internal {
        message: "JWT signing not yet implemented — configure an OIDC provider for token issuance"
            .to_string(),
    })
}

/// POST /auth/logout - Logout and revoke session
///
/// Revokes the refresh token, effectively logging out the user.
///
/// # Rate Limiting
///
/// This endpoint is rate-limited per user ID to prevent logout token exhaustion attacks.
/// The limit is configurable via FRAISEQL_AUTH_LOGOUT_MAX_REQUESTS and
/// FRAISEQL_AUTH_LOGOUT_WINDOW_SECS environment variables.
///
/// # Errors
///
/// Returns `AuthError::RateLimited` if the per-user rate limit is exceeded.
/// Returns `AuthError` if the session lookup or deletion fails.
pub async fn auth_logout(
    State(state): State<AuthState>,
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    Json(req): Json<AuthLogoutRequest>,
) -> Result<StatusCode> {
    let client_ip = addr.ip().to_string();

    if let Some(refresh_token) = req.refresh_token {
        use crate::session::hash_token;
        let token_hash = hash_token(&refresh_token);

        // Get session to extract user ID for per-user rate limiting
        let session = state.session_store.get_session(&token_hash).await?;

        // SECURITY: Check rate limiting for auth/logout endpoint (per user)
        if state.rate_limiters.auth_logout.check(&session.user_id).is_err() {
            return Err(AuthError::RateLimited {
                retry_after_secs: state.rate_limiters.auth_logout.clone_config().window_secs,
            });
        }

        state.session_store.revoke_session(&token_hash).await?;

        // Audit log: Session revoked
        let audit_logger = get_audit_logger();
        audit_logger.log_success(
            AuditEventType::SessionTokenRevoked,
            SecretType::RefreshToken,
            Some(session.user_id),
            "revoke",
        );
    } else {
        // No refresh token - use IP-based rate limiting as fallback
        if state.rate_limiters.auth_logout.check(&client_ip).is_err() {
            return Err(AuthError::RateLimited {
                retry_after_secs: state.rate_limiters.auth_logout.clone_config().window_secs,
            });
        }
    }

    Ok(StatusCode::NO_CONTENT)
}

/// Generate a cryptographically random state for CSRF protection
/// Uses OsRng for cryptographically secure randomness
#[must_use]
pub fn generate_secure_state() -> String {
    use rand::RngCore as _;

    // Generate 32 random bytes for 256 bits of entropy
    let mut bytes = [0u8; 32];
    rand::rng().fill_bytes(&mut bytes);

    // Encode as hex string for safe transmission in URLs/headers
    hex::encode(bytes)
}

/// Maximum byte length for an OAuth authorization code received at the callback.
///
/// RFC 6749 §4.1.2 places no normative cap on authorization codes, but
/// real-world providers issue codes of 32–256 ASCII characters.  512 bytes is
/// an order of magnitude above any legitimate value and prevents heap-flooding
/// via the query-string parser.
pub const MAX_AUTH_CODE_BYTES: usize = 512;

/// Maximum byte length for an OAuth `state` parameter received at the callback.
///
/// The `state` value in FraiseQL PKCE flows is a 64-character hex string
/// (32 random bytes).  When encrypted PKCE state is enabled the value is a
/// base64-encoded ciphertext that grows with the payload, but remains well
/// under 1 KiB in practice.  2048 bytes provides generous headroom while
/// bounding memory allocation from an attacker-supplied value.
pub const MAX_STATE_BYTES: usize = 2_048;

/// Maximum byte length for a refresh token submitted to `/auth/refresh`.
///
/// Session tokens are usually ≤ 2 KiB; 4 KiB covers all real-world formats
/// while bounding memory allocation for an attacker-supplied value.
pub const MAX_REFRESH_TOKEN_BYTES: usize = 4_096;

/// Guard oversized auth inputs before they reach session-store or provider logic.
///
/// Returns `AuthError::InvalidToken` with an internal reason string when
/// `input` exceeds `max_bytes`.  The reason is logged server-side and never
/// forwarded to the client.
///
/// # Errors
///
/// Returns `AuthError::InvalidToken` when `input.len() > max_bytes`.
pub fn validate_auth_input_len(
    input: &str,
    max_bytes: usize,
    field: &str,
) -> crate::error::Result<()> {
    if input.len() > max_bytes {
        return Err(crate::error::AuthError::InvalidToken {
            reason: format!("{field} exceeds maximum length ({} > {max_bytes} bytes)", input.len()),
        });
    }
    Ok(())
}

#[cfg(test)]
mod debug_redaction_tests {
    //! F045 regression — token fields in auth response types must be redacted
    //! from `Debug` output so they never reach structured logs via `?resp`.

    use super::*;

    const SECRET_ACCESS: &str = "eyJhbGciOiJIUzI1NiJ9.SUPER-SECRET-ACCESS-TOKEN.sig";
    const SECRET_REFRESH: &str = "RT-SUPER-SECRET-REFRESH-TOKEN-do-not-leak";

    #[test]
    fn auth_callback_response_debug_redacts_access_and_refresh_tokens() {
        let resp = AuthCallbackResponse {
            access_token:  SECRET_ACCESS.to_string(),
            refresh_token: Some(SECRET_REFRESH.to_string()),
            token_type:    "Bearer".to_string(),
            expires_in:    3600,
        };

        let debug_output = format!("{resp:?}");

        assert!(
            !debug_output.contains(SECRET_ACCESS),
            "access_token leaked in Debug output: {debug_output}",
        );
        assert!(
            !debug_output.contains(SECRET_REFRESH),
            "refresh_token leaked in Debug output: {debug_output}",
        );
        assert!(debug_output.contains("redacted"), "redaction marker missing: {debug_output}",);
        // The non-sensitive fields should still be present for diagnosability.
        assert!(debug_output.contains("Bearer"));
        assert!(debug_output.contains("3600"));
    }

    #[test]
    fn auth_callback_response_debug_with_no_refresh_token_shows_none() {
        let resp = AuthCallbackResponse {
            access_token:  SECRET_ACCESS.to_string(),
            refresh_token: None,
            token_type:    "Bearer".to_string(),
            expires_in:    900,
        };

        let debug_output = format!("{resp:?}");

        assert!(!debug_output.contains(SECRET_ACCESS));
        assert!(
            debug_output.contains("None"),
            "expected None to appear when refresh_token absent, got: {debug_output}",
        );
    }

    #[test]
    fn auth_refresh_response_debug_redacts_access_token() {
        let resp = AuthRefreshResponse {
            access_token: SECRET_ACCESS.to_string(),
            token_type:   "Bearer".to_string(),
            expires_in:   1800,
        };

        let debug_output = format!("{resp:?}");

        assert!(
            !debug_output.contains(SECRET_ACCESS),
            "access_token leaked in Debug output: {debug_output}",
        );
        assert!(debug_output.contains("redacted"), "redaction marker missing: {debug_output}",);
        assert!(debug_output.contains("Bearer"));
        assert!(debug_output.contains("1800"));
    }
}