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:
1 parent
a90ff81650
commit
2b1bc63340
11 files changed
+2455
-79
No files matched your search
@@ -12,9 +12,9 @@ pub mod tokens;
|
||||
|
||||
pub use audit::{AuditEntry, AuditEvent, AuditLog};
|
||||
pub use secrets::{hash_token, random_token, Secrets};
|
||||
pub use service::{AuthService, LoginStep, NewSession, PendingMfa, TotpEnrollment};
|
||||
pub use service::{AuthService, LoginStep, NewSession, PendingMfa, TotpEnrollment, UserView};
|
||||
pub use store::{ApiToken, AuthState, AuthStore, Bootstrap, Role, Scope, Session, User};
|
||||
pub use tokens::{NewToken, Principal, SessionView, TokenView, Via};
|
||||
pub use tokens::{csrf_matches, csrf_token, NewToken, Principal, SessionView, TokenView, Via};
|
||||
|
||||
use crate::error::Result;
|
||||
use fs2::FileExt;
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -945,3 +945,94 @@ fn change_password_clears_flag_and_refuses_the_same_password() {
|
||||
.unwrap();
|
||||
assert!(!flag);
|
||||
}
|
||||
|
||||
// ---- Enrollment through a pending token: re-checked inside the update ----
|
||||
|
||||
fn first_admin(s: &AuthService) -> PendingMfa {
|
||||
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
|
||||
s.complete_bootstrap(&code, "root", PW, T0).unwrap()
|
||||
}
|
||||
|
||||
fn root_id(s: &AuthService) -> String {
|
||||
s.store
|
||||
.read(|st| {
|
||||
st.users
|
||||
.iter()
|
||||
.find(|u| u.username == "root")
|
||||
.unwrap()
|
||||
.id
|
||||
.clone()
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn code_from_uri(uri: &str, unix: u64) -> String {
|
||||
totp_rs::Totp::from_url(uri)
|
||||
.unwrap()
|
||||
.generate(unix)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_enrollment_activates_mfa_and_then_refuses_the_token() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let s = AuthService::open(dir.path(), None).unwrap();
|
||||
let pending = first_admin(&s);
|
||||
let e = s.start_enrollment_pending(&pending.token, T0).unwrap();
|
||||
let codes = s
|
||||
.confirm_enrollment_pending(&pending.token, &code_from_uri(&e.uri, T0), T0)
|
||||
.unwrap();
|
||||
assert!(!codes.is_empty());
|
||||
// A password alone can never replace a second factor that is now active.
|
||||
assert!(s.start_enrollment_pending(&pending.token, T0).is_err());
|
||||
assert!(s
|
||||
.confirm_enrollment_pending(&pending.token, &code_from_uri(&e.uri, T0 + 30), T0 + 30)
|
||||
.is_err());
|
||||
// The same token still finishes the login, with a later code.
|
||||
let step = s
|
||||
.confirm_mfa(&pending.token, &code_from_uri(&e.uri, T0 + 30), T0 + 30)
|
||||
.unwrap();
|
||||
assert!(matches!(step, LoginStep::Session(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_enrollment_refuses_a_stale_epoch_and_other_purposes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let s = AuthService::open(dir.path(), None).unwrap();
|
||||
let pending = first_admin(&s);
|
||||
let e = s.start_enrollment_pending(&pending.token, T0).unwrap();
|
||||
let id = root_id(&s);
|
||||
s.store
|
||||
.update(|st| {
|
||||
st.users.iter_mut().find(|u| u.id == id).unwrap().auth_epoch += 1;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(s.start_enrollment_pending(&pending.token, T0).is_err());
|
||||
assert!(s
|
||||
.confirm_enrollment_pending(&pending.token, &code_from_uri(&e.uri, T0), T0)
|
||||
.is_err());
|
||||
assert!(s.start_enrollment_pending("forged", T0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_users_exposes_no_secret_material() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let s = AuthService::open(dir.path(), None).unwrap();
|
||||
first_admin(&s);
|
||||
let json = serde_json::to_string(&s.list_users().unwrap()).unwrap();
|
||||
assert!(json.contains("root"));
|
||||
for leak in ["password_hash", "recovery", "totp_", "$argon2"] {
|
||||
assert!(!json.contains(leak), "{leak} in {json}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csrf_value_is_bound_to_the_session_and_is_not_its_token_hash() {
|
||||
let a = crate::auth::tokens::csrf_token("session-a");
|
||||
assert_ne!(a, crate::auth::tokens::csrf_token("session-b"));
|
||||
assert_ne!(a, hash_token("session-a"));
|
||||
assert!(crate::auth::tokens::csrf_matches("session-a", &a));
|
||||
assert!(!crate::auth::tokens::csrf_matches("session-b", &a));
|
||||
assert!(!crate::auth::tokens::csrf_matches("session-a", ""));
|
||||
}
|
||||
@@ -85,6 +85,17 @@ pub struct TokenView {
|
||||
pub expires_at: u64,
|
||||
}
|
||||
|
||||
/// The anti-CSRF value of a session. Derived from the session token with a
|
||||
/// domain prefix, so it needs no storage, dies with the session, and differs
|
||||
/// from the digest kept in the store.
|
||||
pub fn csrf_token(session_token: &str) -> String {
|
||||
hash_token(&format!("acaua-csrf:{session_token}"))
|
||||
}
|
||||
|
||||
pub fn csrf_matches(session_token: &str, candidate: &str) -> bool {
|
||||
ct_eq(&csrf_token(session_token), candidate)
|
||||
}
|
||||
|
||||
fn ct_eq(a: &str, b: &str) -> bool {
|
||||
a.as_bytes().ct_eq(b.as_bytes()).into()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user