1use argon2::{
47 password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
48 Argon2,
49};
50use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
51use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
52use chrono::{Duration, Utc};
53use hmac::{Hmac, Mac};
54use http::{header, HeaderMap};
55use rand_core::{OsRng, RngCore};
56use serde::{de::DeserializeOwned, Deserialize, Serialize};
57use sha2::{Digest, Sha256};
58use slabs_core::{id, SlabError, SlabResult};
59use slabs_db::Db;
60use sqlx::{Sqlite, Transaction};
61use std::fmt;
62
63type HmacSha256 = Hmac<Sha256>;
64
65#[derive(Serialize)]
66struct SignedTokenEnvelopeRef<'a, T: ?Sized> {
67 p: &'a str,
68 exp: i64,
69 d: &'a T,
70}
71
72#[derive(Deserialize)]
73struct SignedTokenEnvelope<T> {
74 p: String,
75 exp: i64,
76 d: T,
77}
78
79pub const SESSION_COOKIE_NAME: &str = "slabs_session";
81
82#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
84pub struct Session {
85 pub id: String,
87 pub user_id: String,
89 pub role: String,
91 pub expires_at: String,
93 pub created_at: String,
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct Principal {
100 pub user_id: String,
102 pub role: String,
104 pub auth_kind: String,
106 pub permission: String,
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct MagicLinkIssued {
113 pub id: String,
115 pub email: String,
117 pub purpose: String,
119 pub code: String,
121 pub expires_at: String,
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct MagicLinkConsumed {
128 pub id: String,
130 pub email: String,
132 pub purpose: String,
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct AccessTokenIssued {
139 pub id: String,
141 pub user_id: String,
143 pub description: String,
145 pub permission: String,
147 pub token: String,
149}
150
151#[derive(Clone)]
156pub struct Auth {
157 db: Option<Db>,
158 secret_key: String,
159 cookie_secure: bool,
160}
161
162impl fmt::Debug for Auth {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 f.debug_struct("Auth")
165 .field("db", &self.db)
166 .field("secret_key", &"<redacted>")
167 .field("cookie_secure", &self.cookie_secure)
168 .finish()
169 }
170}
171
172impl Auth {
173 #[must_use]
175 pub fn new(db: Db, secret_key: impl Into<String>, cookie_secure: bool) -> Self {
176 Self {
177 db: Some(db),
178 secret_key: secret_key.into(),
179 cookie_secure,
180 }
181 }
182
183 #[must_use]
185 pub fn for_signing(secret_key: impl Into<String>, cookie_secure: bool) -> Self {
186 Self {
187 db: None,
188 secret_key: secret_key.into(),
189 cookie_secure,
190 }
191 }
192
193 #[must_use]
195 pub fn cookie_secure(&self) -> bool {
196 self.cookie_secure
197 }
198
199 fn db(&self) -> SlabResult<&Db> {
200 self.db
201 .as_ref()
202 .ok_or_else(|| SlabError::internal("Auth requires a database connection"))
203 }
204
205 pub fn hash_password(&self, password: &str) -> SlabResult<String> {
207 let salt = SaltString::generate(&mut OsRng);
208 Argon2::default()
209 .hash_password(password.as_bytes(), &salt)
210 .map(|h| h.to_string())
211 .map_err(|e| SlabError::internal(format!("password hashing failed: {e}")))
212 }
213
214 pub fn verify_password(&self, password: &str, password_hash: &str) -> bool {
216 let Ok(parsed) = PasswordHash::new(password_hash) else {
217 return false;
218 };
219 Argon2::default()
220 .verify_password(password.as_bytes(), &parsed)
221 .is_ok()
222 }
223
224 pub fn hash_token(&self, raw_token: &str) -> String {
226 let mut hasher = Sha256::new();
227 hasher.update(raw_token.as_bytes());
228 hex::encode(hasher.finalize())
229 }
230
231 pub fn generate_token(&self) -> String {
233 let mut bytes = [0u8; 32];
234 OsRng.fill_bytes(&mut bytes);
235 hex::encode(bytes)
236 }
237
238 pub fn generate_short_code(&self, len: usize) -> String {
240 const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
241 let mut bytes = vec![0u8; len];
242 OsRng.fill_bytes(&mut bytes);
243 bytes
244 .into_iter()
245 .map(|b| ALPHABET[(b as usize) % ALPHABET.len()] as char)
246 .collect()
247 }
248
249 pub fn sign(&self, payload: &str) -> String {
251 let mut mac = HmacSha256::new_from_slice(self.secret_key.as_bytes())
252 .expect("HMAC accepts keys of any size");
253 mac.update(payload.as_bytes());
254 hex::encode(mac.finalize().into_bytes())
255 }
256
257 pub fn verify_signature(&self, payload: &str, signature_hex: &str) -> bool {
259 let Ok(sig_bytes) = hex::decode(signature_hex) else {
260 return false;
261 };
262 let Ok(mut mac) = HmacSha256::new_from_slice(self.secret_key.as_bytes()) else {
263 return false;
264 };
265 mac.update(payload.as_bytes());
266 mac.verify_slice(&sig_bytes).is_ok()
267 }
268
269 pub fn sign_token<T: Serialize>(
274 &self,
275 purpose: &str,
276 payload: &T,
277 ttl: std::time::Duration,
278 ) -> SlabResult<String> {
279 let ttl_secs = i64::try_from(ttl.as_secs())
280 .map_err(|_| SlabError::bad_request("token ttl exceeds supported range"))?;
281 let exp = Utc::now()
282 .timestamp()
283 .checked_add(ttl_secs)
284 .ok_or_else(|| SlabError::bad_request("token expiration timestamp overflow"))?;
285 let envelope = SignedTokenEnvelopeRef {
286 p: purpose,
287 exp,
288 d: payload,
289 };
290 let json = sqlx::types::Json(&envelope)
291 .encode_to_string()
292 .map_err(|e| SlabError::internal(format!("failed to serialize signed token: {e}")))?;
293 let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
294 let sig = self.sign(&encoded);
295 Ok(format!("{encoded}.{sig}"))
296 }
297
298 pub fn verify_token<T: DeserializeOwned>(&self, purpose: &str, token: &str) -> SlabResult<T> {
303 let Some((encoded, sig)) = token.split_once('.') else {
304 return Err(SlabError::unauthorized("invalid token format"));
305 };
306 if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
307 return Err(SlabError::unauthorized("invalid token format"));
308 }
309 if !self.verify_signature(encoded, sig) {
310 return Err(SlabError::unauthorized("invalid token signature"));
311 }
312 let raw = URL_SAFE_NO_PAD
313 .decode(encoded)
314 .map_err(|_| SlabError::unauthorized("invalid token encoding"))?;
315 let envelope = sqlx::types::Json::<SignedTokenEnvelope<T>>::decode_from_bytes(&raw)
316 .map_err(|_| SlabError::unauthorized("invalid token payload"))?
317 .0;
318 if envelope.p != purpose {
319 return Err(SlabError::unauthorized("token purpose mismatch"));
320 }
321 if envelope.exp <= Utc::now().timestamp() {
322 return Err(SlabError::unauthorized("token expired"));
323 }
324 Ok(envelope.d)
325 }
326
327 pub async fn create_session_in_tx(
331 &self,
332 tx: &mut Transaction<'_, Sqlite>,
333 user_id: &str,
334 role: &str,
335 ttl_days: i64,
336 ) -> SlabResult<(Session, Cookie<'static>)> {
337 let session_id = id::new("ses");
338 let raw_token = self.generate_token();
339 let token_hash = self.hash_token(&raw_token);
340 let now = Utc::now();
341 let expires = now + Duration::days(ttl_days);
342 let now_str = now.to_rfc3339();
343 let expires_str = expires.to_rfc3339();
344
345 sqlx::query(
346 "INSERT INTO slabs_sessions (id, user_id, role, token_hash, expires_at, created_at)
347 VALUES (?, ?, ?, ?, ?, ?)",
348 )
349 .bind(&session_id)
350 .bind(user_id)
351 .bind(role)
352 .bind(&token_hash)
353 .bind(&expires_str)
354 .bind(&now_str)
355 .execute(&mut **tx)
356 .await?;
357
358 let cookie = self.build_session_cookie(raw_token);
359 let session = Session {
360 id: session_id,
361 user_id: user_id.to_string(),
362 role: role.to_string(),
363 expires_at: expires_str,
364 created_at: now_str,
365 };
366 Ok((session, cookie))
367 }
368
369 pub async fn create_session(
371 &self,
372 user_id: &str,
373 role: &str,
374 ttl_days: i64,
375 ) -> SlabResult<(Session, Cookie<'static>)> {
376 let mut tx = self.db()?.begin().await?;
377 let res = self
378 .create_session_in_tx(&mut tx, user_id, role, ttl_days)
379 .await?;
380 tx.commit().await?;
381 Ok(res)
382 }
383
384 pub async fn optional_session(&self, jar: &CookieJar) -> SlabResult<Option<Session>> {
386 let Some(cookie) = jar.get(SESSION_COOKIE_NAME) else {
387 return Ok(None);
388 };
389 let token_hash = self.hash_token(cookie.value());
390 let now_str = Utc::now().to_rfc3339();
391
392 let session: Option<Session> = sqlx::query_as(
393 "SELECT id, user_id, role, expires_at, created_at
394 FROM slabs_sessions
395 WHERE token_hash = ? AND expires_at > ?",
396 )
397 .bind(&token_hash)
398 .bind(&now_str)
399 .fetch_optional(self.db()?.pool())
400 .await?;
401
402 Ok(session)
403 }
404
405 pub async fn require_session(&self, jar: &CookieJar) -> SlabResult<Session> {
407 self.optional_session(jar)
408 .await?
409 .ok_or_else(|| SlabError::unauthorized("authentication required"))
410 }
411
412 pub async fn require_admin(&self, jar: &CookieJar) -> SlabResult<Session> {
414 let session = self.require_session(jar).await?;
415 if session.role != "admin" {
416 return Err(SlabError::forbidden("administrator role required"));
417 }
418 Ok(session)
419 }
420
421 pub async fn destroy_session(&self, jar: &CookieJar) -> SlabResult<Cookie<'static>> {
423 if let Some(cookie) = jar.get(SESSION_COOKIE_NAME) {
424 let token_hash = self.hash_token(cookie.value());
425 sqlx::query("DELETE FROM slabs_sessions WHERE token_hash = ?")
426 .bind(&token_hash)
427 .execute(self.db()?.pool())
428 .await?;
429 }
430 Ok(self.clear_session_cookie())
431 }
432
433 pub fn build_session_cookie(&self, raw_token: String) -> Cookie<'static> {
435 Cookie::build((SESSION_COOKIE_NAME, raw_token))
436 .path("/")
437 .http_only(true)
438 .same_site(SameSite::Lax)
439 .secure(self.cookie_secure)
440 .build()
441 }
442
443 pub fn clear_session_cookie(&self) -> Cookie<'static> {
445 let mut cookie = Cookie::build((SESSION_COOKIE_NAME, ""))
446 .path("/")
447 .http_only(true)
448 .same_site(SameSite::Lax)
449 .secure(self.cookie_secure)
450 .build();
451 cookie.make_removal();
452 cookie
453 }
454
455 pub async fn issue_magic_link(
459 &self,
460 email: &str,
461 purpose: &str,
462 ttl_minutes: i64,
463 ) -> SlabResult<MagicLinkIssued> {
464 let link_id = id::new("mlk");
465 let code = self.generate_short_code(6);
466 let code_hash = self.hash_token(&code);
467 let now = Utc::now();
468 let expires_at = (now + Duration::minutes(ttl_minutes)).to_rfc3339();
469 let created_at = now.to_rfc3339();
470 let email = email.trim().to_lowercase();
471
472 sqlx::query(
473 "INSERT INTO slabs_magic_links (id, email, purpose, code_hash, expires_at, created_at)
474 VALUES (?, ?, ?, ?, ?, ?)",
475 )
476 .bind(&link_id)
477 .bind(&email)
478 .bind(purpose)
479 .bind(&code_hash)
480 .bind(&expires_at)
481 .bind(&created_at)
482 .execute(self.db()?.pool())
483 .await?;
484
485 Ok(MagicLinkIssued {
486 id: link_id,
487 email,
488 purpose: purpose.to_string(),
489 code,
490 expires_at,
491 })
492 }
493
494 pub async fn consume_magic_link(&self, raw_code: &str) -> SlabResult<MagicLinkConsumed> {
496 let sanitized: String = raw_code
497 .chars()
498 .filter(char::is_ascii_alphanumeric)
499 .map(|c| c.to_ascii_uppercase())
500 .collect();
501 if sanitized.is_empty() {
502 return Err(SlabError::unauthorized(
503 "invalid or expired magic link code",
504 ));
505 }
506
507 let code_hash = self.hash_token(&sanitized);
508 let now_str = Utc::now().to_rfc3339();
509
510 let consumed: Option<(String, String, String)> = sqlx::query_as(
511 "DELETE FROM slabs_magic_links
512 WHERE code_hash = ? AND expires_at > ?
513 RETURNING id, email, purpose",
514 )
515 .bind(&code_hash)
516 .bind(&now_str)
517 .fetch_optional(self.db()?.pool())
518 .await?;
519
520 let Some((id, email, purpose)) = consumed else {
521 return Err(SlabError::unauthorized(
522 "invalid or expired magic link code",
523 ));
524 };
525
526 Ok(MagicLinkConsumed { id, email, purpose })
527 }
528
529 pub async fn cleanup_expired_magic_links(&self) -> SlabResult<u64> {
531 let now_str = Utc::now().to_rfc3339();
532 let res = sqlx::query("DELETE FROM slabs_magic_links WHERE expires_at <= ?")
533 .bind(&now_str)
534 .execute(self.db()?.pool())
535 .await?;
536 Ok(res.rows_affected())
537 }
538
539 pub async fn issue_access_token(
543 &self,
544 user_id: &str,
545 role: &str,
546 description: &str,
547 permission: &str,
548 ) -> SlabResult<AccessTokenIssued> {
549 let token_id = id::new("pat");
550 let raw_token = format!("slb_{}", self.generate_token());
551 let token_hash = self.hash_token(&raw_token);
552 let created_at = Utc::now().to_rfc3339();
553
554 sqlx::query(
555 "INSERT INTO slabs_access_tokens (id, user_id, role, description, permission, token_hash, created_at)
556 VALUES (?, ?, ?, ?, ?, ?, ?)",
557 )
558 .bind(&token_id)
559 .bind(user_id)
560 .bind(role)
561 .bind(description)
562 .bind(permission)
563 .bind(&token_hash)
564 .bind(&created_at)
565 .execute(self.db()?.pool())
566 .await?;
567
568 Ok(AccessTokenIssued {
569 id: token_id,
570 user_id: user_id.to_string(),
571 description: description.to_string(),
572 permission: permission.to_string(),
573 token: raw_token,
574 })
575 }
576
577 pub async fn optional_auth(
581 &self,
582 jar: &CookieJar,
583 headers: &HeaderMap,
584 ) -> SlabResult<Option<Principal>> {
585 if let Some(auth_hdr) = headers
586 .get(header::AUTHORIZATION)
587 .and_then(|v| v.to_str().ok())
588 {
589 if let Some(raw_token) = auth_hdr
590 .strip_prefix("Bearer ")
591 .or_else(|| auth_hdr.strip_prefix("bearer "))
592 {
593 let token_hash = self.hash_token(raw_token.trim());
594 let now_str = Utc::now().to_rfc3339();
595
596 let db = self.db()?;
597 let row: Option<(String, String, String, String)> = sqlx::query_as(
598 "SELECT id, user_id, role, permission
599 FROM slabs_access_tokens
600 WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > ?)",
601 )
602 .bind(&token_hash)
603 .bind(&now_str)
604 .fetch_optional(db.pool())
605 .await?;
606
607 if let Some((token_id, user_id, role, permission)) = row {
608 let _ =
609 sqlx::query("UPDATE slabs_access_tokens SET last_used_at = ? WHERE id = ?")
610 .bind(&now_str)
611 .bind(&token_id)
612 .execute(db.pool())
613 .await;
614
615 return Ok(Some(Principal {
616 user_id,
617 role,
618 auth_kind: "bearer".to_string(),
619 permission,
620 }));
621 }
622 return Ok(None);
623 }
624 }
625
626 if let Some(session) = self.optional_session(jar).await? {
627 return Ok(Some(Principal {
628 user_id: session.user_id,
629 role: session.role,
630 auth_kind: "session".to_string(),
631 permission: "write".to_string(),
632 }));
633 }
634
635 Ok(None)
636 }
637
638 pub async fn require_auth(
640 &self,
641 jar: &CookieJar,
642 headers: &HeaderMap,
643 ) -> SlabResult<Principal> {
644 self.optional_auth(jar, headers).await?.ok_or_else(|| {
645 SlabError::unauthorized("authentication required (session cookie or Bearer token)")
646 })
647 }
648
649 pub async fn require_write_auth(
651 &self,
652 jar: &CookieJar,
653 headers: &HeaderMap,
654 ) -> SlabResult<Principal> {
655 let principal = self.require_auth(jar, headers).await?;
656 if principal.permission != "write" {
657 return Err(SlabError::forbidden(
658 "access token does not have write permission",
659 ));
660 }
661 Ok(principal)
662 }
663}
664
665#[cfg(test)]
666mod tests {
667 use super::*;
668 use std::time::Duration as StdDuration;
669
670 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
671 struct InvitePayload {
672 user_id: String,
673 org_id: String,
674 }
675
676 fn test_auth() -> Auth {
677 Auth::for_signing("unit-test-secret-key-for-signed-tokens", false)
678 }
679
680 #[test]
681 fn sign_and_verify_token_roundtrip() {
682 let auth = test_auth();
683 let payload = InvitePayload {
684 user_id: "usr_01".to_string(),
685 org_id: "org_42".to_string(),
686 };
687
688 let token = auth
689 .sign_token("invite", &payload, StdDuration::from_secs(300))
690 .unwrap();
691 let decoded: InvitePayload = auth.verify_token("invite", &token).unwrap();
692 assert_eq!(decoded, payload);
693 }
694
695 #[test]
696 fn verify_token_rejects_wrong_purpose() {
697 let auth = test_auth();
698 let token = auth
699 .sign_token(
700 "email_verify",
701 &"usr_01".to_string(),
702 StdDuration::from_secs(300),
703 )
704 .unwrap();
705
706 let err = auth
707 .verify_token::<String>("password_reset", &token)
708 .unwrap_err();
709 assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
710 }
711
712 #[test]
713 fn verify_token_rejects_tampered_signature() {
714 let auth = test_auth();
715 let token = auth
716 .sign_token(
717 "download",
718 &"blb_123".to_string(),
719 StdDuration::from_secs(300),
720 )
721 .unwrap();
722 let (encoded, sig) = token.split_once('.').unwrap();
723 let flipped = if sig.starts_with('a') { 'b' } else { 'a' };
724 let tampered = format!("{encoded}.{flipped}{}", &sig[1..]);
725
726 let err = auth
727 .verify_token::<String>("download", &tampered)
728 .unwrap_err();
729 assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
730 }
731
732 #[test]
733 fn verify_token_rejects_expired_token() {
734 let auth = test_auth();
735
736 let zero_ttl = auth
737 .sign_token("reset", &"usr_01".to_string(), StdDuration::ZERO)
738 .unwrap();
739 let err = auth.verify_token::<String>("reset", &zero_ttl).unwrap_err();
740 assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
741
742 let past_envelope = SignedTokenEnvelopeRef {
744 p: "reset",
745 exp: Utc::now().timestamp() - 60,
746 d: &"usr_01",
747 };
748 let json = sqlx::types::Json(&past_envelope)
749 .encode_to_string()
750 .unwrap();
751 let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
752 let sig = auth.sign(&encoded);
753 let expired = format!("{encoded}.{sig}");
754
755 let err = auth.verify_token::<String>("reset", &expired).unwrap_err();
756 assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
757 }
758}