feat(auth): deny-by-default HTTP layer

A global middleware wraps the router and its fallback: only PUBLIC_ROUTES
answer without a credential, and unknown paths look like protected ones.
Adds cookie sessions with per-session CSRF, scoped Bearer tokens, the
/api/auth and /api/admin handlers, Transport for client IP and Secure, and
pending-token enrollment re-checked inside one store update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 19:51:42 -03:00
1 parent a90ff81650
commit 2b1bc63340
11 files changed
+2455 -79

No files matched your search

+94 -5
View File
@@ -87,6 +87,17 @@ impl std::fmt::Debug for TotpEnrollment {
}
}
/// Listing view of an account: no hash, no secret.
#[derive(Debug, Clone, Serialize)]
pub struct UserView {
pub id: String,
pub username: String,
pub role: Role,
pub created_at: u64,
pub mfa_enabled: bool,
pub must_change_password: bool,
}
#[derive(Serialize, Deserialize)]
struct PendingClaims {
purpose: String,
@@ -141,6 +152,15 @@ fn validate_username(username: &str) -> Result<String> {
Ok(name)
}
/// With a pending token's epoch: the account must still be the one the token
/// was issued for, and must still have no active second factor.
fn check_pending_epoch(u: &User, pending_epoch: Option<u64>) -> Result<()> {
match pending_epoch {
Some(epoch) if u.auth_epoch != epoch || u.totp_sealed.is_some() => Err(invalid()),
_ => Ok(()),
}
}
fn has_admin(st: &AuthState) -> bool {
st.users.iter().any(|u| u.role == Role::Admin)
}
@@ -564,8 +584,31 @@ impl AuthService {
}
/// Starts (or restarts) enrollment. An active secret stays in force until
/// `confirm_enrollment` replaces it.
/// `confirm_enrollment` replaces it. Callers must have checked that the
/// actor may do this; a pending token goes through
/// `start_enrollment_pending`.
pub fn start_enrollment(&self, user_id: &str, _now: u64) -> Result<TotpEnrollment> {
self.start_enrollment_guarded(user_id, None)
}
/// Enrollment with only a pending token. `pending_user` alone would leave
/// a gap: the token is re-checked inside the update that stores the secret.
pub fn start_enrollment_pending(&self, pending: &str, now: u64) -> Result<TotpEnrollment> {
let claims = self.open_pending(pending, PENDING_PURPOSE, now)?;
self.start_enrollment_guarded(&claims.user_id, Some(claims.epoch))
}
fn start_enrollment_guarded(
&self,
user_id: &str,
pending_epoch: Option<u64>,
) -> Result<TotpEnrollment> {
let missing = || -> AcauaError {
match pending_epoch {
Some(_) => invalid(),
None => AuthFailure::UserNotFound.into(),
}
};
let name = self
.store
.read(|st| {
@@ -574,7 +617,7 @@ impl AuthService {
.find(|u| u.id == user_id)
.map(|u| u.username.clone())
})?
.ok_or(AuthFailure::UserNotFound)?;
.ok_or_else(missing)?;
let secret = new_totp_secret();
let (uri, qr_png_base64) = totp_uri_and_qr(&secret, &name)?;
let manual_key = manual_key(&uri).ok_or_else(|| {
@@ -582,7 +625,9 @@ impl AuthService {
})?;
let sealed = self.secrets.seal(&secret)?;
self.store.update(|st| {
user_or_missing(st, user_id)?.totp_pending_sealed = Some(sealed);
let u = user_mut(st, user_id).ok_or_else(missing)?;
check_pending_epoch(u, pending_epoch)?;
u.totp_pending_sealed = Some(sealed);
Ok(())
})?;
self.log("mfa.enroll.start", Some(&name), None, true, None)?;
@@ -595,11 +640,38 @@ impl AuthService {
/// Activates the started secret and returns the recovery codes, shown only
/// here. The accepted step is spent, so finishing a login needs a later
/// code. Ends every session of the user.
/// code. Ends every session of the user. A pending token goes through
/// `confirm_enrollment_pending`.
pub fn confirm_enrollment(&self, user_id: &str, code: &str, now: u64) -> Result<Vec<String>> {
self.confirm_enrollment_guarded(user_id, None, code, now)
}
/// As `start_enrollment_pending`: two racing requests get one activation,
/// and the loser cannot replace the factor the winner just set.
pub fn confirm_enrollment_pending(
&self,
pending: &str,
code: &str,
now: u64,
) -> Result<Vec<String>> {
let claims = self.open_pending(pending, PENDING_PURPOSE, now)?;
self.confirm_enrollment_guarded(&claims.user_id, Some(claims.epoch), code, now)
}
fn confirm_enrollment_guarded(
&self,
user_id: &str,
pending_epoch: Option<u64>,
code: &str,
now: u64,
) -> Result<Vec<String>> {
let (texts, hashes) = new_recovery_codes();
let (name, accepted) = self.store.update(|st| {
let u = user_or_missing(st, user_id)?;
let u = match pending_epoch {
Some(_) => user_mut(st, user_id).ok_or_else(invalid)?,
None => user_or_missing(st, user_id)?,
};
check_pending_epoch(u, pending_epoch)?;
let sealed = u
.totp_pending_sealed
.clone()
@@ -626,6 +698,23 @@ impl AuthService {
Ok(texts)
}
/// Every account, without credentials. Authorization is the caller's.
pub fn list_users(&self) -> Result<Vec<UserView>> {
self.store.read(|st| {
st.users
.iter()
.map(|u| UserView {
id: u.id.clone(),
username: u.username.clone(),
role: u.role,
created_at: u.created_at,
mfa_enabled: u.totp_sealed.is_some(),
must_change_password: u.must_change_password,
})
.collect()
})
}
/// `actor` names who acted, for the audit log. Authorization is the
/// caller's. Returns the new user's id.
pub fn create_user(