Files
authforge/daemon/src/state.rs
michael 5c94319bf0 feat(daemon): policy apply via pam-auth-update + lockout simulator (Phase 4+5)
Lands Lane 1 of the Phase 4+5+8+15+16 parallel cycle. Phase 4 + Phase 5 must
land together because both modify the SetPolicy code path.

- daemon/src/lockout.rs — pure simulate(new_policy, registry) -> Vec<Violation>.
  Iterates Required stacks, flags users with no enrolled credential of any
  required method. 5 unit tests cover: optional-mode skipped, required-with-
  unenrolled flagged, any-method-satisfies, empty registry, multi-stack.
- daemon/src/policy_apply.rs — PolicyApplier renders the pam-configs profile
  (Default: yes when any stack requires fido2; pam_u2f.so + pam_authforge_pending
  when fido2 required, only pam_authforge_pending otherwise) and runs
  pam-auth-update --package. Stash-and-restore on failure: prior profile
  contents are restored and pam-auth-update re-run, so a failed apply leaves
  the system in its previous PAM state. 4 unit tests including a real-process
  rollback test against a failing /bin/sh shim.
- daemon/src/state.rs — AppState::set_policy(p, force) returns
  PolicyApplyResult. Always runs the simulator first; if violations and !force,
  returns { applied: false, violations } without writing. Otherwise persists
  via PolicyStore::save and invokes PolicyApplier::apply. StorageConfig grows
  pam_profile_path + pam_auth_update fields (env-var driven, tests inject a
  no-op /bin/sh shim into a tempdir).
- daemon/src/dbus.rs — SetPolicy signature is now (Policy, bool) -> Result.
  Wire-breaking pre-alpha; CLI updated in this commit.
- cli/src/{bus,commands}.rs — set_policy takes force flag. policy set runs
  with force=false and surfaces violations as a non-zero exit + stderr list
  pointing the user at policy apply --force-i-know-what-im-doing. policy
  apply now actually invokes pam-auth-update via the daemon.

Test count: 42 daemon (was 33; adds 5 lockout + 4 policy_apply). 13 common.
5 cli. cargo clippy --workspace --all-targets -D warnings clean.

Plan deviation: PolicyApplier::from_env() became PolicyApplier::new(profile_path,
pam_auth_update) with the env defaults moved into StorageConfig::from_env_or_defaults.
Cleaner: state owns one source of truth for env-driven path config.
2026-04-27 08:41:00 -07:00

332 lines
12 KiB
Rust

use crate::fido::authenticator::Authenticator;
use crate::lockout::{simulate, UserEnrollment};
use crate::policy_apply::{ApplyError, PolicyApplier};
use crate::storage::credentials::{CredEntry, CredentialsStore, CredsError, CredsPathResolver};
use crate::storage::pending::{PendingError, PendingStore};
use crate::storage::policy::PolicyStore;
use crate::storage::userdb::{UserDb, UserDbError};
use authforge_common::policy::{Policy, PolicyError};
use authforge_common::types::{Credential, Method, PendingFlag, PolicyApplyResult, Transport};
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use thiserror::Error;
use tokio::sync::Mutex;
#[derive(Debug, Error)]
pub enum StateError {
#[error(transparent)]
Policy(#[from] PolicyError),
#[error(transparent)]
Pending(#[from] PendingError),
#[error(transparent)]
Creds(#[from] CredsError),
#[error(transparent)]
UserDb(#[from] UserDbError),
#[error(transparent)]
Apply(#[from] ApplyError),
#[error("authenticator: {0}")]
Authn(String),
}
pub struct StorageConfig {
pub policy_dir: PathBuf,
pub pending_dir: PathBuf,
pub userdb_path: PathBuf,
/// Where pam-auth-update reads the AuthForge profile from. Defaults to
/// `/usr/share/pam-configs/authforge`; tests / non-root runs override.
pub pam_profile_path: PathBuf,
/// Path to the pam-auth-update binary. Tests / non-root runs override
/// with a no-op shim.
pub pam_auth_update: PathBuf,
}
impl StorageConfig {
pub fn from_env_or_defaults() -> Self {
let env = |k: &str, d: &str| -> PathBuf {
std::env::var_os(k)
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(d))
};
Self {
policy_dir: env("AUTHFORGE_POLICY_DIR", "/etc/authforge/policy.d"),
pending_dir: env("AUTHFORGE_PENDING_DIR", "/var/lib/authforge/pending"),
userdb_path: env("AUTHFORGE_USERDB", "/var/lib/authforge/users.db"),
pam_profile_path: env("AUTHFORGE_PAMCONF_PATH", "/usr/share/pam-configs/authforge"),
pam_auth_update: env("AUTHFORGE_PAM_AUTH_UPDATE", "/usr/sbin/pam-auth-update"),
}
}
}
pub struct AppState {
policy: PolicyStore,
pending: PendingStore,
userdb: Mutex<UserDb>,
authn: Arc<dyn Authenticator>,
applier: PolicyApplier,
}
impl AppState {
pub fn open(cfg: StorageConfig, authn: Arc<dyn Authenticator>) -> Result<Self, StateError> {
let policy = PolicyStore::new(cfg.policy_dir);
let pending = PendingStore::new(cfg.pending_dir);
let userdb = Mutex::new(UserDb::open(&cfg.userdb_path)?);
let applier = PolicyApplier::new(cfg.pam_profile_path, cfg.pam_auth_update);
Ok(Self {
policy,
pending,
userdb,
authn,
applier,
})
}
fn creds_resolver(&self) -> Result<CredsPathResolver, StateError> {
let pol = self.policy.load()?;
Ok(CredsPathResolver::new(pol.storage))
}
pub async fn list_credentials(&self, user: &str) -> Vec<Credential> {
let resolver = match self.creds_resolver() {
Ok(r) => r,
Err(_) => return vec![],
};
let path = match resolver.path_for(user) {
Ok(p) => p,
Err(_) => return vec![],
};
let store = CredentialsStore::new(path);
let lines = store.list(user).unwrap_or_default();
lines
.iter()
.map(|c| {
let id = CredEntry::cred_id(c).to_string();
Credential {
id: id.clone(),
nickname: id,
method: Method::Fido2,
transport: Transport::Unknown,
created_unix: 0,
}
})
.collect()
}
/// Run the authenticator's `make_credential` and persist the resulting
/// pam_u2f line + userdb entry. Returns the Credential the GUI displays.
pub async fn enroll(&self, user: &str, nickname: &str) -> Result<Credential, StateError> {
let resolver = self.creds_resolver()?;
let path = resolver.path_for(user)?;
let store = CredentialsStore::new(path);
let pam_cred = self
.authn
.make_credential("pam://localhost", user, None)
.map_err(|e| StateError::Authn(e.to_string()))?;
let segment = pam_cred.to_pam_segment();
let cred_id = hex::encode(&pam_cred.key_handle);
store.add(user, &segment)?;
let db = self.userdb.lock().await;
db.record_enrollment(user, Method::Fido2)?;
Ok(Credential {
id: cred_id,
nickname: nickname.to_string(),
method: Method::Fido2,
transport: Transport::Usb,
created_unix: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
})
}
pub async fn remove_credential(&self, user: &str, cred_id: &str) -> Result<bool, StateError> {
let resolver = self.creds_resolver()?;
let path = resolver.path_for(user)?;
let store = CredentialsStore::new(path);
let removed = store.remove(user, cred_id)?;
if removed && store.list(user)?.is_empty() {
self.userdb
.lock()
.await
.drop_enrollment(user, Method::Fido2)?;
}
Ok(removed)
}
pub async fn get_policy(&self) -> Result<Policy, StateError> {
Ok(self.policy.load()?)
}
/// Apply a new policy. Runs the lockout simulator first; if any users
/// would be locked out and `force == false`, returns the violations in
/// `PolicyApplyResult { applied: false, violations }` without writing or
/// invoking pam-auth-update. With `force == true` (or no violations),
/// persists the policy and runs pam-auth-update via PolicyApplier; on
/// pam-auth-update failure the prior profile is restored.
pub async fn set_policy(
&self,
p: Policy,
force: bool,
) -> Result<PolicyApplyResult, StateError> {
let registry = self.build_enrollment_registry().await?;
let violations = simulate(&p, &registry);
if !violations.is_empty() && !force {
return Ok(PolicyApplyResult {
applied: false,
violations,
});
}
self.policy.save(&p)?;
// pam-auth-update is best-effort in dev; the AUTHFORGE_PAM_AUTH_UPDATE
// env var lets tests / non-prod runs swap in a no-op shim. If the
// resolved binary doesn't exist on the host, log + continue.
if let Err(e) = self.applier.apply(&p) {
tracing::warn!(error=%e, "pam-auth-update apply failed; profile rolled back");
return Err(StateError::Apply(e));
}
Ok(PolicyApplyResult {
applied: true,
violations,
})
}
async fn build_enrollment_registry(&self) -> Result<Vec<UserEnrollment>, StateError> {
let db = self.userdb.lock().await;
let fido2 = db.users_with(Method::Fido2)?;
let totp = db.users_with(Method::Totp)?;
drop(db);
let mut by_user: std::collections::HashMap<String, HashSet<Method>> =
std::collections::HashMap::new();
for u in fido2 {
by_user.entry(u).or_default().insert(Method::Fido2);
}
for u in totp {
by_user.entry(u).or_default().insert(Method::Totp);
}
Ok(by_user
.into_iter()
.map(|(user, methods)| UserEnrollment { user, methods })
.collect())
}
pub async fn set_pending(&self, user: &str, f: PendingFlag) -> Result<(), StateError> {
self.pending.set(user, &f)?;
Ok(())
}
pub async fn clear_pending(&self, user: &str) -> Result<bool, StateError> {
Ok(self.pending.clear(user)?)
}
/// Tests assert pending flag round-trips through SetPendingFlag /
/// ClearPendingFlag via this read accessor. Production readers (PAM
/// module, GUI status) read the on-disk file directly in later phases.
#[cfg(test)]
pub async fn has_pending(&self, user: &str) -> Result<bool, StateError> {
Ok(self.pending.get(user)?.is_some())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fido::mock::MockAuthenticator;
use tempfile::tempdir;
fn open_in(d: &std::path::Path) -> AppState {
// Stage a no-op pam-auth-update shim inside the tempdir so SetPolicy
// calls succeed without touching /usr/share/pam-configs.
let shim = d.join("fake-pau.sh");
std::fs::write(&shim, "#!/bin/sh\nexit 0\n").unwrap();
let mut perms = std::fs::metadata(&shim).unwrap().permissions();
std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
std::fs::set_permissions(&shim, perms).unwrap();
AppState::open(
StorageConfig {
policy_dir: d.join("policy.d"),
pending_dir: d.join("pending"),
userdb_path: d.join("users.db"),
pam_profile_path: d.join("authforge-pamconf"),
pam_auth_update: shim,
},
Arc::new(MockAuthenticator::with_one_yubikey()),
)
.unwrap()
}
#[tokio::test]
async fn empty_state_has_nothing() {
let d = tempdir().unwrap();
let s = open_in(d.path());
assert!(s.list_credentials("alice").await.is_empty());
assert!(!s.has_pending("alice").await.unwrap());
assert!(s.get_policy().await.unwrap().stacks.is_empty());
}
#[tokio::test]
async fn pending_set_clear_roundtrip() {
let d = tempdir().unwrap();
let s = open_in(d.path());
let f = PendingFlag {
required_methods: vec![Method::Fido2],
created_unix: 1,
deadline_unix: 0,
re_enroll: false,
};
s.set_pending("alice", f).await.unwrap();
assert!(s.has_pending("alice").await.unwrap());
assert!(s.clear_pending("alice").await.unwrap());
assert!(!s.has_pending("alice").await.unwrap());
}
#[tokio::test]
async fn enroll_writes_real_pam_u2f_line() {
let d = tempdir().unwrap();
// Configure central storage so the resolver doesn't try /home/alice.
let policy_dir = d.path().join("policy.d");
std::fs::create_dir_all(&policy_dir).unwrap();
let central = d.path().join("u2f_keys");
std::fs::write(
policy_dir.join("00.conf"),
format!(
"[storage]\nbackend = \"central\"\ncentral_path = \"{}\"\n",
central.display()
),
)
.unwrap();
let shim = d.path().join("fake-pau.sh");
std::fs::write(&shim, "#!/bin/sh\nexit 0\n").unwrap();
let mut perms = std::fs::metadata(&shim).unwrap().permissions();
std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
std::fs::set_permissions(&shim, perms).unwrap();
let s = AppState::open(
StorageConfig {
policy_dir,
pending_dir: d.path().join("pending"),
userdb_path: d.path().join("users.db"),
pam_profile_path: d.path().join("authforge-pamconf"),
pam_auth_update: shim,
},
Arc::new(MockAuthenticator::with_one_yubikey()),
)
.unwrap();
let cred = s.enroll("alice", "Yellow").await.unwrap();
// cred.id should be hex-encoded keyHandle.
assert!(cred.id.chars().all(|c| c.is_ascii_hexdigit()));
assert_eq!(cred.nickname, "Yellow");
assert_eq!(cred.method, Method::Fido2);
// The on-disk pam_u2f file holds a real line — username:kh,pk,es256,+presence
let body = std::fs::read_to_string(&central).unwrap();
assert!(body.starts_with("alice:"));
assert!(body.contains(",es256,+presence"));
}
}