AirLibrary/Authentication/
mod.rs

1//! # Authentication Service
2//!
3//! Handles user authentication, token management, and cryptographic operations
4//! for the Air daemon. This service manages secure storage of credentials
5//! and provides authentication services to Mountain with resilient patterns.
6
7use std::{collections::HashMap, sync::Arc};
8
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use tokio::sync::{Mutex, RwLock};
12use base64::{Engine as _, engine::general_purpose::URL_SAFE};
13use ring::{aead, rand::SecureRandom};
14
15use crate::{AirError, ApplicationState::ApplicationState, Configuration::ConfigurationManager, Result, Utility};
16
17/// Authentication service implementation
18pub struct AuthenticationService {
19	/// Application state
20	AppState:Arc<ApplicationState>,
21
22	/// Active sessions
23	Sessions:Arc<RwLock<HashMap<String, AuthSession>>>,
24
25	/// Credentials storage
26	Credentials:Arc<Mutex<CredentialsStore>>,
27
28	/// Cryptographic keys
29	CryptoKeys:Arc<Mutex<CryptoKeys>>,
30	/// AEAD algorithm for encryption/decryption
31	AeadAlgo:&'static aead::Algorithm,
32}
33
34/// Authentication session
35#[derive(Debug, Clone, Serialize, Deserialize)]
36pub struct AuthSession {
37	pub SessionId:String,
38	pub UserId:String,
39	pub Provider:String,
40	pub Token:String,
41	pub CreatedAt:DateTime<Utc>,
42	pub ExpiresAt:DateTime<Utc>,
43	pub IsValid:bool,
44}
45
46/// Credentials storage
47#[derive(Debug, Serialize, Deserialize)]
48struct CredentialsStore {
49	Credentials:HashMap<String, UserCredentials>,
50	FilePath:String,
51}
52
53/// User credentials
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct UserCredentials {
56	pub UserId:String,
57	pub Provider:String,
58	pub EncryptedPassword:String,
59	pub LastUsed:DateTime<Utc>,
60	pub IsValid:bool,
61}
62
63/// Cryptographic keys
64#[derive(Debug)]
65struct CryptoKeys {
66	SigningKey:ring::signature::Ed25519KeyPair,
67	EncryptionKey:[u8; 32],
68}
69
70impl AuthenticationService {
71	/// Create a new authentication service
72	pub async fn new(AppState:Arc<ApplicationState>) -> Result<Self> {
73		let config = &AppState.Configuration.Authentication;
74
75		// Expand credentials path
76		let CredentialsPath = ConfigurationManager::ExpandPath(&config.CredentialsPath)?;
77
78		// Load or create credentials store
79		let CredentialsStore = Self::LoadCredentialsStore(&CredentialsPath).await?;
80
81		// Generate cryptographic keys
82		let CryptoKeys = Self::GenerateCryptoKeys()?;
83		let AeadAlgo = &aead::AES_256_GCM;
84
85		let Service = Self {
86			AppState,
87			Sessions:Arc::new(RwLock::new(HashMap::new())),
88			Credentials:Arc::new(Mutex::new(CredentialsStore)),
89			CryptoKeys:Arc::new(Mutex::new(CryptoKeys)),
90			AeadAlgo,
91		};
92
93		// Initialize service status
94		Service
95			.AppState
96			.UpdateServiceStatus("authentication", crate::ApplicationState::ServiceStatus::Running)
97			.await
98			.map_err(|e| AirError::Authentication(e.to_string()))?;
99
100		Ok(Service)
101	}
102
103	/// Authenticate a user
104	pub async fn AuthenticateUser(&self, Username:String, Password:String, Provider:String) -> Result<String> {
105		// Validate input
106		if Username.is_empty() || Password.is_empty() || Provider.is_empty() {
107			return Err(AirError::Authentication("Invalid authentication parameters".to_string()));
108		}
109
110		// Check credentials
111		let _UserCredentials = self.ValidateCredentials(&Username, &Password, &Provider).await?;
112
113		// Generate session token
114		let Token = self.GenerateSessionToken(&Username, &Provider).await?;
115
116		// Create session
117		let SessionId = Utility::GenerateRequestId();
118		let Session = AuthSession {
119			SessionId,
120			UserId:Username.clone(),
121			Provider:Provider.clone(),
122			Token:Token.clone(),
123			CreatedAt:chrono::Utc::now(),
124			ExpiresAt:chrono::Utc::now()
125				+ chrono::Duration::hours(self.AppState.Configuration.Authentication.TokenExpirationHours as i64),
126			IsValid:true,
127		};
128
129		// Store session
130		{
131			let mut Sessions = self.Sessions.write().await;
132			Sessions.insert(Session.SessionId.clone(), Session);
133		}
134
135		// Update credentials usage
136		self.UpdateCredentialsUsage(&Username, &Provider).await?;
137
138		Ok(Token)
139	}
140
141	/// Validate user credentials
142	async fn ValidateCredentials(&self, Username:&str, Password:&str, Provider:&str) -> Result<UserCredentials> {
143		let CredentialsStore = self.Credentials.lock().await;
144
145		let Key = format!("{}:{}", Provider, Username);
146
147		if let Some(UserCredentials) = CredentialsStore.Credentials.get(&Key) {
148			if !UserCredentials.IsValid {
149				return Err(AirError::Authentication("Credentials are invalid".to_string()));
150			}
151
152			// Verify password (in a real implementation, this would decrypt and verify)
153			// For now, we'll use a simple approach
154			let DecryptedPassword = self.DecryptPassword(&UserCredentials.EncryptedPassword).await?;
155
156			if DecryptedPassword == Password {
157				Ok(UserCredentials.clone())
158			} else {
159				Err(AirError::Authentication("Invalid password".to_string()))
160			}
161		} else {
162			Err(AirError::Authentication("User not found".to_string()))
163		}
164	}
165
166	/// Generate a session token
167	async fn GenerateSessionToken(&self, Username:&str, Provider:&str) -> Result<String> {
168		let CryptoKeys = self.CryptoKeys.lock().await;
169
170		let Payload = format!("{}:{}:{}", Username, Provider, Utility::CurrentTimestamp());
171
172		// Sign the payload
173		let Signature = CryptoKeys.SigningKey.sign(Payload.as_bytes());
174
175		// Encode token
176		let Token = URL_SAFE.encode(format!("{}:{}", Payload, URL_SAFE.encode(Signature.as_ref())));
177
178		Ok(Token)
179	}
180
181	/// Update credentials usage timestamp
182	async fn UpdateCredentialsUsage(&self, Username:&str, Provider:&str) -> Result<()> {
183		let mut CredentialsStore = self.Credentials.lock().await;
184
185		let Key = format!("{}:{}", Provider, Username);
186
187		if let Some(UserCredentials) = CredentialsStore.Credentials.get_mut(&Key) {
188			UserCredentials.LastUsed = Utc::now();
189		}
190
191		// Save updated credentials
192		self.SaveCredentialsStore(&CredentialsStore).await?;
193
194		Ok(())
195	}
196
197	/// Encrypt password
198	async fn EncryptPassword(&self, Password:&str) -> Result<String> {
199		let CryptoKeys = self.CryptoKeys.lock().await;
200
201		// Use AES-256-GCM via ring::aead. Prefix nonce to ciphertext and base64 encode.
202		let UnboundKey = aead::UnboundKey::new(&aead::AES_256_GCM, &CryptoKeys.EncryptionKey)
203			.map_err(|e| AirError::Authentication(format!("Failed to create AEAD key: {:?}", e)))?;
204
205		let LessSafe = aead::LessSafeKey::new(UnboundKey);
206		let mut NonceBytes = [0u8; 12];
207		ring::rand::SystemRandom::new()
208			.fill(&mut NonceBytes)
209			.map_err(|e| AirError::Authentication(format!("Failed to generate nonce: {:?}", e)))?;
210
211		let Nonce = aead::Nonce::assume_unique_for_key(NonceBytes);
212
213		let mut InOut = Password.as_bytes().to_vec();
214		// Reserve space for tag
215		InOut.extend_from_slice(&[0u8; 16]); // AES_256_GCM tag length is 16 bytes
216
217		LessSafe
218			.seal_in_place_append_tag(Nonce, aead::Aad::empty(), &mut InOut)
219			.map_err(|e| AirError::Authentication(format!("Encryption failed: {:?}", e)))?;
220
221		// Store nonce + ciphertext
222		let mut Out = Vec::with_capacity(NonceBytes.len() + InOut.len());
223		Out.extend_from_slice(&NonceBytes);
224		Out.extend_from_slice(&InOut);
225
226		Ok(URL_SAFE.encode(&Out))
227	}
228
229	/// Decrypt password
230	async fn DecryptPassword(&self, EncryptedPassword:&str) -> Result<String> {
231		let CryptoKeys = self.CryptoKeys.lock().await;
232
233		let Data = URL_SAFE
234			.decode(EncryptedPassword)
235			.map_err(|e| AirError::Authentication(format!("Failed to decode password: {}", e)))?;
236
237		if Data.len() < 12 + aead::AES_256_GCM.tag_len() {
238			return Err(AirError::Authentication("Encrypted data too short".to_string()));
239		}
240
241		let (NonceBytes, CipherBytes) = Data.split_at(12);
242
243		let mut NonceArr = [0u8; 12];
244		NonceArr.copy_from_slice(&NonceBytes[0..12]);
245
246		let UnboundKey = aead::UnboundKey::new(&aead::AES_256_GCM, &CryptoKeys.EncryptionKey)
247			.map_err(|e| AirError::Authentication(format!("Failed to create AEAD key: {:?}", e)))?;
248
249		let LessSafe = aead::LessSafeKey::new(UnboundKey);
250		let Nonce = aead::Nonce::assume_unique_for_key(NonceArr);
251
252		let mut CipherVec = CipherBytes.to_vec();
253		let Plain = LessSafe
254			.open_in_place(Nonce, aead::Aad::empty(), &mut CipherVec)
255			.map_err(|e| AirError::Authentication(format!("Decryption failed: {:?}", e)))?;
256
257		String::from_utf8(Plain.to_vec())
258			.map_err(|e| AirError::Authentication(format!("Failed to decode password string: {}", e)))
259	}
260
261	/// Load credentials store from file
262	async fn LoadCredentialsStore(FilePath:&std::path::Path) -> Result<CredentialsStore> {
263		if FilePath.exists() {
264			let Content = tokio::fs::read_to_string(FilePath)
265				.await
266				.map_err(|e| AirError::Authentication(format!("Failed to read credentials file: {}", e)))?;
267
268			let Credentials:HashMap<String, UserCredentials> = serde_json::from_str(&Content)
269				.map_err(|e| AirError::Authentication(format!("Failed to parse credentials file: {}", e)))?;
270
271			Ok(CredentialsStore { Credentials, FilePath:FilePath.to_string_lossy().to_string() })
272		} else {
273			// Create new credentials store
274			Ok(CredentialsStore { Credentials:HashMap::new(), FilePath:FilePath.to_string_lossy().to_string() })
275		}
276	}
277
278	/// Save credentials store to file
279	async fn SaveCredentialsStore(&self, Store:&CredentialsStore) -> Result<()> {
280		let Content = serde_json::to_string_pretty(&Store.Credentials)
281			.map_err(|e| AirError::Authentication(format!("Failed to serialize credentials: {}", e)))?;
282
283		// Create directory if it doesn't exist
284		if let Some(Parent) = std::path::Path::new(&Store.FilePath).parent() {
285			tokio::fs::create_dir_all(Parent)
286				.await
287				.map_err(|e| AirError::Authentication(format!("Failed to create credentials directory: {}", e)))?;
288
289			tokio::fs::write(&Store.FilePath, Content)
290				.await
291				.map_err(|e| AirError::Authentication(format!("Failed to write credentials file: {}", e)))?;
292
293			Ok(())
294		} else {
295			Err(AirError::Authentication("Invalid file path - no parent directory".to_string()))
296		}
297	}
298
299	/// Generate cryptographic keys
300	fn GenerateCryptoKeys() -> Result<CryptoKeys> {
301		// Generate signing key
302		let Rng = ring::rand::SystemRandom::new();
303		let Pkcs8Bytes = ring::signature::Ed25519KeyPair::generate_pkcs8(&Rng)
304			.map_err(|e| AirError::Authentication(format!("Failed to generate signing key: {}", e)))?;
305
306		let SigningKey = ring::signature::Ed25519KeyPair::from_pkcs8(Pkcs8Bytes.as_ref())
307			.map_err(|e| AirError::Authentication(format!("Failed to load signing key: {}", e)))?;
308
309		// Generate encryption key
310		let mut EncryptionKey = [0u8; 32];
311		ring::rand::SystemRandom::new()
312			.fill(&mut EncryptionKey)
313			.map_err(|e| AirError::Authentication(format!("Failed to generate encryption key: {}", e)))
314			.map_err(|e| AirError::Authentication(format!("Failed to generate encryption key: {}", e)))?;
315
316		Ok(CryptoKeys { SigningKey, EncryptionKey })
317	}
318
319	/// Start background tasks
320	pub async fn StartBackgroundTasks(&self) -> Result<tokio::task::JoinHandle<()>> {
321		let Service = self.clone();
322
323		let Handle = tokio::spawn(async move {
324			Service.BackgroundTask().await;
325		});
326
327		Ok(Handle)
328	}
329
330	/// Background task for session cleanup
331	async fn BackgroundTask(&self) {
332		let mut Interval = tokio::time::interval(tokio::time::Duration::from_secs(300)); // 5 minutes
333
334		loop {
335			Interval.tick().await;
336
337			// Clean up expired sessions
338			self.CleanupExpiredSessions().await;
339
340			// Save credentials periodically
341			if let Err(E) = self.SaveCredentialsPeriodically().await {
342				log::error!("[Authentication] Failed to save credentials: {}", E);
343			}
344		}
345	}
346
347	/// Clean up expired sessions
348	async fn CleanupExpiredSessions(&self) {
349		let Now = Utc::now();
350		let mut Sessions = self.Sessions.write().await;
351
352		Sessions.retain(|_, Session| Session.ExpiresAt > Now && Session.IsValid);
353
354		log::debug!("[Authentication] Cleaned up expired sessions");
355	}
356
357	/// Save credentials periodically
358	async fn SaveCredentialsPeriodically(&self) -> Result<()> {
359		let CredentialsStore = self.Credentials.lock().await;
360		self.SaveCredentialsStore(&CredentialsStore).await
361	}
362
363	/// Stop background tasks
364	pub async fn StopBackgroundTasks(&self) {
365		// Implementation for graceful shutdown
366		log::info!("[Authentication] Stopping background tasks");
367	}
368}
369
370impl Clone for AuthenticationService {
371	fn clone(&self) -> Self {
372		Self {
373			AppState:self.AppState.clone(),
374			Sessions:self.Sessions.clone(),
375			Credentials:self.Credentials.clone(),
376			CryptoKeys:self.CryptoKeys.clone(),
377			AeadAlgo:self.AeadAlgo,
378		}
379	}
380}