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