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