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