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(unreachable_code, unused_variables)]
355pub async fn handle_saml_acs(
356 State(state): State<ApiState>,
357 axum::Form(form_data): axum::Form<SamlAcsRequest>,
358) -> Json<ApiResponse<serde_json::Value>> {
359 let saml_response_xml =
361 match base64::engine::general_purpose::STANDARD.decode(&form_data.saml_response) {
362 Ok(decoded) => match String::from_utf8(decoded) {
363 Ok(xml) => xml,
364 Err(e) => {
365 tracing::warn!(error = %e, "SAML ACS: invalid UTF-8 in decoded response");
366 return Json(ApiResponse::validation_error_typed(
367 "Invalid SAML response encoding",
368 ));
369 }
370 },
371 Err(e) => {
372 tracing::warn!(error = %e, "SAML ACS: base64 decode failed");
373 return Json(ApiResponse::validation_error_typed(
374 "Invalid SAML response encoding",
375 ));
376 }
377 };
378
379 #[cfg(feature = "saml")]
382 let verified = match validate_saml_signature(&state, &saml_response_xml).await {
383 Ok(verified) => {
384 tracing::info!("SAML ACS: XML signature validated successfully");
385 verified
386 }
387 Err(e) => {
388 tracing::error!(error = %e, "SAML ACS: XML signature validation failed");
389 return Json(ApiResponse::error_typed(
390 "SAML_SIGNATURE_INVALID",
391 format!("SAML response signature validation failed: {}", e),
392 ));
393 }
394 };
395 #[cfg(not(feature = "saml"))]
396 {
397 tracing::error!(
398 "SAML ACS: XML signature validation is not available — \
399 the 'saml' feature is required for secure SAML processing"
400 );
401 return Json(ApiResponse::error_typed(
402 "SAML_SIGNATURE_UNAVAILABLE",
403 "SAML signature validation is not available; the server must be compiled with the 'saml' feature",
404 ));
405 }
406
407 #[cfg(feature = "saml")]
409 let assertion_xml = verified.assertion_xml.clone();
410 #[cfg(not(feature = "saml"))]
411 let assertion_xml = saml_response_xml.clone();
412
413 #[cfg(feature = "saml")]
416 let in_response_to = signed_in_response_to(&saml_response_xml, &verified);
417 #[cfg(not(feature = "saml"))]
418 let in_response_to = extract_in_response_to(&saml_response_xml);
419 if let Some(irt) = in_response_to {
420 let request_key = format!("saml_request:{}", irt);
421 match state.auth_framework.storage().get_kv(&request_key).await {
422 Ok(Some(_)) => {
423 let _ = state.auth_framework.storage().delete_kv(&request_key).await;
425 }
426 _ => {
427 tracing::warn!(in_response_to = %irt, "SAML ACS: InResponseTo references unknown or expired request");
428 return Json(ApiResponse::error_typed(
429 "SAML_INVALID_RESPONSE",
430 "SAML response references an unknown or expired authentication request",
431 ));
432 }
433 }
434 } else {
435 tracing::warn!(
437 "SAML ACS: response has no InResponseTo attribute — rejecting unsolicited response"
438 );
439 return Json(ApiResponse::error_typed(
440 "SAML_UNSOLICITED_RESPONSE",
441 "Unsolicited SAML responses are not accepted; initiate SSO via /api/v1/saml/sso first",
442 ));
443 }
444
445 #[cfg(feature = "saml")]
448 {
449 let sp_entity_id = match load_saml_sp_config(&state).await {
450 Ok(config) => config.entity_id,
451 Err(error) => {
452 tracing::error!(error = %error, "SAML ACS requested without valid SP configuration");
453 return Json(ApiResponse::error_typed(
454 "SAML_CONFIG_ERROR",
455 "Service Provider configuration is missing required entity_id and acs_url values",
456 ));
457 }
458 };
459
460 if let Err(e) = validate_saml_conditions(&assertion_xml, &sp_entity_id) {
461 tracing::warn!(error = %e, "SAML ACS: assertion conditions validation failed");
462 return Json(ApiResponse::error_typed("SAML_CONDITIONS_INVALID", e));
463 }
464 }
465
466 let username = match extract_username_from_saml(&assertion_xml) {
468 Ok(user) => user,
469 Err(e) => return Json(ApiResponse::error_typed("SAML_PARSE_ERROR", e)),
470 };
471
472 let attributes = match extract_attributes_from_saml(&assertion_xml) {
473 Ok(attrs) => attrs,
474 Err(e) => return Json(ApiResponse::error_typed("SAML_PARSE_ERROR", e)),
475 };
476
477 let scopes = vec![
479 "openid".to_string(),
480 "profile".to_string(),
481 "email".to_string(),
482 ];
483 let token = match state
484 .auth_framework
485 .token_manager()
486 .create_auth_token(&username, scopes, "saml", None)
487 {
488 Ok(t) => t,
489 Err(e) => {
490 tracing::error!(user = %username, error = %e, "SAML ACS: failed to create auth token");
491 return Json(ApiResponse::error_typed(
492 "server_error",
493 "Failed to create authentication token",
494 ));
495 }
496 };
497
498 let token_data = serde_json::json!({
499 "access_token": token.access_token,
500 "token_type": "Bearer",
501 "expires_in": (token.expires_at - token.issued_at).num_seconds().max(0) as u64,
502 "refresh_token": token.refresh_token,
503 "user_id": username,
504 "authentication_method": "saml",
505 "attributes": attributes,
506 "relay_state": form_data.relay_state
507 });
508
509 tracing::info!(user = %username, "SAML authentication successful");
510 Json(ApiResponse::success_with_message(
511 token_data,
512 "SAML authentication successful",
513 ))
514}
515
516pub async fn initiate_saml_slo(
519 State(state): State<ApiState>,
520 Json(request): Json<SamlLogoutRequest>,
521) -> Json<ApiResponse<SamlLogoutResponse>> {
522 let idp_key = format!("saml_idp:{}", request.idp_entity_id);
524 let idp_slo_url = match state.auth_framework.storage().get_kv(&idp_key).await {
525 Ok(Some(data)) => {
526 let cfg: serde_json::Value = serde_json::from_slice(&data).unwrap_or_default();
527 match cfg["slo_url"].as_str() {
528 Some(url) => url.to_string(),
529 None => {
530 return Json(ApiResponse::error_typed(
531 "SAML_CONFIG_ERROR",
532 "IdP config is missing required slo_url field",
533 ));
534 }
535 }
536 }
537 Ok(None) => {
538 tracing::warn!(idp = %request.idp_entity_id, "SAML SLO: unknown IdP entity ID");
539 return Json(ApiResponse::error_typed(
540 "SAML_UNKNOWN_IDP",
541 format!("IdP not configured: {}", request.idp_entity_id),
542 ));
543 }
544 Err(e) => {
545 tracing::error!(error = %e, "SAML SLO: storage error looking up IdP");
546 return Json(ApiResponse::error_typed(
547 "server_error",
548 "Failed to look up IdP configuration",
549 ));
550 }
551 };
552
553 let sp_config = match load_saml_sp_config(&state).await {
554 Ok(config) => config,
555 Err(error) => {
556 tracing::error!(error = %error, "SAML SLO requested without valid SP configuration");
557 return Json(ApiResponse::error_typed(
558 "SAML_CONFIG_ERROR",
559 "Service Provider configuration is missing required entity_id and acs_url values",
560 ));
561 }
562 };
563
564 let logout_id = format!("logout_{}", uuid::Uuid::new_v4());
565 let issue_instant = chrono::Utc::now().to_rfc3339();
566
567 let saml_logout_request = format!(
569 r#"<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
570 xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
571 ID="{logout_id}"
572 Version="2.0"
573 IssueInstant="{issue_instant}"
574 Destination="{idp_slo_url}">
575 <saml:Issuer>{sp_entity_id}</saml:Issuer>
576 <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">{name_id}</saml:NameID>
577 {session_index}
578</samlp:LogoutRequest>"#,
579 name_id = xml_escape(&request.name_id),
580 session_index = request.session_index.map_or(String::new(), |si| format!(
581 r#"<samlp:SessionIndex>{}</samlp:SessionIndex>"#,
582 xml_escape(&si)
583 )),
584 sp_entity_id = xml_escape(&sp_config.entity_id),
585 idp_slo_url = xml_escape(&idp_slo_url),
586 );
587
588 let encoded_request = base64::engine::general_purpose::STANDARD.encode(&saml_logout_request);
589 let redirect_url = format!(
590 "{}?SAMLRequest={}",
591 idp_slo_url,
592 urlencoding::encode(&encoded_request)
593 );
594
595 Json(ApiResponse::success_with_message(
596 SamlLogoutResponse {
597 redirect_url,
598 status: "logout_initiated".to_string(),
599 },
600 "SAML logout initiated",
601 ))
602}
603
604pub async fn handle_saml_slo_response(
606 State(_state): State<ApiState>,
607 Query(params): Query<HashMap<String, String>>,
608) -> Json<ApiResponse<()>> {
609 #[cfg(not(feature = "saml"))]
610 {
611 let _ = params;
612 Json(ApiResponse::error_typed(
613 "SAML_SIGNATURE_UNAVAILABLE",
614 "SAML logout response validation is not available; the server must be compiled with the 'saml' feature",
615 ))
616 }
617
618 #[cfg(feature = "saml")]
619 {
620 let saml_response = match params.get("SAMLResponse") {
621 Some(response) => response,
622 None => {
623 return Json(ApiResponse::validation_error(
624 "Missing SAMLResponse parameter",
625 ));
626 }
627 };
628
629 let response_xml = match base64::engine::general_purpose::STANDARD.decode(saml_response) {
631 Ok(decoded) => match String::from_utf8(decoded) {
632 Ok(xml) => xml,
633 Err(e) => {
634 return Json(ApiResponse::validation_error(format!(
635 "Invalid SLO response UTF-8: {}",
636 e
637 )));
638 }
639 },
640 Err(e) => {
641 return Json(ApiResponse::validation_error(format!(
642 "Invalid SLO response encoding: {}",
643 e
644 )));
645 }
646 };
647
648 let slo_success = xml_extract_status_code(&response_xml)
649 .map(|code| code == "urn:oasis:names:tc:SAML:2.0:status:Success")
650 .unwrap_or(false);
651
652 if slo_success {
653 if let Some(name_id) = xml_extract_name_id(&response_xml) {
656 if let Ok(Some(uid_bytes)) = _state
658 .auth_framework
659 .storage()
660 .get_kv(&format!("user:email:{}", name_id))
661 .await
662 {
663 let user_id = String::from_utf8_lossy(&uid_bytes).to_string();
664 let session_key = format!("sessions:user:{}", user_id);
665 let _ = _state
666 .auth_framework
667 .storage()
668 .delete_kv(&session_key)
669 .await;
670 tracing::info!(user_id = %user_id, "SAML SLO: invalidated sessions");
671 }
672 }
673
674 if let Some(relay_state) = params.get("RelayState") {
676 if !relay_state.is_empty() {
677 tracing::debug!(relay_state = %relay_state, "SAML SLO: RelayState provided");
678 }
679 }
680
681 Json(ApiResponse::<()>::ok_with_message(
682 "SAML logout completed successfully",
683 ))
684 } else {
685 Json(ApiResponse::error(
686 "SAML_LOGOUT_FAILED",
687 "SAML logout failed",
688 ))
689 }
690 }
691}
692
693pub async fn create_saml_assertion(
695 State(state): State<ApiState>,
696 Json(request): Json<serde_json::Value>,
697) -> Json<ApiResponse<String>> {
698 let username = match request["username"].as_str() {
699 Some(user) => user,
700 None => return Json(ApiResponse::validation_error_typed("Username required")),
701 };
702
703 let audience = match request["audience"].as_str() {
704 Some(aud) => aud,
705 None => return Json(ApiResponse::validation_error_typed("Audience required")),
706 };
707
708 let sp_config = match load_saml_sp_config(&state).await {
709 Ok(config) => config,
710 Err(error) => {
711 tracing::error!(error = %error, "SAML assertion requested without valid SP configuration");
712 return Json(ApiResponse::error_typed(
713 "SAML_CONFIG_ERROR",
714 "Service Provider configuration is missing required entity_id and acs_url values",
715 ));
716 }
717 };
718
719 let name_id = match request["email"].as_str().map(str::trim) {
720 Some(email) if !email.is_empty() => email.to_string(),
721 _ if username.contains('@') => username.to_string(),
722 _ => {
723 return Json(ApiResponse::validation_error_typed(
724 "Email required when username is not an email address",
725 ));
726 }
727 };
728
729 let assertion_id = uuid::Uuid::new_v4();
734 let response_id = uuid::Uuid::new_v4();
735 let now = chrono::Utc::now();
736 let not_before = (now - chrono::Duration::minutes(1)).to_rfc3339();
737 let not_after = (now + chrono::Duration::hours(1)).to_rfc3339();
738 let now_str = now.to_rfc3339();
739 let issuer = xml_escape(&sp_config.entity_id);
741 let audience_escaped = xml_escape(audience);
742 let name_id_escaped = xml_escape(&name_id);
743 let username_escaped = xml_escape(username);
744
745 let assertion_xml = format!(
746 r#"<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
747 xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
748 ID="response_{response_id}"
749 IssueInstant="{now_str}"
750 Destination="{audience_escaped}"
751 Version="2.0">
752 <saml:Issuer>{issuer}</saml:Issuer>
753 <samlp:Status>
754 <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
755 </samlp:Status>
756 <saml:Assertion ID="assertion_{assertion_id}"
757 IssueInstant="{now_str}"
758 Version="2.0">
759 <saml:Issuer>{issuer}</saml:Issuer>
760 <saml:Subject>
761 <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">{name_id_escaped}</saml:NameID>
762 <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
763 <saml:SubjectConfirmationData NotOnOrAfter="{not_after}" Recipient="{audience_escaped}"/>
764 </saml:SubjectConfirmation>
765 </saml:Subject>
766 <saml:Conditions NotBefore="{not_before}" NotOnOrAfter="{not_after}">
767 <saml:AudienceRestriction>
768 <saml:Audience>{audience_escaped}</saml:Audience>
769 </saml:AudienceRestriction>
770 </saml:Conditions>
771 <saml:AuthnStatement AuthnInstant="{now_str}" SessionIndex="session_{assertion_id}">
772 <saml:AuthnContext>
773 <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
774 </saml:AuthnContext>
775 </saml:AuthnStatement>
776 <saml:AttributeStatement>
777 <saml:Attribute Name="username">
778 <saml:AttributeValue>{username_escaped}</saml:AttributeValue>
779 </saml:Attribute>
780 <saml:Attribute Name="email">
781 <saml:AttributeValue>{name_id_escaped}</saml:AttributeValue>
782 </saml:Attribute>
783 </saml:AttributeStatement>
784 </saml:Assertion>
785</samlp:Response>"#,
786 );
787
788 Json(ApiResponse::success_with_message(
789 assertion_xml,
790 "SAML assertion created",
791 ))
792}
793
794pub async fn list_saml_idps(
798 State(state): State<ApiState>,
799) -> Json<ApiResponse<Vec<serde_json::Value>>> {
800 let entity_ids: Vec<String> = match state
802 .auth_framework
803 .storage()
804 .get_kv("saml_idps:index")
805 .await
806 {
807 Ok(Some(data)) => serde_json::from_slice(&data).unwrap_or_default(),
808 Ok(None) => vec![],
809 Err(e) => {
810 tracing::error!(error = %e, "Failed to load SAML IdP index");
811 return Json(ApiResponse::error_typed(
812 "server_error",
813 "Failed to load IdP list",
814 ));
815 }
816 };
817
818 let mut idps = Vec::with_capacity(entity_ids.len());
820 for entity_id in &entity_ids {
821 let key = format!("saml_idp:{}", entity_id);
822 if let Ok(Some(data)) = state.auth_framework.storage().get_kv(&key).await
823 && let Ok(cfg) = serde_json::from_slice::<serde_json::Value>(&data)
824 {
825 idps.push(cfg);
826 }
827 }
828
829 Json(ApiResponse::success_with_message(
830 idps,
831 "SAML IdPs retrieved",
832 ))
833}
834
835#[cfg(feature = "saml")]
838async fn idp_signing_anchors(
839 state: &ApiState,
840 entity_id: &str,
841) -> Result<SamlTrustAnchors, String> {
842 let idp_key = format!("saml_idp:{}", entity_id);
843 let idp_cfg_data = state
844 .auth_framework
845 .storage()
846 .get_kv(&idp_key)
847 .await
848 .map_err(|e| format!("Storage error loading IdP config: {}", e))?
849 .ok_or_else(|| format!("IdP not configured: {}", entity_id))?;
850
851 let idp_cfg: serde_json::Value = serde_json::from_slice(&idp_cfg_data)
852 .map_err(|e| format!("Invalid IdP config JSON: {}", e))?;
853
854 let signing_cert_pem = idp_cfg["signing_cert"]
855 .as_str()
856 .filter(|pem| !pem.trim().is_empty())
857 .ok_or_else(|| format!("IdP '{}' has no signing_cert configured", entity_id))?;
858
859 let mut anchors = SamlTrustAnchors::new();
860 anchors
861 .trust_pem(entity_id, signing_cert_pem)
862 .map_err(|e| e.to_string())?;
863 Ok(anchors)
864}
865
866#[cfg(feature = "saml")]
878async fn validate_saml_signature(
879 state: &ApiState,
880 saml_xml: &str,
881) -> Result<VerifiedAssertion, String> {
882 let issuer = extract_issuer(saml_xml)
885 .ok_or_else(|| "SAML response does not contain an Issuer element".to_string())?;
886
887 let anchors = idp_signing_anchors(state, &issuer).await?;
888 verify_signed_assertion(saml_xml, &anchors).map_err(|e| e.to_string())
889}
890
891#[cfg(feature = "saml")]
894fn extract_issuer(saml_xml: &str) -> Option<String> {
895 let mut reader = Reader::from_str(saml_xml);
896 let mut in_response = false;
897 let mut in_issuer = false;
898 let mut depth: u32 = 0;
899
900 loop {
901 match reader.read_event() {
902 Ok(Event::Start(e)) => {
903 let local = xml_local(e.name());
904 if local == "Response" && !in_response {
905 in_response = true;
906 depth = 1;
907 } else if in_response {
908 depth += 1;
909 if local == "Issuer" && depth == 2 {
911 in_issuer = true;
912 }
913 }
914 }
915 Ok(Event::End(e)) => {
916 let local = xml_local(e.name());
917 if in_issuer && local == "Issuer" {
918 in_issuer = false;
919 }
920 if in_response {
921 depth -= 1;
922 if depth == 0 {
923 break; }
925 }
926 }
927 Ok(Event::Text(t)) if in_issuer => {
928 let text: &str = &t;
929 let s = text.trim();
930 if !s.is_empty() {
931 return Some(s.to_string());
932 }
933 }
934 Ok(Event::Eof) => break,
935 Err(_) => break,
936 _ => {}
937 }
938 }
939 None
940}
941
942#[cfg(feature = "saml")]
946fn signed_in_response_to(response_xml: &str, verified: &VerifiedAssertion) -> Option<String> {
947 if verified.response_signed
948 && let Some(irt) = extract_in_response_to(response_xml)
949 {
950 return Some(irt);
951 }
952 let mut reader = Reader::from_str(&verified.assertion_xml);
953 loop {
954 match reader.read_event() {
955 Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
956 if xml_local(e.name()) == "SubjectConfirmationData" {
957 for attr in e.attributes().flatten() {
958 if attr.key.as_ref() == "InResponseTo" {
959 return Some(attr.value.to_string());
960 }
961 }
962 }
963 }
964 Ok(Event::Eof) | Err(_) => return None,
965 _ => {}
966 }
967 }
968}
969
970#[cfg(feature = "saml")]
973fn extract_in_response_to(saml_xml: &str) -> Option<String> {
974 let mut reader = Reader::from_str(saml_xml);
975 loop {
976 match reader.read_event() {
977 Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
978 if xml_local(e.name()) == "Response" {
979 for attr in e.attributes().flatten() {
980 if attr.key.as_ref() == "InResponseTo" {
981 return Some(attr.value.to_string());
982 }
983 }
984 return None; }
986 }
987 Ok(Event::Eof) => break,
988 Err(_) => break,
989 _ => {}
990 }
991 }
992 None
993}
994
995#[cfg(not(feature = "saml"))]
997fn extract_in_response_to(saml_xml: &str) -> Option<String> {
998 let response_tag_start = saml_xml.find("<samlp:Response")?;
1001 let tag_end = saml_xml[response_tag_start..].find('>')?;
1002 let tag = &saml_xml[response_tag_start..response_tag_start + tag_end];
1003 let attr_start = tag.find("InResponseTo=\"")?;
1004 let value_start = attr_start + "InResponseTo=\"".len();
1005 let value_end = tag[value_start..].find('"')?;
1006 Some(tag[value_start..value_start + value_end].to_string())
1007}
1008
1009#[cfg(feature = "saml")]
1012fn extract_username_from_saml(saml_xml: &str) -> Result<String, String> {
1013 let mut reader = Reader::from_str(saml_xml);
1014 let mut in_assertion = false;
1015 let mut in_name_id = false;
1016
1017 loop {
1018 match reader.read_event() {
1019 Ok(Event::Start(e)) => {
1020 let local = xml_local(e.name());
1021 if local == "Assertion" {
1022 in_assertion = true;
1023 } else if in_assertion && local == "NameID" {
1024 in_name_id = true;
1025 }
1026 }
1027 Ok(Event::End(e)) => {
1028 let local = xml_local(e.name());
1029 if in_name_id && local == "NameID" {
1030 in_name_id = false;
1031 }
1032 if local == "Assertion" {
1033 break; }
1035 }
1036 Ok(Event::Text(t)) if in_name_id => {
1037 let text: &str = &t;
1038 let s = text.trim();
1039 if !s.is_empty() {
1040 return Ok(s.to_string());
1041 }
1042 }
1043 Ok(Event::Eof) => break,
1044 Err(e) => return Err(format!("XML parse error extracting NameID: {}", e)),
1045 _ => {}
1046 }
1047 }
1048
1049 Err("Could not extract username from SAML assertion".to_string())
1050}
1051
1052#[cfg(not(feature = "saml"))]
1054fn extract_username_from_saml(_saml_xml: &str) -> Result<String, String> {
1055 Err("SAML parsing requires the 'saml' feature".to_string())
1057}
1058
1059#[cfg(feature = "saml")]
1061fn extract_attributes_from_saml(saml_xml: &str) -> Result<HashMap<String, Vec<String>>, String> {
1062 let mut attributes = HashMap::new();
1063 attributes.insert("source".to_string(), vec!["saml".to_string()]);
1064 attributes.insert("auth_method".to_string(), vec!["saml_sso".to_string()]);
1065
1066 let mut reader = Reader::from_str(saml_xml);
1067 let mut in_attr_statement = false;
1068 let mut in_attribute = false;
1069 let mut in_attr_value = false;
1070 let mut current_attr_name: Option<String> = None;
1071 let mut current_values: Vec<String> = Vec::new();
1072
1073 loop {
1074 match reader.read_event() {
1075 Ok(Event::Start(e)) => {
1076 let local = xml_local(e.name());
1077 if local == "AttributeStatement" {
1078 in_attr_statement = true;
1079 } else if in_attr_statement && local == "Attribute" {
1080 in_attribute = true;
1081 current_values.clear();
1082 current_attr_name = None;
1083 for attr in e.attributes().flatten() {
1084 if xml_local(attr.key) == "Name" {
1085 current_attr_name = Some(attr.value.to_string());
1086 }
1087 }
1088 } else if in_attribute && local == "AttributeValue" {
1089 in_attr_value = true;
1090 }
1091 }
1092 Ok(Event::End(e)) => {
1093 let local = xml_local(e.name());
1094 if local == "AttributeValue" {
1095 in_attr_value = false;
1096 } else if local == "Attribute" && in_attribute {
1097 if let Some(name) = current_attr_name.take()
1098 && !current_values.is_empty()
1099 {
1100 attributes.insert(name, std::mem::take(&mut current_values));
1101 }
1102 in_attribute = false;
1103 } else if local == "AttributeStatement" {
1104 in_attr_statement = false;
1105 }
1106 }
1107 Ok(Event::Text(t)) if in_attr_value => {
1108 let text: &str = &t;
1109 let s = text.trim();
1110 if !s.is_empty() {
1111 current_values.push(s.to_string());
1112 }
1113 }
1114 Ok(Event::Eof) => break,
1115 Err(_) => break,
1116 _ => {}
1117 }
1118 }
1119
1120 Ok(attributes)
1121}
1122
1123#[cfg(not(feature = "saml"))]
1125fn extract_attributes_from_saml(_saml_xml: &str) -> Result<HashMap<String, Vec<String>>, String> {
1126 Err("SAML parsing requires the 'saml' feature".to_string())
1127}
1128
1129#[cfg(feature = "saml")]
1135fn validate_saml_conditions(saml_xml: &str, sp_entity_id: &str) -> Result<(), String> {
1136 let mut reader = Reader::from_str(saml_xml);
1137 let mut in_assertion = false;
1138 let mut in_conditions = false;
1139 let mut in_audience_restriction = false;
1140 let mut in_audience = false;
1141 let mut found_conditions = false;
1142 let mut not_before: Option<String> = None;
1143 let mut not_on_or_after: Option<String> = None;
1144 let mut audiences: Vec<String> = Vec::new();
1145
1146 loop {
1147 match reader.read_event() {
1148 Ok(Event::Start(e)) => {
1149 let local = xml_local(e.name());
1150 if local == "Assertion" {
1151 in_assertion = true;
1152 } else if in_assertion && local == "Conditions" {
1153 in_conditions = true;
1154 found_conditions = true;
1155 for attr in e.attributes().flatten() {
1156 let key = attr.key.as_ref();
1157 if key == "NotBefore" {
1158 not_before = Some(attr.value.to_string());
1159 } else if key == "NotOnOrAfter" {
1160 not_on_or_after = Some(attr.value.to_string());
1161 }
1162 }
1163 } else if in_conditions && local == "AudienceRestriction" {
1164 in_audience_restriction = true;
1165 } else if in_audience_restriction && local == "Audience" {
1166 in_audience = true;
1167 }
1168 }
1169 Ok(Event::End(e)) => {
1170 let local = xml_local(e.name());
1171 if local == "Audience" {
1172 in_audience = false;
1173 } else if local == "AudienceRestriction" {
1174 in_audience_restriction = false;
1175 } else if local == "Conditions" {
1176 break; } else if local == "Assertion" {
1178 break;
1179 }
1180 }
1181 Ok(Event::Text(t)) if in_audience => {
1182 let text: &str = &t;
1183 let s = text.trim();
1184 if !s.is_empty() {
1185 audiences.push(s.to_string());
1186 }
1187 }
1188 Ok(Event::Eof) => break,
1189 Err(e) => return Err(format!("XML parse error in Conditions: {}", e)),
1190 _ => {}
1191 }
1192 }
1193
1194 if !found_conditions {
1195 return Err("Assertion does not contain a Conditions element".to_string());
1196 }
1197
1198 let skew = chrono::Duration::seconds(60);
1200 let now = chrono::Utc::now();
1201
1202 if let Some(nb) = not_before {
1203 let ts = chrono::DateTime::parse_from_rfc3339(&nb)
1204 .or_else(|_| chrono::DateTime::parse_from_str(&nb, "%Y-%m-%dT%H:%M:%S%.fZ"))
1205 .map_err(|e| format!("Invalid NotBefore timestamp '{}': {}", nb, e))?;
1206 if now < ts.with_timezone(&chrono::Utc) - skew {
1207 return Err(format!("Assertion is not yet valid (NotBefore: {})", nb));
1208 }
1209 }
1210
1211 if let Some(noa) = not_on_or_after {
1212 let ts = chrono::DateTime::parse_from_rfc3339(&noa)
1213 .or_else(|_| chrono::DateTime::parse_from_str(&noa, "%Y-%m-%dT%H:%M:%S%.fZ"))
1214 .map_err(|e| format!("Invalid NotOnOrAfter timestamp '{}': {}", noa, e))?;
1215 if now >= ts.with_timezone(&chrono::Utc) + skew {
1216 return Err(format!("Assertion has expired (NotOnOrAfter: {})", noa));
1217 }
1218 }
1219
1220 if !audiences.is_empty() && !audiences.iter().any(|a| a == sp_entity_id) {
1222 return Err(format!(
1223 "Assertion audience restriction does not include this SP (expected '{}', got {:?})",
1224 sp_entity_id, audiences
1225 ));
1226 }
1227
1228 Ok(())
1229}
1230
1231#[cfg(feature = "saml")]
1234fn xml_extract_status_code(saml_xml: &str) -> Option<String> {
1235 let mut reader = Reader::from_str(saml_xml);
1236 let mut in_status = false;
1237
1238 loop {
1239 match reader.read_event() {
1240 Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
1241 let local = xml_local(e.name());
1242 if local == "Status" {
1243 in_status = true;
1244 } else if in_status && local == "StatusCode" {
1245 for attr in e.attributes().flatten() {
1246 if attr.key.as_ref() == "Value" {
1247 return Some(attr.value.to_string());
1248 }
1249 }
1250 return None; }
1252 }
1253 Ok(Event::End(e)) => {
1254 if xml_local(e.name()) == "Status" {
1255 return None; }
1257 }
1258 Ok(Event::Eof) => break,
1259 Err(_) => break,
1260 _ => {}
1261 }
1262 }
1263 None
1264}
1265
1266#[cfg(feature = "saml")]
1268fn xml_extract_name_id(saml_xml: &str) -> Option<String> {
1269 let mut reader = Reader::from_str(saml_xml);
1270 let mut in_name_id = false;
1271
1272 loop {
1273 match reader.read_event() {
1274 Ok(Event::Start(e)) => {
1275 if xml_local(e.name()) == "NameID" {
1276 in_name_id = true;
1277 }
1278 }
1279 Ok(Event::Text(e)) if in_name_id => {
1280 let text: &str = &e;
1281 let s = text.trim();
1282 if !s.is_empty() {
1283 return Some(s.to_string());
1284 }
1285 }
1286 Ok(Event::End(e)) if in_name_id && xml_local(e.name()) == "NameID" => {
1287 return None; }
1289 Ok(Event::Eof) => break,
1290 Err(_) => break,
1291 _ => {}
1292 }
1293 }
1294 None
1295}
1296
1297#[cfg(test)]
1298#[cfg(feature = "saml")]
1299mod tests {
1300 use super::*;
1301 #[cfg(feature = "saml")]
1302 use crate::methods::saml::dsig::key_from_x509_der;
1303 use chrono::{Duration, Utc};
1304
1305 #[test]
1314 fn test_key_from_x509_der_accepts_ecdsa_p256_certificate() {
1315 let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
1316 .expect("ECDSA P-256 key generation should succeed");
1317 let params = rcgen::CertificateParams::default();
1318 let cert = params
1319 .self_signed(&key_pair)
1320 .expect("self-signing should succeed");
1321
1322 let key = key_from_x509_der(cert.der().as_ref())
1323 .expect("a valid ECDSA P-256 certificate must be accepted");
1324 assert_eq!(key.usage, bergshamra::KeyUsage::Verify);
1325 }
1326
1327 #[test]
1335 fn test_key_from_x509_der_accepts_rsa_certificate() {
1336 let key_pair =
1337 rcgen::KeyPair::generate_rsa_for(&rcgen::PKCS_RSA_SHA256, rcgen::RsaKeySize::_2048)
1338 .expect("RSA key generation should succeed");
1339 let params = rcgen::CertificateParams::default();
1340 let cert = params
1341 .self_signed(&key_pair)
1342 .expect("self-signing should succeed");
1343
1344 let key = key_from_x509_der(cert.der().as_ref())
1345 .expect("a valid RSA certificate must be accepted");
1346 assert_eq!(key.usage, bergshamra::KeyUsage::Verify);
1347 }
1348
1349 #[test]
1359 fn test_bergshamra_feature_choices_are_deliberate() {
1360 let manifest = include_str!("../../Cargo.toml");
1361 let mut bergshamra_lines = Vec::new();
1362 for line in manifest
1363 .lines()
1364 .skip_while(|l| !l.trim_start().starts_with("bergshamra = {"))
1365 {
1366 let done = line.trim_end().ends_with("optional = true }");
1367 bergshamra_lines.push(line);
1368 if done {
1369 break;
1370 }
1371 }
1372 let bergshamra_line = bergshamra_lines.join("\n");
1373
1374 assert!(
1375 bergshamra_line.contains(r#""aws-lc""#),
1376 "expected bergshamra's feature list to include \"aws-lc\": {bergshamra_line}"
1377 );
1378 for excluded in ["legacy-algorithms", "post-quantum", "pkcs11", "rustcrypto"] {
1379 assert!(
1380 !bergshamra_line.contains(excluded),
1381 "bergshamra's feature list now includes {excluded:?}, which was a deliberate \
1382 exclusion (see the dependency's own Cargo.toml comment) -- if this is an \
1383 intentional change, update that comment and this test together, don't just \
1384 fix the assertion"
1385 );
1386 }
1387 }
1388
1389 #[test]
1390 fn test_key_from_x509_der_rejects_non_certificate_der() {
1391 let err = key_from_x509_der(b"not a certificate")
1392 .expect_err("garbage input must not be accepted as a certificate");
1393 assert!(err.contains("Failed to parse X.509 certificate"));
1394 }
1395
1396 #[test]
1397 fn test_extract_issuer() {
1398 let xml = r#"<samlp:Response><saml:Issuer>https://idp.example.com</saml:Issuer></samlp:Response>"#;
1400 assert_eq!(extract_issuer(xml).unwrap(), "https://idp.example.com");
1401 }
1402
1403 #[test]
1404 fn test_extract_username() {
1405 let xml = r#"<saml:Assertion><saml:Subject><saml:NameID>user@example.com</saml:NameID></saml:Subject></saml:Assertion>"#;
1407 assert_eq!(extract_username_from_saml(xml).unwrap(), "user@example.com");
1408 }
1409
1410 #[test]
1411 fn test_validate_conditions_time() {
1412 let now = Utc::now();
1414 let past = now - Duration::minutes(10);
1415 let future = now + Duration::minutes(10);
1416 let xml = format!(
1417 r#"<saml:Assertion><saml:Conditions NotBefore="{}" NotOnOrAfter="{}"><saml:AudienceRestriction><saml:Audience>test-aud</saml:Audience></saml:AudienceRestriction></saml:Conditions></saml:Assertion>"#,
1418 past.to_rfc3339(),
1419 future.to_rfc3339()
1420 );
1421 assert!(validate_saml_conditions(&xml, "test-aud").is_ok());
1422
1423 let wrong_aud = format!(
1424 r#"<saml:Assertion><saml:Conditions NotBefore="{}" NotOnOrAfter="{}"><saml:AudienceRestriction><saml:Audience>wrong-aud</saml:Audience></saml:AudienceRestriction></saml:Conditions></saml:Assertion>"#,
1425 past.to_rfc3339(),
1426 future.to_rfc3339()
1427 );
1428 assert!(validate_saml_conditions(&wrong_aud, "test-aud").is_err());
1429 }
1430
1431 #[test]
1432 fn test_extract_status() {
1433 let xml = r#"<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>"#;
1434 assert_eq!(
1435 xml_extract_status_code(xml).unwrap(),
1436 "urn:oasis:names:tc:SAML:2.0:status:Success"
1437 );
1438 }
1439}