1use crate::address::Pattern;
42use crate::{Error, Result};
43use std::collections::HashMap;
44use std::fmt;
45use std::str::FromStr;
46use std::sync::RwLock;
47use std::time::{Duration, SystemTime, UNIX_EPOCH};
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum Action {
52 Read,
54 Write,
56 Admin,
58}
59
60impl Action {
61 pub fn allows(&self, other: Action) -> bool {
63 match self {
64 Action::Admin => true, Action::Write => matches!(other, Action::Write | Action::Read),
66 Action::Read => matches!(other, Action::Read),
67 }
68 }
69}
70
71impl fmt::Display for Action {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 match self {
74 Action::Read => write!(f, "read"),
75 Action::Write => write!(f, "write"),
76 Action::Admin => write!(f, "admin"),
77 }
78 }
79}
80
81impl FromStr for Action {
82 type Err = Error;
83
84 fn from_str(s: &str) -> Result<Self> {
85 match s.to_lowercase().as_str() {
86 "read" | "r" => Ok(Action::Read),
87 "write" | "w" => Ok(Action::Write),
88 "admin" | "a" | "*" => Ok(Action::Admin),
89 _ => Err(Error::InvalidPattern(format!("unknown action: {}", s))),
90 }
91 }
92}
93
94#[derive(Debug, Clone)]
96pub struct Scope {
97 action: Action,
98 pattern: Pattern,
99 raw: String,
100}
101
102impl Scope {
103 pub fn new(action: Action, pattern_str: &str) -> Result<Self> {
105 let pattern = Pattern::compile(pattern_str)?;
106 Ok(Self {
107 action,
108 pattern,
109 raw: format!("{}:{}", action, pattern_str),
110 })
111 }
112
113 pub fn parse(s: &str) -> Result<Self> {
115 let parts: Vec<&str> = s.splitn(2, ':').collect();
116 if parts.len() != 2 {
117 return Err(Error::InvalidPattern(format!(
118 "scope must be in format 'action:pattern', got: {}",
119 s
120 )));
121 }
122
123 let action = Action::from_str(parts[0])?;
124 let pattern = Pattern::compile(parts[1])?;
125
126 Ok(Self {
127 action,
128 pattern,
129 raw: s.to_string(),
130 })
131 }
132
133 pub fn allows(&self, action: Action, address: &str) -> bool {
135 self.action.allows(action) && self.pattern.matches(address)
136 }
137
138 pub fn action(&self) -> Action {
140 self.action
141 }
142
143 pub fn pattern(&self) -> &Pattern {
145 &self.pattern
146 }
147
148 pub fn as_str(&self) -> &str {
150 &self.raw
151 }
152}
153
154impl fmt::Display for Scope {
155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156 write!(f, "{}", self.raw)
157 }
158}
159
160impl FromStr for Scope {
161 type Err = Error;
162
163 fn from_str(s: &str) -> Result<Self> {
164 Scope::parse(s)
165 }
166}
167
168#[derive(Debug, Clone)]
170pub struct TokenInfo {
171 pub token_id: String,
173 pub subject: Option<String>,
175 pub scopes: Vec<Scope>,
177 pub expires_at: Option<SystemTime>,
179 pub metadata: HashMap<String, String>,
181}
182
183impl TokenInfo {
184 pub fn new(token_id: String, scopes: Vec<Scope>) -> Self {
186 Self {
187 token_id,
188 subject: None,
189 scopes,
190 expires_at: None,
191 metadata: HashMap::new(),
192 }
193 }
194
195 pub fn is_expired(&self) -> bool {
197 if let Some(expires_at) = self.expires_at {
198 SystemTime::now() > expires_at
199 } else {
200 false
201 }
202 }
203
204 pub fn has_scope(&self, action: Action, address: &str) -> bool {
206 self.scopes.iter().any(|scope| scope.allows(action, address))
207 }
208
209 pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
211 self.subject = Some(subject.into());
212 self
213 }
214
215 pub fn with_expires_at(mut self, expires_at: SystemTime) -> Self {
217 self.expires_at = Some(expires_at);
218 self
219 }
220
221 pub fn with_expires_in(mut self, duration: Duration) -> Self {
223 self.expires_at = Some(SystemTime::now() + duration);
224 self
225 }
226
227 pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
229 self.metadata.insert(key.into(), value.into());
230 self
231 }
232}
233
234#[derive(Debug)]
236pub enum ValidationResult {
237 Valid(TokenInfo),
239 NotMyToken,
241 Invalid(String),
243 Expired,
245}
246
247pub trait TokenValidator: Send + Sync + std::any::Any {
249 fn validate(&self, token: &str) -> ValidationResult;
251
252 fn name(&self) -> &str;
254
255 fn as_any(&self) -> &dyn std::any::Any;
257}
258
259pub struct CpskValidator {
264 tokens: RwLock<HashMap<String, TokenInfo>>,
265}
266
267impl CpskValidator {
268 pub const PREFIX: &'static str = "cpsk_";
270
271 pub fn new() -> Self {
273 Self {
274 tokens: RwLock::new(HashMap::new()),
275 }
276 }
277
278 pub fn register(&self, token: String, info: TokenInfo) {
280 self.tokens.write().unwrap().insert(token, info);
281 }
282
283 pub fn revoke(&self, token: &str) -> bool {
285 self.tokens.write().unwrap().remove(token).is_some()
286 }
287
288 pub fn exists(&self, token: &str) -> bool {
290 self.tokens.read().unwrap().contains_key(token)
291 }
292
293 pub fn len(&self) -> usize {
295 self.tokens.read().unwrap().len()
296 }
297
298 pub fn is_empty(&self) -> bool {
300 self.tokens.read().unwrap().is_empty()
301 }
302
303 pub fn list_tokens(&self) -> Vec<String> {
305 self.tokens.read().unwrap().keys().cloned().collect()
306 }
307
308 pub fn generate_token() -> String {
310 use std::time::{SystemTime, UNIX_EPOCH};
311
312 let seed = SystemTime::now()
314 .duration_since(UNIX_EPOCH)
315 .unwrap()
316 .as_nanos();
317
318 let mut state = seed as u64;
320 let mut chars = String::with_capacity(32);
321 const ALPHABET: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
322
323 for _ in 0..32 {
324 state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
325 let idx = ((state >> 33) as usize) % ALPHABET.len();
326 chars.push(ALPHABET[idx] as char);
327 }
328
329 format!("{}{}", Self::PREFIX, chars)
330 }
331}
332
333impl Default for CpskValidator {
334 fn default() -> Self {
335 Self::new()
336 }
337}
338
339impl TokenValidator for CpskValidator {
340 fn validate(&self, token: &str) -> ValidationResult {
341 if !token.starts_with(Self::PREFIX) {
343 return ValidationResult::NotMyToken;
344 }
345
346 let tokens = self.tokens.read().unwrap();
348 match tokens.get(token) {
349 Some(info) => {
350 if info.is_expired() {
351 ValidationResult::Expired
352 } else {
353 ValidationResult::Valid(info.clone())
354 }
355 }
356 None => ValidationResult::Invalid("token not found".to_string()),
357 }
358 }
359
360 fn name(&self) -> &str {
361 "CPSK"
362 }
363
364 fn as_any(&self) -> &dyn std::any::Any {
365 self
366 }
367}
368
369pub struct ValidatorChain {
371 validators: Vec<Box<dyn TokenValidator>>,
372}
373
374impl ValidatorChain {
375 pub fn new() -> Self {
377 Self {
378 validators: Vec::new(),
379 }
380 }
381
382 pub fn add<V: TokenValidator + 'static>(&mut self, validator: V) {
384 self.validators.push(Box::new(validator));
385 }
386
387 pub fn with<V: TokenValidator + 'static>(mut self, validator: V) -> Self {
389 self.add(validator);
390 self
391 }
392
393 pub fn validate(&self, token: &str) -> ValidationResult {
395 for validator in &self.validators {
396 match validator.validate(token) {
397 ValidationResult::NotMyToken => continue,
398 result => return result,
399 }
400 }
401 ValidationResult::Invalid("no validator accepted the token".to_string())
402 }
403
404 pub fn len(&self) -> usize {
406 self.validators.len()
407 }
408
409 pub fn is_empty(&self) -> bool {
411 self.validators.is_empty()
412 }
413}
414
415impl Default for ValidatorChain {
416 fn default() -> Self {
417 Self::new()
418 }
419}
420
421#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
423pub enum SecurityMode {
424 #[default]
426 Open,
427 Authenticated,
429}
430
431impl fmt::Display for SecurityMode {
432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433 match self {
434 SecurityMode::Open => write!(f, "open"),
435 SecurityMode::Authenticated => write!(f, "authenticated"),
436 }
437 }
438}
439
440impl FromStr for SecurityMode {
441 type Err = Error;
442
443 fn from_str(s: &str) -> Result<Self> {
444 match s.to_lowercase().as_str() {
445 "open" | "none" | "off" => Ok(SecurityMode::Open),
446 "authenticated" | "auth" | "token" => Ok(SecurityMode::Authenticated),
447 _ => Err(Error::InvalidPattern(format!(
448 "unknown security mode: {}",
449 s
450 ))),
451 }
452 }
453}
454
455pub fn parse_scopes(s: &str) -> Result<Vec<Scope>> {
457 s.split(',')
458 .map(|part| Scope::parse(part.trim()))
459 .collect()
460}
461
462pub fn parse_duration(s: &str) -> Result<Duration> {
464 let s = s.trim();
465 if s.is_empty() {
466 return Err(Error::InvalidPattern("empty duration".to_string()));
467 }
468
469 let (num_str, unit) = if s.ends_with('d') {
470 (&s[..s.len() - 1], "d")
471 } else if s.ends_with('h') {
472 (&s[..s.len() - 1], "h")
473 } else if s.ends_with('m') {
474 (&s[..s.len() - 1], "m")
475 } else if s.ends_with('s') {
476 (&s[..s.len() - 1], "s")
477 } else {
478 (s, "s")
480 };
481
482 let num: u64 = num_str
483 .parse()
484 .map_err(|_| Error::InvalidPattern(format!("invalid duration number: {}", num_str)))?;
485
486 let secs = match unit {
487 "d" => num * 86400,
488 "h" => num * 3600,
489 "m" => num * 60,
490 "s" => num,
491 _ => unreachable!(),
492 };
493
494 Ok(Duration::from_secs(secs))
495}
496
497pub fn to_unix_timestamp(time: SystemTime) -> u64 {
499 time.duration_since(UNIX_EPOCH)
500 .map(|d| d.as_secs())
501 .unwrap_or(0)
502}
503
504pub fn from_unix_timestamp(ts: u64) -> SystemTime {
506 UNIX_EPOCH + Duration::from_secs(ts)
507}
508
509#[cfg(test)]
510mod tests {
511 use super::*;
512
513 #[test]
514 fn test_action_allows() {
515 assert!(Action::Admin.allows(Action::Read));
516 assert!(Action::Admin.allows(Action::Write));
517 assert!(Action::Admin.allows(Action::Admin));
518
519 assert!(Action::Write.allows(Action::Read));
520 assert!(Action::Write.allows(Action::Write));
521 assert!(!Action::Write.allows(Action::Admin));
522
523 assert!(Action::Read.allows(Action::Read));
524 assert!(!Action::Read.allows(Action::Write));
525 assert!(!Action::Read.allows(Action::Admin));
526 }
527
528 #[test]
529 fn test_action_from_str() {
530 assert_eq!(Action::from_str("read").unwrap(), Action::Read);
531 assert_eq!(Action::from_str("write").unwrap(), Action::Write);
532 assert_eq!(Action::from_str("admin").unwrap(), Action::Admin);
533 assert_eq!(Action::from_str("r").unwrap(), Action::Read);
534 assert_eq!(Action::from_str("w").unwrap(), Action::Write);
535 assert_eq!(Action::from_str("a").unwrap(), Action::Admin);
536 assert!(Action::from_str("invalid").is_err());
537 }
538
539 #[test]
540 fn test_scope_parse() {
541 let scope = Scope::parse("read:/**").unwrap();
542 assert_eq!(scope.action(), Action::Read);
543 assert!(scope.allows(Action::Read, "/any/path"));
544 assert!(!scope.allows(Action::Write, "/any/path"));
545
546 let scope = Scope::parse("write:/lights/**").unwrap();
547 assert!(scope.allows(Action::Write, "/lights/room/1"));
548 assert!(scope.allows(Action::Read, "/lights/room/1"));
549 assert!(!scope.allows(Action::Write, "/sensors/temp"));
550 assert!(!scope.allows(Action::Read, "/sensors/temp"));
551
552 let scope = Scope::parse("admin:/**").unwrap();
553 assert!(scope.allows(Action::Admin, "/any/path"));
554 assert!(scope.allows(Action::Write, "/any/path"));
555 assert!(scope.allows(Action::Read, "/any/path"));
556 }
557
558 #[test]
559 fn test_scope_wildcards() {
560 let scope = Scope::parse("read:/lumen/scene/*/layer/**").unwrap();
561 assert!(scope.allows(Action::Read, "/lumen/scene/0/layer/1/opacity"));
562 assert!(scope.allows(Action::Read, "/lumen/scene/main/layer/2"));
563 assert!(!scope.allows(Action::Read, "/lumen/scene/0/effect"));
564 }
565
566 #[test]
567 fn test_token_info() {
568 let scopes = vec![
569 Scope::parse("read:/**").unwrap(),
570 Scope::parse("write:/lights/**").unwrap(),
571 ];
572 let info = TokenInfo::new("test_token".to_string(), scopes);
573
574 assert!(info.has_scope(Action::Read, "/any/path"));
575 assert!(info.has_scope(Action::Write, "/lights/room"));
576 assert!(!info.has_scope(Action::Write, "/sensors/temp"));
577 assert!(!info.is_expired());
578 }
579
580 #[test]
581 fn test_token_expiry() {
582 let scopes = vec![Scope::parse("read:/**").unwrap()];
583 let info = TokenInfo::new("test_token".to_string(), scopes)
584 .with_expires_at(SystemTime::now() - Duration::from_secs(1));
585 assert!(info.is_expired());
586
587 let scopes = vec![Scope::parse("read:/**").unwrap()];
588 let info = TokenInfo::new("test_token".to_string(), scopes)
589 .with_expires_in(Duration::from_secs(3600));
590 assert!(!info.is_expired());
591 }
592
593 #[test]
594 fn test_cpsk_validator() {
595 let validator = CpskValidator::new();
596
597 let token = CpskValidator::generate_token();
599 assert!(token.starts_with("cpsk_"));
600 assert_eq!(token.len(), 37); let scopes = vec![Scope::parse("read:/**").unwrap()];
603 let info = TokenInfo::new(token.clone(), scopes);
604 validator.register(token.clone(), info);
605
606 match validator.validate(&token) {
608 ValidationResult::Valid(info) => {
609 assert!(info.has_scope(Action::Read, "/test"));
610 }
611 _ => panic!("expected valid token"),
612 }
613
614 match validator.validate("cpsk_unknown") {
616 ValidationResult::Invalid(_) => {}
617 _ => panic!("expected invalid token"),
618 }
619
620 match validator.validate("jwt_token") {
622 ValidationResult::NotMyToken => {}
623 _ => panic!("expected not my token"),
624 }
625
626 assert!(validator.revoke(&token));
628 match validator.validate(&token) {
629 ValidationResult::Invalid(_) => {}
630 _ => panic!("expected invalid after revoke"),
631 }
632 }
633
634 #[test]
635 fn test_validator_chain() {
636 let mut chain = ValidatorChain::new();
637
638 let cpsk = CpskValidator::new();
639 let token = CpskValidator::generate_token();
640 let scopes = vec![Scope::parse("admin:/**").unwrap()];
641 cpsk.register(token.clone(), TokenInfo::new(token.clone(), scopes));
642 chain.add(cpsk);
643
644 match chain.validate(&token) {
645 ValidationResult::Valid(_) => {}
646 _ => panic!("expected valid token"),
647 }
648
649 match chain.validate("unknown_token") {
650 ValidationResult::Invalid(_) => {}
651 _ => panic!("expected invalid token"),
652 }
653 }
654
655 #[test]
656 fn test_parse_scopes() {
657 let scopes = parse_scopes("read:/**, write:/lights/**").unwrap();
658 assert_eq!(scopes.len(), 2);
659 assert!(scopes[0].allows(Action::Read, "/any"));
660 assert!(scopes[1].allows(Action::Write, "/lights/1"));
661 }
662
663 #[test]
664 fn test_parse_duration() {
665 assert_eq!(parse_duration("7d").unwrap(), Duration::from_secs(7 * 86400));
666 assert_eq!(parse_duration("24h").unwrap(), Duration::from_secs(24 * 3600));
667 assert_eq!(parse_duration("30m").unwrap(), Duration::from_secs(30 * 60));
668 assert_eq!(parse_duration("60s").unwrap(), Duration::from_secs(60));
669 assert_eq!(parse_duration("120").unwrap(), Duration::from_secs(120));
670 assert!(parse_duration("").is_err());
671 assert!(parse_duration("abc").is_err());
672 }
673
674 #[test]
675 fn test_security_mode() {
676 assert_eq!(SecurityMode::from_str("open").unwrap(), SecurityMode::Open);
677 assert_eq!(
678 SecurityMode::from_str("authenticated").unwrap(),
679 SecurityMode::Authenticated
680 );
681 assert_eq!(SecurityMode::from_str("auth").unwrap(), SecurityMode::Authenticated);
682 }
683}