Skip to main content

auth_framework/api/
saml.rs

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