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 [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#[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 == b"Response" && !in_response {
905 in_response = true;
906 depth = 1;
907 } else if in_response {
908 depth += 1;
909 if local == b"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 == b"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 if let Ok(text) = t.decode() {
929 let s = text.trim();
930 if !s.is_empty() {
931 return Some(s.to_string());
932 }
933 }
934 }
935 Ok(Event::Eof) => break,
936 Err(_) => break,
937 _ => {}
938 }
939 }
940 None
941}
942
943#[cfg(feature = "saml")]
947fn signed_in_response_to(response_xml: &str, verified: &VerifiedAssertion) -> Option<String> {
948 if verified.response_signed
949 && let Some(irt) = extract_in_response_to(response_xml)
950 {
951 return Some(irt);
952 }
953 let mut reader = Reader::from_str(&verified.assertion_xml);
954 loop {
955 match reader.read_event() {
956 Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
957 if xml_local(e.name()) == b"SubjectConfirmationData" {
958 for attr in e.attributes().flatten() {
959 if attr.key.as_ref() == b"InResponseTo" {
960 return String::from_utf8(attr.value.to_vec()).ok();
961 }
962 }
963 }
964 }
965 Ok(Event::Eof) | Err(_) => return None,
966 _ => {}
967 }
968 }
969}
970
971#[cfg(feature = "saml")]
974fn extract_in_response_to(saml_xml: &str) -> Option<String> {
975 let mut reader = Reader::from_str(saml_xml);
976 loop {
977 match reader.read_event() {
978 Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
979 if xml_local(e.name()) == b"Response" {
980 for attr in e.attributes().flatten() {
981 if attr.key.as_ref() == b"InResponseTo" {
982 return String::from_utf8(attr.value.to_vec()).ok();
983 }
984 }
985 return None; }
987 }
988 Ok(Event::Eof) => break,
989 Err(_) => break,
990 _ => {}
991 }
992 }
993 None
994}
995
996#[cfg(not(feature = "saml"))]
998fn extract_in_response_to(saml_xml: &str) -> Option<String> {
999 let response_tag_start = saml_xml.find("<samlp:Response")?;
1002 let tag_end = saml_xml[response_tag_start..].find('>')?;
1003 let tag = &saml_xml[response_tag_start..response_tag_start + tag_end];
1004 let attr_start = tag.find("InResponseTo=\"")?;
1005 let value_start = attr_start + "InResponseTo=\"".len();
1006 let value_end = tag[value_start..].find('"')?;
1007 Some(tag[value_start..value_start + value_end].to_string())
1008}
1009
1010#[cfg(feature = "saml")]
1013fn extract_username_from_saml(saml_xml: &str) -> Result<String, String> {
1014 let mut reader = Reader::from_str(saml_xml);
1015 let mut in_assertion = false;
1016 let mut in_name_id = false;
1017
1018 loop {
1019 match reader.read_event() {
1020 Ok(Event::Start(e)) => {
1021 let local = xml_local(e.name());
1022 if local == b"Assertion" {
1023 in_assertion = true;
1024 } else if in_assertion && local == b"NameID" {
1025 in_name_id = true;
1026 }
1027 }
1028 Ok(Event::End(e)) => {
1029 let local = xml_local(e.name());
1030 if in_name_id && local == b"NameID" {
1031 in_name_id = false;
1032 }
1033 if local == b"Assertion" {
1034 break; }
1036 }
1037 Ok(Event::Text(t)) if in_name_id => {
1038 if let Ok(text) = t.decode() {
1039 let s = text.trim();
1040 if !s.is_empty() {
1041 return Ok(s.to_string());
1042 }
1043 }
1044 }
1045 Ok(Event::Eof) => break,
1046 Err(e) => return Err(format!("XML parse error extracting NameID: {}", e)),
1047 _ => {}
1048 }
1049 }
1050
1051 Err("Could not extract username from SAML assertion".to_string())
1052}
1053
1054#[cfg(not(feature = "saml"))]
1056fn extract_username_from_saml(_saml_xml: &str) -> Result<String, String> {
1057 Err("SAML parsing requires the 'saml' feature".to_string())
1059}
1060
1061#[cfg(feature = "saml")]
1063fn extract_attributes_from_saml(saml_xml: &str) -> Result<HashMap<String, Vec<String>>, String> {
1064 let mut attributes = HashMap::new();
1065 attributes.insert("source".to_string(), vec!["saml".to_string()]);
1066 attributes.insert("auth_method".to_string(), vec!["saml_sso".to_string()]);
1067
1068 let mut reader = Reader::from_str(saml_xml);
1069 let mut in_attr_statement = false;
1070 let mut in_attribute = false;
1071 let mut in_attr_value = false;
1072 let mut current_attr_name: Option<String> = None;
1073 let mut current_values: Vec<String> = Vec::new();
1074
1075 loop {
1076 match reader.read_event() {
1077 Ok(Event::Start(e)) => {
1078 let local = xml_local(e.name());
1079 if local == b"AttributeStatement" {
1080 in_attr_statement = true;
1081 } else if in_attr_statement && local == b"Attribute" {
1082 in_attribute = true;
1083 current_values.clear();
1084 current_attr_name = None;
1085 for attr in e.attributes().flatten() {
1086 if xml_local(attr.key) == b"Name" {
1087 current_attr_name = String::from_utf8(attr.value.to_vec()).ok();
1088 }
1089 }
1090 } else if in_attribute && local == b"AttributeValue" {
1091 in_attr_value = true;
1092 }
1093 }
1094 Ok(Event::End(e)) => {
1095 let local = xml_local(e.name());
1096 if local == b"AttributeValue" {
1097 in_attr_value = false;
1098 } else if local == b"Attribute" && in_attribute {
1099 if let Some(name) = current_attr_name.take()
1100 && !current_values.is_empty()
1101 {
1102 attributes.insert(name, std::mem::take(&mut current_values));
1103 }
1104 in_attribute = false;
1105 } else if local == b"AttributeStatement" {
1106 in_attr_statement = false;
1107 }
1108 }
1109 Ok(Event::Text(t)) if in_attr_value => {
1110 if let Ok(text) = t.decode() {
1111 let s = text.trim();
1112 if !s.is_empty() {
1113 current_values.push(s.to_string());
1114 }
1115 }
1116 }
1117 Ok(Event::Eof) => break,
1118 Err(_) => break,
1119 _ => {}
1120 }
1121 }
1122
1123 Ok(attributes)
1124}
1125
1126#[cfg(not(feature = "saml"))]
1128fn extract_attributes_from_saml(_saml_xml: &str) -> Result<HashMap<String, Vec<String>>, String> {
1129 Err("SAML parsing requires the 'saml' feature".to_string())
1130}
1131
1132#[cfg(feature = "saml")]
1138fn validate_saml_conditions(saml_xml: &str, sp_entity_id: &str) -> Result<(), String> {
1139 let mut reader = Reader::from_str(saml_xml);
1140 let mut in_assertion = false;
1141 let mut in_conditions = false;
1142 let mut in_audience_restriction = false;
1143 let mut in_audience = false;
1144 let mut found_conditions = false;
1145 let mut not_before: Option<String> = None;
1146 let mut not_on_or_after: Option<String> = None;
1147 let mut audiences: Vec<String> = Vec::new();
1148
1149 loop {
1150 match reader.read_event() {
1151 Ok(Event::Start(e)) => {
1152 let local = xml_local(e.name());
1153 if local == b"Assertion" {
1154 in_assertion = true;
1155 } else if in_assertion && local == b"Conditions" {
1156 in_conditions = true;
1157 found_conditions = true;
1158 for attr in e.attributes().flatten() {
1159 let key = attr.key.as_ref();
1160 if key == b"NotBefore" {
1161 not_before = String::from_utf8(attr.value.to_vec()).ok();
1162 } else if key == b"NotOnOrAfter" {
1163 not_on_or_after = String::from_utf8(attr.value.to_vec()).ok();
1164 }
1165 }
1166 } else if in_conditions && local == b"AudienceRestriction" {
1167 in_audience_restriction = true;
1168 } else if in_audience_restriction && local == b"Audience" {
1169 in_audience = true;
1170 }
1171 }
1172 Ok(Event::End(e)) => {
1173 let local = xml_local(e.name());
1174 if local == b"Audience" {
1175 in_audience = false;
1176 } else if local == b"AudienceRestriction" {
1177 in_audience_restriction = false;
1178 } else if local == b"Conditions" {
1179 break; } else if local == b"Assertion" {
1181 break;
1182 }
1183 }
1184 Ok(Event::Text(t)) if in_audience => {
1185 if let Ok(text) = t.decode() {
1186 let s = text.trim();
1187 if !s.is_empty() {
1188 audiences.push(s.to_string());
1189 }
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 == b"Status" {
1247 in_status = true;
1248 } else if in_status && local == b"StatusCode" {
1249 for attr in e.attributes().flatten() {
1250 if attr.key.as_ref() == b"Value" {
1251 return String::from_utf8(attr.value.to_vec()).ok();
1252 }
1253 }
1254 return None; }
1256 }
1257 Ok(Event::End(e)) => {
1258 if xml_local(e.name()) == b"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()) == b"NameID" {
1280 in_name_id = true;
1281 }
1282 }
1283 Ok(Event::Text(e)) if in_name_id => {
1284 if let Ok(text) = e.decode() {
1285 let s = text.trim();
1286 if !s.is_empty() {
1287 return Some(s.to_string());
1288 }
1289 }
1290 }
1291 Ok(Event::End(e)) if in_name_id && xml_local(e.name()) == b"NameID" => {
1292 return None; }
1294 Ok(Event::Eof) => break,
1295 Err(_) => break,
1296 _ => {}
1297 }
1298 }
1299 None
1300}
1301
1302#[cfg(test)]
1303#[cfg(feature = "saml")]
1304mod tests {
1305 use super::*;
1306 #[cfg(feature = "saml")]
1307 use crate::methods::saml::dsig::key_from_x509_der;
1308 use chrono::{Duration, Utc};
1309
1310 #[test]
1319 fn test_key_from_x509_der_accepts_ecdsa_p256_certificate() {
1320 let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
1321 .expect("ECDSA P-256 key generation should succeed");
1322 let params = rcgen::CertificateParams::default();
1323 let cert = params
1324 .self_signed(&key_pair)
1325 .expect("self-signing should succeed");
1326
1327 let key = key_from_x509_der(cert.der().as_ref())
1328 .expect("a valid ECDSA P-256 certificate must be accepted");
1329 assert_eq!(key.usage, bergshamra::KeyUsage::Verify);
1330 }
1331
1332 #[test]
1340 fn test_key_from_x509_der_accepts_rsa_certificate() {
1341 let key_pair =
1342 rcgen::KeyPair::generate_rsa_for(&rcgen::PKCS_RSA_SHA256, rcgen::RsaKeySize::_2048)
1343 .expect("RSA key generation should succeed");
1344 let params = rcgen::CertificateParams::default();
1345 let cert = params
1346 .self_signed(&key_pair)
1347 .expect("self-signing should succeed");
1348
1349 let key = key_from_x509_der(cert.der().as_ref())
1350 .expect("a valid RSA certificate must be accepted");
1351 assert_eq!(key.usage, bergshamra::KeyUsage::Verify);
1352 }
1353
1354 #[test]
1364 fn test_bergshamra_feature_choices_are_deliberate() {
1365 let manifest = include_str!("../../Cargo.toml");
1366 let mut bergshamra_lines = Vec::new();
1367 for line in manifest
1368 .lines()
1369 .skip_while(|l| !l.trim_start().starts_with("bergshamra = {"))
1370 {
1371 let done = line.trim_end().ends_with("optional = true }");
1372 bergshamra_lines.push(line);
1373 if done {
1374 break;
1375 }
1376 }
1377 let bergshamra_line = bergshamra_lines.join("\n");
1378
1379 assert!(
1380 bergshamra_line.contains(r#""aws-lc""#),
1381 "expected bergshamra's feature list to include \"aws-lc\": {bergshamra_line}"
1382 );
1383 for excluded in ["legacy-algorithms", "post-quantum", "pkcs11", "rustcrypto"] {
1384 assert!(
1385 !bergshamra_line.contains(excluded),
1386 "bergshamra's feature list now includes {excluded:?}, which was a deliberate \
1387 exclusion (see the dependency's own Cargo.toml comment) -- if this is an \
1388 intentional change, update that comment and this test together, don't just \
1389 fix the assertion"
1390 );
1391 }
1392 }
1393
1394 #[test]
1395 fn test_key_from_x509_der_rejects_non_certificate_der() {
1396 let err = key_from_x509_der(b"not a certificate")
1397 .expect_err("garbage input must not be accepted as a certificate");
1398 assert!(err.contains("Failed to parse X.509 certificate"));
1399 }
1400
1401 #[test]
1402 fn test_extract_issuer() {
1403 let xml = r#"<samlp:Response><saml:Issuer>https://idp.example.com</saml:Issuer></samlp:Response>"#;
1405 assert_eq!(extract_issuer(xml).unwrap(), "https://idp.example.com");
1406 }
1407
1408 #[test]
1409 fn test_extract_username() {
1410 let xml = r#"<saml:Assertion><saml:Subject><saml:NameID>user@example.com</saml:NameID></saml:Subject></saml:Assertion>"#;
1412 assert_eq!(extract_username_from_saml(xml).unwrap(), "user@example.com");
1413 }
1414
1415 #[test]
1416 fn test_validate_conditions_time() {
1417 let now = Utc::now();
1419 let past = now - Duration::minutes(10);
1420 let future = now + Duration::minutes(10);
1421 let xml = format!(
1422 r#"<saml:Assertion><saml:Conditions NotBefore="{}" NotOnOrAfter="{}"><saml:AudienceRestriction><saml:Audience>test-aud</saml:Audience></saml:AudienceRestriction></saml:Conditions></saml:Assertion>"#,
1423 past.to_rfc3339(),
1424 future.to_rfc3339()
1425 );
1426 assert!(validate_saml_conditions(&xml, "test-aud").is_ok());
1427
1428 let wrong_aud = format!(
1429 r#"<saml:Assertion><saml:Conditions NotBefore="{}" NotOnOrAfter="{}"><saml:AudienceRestriction><saml:Audience>wrong-aud</saml:Audience></saml:AudienceRestriction></saml:Conditions></saml:Assertion>"#,
1430 past.to_rfc3339(),
1431 future.to_rfc3339()
1432 );
1433 assert!(validate_saml_conditions(&wrong_aud, "test-aud").is_err());
1434 }
1435
1436 #[test]
1437 fn test_extract_status() {
1438 let xml = r#"<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>"#;
1439 assert_eq!(
1440 xml_extract_status_code(xml).unwrap(),
1441 "urn:oasis:names:tc:SAML:2.0:status:Success"
1442 );
1443 }
1444}