Skip to main content

auth_framework/protocols/
ws_federation.rs

1//! WS-Federation Passive Requestor Profile
2//!
3//! Implements the WS-Federation 1.2 passive requestor profile for browser-based
4//! SSO. WS-Federation is commonly used with Active Directory Federation Services
5//! (ADFS) and Azure AD in legacy enterprise environments.
6//!
7//! # Protocol Flow (Passive Requestor)
8//!
9//! 1. Application redirects the user to the STS sign-in URL with `wa=wsignin1.0`
10//! 2. STS authenticates the user and posts a security token (SAML assertion)
11//!    back to the application's reply URL (`wtrealm`)
12//! 3. Application validates the security token and establishes a session
13//! 4. Logout: redirect to STS with `wa=wsignout1.0`
14//!
15//! # Security Considerations
16//!
17//! - Federation metadata should be fetched over HTTPS and cached
18//! - Security tokens (SAML assertions) are only accepted when their signature
19//!   verifies under a signing certificate (or thumbprint) you configured; with
20//!   none configured the client cannot be built
21//! - Replay protection via `wctx` state parameter
22
23use crate::errors::{AuthError, Result};
24use ring::rand::SecureRandom;
25use serde::{Deserialize, Serialize};
26use std::collections::HashMap;
27use std::time::{SystemTime, UNIX_EPOCH};
28
29/// Parsed assertion fields: `(subject, issuer, audience, not_before, not_on_or_after, claims)`.
30#[cfg(any(feature = "saml", test))]
31type ParsedAssertion = (
32    String,
33    String,
34    String,
35    u64,
36    u64,
37    HashMap<String, Vec<String>>,
38);
39
40// ─── WS-Federation Constants ─────────────────────────────────────────────────
41
42/// WS-Federation action values.
43pub mod action {
44    /// Sign-in action.
45    pub const SIGN_IN: &str = "wsignin1.0";
46    /// Sign-out action.
47    pub const SIGN_OUT: &str = "wsignout1.0";
48    /// Sign-out cleanup action.
49    pub const SIGN_OUT_CLEANUP: &str = "wsignoutcleanup1.0";
50    /// Attribute request action.
51    pub const ATTRIBUTE: &str = "wattr1.0";
52}
53
54/// WS-Federation XML namespace URIs.
55pub mod ns {
56    pub const WS_FED: &str = "http://docs.oasis-open.org/wsfed/federation/200706";
57    pub const WS_TRUST: &str = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
58    pub const WS_ADDRESSING: &str = "http://www.w3.org/2005/08/addressing";
59    pub const SAML_11_ASSERTION: &str = "urn:oasis:names:tc:SAML:1.0:assertion";
60    pub const SAML_20_ASSERTION: &str = "urn:oasis:names:tc:SAML:2.0:assertion";
61}
62
63// ─── Configuration ───────────────────────────────────────────────────────────
64
65/// WS-Federation Relying Party (RP) configuration.
66#[derive(Debug, Clone)]
67pub struct WsFederationConfig {
68    /// STS (Security Token Service) sign-in URL.
69    pub sts_url: String,
70
71    /// This relying party's realm (wtrealm / appliesTo).
72    pub realm: String,
73
74    /// Reply URL where the STS posts the token back (wreply).
75    pub reply_url: String,
76
77    /// Federation metadata URL for dynamic trust configuration.
78    pub metadata_url: Option<String>,
79
80    /// Trusted issuer identifiers.
81    pub trusted_issuers: Vec<String>,
82
83    /// Trusted signing certificate fingerprints (SHA-256 hex). A token is accepted if it is signed
84    /// under a certificate it carries whose thumbprint is listed here.
85    pub trusted_cert_thumbprints: Vec<String>,
86
87    /// Signing certificates to trust, as `(issuer, certificate)` with the certificate a PEM block or
88    /// bare base64 DER (for example from the federation metadata, checked out of band). A token is
89    /// accepted if its issuer is listed and it is signed under that issuer's certificate.
90    ///
91    /// At least one certificate or thumbprint must be configured: a token is only accepted when its
92    /// signature verifies under a key configured here, never under a key the token supplies itself.
93    pub trusted_signing_certificates: Vec<(String, String)>,
94
95    /// Maximum allowed clock skew for token validation (seconds).
96    pub max_clock_skew_secs: u64,
97
98    /// Whether to require encrypted tokens.
99    pub require_encrypted_tokens: bool,
100
101    /// HTTP request timeout.
102    pub timeout_secs: u64,
103
104    /// Custom home realm for IdP discovery (whr parameter).
105    pub home_realm: Option<String>,
106}
107
108impl Default for WsFederationConfig {
109    fn default() -> Self {
110        Self {
111            sts_url: String::new(),
112            realm: String::new(),
113            reply_url: String::new(),
114            metadata_url: None,
115            trusted_issuers: Vec::new(),
116            trusted_cert_thumbprints: Vec::new(),
117            trusted_signing_certificates: Vec::new(),
118            max_clock_skew_secs: 300,
119            require_encrypted_tokens: false,
120            timeout_secs: 10,
121            home_realm: None,
122        }
123    }
124}
125
126// ─── Data Types ──────────────────────────────────────────────────────────────
127
128/// Parsed WS-Federation sign-in response.
129#[derive(Clone, Serialize, Deserialize)]
130pub struct WsFedSignInResponse {
131    /// The action (`wa` parameter) — should be `wsignin1.0`.
132    pub action: String,
133
134    /// The `wresult` — contains the `<RequestSecurityTokenResponse>`.
135    pub result_xml: String,
136
137    /// The `wctx` context/state parameter echoed back from the STS.
138    pub context: Option<String>,
139}
140
141impl std::fmt::Debug for WsFedSignInResponse {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        let mut d = f.debug_struct("WsFedSignInResponse");
144        d.field("action", &self.action);
145        d.field(
146            "result_xml",
147            &crate::utils::redact::redacted(&self.result_xml),
148        );
149        d.field("context", &self.context);
150        d.finish()
151    }
152}
153
154/// Validated security token extracted from a WS-Federation response.
155#[derive(Clone, Serialize, Deserialize)]
156pub struct WsFedSecurityToken {
157    /// Token type (SAML 1.1 or SAML 2.0).
158    pub token_type: WsFedTokenType,
159
160    /// Authenticated subject / name identifier.
161    pub subject: String,
162
163    /// Token issuer.
164    pub issuer: String,
165
166    /// Token audience (appliesTo / realm).
167    pub audience: String,
168
169    /// When the token was issued.
170    pub issued_at: u64,
171
172    /// When the token expires.
173    pub expires_at: u64,
174
175    /// Claims / attributes from the token.
176    pub claims: HashMap<String, Vec<String>>,
177
178    /// Raw assertion XML (for downstream processing).
179    pub raw_assertion: String,
180}
181
182impl std::fmt::Debug for WsFedSecurityToken {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        let mut d = f.debug_struct("WsFedSecurityToken");
185        d.field("token_type", &self.token_type);
186        d.field("subject", &self.subject);
187        d.field("issuer", &self.issuer);
188        d.field("audience", &self.audience);
189        d.field("issued_at", &self.issued_at);
190        d.field("expires_at", &self.expires_at);
191        d.field("claims", &self.claims);
192        d.field(
193            "raw_assertion",
194            &crate::utils::redact::redacted(&self.raw_assertion),
195        );
196        d.finish()
197    }
198}
199
200/// Security token type.
201#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
202pub enum WsFedTokenType {
203    /// SAML 1.1 assertion.
204    Saml11,
205    /// SAML 2.0 assertion.
206    Saml20,
207    /// JWT (non-standard but used by Azure AD).
208    Jwt,
209}
210
211/// Federation metadata for an STS.
212#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct FederationMetadata {
214    /// STS entity ID.
215    pub entity_id: String,
216
217    /// Passive requestor endpoint URL.
218    pub passive_endpoint: Option<String>,
219
220    /// Signing certificate(s) as Base64-encoded DER.
221    pub signing_certificates: Vec<String>,
222
223    /// Token types offered.
224    pub token_types_offered: Vec<String>,
225
226    /// Claim types offered.
227    pub claim_types_offered: Vec<ClaimTypeOffered>,
228}
229
230/// Claim type advertised in federation metadata.
231#[derive(Debug, Clone, Serialize, Deserialize)]
232pub struct ClaimTypeOffered {
233    pub uri: String,
234    pub display_name: Option<String>,
235    pub description: Option<String>,
236}
237
238// ─── Client ──────────────────────────────────────────────────────────────────
239
240/// WS-Federation Relying Party client.
241#[derive(Debug)]
242pub struct WsFederationClient {
243    config: WsFederationConfig,
244    http: reqwest::Client,
245}
246
247impl WsFederationClient {
248    /// Create a new WS-Federation client.
249    pub fn new(config: WsFederationConfig) -> Result<Self> {
250        if config.sts_url.is_empty() {
251            return Err(AuthError::config("WS-Federation STS URL must be set"));
252        }
253        if !config.sts_url.starts_with("https://") {
254            return Err(AuthError::config("WS-Federation STS URL must use HTTPS"));
255        }
256        if config.realm.is_empty() {
257            return Err(AuthError::config("WS-Federation realm must be set"));
258        }
259        if config.trusted_signing_certificates.is_empty()
260            && config.trusted_cert_thumbprints.is_empty()
261        {
262            return Err(AuthError::config(
263                "WS-Federation needs a trusted signing certificate or thumbprint: sign-in tokens are only accepted when signed under a configured key",
264            ));
265        }
266
267        let http = reqwest::Client::builder()
268            .timeout(std::time::Duration::from_secs(config.timeout_secs))
269            .build()
270            .map_err(|e| AuthError::internal(format!("Failed to build HTTP client: {e}")))?;
271
272        Ok(Self { config, http })
273    }
274
275    /// Generate the WS-Federation sign-in redirect URL.
276    ///
277    /// Returns `(url, wctx)` where `wctx` is a random state value for
278    /// CSRF protection.
279    pub fn sign_in_url(&self) -> Result<(String, String)> {
280        let rng = ring::rand::SystemRandom::new();
281        let mut ctx_bytes = [0u8; 16];
282        rng.fill(&mut ctx_bytes)
283            .map_err(|_| AuthError::crypto("Failed to generate wctx nonce"))?;
284        let wctx = hex::encode(ctx_bytes);
285
286        let mut url = format!(
287            "{}?wa={}&wtrealm={}&wreply={}&wctx={}",
288            self.config.sts_url,
289            urlencoding::encode(action::SIGN_IN),
290            urlencoding::encode(&self.config.realm),
291            urlencoding::encode(&self.config.reply_url),
292            urlencoding::encode(&wctx),
293        );
294
295        if let Some(ref whr) = self.config.home_realm {
296            url.push_str(&format!("&whr={}", urlencoding::encode(whr)));
297        }
298
299        Ok((url, wctx))
300    }
301
302    /// Generate the WS-Federation sign-out URL.
303    pub fn sign_out_url(&self) -> String {
304        format!(
305            "{}?wa={}&wtrealm={}",
306            self.config.sts_url,
307            urlencoding::encode(action::SIGN_OUT),
308            urlencoding::encode(&self.config.realm),
309        )
310    }
311
312    /// Process a WS-Federation sign-in response (POST from STS).
313    ///
314    /// The parameters are extracted from the form POST body:
315    /// - `wa`: action (should be `wsignin1.0`)
316    /// - `wresult`: the `<RequestSecurityTokenResponse>` XML
317    /// - `wctx`: echoed state parameter
318    pub fn process_sign_in_response(
319        &self,
320        wa: &str,
321        wresult: &str,
322        wctx: Option<&str>,
323        expected_wctx: &str,
324    ) -> Result<WsFedSecurityToken> {
325        // Validate action
326        if wa != action::SIGN_IN {
327            return Err(AuthError::validation(format!(
328                "Unexpected WS-Fed action: {wa}"
329            )));
330        }
331
332        // Validate wctx for CSRF protection
333        if let Some(ctx) = wctx {
334            if !constant_time_eq(ctx.as_bytes(), expected_wctx.as_bytes()) {
335                return Err(AuthError::validation("WS-Federation wctx mismatch (CSRF)"));
336            }
337        } else {
338            return Err(AuthError::validation("Missing wctx parameter"));
339        }
340
341        // Verify the signature under a configured key and read the assertion it covers
342        let token = self.verify_and_parse(wresult)?;
343
344        // Validate token
345        self.validate_token(&token)?;
346
347        Ok(token)
348    }
349
350    /// Fetch and parse federation metadata from the metadata URL.
351    pub async fn fetch_metadata(&self) -> Result<FederationMetadata> {
352        let url = self
353            .config
354            .metadata_url
355            .as_deref()
356            .ok_or_else(|| AuthError::config("Federation metadata URL not configured"))?;
357
358        let resp =
359            self.http.get(url).send().await.map_err(|e| {
360                AuthError::internal(format!("Federation metadata fetch failed: {e}"))
361            })?;
362
363        if !resp.status().is_success() {
364            let status = resp.status();
365            return Err(AuthError::internal(format!(
366                "Federation metadata HTTP error: {status}"
367            )));
368        }
369
370        let body = resp
371            .text()
372            .await
373            .map_err(|e| AuthError::internal(format!("Federation metadata read failed: {e}")))?;
374
375        parse_federation_metadata(&body)
376    }
377
378    /// Verify a RequestSecurityTokenResponse (RSTR) and read the security token out of it.
379    ///
380    /// The assertion must be signed under a key configured in `trusted_signing_certificates` (for
381    /// its issuer) or identified by `trusted_cert_thumbprints`; only the assertion that signature
382    /// covers is read. JWT tokens are not accepted: their signature is not verified here.
383    #[cfg(feature = "saml")]
384    fn verify_and_parse(&self, rstr_xml: &str) -> Result<WsFedSecurityToken> {
385        use crate::methods::saml::{
386            SamlTrustAnchors, anchors_for_thumbprints, verify_signed_assertion,
387        };
388
389        let mut anchors = SamlTrustAnchors::new();
390        for (issuer, certificate) in &self.config.trusted_signing_certificates {
391            anchors.trust_pem(issuer.clone(), certificate)?;
392        }
393        anchors.extend(anchors_for_thumbprints(
394            rstr_xml,
395            &self.config.trusted_issuers,
396            &self.config.trusted_cert_thumbprints,
397        )?);
398
399        let verified = verify_signed_assertion(rstr_xml, &anchors)?;
400        let raw_assertion = verified.assertion_xml;
401
402        // SAML 1.1 assertions carry `MajorVersion` and `AssertionID` on the element itself.
403        let opening = raw_assertion.split('>').next().unwrap_or_default();
404        let token_type = if opening.contains("AssertionID=") || opening.contains("MajorVersion=") {
405            WsFedTokenType::Saml11
406        } else {
407            WsFedTokenType::Saml20
408        };
409        let (subject, _claimed_issuer, audience, issued_at, expires_at, claims) = match token_type {
410            WsFedTokenType::Saml11 => parse_saml11_assertion(&raw_assertion)?,
411            _ => parse_saml20_assertion(&raw_assertion)?,
412        };
413
414        Ok(WsFedSecurityToken {
415            token_type,
416            subject,
417            // The issuer the signature was verified for, not whatever text the assertion repeats.
418            issuer: verified.issuer,
419            audience,
420            issued_at,
421            expires_at,
422            claims,
423            raw_assertion,
424        })
425    }
426
427    /// Without the `saml` feature there is no signature verification, so nothing is accepted.
428    #[cfg(not(feature = "saml"))]
429    fn verify_and_parse(&self, _rstr_xml: &str) -> Result<WsFedSecurityToken> {
430        Err(AuthError::config(
431            "WS-Federation sign-in tokens can only be accepted when their signature is verified: build with the `saml` feature",
432        ))
433    }
434
435    /// Validate a security token against the configuration.
436    fn validate_token(&self, token: &WsFedSecurityToken) -> Result<()> {
437        // Check issuer trust
438        if !self.config.trusted_issuers.is_empty()
439            && !self.config.trusted_issuers.contains(&token.issuer)
440        {
441            return Err(AuthError::validation(format!(
442                "Token issuer '{}' is not trusted",
443                token.issuer
444            )));
445        }
446
447        // Check audience
448        if !token.audience.is_empty() && token.audience != self.config.realm {
449            return Err(AuthError::validation(format!(
450                "Token audience '{}' does not match realm '{}'",
451                token.audience, self.config.realm
452            )));
453        }
454
455        // Check expiration
456        let now = SystemTime::now()
457            .duration_since(UNIX_EPOCH)
458            .map_err(|e| AuthError::internal(format!("Clock error: {e}")))?
459            .as_secs();
460
461        let skew = self.config.max_clock_skew_secs;
462        if token.expires_at.saturating_add(skew) < now {
463            return Err(AuthError::validation("Security token has expired"));
464        }
465
466        if token.issued_at > now.saturating_add(skew) {
467            return Err(AuthError::validation("Security token issued in the future"));
468        }
469
470        Ok(())
471    }
472}
473
474// ─── XML Parsing Helpers ─────────────────────────────────────────────────────
475
476/// Parse a SAML 2.0 assertion.
477#[cfg(any(feature = "saml", test))]
478fn parse_saml20_assertion(xml: &str) -> Result<ParsedAssertion> {
479    let subject = extract_xml_text(xml, "NameID")
480        .or_else(|| extract_xml_text(xml, "saml:NameID"))
481        .unwrap_or_default();
482
483    let issuer = extract_xml_text(xml, "Issuer")
484        .or_else(|| extract_xml_text(xml, "saml:Issuer"))
485        .unwrap_or_default();
486
487    let audience = extract_xml_text(xml, "Audience")
488        .or_else(|| extract_xml_text(xml, "saml:Audience"))
489        .unwrap_or_default();
490
491    let not_before = extract_xml_attr_val(xml, "Conditions", "NotBefore")
492        .or_else(|| extract_xml_attr_val(xml, "saml:Conditions", "NotBefore"))
493        .and_then(|s| parse_iso_timestamp(&s))
494        .unwrap_or(0);
495
496    let not_on_or_after = extract_xml_attr_val(xml, "Conditions", "NotOnOrAfter")
497        .or_else(|| extract_xml_attr_val(xml, "saml:Conditions", "NotOnOrAfter"))
498        .and_then(|s| parse_iso_timestamp(&s))
499        .unwrap_or(u64::MAX);
500
501    let claims = extract_saml_attributes(xml);
502
503    Ok((
504        subject,
505        issuer,
506        audience,
507        not_before,
508        not_on_or_after,
509        claims,
510    ))
511}
512
513/// Parse a SAML 1.1 assertion.
514#[cfg(feature = "saml")]
515fn parse_saml11_assertion(xml: &str) -> Result<ParsedAssertion> {
516    let subject = extract_xml_text(xml, "NameIdentifier")
517        .or_else(|| extract_xml_text(xml, "saml:NameIdentifier"))
518        .unwrap_or_default();
519
520    let issuer = extract_xml_attr_val(xml, "Assertion", "Issuer")
521        .or_else(|| extract_xml_attr_val(xml, "saml:Assertion", "Issuer"))
522        .unwrap_or_default();
523
524    let audience = extract_xml_text(xml, "Audience")
525        .or_else(|| extract_xml_text(xml, "saml:Audience"))
526        .unwrap_or_default();
527
528    let not_before = extract_xml_attr_val(xml, "Conditions", "NotBefore")
529        .or_else(|| extract_xml_attr_val(xml, "saml:Conditions", "NotBefore"))
530        .and_then(|s| parse_iso_timestamp(&s))
531        .unwrap_or(0);
532
533    let not_on_or_after = extract_xml_attr_val(xml, "Conditions", "NotOnOrAfter")
534        .or_else(|| extract_xml_attr_val(xml, "saml:Conditions", "NotOnOrAfter"))
535        .and_then(|s| parse_iso_timestamp(&s))
536        .unwrap_or(u64::MAX);
537
538    let claims = extract_saml_attributes(xml);
539
540    Ok((
541        subject,
542        issuer,
543        audience,
544        not_before,
545        not_on_or_after,
546        claims,
547    ))
548}
549
550/// Extract text content from an XML element.
551fn extract_xml_text(xml: &str, tag: &str) -> Option<String> {
552    let open = format!("<{tag}");
553    let close = format!("</{tag}>");
554    let mut search_from = 0;
555    loop {
556        let start = xml[search_from..].find(&open).map(|i| search_from + i)?;
557        // Ensure we matched the exact tag, not a prefix (e.g. "Audience" vs "AudienceRestriction")
558        let after_name = start + open.len();
559        if after_name < xml.len() {
560            let next_char = xml.as_bytes()[after_name];
561            if next_char != b'>' && next_char != b' ' && next_char != b'/' {
562                search_from = after_name;
563                continue;
564            }
565        }
566        let after_tag = xml[after_name..].find('>')?;
567        let content_start = after_name + after_tag + 1;
568        let content_end = xml[content_start..].find(&close)?;
569        return Some(
570            xml[content_start..content_start + content_end]
571                .trim()
572                .to_string(),
573        );
574    }
575}
576
577/// Extract an attribute value from an XML element.
578fn extract_xml_attr_val(xml: &str, tag: &str, attr: &str) -> Option<String> {
579    let open = format!("<{tag}");
580    let start = xml.find(&open)?;
581    let tag_end = xml[start..].find('>')?;
582    let tag_content = &xml[start..start + tag_end];
583    let attr_search = format!("{attr}=\"");
584    let attr_start = tag_content.find(&attr_search)?;
585    let val_start = attr_start + attr_search.len();
586    let val_end = tag_content[val_start..].find('"')?;
587    Some(tag_content[val_start..val_start + val_end].to_string())
588}
589
590/// Extract SAML attribute statements.
591#[cfg(any(feature = "saml", test))]
592fn extract_saml_attributes(xml: &str) -> HashMap<String, Vec<String>> {
593    let mut attrs = HashMap::new();
594
595    // Find all <Attribute Name="..."> elements
596    let mut search_pos = 0;
597    while let Some(attr_pos) = xml[search_pos..].find("<Attribute ") {
598        let abs_pos = search_pos + attr_pos;
599        let tag_end = match xml[abs_pos..].find('>') {
600            Some(p) => abs_pos + p,
601            None => break,
602        };
603
604        // Extract attribute name
605        let tag_content = &xml[abs_pos..tag_end];
606        let name = if let Some(n) = extract_inline_attr(tag_content, "Name") {
607            n
608        } else {
609            search_pos = tag_end + 1;
610            continue;
611        };
612
613        // Find the closing </Attribute> or </saml:Attribute>
614        let close_tag = "</Attribute>";
615        let alt_close = "</saml:Attribute>".to_string();
616        let end_pos = xml[tag_end..]
617            .find(close_tag)
618            .or_else(|| xml[tag_end..].find(&alt_close))
619            .map(|p| tag_end + p)
620            .unwrap_or(xml.len());
621
622        // Extract <AttributeValue> elements within this attribute
623        let attr_block = &xml[tag_end + 1..end_pos];
624        let values = extract_attribute_values(attr_block);
625
626        if !values.is_empty() {
627            attrs.entry(name).or_insert_with(Vec::new).extend(values);
628        }
629
630        search_pos = end_pos;
631    }
632
633    attrs
634}
635
636/// Extract the value of an inline XML attribute.
637fn extract_inline_attr(tag: &str, attr: &str) -> Option<String> {
638    let search = format!("{attr}=\"");
639    let start = tag.find(&search)?;
640    let val_start = start + search.len();
641    let val_end = tag[val_start..].find('"')?;
642    Some(tag[val_start..val_start + val_end].to_string())
643}
644
645/// Extract <AttributeValue> elements from an attribute block.
646#[cfg(any(feature = "saml", test))]
647fn extract_attribute_values(block: &str) -> Vec<String> {
648    let mut values = Vec::new();
649    let mut pos = 0;
650
651    let open_tags = ["<AttributeValue", "<saml:AttributeValue"];
652    let close_tags = ["</AttributeValue>", "</saml:AttributeValue>"];
653
654    while pos < block.len() {
655        let mut found = false;
656        for (open, close) in open_tags.iter().zip(close_tags.iter()) {
657            if let Some(start) = block[pos..].find(open) {
658                let abs_start = pos + start;
659                if let Some(tag_end) = block[abs_start..].find('>') {
660                    let content_start = abs_start + tag_end + 1;
661                    if let Some(close_pos) = block[content_start..].find(close) {
662                        let val = block[content_start..content_start + close_pos].trim();
663                        if !val.is_empty() {
664                            values.push(val.to_string());
665                        }
666                        pos = content_start + close_pos + close.len();
667                        found = true;
668                        break;
669                    }
670                }
671            }
672        }
673        if !found {
674            break;
675        }
676    }
677
678    values
679}
680
681/// Parse an ISO 8601 timestamp to Unix epoch seconds.
682#[cfg(any(feature = "saml", test))]
683fn parse_iso_timestamp(s: &str) -> Option<u64> {
684    chrono::DateTime::parse_from_rfc3339(s)
685        .ok()
686        .map(|dt| dt.timestamp() as u64)
687}
688
689/// Parse federation metadata XML.
690fn parse_federation_metadata(xml: &str) -> Result<FederationMetadata> {
691    let entity_id = extract_xml_attr_val(xml, "EntityDescriptor", "entityID").unwrap_or_default();
692
693    // Extract passive endpoint
694    let passive_endpoint = extract_xml_attr_val(xml, "PassiveRequestorEndpoint", "Location")
695        .or_else(|| {
696            // Also look in Address element
697            extract_xml_text(xml, "Address").or_else(|| extract_xml_text(xml, "wsa:Address"))
698        });
699
700    // Extract signing certificates
701    let signing_certificates = extract_all_x509_certs(xml);
702
703    // Extract token types offered
704    let token_types = extract_xml_list_by_tag(xml, "TokenType");
705
706    // Extract claim types
707    let claim_types = extract_claim_types(xml);
708
709    Ok(FederationMetadata {
710        entity_id,
711        passive_endpoint,
712        signing_certificates,
713        token_types_offered: token_types,
714        claim_types_offered: claim_types,
715    })
716}
717
718/// Extract all X509Certificate values from metadata.
719fn extract_all_x509_certs(xml: &str) -> Vec<String> {
720    let mut certs = Vec::new();
721    let tag = "X509Certificate";
722    let open = format!("<{tag}>");
723    let close = format!("</{tag}>");
724    let mut pos = 0;
725
726    while let Some(start) = xml[pos..].find(&open) {
727        let content_start = pos + start + open.len();
728        if let Some(end) = xml[content_start..].find(&close) {
729            let cert = xml[content_start..content_start + end]
730                .trim()
731                .replace(['\n', '\r', ' '], "");
732            if !cert.is_empty() {
733                certs.push(cert);
734            }
735            pos = content_start + end + close.len();
736        } else {
737            break;
738        }
739    }
740
741    certs
742}
743
744/// Extract token type values.
745fn extract_xml_list_by_tag(xml: &str, tag: &str) -> Vec<String> {
746    let mut values = Vec::new();
747    let open = format!("<{tag}");
748    let close = format!("</{tag}>");
749    let mut pos = 0;
750
751    while let Some(start) = xml[pos..].find(&open) {
752        let abs = pos + start;
753        if let Some(tag_end) = xml[abs..].find('>') {
754            let content_start = abs + tag_end + 1;
755            if let Some(close_pos) = xml[content_start..].find(&close) {
756                let val = xml[content_start..content_start + close_pos].trim();
757                if !val.is_empty() {
758                    values.push(val.to_string());
759                }
760                pos = content_start + close_pos + close.len();
761            } else {
762                break;
763            }
764        } else {
765            break;
766        }
767    }
768
769    values
770}
771
772/// Extract claim types offered from metadata.
773fn extract_claim_types(xml: &str) -> Vec<ClaimTypeOffered> {
774    let mut claims = Vec::new();
775    let mut pos = 0;
776
777    while let Some(start) = xml[pos..].find("<ClaimType ") {
778        let abs = pos + start;
779        let tag_end = match xml[abs..].find('>') {
780            Some(p) => abs + p,
781            None => break,
782        };
783        let tag = &xml[abs..tag_end];
784
785        let uri = extract_inline_attr(tag, "Uri").unwrap_or_default();
786
787        let close = "</ClaimType>";
788        let block_end = xml[tag_end..]
789            .find(close)
790            .map(|p| tag_end + p + close.len())
791            .unwrap_or(xml.len());
792
793        let block = &xml[tag_end + 1..block_end.saturating_sub(close.len())];
794
795        let display_name = extract_xml_text(block, "DisplayName");
796        let description = extract_xml_text(block, "Description");
797
798        claims.push(ClaimTypeOffered {
799            uri,
800            display_name,
801            description,
802        });
803
804        pos = block_end;
805    }
806
807    claims
808}
809
810/// Constant-time byte comparison.
811fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
812    use subtle::ConstantTimeEq;
813    if a.len() != b.len() {
814        return false;
815    }
816    a.ct_eq(b).into()
817}
818
819#[cfg(test)]
820mod tests {
821    use super::*;
822
823    #[test]
824    fn test_config_defaults() {
825        let config = WsFederationConfig::default();
826        assert_eq!(config.max_clock_skew_secs, 300);
827        assert!(!config.require_encrypted_tokens);
828    }
829
830    #[test]
831    fn test_client_requires_https() {
832        let config = WsFederationConfig {
833            sts_url: "http://adfs.example.com/adfs/ls".into(),
834            realm: "https://app.example.com".into(),
835            ..Default::default()
836        };
837        let err = WsFederationClient::new(config).unwrap_err();
838        assert!(err.to_string().contains("HTTPS"));
839    }
840
841    #[test]
842    fn test_client_requires_realm() {
843        let config = WsFederationConfig {
844            sts_url: "https://adfs.example.com/adfs/ls".into(),
845            ..Default::default()
846        };
847        let err = WsFederationClient::new(config).unwrap_err();
848        assert!(err.to_string().contains("realm"));
849    }
850
851    #[test]
852    fn test_sign_in_url() {
853        let config = WsFederationConfig {
854            sts_url: "https://adfs.example.com/adfs/ls".into(),
855            realm: "https://app.example.com".into(),
856            reply_url: "https://app.example.com/auth/wsfed".into(),
857            trusted_cert_thumbprints: vec!["ab".repeat(32)],
858            ..Default::default()
859        };
860        let client = WsFederationClient::new(config).unwrap();
861        let (url, wctx) = client.sign_in_url().unwrap();
862        assert!(url.contains("wa=wsignin1.0"));
863        assert!(url.contains("wtrealm="));
864        assert!(url.contains("wreply="));
865        assert!(url.contains(&wctx));
866    }
867
868    #[test]
869    fn test_sign_out_url() {
870        let config = WsFederationConfig {
871            sts_url: "https://adfs.example.com/adfs/ls".into(),
872            realm: "https://app.example.com".into(),
873            reply_url: "https://app.example.com/auth/wsfed".into(),
874            trusted_cert_thumbprints: vec!["ab".repeat(32)],
875            ..Default::default()
876        };
877        let client = WsFederationClient::new(config).unwrap();
878        let url = client.sign_out_url();
879        assert!(url.contains("wa=wsignout1.0"));
880    }
881
882    #[test]
883    fn test_parse_saml20_assertion() {
884        let xml = r#"
885        <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Version="2.0">
886            <saml:Issuer>https://idp.example.com</saml:Issuer>
887            <saml:Subject>
888                <saml:NameID>jdoe@example.com</saml:NameID>
889            </saml:Subject>
890            <saml:Conditions NotBefore="2024-01-01T00:00:00Z" NotOnOrAfter="2034-01-01T00:00:00Z">
891                <saml:AudienceRestriction>
892                    <saml:Audience>https://app.example.com</saml:Audience>
893                </saml:AudienceRestriction>
894            </saml:Conditions>
895            <saml:AttributeStatement>
896                <Attribute Name="email">
897                    <AttributeValue>jdoe@example.com</AttributeValue>
898                </Attribute>
899            </saml:AttributeStatement>
900        </saml:Assertion>
901        "#;
902
903        let (subject, issuer, audience, _issued, _expires, claims) =
904            parse_saml20_assertion(xml).unwrap();
905
906        assert_eq!(subject, "jdoe@example.com");
907        assert_eq!(issuer, "https://idp.example.com");
908        assert_eq!(audience, "https://app.example.com");
909        assert!(claims.contains_key("email"));
910    }
911
912    #[test]
913    fn test_action_constants() {
914        assert_eq!(action::SIGN_IN, "wsignin1.0");
915        assert_eq!(action::SIGN_OUT, "wsignout1.0");
916    }
917}