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