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