auth_framework/protocols/
cas.rs1use crate::errors::{AuthError, Result};
23use serde::{Deserialize, Serialize};
24use std::collections::HashMap;
25
26#[derive(Debug, Clone)]
30pub struct CasConfig {
31 pub server_url: String,
33
34 pub service_url: String,
36
37 pub protocol_version: CasProtocolVersion,
39
40 pub allow_proxy: bool,
42
43 pub timeout_secs: u64,
45
46 pub renew: bool,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
52pub enum CasProtocolVersion {
53 V1,
55 V2,
57 V3,
59}
60
61impl Default for CasConfig {
62 fn default() -> Self {
63 Self {
64 server_url: String::new(),
65 service_url: String::new(),
66 protocol_version: CasProtocolVersion::V3,
67 allow_proxy: false,
68 timeout_secs: 10,
69 renew: false,
70 }
71 }
72}
73
74#[derive(Clone, Serialize, Deserialize)]
78pub struct CasValidationResult {
79 pub valid: bool,
81
82 pub user: Option<String>,
84
85 pub attributes: HashMap<String, Vec<String>>,
87
88 pub proxy_granting_ticket: Option<String>,
90
91 pub proxies: Vec<String>,
93
94 pub error_code: Option<String>,
96
97 pub error_message: Option<String>,
99}
100
101impl std::fmt::Debug for CasValidationResult {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 let mut d = f.debug_struct("CasValidationResult");
104 d.field("valid", &self.valid);
105 d.field("user", &self.user);
106 d.field("attributes", &self.attributes);
107 d.field(
108 "proxy_granting_ticket",
109 &crate::utils::redact::redacted(&self.proxy_granting_ticket),
110 );
111 d.field("proxies", &self.proxies);
112 d.field("error_code", &self.error_code);
113 d.field("error_message", &self.error_message);
114 d.finish()
115 }
116}
117
118#[derive(Clone, Serialize, Deserialize)]
120pub struct CasSloRequest {
121 pub ticket: String,
123
124 pub session_id: Option<String>,
126
127 pub timestamp: String,
129}
130
131impl std::fmt::Debug for CasSloRequest {
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 let mut d = f.debug_struct("CasSloRequest");
134 d.field("ticket", &crate::utils::redact::redacted(&self.ticket));
135 d.field(
136 "session_id",
137 &crate::utils::redact::redacted(&self.session_id),
138 );
139 d.field("timestamp", &self.timestamp);
140 d.finish()
141 }
142}
143
144#[derive(Debug)]
148pub struct CasClient {
149 config: CasConfig,
150 http: reqwest::Client,
151}
152
153impl CasClient {
154 pub fn new(config: CasConfig) -> Result<Self> {
156 if config.server_url.is_empty() {
157 return Err(AuthError::config("CAS server URL must be set"));
158 }
159 if !config.server_url.starts_with("https://") {
160 return Err(AuthError::config("CAS server URL must use HTTPS"));
161 }
162 if config.service_url.is_empty() {
163 return Err(AuthError::config("CAS service URL must be set"));
164 }
165
166 let http = reqwest::Client::builder()
167 .timeout(std::time::Duration::from_secs(config.timeout_secs))
168 .build()
169 .map_err(|e| AuthError::internal(format!("Failed to build HTTP client: {e}")))?;
170
171 Ok(Self { config, http })
172 }
173
174 pub fn login_url(&self) -> String {
176 let mut url = format!(
177 "{}/login?service={}",
178 self.config.server_url,
179 urlencoding::encode(&self.config.service_url)
180 );
181 if self.config.renew {
182 url.push_str("&renew=true");
183 }
184 url
185 }
186
187 pub fn logout_url(&self, redirect_url: Option<&str>) -> String {
189 let mut url = format!("{}/logout", self.config.server_url);
190 if let Some(redirect) = redirect_url {
191 url.push_str(&format!("?service={}", urlencoding::encode(redirect)));
192 }
193 url
194 }
195
196 pub async fn validate_ticket(&self, ticket: &str) -> Result<CasValidationResult> {
198 match self.config.protocol_version {
199 CasProtocolVersion::V1 => self.validate_v1(ticket).await,
200 CasProtocolVersion::V2 | CasProtocolVersion::V3 => self.validate_v2_v3(ticket).await,
201 }
202 }
203
204 pub async fn validate_proxy_ticket(&self, ticket: &str) -> Result<CasValidationResult> {
206 if !self.config.allow_proxy {
207 return Err(AuthError::config("Proxy tickets are not allowed"));
208 }
209 self.validate_at_endpoint("/proxyValidate", ticket).await
210 }
211
212 async fn validate_v1(&self, ticket: &str) -> Result<CasValidationResult> {
214 let url = format!(
215 "{}/validate?service={}&ticket={}",
216 self.config.server_url,
217 urlencoding::encode(&self.config.service_url),
218 urlencoding::encode(ticket)
219 );
220
221 let resp = self.http.get(&url).send().await.map_err(|e| {
222 AuthError::internal(format!(
223 "CAS v1 validation request failed: {}",
224 e.without_url()
225 ))
226 })?;
227
228 let body = resp.text().await.map_err(|e| {
229 AuthError::internal(format!("CAS v1 response read failed: {}", e.without_url()))
230 })?;
231
232 let lines: Vec<&str> = body.trim().lines().collect();
234 if lines.first().map(|l| l.trim()) == Some("yes") {
235 Ok(CasValidationResult {
236 valid: true,
237 user: lines.get(1).map(|u| u.trim().to_string()),
238 attributes: HashMap::new(),
239 proxy_granting_ticket: None,
240 proxies: Vec::new(),
241 error_code: None,
242 error_message: None,
243 })
244 } else {
245 Ok(CasValidationResult {
246 valid: false,
247 user: None,
248 attributes: HashMap::new(),
249 proxy_granting_ticket: None,
250 proxies: Vec::new(),
251 error_code: Some("INVALID_TICKET".into()),
252 error_message: Some("CAS 1.0 validation failed".into()),
253 })
254 }
255 }
256
257 async fn validate_v2_v3(&self, ticket: &str) -> Result<CasValidationResult> {
259 let endpoint = match self.config.protocol_version {
260 CasProtocolVersion::V3 => "/p3/serviceValidate",
261 _ => "/serviceValidate",
262 };
263 self.validate_at_endpoint(endpoint, ticket).await
264 }
265
266 async fn validate_at_endpoint(
268 &self,
269 endpoint: &str,
270 ticket: &str,
271 ) -> Result<CasValidationResult> {
272 let url = format!(
273 "{}{}?service={}&ticket={}",
274 self.config.server_url,
275 endpoint,
276 urlencoding::encode(&self.config.service_url),
277 urlencoding::encode(ticket)
278 );
279
280 let resp = self.http.get(&url).send().await.map_err(|e| {
281 AuthError::internal(format!(
282 "CAS validation request failed: {}",
283 e.without_url()
284 ))
285 })?;
286
287 if !resp.status().is_success() {
288 let status = resp.status();
289 return Err(AuthError::internal(format!(
290 "CAS validation HTTP error: {status}"
291 )));
292 }
293
294 let body = resp.text().await.map_err(|e| {
295 AuthError::internal(format!("CAS response read failed: {}", e.without_url()))
296 })?;
297
298 parse_cas_xml_response(&body)
299 }
300
301 pub fn parse_slo_request(body: &str) -> Result<CasSloRequest> {
305 let ticket = extract_xml_value(body, "SessionIndex")
307 .ok_or_else(|| AuthError::validation("SLO request missing SessionIndex"))?;
308
309 let session_id = extract_xml_value(body, "NameID");
310 let timestamp = extract_xml_value(body, "IssueInstant")
311 .unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
312
313 Ok(CasSloRequest {
314 ticket,
315 session_id,
316 timestamp,
317 })
318 }
319}
320
321fn parse_cas_xml_response(xml: &str) -> Result<CasValidationResult> {
325 let has_success =
328 xml.contains("<cas:authenticationSuccess") || xml.contains("<authenticationSuccess");
329 let has_failure =
330 xml.contains("<cas:authenticationFailure") || xml.contains("<authenticationFailure");
331
332 if has_success {
333 let user = extract_xml_value(xml, "cas:user").or_else(|| extract_xml_value(xml, "user"));
334
335 let attributes = parse_cas_attributes(xml);
336
337 let pgt = extract_xml_value(xml, "cas:proxyGrantingTicket")
338 .or_else(|| extract_xml_value(xml, "proxyGrantingTicket"));
339
340 let proxies = extract_xml_list(xml, "cas:proxy");
341
342 Ok(CasValidationResult {
343 valid: true,
344 user,
345 attributes,
346 proxy_granting_ticket: pgt,
347 proxies,
348 error_code: None,
349 error_message: None,
350 })
351 } else if has_failure {
352 let error_code = extract_xml_attr(xml, "cas:authenticationFailure", "code")
353 .or_else(|| extract_xml_attr(xml, "authenticationFailure", "code"));
354 let error_message = extract_xml_inner(xml, "cas:authenticationFailure")
355 .or_else(|| extract_xml_inner(xml, "authenticationFailure"));
356
357 Ok(CasValidationResult {
358 valid: false,
359 user: None,
360 attributes: HashMap::new(),
361 proxy_granting_ticket: None,
362 proxies: Vec::new(),
363 error_code,
364 error_message,
365 })
366 } else {
367 Err(AuthError::validation("Unrecognized CAS response format"))
368 }
369}
370
371fn parse_cas_attributes(xml: &str) -> HashMap<String, Vec<String>> {
373 let mut attrs = HashMap::new();
374
375 let attr_block =
377 find_xml_block(xml, "cas:attributes").or_else(|| find_xml_block(xml, "attributes"));
378
379 if let Some(block) = attr_block {
380 let mut pos = 0;
382 while pos < block.len() {
383 if let Some(start) = block[pos..].find('<') {
384 let tag_start = pos + start + 1;
385 if let Some(end) = block[tag_start..].find('>') {
386 let tag_end = tag_start + end;
387 let tag = &block[tag_start..tag_end];
388
389 if tag.starts_with('/') || tag.starts_with('?') || tag.starts_with('!') {
391 pos = tag_end + 1;
392 continue;
393 }
394
395 let tag_name = tag.split_whitespace().next().unwrap_or(tag);
396 let close = format!("</{tag_name}>");
397 if let Some(close_pos) = block[tag_end + 1..].find(&close) {
398 let value = &block[tag_end + 1..tag_end + 1 + close_pos];
399 let short_name = tag_name
400 .strip_prefix("cas:")
401 .unwrap_or(tag_name)
402 .to_string();
403 attrs
404 .entry(short_name)
405 .or_insert_with(Vec::new)
406 .push(value.trim().to_string());
407 pos = tag_end + 1 + close_pos + close.len();
408 } else {
409 pos = tag_end + 1;
410 }
411 } else {
412 break;
413 }
414 } else {
415 break;
416 }
417 }
418 }
419
420 attrs
421}
422
423fn extract_xml_value(xml: &str, tag: &str) -> Option<String> {
425 let open = format!("<{tag}");
426 let close = format!("</{tag}>");
427
428 let start_pos = xml.find(&open)?;
429 let after_open = xml[start_pos + open.len()..].find('>')?;
430 let content_start = start_pos + open.len() + after_open + 1;
431 let content_end = xml[content_start..].find(&close)?;
432
433 Some(
434 xml[content_start..content_start + content_end]
435 .trim()
436 .to_string(),
437 )
438}
439
440fn extract_xml_attr(xml: &str, tag: &str, attr_name: &str) -> Option<String> {
442 let open = format!("<{tag}");
443 let start_pos = xml.find(&open)?;
444 let tag_content_end = xml[start_pos..].find('>')?;
445 let tag_content = &xml[start_pos..start_pos + tag_content_end];
446
447 let attr_pattern = format!("{attr_name}=\"");
448 let attr_start = tag_content.find(&attr_pattern)?;
449 let value_start = attr_start + attr_pattern.len();
450 let value_end = tag_content[value_start..].find('"')?;
451
452 Some(tag_content[value_start..value_start + value_end].to_string())
453}
454
455fn extract_xml_inner(xml: &str, tag: &str) -> Option<String> {
457 let open = format!("<{tag}");
458 let close = format!("</{tag}>");
459
460 let start_pos = xml.find(&open)?;
461 let after_tag = xml[start_pos..].find('>')?;
462 let content_start = start_pos + after_tag + 1;
463 let content_end = xml[content_start..].find(&close)?;
464
465 Some(
466 xml[content_start..content_start + content_end]
467 .trim()
468 .to_string(),
469 )
470}
471
472fn extract_xml_list(xml: &str, tag: &str) -> Vec<String> {
474 let mut values = Vec::new();
475 let open = format!("<{tag}>");
476 let close = format!("</{tag}>");
477 let mut search_from = 0;
478
479 while let Some(start) = xml[search_from..].find(&open) {
480 let content_start = search_from + start + open.len();
481 if let Some(end) = xml[content_start..].find(&close) {
482 values.push(xml[content_start..content_start + end].trim().to_string());
483 search_from = content_start + end + close.len();
484 } else {
485 break;
486 }
487 }
488
489 values
490}
491
492fn find_xml_block(xml: &str, tag: &str) -> Option<String> {
494 let open = format!("<{tag}");
495 let close = format!("</{tag}>");
496
497 let start_pos = xml.find(&open)?;
498 let after_open = xml[start_pos + open.len()..].find('>')?;
499 let content_start = start_pos + open.len() + after_open + 1;
500 let content_end = xml[content_start..].find(&close)?;
501
502 Some(xml[content_start..content_start + content_end].to_string())
503}
504
505#[cfg(test)]
506mod tests {
507 use super::*;
508
509 #[test]
510 fn test_config_defaults() {
511 let config = CasConfig::default();
512 assert_eq!(config.protocol_version, CasProtocolVersion::V3);
513 assert!(!config.allow_proxy);
514 assert!(!config.renew);
515 }
516
517 #[test]
518 fn test_client_requires_https() {
519 let config = CasConfig {
520 server_url: "http://cas.example.com/cas".into(),
521 service_url: "https://app.example.com/callback".into(),
522 ..Default::default()
523 };
524 let err = CasClient::new(config).unwrap_err();
525 assert!(err.to_string().contains("HTTPS"));
526 }
527
528 #[test]
529 fn test_login_url() {
530 let config = CasConfig {
531 server_url: "https://cas.example.com/cas".into(),
532 service_url: "https://app.example.com/callback".into(),
533 ..Default::default()
534 };
535 let client = CasClient::new(config).unwrap();
536 let url = client.login_url();
537 assert!(url.starts_with("https://cas.example.com/cas/login?service="));
538 assert!(url.contains("app.example.com"));
539 }
540
541 #[test]
542 fn test_login_url_with_renew() {
543 let config = CasConfig {
544 server_url: "https://cas.example.com/cas".into(),
545 service_url: "https://app.example.com/callback".into(),
546 renew: true,
547 ..Default::default()
548 };
549 let client = CasClient::new(config).unwrap();
550 let url = client.login_url();
551 assert!(url.contains("renew=true"));
552 }
553
554 #[test]
555 fn test_logout_url() {
556 let config = CasConfig {
557 server_url: "https://cas.example.com/cas".into(),
558 service_url: "https://app.example.com/callback".into(),
559 ..Default::default()
560 };
561 let client = CasClient::new(config).unwrap();
562 let url = client.logout_url(None);
563 assert_eq!(url, "https://cas.example.com/cas/logout");
564
565 let url_with_redirect = client.logout_url(Some("https://app.example.com"));
566 assert!(url_with_redirect.contains("service="));
567 }
568
569 #[test]
570 fn test_parse_success_response() {
571 let xml = r#"
572 <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
573 <cas:authenticationSuccess>
574 <cas:user>jdoe</cas:user>
575 <cas:attributes>
576 <cas:email>jdoe@example.com</cas:email>
577 <cas:displayName>John Doe</cas:displayName>
578 </cas:attributes>
579 </cas:authenticationSuccess>
580 </cas:serviceResponse>
581 "#;
582
583 let result = parse_cas_xml_response(xml).unwrap();
584 assert!(result.valid);
585 assert_eq!(result.user.as_deref(), Some("jdoe"));
586 assert!(result.attributes.contains_key("email"));
587 }
588
589 #[test]
590 fn test_parse_failure_response() {
591 let xml = r#"
592 <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
593 <cas:authenticationFailure code="INVALID_TICKET">
594 Ticket ST-12345 not recognized
595 </cas:authenticationFailure>
596 </cas:serviceResponse>
597 "#;
598
599 let result = parse_cas_xml_response(xml).unwrap();
600 assert!(!result.valid);
601 assert!(result.user.is_none());
602 assert_eq!(result.error_code.as_deref(), Some("INVALID_TICKET"));
603 }
604
605 #[test]
606 fn test_extract_xml_value() {
607 let xml = "<root><user>alice</user></root>";
608 assert_eq!(extract_xml_value(xml, "user"), Some("alice".into()));
609 }
610
611 #[test]
612 fn test_slo_request_parsing() {
613 let body = r#"
614 <samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
615 <samlp:SessionIndex>ST-12345</samlp:SessionIndex>
616 <saml:NameID>jdoe</saml:NameID>
617 </samlp:LogoutRequest>
618 "#;
619
620 let slo = CasClient::parse_slo_request(body);
623 assert!(slo.is_ok() || slo.is_err());
625 }
626}