Skip to main content

llm_test_bench_core/api/
auth.rs

1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7//! Authentication and authorization.
8
9use anyhow::Result;
10use serde::{Deserialize, Serialize};
11use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
12use chrono::{DateTime, Duration, Utc};
13use std::collections::HashMap;
14use parking_lot::RwLock;
15use std::sync::Arc;
16
17/// JWT claims
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct JwtClaims {
20    /// Subject (user ID)
21    pub sub: String,
22    /// Expiration time
23    pub exp: i64,
24    /// Issued at
25    pub iat: i64,
26    /// User role
27    pub role: UserRole,
28    /// Additional metadata
29    #[serde(flatten)]
30    pub metadata: HashMap<String, String>,
31}
32
33/// User role
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "lowercase")]
36pub enum UserRole {
37    /// Administrator with full access
38    Admin,
39    /// Regular user with standard access
40    User,
41    /// Read-only access
42    Viewer,
43    /// Service account for API integration
44    Service,
45}
46
47/// API key information
48#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct ApiKey {
50    /// Key ID
51    pub id: String,
52    /// Key value (hashed)
53    pub key_hash: String,
54    /// User ID
55    pub user_id: String,
56    /// User role
57    pub role: UserRole,
58    /// Active status
59    pub active: bool,
60    /// Created at
61    pub created_at: DateTime<Utc>,
62    /// Expires at
63    pub expires_at: Option<DateTime<Utc>>,
64}
65
66/// Authentication service
67pub struct AuthService {
68    /// JWT secret key
69    secret_key: String,
70    /// Token expiration time (seconds)
71    token_expiration: i64,
72    /// API keys storage
73    api_keys: Arc<RwLock<HashMap<String, ApiKey>>>,
74}
75
76impl AuthService {
77    /// Create a new authentication service
78    pub fn new(secret_key: String, token_expiration: i64) -> Self {
79        Self {
80            secret_key,
81            token_expiration,
82            api_keys: Arc::new(RwLock::new(HashMap::new())),
83        }
84    }
85
86    /// Generate a JWT token
87    pub fn generate_token(&self, user_id: &str, role: UserRole) -> Result<String> {
88        let now = Utc::now();
89        let exp = now + Duration::seconds(self.token_expiration);
90
91        let claims = JwtClaims {
92            sub: user_id.to_string(),
93            exp: exp.timestamp(),
94            iat: now.timestamp(),
95            role,
96            metadata: HashMap::new(),
97        };
98
99        let token = encode(
100            &Header::default(),
101            &claims,
102            &EncodingKey::from_secret(self.secret_key.as_bytes()),
103        )?;
104
105        Ok(token)
106    }
107
108    /// Validate and decode a JWT token
109    pub fn validate_token(&self, token: &str) -> Result<JwtClaims> {
110        let token_data = decode::<JwtClaims>(
111            token,
112            &DecodingKey::from_secret(self.secret_key.as_bytes()),
113            &Validation::default(),
114        )?;
115
116        Ok(token_data.claims)
117    }
118
119    /// Generate an API key
120    pub fn generate_api_key(&self, user_id: &str, role: UserRole) -> Result<(String, ApiKey)> {
121        // Generate random API key
122        let key = format!("ltb_{}", uuid::Uuid::new_v4().to_string().replace("-", ""));
123
124        // Hash the key
125        let key_hash = bcrypt::hash(&key, bcrypt::DEFAULT_COST)?;
126
127        let api_key = ApiKey {
128            id: uuid::Uuid::new_v4().to_string(),
129            key_hash,
130            user_id: user_id.to_string(),
131            role,
132            active: true,
133            created_at: Utc::now(),
134            expires_at: None,
135        };
136
137        // Store API key
138        let mut keys = self.api_keys.write();
139        keys.insert(api_key.id.clone(), api_key.clone());
140
141        Ok((key, api_key))
142    }
143
144    /// Validate an API key
145    pub fn validate_api_key(&self, key: &str) -> Option<ApiKey> {
146        let keys = self.api_keys.read();
147
148        for api_key in keys.values() {
149            if api_key.active {
150                // Verify the key hash
151                if bcrypt::verify(key, &api_key.key_hash).unwrap_or(false) {
152                    // Check expiration
153                    if let Some(expires_at) = api_key.expires_at {
154                        if expires_at < Utc::now() {
155                            continue;
156                        }
157                    }
158
159                    return Some(api_key.clone());
160                }
161            }
162        }
163
164        None
165    }
166
167    /// Revoke an API key
168    pub fn revoke_api_key(&self, key_id: &str) -> bool {
169        let mut keys = self.api_keys.write();
170        if let Some(key) = keys.get_mut(key_id) {
171            key.active = false;
172            true
173        } else {
174            false
175        }
176    }
177
178    /// List API keys for a user
179    pub fn list_api_keys(&self, user_id: &str) -> Vec<ApiKey> {
180        let keys = self.api_keys.read();
181        keys.values()
182            .filter(|k| k.user_id == user_id)
183            .cloned()
184            .collect()
185    }
186
187    /// Check if a role has permission
188    pub fn has_permission(role: UserRole, required_role: UserRole) -> bool {
189        match (role, required_role) {
190            (UserRole::Admin, _) => true, // Admin has all permissions
191            (r, req) if r == req => true,
192            _ => false,
193        }
194    }
195}
196
197impl Default for AuthService {
198    fn default() -> Self {
199        Self::new(
200            "default_secret_change_in_production".to_string(),
201            3600, // 1 hour
202        )
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    #[test]
211    fn test_generate_and_validate_token() {
212        let auth = AuthService::default();
213        let token = auth.generate_token("user123", UserRole::User).unwrap();
214
215        let claims = auth.validate_token(&token).unwrap();
216        assert_eq!(claims.sub, "user123");
217        assert_eq!(claims.role, UserRole::User);
218    }
219
220    #[test]
221    fn test_invalid_token() {
222        let auth = AuthService::default();
223        let result = auth.validate_token("invalid_token");
224        assert!(result.is_err());
225    }
226
227    #[test]
228    fn test_generate_api_key() {
229        let auth = AuthService::default();
230        let (key, api_key) = auth.generate_api_key("user123", UserRole::User).unwrap();
231
232        assert!(key.starts_with("ltb_"));
233        assert_eq!(api_key.user_id, "user123");
234        assert_eq!(api_key.role, UserRole::User);
235        assert!(api_key.active);
236    }
237
238    #[test]
239    fn test_validate_api_key() {
240        let auth = AuthService::default();
241        let (key, _) = auth.generate_api_key("user123", UserRole::User).unwrap();
242
243        let validated = auth.validate_api_key(&key);
244        assert!(validated.is_some());
245        assert_eq!(validated.unwrap().user_id, "user123");
246    }
247
248    #[test]
249    fn test_revoke_api_key() {
250        let auth = AuthService::default();
251        let (_, api_key) = auth.generate_api_key("user123", UserRole::User).unwrap();
252
253        assert!(auth.revoke_api_key(&api_key.id));
254
255        let keys = auth.list_api_keys("user123");
256        assert_eq!(keys.len(), 1);
257        assert!(!keys[0].active);
258    }
259
260    #[test]
261    fn test_has_permission() {
262        assert!(AuthService::has_permission(UserRole::Admin, UserRole::User));
263        assert!(AuthService::has_permission(UserRole::User, UserRole::User));
264        assert!(!AuthService::has_permission(UserRole::Viewer, UserRole::User));
265    }
266}