~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
576 lines · 20.6 KB Raw History
//! Passkeys (`spec/PASSKEYS.md`): an account signs in on the authorization
//! page with a WebAuthn credential instead of its password, and adds one
//! through a link it asks for with its password session.
//!
//! The account's routes, `_passkeyList`, `_passkeyAdd` and
//! `_passkeyRemove`, are answered as the account's OAuth routes are
//! (`super::account`), what each does here (`act`); the page a link opens
//! is `page`, and the API's calls `passkey-register` (`register`),
//! `passkey-options` (`options`) and `passkey-sign-in` (`sign_in`). What a
//! credential is checked for is `webauthn`, reading CBOR with `cbor`.
//!
//! Each passkey is kept with what OAuth keeps (`Kept`, in `State`),
//! changed by entries of `accounts.log`: `oauthPasskeyAdd`,
//! `oauthPasskeyUse` (in the frame of the sign-in it made) and
//! `oauthPasskeyRemove`; a deletion forgets an account's. An account's user
//! handle is made from its DID under OAuth's secret (`OAuth::user_handle`),
//! so it is kept nowhere. Links and sign-in challenges are held in memory
//! alone (`Held`), under a lock taken after OAuth's, never before.

pub(super) mod cbor;
#[cfg(test)]
pub(crate) mod tests;
pub(super) mod webauthn;

use super::account::Route;
use super::page::{self, Device, Refusal};
use super::{State, Tx, Whence, low};
use crate::{Service, Shared, XrpcError, invalid};
use axum::extract::State as AxState;
use axum::http::{HeaderMap, Method, StatusCode, Uri};
use axum::response::{IntoResponse, Response};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use serde_json::{Map, Value as Json, json};
use std::collections::HashMap;

/// The kinds of `accounts.log` entry passkeys keep, among OAuth's.
pub(super) const ENTRIES: [&str; 3] = ["oauthPasskeyAdd", "oauthPasskeyUse", "oauthPasskeyRemove"];

/// The most passkeys an account has.
pub(super) const MAX: usize = 20;
/// How long a link holds, in milliseconds.
const LINK_LIFE: u64 = 900_000;
/// How long a sign-in challenge is held, in seconds.
const CHALLENGE_LIFE: u64 = 300;
/// The `timeout` the options give the browser, in milliseconds.
const TIMEOUT: u64 = 300_000;

/// A passkey, as kept.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Passkey {
    did: String,
    /// Its public key, of ES256 or RS256.
    key: webauthn::Key,
    count: u32,
    be: bool,
    bs: bool,
    transports: Vec<String>,
    name: String,
    /// When it was added, and last signed in, in milliseconds since the epoch.
    created: u64,
    used: Option<u64>,
}

/// The passkeys kept.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Kept {
    /// Every passkey, by its credential ID, base64url.
    by_id: HashMap<String, Passkey>,
}

impl Kept {
    /// Make the change an entry of `ENTRIES` says, of account `did`.
    pub(super) fn apply(&mut self, e: &Json, did: String) -> Result<(), String> {
        let text = |k: &str| {
            e[k].as_str()
                .map(str::to_string)
                .ok_or_else(|| format!("an entry with no {k}: {e}"))
        };
        let number = |k: &str| {
            e[k].as_u64()
                .ok_or_else(|| format!("an entry with no {k}: {e}"))
        };
        let count =
            || u32::try_from(number("count")?).map_err(|_| format!("a count out of range: {e}"));
        let flag = |k: &str| {
            e[k].as_bool()
                .ok_or_else(|| format!("an entry with no {k}: {e}"))
        };
        let id = text("id")?;
        let theirs = self.by_id.get(&id).is_some_and(|p| p.did == did);
        let not_theirs = || format!("an entry of passkey {id}, which {did} has not");
        match e["t"].as_str() {
            Some("oauthPasskeyAdd") => {
                if self.by_id.contains_key(&id) {
                    return Err(format!("a second passkey {id}"));
                }
                let bytes = |k: &str| {
                    B64.decode(text(k)?)
                        .map_err(|_| format!("a passkey whose {k} is not base64url: {e}"))
                };
                // An entry with no `alg` is of ES256, as all were before RS256.
                let key = match e["alg"].as_i64() {
                    None | Some(-7) => webauthn::Key::Es256(bytes("key")?),
                    Some(-257) => webauthn::Key::Rs256 {
                        n: bytes("key")?,
                        e: bytes("e")?,
                    },
                    Some(alg) => return Err(format!("a passkey of algorithm {alg}: {e}")),
                };
                let transports = super::strings(&e["transports"])
                    .ok_or_else(|| format!("an entry with no transports: {e}"))?;
                let p = Passkey {
                    did,
                    key,
                    count: count()?,
                    be: flag("be")?,
                    bs: flag("bs")?,
                    transports,
                    name: text("name")?,
                    created: number("at")?,
                    used: None,
                };
                self.by_id.insert(id, p);
            }
            Some("oauthPasskeyUse") => {
                let (n, bs, at) = (count()?, flag("bs")?, number("at")?);
                let Some(p) = self.by_id.get_mut(&id).filter(|_| theirs) else {
                    return Err(not_theirs());
                };
                (p.count, p.bs, p.used) = (n, bs, Some(at));
            }
            Some("oauthPasskeyRemove") => {
                if !theirs {
                    return Err(not_theirs());
                }
                self.by_id.remove(&id);
            }
            t => return Err(format!("a passkey entry of no known type: {t:?}")),
        }
        Ok(())
    }

    /// Forget every passkey of account `did`: it was deleted.
    pub(super) fn forget_account(&mut self, did: &str) {
        self.by_id.retain(|_, p| p.did != did);
    }

    /// Whether any passkey is kept.
    pub(super) fn any(&self) -> bool {
        !self.by_id.is_empty()
    }

    /// The credential IDs of `did`'s passkeys, in order.
    fn ids_of(&self, did: &str) -> Vec<&String> {
        let mut ids: Vec<&String> = self
            .by_id
            .iter()
            .filter(|(_, p)| p.did == did)
            .map(|(id, _)| id)
            .collect();
        ids.sort();
        ids
    }

    /// The entries that remove every passkey of `did`.
    pub(super) fn removals(&self, did: &str) -> Vec<Json> {
        self.ids_of(did)
            .into_iter()
            .map(|id| json!({ "t": "oauthPasskeyRemove", "did": did, "id": id }))
            .collect()
    }
}

/// A link that adds a passkey (`spec/PASSKEYS.md`, "_passkeyAdd").
#[derive(Clone)]
struct Link {
    token: String,
    name: String,
    /// Its challenge, base64url.
    challenge: String,
    /// When it ends, in milliseconds since the epoch.
    expires: u64,
}

/// What passkeys hold in memory alone.
#[derive(Default)]
pub(crate) struct Held {
    /// Each account's link.
    links: HashMap<String, Link>,
    /// Each device's sign-in challenge, base64url, and when it ends, in seconds.
    challenges: HashMap<String, (String, u64)>,
    /// When the challenges past their time are next forgotten.
    next_forget: u64,
}

impl Held {
    /// The link `token` names, of its account, if it holds at `now_ms`.
    fn link(&self, token: &str, now_ms: u64) -> Option<(String, Link)> {
        self.links
            .iter()
            .find(|(_, l)| l.token == token && now_ms < l.expires)
            .map(|(did, l)| (did.clone(), l.clone()))
    }

    /// End account `did`'s link.
    pub(super) fn end_for(&mut self, did: &str) {
        self.links.remove(did);
    }
}

/// 32 random bytes, base64url.
fn random() -> String {
    B64.encode(rand::random::<[u8; 32]>())
}

/// Milliseconds since the epoch as a datetime, in UTC to the millisecond.
fn datetime(ms: u64) -> String {
    pds_repo::data::datetime_string(i64::try_from(ms).unwrap_or(i64::MAX))
}

/// The relying party: the issuer's host, without its port, and the issuer
/// (`spec/PASSKEYS.md`, "The relying party").
fn rp_id(svc: &Service) -> String {
    url::Url::parse(&svc.oauth.issuer)
        .ok()
        .and_then(|u| u.host_str().map(str::to_string))
        .unwrap_or_default()
}

/// Whether account `did` may have its link: there, neither taken down nor
/// deleted. Read under OAuth's lock, which a change of its state takes first.
fn usable(svc: &Service, did: &str) -> bool {
    svc.account(did).is_some_and(|a| {
        let state = crate::read(&a.state);
        !state.deleted && state.takedown.is_none()
    })
}

/// What a passkey route does for account `did`, with its argument (`name`
/// or `id`), under OAuth's lock: the entries to log, and the answer.
pub(super) fn act(
    svc: &Service,
    st: &State,
    route: Route,
    did: &str,
    arg: &str,
) -> (Vec<Json>, Result<Json, XrpcError>) {
    let kept = &st.passkeys;
    match route {
        Route::PasskeyAdd => {
            if kept.ids_of(did).len() >= MAX {
                return (
                    vec![],
                    invalid(format!("An account has at most {MAX} passkeys")),
                );
            }
            let mut held = svc.oauth.held();
            let link = Link {
                token: random(),
                name: arg.to_string(),
                challenge: random(),
                expires: svc.sessions.now_ms() + LINK_LIFE,
            };
            let answer = json!({
                "url": format!("{}/oauth/passkey?token={}", svc.oauth.issuer, link.token),
                "expiresAt": datetime(link.expires),
            });
            held.links.insert(did.to_string(), link);
            (vec![], Ok(answer))
        }
        Route::PasskeyRemove => (
            kept.by_id
                .get(arg)
                .filter(|p| p.did == did)
                .map(|_| json!({ "t": "oauthPasskeyRemove", "did": did, "id": arg }))
                .into_iter()
                .collect(),
            Ok(json!({})),
        ),
        _ => {
            let mut listed: Vec<(&String, &Passkey)> =
                kept.by_id.iter().filter(|(_, p)| p.did == did).collect();
            listed.sort_by(|a, b| b.1.created.cmp(&a.1.created).then_with(|| a.0.cmp(b.0)));
            let passkeys: Vec<Json> = listed
                .into_iter()
                .map(|(id, p)| {
                    let mut j = json!({ "id": id, "name": p.name, "createdAt": datetime(p.created), "backedUp": p.bs });
                    if let Some(at) = p.used {
                        j["lastUsedAt"] = json!(datetime(at));
                    }
                    j
                })
                .collect();
            (vec![], Ok(json!({ "passkeys": passkeys })))
        }
    }
}

/// `GET /oauth/passkey?token=<token>`: the page a link opens
/// (`spec/PASSKEYS.md`, "The passkey page"). It keeps nothing.
pub(super) async fn passkey_page(
    AxState(svc): AxState<Shared>,
    method: Method,
    headers: HeaderMap,
    uri: Uri,
) -> Response {
    if method != Method::GET {
        return StatusCode::NOT_FOUND.into_response();
    }
    if !page::navigation(
        &svc,
        &headers,
        &["same-origin", "same-site", "cross-site", "none"],
    ) {
        return page::bad_page("This page must be navigated to");
    }
    let q = page::query(&uri);
    let Some(token) = page::param(&q, "token") else {
        return page::bad_page("token is required");
    };
    let now_ms = svc.sessions.now_ms();
    let Some((did, link)) = svc.oauth.held().link(token, now_ms) else {
        return page::bad_page("Unknown or ended link");
    };
    let Some(account) = svc.account(&did).filter(|_| usable(&svc, &did)) else {
        return page::bad_page("Unknown or ended link");
    };
    let shown = page::account_json(&svc, &account);
    let mut who = json!({ "did": shown["did"], "handle": shown["handle"] });
    for k in ["name", "picture"] {
        if let Some(v) = shown.get(k) {
            who[k] = v.clone();
        }
    }
    let (handle, exclude) = {
        let st = svc.oauth.lock();
        let kept = &st.passkeys;
        let exclude: Vec<Json> = kept
            .ids_of(&did)
            .into_iter()
            .map(|id| {
                let mut c = json!({ "type": "public-key", "id": id });
                let p = &kept.by_id[id];
                if !p.transports.is_empty() {
                    c["transports"] = json!(p.transports);
                }
                c
            })
            .collect();
        (B64.encode(svc.oauth.user_handle(&did)), exclude)
    };
    let rp = rp_id(&svc);
    let display = shown["name"]
        .as_str()
        .unwrap_or(account.handle().as_str())
        .to_string();
    let data = json!({
        "account": who,
        "name": link.name,
        "expiresAt": datetime(link.expires),
        "options": {
            "rp": { "id": rp, "name": rp },
            "user": { "id": handle, "name": account.handle(), "displayName": display },
            "challenge": link.challenge,
            "pubKeyCredParams": [{ "type": "public-key", "alg": -7 }, { "type": "public-key", "alg": -257 }],
            "timeout": TIMEOUT,
            "excludeCredentials": exclude,
            "authenticatorSelection": { "residentKey": "required", "requireResidentKey": true, "userVerification": "required" },
            "attestation": "none",
        },
    });
    let mut r = page::page(200, "Add a passkey", &[("__passkeyData", &data)]);
    page::csrf_cookie(&svc, &mut r);
    r
}

/// The link a `Referer` names, if it is the passkey page: the issuer's
/// origin, path `/oauth/passkey`, and a `token`.
pub(super) fn referer_link(svc: &Service, headers: &HeaderMap) -> Option<String> {
    let u = url::Url::parse(page::header_text(headers, "referer")?).ok()?;
    if u.origin().ascii_serialization() != svc.oauth.issuer || u.path() != "/oauth/passkey" {
        return None;
    }
    let (_, token) = u.query_pairs().find(|(k, _)| k == "token")?;
    Some(token.into_owned())
}

/// A refusal of the API's: `400` with this error.
fn refusal(error: &'static str, description: impl Into<String>) -> Refusal {
    Refusal {
        status: 400,
        error,
        description: description.into(),
        retry_after: None,
    }
}

/// `passkey-register` `{credential}`, for the link `token` names
/// (`spec/PASSKEYS.md`, "passkey-register"): checked under OAuth's lock,
/// so that a link adds one passkey, and a credential ID is had once. The
/// passkey added, the link ends.
pub(super) fn register(
    svc: &Shared,
    tx: &mut Tx<'_>,
    token: &str,
    b: &Map<String, Json>,
) -> Result<Json, Refusal> {
    let (rp, low) = (rp_id(svc), low(svc));
    let party = webauthn::Party {
        id: &rp,
        origin: &svc.oauth.issuer,
    };
    let credential = b.get("credential").unwrap_or(&Json::Null);
    tx.change(|st, _| {
        let mut held = svc.oauth.held();
        let now_ms = svc.sessions.now_ms();
        // 1. The link.
        let Some((did, link)) = held.link(token, now_ms).filter(|(did, _)| usable(svc, did)) else {
            return (vec![], Err(refusal("access_denied", "This link has ended")));
        };
        let kept = &st.passkeys;
        // 2 to 5.
        let made = match webauthn::registration(&party, &link.challenge, credential) {
            Ok(m) => m,
            Err(why) => return (vec![], Err(Refusal::from(why))),
        };
        // 6. New.
        let id = B64.encode(&made.id);
        if kept.by_id.contains_key(&id) {
            return (
                vec![],
                Err(Refusal::from("This passkey was added already".to_string())),
            );
        }
        if low {
            return (vec![], Err(page::out_of_space()));
        }
        let mut entry = json!({
            "t": "oauthPasskeyAdd", "did": did, "id": id,
            "count": made.count, "be": made.be, "bs": made.bs, "transports": made.transports,
            "name": link.name, "at": now_ms,
        });
        match &made.key {
            webauthn::Key::Es256(point) => entry["key"] = json!(B64.encode(point)),
            webauthn::Key::Rs256 { n, e } => {
                entry["alg"] = json!(-257);
                entry["key"] = json!(B64.encode(n));
                entry["e"] = json!(B64.encode(e));
            }
        }
        // A link adds one passkey: ended now, under the lock, a call through it at once is `access_denied`.
        held.end_for(&did);
        (vec![entry], Ok(json!({})))
    })
}

/// `passkey-options` `{}`: a new challenge, held for the call's device
/// (`spec/PASSKEYS.md`, "passkey-options"), which a call must name.
pub(super) fn options(svc: &Service, device: &Device) -> Result<Json, Refusal> {
    if !device.named {
        return Err(Refusal::from("The call names no device".to_string()));
    }
    Ok(json!({ "options": challenge_for(svc, &device.id) }))
}

/// Give device `device` a new challenge, in place of any it held, and
/// answer its options (`spec/PASSKEYS.md`, "Signing in"): what
/// `passkey-options` answers, and the authorization page's
/// `__passkeyOptions` ("The page's options"). Held in memory alone.
pub(super) fn challenge_for(svc: &Service, device: &str) -> Json {
    let (challenge, now) = (random(), svc.sessions.now());
    {
        let mut held = svc.oauth.held();
        if held.next_forget <= now {
            held.challenges.retain(|_, (_, until)| *until > now);
            held.next_forget = now + 60;
        }
        held.challenges.insert(
            device.to_string(),
            (challenge.clone(), now + CHALLENGE_LIFE),
        );
    }
    json!({
        "challenge": challenge, "rpId": rp_id(svc), "timeout": TIMEOUT,
        "userVerification": "required", "allowCredentials": [],
    })
}

/// `passkey-sign-in` `{locale, credential, remember?}` (`spec/PASSKEYS.md`,
/// "passkey-sign-in"): the device's challenge spent, the credential checked
/// against its passkey, then the account signed in as `sign-in` signs it
/// in, the passkey's count, BS and last use logged in the same frame.
pub(super) fn sign_in(
    svc: &Shared,
    tx: &mut Tx<'_>,
    device: &mut Device,
    request_id: &str,
    whence: &Whence,
    b: &Map<String, Json>,
) -> Result<Json, Refusal> {
    let refused = |why: &str| Err(Refusal::from(why.to_string()));
    // 1. The challenge, spent whatever follows.
    let now = svc.sessions.now();
    let challenge = svc.oauth.held().challenges.remove(&device.id);
    let Some((challenge, _)) = challenge.filter(|(_, until)| *until > now) else {
        return refused("No passkey challenge is held for this device");
    };
    // 2. Its form.
    let a =
        webauthn::assertion(b.get("credential").unwrap_or(&Json::Null)).map_err(Refusal::from)?;
    let (id, handle) = (B64.encode(&a.id), B64.encode(&a.user_handle));
    // 3. The passkey, whose account's user handle is the one given.
    let passkey = {
        let st = svc.oauth.lock();
        let kept = &st.passkeys;
        kept.by_id
            .get(&id)
            .filter(|p| B64.encode(svc.oauth.user_handle(&p.did)) == handle)
            .cloned()
    };
    let Some(passkey) = passkey else {
        return refused("No passkey of this credential ID and user handle");
    };
    // 4 to 7.
    let rp = rp_id(svc);
    let party = webauthn::Party {
        id: &rp,
        origin: &svc.oauth.issuer,
    };
    let kept = webauthn::Kept {
        key: &passkey.key,
        count: passkey.count,
        be: passkey.be,
    };
    let used = webauthn::verify(&party, &challenge, &a, &kept).map_err(Refusal::from)?;
    // 8. The account.
    let did = passkey.did.clone();
    let Some(account) = svc.account(&did) else {
        return refused("No passkey of this credential ID and user handle");
    };
    if crate::read(&account.state).takedown.is_some() {
        return refused("Account was taken down");
    }
    if low(svc) {
        return Err(page::out_of_space());
    }
    // The count again, under OAuth's lock with the sign-in: a sign-in made
    // meanwhile with the same count is the copy.
    let remembered = page::sign_in_here(
        tx,
        device,
        &did,
        b.get("remember").and_then(Json::as_bool),
        whence,
        |st, _| {
            let still = st.passkeys.by_id.get(&id).filter(|p| {
                p.did == did
                    && p.key == passkey.key
                    && (used.count == 0 && p.count == 0 || used.count > p.count)
            });
            if still.is_none() {
                return Err(Refusal::from(
                    "The passkey changed while it signed in".to_string(),
                ));
            }
            let at = svc.sessions.now_ms();
            Ok(vec![
                json!({ "t": "oauthPasskeyUse", "did": did, "id": id, "count": used.count, "bs": used.bs, "at": at }),
            ])
        },
    )?;
    Ok(page::signed_in(
        svc, &account, device, request_id, remembered,
    ))
}