Cotton code
446 lines · 18.3 KB · RustRaw
//! A Credential Exchange export read into the passkeys and passwords it carries.//!//! ```text//! read (json) → Export { exporter, exported_at, passkeys[], passwords[], skipped[] }//! ```//!//! The format is the FIDO Alliance **Credential Exchange Format 1.0**, Proposed//! Standard of 14 August 2025 (`cxf-v1.0-ps-20250814`); section numbers below//! are that document's. It is what iOS 26's Passwords app hands a credential//! provider through Credential Exchange (`ASCredentialImportManager`).//!//! What is read, exactly as the spec says://! - §3.1 Header: `version`, `exporterRpId`, `exporterDisplayName`,//!   `timestamp` (UNIX seconds), `accounts` — all REQUIRED.//! - §3.1.1 Version: `{ major, minor }`; major 1 is read, any minor (minor is//!   purely additive). The 2024 working draft's bare-number `version` is//!   refused in words: its passkey spells `userName`, 1.0 spells `username`.//! - §3.2.1 Account: `id`, `username`, `email`, `collections`, `items`.//! - §3.2.3 Item: `id`, `title`, `credentials` REQUIRED; `creationAt`,//!   `subtitle` read when present.//! - §3.3.12 Passkey: `credentialId`, `rpId`, `username`, `userDisplayName`,//!   `userHandle`, `key` (PKCS#8 DER) REQUIRED; `fido2Extensions` (§3.3.12.2)//!   is not carried and its member names are reported. Counters start at 0.//! - §3.3.2 BasicAuth: `username` and `password`, each an EditableField//!   (§3.3.1, its `value` read), into a login ([`ImportedPassword`]); the//!   item's `scope.urls` (§3.2.4) gives its site, its `title` its name. A//!   `totp` (§3.3.21) and a `note` (§3.3.15, `content`) in the same item ride//!   with the item's first password, the code as an `otpauth://` address, the//!   note as its notes; alone they are skipped.//! - §2.1 b64url: RFC 4648 URL-safe base64. The spec does not say padded or//!   not; both are accepted. The standard alphabet (`+`, `/`) is refused.//! - §3.1.1 / §2.1.1: unknown fields are ignored; a credential of a type this//!   reader does not import (every other type, and unknown types) lands//!   in `skipped` with words. §2.1.2: a REQUIRED array must be present even//!   when empty, so a missing one is refused.//!//! The header and accounts are the export's frame: a broken frame refuses the//! whole export ([`CxfError`]). An item or credential that is broken lands in//! `skipped` and the rest is still read. Nothing here panics on input.//!//! **Pure**, as the rest of [`crate::keys`]. The private halves live in the//! returned [`Passkey`]s and are wiped when they drop; a password lives in its//! [`ImportedPassword`]'s payload and nowhere else.use std::collections::HashSet;use base64::alphabet::URL_SAFE;use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};use base64::Engine as _;use serde_json::{Map, Value};use super::passkey::{self, Algorithm, Passkey};pub use super::password_import::ImportedPassword;/// RFC 4648 §5 base64url, padded or not.const B64URL: GeneralPurpose = GeneralPurpose::new(    &URL_SAFE,    GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),);/// The major version of CXF this reader reads (§3.1.1).pub const CXF_MAJOR: u64 = 1;/// Why a whole export was refused, in words.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum CxfError {    #[error("this is not a Credential Exchange export: it is not JSON ({0})")]    NotJson(String),    #[error("this is not a Credential Exchange export: {0}")]    BadFrame(String),    #[error("this export uses the 2024 CXF working draft (version {0}); Cotton Vault reads CXF 1.0")]    DraftVersion(u64),    #[error("this export is CXF {major}.{minor}; Cotton Vault reads CXF 1.x")]    UnsupportedVersion { major: u64, minor: u64 },}/// Who made the export (§3.1).#[derive(Debug, Clone, PartialEq, Eq)]pub struct Exporter {    /// `exporterRpId`: the exporting app as a relying party id.    pub rp_id: String,    /// `exporterDisplayName`.    pub display_name: String,}/// An export, read.#[derive(Debug)]pub struct Export {    pub exporter: Exporter,    /// `timestamp`: UNIX seconds the export was completed.    pub exported_at: u64,    pub passkeys: Vec<ImportedPasskey>,    /// Each `basic-auth` credential, as a login.    pub passwords: Vec<ImportedPassword>,    pub skipped: Vec<Skipped>,}/// One passkey the export carried, its key read and checked.#[derive(Debug)]pub struct ImportedPasskey {    pub rp_id: String,    /// The item's `title`, or the rp id when the title is blank.    pub rp_name: String,    /// `username` (§3.3.12; user-editable at the exporter, §3.3.12.1).    pub user_name: String,    /// `userDisplayName`.    pub user_display_name: String,    /// `userHandle`, decoded.    pub user_handle: Vec<u8>,    /// `credentialId`, decoded: the `rawId` the site registered.    pub credential_id: Vec<u8>,    pub algorithm: Algorithm,    /// The key, at sign count 0 (§3.3.12: importers MUST set zero).    pub passkey: Passkey,    /// The item's `subtitle`, when it has one.    pub note: Option<String>,    /// The item's `creationAt`, UNIX seconds, when it has one.    pub created_at: Option<u64>,    /// The `fido2Extensions` members present and not carried (§3.3.12.2), e.g.    /// `hmacCredentials`: a site relying on one will not get it from this key.    pub dropped_extensions: Vec<String>,}/// Something in the export that was not imported, and why.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Skipped {    /// The item's `title`, or empty when the item has none.    pub title: String,    /// The credential's `type`, or `item` when the whole item was skipped.    pub kind: String,    pub reason: String,}/// Read a CXF 1.0 export (§3.1) into its passkeys and what was skipped.pub fn read(json: &str) -> Result<Export, CxfError> {    let root: Value = serde_json::from_str(json).map_err(|err| CxfError::NotJson(err.to_string()))?;    let header = root        .as_object()        .ok_or_else(|| frame("the export is not a JSON object"))?;    check_version(header)?;    let exporter = Exporter {        rp_id: frame_str(header, "exporterRpId", "the export")?,        display_name: frame_str(header, "exporterDisplayName", "the export")?,    };    let exported_at = header        .get("timestamp")        .ok_or_else(|| frame("the export has no timestamp"))?        .as_u64()        .ok_or_else(|| frame("the export's timestamp is not UNIX seconds"))?;    let accounts = frame_array(header, "accounts", "the export")?;    let mut out = Export {        exporter,        exported_at,        passkeys: Vec::new(),        passwords: Vec::new(),        skipped: Vec::new(),    };    let mut seen = HashSet::new();    for (index, account) in accounts.iter().enumerate() {        let what = format!("account {}", index + 1);        let account = account            .as_object()            .ok_or_else(|| frame(&format!("{what} is not an object")))?;        for field in ["id", "username", "email"] {            frame_str(account, field, &what)?;        }        frame_array(account, "collections", &what)?;        for item in frame_array(account, "items", &what)? {            read_item(item, &mut out, &mut seen);        }    }    Ok(out)}fn check_version(header: &Map<String, Value>) -> Result<(), CxfError> {    let version = header        .get("version")        .ok_or_else(|| frame("the export has no version"))?;    if let Some(draft) = version.as_u64() {        return Err(CxfError::DraftVersion(draft));    }    let version = version        .as_object()        .ok_or_else(|| frame("the export's version is not { major, minor }"))?;    let part = |name| {        version            .get(name)            .and_then(Value::as_u64)            .ok_or_else(|| frame(&format!("the export's version has no {name}")))    };    let (major, minor) = (part("major")?, part("minor")?);    if major != CXF_MAJOR {        return Err(CxfError::UnsupportedVersion { major, minor });    }    Ok(())}fn read_item(item: &Value, out: &mut Export, seen: &mut HashSet<Vec<u8>>) {    let Some(item) = item.as_object() else {        out.skipped.push(skip("", "item", "the item is not an object"));        return;    };    let title = item.get("title").and_then(Value::as_str);    let shown = title.unwrap_or("").to_string();    let missing = if item.get("id").and_then(Value::as_str).is_none() {        Some("the item has no id")    } else if title.is_none() {        Some("the item has no title")    } else {        None    };    if let Some(reason) = missing {        out.skipped.push(skip(&shown, "item", reason));        return;    }    let Some(credentials) = item.get("credentials").and_then(Value::as_array) else {        out.skipped.push(skip(&shown, "item", "the item has no credentials list"));        return;    };    let note = item.get("subtitle").and_then(Value::as_str).map(str::to_string);    let created_at = item.get("creationAt").and_then(Value::as_u64);    let type_of = |entry: &Value| entry.get("type").and_then(Value::as_str).unwrap_or("").to_string();    let logins = credentials.iter().filter(|entry| type_of(entry) == "basic-auth").count();    // A code and a note ride with the item's first password (§3.2.3: one item, one account).    let mut code = credentials.iter().find(|entry| type_of(entry) == "totp").and_then(|entry| otpauth(entry, &shown));    let mut notes = credentials        .iter()        .find(|entry| type_of(entry) == "note")        .and_then(|entry| field_value(entry, "content"));    let site = item        .get("scope")        .and_then(|scope| scope.get("urls"))        .and_then(Value::as_array)        .and_then(|urls| urls.iter().find_map(Value::as_str))        .map(str::to_string);    for entry in credentials {        let kind = type_of(entry);        if kind == "basic-auth" {            let username = field_value(entry, "username");            let password = field_value(entry, "password").unwrap_or_default();            match super::password_import::login(&shown, site.as_deref(), username.as_deref(), &password, notes.as_deref(), code.as_deref(), created_at) {                Ok(login) => {                    notes = None;                    code = None;                    out.passwords.push(login);                }                Err(reason) => out.skipped.push(skip(&shown, "basic-auth", &reason)),            }            continue;        }        if logins > 0 && (kind == "totp" || kind == "note") {            continue;        }        if kind != "passkey" {            let reason = if kind.is_empty() {                "a credential with no type".to_string()            } else if kind == "totp" {                "a totp credential with no password beside it: Cotton Vault keeps a one-time code with its password".to_string()            } else {                format!("a {kind} credential: Cotton Vault imports passkeys and passwords only")            };            out.skipped.push(skip(&shown, if kind.is_empty() { "credential" } else { &kind }, &reason));            continue;        }        match read_passkey(entry, &shown, note.clone(), created_at) {            Ok(imported) if !seen.insert(imported.credential_id.clone()) => out.skipped.push(skip(                &shown,                "passkey",                "the same passkey (credential id) appears earlier in this export",            )),            Ok(imported) => out.passkeys.push(imported),            Err(reason) => out.skipped.push(skip(&shown, "passkey", &reason)),        }    }}/// One `type: "passkey"` credential (§3.3.12), or why it was not imported.fn read_passkey(    entry: &Value,    title: &str,    note: Option<String>,    created_at: Option<u64>,) -> Result<ImportedPasskey, String> {    let fields = entry        .as_object()        .ok_or_else(|| "the passkey is not an object".to_string())?;    let text = |name: &str| -> Result<String, String> {        match fields.get(name) {            Some(Value::String(value)) => Ok(value.clone()),            Some(_) => Err(format!("the passkey's {name} is not text")),            None if name == "username" && fields.contains_key("userName") => Err(                "the passkey spells userName (the 2024 draft); CXF 1.0 §3.3.12 spells username"                    .to_string(),            ),            None => Err(format!("the passkey has no {name}")),        }    };    let bytes = |name: &str| -> Result<Vec<u8>, String> {        let value = text(name)?;        B64URL            .decode(value.as_bytes())            .map_err(|_| format!("the passkey's {name} is not base64url"))    };    let credential_id = bytes("credentialId")?;    let rp_id = text("rpId")?;    let user_name = text("username")?;    let user_display_name = text("userDisplayName")?;    let user_handle = bytes("userHandle")?;    let der = zeroize::Zeroizing::new(bytes("key")?);    let dropped_extensions = match fields.get("fido2Extensions") {        None => Vec::new(),        Some(Value::Object(members)) => members.keys().cloned().collect(),        Some(_) => return Err("the passkey's fido2Extensions is not an object".to_string()),    };    let passkey = passkey::from_pkcs8(&rp_id, &user_handle, &credential_id, &der)        .map_err(|err| err.to_string())?;    let rp_name = if title.trim().is_empty() { rp_id.clone() } else { title.to_string() };    Ok(ImportedPasskey {        rp_id,        rp_name,        user_name,        user_display_name,        user_handle,        credential_id,        algorithm: passkey.algorithm,        passkey,        note,        created_at,        dropped_extensions,    })}/// An EditableField's `value` (§3.3.1), when it is text and not blank.fn field_value(entry: &Value, name: &str) -> Option<String> {    entry.get(name)?.get("value")?.as_str().filter(|value| !value.is_empty()).map(str::to_string)}/// A `totp` credential (§3.3.21) as the `otpauth://totp/` address an/// authenticator reads: its secret (Base32) and its period, digits,/// algorithm and issuer when given. `None` without a secret.fn otpauth(entry: &Value, title: &str) -> Option<String> {    let encode = |text: &str| url::form_urlencoded::byte_serialize(text.as_bytes()).collect::<String>().replace('+', "%20");    let text = |name: &str| entry.get(name).and_then(Value::as_str).filter(|value| !value.is_empty());    let secret = text("secret")?;    let issuer = text("issuer");    let account = text("username").unwrap_or(title);    let label = match issuer {        Some(issuer) => format!("{}:{}", encode(issuer), encode(account)),        None => encode(account),    };    let mut address = format!("otpauth://totp/{label}?secret={}", encode(secret));    if let Some(issuer) = issuer {        address.push_str(&format!("&issuer={}", encode(issuer)));    }    if let Some(algorithm) = text("algorithm") {        address.push_str(&format!("&algorithm={}", encode(&algorithm.to_uppercase())));    }    for name in ["digits", "period"] {        if let Some(number) = entry.get(name).and_then(Value::as_u64) {            address.push_str(&format!("&{name}={number}"));        }    }    Some(address)}fn frame(words: &str) -> CxfError {    CxfError::BadFrame(words.to_string())}fn frame_str(map: &Map<String, Value>, name: &str, what: &str) -> Result<String, CxfError> {    match map.get(name) {        Some(Value::String(value)) => Ok(value.clone()),        Some(_) => Err(frame(&format!("{what}'s {name} is not text"))),        None => Err(frame(&format!("{what} has no {name}"))),    }}fn frame_array<'a>(    map: &'a Map<String, Value>,    name: &str,    what: &str,) -> Result<&'a Vec<Value>, CxfError> {    match map.get(name) {        Some(Value::Array(values)) => Ok(values),        Some(_) => Err(frame(&format!("{what}'s {name} is not a list"))),        None => Err(frame(&format!("{what} has no {name} list"))),    }}fn skip(title: &str, kind: &str, reason: &str) -> Skipped {    Skipped {        title: title.to_string(),        kind: kind.to_string(),        reason: reason.to_string(),    }}/// The field names an export used that CXF 1.0 does not name, as/// `<where>.<name>` (`header`, `account`, `item`, `passkey`), each once, in the/// order met (`basic-auth` too). Names only, never a value: what the first real export from/// another app teaches about its shape, for a developer log. JSON that does not/// read answers nothing (the refusal is [`read`]'s to say).pub fn unnamed_fields(json: &str) -> Vec<String> {    const HEADER: &[&str] = &["version", "exporterRpId", "exporterDisplayName", "timestamp", "accounts"];    const ACCOUNT: &[&str] = &["id", "username", "email", "fullName", "collections", "items", "extensions"];    const ITEM: &[&str] =        &["id", "creationAt", "modifiedAt", "title", "subtitle", "favorite", "scope", "credentials", "tags", "extensions"];    const PASSKEY: &[&str] =        &["type", "credentialId", "rpId", "username", "userDisplayName", "userHandle", "key", "fido2Extensions"];    const BASIC_AUTH: &[&str] = &["type", "username", "password"];    let mut out: Vec<String> = Vec::new();    let mut note = |place: &str, map: &Map<String, Value>, known: &[&str]| {        for name in map.keys() {            let named = format!("{place}.{name}");            if !known.contains(&name.as_str()) && !out.contains(&named) {                out.push(named);            }        }    };    let Ok(Value::Object(header)) = serde_json::from_str::<Value>(json) else {        return Vec::new();    };    note("header", &header, HEADER);    let accounts = header.get("accounts").and_then(Value::as_array).into_iter().flatten();    for account in accounts.filter_map(Value::as_object) {        note("account", account, ACCOUNT);        let items = account.get("items").and_then(Value::as_array).into_iter().flatten();        for item in items.filter_map(Value::as_object) {            note("item", item, ITEM);            let credentials = item.get("credentials").and_then(Value::as_array).into_iter().flatten();            for credential in credentials.filter_map(Value::as_object) {                match credential.get("type").and_then(Value::as_str) {                    Some("passkey") => note("passkey", credential, PASSKEY),                    Some("basic-auth") => note("basic-auth", credential, BASIC_AUTH),                    _ => {}                }            }        }    }    out}#[cfg(test)]#[path = "cxf_tests.rs"]mod tests;