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