cedros-login-server 0.0.1

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
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
//! Admin SSO provider management handlers
//!
//! CRUD endpoints for managing SSO (OIDC) providers per organization.
//! All endpoints require system admin privileges.

use axum::{
    extract::{Path, Query, State},
    http::HeaderMap,
    Json,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use url::Url;
use uuid::Uuid;

use crate::callback::AuthCallback;
use crate::errors::{AppError, ERR_SYSTEM_ADMIN_REQUIRED};
use crate::models::sso::SsoProvider;
use crate::repositories::pagination::{cap_limit, cap_offset};
use crate::services::EmailService;
use crate::utils::authenticate;
use crate::AppState;

/// Validate system admin access
async fn validate_system_admin<C: AuthCallback, E: EmailService>(
    state: &Arc<AppState<C, E>>,
    headers: &HeaderMap,
) -> Result<Uuid, AppError> {
    let auth_user = authenticate(state, headers).await?;

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

    if !user.is_system_admin {
        return Err(AppError::Forbidden(ERR_SYSTEM_ADMIN_REQUIRED.into()));
    }

    Ok(auth_user.user_id)
}

/// Query params for listing SSO providers
#[derive(Debug, Deserialize)]
pub struct ListSsoProvidersQuery {
    /// Filter by organization ID
    pub org_id: Option<Uuid>,
    /// Pagination limit
    #[serde(default = "default_limit")]
    pub limit: u32,
    /// Pagination offset
    #[serde(default)]
    pub offset: u32,
}

fn default_limit() -> u32 {
    50
}

/// Response for listing SSO providers
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ListSsoProvidersResponse {
    pub providers: Vec<SsoProviderResponse>,
    pub total: usize,
    pub limit: u32,
    pub offset: u32,
}

/// SSO provider response (excludes encrypted secrets)
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SsoProviderResponse {
    pub id: Uuid,
    pub org_id: Uuid,
    pub name: String,
    pub issuer_url: String,
    pub client_id: String,
    pub scopes: Vec<String>,
    pub enabled: bool,
    pub allow_registration: bool,
    pub email_domain: Option<String>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl From<&SsoProvider> for SsoProviderResponse {
    fn from(p: &SsoProvider) -> Self {
        Self {
            id: p.id,
            org_id: p.org_id,
            name: p.name.clone(),
            issuer_url: p.issuer_url.clone(),
            client_id: p.client_id.clone(),
            scopes: p.scopes.clone(),
            enabled: p.enabled,
            allow_registration: p.allow_registration,
            email_domain: p.email_domain.clone(),
            created_at: p.created_at,
            updated_at: p.updated_at,
        }
    }
}

/// Request to create an SSO provider
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateSsoProviderRequest {
    pub org_id: Uuid,
    pub name: String,
    pub issuer_url: String,
    pub client_id: String,
    pub client_secret: String,
    #[serde(default = "default_scopes")]
    pub scopes: Vec<String>,
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default = "default_true")]
    pub allow_registration: bool,
    pub email_domain: Option<String>,
}

fn default_scopes() -> Vec<String> {
    vec!["openid".into(), "email".into(), "profile".into()]
}

fn default_true() -> bool {
    true
}

fn is_production_env(environment: &str) -> bool {
    environment.eq_ignore_ascii_case("production") || environment.eq_ignore_ascii_case("prod")
}

fn validate_sso_provider_settings(
    issuer_url: &str,
    scopes: &[String],
    environment: &str,
) -> Result<(), AppError> {
    let issuer =
        Url::parse(issuer_url).map_err(|_| AppError::Validation("Invalid issuer URL".into()))?;

    if is_production_env(environment) && issuer.scheme() != "https" {
        return Err(AppError::Validation(
            "OIDC issuer URL must use https in production".into(),
        ));
    }

    let required_scopes = ["openid", "email"];
    for required in required_scopes {
        if !scopes.iter().any(|s| s.eq_ignore_ascii_case(required)) {
            return Err(AppError::Validation(format!(
                "OIDC scope '{}' is required",
                required
            )));
        }
    }

    Ok(())
}

/// Request to update an SSO provider
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateSsoProviderRequest {
    pub name: Option<String>,
    pub issuer_url: Option<String>,
    pub client_id: Option<String>,
    pub client_secret: Option<String>,
    pub scopes: Option<Vec<String>>,
    pub enabled: Option<bool>,
    pub allow_registration: Option<bool>,
    pub email_domain: Option<String>,
}

/// GET /admin/sso-providers - List all SSO providers
pub async fn list_sso_providers<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Query(params): Query<ListSsoProvidersQuery>,
) -> Result<Json<ListSsoProvidersResponse>, AppError> {
    validate_system_admin(&state, &headers).await?;

    let limit = cap_limit(params.limit);
    let offset = cap_offset(params.offset);

    let (providers_result, total_result) = if let Some(org_id) = params.org_id {
        tokio::join!(
            state
                .storage
                .sso_repository()
                .list_providers_for_org_paged(org_id, limit, offset),
            state
                .storage
                .sso_repository()
                .count_providers_for_org(org_id)
        )
    } else {
        tokio::join!(
            state
                .storage
                .sso_repository()
                .list_all_providers_paged(limit, offset),
            state.storage.sso_repository().count_all_providers()
        )
    };

    let providers = providers_result?;
    let total = total_result?;
    let providers: Vec<SsoProviderResponse> =
        providers.iter().map(SsoProviderResponse::from).collect();

    Ok(Json(ListSsoProvidersResponse {
        providers,
        total: total as usize,
        limit,
        offset,
    }))
}

/// GET /admin/sso-providers/:id - Get a specific SSO provider
pub async fn get_sso_provider<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Path(id): Path<Uuid>,
) -> Result<Json<SsoProviderResponse>, AppError> {
    validate_system_admin(&state, &headers).await?;

    let provider = state
        .storage
        .sso_repository()
        .find_provider_by_id(id)
        .await?
        .ok_or_else(|| AppError::NotFound("SSO provider not found".into()))?;

    Ok(Json(SsoProviderResponse::from(&provider)))
}

/// POST /admin/sso-providers - Create an SSO provider
pub async fn create_sso_provider<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Json(request): Json<CreateSsoProviderRequest>,
) -> Result<Json<SsoProviderResponse>, AppError> {
    let admin_id = validate_system_admin(&state, &headers).await?;

    // Validate organization exists
    let _org = state
        .org_repo
        .find_by_id(request.org_id)
        .await?
        .ok_or_else(|| AppError::NotFound("Organization not found".into()))?;

    validate_sso_provider_settings(
        &request.issuer_url,
        &request.scopes,
        &state.config.notification.environment,
    )?;

    // Encrypt the client secret
    let encrypted_secret = state.encryption_service.encrypt(&request.client_secret)?;

    let now = chrono::Utc::now();
    let provider = SsoProvider {
        id: Uuid::new_v4(),
        org_id: request.org_id,
        name: request.name,
        issuer_url: request.issuer_url,
        client_id: request.client_id,
        client_secret_encrypted: encrypted_secret,
        scopes: request.scopes,
        enabled: request.enabled,
        allow_registration: request.allow_registration,
        email_domain: request.email_domain,
        created_at: now,
        updated_at: now,
    };

    let created = state
        .storage
        .sso_repository()
        .create_provider(provider)
        .await?;

    tracing::info!(
        admin_id = %admin_id,
        provider_id = %created.id,
        org_id = %created.org_id,
        provider_name = %created.name,
        issuer_url = %created.issuer_url,
        "Admin created SSO provider"
    );

    Ok(Json(SsoProviderResponse::from(&created)))
}

/// PUT /admin/sso-providers/:id - Update an SSO provider
///
/// ## HANDLER-10: No Reachability Validation
///
/// This endpoint validates URL format and scopes but doesn't verify the issuer_url
/// is actually reachable. Trade-offs considered:
///
/// - **With reachability check**: Slower updates, can fail due to transient network issues,
///   provider might be intentionally unreachable during setup
/// - **Without reachability check** (current): Fast updates, works for staged configurations
///
/// Recommendation: If reachability validation is needed, implement as async background job
/// that warns admins via notification if discovery document can't be fetched.
pub async fn update_sso_provider<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Path(id): Path<Uuid>,
    Json(request): Json<UpdateSsoProviderRequest>,
) -> Result<Json<SsoProviderResponse>, AppError> {
    let admin_id = validate_system_admin(&state, &headers).await?;

    let mut provider = state
        .storage
        .sso_repository()
        .find_provider_by_id(id)
        .await?
        .ok_or_else(|| AppError::NotFound("SSO provider not found".into()))?;

    // Apply updates
    if let Some(name) = request.name {
        provider.name = name;
    }
    if let Some(issuer_url) = request.issuer_url {
        provider.issuer_url = issuer_url;
    }
    if let Some(client_id) = request.client_id {
        provider.client_id = client_id;
    }
    if let Some(client_secret) = request.client_secret {
        provider.client_secret_encrypted = state.encryption_service.encrypt(&client_secret)?;
    }
    if let Some(scopes) = request.scopes {
        provider.scopes = scopes;
    }
    if let Some(enabled) = request.enabled {
        provider.enabled = enabled;
    }
    if let Some(allow_registration) = request.allow_registration {
        provider.allow_registration = allow_registration;
    }
    if request.email_domain.is_some() {
        provider.email_domain = request.email_domain;
    }

    provider.updated_at = chrono::Utc::now();

    validate_sso_provider_settings(
        &provider.issuer_url,
        &provider.scopes,
        &state.config.notification.environment,
    )?;

    let updated = state
        .storage
        .sso_repository()
        .update_provider(provider)
        .await?;

    tracing::info!(
        admin_id = %admin_id,
        provider_id = %updated.id,
        provider_name = %updated.name,
        "Admin updated SSO provider"
    );

    Ok(Json(SsoProviderResponse::from(&updated)))
}

/// DELETE /admin/sso-providers/:id - Delete an SSO provider
pub async fn delete_sso_provider<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Path(id): Path<Uuid>,
) -> Result<Json<DeleteResponse>, AppError> {
    let admin_id = validate_system_admin(&state, &headers).await?;

    // Check provider exists
    let provider = state
        .storage
        .sso_repository()
        .find_provider_by_id(id)
        .await?
        .ok_or_else(|| AppError::NotFound("SSO provider not found".into()))?;

    state.storage.sso_repository().delete_provider(id).await?;

    tracing::info!(
        admin_id = %admin_id,
        provider_id = %id,
        provider_name = %provider.name,
        org_id = %provider.org_id,
        "Admin deleted SSO provider"
    );

    Ok(Json(DeleteResponse { success: true }))
}

/// Response for delete operations
#[derive(Debug, Serialize)]
pub struct DeleteResponse {
    pub success: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validate_sso_provider_settings_requires_scopes() {
        let scopes = vec!["openid".to_string()];
        let result =
            validate_sso_provider_settings("https://issuer.example.com", &scopes, "production");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_sso_provider_settings_requires_https_in_production() {
        let scopes = vec!["openid".to_string(), "email".to_string()];
        let result =
            validate_sso_provider_settings("http://issuer.example.com", &scopes, "production");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_sso_provider_settings_allows_http_in_development() {
        let scopes = vec!["openid".to_string(), "email".to_string()];
        let result =
            validate_sso_provider_settings("http://issuer.example.com", &scopes, "development");
        assert!(result.is_ok());
    }
}