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
11fn 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("<"),
19 '>' => output.push_str(">"),
20 '"' => output.push_str("""),
21 '\'' => output.push_str("'"),
22 _ => output.push(ch),
23 }
24 }
25 output
26}
27
28#[cfg(feature = "saml")]
29use crate::methods::saml::{SamlTrustAnchors, VerifiedAssertion, verify_signed_assertion};
30#[cfg(feature = "saml")]
31use quick_xml::Reader;
32#[cfg(feature = "saml")]
33use quick_xml::events::Event;
34#[cfg(feature = "saml")]
35use quick_xml::name::QName;
36
37#[cfg(feature = "saml")]
40fn xml_local<'a>(name: QName<'a>) -> &'a str {
41 let full = name.0;
42 match full.find(':') {
43 Some(pos) => &full[pos + 1..],
44 None => full,
45 }
46}
47
48#[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#[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#[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#[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#[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#[derive(Debug, Serialize, Deserialize)]
153pub struct SamlLogoutResponse {
154 pub redirect_url: String,
155 pub status: String,
156}
157
158pub 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 (
206 StatusCode::OK,
207 [(
208 axum::http::header::CONTENT_TYPE,
209 "application/samlmetadata+xml",
210 )],
211 metadata_xml,
212 )
213 .into_response()
214}
215
216pub async fn initiate_saml_sso(
221 State(state): State<ApiState>,
222 Json(request): Json<SamlSsoRequest>,
223) -> Json<ApiResponse<SamlSsoResponse>> {
224 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 #[cfg(feature = "saml")]
270 if let Err(error) = idp_signing_anchors(&state, &request.idp_entity_id).await {
271 tracing::error!(idp = %request.idp_entity_id, error = %error, "SAML SSO: IdP has no usable pinned signing certificate");
272 return Json(ApiResponse::error_typed(
273 "SAML_CONFIG_ERROR",
274 format!(
275 "IdP '{}' cannot be used for login: {}",
276 request.idp_entity_id, error
277 ),
278 ));
279 }
280
281 let request_id = format!("saml_{}", uuid::Uuid::new_v4());
283 let issue_instant = chrono::Utc::now().to_rfc3339();
284
285 let saml_request = format!(
286 r#"<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
287 xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
288 ID="{request_id}"
289 Version="2.0"
290 IssueInstant="{issue_instant}"
291 Destination="{idp_sso_url}"
292 {force_authn}
293 {is_passive}
294 AssertionConsumerServiceURL="{sp_acs_url}">
295 <saml:Issuer>{sp_entity_id}</saml:Issuer>
296 <samlp:NameIDPolicy Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
297 AllowCreate="true" />
298</samlp:AuthnRequest>"#,
299 force_authn = request
300 .force_authn
301 .map_or(String::new(), |fa| format!(r#"ForceAuthn="{}""#, fa)),
302 is_passive = request
303 .is_passive
304 .map_or(String::new(), |ip| format!(r#"IsPassive="{}""#, ip)),
305 sp_entity_id = xml_escape(&sp_config.entity_id),
306 sp_acs_url = xml_escape(&sp_config.acs_url),
307 idp_sso_url = xml_escape(&idp_sso_url),
308 );
309
310 let encoded_request = base64::engine::general_purpose::STANDARD.encode(&saml_request);
312
313 let mut redirect_url = format!(
315 "{}?SAMLRequest={}",
316 idp_sso_url,
317 urlencoding::encode(&encoded_request)
318 );
319
320 if let Some(relay_state) = &request.relay_state {
321 redirect_url.push_str(&format!("&RelayState={}", urlencoding::encode(relay_state)));
322 }
323
324 let request_key = format!("saml_request:{}", request_id);
326 let request_data = serde_json::json!({
327 "request_id": request_id,
328 "idp_entity_id": request.idp_entity_id,
329 "relay_state": request.relay_state,
330 "issued_at": chrono::Utc::now().to_rfc3339(),
331 })
332 .to_string();
333 if let Err(e) = state
334 .auth_framework
335 .storage()
336 .store_kv(
337 &request_key,
338 request_data.as_bytes(),
339 Some(std::time::Duration::from_secs(600)),
340 )
341 .await
342 {
343 tracing::warn!(error = %e, "SAML SSO: failed to persist AuthnRequest — InResponseTo validation will be skipped");
344 }
345
346 Json(ApiResponse::success(SamlSsoResponse {
347 redirect_url,
348 saml_request: encoded_request,
349 relay_state: request.relay_state,
350 }))
351}
352
353#[allow(
355 unreachable_code,
356 unused_variables,
357 reason = "without the `saml` feature the handler returns SAML_SIGNATURE_UNAVAILABLE early, leaving the rest unreachable and `state` and `saml_response_xml` unused"
358)]
359pub async fn handle_saml_acs(
360 State(state): State<ApiState>,
361 axum::Form(form_data): axum::Form<SamlAcsRequest>,
362) -> Json<ApiResponse<serde_json::Value>> {
363 let saml_response_xml =
365 match base64::engine::general_purpose::STANDARD.decode(&form_data.saml_response) {
366 Ok(decoded) => match String::from_utf8(decoded) {
367 Ok(xml) => xml,
368 Err(e) => {
369 tracing::warn!(error = %e, "SAML ACS: invalid UTF-8 in decoded response");
370 return Json(ApiResponse::validation_error_typed(
371 "Invalid SAML response encoding",
372 ));
373 }
374 },
375 Err(e) => {
376 tracing::warn!(error = %e, "SAML ACS: base64 decode failed");
377 return Json(ApiResponse::validation_error_typed(
378 "Invalid SAML response encoding",
379 ));
380 }
381 };
382
383 #[cfg(feature = "saml")]
386 let verified = match validate_saml_signature(&state, &saml_response_xml).await {
387 Ok(verified) => {
388 tracing::info!("SAML ACS: XML signature validated successfully");
389 verified
390 }
391 Err(e) => {
392 tracing::error!(error = %e, "SAML ACS: XML signature validation failed");
393 return Json(ApiResponse::error_typed(
394 "SAML_SIGNATURE_INVALID",
395 format!("SAML response signature validation failed: {}", e),
396 ));
397 }
398 };
399 #[cfg(not(feature = "saml"))]
400 {
401 tracing::error!(
402 "SAML ACS: XML signature validation is not available — \
403 the 'saml' feature is required for secure SAML processing"
404 );
405 return Json(ApiResponse::error_typed(
406 "SAML_SIGNATURE_UNAVAILABLE",
407 "SAML signature validation is not available; the server must be compiled with the 'saml' feature",
408 ));
409 }
410
411 #[cfg(feature = "saml")]
413 let assertion_xml = verified.assertion_xml.clone();
414 #[cfg(not(feature = "saml"))]
415 let assertion_xml = saml_response_xml.clone();
416
417 #[cfg(feature = "saml")]
420 let in_response_to = signed_in_response_to(&saml_response_xml, &verified);
421 #[cfg(not(feature = "saml"))]
422 let in_response_to = extract_in_response_to(&saml_response_xml);
423 if let Some(irt) = in_response_to {
424 let request_key = format!("saml_request:{}", irt);
425 match state.auth_framework.storage().get_kv(&request_key).await {
426 Ok(Some(_)) => {
427 let _ = state.auth_framework.storage().delete_kv(&request_key).await;
429 }
430 _ => {
431 tracing::warn!(in_response_to = %irt, "SAML ACS: InResponseTo references unknown or expired request");
432 return Json(ApiResponse::error_typed(
433 "SAML_INVALID_RESPONSE",
434 "SAML response references an unknown or expired authentication request",
435 ));
436 }
437 }
438 } else {
439 tracing::warn!(
441 "SAML ACS: response has no InResponseTo attribute — rejecting unsolicited response"
442 );
443 return Json(ApiResponse::error_typed(
444 "SAML_UNSOLICITED_RESPONSE",
445 "Unsolicited SAML responses are not accepted; initiate SSO via /api/v1/saml/sso first",
446 ));
447 }
448
449 #[cfg(feature = "saml")]
452 {
453 let sp_entity_id = match load_saml_sp_config(&state).await {
454 Ok(config) => config.entity_id,
455 Err(error) => {
456 tracing::error!(error = %error, "SAML ACS requested without valid SP configuration");
457 return Json(ApiResponse::error_typed(
458 "SAML_CONFIG_ERROR",
459 "Service Provider configuration is missing required entity_id and acs_url values",
460 ));
461 }
462 };
463
464 if let Err(e) = validate_saml_conditions(&assertion_xml, &sp_entity_id) {
465 tracing::warn!(error = %e, "SAML ACS: assertion conditions validation failed");
466 return Json(ApiResponse::error_typed("SAML_CONDITIONS_INVALID", e));
467 }
468 }
469
470 let username = match extract_username_from_saml(&assertion_xml) {
472 Ok(user) => user,
473 Err(e) => return Json(ApiResponse::error_typed("SAML_PARSE_ERROR", e)),
474 };
475
476 let attributes = match extract_attributes_from_saml(&assertion_xml) {
477 Ok(attrs) => attrs,
478 Err(e) => return Json(ApiResponse::error_typed("SAML_PARSE_ERROR", e)),
479 };
480
481 let scopes = vec![
483 "openid".to_string(),
484 "profile".to_string(),
485 "email".to_string(),
486 ];
487 let token = match state
488 .auth_framework
489 .token_manager()
490 .create_auth_token(&username, scopes, "saml", None)
491 {
492 Ok(t) => t,
493 Err(e) => {
494 tracing::error!(user = %username, error = %e, "SAML ACS: failed to create auth token");
495 return Json(ApiResponse::error_typed(
496 "server_error",
497 "Failed to create authentication token",
498 ));
499 }
500 };
501
502 let token_data = serde_json::json!({
503 "access_token": token.access_token,
504 "token_type": "Bearer",
505 "expires_in": (token.expires_at - token.issued_at).num_seconds().max(0) as u64,
506 "refresh_token": token.refresh_token,
507 "user_id": username,
508 "authentication_method": "saml",
509 "attributes": attributes,
510 "relay_state": form_data.relay_state
511 });
512
513 tracing::info!(user = %username, "SAML authentication successful");
514 Json(ApiResponse::success_with_message(
515 token_data,
516 "SAML authentication successful",
517 ))
518}
519
520pub async fn initiate_saml_slo(
523 State(state): State<ApiState>,
524 Json(request): Json<SamlLogoutRequest>,
525) -> Json<ApiResponse<SamlLogoutResponse>> {
526 let idp_key = format!("saml_idp:{}", request.idp_entity_id);
528 let idp_slo_url = match state.auth_framework.storage().get_kv(&idp_key).await {
529 Ok(Some(data)) => {
530 let cfg: serde_json::Value = serde_json::from_slice(&data).unwrap_or_default();
531 match cfg["slo_url"].as_str() {
532 Some(url) => url.to_string(),
533 None => {
534 return Json(ApiResponse::error_typed(
535 "SAML_CONFIG_ERROR",
536 "IdP config is missing required slo_url field",
537 ));
538 }
539 }
540 }
541 Ok(None) => {
542 tracing::warn!(idp = %request.idp_entity_id, "SAML SLO: unknown IdP entity ID");
543 return Json(ApiResponse::error_typed(
544 "SAML_UNKNOWN_IDP",
545 format!("IdP not configured: {}", request.idp_entity_id),
546 ));
547 }
548 Err(e) => {
549 tracing::error!(error = %e, "SAML SLO: storage error looking up IdP");
550 return Json(ApiResponse::error_typed(
551 "server_error",
552 "Failed to look up IdP configuration",
553 ));
554 }
555 };
556
557 let sp_config = match load_saml_sp_config(&state).await {
558 Ok(config) => config,
559 Err(error) => {
560 tracing::error!(error = %error, "SAML SLO requested without valid SP configuration");
561 return Json(ApiResponse::error_typed(
562 "SAML_CONFIG_ERROR",
563 "Service Provider configuration is missing required entity_id and acs_url values",
564 ));
565 }
566 };
567
568 let logout_id = format!("logout_{}", uuid::Uuid::new_v4());
569 let issue_instant = chrono::Utc::now().to_rfc3339();
570
571 let saml_logout_request = format!(
573 r#"<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
574 xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
575 ID="{logout_id}"
576 Version="2.0"
577 IssueInstant="{issue_instant}"
578 Destination="{idp_slo_url}">
579 <saml:Issuer>{sp_entity_id}</saml:Issuer>
580 <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">{name_id}</saml:NameID>
581 {session_index}
582</samlp:LogoutRequest>"#,
583 name_id = xml_escape(&request.name_id),
584 session_index = request.session_index.map_or(String::new(), |si| format!(
585 r#"<samlp:SessionIndex>{}</samlp:SessionIndex>"#,
586 xml_escape(&si)
587 )),
588 sp_entity_id = xml_escape(&sp_config.entity_id),
589 idp_slo_url = xml_escape(&idp_slo_url),
590 );
591
592 let encoded_request = base64::engine::general_purpose::STANDARD.encode(&saml_logout_request);
593 let redirect_url = format!(
594 "{}?SAMLRequest={}",
595 idp_slo_url,
596 urlencoding::encode(&encoded_request)
597 );
598
599 Json(ApiResponse::success_with_message(
600 SamlLogoutResponse {
601 redirect_url,
602 status: "logout_initiated".to_string(),
603 },
604 "SAML logout initiated",
605 ))
606}
607
608pub async fn handle_saml_slo_response(
610 State(_state): State<ApiState>,
611 Query(params): Query<HashMap<String, String>>,
612) -> Json<ApiResponse<()>> {
613 #[cfg(not(feature = "saml"))]
614 {
615 let _ = params;
616 Json(ApiResponse::error_typed(
617 "SAML_SIGNATURE_UNAVAILABLE",
618 "SAML logout response validation is not available; the server must be compiled with the 'saml' feature",
619 ))
620 }
621
622 #[cfg(feature = "saml")]
623 {
624 let saml_response = match params.get("SAMLResponse") {
625 Some(response) => response,
626 None => {
627 return Json(ApiResponse::validation_error(
628 "Missing SAMLResponse parameter",
629 ));
630 }
631 };
632
633 let response_xml = match base64::engine::general_purpose::STANDARD.decode(saml_response) {
635 Ok(decoded) => match String::from_utf8(decoded) {
636 Ok(xml) => xml,
637 Err(e) => {
638 return Json(ApiResponse::validation_error(format!(
639 "Invalid SLO response UTF-8: {}",
640 e
641 )));
642 }
643 },
644 Err(e) => {
645 return Json(ApiResponse::validation_error(format!(
646 "Invalid SLO response encoding: {}",
647 e
648 )));
649 }
650 };
651
652 let slo_success = xml_extract_status_code(&response_xml)
653 .map(|code| code == "urn:oasis:names:tc:SAML:2.0:status:Success")
654 .unwrap_or(false);
655
656 if slo_success {
657 if let Some(name_id) = xml_extract_name_id(&response_xml) {
660 if let Ok(Some(uid_bytes)) = _state
662 .auth_framework
663 .storage()
664 .get_kv(&format!("user:email:{}", name_id))
665 .await
666 {
667 let user_id = String::from_utf8_lossy(&uid_bytes).to_string();
668 let session_key = format!("sessions:user:{}", user_id);
669 let _ = _state
670 .auth_framework
671 .storage()
672 .delete_kv(&session_key)
673 .await;
674 tracing::info!(user_id = %user_id, "SAML SLO: invalidated sessions");
675 }
676 }
677
678 if let Some(relay_state) = params.get("RelayState")
680 && !relay_state.is_empty()
681 {
682 tracing::debug!(relay_state = %relay_state, "SAML SLO: RelayState provided");
683 }
684
685 Json(ApiResponse::<()>::ok_with_message(
686 "SAML logout completed successfully",
687 ))
688 } else {
689 Json(ApiResponse::error(
690 "SAML_LOGOUT_FAILED",
691 "SAML logout failed",
692 ))
693 }
694 }
695}
696
697pub async fn create_saml_assertion(
699 State(state): State<ApiState>,
700 Json(request): Json<serde_json::Value>,
701) -> Json<ApiResponse<String>> {
702 let username = match request["username"].as_str() {
703 Some(user) => user,
704 None => return Json(ApiResponse::validation_error_typed("Username required")),
705 };
706
707 let audience = match request["audience"].as_str() {
708 Some(aud) => aud,
709 None => return Json(ApiResponse::validation_error_typed("Audience required")),
710 };
711
712 let sp_config = match load_saml_sp_config(&state).await {
713 Ok(config) => config,
714 Err(error) => {
715 tracing::error!(error = %error, "SAML assertion requested without valid SP configuration");
716 return Json(ApiResponse::error_typed(
717 "SAML_CONFIG_ERROR",
718 "Service Provider configuration is missing required entity_id and acs_url values",
719 ));
720 }
721 };
722
723 let name_id = match request["email"].as_str().map(str::trim) {
724 Some(email) if !email.is_empty() => email.to_string(),
725 _ if username.contains('@') => username.to_string(),
726 _ => {
727 return Json(ApiResponse::validation_error_typed(
728 "Email required when username is not an email address",
729 ));
730 }
731 };
732
733 let assertion_id = uuid::Uuid::new_v4();
738 let response_id = uuid::Uuid::new_v4();
739 let now = chrono::Utc::now();
740 let not_before = (now - chrono::Duration::minutes(1)).to_rfc3339();
741 let not_after = (now + chrono::Duration::hours(1)).to_rfc3339();
742 let now_str = now.to_rfc3339();
743 let issuer = xml_escape(&sp_config.entity_id);
745 let audience_escaped = xml_escape(audience);
746 let name_id_escaped = xml_escape(&name_id);
747 let username_escaped = xml_escape(username);
748
749 let assertion_xml = format!(
750 r#"<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
751 xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
752 ID="response_{response_id}"
753 IssueInstant="{now_str}"
754 Destination="{audience_escaped}"
755 Version="2.0">
756 <saml:Issuer>{issuer}</saml:Issuer>
757 <samlp:Status>
758 <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
759 </samlp:Status>
760 <saml:Assertion ID="assertion_{assertion_id}"
761 IssueInstant="{now_str}"
762 Version="2.0">
763 <saml:Issuer>{issuer}</saml:Issuer>
764 <saml:Subject>
765 <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">{name_id_escaped}</saml:NameID>
766 <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
767 <saml:SubjectConfirmationData NotOnOrAfter="{not_after}" Recipient="{audience_escaped}"/>
768 </saml:SubjectConfirmation>
769 </saml:Subject>
770 <saml:Conditions NotBefore="{not_before}" NotOnOrAfter="{not_after}">
771 <saml:AudienceRestriction>
772 <saml:Audience>{audience_escaped}</saml:Audience>
773 </saml:AudienceRestriction>
774 </saml:Conditions>
775 <saml:AuthnStatement AuthnInstant="{now_str}" SessionIndex="session_{assertion_id}">
776 <saml:AuthnContext>
777 <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
778 </saml:AuthnContext>
779 </saml:AuthnStatement>
780 <saml:AttributeStatement>
781 <saml:Attribute Name="username">
782 <saml:AttributeValue>{username_escaped}</saml:AttributeValue>
783 </saml:Attribute>
784 <saml:Attribute Name="email">
785 <saml:AttributeValue>{name_id_escaped}</saml:AttributeValue>
786 </saml:Attribute>
787 </saml:AttributeStatement>
788 </saml:Assertion>
789</samlp:Response>"#,
790 );
791
792 Json(ApiResponse::success_with_message(
793 assertion_xml,
794 "SAML assertion created",
795 ))
796}
797
798pub async fn list_saml_idps(
802 State(state): State<ApiState>,
803) -> Json<ApiResponse<Vec<serde_json::Value>>> {
804 let entity_ids: Vec<String> = match state
806 .auth_framework
807 .storage()
808 .get_kv("saml_idps:index")
809 .await
810 {
811 Ok(Some(data)) => serde_json::from_slice(&data).unwrap_or_default(),
812 Ok(None) => vec![],
813 Err(e) => {
814 tracing::error!(error = %e, "Failed to load SAML IdP index");
815 return Json(ApiResponse::error_typed(
816 "server_error",
817 "Failed to load IdP list",
818 ));
819 }
820 };
821
822 let mut idps = Vec::with_capacity(entity_ids.len());
824 for entity_id in &entity_ids {
825 let key = format!("saml_idp:{}", entity_id);
826 if let Ok(Some(data)) = state.auth_framework.storage().get_kv(&key).await
827 && let Ok(cfg) = serde_json::from_slice::<serde_json::Value>(&data)
828 {
829 idps.push(cfg);
830 }
831 }
832
833 Json(ApiResponse::success_with_message(
834 idps,
835 "SAML IdPs retrieved",
836 ))
837}
838
839#[cfg(feature = "saml")]
842async fn idp_signing_anchors(
843 state: &ApiState,
844 entity_id: &str,
845) -> Result<SamlTrustAnchors, String> {
846 let idp_key = format!("saml_idp:{}", entity_id);
847 let idp_cfg_data = state
848 .auth_framework
849 .storage()
850 .get_kv(&idp_key)
851 .await
852 .map_err(|e| format!("Storage error loading IdP config: {}", e))?
853 .ok_or_else(|| format!("IdP not configured: {}", entity_id))?;
854
855 let idp_cfg: serde_json::Value = serde_json::from_slice(&idp_cfg_data)
856 .map_err(|e| format!("Invalid IdP config JSON: {}", e))?;
857
858 let signing_cert_pem = idp_cfg["signing_cert"]
859 .as_str()
860 .filter(|pem| !pem.trim().is_empty())
861 .ok_or_else(|| format!("IdP '{}' has no signing_cert configured", entity_id))?;
862
863 let mut anchors = SamlTrustAnchors::new();
864 anchors
865 .trust_pem(entity_id, signing_cert_pem)
866 .map_err(|e| e.to_string())?;
867 Ok(anchors)
868}
869
870#[cfg(feature = "saml")]
882async fn validate_saml_signature(
883 state: &ApiState,
884 saml_xml: &str,
885) -> Result<VerifiedAssertion, String> {
886 let issuer = extract_issuer(saml_xml)
889 .ok_or_else(|| "SAML response does not contain an Issuer element".to_string())?;
890
891 let anchors = idp_signing_anchors(state, &issuer).await?;
892 verify_signed_assertion(saml_xml, &anchors).map_err(|e| e.to_string())
893}
894
895#[cfg(feature = "saml")]
898fn extract_issuer(saml_xml: &str) -> Option<String> {
899 let mut reader = Reader::from_str(saml_xml);
900 let mut in_response = false;
901 let mut in_issuer = false;
902 let mut depth: u32 = 0;
903
904 loop {
905 match reader.read_event() {
906 Ok(Event::Start(e)) => {
907 let local = xml_local(e.name());
908 if local == "Response" && !in_response {
909 in_response = true;
910 depth = 1;
911 } else if in_response {
912 depth += 1;
913 if local == "Issuer" && depth == 2 {
915 in_issuer = true;
916 }
917 }
918 }
919 Ok(Event::End(e)) => {
920 let local = xml_local(e.name());
921 if in_issuer && local == "Issuer" {
922 in_issuer = false;
923 }
924 if in_response {
925 depth -= 1;
926 if depth == 0 {
927 break; }
929 }
930 }
931 Ok(Event::Text(t)) if in_issuer => {
932 let text: &str = &t;
933 let s = text.trim();
934 if !s.is_empty() {
935 return Some(s.to_string());
936 }
937 }
938 Ok(Event::Eof) => break,
939 Err(_) => break,
940 _ => {}
941 }
942 }
943 None
944}
945
946#[cfg(feature = "saml")]
950fn signed_in_response_to(response_xml: &str, verified: &VerifiedAssertion) -> Option<String> {
951 if verified.response_signed
952 && let Some(irt) = extract_in_response_to(response_xml)
953 {
954 return Some(irt);
955 }
956 let mut reader = Reader::from_str(&verified.assertion_xml);
957 loop {
958 match reader.read_event() {
959 Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
960 if xml_local(e.name()) == "SubjectConfirmationData" {
961 for attr in e.attributes().flatten() {
962 if attr.key.as_ref() == "InResponseTo" {
963 return Some(attr.value.to_string());
964 }
965 }
966 }
967 }
968 Ok(Event::Eof) | Err(_) => return None,
969 _ => {}
970 }
971 }
972}
973
974#[cfg(feature = "saml")]
977fn extract_in_response_to(saml_xml: &str) -> Option<String> {
978 let mut reader = Reader::from_str(saml_xml);
979 loop {
980 match reader.read_event() {
981 Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
982 if xml_local(e.name()) == "Response" {
983 for attr in e.attributes().flatten() {
984 if attr.key.as_ref() == "InResponseTo" {
985 return Some(attr.value.to_string());
986 }
987 }
988 return None; }
990 }
991 Ok(Event::Eof) => break,
992 Err(_) => break,
993 _ => {}
994 }
995 }
996 None
997}
998
999#[cfg(not(feature = "saml"))]
1001fn extract_in_response_to(saml_xml: &str) -> Option<String> {
1002 let response_tag_start = saml_xml.find("<samlp:Response")?;
1005 let tag_end = saml_xml[response_tag_start..].find('>')?;
1006 let tag = &saml_xml[response_tag_start..response_tag_start + tag_end];
1007 let attr_start = tag.find("InResponseTo=\"")?;
1008 let value_start = attr_start + "InResponseTo=\"".len();
1009 let value_end = tag[value_start..].find('"')?;
1010 Some(tag[value_start..value_start + value_end].to_string())
1011}
1012
1013#[cfg(feature = "saml")]
1016fn extract_username_from_saml(saml_xml: &str) -> Result<String, String> {
1017 let mut reader = Reader::from_str(saml_xml);
1018 let mut in_assertion = false;
1019 let mut in_name_id = false;
1020
1021 loop {
1022 match reader.read_event() {
1023 Ok(Event::Start(e)) => {
1024 let local = xml_local(e.name());
1025 if local == "Assertion" {
1026 in_assertion = true;
1027 } else if in_assertion && local == "NameID" {
1028 in_name_id = true;
1029 }
1030 }
1031 Ok(Event::End(e)) => {
1032 let local = xml_local(e.name());
1033 if in_name_id && local == "NameID" {
1034 in_name_id = false;
1035 }
1036 if local == "Assertion" {
1037 break; }
1039 }
1040 Ok(Event::Text(t)) if in_name_id => {
1041 let text: &str = &t;
1042 let s = text.trim();
1043 if !s.is_empty() {
1044 return Ok(s.to_string());
1045 }
1046 }
1047 Ok(Event::Eof) => break,
1048 Err(e) => return Err(format!("XML parse error extracting NameID: {}", e)),
1049 _ => {}
1050 }
1051 }
1052
1053 Err("Could not extract username from SAML assertion".to_string())
1054}
1055
1056#[cfg(not(feature = "saml"))]
1058fn extract_username_from_saml(_saml_xml: &str) -> Result<String, String> {
1059 Err("SAML parsing requires the 'saml' feature".to_string())
1061}
1062
1063#[cfg(feature = "saml")]
1065fn extract_attributes_from_saml(saml_xml: &str) -> Result<HashMap<String, Vec<String>>, String> {
1066 let mut attributes = HashMap::new();
1067 attributes.insert("source".to_string(), vec!["saml".to_string()]);
1068 attributes.insert("auth_method".to_string(), vec!["saml_sso".to_string()]);
1069
1070 let mut reader = Reader::from_str(saml_xml);
1071 let mut in_attr_statement = false;
1072 let mut in_attribute = false;
1073 let mut in_attr_value = false;
1074 let mut current_attr_name: Option<String> = None;
1075 let mut current_values: Vec<String> = Vec::new();
1076
1077 loop {
1078 match reader.read_event() {
1079 Ok(Event::Start(e)) => {
1080 let local = xml_local(e.name());
1081 if local == "AttributeStatement" {
1082 in_attr_statement = true;
1083 } else if in_attr_statement && local == "Attribute" {
1084 in_attribute = true;
1085 current_values.clear();
1086 current_attr_name = None;
1087 for attr in e.attributes().flatten() {
1088 if xml_local(attr.key) == "Name" {
1089 current_attr_name = Some(attr.value.to_string());
1090 }
1091 }
1092 } else if in_attribute && local == "AttributeValue" {
1093 in_attr_value = true;
1094 }
1095 }
1096 Ok(Event::End(e)) => {
1097 let local = xml_local(e.name());
1098 if local == "AttributeValue" {
1099 in_attr_value = false;
1100 } else if local == "Attribute" && in_attribute {
1101 if let Some(name) = current_attr_name.take()
1102 && !current_values.is_empty()
1103 {
1104 attributes.insert(name, std::mem::take(&mut current_values));
1105 }
1106 in_attribute = false;
1107 } else if local == "AttributeStatement" {
1108 in_attr_statement = false;
1109 }
1110 }
1111 Ok(Event::Text(t)) if in_attr_value => {
1112 let text: &str = &t;
1113 let s = text.trim();
1114 if !s.is_empty() {
1115 current_values.push(s.to_string());
1116 }
1117 }
1118 Ok(Event::Eof) => break,
1119 Err(_) => break,
1120 _ => {}
1121 }
1122 }
1123
1124 Ok(attributes)
1125}
1126
1127#[cfg(not(feature = "saml"))]
1129fn extract_attributes_from_saml(_saml_xml: &str) -> Result<HashMap<String, Vec<String>>, String> {
1130 Err("SAML parsing requires the 'saml' feature".to_string())
1131}
1132
1133#[cfg(feature = "saml")]
1139fn validate_saml_conditions(saml_xml: &str, sp_entity_id: &str) -> Result<(), String> {
1140 let mut reader = Reader::from_str(saml_xml);
1141 let mut in_assertion = false;
1142 let mut in_conditions = false;
1143 let mut in_audience_restriction = false;
1144 let mut in_audience = false;
1145 let mut found_conditions = false;
1146 let mut not_before: Option<String> = None;
1147 let mut not_on_or_after: Option<String> = None;
1148 let mut audiences: Vec<String> = Vec::new();
1149
1150 loop {
1151 match reader.read_event() {
1152 Ok(Event::Start(e)) => {
1153 let local = xml_local(e.name());
1154 if local == "Assertion" {
1155 in_assertion = true;
1156 } else if in_assertion && local == "Conditions" {
1157 in_conditions = true;
1158 found_conditions = true;
1159 for attr in e.attributes().flatten() {
1160 let key = attr.key.as_ref();
1161 if key == "NotBefore" {
1162 not_before = Some(attr.value.to_string());
1163 } else if key == "NotOnOrAfter" {
1164 not_on_or_after = Some(attr.value.to_string());
1165 }
1166 }
1167 } else if in_conditions && local == "AudienceRestriction" {
1168 in_audience_restriction = true;
1169 } else if in_audience_restriction && local == "Audience" {
1170 in_audience = true;
1171 }
1172 }
1173 Ok(Event::End(e)) => {
1174 let local = xml_local(e.name());
1175 if local == "Audience" {
1176 in_audience = false;
1177 } else if local == "AudienceRestriction" {
1178 in_audience_restriction = false;
1179 } else if local == "Conditions" {
1180 break; } else if local == "Assertion" {
1182 break;
1183 }
1184 }
1185 Ok(Event::Text(t)) if in_audience => {
1186 let text: &str = &t;
1187 let s = text.trim();
1188 if !s.is_empty() {
1189 audiences.push(s.to_string());
1190 }
1191 }
1192 Ok(Event::Eof) => break,
1193 Err(e) => return Err(format!("XML parse error in Conditions: {}", e)),
1194 _ => {}
1195 }
1196 }
1197
1198 if !found_conditions {
1199 return Err("Assertion does not contain a Conditions element".to_string());
1200 }
1201
1202 let skew = chrono::Duration::seconds(60);
1204 let now = chrono::Utc::now();
1205
1206 if let Some(nb) = not_before {
1207 let ts = chrono::DateTime::parse_from_rfc3339(&nb)
1208 .or_else(|_| chrono::DateTime::parse_from_str(&nb, "%Y-%m-%dT%H:%M:%S%.fZ"))
1209 .map_err(|e| format!("Invalid NotBefore timestamp '{}': {}", nb, e))?;
1210 if now < ts.with_timezone(&chrono::Utc) - skew {
1211 return Err(format!("Assertion is not yet valid (NotBefore: {})", nb));
1212 }
1213 }
1214
1215 if let Some(noa) = not_on_or_after {
1216 let ts = chrono::DateTime::parse_from_rfc3339(&noa)
1217 .or_else(|_| chrono::DateTime::parse_from_str(&noa, "%Y-%m-%dT%H:%M:%S%.fZ"))
1218 .map_err(|e| format!("Invalid NotOnOrAfter timestamp '{}': {}", noa, e))?;
1219 if now >= ts.with_timezone(&chrono::Utc) + skew {
1220 return Err(format!("Assertion has expired (NotOnOrAfter: {})", noa));
1221 }
1222 }
1223
1224 if !audiences.is_empty() && !audiences.iter().any(|a| a == sp_entity_id) {
1226 return Err(format!(
1227 "Assertion audience restriction does not include this SP (expected '{}', got {:?})",
1228 sp_entity_id, audiences
1229 ));
1230 }
1231
1232 Ok(())
1233}
1234
1235#[cfg(feature = "saml")]
1238fn xml_extract_status_code(saml_xml: &str) -> Option<String> {
1239 let mut reader = Reader::from_str(saml_xml);
1240 let mut in_status = false;
1241
1242 loop {
1243 match reader.read_event() {
1244 Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
1245 let local = xml_local(e.name());
1246 if local == "Status" {
1247 in_status = true;
1248 } else if in_status && local == "StatusCode" {
1249 for attr in e.attributes().flatten() {
1250 if attr.key.as_ref() == "Value" {
1251 return Some(attr.value.to_string());
1252 }
1253 }
1254 return None; }
1256 }
1257 Ok(Event::End(e)) => {
1258 if xml_local(e.name()) == "Status" {
1259 return None; }
1261 }
1262 Ok(Event::Eof) => break,
1263 Err(_) => break,
1264 _ => {}
1265 }
1266 }
1267 None
1268}
1269
1270#[cfg(feature = "saml")]
1272fn xml_extract_name_id(saml_xml: &str) -> Option<String> {
1273 let mut reader = Reader::from_str(saml_xml);
1274 let mut in_name_id = false;
1275
1276 loop {
1277 match reader.read_event() {
1278 Ok(Event::Start(e)) => {
1279 if xml_local(e.name()) == "NameID" {
1280 in_name_id = true;
1281 }
1282 }
1283 Ok(Event::Text(e)) if in_name_id => {
1284 let text: &str = &e;
1285 let s = text.trim();
1286 if !s.is_empty() {
1287 return Some(s.to_string());
1288 }
1289 }
1290 Ok(Event::End(e)) if in_name_id && xml_local(e.name()) == "NameID" => {
1291 return None; }
1293 Ok(Event::Eof) => break,
1294 Err(_) => break,
1295 _ => {}
1296 }
1297 }
1298 None
1299}
1300
1301#[cfg(test)]
1302#[cfg(feature = "saml")]
1303mod tests {
1304 use super::*;
1305 #[cfg(feature = "saml")]
1306 use crate::methods::saml::dsig::key_from_x509_der;
1307 use chrono::{Duration, Utc};
1308
1309 #[test]
1318 fn test_key_from_x509_der_accepts_ecdsa_p256_certificate() {
1319 let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
1320 .expect("ECDSA P-256 key generation should succeed");
1321 let params = rcgen::CertificateParams::default();
1322 let cert = params
1323 .self_signed(&key_pair)
1324 .expect("self-signing should succeed");
1325
1326 let key = key_from_x509_der(cert.der().as_ref())
1327 .expect("a valid ECDSA P-256 certificate must be accepted");
1328 assert_eq!(key.usage, bergshamra::KeyUsage::Verify);
1329 }
1330
1331 #[test]
1339 fn test_key_from_x509_der_accepts_rsa_certificate() {
1340 let key_pair =
1341 rcgen::KeyPair::generate_rsa_for(&rcgen::PKCS_RSA_SHA256, rcgen::RsaKeySize::_2048)
1342 .expect("RSA 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 RSA certificate must be accepted");
1350 assert_eq!(key.usage, bergshamra::KeyUsage::Verify);
1351 }
1352
1353 #[test]
1363 fn test_bergshamra_feature_choices_are_deliberate() {
1364 let manifest = include_str!("../../Cargo.toml");
1365 let mut bergshamra_lines = Vec::new();
1366 for line in manifest
1367 .lines()
1368 .skip_while(|l| !l.trim_start().starts_with("bergshamra = {"))
1369 {
1370 let done = line.trim_end().ends_with("optional = true }");
1371 bergshamra_lines.push(line);
1372 if done {
1373 break;
1374 }
1375 }
1376 let bergshamra_line = bergshamra_lines.join("\n");
1377
1378 assert!(
1379 bergshamra_line.contains(r#""aws-lc""#),
1380 "expected bergshamra's feature list to include \"aws-lc\": {bergshamra_line}"
1381 );
1382 for excluded in ["legacy-algorithms", "post-quantum", "pkcs11", "rustcrypto"] {
1383 assert!(
1384 !bergshamra_line.contains(excluded),
1385 "bergshamra's feature list now includes {excluded:?}, which was a deliberate \
1386 exclusion (see the dependency's own Cargo.toml comment) -- if this is an \
1387 intentional change, update that comment and this test together, don't just \
1388 fix the assertion"
1389 );
1390 }
1391 }
1392
1393 #[test]
1394 fn test_key_from_x509_der_rejects_non_certificate_der() {
1395 let err = key_from_x509_der(b"not a certificate")
1396 .expect_err("garbage input must not be accepted as a certificate");
1397 assert!(err.contains("Failed to parse X.509 certificate"));
1398 }
1399
1400 #[test]
1401 fn test_extract_issuer() {
1402 let xml = r#"<samlp:Response><saml:Issuer>https://idp.example.com</saml:Issuer></samlp:Response>"#;
1404 assert_eq!(extract_issuer(xml).unwrap(), "https://idp.example.com");
1405 }
1406
1407 #[test]
1408 fn test_extract_username() {
1409 let xml = r#"<saml:Assertion><saml:Subject><saml:NameID>user@example.com</saml:NameID></saml:Subject></saml:Assertion>"#;
1411 assert_eq!(extract_username_from_saml(xml).unwrap(), "user@example.com");
1412 }
1413
1414 #[test]
1415 fn test_validate_conditions_time() {
1416 let now = Utc::now();
1418 let past = now - Duration::minutes(10);
1419 let future = now + Duration::minutes(10);
1420 let xml = format!(
1421 r#"<saml:Assertion><saml:Conditions NotBefore="{}" NotOnOrAfter="{}"><saml:AudienceRestriction><saml:Audience>test-aud</saml:Audience></saml:AudienceRestriction></saml:Conditions></saml:Assertion>"#,
1422 past.to_rfc3339(),
1423 future.to_rfc3339()
1424 );
1425 assert!(validate_saml_conditions(&xml, "test-aud").is_ok());
1426
1427 let wrong_aud = format!(
1428 r#"<saml:Assertion><saml:Conditions NotBefore="{}" NotOnOrAfter="{}"><saml:AudienceRestriction><saml:Audience>wrong-aud</saml:Audience></saml:AudienceRestriction></saml:Conditions></saml:Assertion>"#,
1429 past.to_rfc3339(),
1430 future.to_rfc3339()
1431 );
1432 assert!(validate_saml_conditions(&wrong_aud, "test-aud").is_err());
1433 }
1434
1435 #[test]
1436 fn test_extract_status() {
1437 let xml = r#"<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>"#;
1438 assert_eq!(
1439 xml_extract_status_code(xml).unwrap(),
1440 "urn:oasis:names:tc:SAML:2.0:status:Success"
1441 );
1442 }
1443}