rustant_core/gateway/
auth.rs1use super::GatewayConfig;
4
5#[derive(Debug, Clone)]
7pub struct GatewayAuth {
8 valid_tokens: Vec<String>,
9}
10
11impl GatewayAuth {
12 pub fn from_config(config: &GatewayConfig) -> Self {
14 Self {
15 valid_tokens: config.auth_tokens.clone(),
16 }
17 }
18
19 pub fn new(tokens: Vec<String>) -> Self {
21 Self {
22 valid_tokens: tokens,
23 }
24 }
25
26 pub fn validate(&self, token: &str) -> bool {
30 if self.valid_tokens.is_empty() {
31 return true; }
33 self.valid_tokens.iter().any(|t| t == token)
34 }
35
36 pub fn token_count(&self) -> usize {
38 self.valid_tokens.len()
39 }
40
41 pub fn is_open_mode(&self) -> bool {
43 self.valid_tokens.is_empty()
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn test_auth_validate_valid_token() {
53 let auth = GatewayAuth::new(vec!["token-1".into(), "token-2".into()]);
54 assert!(auth.validate("token-1"));
55 assert!(auth.validate("token-2"));
56 }
57
58 #[test]
59 fn test_auth_validate_invalid_token() {
60 let auth = GatewayAuth::new(vec!["token-1".into()]);
61 assert!(!auth.validate("wrong-token"));
62 assert!(!auth.validate(""));
63 }
64
65 #[test]
66 fn test_auth_open_mode() {
67 let auth = GatewayAuth::new(vec![]);
68 assert!(auth.is_open_mode());
69 assert!(auth.validate("anything"));
70 assert!(auth.validate(""));
71 }
72
73 #[test]
74 fn test_auth_from_config() {
75 let config = GatewayConfig {
76 auth_tokens: vec!["abc".into(), "def".into()],
77 ..GatewayConfig::default()
78 };
79 let auth = GatewayAuth::from_config(&config);
80 assert_eq!(auth.token_count(), 2);
81 assert!(auth.validate("abc"));
82 assert!(!auth.validate("xyz"));
83 }
84}