Skip to main content

allsource_core/infrastructure/security/
auth.rs

1use crate::{
2    error::{AllSourceError, Result},
3    infrastructure::hash_state::{FastDashMap, fast_dashmap},
4};
5use argon2::{
6    Argon2,
7    password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
8};
9use chrono::{Duration, Utc};
10use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
11use serde::{Deserialize, Serialize};
12use std::sync::Arc;
13use uuid::Uuid;
14
15/// User role for RBAC
16#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
17#[serde(rename_all = "lowercase")]
18pub enum Role {
19    Admin,          // Full system access
20    Developer,      // Read/write events, manage schemas
21    ReadOnly,       // Read-only access to events
22    ServiceAccount, // Programmatic access for services
23}
24
25impl Role {
26    /// Check if role has specific permission
27    pub fn has_permission(&self, permission: Permission) -> bool {
28        match self {
29            Role::Admin => true, // Admin has all permissions
30            Role::Developer => matches!(
31                permission,
32                Permission::Read
33                    | Permission::Write
34                    | Permission::Metrics
35                    | Permission::ManageSchemas
36                    | Permission::ManagePipelines
37            ),
38            Role::ReadOnly => matches!(permission, Permission::Read | Permission::Metrics),
39            Role::ServiceAccount => {
40                matches!(permission, Permission::Read | Permission::Write)
41            }
42        }
43    }
44
45    /// Canonical role preset for MCP tokens issued to Pro-tier subscribers.
46    /// Pro unlocks MCP server access at a read-only scope — consumers can
47    /// query events, sample streams, and read metrics, but cannot mutate
48    /// state. Call this from the API-key provisioning path when a Pro
49    /// tenant requests an MCP key so the mapping stays centralized here
50    /// rather than hardcoded at call sites.
51    pub fn mcp_readonly_preset() -> Self {
52        Role::ReadOnly
53    }
54}
55
56/// Permission types
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Permission {
59    Read,
60    Write,
61    Admin,
62    Metrics,
63    ManageSchemas,
64    ManagePipelines,
65    ManageTenants,
66}
67
68/// JWT Claims
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct Claims {
71    /// Subject (user ID or API key ID)
72    pub sub: String,
73    /// Tenant ID
74    pub tenant_id: String,
75    /// User role
76    pub role: Role,
77    /// Expiration time (UNIX timestamp)
78    pub exp: i64,
79    /// Issued at time (UNIX timestamp)
80    pub iat: i64,
81    /// Issuer
82    pub iss: String,
83}
84
85impl Claims {
86    /// Create new claims for a user
87    pub fn new(user_id: String, tenant_id: String, role: Role, expires_in: Duration) -> Self {
88        let now = Utc::now();
89        Self {
90            sub: user_id,
91            tenant_id,
92            role,
93            iat: now.timestamp(),
94            exp: (now + expires_in).timestamp(),
95            iss: "allsource".to_string(),
96        }
97    }
98
99    /// Check if claims are expired
100    pub fn is_expired(&self) -> bool {
101        Utc::now().timestamp() > self.exp
102    }
103
104    /// Check if user has permission
105    pub fn has_permission(&self, permission: Permission) -> bool {
106        self.role.has_permission(permission)
107    }
108}
109
110/// User account
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct User {
113    pub id: Uuid,
114    pub username: String,
115    pub email: String,
116    #[serde(skip_serializing)]
117    pub password_hash: String,
118    pub role: Role,
119    pub tenant_id: String,
120    pub created_at: chrono::DateTime<Utc>,
121    pub active: bool,
122}
123
124impl User {
125    /// Create a new user with hashed password
126    pub fn new(
127        username: String,
128        email: String,
129        password: &str,
130        role: Role,
131        tenant_id: String,
132    ) -> Result<Self> {
133        let password_hash = hash_password(password)?;
134
135        Ok(Self {
136            id: Uuid::new_v4(),
137            username,
138            email,
139            password_hash,
140            role,
141            tenant_id,
142            created_at: Utc::now(),
143            active: true,
144        })
145    }
146
147    /// Verify password
148    pub fn verify_password(&self, password: &str) -> Result<bool> {
149        verify_password(password, &self.password_hash)
150    }
151}
152
153/// API Key for programmatic access
154#[derive(Debug, Clone, Serialize, Deserialize)]
155pub struct ApiKey {
156    pub id: Uuid,
157    pub name: String,
158    pub tenant_id: String,
159    pub role: Role,
160    #[serde(skip_serializing)]
161    pub key_hash: String,
162    pub created_at: chrono::DateTime<Utc>,
163    pub expires_at: Option<chrono::DateTime<Utc>>,
164    pub active: bool,
165    pub last_used: Option<chrono::DateTime<Utc>>,
166}
167
168impl ApiKey {
169    /// Create new API key
170    pub fn new(
171        name: String,
172        tenant_id: String,
173        role: Role,
174        expires_at: Option<chrono::DateTime<Utc>>,
175    ) -> (Self, String) {
176        let key = generate_api_key();
177        let key_hash = hash_api_key(&key);
178
179        let api_key = Self {
180            id: Uuid::new_v4(),
181            name,
182            tenant_id,
183            role,
184            key_hash,
185            created_at: Utc::now(),
186            expires_at,
187            active: true,
188            last_used: None,
189        };
190
191        (api_key, key)
192    }
193
194    /// Verify API key
195    pub fn verify(&self, key: &str) -> bool {
196        if !self.active {
197            return false;
198        }
199
200        if let Some(expires_at) = self.expires_at
201            && Utc::now() > expires_at
202        {
203            return false;
204        }
205
206        hash_api_key(key) == self.key_hash
207    }
208
209    /// Check if expired
210    pub fn is_expired(&self) -> bool {
211        if let Some(expires_at) = self.expires_at {
212            Utc::now() > expires_at
213        } else {
214            false
215        }
216    }
217}
218
219/// Authentication manager
220pub struct AuthManager {
221    /// JWT encoding key
222    encoding_key: EncodingKey,
223    /// JWT decoding key
224    decoding_key: DecodingKey,
225    /// JWT validation rules
226    validation: Validation,
227    /// Users storage (in production, use database)
228    users: Arc<FastDashMap<Uuid, User>>,
229    /// API keys storage (in production, use database)
230    api_keys: Arc<FastDashMap<Uuid, ApiKey>>,
231    /// Username to user ID mapping
232    username_index: Arc<FastDashMap<String, Uuid>>,
233    /// Optional event-sourced auth repository for durable key storage.
234    /// When set, API key operations are persisted to the system WAL.
235    auth_repo: Option<Arc<crate::infrastructure::repositories::EventSourcedAuthRepository>>,
236}
237
238impl AuthManager {
239    /// Create new authentication manager
240    pub fn new(jwt_secret: &str) -> Self {
241        let encoding_key = EncodingKey::from_secret(jwt_secret.as_bytes());
242        let decoding_key = DecodingKey::from_secret(jwt_secret.as_bytes());
243
244        let mut validation = Validation::new(Algorithm::HS256);
245        validation.set_issuer(&["allsource"]);
246
247        Self {
248            encoding_key,
249            decoding_key,
250            validation,
251            users: Arc::new(fast_dashmap()),
252            api_keys: Arc::new(fast_dashmap()),
253            username_index: Arc::new(fast_dashmap()),
254            auth_repo: None,
255        }
256    }
257
258    /// Attach an event-sourced auth repository for durable API key storage.
259    ///
260    /// Loads all previously persisted keys into the in-memory cache.
261    /// Subsequent `create_api_key` and `revoke_api_key` calls will also
262    /// write events to the system WAL.
263    pub fn with_auth_repository(
264        mut self,
265        repo: Arc<crate::infrastructure::repositories::EventSourcedAuthRepository>,
266    ) -> Self {
267        // Load persisted keys into the in-memory DashMap
268        for key in repo.all_keys() {
269            self.api_keys.insert(key.id, key);
270        }
271        let loaded = self.api_keys.len();
272        if loaded > 0 {
273            tracing::info!("Loaded {} API keys from durable storage", loaded);
274        }
275        self.auth_repo = Some(repo);
276        self
277    }
278
279    /// Register a new user
280    pub fn register_user(
281        &self,
282        username: String,
283        email: String,
284        password: &str,
285        role: Role,
286        tenant_id: String,
287    ) -> Result<User> {
288        // Check if username already exists
289        if self.username_index.contains_key(&username) {
290            return Err(AllSourceError::ValidationError(
291                "Username already exists".to_string(),
292            ));
293        }
294
295        let user = User::new(username.clone(), email, password, role, tenant_id)?;
296
297        self.users.insert(user.id, user.clone());
298        self.username_index.insert(username, user.id);
299
300        Ok(user)
301    }
302
303    /// Authenticate user with username and password
304    pub fn authenticate(&self, username: &str, password: &str) -> Result<String> {
305        let user_id = self
306            .username_index
307            .get(username)
308            .ok_or_else(|| AllSourceError::ValidationError("Invalid credentials".to_string()))?;
309
310        let user = self
311            .users
312            .get(&user_id)
313            .ok_or_else(|| AllSourceError::ValidationError("User not found".to_string()))?;
314
315        if !user.active {
316            return Err(AllSourceError::ValidationError(
317                "User account is inactive".to_string(),
318            ));
319        }
320
321        if !user.verify_password(password)? {
322            return Err(AllSourceError::ValidationError(
323                "Invalid credentials".to_string(),
324            ));
325        }
326
327        // Generate JWT token
328        let claims = Claims::new(
329            user.id.to_string(),
330            user.tenant_id.clone(),
331            user.role.clone(),
332            Duration::hours(24), // Token expires in 24 hours
333        );
334
335        let token = encode(&Header::default(), &claims, &self.encoding_key)
336            .map_err(|e| AllSourceError::ValidationError(format!("Failed to create token: {e}")))?;
337
338        Ok(token)
339    }
340
341    /// Validate JWT token
342    pub fn validate_token(&self, token: &str) -> Result<Claims> {
343        let token_data = decode::<Claims>(token, &self.decoding_key, &self.validation)
344            .map_err(|e| AllSourceError::ValidationError(format!("Invalid token: {e}")))?;
345
346        if token_data.claims.is_expired() {
347            return Err(AllSourceError::ValidationError("Token expired".to_string()));
348        }
349
350        Ok(token_data.claims)
351    }
352
353    /// Create API key
354    ///
355    /// When an auth repository is attached, the key is persisted to the
356    /// system WAL and survives restarts.
357    pub fn create_api_key(
358        &self,
359        name: String,
360        tenant_id: String,
361        role: Role,
362        expires_at: Option<chrono::DateTime<Utc>>,
363    ) -> (ApiKey, String) {
364        let (api_key, key) = ApiKey::new(name, tenant_id, role, expires_at);
365        self.api_keys.insert(api_key.id, api_key.clone());
366
367        // Persist to durable storage if available
368        if let Some(ref repo) = self.auth_repo
369            && let Err(e) = repo.persist_api_key(&api_key)
370        {
371            tracing::error!("Failed to persist API key to system store: {e}");
372        }
373
374        (api_key, key)
375    }
376
377    /// Validate API key
378    pub fn validate_api_key(&self, key: &str) -> Result<Claims> {
379        // First, find the matching key and extract the data we need
380        // We must complete iteration before calling get_mut to avoid deadlock
381        let found_key = self.api_keys.iter().find_map(|entry| {
382            let api_key = entry.value();
383            if api_key.verify(key) {
384                Some((api_key.id, api_key.tenant_id.clone(), api_key.role.clone()))
385            } else {
386                None
387            }
388        });
389
390        if let Some((key_id, tenant_id, role)) = found_key {
391            // Now safe to acquire write lock since iteration is complete
392            if let Some(mut key_mut) = self.api_keys.get_mut(&key_id) {
393                key_mut.last_used = Some(Utc::now());
394            }
395
396            let claims = Claims::new(key_id.to_string(), tenant_id, role, Duration::hours(24));
397
398            return Ok(claims);
399        }
400
401        Err(AllSourceError::ValidationError(
402            "Invalid API key".to_string(),
403        ))
404    }
405
406    /// Get user by ID
407    pub fn get_user(&self, user_id: &Uuid) -> Option<User> {
408        self.users.get(user_id).map(|u| u.clone())
409    }
410
411    /// List all users (admin only)
412    pub fn list_users(&self) -> Vec<User> {
413        self.users
414            .iter()
415            .map(|entry| entry.value().clone())
416            .collect()
417    }
418
419    /// Delete user
420    pub fn delete_user(&self, user_id: &Uuid) -> Result<()> {
421        if let Some((_, user)) = self.users.remove(user_id) {
422            self.username_index.remove(&user.username);
423            Ok(())
424        } else {
425            Err(AllSourceError::ValidationError(
426                "User not found".to_string(),
427            ))
428        }
429    }
430
431    /// Revoke API key
432    ///
433    /// When an auth repository is attached, the revocation is persisted
434    /// to the system WAL and survives restarts.
435    pub fn revoke_api_key(&self, key_id: &Uuid) -> Result<()> {
436        if let Some(mut api_key) = self.api_keys.get_mut(key_id) {
437            api_key.active = false;
438
439            // Persist revocation to durable storage
440            if let Some(ref repo) = self.auth_repo
441                && let Err(e) = repo.persist_key_revocation(key_id)
442            {
443                tracing::error!("Failed to persist key revocation to system store: {e}");
444            }
445
446            Ok(())
447        } else {
448            Err(AllSourceError::ValidationError(
449                "API key not found".to_string(),
450            ))
451        }
452    }
453
454    /// List API keys for a tenant
455    pub fn list_api_keys(&self, tenant_id: &str) -> Vec<ApiKey> {
456        self.api_keys
457            .iter()
458            .filter(|entry| entry.value().tenant_id == tenant_id)
459            .map(|entry| entry.value().clone())
460            .collect()
461    }
462
463    /// Register a bootstrap API key with a specific key value.
464    ///
465    /// This is used on startup to create a pre-configured API key from
466    /// the `ALLSOURCE_BOOTSTRAP_API_KEY` environment variable.
467    ///
468    /// If an auth repository is attached, the key is persisted to the
469    /// system WAL. On subsequent restarts, the key is loaded from storage
470    /// automatically — the bootstrap only creates the key if it doesn't
471    /// already exist (idempotent).
472    pub fn register_bootstrap_api_key(&self, key: &str, tenant_id: &str) -> ApiKey {
473        let key_hash = hash_api_key(key);
474
475        // Check if this exact key already exists (idempotent bootstrap)
476        let existing = self.api_keys.iter().find_map(|entry| {
477            if entry.value().key_hash == key_hash && entry.value().active {
478                Some(entry.value().clone())
479            } else {
480                None
481            }
482        });
483
484        if let Some(existing_key) = existing {
485            tracing::debug!("Bootstrap API key already exists (idempotent)");
486            return existing_key;
487        }
488
489        let api_key = ApiKey {
490            id: Uuid::new_v4(),
491            name: "bootstrap".to_string(),
492            tenant_id: tenant_id.to_string(),
493            role: Role::Admin,
494            key_hash,
495            created_at: Utc::now(),
496            expires_at: None,
497            active: true,
498            last_used: None,
499        };
500
501        self.api_keys.insert(api_key.id, api_key.clone());
502
503        // Persist to durable storage if available
504        if let Some(ref repo) = self.auth_repo
505            && let Err(e) = repo.persist_api_key(&api_key)
506        {
507            tracing::error!("Failed to persist bootstrap API key: {e}");
508        }
509
510        api_key
511    }
512}
513
514impl Default for AuthManager {
515    fn default() -> Self {
516        use base64::{Engine as _, engine::general_purpose};
517        let secret = general_purpose::STANDARD.encode(rand::random::<[u8; 32]>());
518        Self::new(&secret)
519    }
520}
521
522/// Hash password using Argon2
523fn hash_password(password: &str) -> Result<String> {
524    let argon2 = Argon2::default();
525
526    let hash: PasswordHash = argon2
527        .hash_password(password.as_bytes())
528        .map_err(|e| AllSourceError::ValidationError(format!("Password hashing failed: {e}")))?;
529
530    Ok(hash.to_string())
531}
532
533/// Verify password against hash
534fn verify_password(password: &str, hash: &str) -> Result<bool> {
535    let parsed_hash = PasswordHash::new(hash)
536        .map_err(|e| AllSourceError::ValidationError(format!("Invalid password hash: {e}")))?;
537
538    let argon2 = Argon2::default();
539    Ok(argon2
540        .verify_password(password.as_bytes(), &parsed_hash)
541        .is_ok())
542}
543
544/// Generate API key
545fn generate_api_key() -> String {
546    use base64::{Engine as _, engine::general_purpose};
547    let random_bytes: [u8; 32] = rand::random();
548    format!(
549        "ask_{}",
550        general_purpose::URL_SAFE_NO_PAD.encode(random_bytes)
551    )
552}
553
554/// Hash API key for storage
555fn hash_api_key(key: &str) -> String {
556    use std::{
557        collections::hash_map::DefaultHasher,
558        hash::{Hash, Hasher},
559    };
560
561    let mut hasher = DefaultHasher::new();
562    key.hash(&mut hasher);
563    format!("{:x}", hasher.finish())
564}
565
566#[cfg(test)]
567mod tests {
568    use super::*;
569
570    #[test]
571    fn test_user_creation_and_verification() {
572        let user = User::new(
573            "testuser".to_string(),
574            "test@example.com".to_string(),
575            "password123",
576            Role::Developer,
577            "tenant1".to_string(),
578        )
579        .unwrap();
580
581        assert!(user.verify_password("password123").unwrap());
582        assert!(!user.verify_password("wrongpassword").unwrap());
583    }
584
585    #[test]
586    fn test_role_permissions() {
587        assert!(Role::Admin.has_permission(Permission::Admin));
588        assert!(Role::Developer.has_permission(Permission::Write));
589        assert!(!Role::ReadOnly.has_permission(Permission::Write));
590        assert!(Role::ReadOnly.has_permission(Permission::Read));
591    }
592
593    #[test]
594    fn test_auth_manager() {
595        let auth = AuthManager::new("test_secret");
596
597        // Register user
598        let user = auth
599            .register_user(
600                "alice".to_string(),
601                "alice@example.com".to_string(),
602                "password123",
603                Role::Developer,
604                "tenant1".to_string(),
605            )
606            .unwrap();
607
608        // Authenticate
609        let token = auth.authenticate("alice", "password123").unwrap();
610        assert!(!token.is_empty());
611
612        // Validate token
613        let claims = auth.validate_token(&token).unwrap();
614        assert_eq!(claims.tenant_id, "tenant1");
615        assert_eq!(claims.role, Role::Developer);
616    }
617
618    #[test]
619    fn test_api_key() {
620        let auth = AuthManager::new("test_secret");
621
622        let (api_key, key) = auth.create_api_key(
623            "test-key".to_string(),
624            "tenant1".to_string(),
625            Role::ServiceAccount,
626            None,
627        );
628
629        // Validate key
630        let claims = auth.validate_api_key(&key).unwrap();
631        assert_eq!(claims.tenant_id, "tenant1");
632        assert_eq!(claims.role, Role::ServiceAccount);
633
634        // Revoke key
635        auth.revoke_api_key(&api_key.id).unwrap();
636
637        // Should fail after revocation
638        assert!(auth.validate_api_key(&key).is_err());
639    }
640
641    #[test]
642    fn test_claims_expiration() {
643        let claims = Claims::new(
644            "user1".to_string(),
645            "tenant1".to_string(),
646            Role::Developer,
647            Duration::seconds(-1), // Expired 1 second ago
648        );
649
650        assert!(claims.is_expired());
651    }
652}