Files
sausage/host/src/cred/webauthn.rs
T
surma 1dc09bc418 cred: add passkey challenges and encrypted secret entry
Validation remains blocked by rusqlite u64 conversions in cred/grants.rs, which T19 owns.
2026-11-06 19:04:42 +00:00

248 lines
8.1 KiB
Rust

//! Passkey enrollment and single-use assertions for host-owned bindings.
//! The caller supplies cred.sqlite and serializes access to this manager.
//! Browser responses and challenges use WebAuthn JSON. Enrollment assertions
//! must bind the exact new label. Neither decision nor secret-entry assertions
//! authorize enrollment. Without passkeys, the host is unlocked and permits
//! first registration without a gate. Restart drops all pending challenges.
use anyhow::{Result, bail};
use rusqlite::{Connection, params};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
time::{Duration, Instant},
};
use webauthn_rs::prelude::*;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Binding {
Decision {
request_id: String,
decision: String,
overrides: serde_json::Value,
},
SecretEntry {
item: String,
field: String,
ciphertext_sha256: String,
},
Enrollment {
label: String,
},
}
#[derive(Serialize, Deserialize)]
pub struct Gate {
pub id: String,
pub response: PublicKeyCredential,
}
#[derive(Serialize, Deserialize)]
pub struct Challenge<T> {
pub id: String,
pub options: T,
}
struct Pending<T> {
deadline: Instant,
value: T,
}
pub struct Passkeys<'a> {
db: &'a Connection,
webauthn: Webauthn,
registrations: HashMap<String, Pending<(String, bool, PasskeyRegistration)>>,
assertions: HashMap<String, Pending<(Binding, PasskeyAuthentication)>>,
}
impl<'a> Passkeys<'a> {
pub fn new(db: &'a Connection, rp_id: &str, origin: &str) -> Result<Self> {
let origin = Url::parse(origin)?;
let webauthn = WebauthnBuilder::new(rp_id, &origin)?.build()?;
db.execute_batch(
"CREATE TABLE IF NOT EXISTS passkey_credentials (
id TEXT PRIMARY KEY, label TEXT NOT NULL, credential TEXT NOT NULL)",
)?;
Ok(Self {
db,
webauthn,
registrations: HashMap::new(),
assertions: HashMap::new(),
})
}
/// Database errors leave the manager locked.
pub fn is_unlocked(&self) -> bool {
self.db
.query_row(
"SELECT NOT EXISTS(SELECT 1 FROM passkey_credentials)",
[],
|row| row.get(0),
)
.unwrap_or(false)
}
fn credentials(&self) -> Result<Vec<Passkey>> {
let mut stmt = self
.db
.prepare("SELECT credential FROM passkey_credentials")?;
let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
rows.map(|row| Ok(serde_json::from_str(&row?)?)).collect()
}
pub fn start_registration(
&mut self,
label: String,
gate: Option<Gate>,
) -> Result<Challenge<CreationChallengeResponse>> {
let gated = gate.is_some();
match gate {
None if !self.is_unlocked() => bail!("enrollment assertion required"),
None => {}
Some(Gate { id, response }) => {
let (_, binding) = self.finish_assertion(&id, response)?;
if binding
!= (Binding::Enrollment {
label: label.clone(),
})
{
bail!("invalid enrollment gate");
}
}
}
let exclude = self
.credentials()?
.iter()
.map(|p| p.cred_id().clone())
.collect();
let (options, state) = self.webauthn.start_passkey_registration(
Uuid::new_v4(),
&label,
&label,
Some(exclude),
)?;
self.registrations
.retain(|_, p| p.deadline > Instant::now());
let id = Uuid::new_v4().to_string();
self.registrations.insert(
id.clone(),
Pending {
deadline: Instant::now() + Duration::from_secs(300),
value: (label, gated, state),
},
);
Ok(Challenge { id, options })
}
pub fn finish_registration(
&mut self,
id: &str,
response: RegisterPublicKeyCredential,
) -> Result<Passkey> {
let (label, gated, state) = take(&mut self.registrations, id)?;
if !gated && !self.is_unlocked() {
bail!("enrollment assertion required");
}
let credential = self
.webauthn
.finish_passkey_registration(&response, &state)?;
self.db.execute(
"INSERT INTO passkey_credentials (id, label, credential) VALUES (?1, ?2, ?3)",
params![
serde_json::to_string(credential.cred_id())?,
label,
serde_json::to_string(&credential)?
],
)?;
Ok(credential)
}
pub fn start_assertion(
&mut self,
binding: Binding,
) -> Result<Challenge<RequestChallengeResponse>> {
let (options, state) = self
.webauthn
.start_passkey_authentication(&self.credentials()?)?;
self.assertions.retain(|_, p| p.deadline > Instant::now());
let id = Uuid::new_v4().to_string();
self.assertions.insert(
id.clone(),
Pending {
deadline: Instant::now() + Duration::from_secs(300),
value: (binding, state),
},
);
Ok(Challenge { id, options })
}
pub fn finish_assertion(
&mut self,
id: &str,
response: PublicKeyCredential,
) -> Result<(CredentialID, Binding)> {
let (binding, state) = take(&mut self.assertions, id)?;
let result = self
.webauthn
.finish_passkey_authentication(&response, &state)?;
let mut credentials = self.credentials()?;
let credential = credentials
.iter_mut()
.find(|p| p.cred_id() == result.cred_id())
.ok_or_else(|| anyhow::anyhow!("unregistered passkey"))?;
// Check the latest stored counter too. Another outstanding assertion may
// contain an older snapshot of this credential.
let stored = serde_json::to_value(&*credential)?;
let counter = stored["cred"]["counter"]
.as_u64()
.ok_or_else(|| anyhow::anyhow!("invalid stored passkey counter"))?;
if (counter > 0 || result.counter() > 0) && u64::from(result.counter()) <= counter {
bail!("passkey counter did not increase");
}
credential.update_credential(&result);
self.db.execute(
"UPDATE passkey_credentials SET credential = ?1 WHERE id = ?2",
params![
serde_json::to_string(credential)?,
serde_json::to_string(result.cred_id())?
],
)?;
Ok((result.cred_id().clone(), binding))
}
}
fn take<T>(map: &mut HashMap<String, Pending<T>>, id: &str) -> Result<T> {
let pending = map
.remove(id)
.ok_or_else(|| anyhow::anyhow!("unknown or consumed challenge"))?;
if pending.deadline <= Instant::now() {
bail!("expired challenge");
}
Ok(pending.value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expired_assertion() -> Result<()> {
use webauthn_authenticator_rs::{WebauthnAuthenticator, softpasskey::SoftPasskey};
let db = Connection::open_in_memory()?;
let mut host = Passkeys::new(&db, "localhost", "http://localhost:8000")?;
let start = host.start_registration("test".into(), None)?;
let mut auth = WebauthnAuthenticator::new(SoftPasskey::new(true));
let origin = Url::parse("http://localhost:8000")?;
let response = auth.do_registration(origin.clone(), start.options)?;
host.finish_registration(&start.id, response)?;
let start = host.start_assertion(Binding::Enrollment {
label: "next".into(),
})?;
let response = auth.do_authentication(origin, start.options)?;
host.assertions.get_mut(&start.id).unwrap().deadline = Instant::now();
assert!(host.finish_assertion(&start.id, response).is_err());
assert!(!host.assertions.contains_key(&start.id));
Ok(())
}
}