Skip to main content

auth_framework/api/
saml.rs

1use crate::api::{ApiResponse, ApiState};
2use axum::{
3    extract::{Query, State},
4    http::StatusCode,
5    response::{Html, IntoResponse, Json},
6};
7use base64::Engine;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11/// Escape a string for safe inclusion in XML attribute values and text content.
12/// Prevents XML injection by escaping the five predefined XML entities.
13fn xml_escape(input: &str) -> String {
14    let mut output = String::with_capacity(input.len());
15    for ch in input.chars() {
16        match ch {
17            '&' => output.push_str("&"),
18            '<' => output.push_str("&lt;"),
19            '>' => output.push_str("&gt;"),
20            '"' => output.push_str("&quot;"),
21            '\'' => output.push_str("&apos;"),
22            _ => output.push(ch),
23        }
24    }
25    output
26}
27
28#[cfg(feature = "saml")]
29use bergshamra::{DsigContext, Key, KeyData, KeysManager, VerifyResult, verify};
30#[cfg(feature = "saml")]
31use quick_xml::Reader;
32#[cfg(feature = "saml")]
33use quick_xml::events::Event;
34#[cfg(feature = "saml")]
35use quick_xml::name::QName;
36
37/// Extract the local name (without namespace prefix) from a `QName`, taking
38/// ownership to avoid temporary-lifetime issues from method chaining.
39#[cfg(feature = "saml")]
40fn xml_local<'a>(name: QName<'a>) -> &'a [u8] {
41    let full = name.0;
42    match full.iter().position(|&b| b == b':') {
43        Some(pos) => &full[pos + 1..],
44        None => full,
45    }
46}
47
48/// SAML SSO initiation request
49#[derive(Debug, Serialize, Deserialize)]
50pub struct SamlSsoRequest {
51    pub idp_entity_id: String,
52    pub relay_state: Option<String>,
53    pub force_authn: Option<bool>,
54    pub is_passive: Option<bool>,
55}
56
57/// SAML SSO response containing redirect URL
58#[derive(Debug, Serialize, Deserialize)]
59pub struct SamlSsoResponse {
60    pub redirect_url: String,
61    pub saml_request: String,
62    pub relay_state: Option<String>,
63}
64
65/// SAML ACS (Assertion Consumer Service) request
66#[derive(Debug, Serialize, Deserialize)]
67pub struct SamlAcsRequest {
68    #[serde(rename = "SAMLResponse")]
69    pub saml_response: String,
70    #[serde(rename = "RelayState")]
71    pub relay_state: Option<String>,
72    #[serde(rename = "SigAlg")]
73    pub sig_alg: Option<String>,
74    #[serde(rename = "Signature")]
75    pub signature: Option<String>,
76}
77
78/// SAML metadata configuration
79#[derive(Debug, Serialize, Deserialize)]
80pub struct SamlMetadataResponse {
81    pub entity_id: String,
82    pub acs_url: String,
83    pub sls_url: Option<String>,
84    pub certificate: Option<String>,
85    pub name_id_format: String,
86}
87
88#[derive(Debug, Deserialize)]
89struct SamlSpConfig {
90    entity_id: String,
91    acs_url: String,
92    #[serde(default)]
93    slo_url: Option<String>,
94}
95
96impl SamlSpConfig {
97    fn validate(self) -> Result<Self, String> {
98        if self.entity_id.trim().is_empty() {
99            return Err("missing entity_id".to_string());
100        }
101        if self.acs_url.trim().is_empty() {
102            return Err("missing acs_url".to_string());
103        }
104        Ok(self)
105    }
106
107    fn slo_url(&self) -> Result<&str, String> {
108        self.slo_url
109            .as_deref()
110            .filter(|value| !value.trim().is_empty())
111            .ok_or_else(|| "missing slo_url".to_string())
112    }
113}
114
115async fn load_saml_sp_config(state: &ApiState) -> Result<SamlSpConfig, String> {
116    let data = state
117        .auth_framework
118        .storage()
119        .get_kv("saml_sp:config")
120        .await
121        .map_err(|_| "failed to load saml_sp:config".to_string())?
122        .ok_or_else(|| "missing saml_sp:config".to_string())?;
123
124    serde_json::from_slice::<SamlSpConfig>(&data)
125        .map_err(|_| "invalid saml_sp:config JSON".to_string())?
126        .validate()
127}
128
129/// SAML logout request
130#[derive(Debug, Serialize, Deserialize)]
131pub struct SamlLogoutRequest {
132    pub name_id: String,
133    pub session_index: Option<String>,
134    pub idp_entity_id: String,
135}
136
137/// SAML logout response
138#[derive(Debug, Serialize, Deserialize)]
139pub struct SamlLogoutResponse {
140    pub redirect_url: String,
141    pub status: String,
142}
143
144/// Get SAML metadata for this SP (Service Provider).
145/// SP configuration (entity_id, acs_url, slo_url) is read from storage key `saml_sp:config`.
146/// Store a JSON object with those fields to customise the metadata for your deployment.
147pub async fn get_saml_metadata(State(state): State<ApiState>) -> impl IntoResponse {
148    let sp_config = match load_saml_sp_config(&state).await {
149        Ok(config) => config,
150        Err(error) => {
151            tracing::error!(error = %error, "SAML metadata requested without valid SP configuration");
152            return (
153                StatusCode::INTERNAL_SERVER_ERROR,
154                Html("SAML service provider configuration is missing or incomplete".to_string()),
155            )
156                .into_response();
157        }
158    };
159    let slo_url = match sp_config.slo_url() {
160        Ok(url) => url,
161        Err(error) => {
162            tracing::error!(error = %error, "SAML metadata requested without SLO URL configured");
163            return (
164                StatusCode::INTERNAL_SERVER_ERROR,
165                Html("SAML service provider configuration is missing or incomplete".to_string()),
166            )
167                .into_response();
168        }
169    };
170
171    let metadata_xml = format!(
172        r#"<?xml version="1.0" encoding="UTF-8"?>
173<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
174                     entityID="{entity_id}">
175  <md:SPSSODescriptor AuthnRequestsSigned="true" WantAssertionsSigned="true"
176                      protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
177    <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
178    <md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
179                                Location="{acs_url}"
180                                index="0" />
181    <md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
182                               Location="{slo_url}" />
183  </md:SPSSODescriptor>
184</md:EntityDescriptor>"#,
185        entity_id = xml_escape(&sp_config.entity_id),
186        acs_url = xml_escape(&sp_config.acs_url),
187        slo_url = xml_escape(slo_url),
188    );
189
190    // Return SAML metadata with correct Content-Type per SAML metadata spec
191    (
192        StatusCode::OK,
193        [(
194            axum::http::header::CONTENT_TYPE,
195            "application/samlmetadata+xml",
196        )],
197        metadata_xml,
198    )
199        .into_response()
200}
201
202/// Initiate SAML SSO flow.
203/// The IdP must be pre-registered in storage under the key `saml_idp:{idp_entity_id}`
204/// as a JSON object with at least a `sso_url` field.  SP configuration is read from
205/// `saml_sp:config` (fields: `entity_id`, `acs_url`).
206pub async fn initiate_saml_sso(
207    State(state): State<ApiState>,
208    Json(request): Json<SamlSsoRequest>,
209) -> Json<ApiResponse<SamlSsoResponse>> {
210    // Look up IdP SSO URL from storage — reject unknown IdPs rather than
211    // redirecting to a hardcoded placeholder.
212    let idp_key = format!("saml_idp:{}", request.idp_entity_id);
213    let idp_sso_url = match state.auth_framework.storage().get_kv(&idp_key).await {
214        Ok(Some(data)) => {
215            let cfg: serde_json::Value = serde_json::from_slice(&data).unwrap_or_default();
216            match cfg["sso_url"].as_str() {
217                Some(url) => url.to_string(),
218                None => {
219                    return Json(ApiResponse::error_typed(
220                        "SAML_CONFIG_ERROR",
221                        "IdP config is missing required sso_url field",
222                    ));
223                }
224            }
225        }
226        Ok(None) => {
227            tracing::warn!(idp = %request.idp_entity_id, "SAML SSO: unknown IdP entity ID");
228            return Json(ApiResponse::error_typed(
229                "SAML_UNKNOWN_IDP",
230                format!("IdP not configured: {}", request.idp_entity_id),
231            ));
232        }
233        Err(e) => {
234            tracing::error!(error = %e, "SAML SSO: storage error looking up IdP");
235            return Json(ApiResponse::error_typed(
236                "server_error",
237                "Failed to look up IdP configuration",
238            ));
239        }
240    };
241
242    let sp_config = match load_saml_sp_config(&state).await {
243        Ok(config) => config,
244        Err(error) => {
245            tracing::error!(error = %error, "SAML SSO requested without valid SP configuration");
246            return Json(ApiResponse::error_typed(
247                "SAML_CONFIG_ERROR",
248                "Service Provider configuration is missing required entity_id and acs_url values",
249            ));
250        }
251    };
252
253    // Generate SAML AuthnRequest
254    let request_id = format!("saml_{}", uuid::Uuid::new_v4());
255    let issue_instant = chrono::Utc::now().to_rfc3339();
256
257    let saml_request = format!(
258        r#"<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
259                           xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
260                           ID="{request_id}"
261                           Version="2.0"
262                           IssueInstant="{issue_instant}"
263                           Destination="{idp_sso_url}"
264                           {force_authn}
265                           {is_passive}
266                           AssertionConsumerServiceURL="{sp_acs_url}">
267  <saml:Issuer>{sp_entity_id}</saml:Issuer>
268  <samlp:NameIDPolicy Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
269                      AllowCreate="true" />
270</samlp:AuthnRequest>"#,
271        force_authn = request
272            .force_authn
273            .map_or(String::new(), |fa| format!(r#"ForceAuthn="{}""#, fa)),
274        is_passive = request
275            .is_passive
276            .map_or(String::new(), |ip| format!(r#"IsPassive="{}""#, ip)),
277        sp_entity_id = xml_escape(&sp_config.entity_id),
278        sp_acs_url = xml_escape(&sp_config.acs_url),
279        idp_sso_url = xml_escape(&idp_sso_url),
280    );
281
282    // Encode SAML request
283    let encoded_request = base64::engine::general_purpose::STANDARD.encode(&saml_request);
284
285    // Build redirect URL
286    let mut redirect_url = format!(
287        "{}?SAMLRequest={}",
288        idp_sso_url,
289        urlencoding::encode(&encoded_request)
290    );
291
292    if let Some(relay_state) = &request.relay_state {
293        redirect_url.push_str(&format!("&RelayState={}", urlencoding::encode(relay_state)));
294    }
295
296    // Persist the AuthnRequest so the ACS handler can validate InResponseTo.
297    let request_key = format!("saml_request:{}", request_id);
298    let request_data = serde_json::json!({
299        "request_id": request_id,
300        "idp_entity_id": request.idp_entity_id,
301        "relay_state": request.relay_state,
302        "issued_at": chrono::Utc::now().to_rfc3339(),
303    })
304    .to_string();
305    if let Err(e) = state
306        .auth_framework
307        .storage()
308        .store_kv(
309            &request_key,
310            request_data.as_bytes(),
311            Some(std::time::Duration::from_secs(600)),
312        )
313        .await
314    {
315        tracing::warn!(error = %e, "SAML SSO: failed to persist AuthnRequest — InResponseTo validation will be skipped");
316    }
317
318    Json(ApiResponse::success(SamlSsoResponse {
319        redirect_url,
320        saml_request: encoded_request,
321        relay_state: request.relay_state,
322    }))
323}
324
325/// Handle SAML ACS (Assertion Consumer Service) - where IdP sends response
326#[allow(unreachable_code, unused_variables)]
327pub async fn handle_saml_acs(
328    State(state): State<ApiState>,
329    axum::Form(form_data): axum::Form<SamlAcsRequest>,
330) -> Json<ApiResponse<serde_json::Value>> {
331    // Decode SAML response
332    let saml_response_xml =
333        match base64::engine::general_purpose::STANDARD.decode(&form_data.saml_response) {
334            Ok(decoded) => match String::from_utf8(decoded) {
335                Ok(xml) => xml,
336                Err(e) => {
337                    tracing::warn!(error = %e, "SAML ACS: invalid UTF-8 in decoded response");
338                    return Json(ApiResponse::validation_error_typed(
339                        "Invalid SAML response encoding",
340                    ));
341                }
342            },
343            Err(e) => {
344                tracing::warn!(error = %e, "SAML ACS: base64 decode failed");
345                return Json(ApiResponse::validation_error_typed(
346                    "Invalid SAML response encoding",
347                ));
348            }
349        };
350
351    // --- XML Digital Signature Validation ---
352    #[cfg(feature = "saml")]
353    {
354        match validate_saml_signature(&state, &saml_response_xml).await {
355            Ok(()) => {
356                tracing::info!("SAML ACS: XML signature validated successfully");
357            }
358            Err(e) => {
359                tracing::error!(error = %e, "SAML ACS: XML signature validation failed");
360                return Json(ApiResponse::error_typed(
361                    "SAML_SIGNATURE_INVALID",
362                    format!("SAML response signature validation failed: {}", e),
363                ));
364            }
365        }
366    }
367    #[cfg(not(feature = "saml"))]
368    {
369        tracing::error!(
370            "SAML ACS: XML signature validation is not available — \
371             the 'saml' feature is required for secure SAML processing"
372        );
373        return Json(ApiResponse::error_typed(
374            "SAML_SIGNATURE_UNAVAILABLE",
375            "SAML signature validation is not available; the server must be compiled with the 'saml' feature",
376        ));
377    }
378
379    if !saml_response_xml.contains("<saml:Assertion")
380        && !saml_response_xml.contains("<saml2:Assertion")
381        && !saml_response_xml.contains("<Assertion")
382    {
383        return Json(ApiResponse::validation_error_typed(
384            "No SAML assertion found",
385        ));
386    }
387
388    // Validate InResponseTo: the SAML response must reference an AuthnRequest that
389    // we actually issued.  This prevents unsolicited response injection attacks.
390    if let Some(irt) = extract_in_response_to(&saml_response_xml) {
391        let request_key = format!("saml_request:{}", irt);
392        match state.auth_framework.storage().get_kv(&request_key).await {
393            Ok(Some(_)) => {
394                // Valid outstanding request — consume it so it cannot be replayed.
395                let _ = state.auth_framework.storage().delete_kv(&request_key).await;
396            }
397            _ => {
398                tracing::warn!(in_response_to = %irt, "SAML ACS: InResponseTo references unknown or expired request");
399                return Json(ApiResponse::error_typed(
400                    "SAML_INVALID_RESPONSE",
401                    "SAML response references an unknown or expired authentication request",
402                ));
403            }
404        }
405    } else {
406        // Unsolicited SAML responses (no InResponseTo) are a common attack vector.
407        tracing::warn!(
408            "SAML ACS: response has no InResponseTo attribute — rejecting unsolicited response"
409        );
410        return Json(ApiResponse::error_typed(
411            "SAML_UNSOLICITED_RESPONSE",
412            "Unsolicited SAML responses are not accepted; initiate SSO via /api/v1/saml/sso first",
413        ));
414    }
415
416    // --- SAML Assertion Conditions Validation ---
417    // Validate NotBefore, NotOnOrAfter, and AudienceRestriction per SAML Core 2.5.1.
418    #[cfg(feature = "saml")]
419    {
420        let sp_entity_id = match load_saml_sp_config(&state).await {
421            Ok(config) => config.entity_id,
422            Err(error) => {
423                tracing::error!(error = %error, "SAML ACS requested without valid SP configuration");
424                return Json(ApiResponse::error_typed(
425                    "SAML_CONFIG_ERROR",
426                    "Service Provider configuration is missing required entity_id and acs_url values",
427                ));
428            }
429        };
430
431        if let Err(e) = validate_saml_conditions(&saml_response_xml, &sp_entity_id) {
432            tracing::warn!(error = %e, "SAML ACS: assertion conditions validation failed");
433            return Json(ApiResponse::error_typed("SAML_CONDITIONS_INVALID", e));
434        }
435    }
436
437    // Extract user information from assertion
438    let username = match extract_username_from_saml(&saml_response_xml) {
439        Ok(user) => user,
440        Err(e) => return Json(ApiResponse::error_typed("SAML_PARSE_ERROR", e)),
441    };
442
443    let attributes = match extract_attributes_from_saml(&saml_response_xml) {
444        Ok(attrs) => attrs,
445        Err(e) => return Json(ApiResponse::error_typed("SAML_PARSE_ERROR", e)),
446    };
447
448    // Issue a proper JWT/auth token using the framework's token infrastructure.
449    let scopes = vec![
450        "openid".to_string(),
451        "profile".to_string(),
452        "email".to_string(),
453    ];
454    let token = match state
455        .auth_framework
456        .token_manager()
457        .create_auth_token(&username, scopes, "saml", None)
458    {
459        Ok(t) => t,
460        Err(e) => {
461            tracing::error!(user = %username, error = %e, "SAML ACS: failed to create auth token");
462            return Json(ApiResponse::error_typed(
463                "server_error",
464                "Failed to create authentication token",
465            ));
466        }
467    };
468
469    let token_data = serde_json::json!({
470        "access_token": token.access_token,
471        "token_type": "Bearer",
472        "expires_in": (token.expires_at - token.issued_at).num_seconds().max(0) as u64,
473        "refresh_token": token.refresh_token,
474        "user_id": username,
475        "authentication_method": "saml",
476        "attributes": attributes,
477        "relay_state": form_data.relay_state
478    });
479
480    tracing::info!(user = %username, "SAML authentication successful");
481    Json(ApiResponse::success_with_message(
482        token_data,
483        "SAML authentication successful",
484    ))
485}
486
487/// Initiate SAML Single Logout (SLO).
488/// The IdP must be pre-registered in storage under `saml_idp:{idp_entity_id}` with a `slo_url` field.
489pub async fn initiate_saml_slo(
490    State(state): State<ApiState>,
491    Json(request): Json<SamlLogoutRequest>,
492) -> Json<ApiResponse<SamlLogoutResponse>> {
493    // Look up IdP SLO URL from storage.
494    let idp_key = format!("saml_idp:{}", request.idp_entity_id);
495    let idp_slo_url = match state.auth_framework.storage().get_kv(&idp_key).await {
496        Ok(Some(data)) => {
497            let cfg: serde_json::Value = serde_json::from_slice(&data).unwrap_or_default();
498            match cfg["slo_url"].as_str() {
499                Some(url) => url.to_string(),
500                None => {
501                    return Json(ApiResponse::error_typed(
502                        "SAML_CONFIG_ERROR",
503                        "IdP config is missing required slo_url field",
504                    ));
505                }
506            }
507        }
508        Ok(None) => {
509            tracing::warn!(idp = %request.idp_entity_id, "SAML SLO: unknown IdP entity ID");
510            return Json(ApiResponse::error_typed(
511                "SAML_UNKNOWN_IDP",
512                format!("IdP not configured: {}", request.idp_entity_id),
513            ));
514        }
515        Err(e) => {
516            tracing::error!(error = %e, "SAML SLO: storage error looking up IdP");
517            return Json(ApiResponse::error_typed(
518                "server_error",
519                "Failed to look up IdP configuration",
520            ));
521        }
522    };
523
524    let sp_config = match load_saml_sp_config(&state).await {
525        Ok(config) => config,
526        Err(error) => {
527            tracing::error!(error = %error, "SAML SLO requested without valid SP configuration");
528            return Json(ApiResponse::error_typed(
529                "SAML_CONFIG_ERROR",
530                "Service Provider configuration is missing required entity_id and acs_url values",
531            ));
532        }
533    };
534
535    let logout_id = format!("logout_{}", uuid::Uuid::new_v4());
536    let issue_instant = chrono::Utc::now().to_rfc3339();
537
538    // Build SAML LogoutRequest
539    let saml_logout_request = format!(
540        r#"<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
541                            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
542                            ID="{logout_id}"
543                            Version="2.0"
544                            IssueInstant="{issue_instant}"
545                            Destination="{idp_slo_url}">
546    <saml:Issuer>{sp_entity_id}</saml:Issuer>
547  <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">{name_id}</saml:NameID>
548  {session_index}
549</samlp:LogoutRequest>"#,
550        name_id = xml_escape(&request.name_id),
551        session_index = request.session_index.map_or(String::new(), |si| format!(
552            r#"<samlp:SessionIndex>{}</samlp:SessionIndex>"#,
553            xml_escape(&si)
554        )),
555        sp_entity_id = xml_escape(&sp_config.entity_id),
556        idp_slo_url = xml_escape(&idp_slo_url),
557    );
558
559    let encoded_request = base64::engine::general_purpose::STANDARD.encode(&saml_logout_request);
560    let redirect_url = format!(
561        "{}?SAMLRequest={}",
562        idp_slo_url,
563        urlencoding::encode(&encoded_request)
564    );
565
566    Json(ApiResponse::success_with_message(
567        SamlLogoutResponse {
568            redirect_url,
569            status: "logout_initiated".to_string(),
570        },
571        "SAML logout initiated",
572    ))
573}
574
575/// Handle SAML SLO response from IdP
576pub async fn handle_saml_slo_response(
577    State(_state): State<ApiState>,
578    Query(params): Query<HashMap<String, String>>,
579) -> Json<ApiResponse<()>> {
580    #[cfg(not(feature = "saml"))]
581    {
582        let _ = params;
583        return Json(ApiResponse::error_typed(
584            "SAML_SIGNATURE_UNAVAILABLE",
585            "SAML logout response validation is not available; the server must be compiled with the 'saml' feature",
586        ));
587    }
588
589    #[cfg(feature = "saml")]
590    {
591        let saml_response = match params.get("SAMLResponse") {
592            Some(response) => response,
593            None => {
594                return Json(ApiResponse::validation_error(
595                    "Missing SAMLResponse parameter",
596                ));
597            }
598        };
599
600        // Decode and validate SLO response.
601        let response_xml = match base64::engine::general_purpose::STANDARD.decode(saml_response) {
602            Ok(decoded) => match String::from_utf8(decoded) {
603                Ok(xml) => xml,
604                Err(e) => {
605                    return Json(ApiResponse::validation_error(format!(
606                        "Invalid SLO response UTF-8: {}",
607                        e
608                    )));
609                }
610            },
611            Err(e) => {
612                return Json(ApiResponse::validation_error(format!(
613                    "Invalid SLO response encoding: {}",
614                    e
615                )));
616            }
617        };
618
619        let slo_success = xml_extract_status_code(&response_xml)
620            .map(|code| code == "urn:oasis:names:tc:SAML:2.0:status:Success")
621            .unwrap_or(false);
622
623        if slo_success {
624            // Invalidate the user's session associated with this SAML exchange.
625            // The SAML response should carry the NameID that maps to our user.
626            if let Some(name_id) = xml_extract_name_id(&response_xml) {
627                // Look up user by email (NameID) and invalidate their sessions.
628                if let Ok(Some(uid_bytes)) = _state
629                    .auth_framework
630                    .storage()
631                    .get_kv(&format!("user:email:{}", name_id))
632                    .await
633                {
634                    let user_id = String::from_utf8_lossy(&uid_bytes).to_string();
635                    let session_key = format!("sessions:user:{}", user_id);
636                    let _ = _state
637                        .auth_framework
638                        .storage()
639                        .delete_kv(&session_key)
640                        .await;
641                    tracing::info!(user_id = %user_id, "SAML SLO: invalidated sessions");
642                }
643            }
644
645            // Handle RelayState redirect if provided
646            if let Some(relay_state) = params.get("RelayState") {
647                if !relay_state.is_empty() {
648                    tracing::debug!(relay_state = %relay_state, "SAML SLO: RelayState provided");
649                }
650            }
651
652            Json(ApiResponse::<()>::ok_with_message(
653                "SAML logout completed successfully",
654            ))
655        } else {
656            Json(ApiResponse::error(
657                "SAML_LOGOUT_FAILED",
658                "SAML logout failed",
659            ))
660        }
661    }
662}
663
664/// Create SAML assertion (for Identity Provider functionality)
665pub async fn create_saml_assertion(
666    State(state): State<ApiState>,
667    Json(request): Json<serde_json::Value>,
668) -> Json<ApiResponse<String>> {
669    let username = match request["username"].as_str() {
670        Some(user) => user,
671        None => return Json(ApiResponse::validation_error_typed("Username required")),
672    };
673
674    let audience = match request["audience"].as_str() {
675        Some(aud) => aud,
676        None => return Json(ApiResponse::validation_error_typed("Audience required")),
677    };
678
679    let sp_config = match load_saml_sp_config(&state).await {
680        Ok(config) => config,
681        Err(error) => {
682            tracing::error!(error = %error, "SAML assertion requested without valid SP configuration");
683            return Json(ApiResponse::error_typed(
684                "SAML_CONFIG_ERROR",
685                "Service Provider configuration is missing required entity_id and acs_url values",
686            ));
687        }
688    };
689
690    let name_id = match request["email"].as_str().map(str::trim) {
691        Some(email) if !email.is_empty() => email.to_string(),
692        _ if username.contains('@') => username.to_string(),
693        _ => {
694            return Json(ApiResponse::validation_error_typed(
695                "Email required when username is not an email address",
696            ));
697        }
698    };
699
700    // Create SAML assertion with Response wrapper.
701    // Note: In production, this assertion should be signed with an XML-DSig
702    // private key. Without signing, relying parties that enforce signature
703    // verification will reject the assertion.
704    let assertion_id = uuid::Uuid::new_v4();
705    let response_id = uuid::Uuid::new_v4();
706    let now = chrono::Utc::now();
707    let not_before = (now - chrono::Duration::minutes(1)).to_rfc3339();
708    let not_after = (now + chrono::Duration::hours(1)).to_rfc3339();
709    let now_str = now.to_rfc3339();
710    // Issuer is our own entity (acting as IdP), not the SP
711    let issuer = xml_escape(&sp_config.entity_id);
712    let audience_escaped = xml_escape(audience);
713    let name_id_escaped = xml_escape(&name_id);
714    let username_escaped = xml_escape(username);
715
716    let assertion_xml = format!(
717        r#"<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
718                         xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
719                         ID="response_{response_id}"
720                         IssueInstant="{now_str}"
721                         Destination="{audience_escaped}"
722                         Version="2.0">
723  <saml:Issuer>{issuer}</saml:Issuer>
724  <samlp:Status>
725    <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
726  </samlp:Status>
727  <saml:Assertion ID="assertion_{assertion_id}"
728                  IssueInstant="{now_str}"
729                  Version="2.0">
730    <saml:Issuer>{issuer}</saml:Issuer>
731    <saml:Subject>
732      <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">{name_id_escaped}</saml:NameID>
733      <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
734        <saml:SubjectConfirmationData NotOnOrAfter="{not_after}" Recipient="{audience_escaped}"/>
735      </saml:SubjectConfirmation>
736    </saml:Subject>
737    <saml:Conditions NotBefore="{not_before}" NotOnOrAfter="{not_after}">
738      <saml:AudienceRestriction>
739        <saml:Audience>{audience_escaped}</saml:Audience>
740      </saml:AudienceRestriction>
741    </saml:Conditions>
742    <saml:AuthnStatement AuthnInstant="{now_str}" SessionIndex="session_{assertion_id}">
743      <saml:AuthnContext>
744        <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
745      </saml:AuthnContext>
746    </saml:AuthnStatement>
747    <saml:AttributeStatement>
748      <saml:Attribute Name="username">
749        <saml:AttributeValue>{username_escaped}</saml:AttributeValue>
750      </saml:Attribute>
751      <saml:Attribute Name="email">
752        <saml:AttributeValue>{name_id_escaped}</saml:AttributeValue>
753      </saml:Attribute>
754    </saml:AttributeStatement>
755  </saml:Assertion>
756</samlp:Response>"#,
757    );
758
759    Json(ApiResponse::success_with_message(
760        assertion_xml,
761        "SAML assertion created",
762    ))
763}
764
765/// List configured SAML Identity Providers.
766/// IdPs are indexed in storage under the key `saml_idps:index` (JSON array of entity ID strings).
767/// Each IdP's configuration is stored under `saml_idp:{entity_id}`.
768pub async fn list_saml_idps(
769    State(state): State<ApiState>,
770) -> Json<ApiResponse<Vec<serde_json::Value>>> {
771    // Load the IdP index from storage.
772    let entity_ids: Vec<String> = match state
773        .auth_framework
774        .storage()
775        .get_kv("saml_idps:index")
776        .await
777    {
778        Ok(Some(data)) => serde_json::from_slice(&data).unwrap_or_default(),
779        Ok(None) => vec![],
780        Err(e) => {
781            tracing::error!(error = %e, "Failed to load SAML IdP index");
782            return Json(ApiResponse::error_typed(
783                "server_error",
784                "Failed to load IdP list",
785            ));
786        }
787    };
788
789    // Fetch each IdP's config.
790    let mut idps = Vec::with_capacity(entity_ids.len());
791    for entity_id in &entity_ids {
792        let key = format!("saml_idp:{}", entity_id);
793        if let Ok(Some(data)) = state.auth_framework.storage().get_kv(&key).await
794            && let Ok(cfg) = serde_json::from_slice::<serde_json::Value>(&data)
795        {
796            idps.push(cfg);
797        }
798    }
799
800    Json(ApiResponse::success_with_message(
801        idps,
802        "SAML IdPs retrieved",
803    ))
804}
805
806/// Validate the XML-DSig signature on a SAML response using the IdP's trusted signing key.
807///
808/// The IdP's signing certificate (PEM-encoded X.509) must be stored under
809/// `saml_idp:{entity_id}` in the `signing_cert` field.  The IdP entity ID is
810/// extracted from the `<saml:Issuer>` element inside the SAML response.
811///
812/// Uses bergshamra with SAML-hardened settings:
813/// - `trusted_keys_only = true` — ignores attacker-embedded inline KeyInfo
814/// - `strict_verification = true` — XSW attack protection
815/// - `verify_keys = true` — validates key certificates
816#[cfg(feature = "saml")]
817async fn validate_saml_signature(state: &ApiState, saml_xml: &str) -> Result<(), String> {
818    // Extract the IdP entity ID (Issuer) from the response so we can look up
819    // the correct signing key.
820    let issuer = extract_issuer(saml_xml)
821        .ok_or_else(|| "SAML response does not contain an Issuer element".to_string())?;
822
823    // Load the IdP's signing certificate from storage.
824    let idp_key = format!("saml_idp:{}", issuer);
825    let idp_cfg_data = state
826        .auth_framework
827        .storage()
828        .get_kv(&idp_key)
829        .await
830        .map_err(|e| format!("Storage error loading IdP config: {}", e))?
831        .ok_or_else(|| format!("IdP not configured: {}", issuer))?;
832
833    let idp_cfg: serde_json::Value = serde_json::from_slice(&idp_cfg_data)
834        .map_err(|e| format!("Invalid IdP config JSON: {}", e))?;
835
836    let signing_cert_pem = idp_cfg["signing_cert"]
837        .as_str()
838        .ok_or_else(|| format!("IdP '{}' has no signing_cert configured", issuer))?;
839
840    // Parse PEM certificate to DER bytes.
841    let der_bytes = pem_to_der(signing_cert_pem)?;
842
843    // Build the KeysManager with the trusted IdP key.
844    let mut keys_manager = KeysManager::new();
845
846    // Parse the X.509 certificate to extract the public key, then build a
847    // bergshamra Key from it.  Most SAML IdPs use RSA; we also support ECDSA.
848    let key = key_from_x509_der(&der_bytes)?;
849    keys_manager.add_key(key);
850
851    // Also register the cert as a trusted certificate for chain validation.
852    keys_manager.add_trusted_cert(der_bytes);
853
854    // SAML-hardened DsigContext configuration:
855    // - trusted_keys_only: only use our pre-loaded IdP key, ignore inline KeyInfo
856    // - strict_verification: reject XSW (XML Signature Wrapping) attacks
857    // - verify_keys: validate certificates on the keys
858    let ctx = DsigContext::new(keys_manager)
859        .with_trusted_keys_only(true)
860        .with_strict_verification(true)
861        .with_verify_keys(true);
862
863    // Verify the XML signature.
864    let result =
865        verify(&ctx, saml_xml).map_err(|e| format!("XML-DSig verification error: {}", e))?;
866
867    match result {
868        VerifyResult::Valid { references, .. } => {
869            // Ensure the signature actually covers content (not an empty reference set).
870            if references.is_empty() {
871                return Err("Signature is valid but covers no references".to_string());
872            }
873            Ok(())
874        }
875        VerifyResult::Invalid { reason } => Err(format!("Signature invalid: {}", reason)),
876    }
877}
878
879/// Decode a PEM-encoded certificate to raw DER bytes.
880#[cfg(feature = "saml")]
881fn pem_to_der(pem: &str) -> Result<Vec<u8>, String> {
882    // Strip PEM headers/footers and whitespace, then base64-decode.
883    let b64: String = pem
884        .lines()
885        .filter(|line| {
886            !line.starts_with("-----BEGIN") && !line.starts_with("-----END") && !line.is_empty()
887        })
888        .collect::<Vec<&str>>()
889        .join("");
890
891    base64::engine::general_purpose::STANDARD
892        .decode(&b64)
893        .map_err(|e| format!("Failed to base64-decode PEM certificate: {}", e))
894}
895
896/// Extract a bergshamra `Key` from a DER-encoded X.509 certificate.
897///
898/// Supports RSA and ECDSA (P-256/P-384) public keys — the algorithms used by
899/// the vast majority of SAML Identity Providers.
900#[cfg(feature = "saml")]
901fn key_from_x509_der(der: &[u8]) -> Result<Key, String> {
902    use rsa::pkcs8::DecodePublicKey;
903    use x509_parser::prelude::*;
904
905    let (_, cert) = X509Certificate::from_der(der)
906        .map_err(|e| format!("Failed to parse X.509 certificate: {}", e))?;
907
908    let spki = cert.public_key();
909    let spki_der = spki.raw;
910
911    // Try RSA first (by far the most common in SAML).
912    if let Ok(rsa_pub) = rsa::RsaPublicKey::from_public_key_der(spki_der) {
913        return Ok(Key::new(
914            KeyData::Rsa {
915                public: rsa_pub,
916                private: None,
917            },
918            bergshamra::KeyUsage::Verify,
919        ));
920    }
921
922    // ECDSA P-256.
923    if let Ok(ec_key) = p256::ecdsa::VerifyingKey::from_public_key_der(spki_der) {
924        return Ok(Key::new(
925            KeyData::EcP256 {
926                public: ec_key,
927                private: None,
928            },
929            bergshamra::KeyUsage::Verify,
930        ));
931    }
932
933    // ECDSA P-384.
934    if let Ok(ec_key) = p384::ecdsa::VerifyingKey::from_public_key_der(spki_der) {
935        return Ok(Key::new(
936            KeyData::EcP384 {
937                public: ec_key,
938                private: None,
939            },
940            bergshamra::KeyUsage::Verify,
941        ));
942    }
943
944    Err(format!(
945        "Unsupported IdP signing key algorithm (OID: {}). RSA, P-256, and P-384 are supported.",
946        cert.public_key().algorithm.oid()
947    ))
948}
949
950/// Extract the `<saml:Issuer>` or `<saml2:Issuer>` value from the top-level
951/// `<samlp:Response>` element using proper XML parsing.
952#[cfg(feature = "saml")]
953fn extract_issuer(saml_xml: &str) -> Option<String> {
954    let mut reader = Reader::from_str(saml_xml);
955    let mut in_response = false;
956    let mut in_issuer = false;
957    let mut depth: u32 = 0;
958
959    loop {
960        match reader.read_event() {
961            Ok(Event::Start(e)) => {
962                let local = xml_local(e.name());
963                if local == b"Response" && !in_response {
964                    in_response = true;
965                    depth = 1;
966                } else if in_response {
967                    depth += 1;
968                    // Issuer must be a direct child of Response (depth == 2).
969                    if local == b"Issuer" && depth == 2 {
970                        in_issuer = true;
971                    }
972                }
973            }
974            Ok(Event::End(e)) => {
975                let local = xml_local(e.name());
976                if in_issuer && local == b"Issuer" {
977                    in_issuer = false;
978                }
979                if in_response {
980                    depth -= 1;
981                    if depth == 0 {
982                        break; // Exited the Response element.
983                    }
984                }
985            }
986            Ok(Event::Text(t)) if in_issuer => {
987                if let Ok(text) = t.decode() {
988                    let s = text.trim();
989                    if !s.is_empty() {
990                        return Some(s.to_string());
991                    }
992                }
993            }
994            Ok(Event::Eof) => break,
995            Err(_) => break,
996            _ => {}
997        }
998    }
999    None
1000}
1001
1002/// Extract the `InResponseTo` attribute from the top-level `<samlp:Response>` element
1003/// using proper XML parsing.
1004#[cfg(feature = "saml")]
1005fn extract_in_response_to(saml_xml: &str) -> Option<String> {
1006    let mut reader = Reader::from_str(saml_xml);
1007    loop {
1008        match reader.read_event() {
1009            Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
1010                if xml_local(e.name()) == b"Response" {
1011                    for attr in e.attributes().flatten() {
1012                        if attr.key.as_ref() == b"InResponseTo" {
1013                            return String::from_utf8(attr.value.to_vec()).ok();
1014                        }
1015                    }
1016                    return None; // Found Response but no InResponseTo.
1017                }
1018            }
1019            Ok(Event::Eof) => break,
1020            Err(_) => break,
1021            _ => {}
1022        }
1023    }
1024    None
1025}
1026
1027/// Fallback InResponseTo extractor used when `saml` feature is disabled.
1028#[cfg(not(feature = "saml"))]
1029fn extract_in_response_to(saml_xml: &str) -> Option<String> {
1030    // Minimal string-based fallback — only used in the non-saml path which now
1031    // hard-fails before reaching username extraction, so this is defence-in-depth.
1032    let response_tag_start = saml_xml.find("<samlp:Response")?;
1033    let tag_end = saml_xml[response_tag_start..].find('>')?;
1034    let tag = &saml_xml[response_tag_start..response_tag_start + tag_end];
1035    let attr_start = tag.find("InResponseTo=\"")?;
1036    let value_start = attr_start + "InResponseTo=\"".len();
1037    let value_end = tag[value_start..].find('"')?;
1038    Some(tag[value_start..value_start + value_end].to_string())
1039}
1040
1041/// Extract the username from the `<saml:NameID>` element inside the first
1042/// `<saml:Assertion>` using proper XML parsing.
1043#[cfg(feature = "saml")]
1044fn extract_username_from_saml(saml_xml: &str) -> Result<String, String> {
1045    let mut reader = Reader::from_str(saml_xml);
1046    let mut in_assertion = false;
1047    let mut in_name_id = false;
1048
1049    loop {
1050        match reader.read_event() {
1051            Ok(Event::Start(e)) => {
1052                let local = xml_local(e.name());
1053                if local == b"Assertion" {
1054                    in_assertion = true;
1055                } else if in_assertion && local == b"NameID" {
1056                    in_name_id = true;
1057                }
1058            }
1059            Ok(Event::End(e)) => {
1060                let local = xml_local(e.name());
1061                if in_name_id && local == b"NameID" {
1062                    in_name_id = false;
1063                }
1064                if local == b"Assertion" {
1065                    break; // Only look in the first Assertion.
1066                }
1067            }
1068            Ok(Event::Text(t)) if in_name_id => {
1069                if let Ok(text) = t.decode() {
1070                    let s = text.trim();
1071                    if !s.is_empty() {
1072                        return Ok(s.to_string());
1073                    }
1074                }
1075            }
1076            Ok(Event::Eof) => break,
1077            Err(e) => return Err(format!("XML parse error extracting NameID: {}", e)),
1078            _ => {}
1079        }
1080    }
1081
1082    Err("Could not extract username from SAML assertion".to_string())
1083}
1084
1085/// Fallback username extractor used when `saml` feature is disabled.
1086#[cfg(not(feature = "saml"))]
1087fn extract_username_from_saml(_saml_xml: &str) -> Result<String, String> {
1088    // The non-saml path now hard-fails before reaching this point.
1089    Err("SAML parsing requires the 'saml' feature".to_string())
1090}
1091
1092/// Extract SAML attributes from `<saml:AttributeStatement>` using proper XML parsing.
1093#[cfg(feature = "saml")]
1094fn extract_attributes_from_saml(saml_xml: &str) -> Result<HashMap<String, Vec<String>>, String> {
1095    let mut attributes = HashMap::new();
1096    attributes.insert("source".to_string(), vec!["saml".to_string()]);
1097    attributes.insert("auth_method".to_string(), vec!["saml_sso".to_string()]);
1098
1099    let mut reader = Reader::from_str(saml_xml);
1100    let mut in_attr_statement = false;
1101    let mut in_attribute = false;
1102    let mut in_attr_value = false;
1103    let mut current_attr_name: Option<String> = None;
1104    let mut current_values: Vec<String> = Vec::new();
1105
1106    loop {
1107        match reader.read_event() {
1108            Ok(Event::Start(e)) => {
1109                let local = xml_local(e.name());
1110                if local == b"AttributeStatement" {
1111                    in_attr_statement = true;
1112                } else if in_attr_statement && local == b"Attribute" {
1113                    in_attribute = true;
1114                    current_values.clear();
1115                    current_attr_name = None;
1116                    for attr in e.attributes().flatten() {
1117                        if xml_local(attr.key) == b"Name" {
1118                            current_attr_name = String::from_utf8(attr.value.to_vec()).ok();
1119                        }
1120                    }
1121                } else if in_attribute && local == b"AttributeValue" {
1122                    in_attr_value = true;
1123                }
1124            }
1125            Ok(Event::End(e)) => {
1126                let local = xml_local(e.name());
1127                if local == b"AttributeValue" {
1128                    in_attr_value = false;
1129                } else if local == b"Attribute" && in_attribute {
1130                    if let Some(name) = current_attr_name.take()
1131                        && !current_values.is_empty()
1132                    {
1133                        attributes.insert(name, std::mem::take(&mut current_values));
1134                    }
1135                    in_attribute = false;
1136                } else if local == b"AttributeStatement" {
1137                    in_attr_statement = false;
1138                }
1139            }
1140            Ok(Event::Text(t)) if in_attr_value => {
1141                if let Ok(text) = t.decode() {
1142                    let s = text.trim();
1143                    if !s.is_empty() {
1144                        current_values.push(s.to_string());
1145                    }
1146                }
1147            }
1148            Ok(Event::Eof) => break,
1149            Err(_) => break,
1150            _ => {}
1151        }
1152    }
1153
1154    Ok(attributes)
1155}
1156
1157/// Fallback attribute extractor used when `saml` feature is disabled.
1158#[cfg(not(feature = "saml"))]
1159fn extract_attributes_from_saml(_saml_xml: &str) -> Result<HashMap<String, Vec<String>>, String> {
1160    Err("SAML parsing requires the 'saml' feature".to_string())
1161}
1162
1163/// Validate the SAML assertion's `<saml:Conditions>` element.
1164///
1165/// Checks:
1166/// - `NotBefore` / `NotOnOrAfter` against the current time (with 60-second clock skew allowance)
1167/// - `AudienceRestriction` contains the SP's entity ID
1168#[cfg(feature = "saml")]
1169fn validate_saml_conditions(saml_xml: &str, sp_entity_id: &str) -> Result<(), String> {
1170    let mut reader = Reader::from_str(saml_xml);
1171    let mut in_assertion = false;
1172    let mut in_conditions = false;
1173    let mut in_audience_restriction = false;
1174    let mut in_audience = false;
1175    let mut found_conditions = false;
1176    let mut not_before: Option<String> = None;
1177    let mut not_on_or_after: Option<String> = None;
1178    let mut audiences: Vec<String> = Vec::new();
1179
1180    loop {
1181        match reader.read_event() {
1182            Ok(Event::Start(e)) => {
1183                let local = xml_local(e.name());
1184                if local == b"Assertion" {
1185                    in_assertion = true;
1186                } else if in_assertion && local == b"Conditions" {
1187                    in_conditions = true;
1188                    found_conditions = true;
1189                    for attr in e.attributes().flatten() {
1190                        let key = attr.key.as_ref();
1191                        if key == b"NotBefore" {
1192                            not_before = String::from_utf8(attr.value.to_vec()).ok();
1193                        } else if key == b"NotOnOrAfter" {
1194                            not_on_or_after = String::from_utf8(attr.value.to_vec()).ok();
1195                        }
1196                    }
1197                } else if in_conditions && local == b"AudienceRestriction" {
1198                    in_audience_restriction = true;
1199                } else if in_audience_restriction && local == b"Audience" {
1200                    in_audience = true;
1201                }
1202            }
1203            Ok(Event::End(e)) => {
1204                let local = xml_local(e.name());
1205                if local == b"Audience" {
1206                    in_audience = false;
1207                } else if local == b"AudienceRestriction" {
1208                    in_audience_restriction = false;
1209                } else if local == b"Conditions" {
1210                    break; // Only process the first Conditions element.
1211                } else if local == b"Assertion" {
1212                    break;
1213                }
1214            }
1215            Ok(Event::Text(t)) if in_audience => {
1216                if let Ok(text) = t.decode() {
1217                    let s = text.trim();
1218                    if !s.is_empty() {
1219                        audiences.push(s.to_string());
1220                    }
1221                }
1222            }
1223            Ok(Event::Eof) => break,
1224            Err(e) => return Err(format!("XML parse error in Conditions: {}", e)),
1225            _ => {}
1226        }
1227    }
1228
1229    if !found_conditions {
1230        return Err("Assertion does not contain a Conditions element".to_string());
1231    }
1232
1233    // 60-second clock skew allowance per SAML implementation best practice.
1234    let skew = chrono::Duration::seconds(60);
1235    let now = chrono::Utc::now();
1236
1237    if let Some(nb) = not_before {
1238        let ts = chrono::DateTime::parse_from_rfc3339(&nb)
1239            .or_else(|_| chrono::DateTime::parse_from_str(&nb, "%Y-%m-%dT%H:%M:%S%.fZ"))
1240            .map_err(|e| format!("Invalid NotBefore timestamp '{}': {}", nb, e))?;
1241        if now < ts.with_timezone(&chrono::Utc) - skew {
1242            return Err(format!("Assertion is not yet valid (NotBefore: {})", nb));
1243        }
1244    }
1245
1246    if let Some(noa) = not_on_or_after {
1247        let ts = chrono::DateTime::parse_from_rfc3339(&noa)
1248            .or_else(|_| chrono::DateTime::parse_from_str(&noa, "%Y-%m-%dT%H:%M:%S%.fZ"))
1249            .map_err(|e| format!("Invalid NotOnOrAfter timestamp '{}': {}", noa, e))?;
1250        if now >= ts.with_timezone(&chrono::Utc) + skew {
1251            return Err(format!("Assertion has expired (NotOnOrAfter: {})", noa));
1252        }
1253    }
1254
1255    // Audience restriction: at least one <Audience> must match the SP's entity ID.
1256    if !audiences.is_empty() && !audiences.iter().any(|a| a == sp_entity_id) {
1257        return Err(format!(
1258            "Assertion audience restriction does not include this SP (expected '{}', got {:?})",
1259            sp_entity_id, audiences
1260        ));
1261    }
1262
1263    Ok(())
1264}
1265
1266/// Extract the `StatusCode@Value` from the first `<samlp:Status>` element
1267/// using proper XML parsing (used for SLO response validation).
1268#[cfg(feature = "saml")]
1269fn xml_extract_status_code(saml_xml: &str) -> Option<String> {
1270    let mut reader = Reader::from_str(saml_xml);
1271    let mut in_status = false;
1272
1273    loop {
1274        match reader.read_event() {
1275            Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
1276                let local = xml_local(e.name());
1277                if local == b"Status" {
1278                    in_status = true;
1279                } else if in_status && local == b"StatusCode" {
1280                    for attr in e.attributes().flatten() {
1281                        if attr.key.as_ref() == b"Value" {
1282                            return String::from_utf8(attr.value.to_vec()).ok();
1283                        }
1284                    }
1285                    return None; // StatusCode without Value attribute.
1286                }
1287            }
1288            Ok(Event::End(e)) => {
1289                if xml_local(e.name()) == b"Status" {
1290                    return None; // Status element ended without StatusCode.
1291                }
1292            }
1293            Ok(Event::Eof) => break,
1294            Err(_) => break,
1295            _ => {}
1296        }
1297    }
1298    None
1299}
1300
1301/// Extract the NameID text from the first `<saml:NameID>` element.
1302#[cfg(feature = "saml")]
1303fn xml_extract_name_id(saml_xml: &str) -> Option<String> {
1304    let mut reader = Reader::from_str(saml_xml);
1305    let mut in_name_id = false;
1306
1307    loop {
1308        match reader.read_event() {
1309            Ok(Event::Start(e)) => {
1310                if xml_local(e.name()) == b"NameID" {
1311                    in_name_id = true;
1312                }
1313            }
1314            Ok(Event::Text(e)) if in_name_id => {
1315                if let Ok(text) = e.decode() {
1316                    let s = text.trim();
1317                    if !s.is_empty() {
1318                        return Some(s.to_string());
1319                    }
1320                }
1321            }
1322            Ok(Event::End(e)) if in_name_id && xml_local(e.name()) == b"NameID" => {
1323                return None; // Empty NameID
1324            }
1325            Ok(Event::Eof) => break,
1326            Err(_) => break,
1327            _ => {}
1328        }
1329    }
1330    None
1331}
1332
1333#[cfg(test)]
1334#[cfg(feature = "saml")]
1335mod tests {
1336    use super::*;
1337    use chrono::{Duration, Utc};
1338
1339    #[test]
1340    fn test_extract_issuer() {
1341        // extract_issuer looks for an <Issuer> that is a direct child of a <Response> element.
1342        let xml = r#"<samlp:Response><saml:Issuer>https://idp.example.com</saml:Issuer></samlp:Response>"#;
1343        assert_eq!(extract_issuer(xml).unwrap(), "https://idp.example.com");
1344    }
1345
1346    #[test]
1347    fn test_extract_username() {
1348        // extract_username_from_saml looks for a <NameID> inside an <Assertion> element.
1349        let xml = r#"<saml:Assertion><saml:Subject><saml:NameID>user@example.com</saml:NameID></saml:Subject></saml:Assertion>"#;
1350        assert_eq!(extract_username_from_saml(xml).unwrap(), "user@example.com");
1351    }
1352
1353    #[test]
1354    fn test_validate_conditions_time() {
1355        // validate_saml_conditions looks for <Conditions> inside an <Assertion> element.
1356        let now = Utc::now();
1357        let past = now - Duration::minutes(10);
1358        let future = now + Duration::minutes(10);
1359        let xml = format!(
1360            r#"<saml:Assertion><saml:Conditions NotBefore="{}" NotOnOrAfter="{}"><saml:AudienceRestriction><saml:Audience>test-aud</saml:Audience></saml:AudienceRestriction></saml:Conditions></saml:Assertion>"#,
1361            past.to_rfc3339(),
1362            future.to_rfc3339()
1363        );
1364        assert!(validate_saml_conditions(&xml, "test-aud").is_ok());
1365
1366        let wrong_aud = format!(
1367            r#"<saml:Assertion><saml:Conditions NotBefore="{}" NotOnOrAfter="{}"><saml:AudienceRestriction><saml:Audience>wrong-aud</saml:Audience></saml:AudienceRestriction></saml:Conditions></saml:Assertion>"#,
1368            past.to_rfc3339(),
1369            future.to_rfc3339()
1370        );
1371        assert!(validate_saml_conditions(&wrong_aud, "test-aud").is_err());
1372    }
1373
1374    #[test]
1375    fn test_extract_status() {
1376        let xml = r#"<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>"#;
1377        assert_eq!(
1378            xml_extract_status_code(xml).unwrap(),
1379            "urn:oasis:names:tc:SAML:2.0:status:Success"
1380        );
1381    }
1382}