clasp_core/
security.rs

1//! Security primitives for CLASP authentication and authorization
2//!
3//! This module provides a hybrid token system that works across all platforms,
4//! including embedded devices with limited resources.
5//!
6//! # Token Types
7//!
8//! ## Capability Pre-Shared Keys (CPSK) - Default
9//! ```text
10//! Format: cpsk_<base62-random-32-chars>
11//! Example: cpsk_7kX9mP2nQ4rT6vW8xZ0aB3cD5eF1gH
12//! ```
13//! Simple lookup-based validation, works on any device.
14//!
15//! ## External Tokens (PASETO/JWT) - Optional
16//! ```text
17//! Format: ext_<paseto-or-jwt-token>
18//! ```
19//! Cryptographic validation for federated identity providers.
20//!
21//! # Scope Format
22//! ```text
23//! action:pattern
24//!
25//! Actions:
26//!   read   - SUBSCRIBE, GET
27//!   write  - SET, PUBLISH
28//!   admin  - Full access
29//!
30//! Patterns:
31//!   /path/to/addr   - Exact match
32//!   /path/*         - Single segment wildcard
33//!   /path/**        - Multi-segment wildcard
34//!
35//! Examples:
36//!   read:/**                 - Read everything
37//!   write:/lights/**         - Control lights namespace
38//!   admin:/**                - Full access
39//! ```
40
41use 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/// Actions that can be performed on addresses
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum Action {
52    /// Read operations: SUBSCRIBE, GET
53    Read,
54    /// Write operations: SET, PUBLISH
55    Write,
56    /// Full access: all operations
57    Admin,
58}
59
60impl Action {
61    /// Check if this action allows the given operation
62    pub fn allows(&self, other: Action) -> bool {
63        match self {
64            Action::Admin => true, // Admin allows everything
65            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/// A scope defines what actions are allowed on which address patterns
95#[derive(Debug, Clone)]
96pub struct Scope {
97    action: Action,
98    pattern: Pattern,
99    raw: String,
100}
101
102impl Scope {
103    /// Create a new scope from an action and pattern string
104    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    /// Parse a scope from string format "action:pattern"
114    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    /// Check if this scope allows the given action on the given address
134    pub fn allows(&self, action: Action, address: &str) -> bool {
135        self.action.allows(action) && self.pattern.matches(address)
136    }
137
138    /// Get the action for this scope
139    pub fn action(&self) -> Action {
140        self.action
141    }
142
143    /// Get the pattern for this scope
144    pub fn pattern(&self) -> &Pattern {
145        &self.pattern
146    }
147
148    /// Get the raw scope string
149    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/// Information about a validated token
169#[derive(Debug, Clone)]
170pub struct TokenInfo {
171    /// Token identifier (the token itself for CPSK, or extracted ID for JWT/PASETO)
172    pub token_id: String,
173    /// Subject identifier (user, device, or service)
174    pub subject: Option<String>,
175    /// Scopes granted by this token
176    pub scopes: Vec<Scope>,
177    /// When the token expires (if any)
178    pub expires_at: Option<SystemTime>,
179    /// Additional metadata
180    pub metadata: HashMap<String, String>,
181}
182
183impl TokenInfo {
184    /// Create a new TokenInfo with minimal fields
185    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    /// Check if this token is expired
196    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    /// Check if the token allows the given action on the given address
205    pub fn has_scope(&self, action: Action, address: &str) -> bool {
206        self.scopes.iter().any(|scope| scope.allows(action, address))
207    }
208
209    /// Set the subject
210    pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
211        self.subject = Some(subject.into());
212        self
213    }
214
215    /// Set the expiration time
216    pub fn with_expires_at(mut self, expires_at: SystemTime) -> Self {
217        self.expires_at = Some(expires_at);
218        self
219    }
220
221    /// Set the expiration from a duration
222    pub fn with_expires_in(mut self, duration: Duration) -> Self {
223        self.expires_at = Some(SystemTime::now() + duration);
224        self
225    }
226
227    /// Add metadata
228    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/// Result of token validation
235#[derive(Debug)]
236pub enum ValidationResult {
237    /// Token is valid
238    Valid(TokenInfo),
239    /// Token format not recognized by this validator
240    NotMyToken,
241    /// Token is invalid (wrong signature, malformed, etc.)
242    Invalid(String),
243    /// Token has expired
244    Expired,
245}
246
247/// Trait for token validators
248pub trait TokenValidator: Send + Sync + std::any::Any {
249    /// Validate a token and return token information if valid
250    fn validate(&self, token: &str) -> ValidationResult;
251
252    /// Get the name of this validator (for logging)
253    fn name(&self) -> &str;
254
255    /// Returns self as Any for downcasting
256    fn as_any(&self) -> &dyn std::any::Any;
257}
258
259/// Capability Pre-Shared Key (CPSK) validator
260///
261/// Stores tokens in memory with their associated scopes.
262/// Tokens have the format: `cpsk_<base62-random-32-chars>`
263pub struct CpskValidator {
264    tokens: RwLock<HashMap<String, TokenInfo>>,
265}
266
267impl CpskValidator {
268    /// Token prefix for CPSK tokens
269    pub const PREFIX: &'static str = "cpsk_";
270
271    /// Create a new empty CPSK validator
272    pub fn new() -> Self {
273        Self {
274            tokens: RwLock::new(HashMap::new()),
275        }
276    }
277
278    /// Register a token with the given scopes
279    pub fn register(&self, token: String, info: TokenInfo) {
280        self.tokens.write().unwrap().insert(token, info);
281    }
282
283    /// Revoke a token
284    pub fn revoke(&self, token: &str) -> bool {
285        self.tokens.write().unwrap().remove(token).is_some()
286    }
287
288    /// Check if a token exists (without full validation)
289    pub fn exists(&self, token: &str) -> bool {
290        self.tokens.read().unwrap().contains_key(token)
291    }
292
293    /// Get the number of registered tokens
294    pub fn len(&self) -> usize {
295        self.tokens.read().unwrap().len()
296    }
297
298    /// Check if the validator has no tokens
299    pub fn is_empty(&self) -> bool {
300        self.tokens.read().unwrap().is_empty()
301    }
302
303    /// List all token IDs (for admin purposes)
304    pub fn list_tokens(&self) -> Vec<String> {
305        self.tokens.read().unwrap().keys().cloned().collect()
306    }
307
308    /// Generate a new CPSK token string
309    pub fn generate_token() -> String {
310        use std::time::{SystemTime, UNIX_EPOCH};
311
312        // Use time-based seed for randomness
313        let seed = SystemTime::now()
314            .duration_since(UNIX_EPOCH)
315            .unwrap()
316            .as_nanos();
317
318        // Simple LCG-based random generator
319        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        // Check prefix
342        if !token.starts_with(Self::PREFIX) {
343            return ValidationResult::NotMyToken;
344        }
345
346        // Look up token
347        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
369/// A chain of validators that tries each one in order
370pub struct ValidatorChain {
371    validators: Vec<Box<dyn TokenValidator>>,
372}
373
374impl ValidatorChain {
375    /// Create a new empty validator chain
376    pub fn new() -> Self {
377        Self {
378            validators: Vec::new(),
379        }
380    }
381
382    /// Add a validator to the chain
383    pub fn add<V: TokenValidator + 'static>(&mut self, validator: V) {
384        self.validators.push(Box::new(validator));
385    }
386
387    /// Add a validator and return self for chaining
388    pub fn with<V: TokenValidator + 'static>(mut self, validator: V) -> Self {
389        self.add(validator);
390        self
391    }
392
393    /// Validate a token using all validators in order
394    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    /// Get the number of validators
405    pub fn len(&self) -> usize {
406        self.validators.len()
407    }
408
409    /// Check if chain is empty
410    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/// Security mode for the router
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
423pub enum SecurityMode {
424    /// No authentication required (default for local development)
425    #[default]
426    Open,
427    /// Token authentication required
428    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
455/// Parse multiple scopes from a comma-separated string
456pub fn parse_scopes(s: &str) -> Result<Vec<Scope>> {
457    s.split(',')
458        .map(|part| Scope::parse(part.trim()))
459        .collect()
460}
461
462/// Parse a duration string like "7d", "24h", "30m", "60s"
463pub 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        // Default to seconds
479        (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
497/// Format a SystemTime as a Unix timestamp
498pub 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
504/// Parse a Unix timestamp to SystemTime
505pub 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        // Generate and register a token
598        let token = CpskValidator::generate_token();
599        assert!(token.starts_with("cpsk_"));
600        assert_eq!(token.len(), 37); // "cpsk_" + 32 chars
601
602        let scopes = vec![Scope::parse("read:/**").unwrap()];
603        let info = TokenInfo::new(token.clone(), scopes);
604        validator.register(token.clone(), info);
605
606        // Validate
607        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        // Unknown token
615        match validator.validate("cpsk_unknown") {
616            ValidationResult::Invalid(_) => {}
617            _ => panic!("expected invalid token"),
618        }
619
620        // Wrong prefix
621        match validator.validate("jwt_token") {
622            ValidationResult::NotMyToken => {}
623            _ => panic!("expected not my token"),
624        }
625
626        // Revoke
627        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}