cedros-login-server 0.0.43

Authentication server for cedros-login with email/password, Google OAuth, and Solana wallet sign-in
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
//! WebAuthn handlers for passkey registration and authentication
//!
//! Endpoints:
//! - POST /auth/webauthn/register/options - Start passkey registration
//! - POST /auth/webauthn/register/verify - Complete passkey registration
//! - POST /auth/webauthn/auth/options - Start passkey authentication
//! - POST /auth/webauthn/auth/verify - Complete passkey authentication

use axum::{extract::State, http::HeaderMap, response::IntoResponse, Json};
use chrono::{Duration, Utc};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use uuid::Uuid;

use crate::callback::{AuthCallback, AuthCallbackPayload};
use crate::errors::AppError;
use crate::handlers::auth::call_authenticated_callback_with_timeout;
use crate::models::{AuthMethod, AuthResponse};
use crate::repositories::{
    normalize_email, AuditEventType, CredentialEntity, CredentialType, SessionEntity,
};
use crate::services::{
    webauthn_service::{VerifyAuthenticationRequest, VerifyRegistrationRequest},
    EmailService,
};
use crate::utils::{
    auth::authenticate, build_json_response_with_cookies, compute_post_login, extract_client_ip,
    get_default_org_context, hash_refresh_token, user_entity_to_auth_user,
};
use crate::AppState;

/// Response for registration options
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RegisterOptionsResponse {
    pub challenge_id: Uuid,
    pub options: serde_json::Value,
}

/// Response for authentication options
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthOptionsResponse {
    pub challenge_id: Uuid,
    pub options: serde_json::Value,
}

/// Request to start authentication (optional email for email-first flow)
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StartAuthRequest {
    /// Email for email-first authentication flow (optional)
    pub email: Option<String>,
}

/// Request to verify registration
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VerifyRegisterRequest {
    pub challenge_id: Uuid,
    pub credential: serde_json::Value,
    pub label: Option<String>,
}

/// Request to verify authentication
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VerifyAuthRequest {
    pub challenge_id: Uuid,
    pub credential: serde_json::Value,
}

/// POST /auth/webauthn/register/options
///
/// Start passkey registration ceremony.
/// Requires authentication (user must already be signed in).
pub async fn register_options<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
) -> Result<Json<RegisterOptionsResponse>, AppError> {
    // Verify user is authenticated
    let auth_user = authenticate(&state, &headers).await?;

    // Get user details
    let user = state
        .user_repo
        .find_by_id(auth_user.user_id)
        .await?
        .ok_or(AppError::InvalidToken)?;

    // Get existing WebAuthn credentials to exclude
    let existing = state
        .storage
        .webauthn_repository()
        .find_by_user(auth_user.user_id)
        .await?;

    // Start registration
    let result = state
        .webauthn_service
        .start_registration(
            auth_user.user_id,
            user.email.as_deref(),
            user.name.as_deref(),
            &existing,
            &state.storage.webauthn_repo,
        )
        .await?;

    // Convert options to JSON value for flexibility
    let options_json =
        serde_json::to_value(&result.options).map_err(|e| AppError::Internal(e.into()))?;

    Ok(Json(RegisterOptionsResponse {
        challenge_id: result.challenge_id,
        options: options_json,
    }))
}

/// POST /auth/webauthn/register/verify
///
/// Complete passkey registration ceremony.
/// Requires authentication.
pub async fn register_verify<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Json(request): Json<VerifyRegisterRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Verify user is authenticated
    let auth_user = authenticate(&state, &headers).await?;

    // Parse the credential from JSON
    let credential: webauthn_rs::prelude::RegisterPublicKeyCredential =
        serde_json::from_value(request.credential)
            .map_err(|e| AppError::Validation(format!("Invalid credential format: {}", e)))?;

    // Complete registration
    let webauthn_cred = state
        .webauthn_service
        .finish_registration(
            VerifyRegistrationRequest {
                challenge_id: request.challenge_id,
                credential,
                label: request.label.clone(),
            },
            &state.storage.webauthn_repo,
        )
        .await?;

    // Also create a unified credential entry
    let unified_cred = CredentialEntity::new(
        auth_user.user_id,
        CredentialType::WebauthnPasskey,
        request.label,
    );
    // S-30: Log error instead of silently ignoring unified credential creation failure
    if let Err(e) = state
        .storage
        .credential_repository()
        .create(unified_cred)
        .await
    {
        tracing::warn!(
            user_id = %auth_user.user_id,
            error = %e,
            "Failed to create unified credential entry for WebAuthn passkey"
        );
    }

    Ok(Json(serde_json::json!({
        "success": true,
        "credentialId": webauthn_cred.id,
        "label": webauthn_cred.label
    })))
}

/// POST /auth/webauthn/auth/options
///
/// Start passkey authentication ceremony.
/// Can be used for:
/// - S-16: Username-less authentication (no body required, uses discoverable credentials)
/// - Email-first authentication (provide email in body)
pub async fn auth_options<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    Json(request): Json<StartAuthRequest>,
) -> Result<Json<AuthOptionsResponse>, AppError> {
    // Enabled check: runtime setting > static config
    let enabled = state
        .settings_service
        .get_bool("auth_webauthn_enabled")
        .await
        .ok()
        .flatten()
        .unwrap_or(state.config.webauthn.enabled);
    if !enabled {
        return Err(AppError::NotFound("WebAuthn auth disabled".into()));
    }

    let result = if let Some(ref email) = request.email {
        // F-34: Normalize email (NFKC + lowercase) to prevent Unicode homograph bypasses
        let normalized = normalize_email(email);
        // S-11: Return uniform error for non-existent user and no-passkeys user
        // to prevent email enumeration via differing error responses.
        let user = state
            .user_repo
            .find_by_email(&normalized)
            .await?
            .ok_or_else(|| AppError::InvalidCredentials)?;

        let creds = state
            .storage
            .webauthn_repository()
            .find_by_user(user.id)
            .await?;

        if creds.is_empty() {
            return Err(AppError::InvalidCredentials);
        }

        state
            .webauthn_service
            .start_authentication(Some(user.id), &creds, &state.storage.webauthn_repo)
            .await?
    } else {
        // S-16: Discoverable credential flow (username-less)
        // The authenticator will prompt the user to select a passkey
        state
            .webauthn_service
            .start_discoverable_authentication(&state.storage.webauthn_repo)
            .await?
    };

    // Convert options to JSON value
    let options_json =
        serde_json::to_value(&result.options).map_err(|e| AppError::Internal(e.into()))?;

    Ok(Json(AuthOptionsResponse {
        challenge_id: result.challenge_id,
        options: options_json,
    }))
}

/// POST /auth/webauthn/auth/verify
///
/// Complete passkey authentication ceremony.
/// Returns JWT tokens on success.
/// Supports both email-first and S-16 discoverable (username-less) flows.
pub async fn auth_verify<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Json(request): Json<VerifyAuthRequest>,
) -> Result<impl IntoResponse, AppError> {
    // Enabled check: runtime setting > static config
    let enabled = state
        .settings_service
        .get_bool("auth_webauthn_enabled")
        .await
        .ok()
        .flatten()
        .unwrap_or(state.config.webauthn.enabled);
    if !enabled {
        return Err(AppError::NotFound("WebAuthn auth disabled".into()));
    }

    // Parse the credential from JSON
    let credential: webauthn_rs::prelude::PublicKeyCredential =
        serde_json::from_value(request.credential.clone())
            .map_err(|e| AppError::Validation(format!("Invalid credential format: {}", e)))?;

    // Peek at the challenge to determine which flow to use
    // We don't consume it here - the service methods will consume it
    let challenge = state
        .storage
        .webauthn_repository()
        .find_challenge(request.challenge_id)
        .await?
        .ok_or_else(|| AppError::Validation("Challenge expired or not found".into()))?;

    // S-16: Handle discoverable vs email-first flow based on challenge type
    let verified_user_id = if challenge.challenge_type == "discoverable" {
        // Discoverable flow - user identity comes from the credential
        let (user_id, _cred) = state
            .webauthn_service
            .finish_discoverable_authentication(
                VerifyAuthenticationRequest {
                    challenge_id: request.challenge_id,
                    credential,
                },
                &state.storage.webauthn_repo,
            )
            .await?;
        user_id
    } else {
        // Email-first flow - user was identified at options step
        let user_id = challenge
            .user_id
            .ok_or_else(|| AppError::Internal(anyhow::anyhow!("Missing user_id in challenge")))?;

        // Get user's credentials for verification
        let credentials = state
            .storage
            .webauthn_repository()
            .find_by_user(user_id)
            .await?;

        // Complete authentication
        let (verified_user_id, _cred) = state
            .webauthn_service
            .finish_authentication(
                VerifyAuthenticationRequest {
                    challenge_id: request.challenge_id,
                    credential,
                },
                &credentials,
                &state.storage.webauthn_repo,
            )
            .await?;
        verified_user_id
    };

    // Get the user
    let user = state
        .user_repo
        .find_by_id(verified_user_id)
        .await?
        .ok_or(AppError::Internal(anyhow::anyhow!(
            "User not found after WebAuthn auth"
        )))?;

    // Get memberships for token context
    let memberships = state.membership_repo.find_by_user(verified_user_id).await?;
    let token_context =
        get_default_org_context(&memberships, user.is_system_admin, user.email_verified);

    // Create session
    let session_id = Uuid::new_v4();
    let token_pair = state.jwt_service.generate_token_pair_with_context(
        verified_user_id,
        session_id,
        &token_context,
    )?;
    let refresh_expiry =
        Utc::now() + Duration::seconds(state.jwt_service.refresh_expiry_secs() as i64);

    let ip_address = extract_client_ip(&headers, state.config.server.trust_proxy);
    let user_agent = headers
        .get(axum::http::header::USER_AGENT)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string());

    let mut session = SessionEntity::new_with_id(
        session_id,
        verified_user_id,
        hash_refresh_token(&token_pair.refresh_token, &state.config.jwt.secret),
        refresh_expiry,
        ip_address.clone(),
        user_agent.clone(),
    );
    session.last_strong_auth_at = Some(Utc::now());
    state.session_repo.create(session).await?;

    // Fire callback
    let auth_user = user_entity_to_auth_user(&user);
    let payload = AuthCallbackPayload {
        user: auth_user.clone(),
        method: AuthMethod::WebAuthn,
        is_new_user: false,
        session_id: session_id.to_string(),
        ip_address,
        user_agent,
        referral: None,
    };
    let callback_data = call_authenticated_callback_with_timeout(&state.callback, &payload).await;

    // Log audit event
    let _ = state
        .audit_service
        .log_user_event(AuditEventType::UserLogin, verified_user_id, Some(&headers))
        .await;

    let response_tokens = if state.config.cookie.enabled {
        None
    } else {
        Some(token_pair.clone())
    };

    let response = AuthResponse {
        user: auth_user,
        tokens: response_tokens,
        is_new_user: false,
        callback_data,
        api_key: None,
        email_queued: None,
        post_login: compute_post_login(
            &user,
            &state.settings_service,
            &*state.totp_repo,
            &*state.credential_repo,
            &*state.wallet_material_repo,
            &*state.storage.pending_wallet_recovery_repo,
        )
        .await,
    };

    Ok(build_json_response_with_cookies(
        &state.config.cookie,
        &token_pair,
        state.jwt_service.refresh_expiry_secs(),
        response,
    ))
}