use argon2::{
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
Argon2,
};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use chrono::{Duration, Utc};
use hmac::{Hmac, Mac};
use http::{header, HeaderMap};
use rand_core::{OsRng, RngCore};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sha2::{Digest, Sha256};
use slabs_core::{id, SlabError, SlabResult};
use slabs_db::Db;
use sqlx::{Sqlite, Transaction};
use std::fmt;
type HmacSha256 = Hmac<Sha256>;
#[derive(Serialize)]
struct SignedTokenEnvelopeRef<'a, T: ?Sized> {
p: &'a str,
exp: i64,
d: &'a T,
}
#[derive(Deserialize)]
struct SignedTokenEnvelope<T> {
p: String,
exp: i64,
d: T,
}
pub const SESSION_COOKIE_NAME: &str = "slabs_session";
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Session {
pub id: String,
pub user_id: String,
pub role: String,
pub expires_at: String,
pub created_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Principal {
pub user_id: String,
pub role: String,
pub auth_kind: String,
pub permission: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MagicLinkIssued {
pub id: String,
pub email: String,
pub purpose: String,
pub code: String,
pub expires_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MagicLinkConsumed {
pub id: String,
pub email: String,
pub purpose: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessTokenIssued {
pub id: String,
pub user_id: String,
pub description: String,
pub permission: String,
pub token: String,
}
#[derive(Clone)]
pub struct Auth {
db: Option<Db>,
secret_key: String,
cookie_secure: bool,
}
impl fmt::Debug for Auth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Auth")
.field("db", &self.db)
.field("secret_key", &"<redacted>")
.field("cookie_secure", &self.cookie_secure)
.finish()
}
}
impl Auth {
#[must_use]
pub fn new(db: Db, secret_key: impl Into<String>, cookie_secure: bool) -> Self {
Self {
db: Some(db),
secret_key: secret_key.into(),
cookie_secure,
}
}
#[must_use]
pub fn for_signing(secret_key: impl Into<String>, cookie_secure: bool) -> Self {
Self {
db: None,
secret_key: secret_key.into(),
cookie_secure,
}
}
#[must_use]
pub fn cookie_secure(&self) -> bool {
self.cookie_secure
}
fn db(&self) -> SlabResult<&Db> {
self.db
.as_ref()
.ok_or_else(|| SlabError::internal("Auth requires a database connection"))
}
pub fn hash_password(&self, password: &str) -> SlabResult<String> {
let salt = SaltString::generate(&mut OsRng);
Argon2::default()
.hash_password(password.as_bytes(), &salt)
.map(|h| h.to_string())
.map_err(|e| SlabError::internal(format!("password hashing failed: {e}")))
}
pub fn verify_password(&self, password: &str, password_hash: &str) -> bool {
let Ok(parsed) = PasswordHash::new(password_hash) else {
return false;
};
Argon2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok()
}
pub fn hash_token(&self, raw_token: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(raw_token.as_bytes());
hex::encode(hasher.finalize())
}
pub fn generate_token(&self) -> String {
let mut bytes = [0u8; 32];
OsRng.fill_bytes(&mut bytes);
hex::encode(bytes)
}
pub fn generate_short_code(&self, len: usize) -> String {
const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
let mut bytes = vec![0u8; len];
OsRng.fill_bytes(&mut bytes);
bytes
.into_iter()
.map(|b| ALPHABET[(b as usize) % ALPHABET.len()] as char)
.collect()
}
pub fn sign(&self, payload: &str) -> String {
let mut mac = HmacSha256::new_from_slice(self.secret_key.as_bytes())
.expect("HMAC accepts keys of any size");
mac.update(payload.as_bytes());
hex::encode(mac.finalize().into_bytes())
}
pub fn verify_signature(&self, payload: &str, signature_hex: &str) -> bool {
let Ok(sig_bytes) = hex::decode(signature_hex) else {
return false;
};
let Ok(mut mac) = HmacSha256::new_from_slice(self.secret_key.as_bytes()) else {
return false;
};
mac.update(payload.as_bytes());
mac.verify_slice(&sig_bytes).is_ok()
}
pub fn sign_token<T: Serialize>(
&self,
purpose: &str,
payload: &T,
ttl: std::time::Duration,
) -> SlabResult<String> {
let ttl_secs = i64::try_from(ttl.as_secs())
.map_err(|_| SlabError::bad_request("token ttl exceeds supported range"))?;
let exp = Utc::now()
.timestamp()
.checked_add(ttl_secs)
.ok_or_else(|| SlabError::bad_request("token expiration timestamp overflow"))?;
let envelope = SignedTokenEnvelopeRef {
p: purpose,
exp,
d: payload,
};
let json = sqlx::types::Json(&envelope)
.encode_to_string()
.map_err(|e| SlabError::internal(format!("failed to serialize signed token: {e}")))?;
let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
let sig = self.sign(&encoded);
Ok(format!("{encoded}.{sig}"))
}
pub fn verify_token<T: DeserializeOwned>(&self, purpose: &str, token: &str) -> SlabResult<T> {
let Some((encoded, sig)) = token.split_once('.') else {
return Err(SlabError::unauthorized("invalid token format"));
};
if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
return Err(SlabError::unauthorized("invalid token format"));
}
if !self.verify_signature(encoded, sig) {
return Err(SlabError::unauthorized("invalid token signature"));
}
let raw = URL_SAFE_NO_PAD
.decode(encoded)
.map_err(|_| SlabError::unauthorized("invalid token encoding"))?;
let envelope = sqlx::types::Json::<SignedTokenEnvelope<T>>::decode_from_bytes(&raw)
.map_err(|_| SlabError::unauthorized("invalid token payload"))?
.0;
if envelope.p != purpose {
return Err(SlabError::unauthorized("token purpose mismatch"));
}
if envelope.exp <= Utc::now().timestamp() {
return Err(SlabError::unauthorized("token expired"));
}
Ok(envelope.d)
}
pub async fn create_session_in_tx(
&self,
tx: &mut Transaction<'_, Sqlite>,
user_id: &str,
role: &str,
ttl_days: i64,
) -> SlabResult<(Session, Cookie<'static>)> {
let session_id = id::new("ses");
let raw_token = self.generate_token();
let token_hash = self.hash_token(&raw_token);
let now = Utc::now();
let expires = now + Duration::days(ttl_days);
let now_str = now.to_rfc3339();
let expires_str = expires.to_rfc3339();
sqlx::query(
"INSERT INTO slabs_sessions (id, user_id, role, token_hash, expires_at, created_at)
VALUES (?, ?, ?, ?, ?, ?)",
)
.bind(&session_id)
.bind(user_id)
.bind(role)
.bind(&token_hash)
.bind(&expires_str)
.bind(&now_str)
.execute(&mut **tx)
.await?;
let cookie = self.build_session_cookie(raw_token);
let session = Session {
id: session_id,
user_id: user_id.to_string(),
role: role.to_string(),
expires_at: expires_str,
created_at: now_str,
};
Ok((session, cookie))
}
pub async fn create_session(
&self,
user_id: &str,
role: &str,
ttl_days: i64,
) -> SlabResult<(Session, Cookie<'static>)> {
let mut tx = self.db()?.begin().await?;
let res = self
.create_session_in_tx(&mut tx, user_id, role, ttl_days)
.await?;
tx.commit().await?;
Ok(res)
}
pub async fn optional_session(&self, jar: &CookieJar) -> SlabResult<Option<Session>> {
let Some(cookie) = jar.get(SESSION_COOKIE_NAME) else {
return Ok(None);
};
let token_hash = self.hash_token(cookie.value());
let now_str = Utc::now().to_rfc3339();
let session: Option<Session> = sqlx::query_as(
"SELECT id, user_id, role, expires_at, created_at
FROM slabs_sessions
WHERE token_hash = ? AND expires_at > ?",
)
.bind(&token_hash)
.bind(&now_str)
.fetch_optional(self.db()?.pool())
.await?;
Ok(session)
}
pub async fn require_session(&self, jar: &CookieJar) -> SlabResult<Session> {
self.optional_session(jar)
.await?
.ok_or_else(|| SlabError::unauthorized("authentication required"))
}
pub async fn require_admin(&self, jar: &CookieJar) -> SlabResult<Session> {
let session = self.require_session(jar).await?;
if session.role != "admin" {
return Err(SlabError::forbidden("administrator role required"));
}
Ok(session)
}
pub async fn destroy_session(&self, jar: &CookieJar) -> SlabResult<Cookie<'static>> {
if let Some(cookie) = jar.get(SESSION_COOKIE_NAME) {
let token_hash = self.hash_token(cookie.value());
sqlx::query("DELETE FROM slabs_sessions WHERE token_hash = ?")
.bind(&token_hash)
.execute(self.db()?.pool())
.await?;
}
Ok(self.clear_session_cookie())
}
pub fn build_session_cookie(&self, raw_token: String) -> Cookie<'static> {
Cookie::build((SESSION_COOKIE_NAME, raw_token))
.path("/")
.http_only(true)
.same_site(SameSite::Lax)
.secure(self.cookie_secure)
.build()
}
pub fn clear_session_cookie(&self) -> Cookie<'static> {
let mut cookie = Cookie::build((SESSION_COOKIE_NAME, ""))
.path("/")
.http_only(true)
.same_site(SameSite::Lax)
.secure(self.cookie_secure)
.build();
cookie.make_removal();
cookie
}
pub async fn issue_magic_link(
&self,
email: &str,
purpose: &str,
ttl_minutes: i64,
) -> SlabResult<MagicLinkIssued> {
let link_id = id::new("mlk");
let code = self.generate_short_code(6);
let code_hash = self.hash_token(&code);
let now = Utc::now();
let expires_at = (now + Duration::minutes(ttl_minutes)).to_rfc3339();
let created_at = now.to_rfc3339();
let email = email.trim().to_lowercase();
sqlx::query(
"INSERT INTO slabs_magic_links (id, email, purpose, code_hash, expires_at, created_at)
VALUES (?, ?, ?, ?, ?, ?)",
)
.bind(&link_id)
.bind(&email)
.bind(purpose)
.bind(&code_hash)
.bind(&expires_at)
.bind(&created_at)
.execute(self.db()?.pool())
.await?;
Ok(MagicLinkIssued {
id: link_id,
email,
purpose: purpose.to_string(),
code,
expires_at,
})
}
pub async fn consume_magic_link(&self, raw_code: &str) -> SlabResult<MagicLinkConsumed> {
let sanitized: String = raw_code
.chars()
.filter(char::is_ascii_alphanumeric)
.map(|c| c.to_ascii_uppercase())
.collect();
if sanitized.is_empty() {
return Err(SlabError::unauthorized(
"invalid or expired magic link code",
));
}
let code_hash = self.hash_token(&sanitized);
let now_str = Utc::now().to_rfc3339();
let consumed: Option<(String, String, String)> = sqlx::query_as(
"DELETE FROM slabs_magic_links
WHERE code_hash = ? AND expires_at > ?
RETURNING id, email, purpose",
)
.bind(&code_hash)
.bind(&now_str)
.fetch_optional(self.db()?.pool())
.await?;
let Some((id, email, purpose)) = consumed else {
return Err(SlabError::unauthorized(
"invalid or expired magic link code",
));
};
Ok(MagicLinkConsumed { id, email, purpose })
}
pub async fn cleanup_expired_magic_links(&self) -> SlabResult<u64> {
let now_str = Utc::now().to_rfc3339();
let res = sqlx::query("DELETE FROM slabs_magic_links WHERE expires_at <= ?")
.bind(&now_str)
.execute(self.db()?.pool())
.await?;
Ok(res.rows_affected())
}
pub async fn issue_access_token(
&self,
user_id: &str,
role: &str,
description: &str,
permission: &str,
) -> SlabResult<AccessTokenIssued> {
let token_id = id::new("pat");
let raw_token = format!("slb_{}", self.generate_token());
let token_hash = self.hash_token(&raw_token);
let created_at = Utc::now().to_rfc3339();
sqlx::query(
"INSERT INTO slabs_access_tokens (id, user_id, role, description, permission, token_hash, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)",
)
.bind(&token_id)
.bind(user_id)
.bind(role)
.bind(description)
.bind(permission)
.bind(&token_hash)
.bind(&created_at)
.execute(self.db()?.pool())
.await?;
Ok(AccessTokenIssued {
id: token_id,
user_id: user_id.to_string(),
description: description.to_string(),
permission: permission.to_string(),
token: raw_token,
})
}
pub async fn optional_auth(
&self,
jar: &CookieJar,
headers: &HeaderMap,
) -> SlabResult<Option<Principal>> {
if let Some(auth_hdr) = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
{
if let Some(raw_token) = auth_hdr
.strip_prefix("Bearer ")
.or_else(|| auth_hdr.strip_prefix("bearer "))
{
let token_hash = self.hash_token(raw_token.trim());
let now_str = Utc::now().to_rfc3339();
let db = self.db()?;
let row: Option<(String, String, String, String)> = sqlx::query_as(
"SELECT id, user_id, role, permission
FROM slabs_access_tokens
WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > ?)",
)
.bind(&token_hash)
.bind(&now_str)
.fetch_optional(db.pool())
.await?;
if let Some((token_id, user_id, role, permission)) = row {
let _ =
sqlx::query("UPDATE slabs_access_tokens SET last_used_at = ? WHERE id = ?")
.bind(&now_str)
.bind(&token_id)
.execute(db.pool())
.await;
return Ok(Some(Principal {
user_id,
role,
auth_kind: "bearer".to_string(),
permission,
}));
}
return Ok(None);
}
}
if let Some(session) = self.optional_session(jar).await? {
return Ok(Some(Principal {
user_id: session.user_id,
role: session.role,
auth_kind: "session".to_string(),
permission: "write".to_string(),
}));
}
Ok(None)
}
pub async fn require_auth(
&self,
jar: &CookieJar,
headers: &HeaderMap,
) -> SlabResult<Principal> {
self.optional_auth(jar, headers).await?.ok_or_else(|| {
SlabError::unauthorized("authentication required (session cookie or Bearer token)")
})
}
pub async fn require_write_auth(
&self,
jar: &CookieJar,
headers: &HeaderMap,
) -> SlabResult<Principal> {
let principal = self.require_auth(jar, headers).await?;
if principal.permission != "write" {
return Err(SlabError::forbidden(
"access token does not have write permission",
));
}
Ok(principal)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration as StdDuration;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct InvitePayload {
user_id: String,
org_id: String,
}
fn test_auth() -> Auth {
Auth::for_signing("unit-test-secret-key-for-signed-tokens", false)
}
#[test]
fn sign_and_verify_token_roundtrip() {
let auth = test_auth();
let payload = InvitePayload {
user_id: "usr_01".to_string(),
org_id: "org_42".to_string(),
};
let token = auth
.sign_token("invite", &payload, StdDuration::from_secs(300))
.unwrap();
let decoded: InvitePayload = auth.verify_token("invite", &token).unwrap();
assert_eq!(decoded, payload);
}
#[test]
fn verify_token_rejects_wrong_purpose() {
let auth = test_auth();
let token = auth
.sign_token(
"email_verify",
&"usr_01".to_string(),
StdDuration::from_secs(300),
)
.unwrap();
let err = auth
.verify_token::<String>("password_reset", &token)
.unwrap_err();
assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
}
#[test]
fn verify_token_rejects_tampered_signature() {
let auth = test_auth();
let token = auth
.sign_token(
"download",
&"blb_123".to_string(),
StdDuration::from_secs(300),
)
.unwrap();
let (encoded, sig) = token.split_once('.').unwrap();
let flipped = if sig.starts_with('a') { 'b' } else { 'a' };
let tampered = format!("{encoded}.{flipped}{}", &sig[1..]);
let err = auth
.verify_token::<String>("download", &tampered)
.unwrap_err();
assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
}
#[test]
fn verify_token_rejects_expired_token() {
let auth = test_auth();
let zero_ttl = auth
.sign_token("reset", &"usr_01".to_string(), StdDuration::ZERO)
.unwrap();
let err = auth.verify_token::<String>("reset", &zero_ttl).unwrap_err();
assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
let past_envelope = SignedTokenEnvelopeRef {
p: "reset",
exp: Utc::now().timestamp() - 60,
d: &"usr_01",
};
let json = sqlx::types::Json(&past_envelope)
.encode_to_string()
.unwrap();
let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
let sig = auth.sign(&encoded);
let expired = format!("{encoded}.{sig}");
let err = auth.verify_token::<String>("reset", &expired).unwrap_err();
assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
}
}