Skip to main content

hyprstream_core/services/oauth/
scim.rs

1//! SCIM 2.0 HTTP handlers for user provisioning.
2//!
3//! Implements RFC 7644 endpoints under `/scim/v2/Users`.
4//! Delegates to `UserService` for shared CRUD logic.
5
6use std::sync::Arc;
7
8use axum::{
9    extract::{Path, Query, State},
10    http::{header, HeaderMap, HeaderValue, StatusCode},
11    response::IntoResponse,
12    Json,
13};
14use hex;
15use serde::Deserialize;
16use sha2::{Digest, Sha256};
17
18use super::state::OAuthState;
19use super::user_service;
20use crate::auth::{decode_pubkey_base64, UserFilter};
21
22use super::scim_types::*;
23
24// ─── Query parameters ───────────────────────────────────────────────────────
25
26#[derive(Debug, Deserialize)]
27pub struct ListParams {
28    pub filter: Option<String>,
29    #[serde(rename = "sortBy")]
30    pub sort_by: Option<String>,
31    #[serde(rename = "sortOrder")]
32    pub sort_order: Option<String>,
33    pub count: Option<u32>,
34    #[serde(rename = "startIndex")]
35    pub start_index: Option<u32>,
36    pub attributes: Option<String>,
37    #[serde(rename = "excludedAttributes")]
38    pub excluded_attributes: Option<String>,
39}
40
41// ─── Helpers ─────────────────────────────────────────────────────────────────
42
43fn scim_error(status: u16, scim_type: &str, detail: &str) -> axum::response::Response {
44    (
45        StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST),
46        [(header::CONTENT_TYPE, "application/scim+json")],
47        Json(ScimError {
48            schemas: vec![SCIM_API_ERROR.to_owned()],
49            detail: Some(detail.to_owned()),
50            status: status.to_string(),
51            scim_type: Some(scim_type.to_owned()),
52        }),
53    )
54        .into_response()
55}
56
57fn scim_error_simple(status: u16, detail: &str) -> axum::response::Response {
58    (
59        StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST),
60        [(header::CONTENT_TYPE, "application/scim+json")],
61        Json(ScimError {
62            schemas: vec![SCIM_API_ERROR.to_owned()],
63            detail: Some(detail.to_owned()),
64            status: status.to_string(),
65            scim_type: None,
66        }),
67    )
68        .into_response()
69}
70
71fn user_service(
72    state: &Arc<OAuthState>,
73) -> Result<&Arc<user_service::UserService>, Box<axum::response::Response>> {
74    state
75        .user_service
76        .as_ref()
77        .ok_or_else(|| Box::new(scim_error_simple(503, "User service not configured")))
78}
79
80fn hosted_account_did_from_body(
81    state: &OAuthState,
82    body: &serde_json::Value,
83) -> Result<Option<String>, Box<axum::response::Response>> {
84    let did = body
85        .get(SCIM_SCHEMA_EXT_HYPRSTREAM)
86        .and_then(|extension| extension.get("hosted_account_did"))
87        .and_then(serde_json::Value::as_str)
88        .map(str::trim)
89        .filter(|did| !did.is_empty())
90        .map(str::to_owned);
91    if let Some(did) = did.as_deref() {
92        super::token::hosted_account_tenant_from_did(did, state.hosted_account_zone.as_ref())
93            .map_err(|error| {
94                Box::new(scim_error(
95                    400,
96                    "invalidValue",
97                    &format!("invalid hosted_account_did: {error}"),
98                ))
99            })?;
100    }
101    Ok(did)
102}
103
104fn user_to_scim(info: &user_service::UserInfo, base_url: &str, include_pubkey: bool) -> ScimUser {
105    let etag = compute_etag(&info.sub, info.active);
106    ScimUser {
107        schemas: {
108            let mut s = vec![SCIM_SCHEMA_USER.to_owned()];
109            if include_pubkey && (!info.pubkey_base64.is_empty() || info.atproto_did.is_some()) {
110                s.push(SCIM_SCHEMA_EXT_HYPRSTREAM.to_owned());
111            }
112            s
113        },
114        id: info.sub.clone(),
115        external_id: info.external_id.clone(),
116        user_name: info.username.clone(),
117        display_name: info.name.clone(),
118        active: Some(info.active),
119        emails: info.email.as_ref().map(|email| {
120            vec![ScimEmail {
121                value: email.clone(),
122                primary: Some(info.email_verified),
123                email_type: None,
124            }]
125        }),
126        meta: ScimMeta {
127            resource_type: "User".to_owned(),
128            created: None,
129            last_modified: None,
130            location: Some(format!("{base_url}/scim/v2/Users/{}", info.sub)),
131            version: Some(etag),
132        },
133        hyprstream: if include_pubkey
134            && (!info.pubkey_base64.is_empty() || info.atproto_did.is_some())
135        {
136            Some(ScimHyprstreamExtension {
137                pubkey_base64: info.pubkey_base64.clone(),
138                hosted_account_did: info.atproto_did.clone(),
139            })
140        } else {
141            None
142        },
143    }
144}
145
146fn compute_etag(sub: &str, active: bool) -> String {
147    let mut hasher = Sha256::new();
148    hasher.update(sub.as_bytes());
149    hasher.update([active as u8]);
150    let hash = hasher.finalize();
151    format!("W/\"{}\"", hex::encode(hash))
152}
153
154/// Check If-Match header against current ETag. Returns `true` if OK to proceed.
155fn check_if_match(
156    headers: &HeaderMap,
157    current_etag: &str,
158) -> Result<(), Box<axum::response::Response>> {
159    if let Some(if_match) = headers.get(header::IF_MATCH) {
160        let if_match_str = if_match
161            .to_str()
162            .map_err(|_| Box::new(scim_error_simple(400, "Invalid If-Match header")))?;
163        // Support both "W/\"hash\"" and bare etag
164        if if_match_str != current_etag && if_match_str != "*" {
165            return Err(Box::new(scim_error(
166                412,
167                "invalidValue",
168                "Resource version mismatch (ETag)",
169            )));
170        }
171    }
172    Ok(())
173}
174
175/// Apply attribute projection to a ScimUser.
176fn apply_attributes(user: &mut ScimUser, attributes: Option<&str>, excluded: Option<&str>) {
177    // Always-returned: id, userName, meta (returned: always)
178    if let Some(attrs) = attributes {
179        let requested: Vec<&str> = attrs.split(',').map(str::trim).collect();
180        // Clear fields not in the requested set
181        if !requested
182            .iter()
183            .any(|a| *a == "displayName" || *a == "name")
184        {
185            user.display_name = None;
186        }
187        if !requested.contains(&"emails") {
188            user.emails = None;
189        }
190        if !requested.contains(&"active") {
191            user.active = None;
192        }
193        if !requested.contains(&"externalId") {
194            user.external_id = None;
195        }
196    }
197    if let Some(excluded) = excluded {
198        let excluded_set: Vec<&str> = excluded.split(',').map(str::trim).collect();
199        if excluded_set
200            .iter()
201            .any(|a| *a == "displayName" || *a == "name")
202        {
203            user.display_name = None;
204        }
205        if excluded_set.contains(&"emails") {
206            user.emails = None;
207        }
208        if excluded_set.contains(&"active") {
209            user.active = None;
210        }
211        if excluded_set.contains(&"externalId") {
212            user.external_id = None;
213        }
214    }
215}
216
217// ─── Handlers ─────────────────────────────────────────────────────────────────
218
219fn base_url() -> String {
220    crate::config::HyprConfig::load()
221        .unwrap_or_default()
222        .oauth
223        .issuer_url()
224}
225
226/// Find a user by id (sub) or userName.
227async fn find_user(
228    svc: &user_service::UserService,
229    id: &str,
230) -> anyhow::Result<Option<user_service::UserInfo>> {
231    if let Some(i) = svc.get(id).await? {
232        return Ok(Some(i));
233    }
234    // Try by sub/id
235    let filter = UserFilter {
236        filter: Some(format!("id eq \"{}\"", id)),
237        ..Default::default()
238    };
239    Ok(svc.list(&filter).await?.users.into_iter().next())
240}
241
242/// Build a SCIM JSON response with standard headers.
243fn scim_response(status: StatusCode, body: &ScimUser, etag: &str) -> axum::response::Response {
244    let mut resp =
245        axum::response::Response::new(serde_json::to_string(body).unwrap_or_default().into());
246    *resp.status_mut() = status;
247    let headers = resp.headers_mut();
248    headers.insert(
249        header::CONTENT_TYPE,
250        HeaderValue::from_static("application/scim+json"),
251    );
252    if let Ok(val) = HeaderValue::from_str(etag) {
253        headers.insert(header::ETAG, val);
254    }
255    resp
256}
257
258/// GET /scim/v2/Users — List/search users (RFC 7644 §3.4.2).
259pub async fn list_users(
260    State(state): State<Arc<OAuthState>>,
261    Query(params): Query<ListParams>,
262) -> axum::response::Response {
263    let svc = match user_service(&state) {
264        Ok(s) => s,
265        Err(e) => return *e,
266    };
267
268    // Parse SCIM filter if provided
269    let filter = UserFilter {
270        filter: params.filter.clone(),
271        active_only: None,
272        count: params.count.map(|c| c as usize),
273        start_index: params.start_index.map(|s| s as usize),
274        sort_by: params.sort_by.clone(),
275        sort_order: params.sort_order.clone(),
276    };
277
278    let list = match svc.list(&filter).await {
279        Ok(l) => l,
280        Err(e) => return scim_error_simple(500, &e.to_string()),
281    };
282
283    let base_url = {
284        let config = crate::config::HyprConfig::load().unwrap_or_default();
285        config.oauth.issuer_url()
286    };
287
288    let resources: Vec<ScimUser> = list
289        .users
290        .iter()
291        .map(|u| {
292            let mut scim = user_to_scim(u, &base_url, true);
293            apply_attributes(
294                &mut scim,
295                params.attributes.as_deref(),
296                params.excluded_attributes.as_deref(),
297            );
298            scim
299        })
300        .collect();
301
302    let response = ScimListResponse {
303        schemas: vec![SCIM_SCHEMA_LIST.to_owned()],
304        total_results: list.total_results as u32,
305        items_per_page: params.count,
306        start_index: params.start_index,
307        resources: Some(resources),
308    };
309
310    (
311        StatusCode::OK,
312        [(header::CONTENT_TYPE, "application/scim+json")],
313        Json(response),
314    )
315        .into_response()
316}
317
318/// POST /scim/v2/Users — Create user (RFC 7644 §3.3).
319pub async fn create_user(
320    State(state): State<Arc<OAuthState>>,
321    Json(body): Json<serde_json::Value>,
322) -> axum::response::Response {
323    let svc = match user_service(&state) {
324        Ok(s) => s,
325        Err(e) => return *e,
326    };
327
328    let user_name = match body.get("userName").and_then(|v| v.as_str()) {
329        Some(n) => n.to_owned(),
330        None => return scim_error(400, "invalidValue", "userName is required"),
331    };
332
333    // Check for duplicate userName
334    match svc.get(&user_name).await {
335        Ok(Some(_)) => {
336            return scim_error(
337                409,
338                "uniqueness",
339                &format!("User '{}' already exists", user_name),
340            );
341        }
342        Ok(None) => {}
343        Err(error) => return scim_error_simple(500, &error.to_string()),
344    }
345
346    let pubkey_base64 = body
347        .get("urn:ietf:params:scim:schemas:extension:hyprstream:1.0")
348        .and_then(|ext| ext.get("pubkey_base64"))
349        .and_then(|v| v.as_str())
350        .unwrap_or("")
351        .to_owned();
352
353    let display_name = body
354        .get("displayName")
355        .and_then(|v| v.as_str())
356        .map(std::borrow::ToOwned::to_owned);
357    let email = body
358        .get("emails")
359        .and_then(|v| v.as_array())
360        .and_then(|arr| arr.first())
361        .and_then(|e| e.get("value"))
362        .and_then(|v| v.as_str())
363        .map(std::borrow::ToOwned::to_owned);
364    let external_id = body
365        .get("externalId")
366        .and_then(|v| v.as_str())
367        .map(std::borrow::ToOwned::to_owned);
368    let hosted_account_did = match hosted_account_did_from_body(&state, &body) {
369        Ok(did) => did,
370        Err(response) => return *response,
371    };
372
373    let _info = match svc.register(&user_name, &pubkey_base64).await {
374        Ok(i) => i,
375        Err(e) => return scim_error_simple(400, &e.to_string()),
376    };
377
378    // Set optional profile fields
379    if display_name.is_some()
380        || email.is_some()
381        || external_id.is_some()
382        || hosted_account_did.is_some()
383    {
384        let update = user_service::UserUpdate {
385            name: display_name.map(Some),
386            email: email.map(Some),
387            external_id: external_id.map(Some),
388            email_verified: None,
389            atproto_did: hosted_account_did.map(Some),
390        };
391        if let Err(e) = svc.update(&user_name, update).await {
392            return scim_error_simple(500, &e.to_string());
393        }
394    }
395
396    let info = match svc.get(&user_name).await {
397        Ok(Some(i)) => i,
398        Ok(None) => return scim_error_simple(500, "User not found after creation"),
399        Err(error) => return scim_error_simple(500, &error.to_string()),
400    };
401
402    let base_url = {
403        let config = crate::config::HyprConfig::load().unwrap_or_default();
404        config.oauth.issuer_url()
405    };
406    let scim = user_to_scim(&info, &base_url, true);
407    let etag = scim.meta.version.clone().unwrap_or_default();
408
409    let mut resp =
410        axum::response::Response::new(serde_json::to_string(&scim).unwrap_or_default().into());
411    *resp.status_mut() = StatusCode::CREATED;
412    let headers = resp.headers_mut();
413    headers.insert(
414        header::CONTENT_TYPE,
415        HeaderValue::from_static("application/scim+json"),
416    );
417    if let Ok(val) = HeaderValue::from_str(&format!("{base_url}/scim/v2/Users/{}", info.sub)) {
418        headers.insert(header::LOCATION, val);
419    }
420    if let Ok(val) = HeaderValue::from_str(&etag) {
421        headers.insert(header::ETAG, val);
422    }
423    resp
424}
425
426/// GET /scim/v2/Users/:id — Get single user (RFC 7644 §3.4.1).
427pub async fn get_user(
428    State(state): State<Arc<OAuthState>>,
429    Path(id): Path<String>,
430) -> axum::response::Response {
431    let svc = match user_service(&state) {
432        Ok(s) => s,
433        Err(e) => return *e,
434    };
435
436    let info = match find_user(svc, &id).await {
437        Ok(Some(i)) => i,
438        Ok(None) => return scim_error_simple(404, "Resource not found"),
439        Err(error) => return scim_error_simple(500, &error.to_string()),
440    };
441
442    let base_url = base_url();
443    let scim = user_to_scim(&info, &base_url, true);
444    let etag = scim.meta.version.clone().unwrap_or_default();
445
446    scim_response(StatusCode::OK, &scim, &etag)
447}
448
449/// PUT /scim/v2/Users/:id — Replace user (RFC 7644 §3.5.1).
450pub async fn replace_user(
451    State(state): State<Arc<OAuthState>>,
452    headers: HeaderMap,
453    Path(id): Path<String>,
454    Json(body): Json<serde_json::Value>,
455) -> axum::response::Response {
456    let svc = match user_service(&state) {
457        Ok(s) => s,
458        Err(e) => return *e,
459    };
460
461    let info = match find_user(svc, &id).await {
462        Ok(Some(i)) => i,
463        Ok(None) => return scim_error_simple(404, "Resource not found"),
464        Err(error) => return scim_error_simple(500, &error.to_string()),
465    };
466
467    let current_etag = compute_etag(&info.sub, info.active);
468    if let Err(e) = check_if_match(&headers, &current_etag) {
469        return *e;
470    }
471
472    let display_name = body
473        .get("displayName")
474        .and_then(|v| v.as_str())
475        .map(std::borrow::ToOwned::to_owned);
476    let email = body
477        .get("emails")
478        .and_then(|v| v.as_array())
479        .and_then(|arr| arr.first())
480        .and_then(|e| e.get("value"))
481        .and_then(|v| v.as_str())
482        .map(std::borrow::ToOwned::to_owned);
483    let external_id = body
484        .get("externalId")
485        .and_then(|v| v.as_str())
486        .map(std::borrow::ToOwned::to_owned);
487    let active = body.get("active").and_then(serde_json::Value::as_bool);
488    let hosted_account_did = match hosted_account_did_from_body(&state, &body) {
489        Ok(did) => did,
490        Err(response) => return *response,
491    };
492
493    let update = user_service::UserUpdate {
494        name: display_name.map(Some),
495        email: email.map(Some),
496        external_id: external_id.map(Some),
497        email_verified: None,
498        atproto_did: hosted_account_did.map(Some),
499    };
500
501    if let Err(error) = svc.update(&info.username, update).await {
502        return scim_error_simple(500, &error.to_string());
503    }
504    if let Some(want_active) = active {
505        let active_result = if want_active && !info.active {
506            svc.resume(&info.username).await
507        } else if !want_active && info.active {
508            svc.suspend(&info.username).await
509        } else {
510            Ok(())
511        };
512        if let Err(error) = active_result {
513            return scim_error_simple(500, &error.to_string());
514        }
515    }
516
517    let updated = match svc.get(&info.username).await {
518        Ok(Some(updated)) => updated,
519        Ok(None) => return scim_error_simple(500, "User not found after replacement"),
520        Err(error) => return scim_error_simple(500, &error.to_string()),
521    };
522    let url = base_url();
523    let scim = user_to_scim(&updated, &url, true);
524    let etag = scim.meta.version.clone().unwrap_or_default();
525    scim_response(StatusCode::OK, &scim, &etag)
526}
527
528/// DELETE /scim/v2/Users/:id — Delete user (soft delete: set active=false) (RFC 7644 §3.6).
529pub async fn delete_user(
530    State(state): State<Arc<OAuthState>>,
531    headers: HeaderMap,
532    Path(id): Path<String>,
533) -> axum::response::Response {
534    let svc = match user_service(&state) {
535        Ok(s) => s,
536        Err(e) => return *e,
537    };
538
539    let info = match find_user(svc, &id).await {
540        Ok(Some(i)) => i,
541        Ok(None) => return scim_error_simple(404, "Resource not found"),
542        Err(error) => return scim_error_simple(500, &error.to_string()),
543    };
544
545    let current_etag = compute_etag(&info.sub, info.active);
546    if let Err(e) = check_if_match(&headers, &current_etag) {
547        return *e;
548    }
549
550    // Soft delete: suspend (set active=false)
551    if let Err(e) = svc.suspend(&info.username).await {
552        return scim_error_simple(500, &e.to_string());
553    }
554
555    StatusCode::NO_CONTENT.into_response()
556}
557
558// ─── Key management endpoints ─────────────────────────────────────────────────
559
560/// GET /scim/v2/Users/:id/keys — List public keys for a user.
561pub async fn list_user_keys(
562    State(state): State<Arc<OAuthState>>,
563    Path(id): Path<String>,
564) -> axum::response::Response {
565    let svc = match user_service(&state) {
566        Ok(s) => s,
567        Err(e) => return *e,
568    };
569
570    let info = match find_user(svc, &id).await {
571        Ok(Some(i)) => i,
572        Ok(None) => return scim_error_simple(404, "Resource not found"),
573        Err(error) => return scim_error_simple(500, &error.to_string()),
574    };
575
576    let resources: Vec<serde_json::Value> = info
577        .pubkeys
578        .iter()
579        .map(|pk| {
580            serde_json::json!({
581                "fingerprint": pk.fingerprint,
582                "pubkeyBase64": pk.pubkey_base64,
583                "label": pk.label,
584                "createdAt": pk.created_at,
585                "lastUsedAt": pk.last_used_at,
586            })
587        })
588        .collect();
589    let total = resources.len();
590
591    (
592        StatusCode::OK,
593        [(header::CONTENT_TYPE, "application/scim+json")],
594        Json(serde_json::json!({
595            "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
596            "totalResults": total,
597            "Resources": resources,
598        })),
599    )
600        .into_response()
601}
602
603/// POST /scim/v2/Users/:id/keys — Add a public key for a user.
604pub async fn add_user_key(
605    State(state): State<Arc<OAuthState>>,
606    Path(id): Path<String>,
607    Json(body): Json<serde_json::Value>,
608) -> axum::response::Response {
609    let svc = match user_service(&state) {
610        Ok(s) => s,
611        Err(e) => return *e,
612    };
613
614    let info = match find_user(svc, &id).await {
615        Ok(Some(i)) => i,
616        Ok(None) => return scim_error_simple(404, "Resource not found"),
617        Err(error) => return scim_error_simple(500, &error.to_string()),
618    };
619
620    let pubkey_b64 = match body.get("pubkeyBase64").and_then(|v| v.as_str()) {
621        Some(s) => s,
622        None => return scim_error(400, "invalidValue", "pubkeyBase64 is required"),
623    };
624    let label = body
625        .get("label")
626        .and_then(|v| v.as_str())
627        .map(str::to_owned);
628
629    let pubkey = match decode_pubkey_base64(pubkey_b64) {
630        Ok(k) => k,
631        Err(e) => return scim_error(400, "invalidValue", &e.to_string()),
632    };
633
634    match svc.add_pubkey(&info.username, pubkey, label).await {
635        Ok(entry) => (
636            StatusCode::CREATED,
637            [(header::CONTENT_TYPE, "application/scim+json")],
638            Json(serde_json::json!({
639                "fingerprint": entry.fingerprint,
640                "pubkeyBase64": entry.pubkey_base64,
641                "label": entry.label,
642                "createdAt": entry.created_at,
643            })),
644        )
645            .into_response(),
646        Err(e) => scim_error_simple(500, &e.to_string()),
647    }
648}
649
650/// DELETE /scim/v2/Users/:id/keys/:fingerprint — Remove a public key.
651pub async fn remove_user_key(
652    State(state): State<Arc<OAuthState>>,
653    Path((id, fingerprint)): Path<(String, String)>,
654) -> axum::response::Response {
655    let svc = match user_service(&state) {
656        Ok(s) => s,
657        Err(e) => return *e,
658    };
659
660    let info = match find_user(svc, &id).await {
661        Ok(Some(i)) => i,
662        Ok(None) => return scim_error_simple(404, "Resource not found"),
663        Err(error) => return scim_error_simple(500, &error.to_string()),
664    };
665
666    // Normalize: ensure SHA256: prefix is present regardless of whether client included it
667    let owned;
668    let fp = if fingerprint.starts_with("SHA256:") {
669        fingerprint.as_str()
670    } else {
671        owned = format!("SHA256:{fingerprint}");
672        &owned
673    };
674    match svc.remove_pubkey(&info.username, fp).await {
675        Ok(true) => StatusCode::NO_CONTENT.into_response(),
676        Ok(false) => scim_error_simple(404, "Key not found"),
677        Err(e) => scim_error_simple(500, &e.to_string()),
678    }
679}
680
681// ─── Discovery endpoints ─────────────────────────────────────────────────────
682
683/// GET /scim/v2/ServiceProviderConfig (RFC 7644 §4).
684pub async fn service_provider_config() -> axum::response::Response {
685    let config = ScimServiceProviderConfig {
686        schemas: vec!["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig".to_owned()],
687        patch: ScimFeature { supported: false },
688        bulk: ScimFeatureWithMax {
689            supported: false,
690            max_operations: 0,
691            max_payload_size: 0,
692        },
693        filter: ScimFilterFeature {
694            supported: true,
695            max_results: 100,
696        },
697        change_password: ScimFeature { supported: false },
698        sort: ScimFeature { supported: true },
699        etag: ScimFeature { supported: true },
700        authentication_schemes: vec![ScimAuthScheme {
701            name: "OAuth Bearer Token".to_owned(),
702            description: "Authentication via OAuth 2.0 Bearer Token".to_owned(),
703            spec_uri: "https://www.rfc-editor.org/rfc/rfc6750".to_owned(),
704            auth_type: "oauthbearertoken".to_owned(),
705            primary: true,
706        }],
707    };
708
709    (
710        StatusCode::OK,
711        [(header::CONTENT_TYPE, "application/scim+json")],
712        Json(config),
713    )
714        .into_response()
715}
716
717/// GET /scim/v2/Schemas (RFC 7644 §4).
718pub async fn schemas() -> axum::response::Response {
719    let user_schema = ScimSchema {
720        schemas: vec!["urn:ietf:params:scim:schemas:core:2.0:Schema".to_owned()],
721        id: SCIM_SCHEMA_USER.to_owned(),
722        name: "User".to_owned(),
723        description: "User Account".to_owned(),
724        attributes: vec![
725            ScimAttribute {
726                name: "userName".to_owned(),
727                attr_type: "string".to_owned(),
728                multi_valued: false,
729                required: true,
730                case_exact: false,
731                mutability: "readWrite".to_owned(),
732                returned: "default".to_owned(),
733                uniqueness: "server".to_owned(),
734                sub_attributes: None,
735            },
736            ScimAttribute {
737                name: "displayName".to_owned(),
738                attr_type: "string".to_owned(),
739                multi_valued: false,
740                required: false,
741                case_exact: false,
742                mutability: "readWrite".to_owned(),
743                returned: "default".to_owned(),
744                uniqueness: "none".to_owned(),
745                sub_attributes: None,
746            },
747            ScimAttribute {
748                name: "active".to_owned(),
749                attr_type: "boolean".to_owned(),
750                multi_valued: false,
751                required: false,
752                case_exact: false,
753                mutability: "readWrite".to_owned(),
754                returned: "default".to_owned(),
755                uniqueness: "none".to_owned(),
756                sub_attributes: None,
757            },
758            ScimAttribute {
759                name: "emails".to_owned(),
760                attr_type: "complex".to_owned(),
761                multi_valued: true,
762                required: false,
763                case_exact: false,
764                mutability: "readWrite".to_owned(),
765                returned: "default".to_owned(),
766                uniqueness: "none".to_owned(),
767                sub_attributes: Some(vec![
768                    ScimAttribute {
769                        name: "value".to_owned(),
770                        attr_type: "string".to_owned(),
771                        multi_valued: false,
772                        required: false,
773                        case_exact: false,
774                        mutability: "readWrite".to_owned(),
775                        returned: "default".to_owned(),
776                        uniqueness: "none".to_owned(),
777                        sub_attributes: None,
778                    },
779                    ScimAttribute {
780                        name: "primary".to_owned(),
781                        attr_type: "boolean".to_owned(),
782                        multi_valued: false,
783                        required: false,
784                        case_exact: false,
785                        mutability: "readWrite".to_owned(),
786                        returned: "default".to_owned(),
787                        uniqueness: "none".to_owned(),
788                        sub_attributes: None,
789                    },
790                ]),
791            },
792            ScimAttribute {
793                name: "externalId".to_owned(),
794                attr_type: "string".to_owned(),
795                multi_valued: false,
796                required: false,
797                case_exact: false,
798                mutability: "readWrite".to_owned(),
799                returned: "default".to_owned(),
800                uniqueness: "none".to_owned(),
801                sub_attributes: None,
802            },
803        ],
804    };
805
806    (
807        StatusCode::OK,
808        [(header::CONTENT_TYPE, "application/scim+json")],
809        Json(vec![user_schema]),
810    )
811        .into_response()
812}
813
814/// GET /scim/v2/ResourceTypes (RFC 7644 §4).
815pub async fn resource_types() -> axum::response::Response {
816    let user_type = ScimResourceType {
817        schemas: vec!["urn:ietf:params:scim:schemas:core:2.0:ResourceType".to_owned()],
818        id: "User".to_owned(),
819        name: "User".to_owned(),
820        endpoint: "/scim/v2/Users".to_owned(),
821        description: "User Account".to_owned(),
822        schema_: SCIM_SCHEMA_USER.to_owned(),
823    };
824
825    (
826        StatusCode::OK,
827        [(header::CONTENT_TYPE, "application/scim+json")],
828        Json(vec![user_type]),
829    )
830        .into_response()
831}