Cotton code
518 lines · 22.5 KB · RustRaw
use super::*;use p256::elliptic_curve::sec1::ToEncodedPoint as _;use p256::pkcs8::der::asn1::AnyRef;use p256::pkcs8::der::Encode as _;use p256::pkcs8::{AlgorithmIdentifierRef, EncodePrivateKey as _, ObjectIdentifier, PrivateKeyInfo};use serde_json::json;use sha2::{Digest, Sha256};/// The hand-written minimal export: two synthetic passkeys (one key padded,/// one not), one TOTP. Written by `the_minimal_fixture_is_what_the_test_makes`/// when CXF_WRITE=1.const MINIMAL: &str = "tests/fixtures/cxf/minimal.json";/// What [`read`] makes of it: ids as hex, verifying keys as COSE, no scalar.const MINIMAL_READ: &str = "tests/fixtures/cxf/minimal.read.json";/// CXF 1.0 PS Appendix A, verbatim: the spec's own example payload.const APPENDIX_A: &str = include_str!("../../tests/fixtures/cxf/spec-appendix-a.json");fn fixture_path(relative: &str) -> std::path::PathBuf {    cotton_store::manifest_dir().join(relative)}/// A synthetic scalar the test derives from a label: never a real key.fn scalar(label: &str) -> p256::SecretKey {    p256::SecretKey::from_slice(&Sha256::digest(label.as_bytes())).unwrap()}fn b64(bytes: &[u8], padded: bool) -> String {    use base64::engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD};    if padded { URL_SAFE.encode(bytes) } else { URL_SAFE_NO_PAD.encode(bytes) }}/// A PKCS#8 v2 (RFC 5958) of `key`, its public key in the envelope.fn pkcs8_v2(key: &p256::SecretKey) -> Vec<u8> {    let inner = key.to_sec1_der().unwrap();    let point = key.public_key().to_encoded_point(false);    let curve = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");    PrivateKeyInfo {        algorithm: AlgorithmIdentifierRef {            oid: ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"),            parameters: Some(AnyRef::from(&curve)),        },        private_key: &inner,        public_key: Some(point.as_bytes()),    }    .to_der()    .unwrap()}/// The minimal export, built from keys this test makes.fn minimal() -> Value {    let first = scalar("cotton cxf fixture: first passkey");    let second = scalar("cotton cxf fixture: second passkey");    json!({        "version": { "major": 1, "minor": 0 },        "exporterRpId": "exporter.example",        "exporterDisplayName": "Synthetic Exporter",        "timestamp": 1_767_225_600u64,        "accounts": [{            "id": b64(b"account-1", false),            "username": "",            "email": "person@example.com",            "collections": [],            "items": [                {                    "id": b64(b"item-1", false),                    "creationAt": 1_735_689_600u64,                    "title": "Example",                    "credentials": [{                        "type": "passkey",                        "credentialId": b64(&[0xc1; 16], false),                        "rpId": "example.com",                        "username": "person@example.com",                        "userDisplayName": "Synthetic Person",                        "userHandle": b64(b"user-handle-1", false),                        "key": b64(first.to_pkcs8_der().unwrap().as_bytes(), false),                    }],                },                {                    "id": b64(b"item-2", false),                    "title": "Example Login",                    "subtitle": "work account",                    "credentials": [{                        "type": "passkey",                        "credentialId": b64(&[0xc2; 20], true),                        "rpId": "login.example.org",                        "username": "person",                        "userDisplayName": "Synthetic Person",                        "userHandle": b64(&[0x02; 32], true),                        "key": b64(&pkcs8_v2(&second), true),                        "fido2Extensions": { "credBlob": b64(b"blob", false) },                    }],                },                {                    "id": b64(b"item-3", false),                    "title": "Example 2FA",                    "credentials": [{                        "type": "totp",                        "secret": "JBSWY3DPEHPK3PXP",                        "period": 30,                        "digits": 6,                        "algorithm": "sha1",                    }],                },            ],        }],    })}/// What a read is, without a private scalar anywhere.fn summary(export: &Export) -> Value {    json!({        "exporter": { "rpId": export.exporter.rp_id, "displayName": export.exporter.display_name },        "exportedAt": export.exported_at,        "passkeys": export.passkeys.iter().map(|p| json!({            "rpId": p.rp_id,            "rpName": p.rp_name,            "userName": p.user_name,            "userDisplayName": p.user_display_name,            "userHandleHex": hex::encode(&p.user_handle),            "credentialIdHex": hex::encode(&p.credential_id),            "algorithm": p.algorithm.as_str(),            "publicKeyCose": p.passkey.public_key,            "signCount": p.passkey.sign_count,            "note": p.note,            "createdAt": p.created_at,            "droppedExtensions": p.dropped_extensions,        })).collect::<Vec<_>>(),        "skipped": export.skipped.iter().map(|s| json!({            "title": s.title, "kind": s.kind, "reason": s.reason,        })).collect::<Vec<_>>(),    })}fn pretty(value: &Value) -> String {    serde_json::to_string_pretty(value).unwrap() + "\n"}fn compare_or_write(relative: &str, made: &str) {    let path = fixture_path(relative);    if std::env::var("CXF_WRITE").as_deref() == Ok("1") {        std::fs::write(&path, made).unwrap();        return;    }    let held = std::fs::read_to_string(&path)        .unwrap_or_else(|err| panic!("{relative}: {err}; write it with CXF_WRITE=1"));    assert_eq!(held, made, "{relative} differs from what the test makes; CXF_WRITE=1 rewrites it");}fn read_value(value: &Value) -> Result<Export, CxfError> {    read(&value.to_string())}/// The minimal export with one edit to its first passkey credential.fn first_passkey(edit: impl FnOnce(&mut Map<String, Value>)) -> Value {    let mut value = minimal();    edit(value["accounts"][0]["items"][0]["credentials"][0].as_object_mut().unwrap());    value}/// The one skip a broken first passkey makes.fn first_skip(value: &Value) -> Skipped {    let export = read_value(value).unwrap();    assert_eq!(export.passkeys.len(), 1, "the second passkey still reads");    export        .skipped        .into_iter()        .find(|s| s.kind == "passkey")        .expect("the broken passkey is skipped")}#[test]fn the_minimal_fixture_is_what_the_test_makes() {    let made = pretty(&minimal());    compare_or_write(MINIMAL, &made);    let export = read(&made).unwrap();    let summary = pretty(&summary(&export));    for label in ["cotton cxf fixture: first passkey", "cotton cxf fixture: second passkey"] {        let scalar_hex = hex::encode(scalar(label).to_bytes());        assert!(!summary.contains(&scalar_hex), "a scalar reached the read fixture");    }    compare_or_write(MINIMAL_READ, &summary);}#[test]fn the_minimal_export_reads_two_passkeys_and_skips_the_totp() {    let held = std::fs::read_to_string(fixture_path(MINIMAL)).unwrap();    let export = read(&held).unwrap();    assert_eq!(export.exporter.rp_id, "exporter.example");    assert_eq!(export.exporter.display_name, "Synthetic Exporter");    assert_eq!(export.exported_at, 1_767_225_600);    assert_eq!(export.passkeys.len(), 2);    let first = &export.passkeys[0];    assert_eq!(first.rp_id, "example.com");    assert_eq!(first.rp_name, "Example");    assert_eq!(first.user_handle, b"user-handle-1");    assert_eq!(first.credential_id, [0xc1; 16]);    assert_eq!(first.created_at, Some(1_735_689_600));    assert_eq!(first.note, None);    let expected = scalar("cotton cxf fixture: first passkey").public_key();    assert_eq!(first.passkey.verifying_key(), p256::ecdsa::VerifyingKey::from(expected));    assert_eq!(first.passkey.sign_count, 0);    assert_eq!(first.passkey.rp_id, "example.com");    let second = &export.passkeys[1];    assert_eq!(second.credential_id, [0xc2; 20], "a padded id reads");    assert_eq!(second.user_handle, [0x02; 32], "a padded handle reads");    assert_eq!(second.note.as_deref(), Some("work account"));    assert_eq!(second.dropped_extensions, ["credBlob"]);    let expected = scalar("cotton cxf fixture: second passkey").public_key();    assert_eq!(second.passkey.verifying_key(), p256::ecdsa::VerifyingKey::from(expected));    assert_eq!(        export.skipped,        [Skipped {            title: "Example 2FA".into(),            kind: "totp".into(),            reason: "a totp credential with no password beside it: Cotton Vault keeps a one-time code with its password".into(),        }]    );}#[test]fn the_specs_appendix_a_reads_its_one_passkey_its_one_password_and_skips_the_rest() {    let export = read(APPENDIX_A).unwrap();    assert_eq!(export.exporter.rp_id, "exporter.example.com");    assert_eq!(export.exported_at, 1_705_228_800);    assert_eq!(export.passkeys.len(), 1);    let passkey = &export.passkeys[0];    assert_eq!(passkey.rp_id, "webauthn.io");    assert_eq!(passkey.rp_name, "WebAuthn.io");    assert_eq!(passkey.user_name, "johndoe");    assert_eq!(passkey.user_display_name, "John Doe");    assert_eq!(passkey.credential_id, b"credentialIdExample");    // Appendix A's example carries `hmacSecret`, not §3.3.12.2's `hmacCredentials`:    // the spec's own example and its CDDL disagree; either is reported, neither carried.    assert_eq!(passkey.dropped_extensions, ["hmacSecret"]);    // Its GitHub item: a basic-auth credential with a totp beside it, as one login.    assert_eq!(export.passwords.len(), 1);    let login = &export.passwords[0];    assert_eq!((login.name.as_str(), login.site.as_deref(), login.username.as_deref()), ("GitHub Login", Some("github.com"), Some("johndoe")));    assert_eq!(login.created_at, Some(1_705_142_400));    match &login.payload {        crate::vault::payload::SecretPayload::Login { password, notes, totp, .. } => {            assert!(password == "securepassword123", "the spec's example password is read");            assert_eq!(notes, &None);            assert_eq!(                totp.as_deref(),                Some("otpauth://totp/Google:jane.smith%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=Google&algorithm=SHA256&digits=6&period=30"),                "the spec's example code, as an authenticator reads it"            );        }        _ => panic!("a login"),    }    let kinds: Vec<&str> = export.skipped.iter().map(|s| s.kind.as_str()).collect();    assert_eq!(        kinds,        [            "credit-card", "wifi", "note", "drivers-license", "address",            "ssh-key", "file", "identity-document", "passport", "person-name", "api-key",            "generated-password",        ]    );}#[test]fn a_draft_user_name_spelling_is_refused_naming_the_spelling() {    let value = first_passkey(|c| {        let name = c.remove("username").unwrap();        c.insert("userName".into(), name);    });    let skip = first_skip(&value);    assert!(skip.reason.contains("userName (the 2024 draft)"), "{}", skip.reason);    assert_eq!(skip.title, "Example");}#[test]fn each_missing_passkey_field_is_skipped_by_name() {    for field in ["credentialId", "rpId", "username", "userDisplayName", "userHandle", "key"] {        let skip = first_skip(&first_passkey(|c| {            c.remove(field);        }));        assert_eq!(skip.reason, format!("the passkey has no {field}"));        let skip = first_skip(&first_passkey(|c| {            c.insert(field.into(), json!(7));        }));        assert_eq!(skip.reason, format!("the passkey's {field} is not text"));    }}#[test]fn base64_that_is_not_url_safe_is_skipped() {    for field in ["credentialId", "userHandle", "key"] {        let skip = first_skip(&first_passkey(|c| {            c.insert(field.into(), json!("ab+/"));        }));        assert_eq!(skip.reason, format!("the passkey's {field} is not base64url"));        let skip = first_skip(&first_passkey(|c| {            c.insert(field.into(), json!("not base64!"));        }));        assert_eq!(skip.reason, format!("the passkey's {field} is not base64url"));    }}#[test]fn refused_keys_are_skipped_with_the_key_refusal() {    let rsa = include_bytes!("../../tests/fixtures/cxf/pkcs8/pkcs8-crate-rsa2048.der");    let skip = first_skip(&first_passkey(|c| {        c.insert("key".into(), json!(b64(rsa, false)));    }));    assert_eq!(skip.reason, "RS256 passkeys are not made yet: Cotton Vault makes ES256 (P-256) only");    let ed = include_bytes!("../../tests/fixtures/cxf/pkcs8/pkcs8-crate-ed25519-v2.der");    let skip = first_skip(&first_passkey(|c| {        c.insert("key".into(), json!(b64(ed, true)));    }));    assert!(skip.reason.starts_with("EdDSA passkeys are not made yet"), "{}", skip.reason);    let skip = first_skip(&first_passkey(|c| {        c.insert("key".into(), json!(b64(b"not der", false)));    }));    assert!(skip.reason.starts_with("the private key is not PKCS#8 DER"), "{}", skip.reason);}#[test]fn a_bad_account_id_or_credential_id_length_is_skipped() {    let skip = first_skip(&first_passkey(|c| {        c.insert("userHandle".into(), json!(b64(&[1; 65], false)));    }));    assert_eq!(skip.reason, "the account id (user_handle) must be base64url of 1 to 64 bytes");    let skip = first_skip(&first_passkey(|c| {        c.insert("credentialId".into(), json!(""));    }));    assert_eq!(skip.reason, "a credential id is 1 to 1023 bytes, not 0");    let skip = first_skip(&first_passkey(|c| {        c.insert("rpId".into(), json!(" "));    }));    assert_eq!(skip.reason, "a passkey needs a site (rp_id)");}#[test]fn fido2_extensions_that_are_not_an_object_are_skipped() {    let skip = first_skip(&first_passkey(|c| {        c.insert("fido2Extensions".into(), json!([]));    }));    assert_eq!(skip.reason, "the passkey's fido2Extensions is not an object");}#[test]fn the_same_passkey_twice_is_read_once() {    let mut value = minimal();    let item = value["accounts"][0]["items"][0].clone();    value["accounts"][0]["items"].as_array_mut().unwrap().push(item);    let export = read_value(&value).unwrap();    assert_eq!(export.passkeys.len(), 2);    assert!(export.skipped.iter().any(|s| s.kind == "passkey"        && s.reason == "the same passkey (credential id) appears earlier in this export"));}#[test]fn broken_items_and_unknown_types_are_skipped_not_fatal() {    let mut value = minimal();    let items = value["accounts"][0]["items"].as_array_mut().unwrap();    items.push(json!("not an item"));    items.push(json!({ "title": "No id", "credentials": [] }));    items.push(json!({ "id": "aWQ", "credentials": [] }));    items.push(json!({ "id": "aWQ", "title": "No list" }));    items.push(json!({ "id": "aWQ", "title": "Odd", "credentials": [{ "type": "x-future" }, { "no": "type" }] }));    let export = read_value(&value).unwrap();    assert_eq!(export.passkeys.len(), 2);    let reasons: Vec<(&str, &str, &str)> = export        .skipped        .iter()        .map(|s| (s.title.as_str(), s.kind.as_str(), s.reason.as_str()))        .collect();    assert_eq!(        reasons[1..],        [            ("", "item", "the item is not an object"),            ("No id", "item", "the item has no id"),            ("", "item", "the item has no title"),            ("No list", "item", "the item has no credentials list"),            ("Odd", "x-future", "a x-future credential: Cotton Vault imports passkeys and passwords only"),            ("Odd", "credential", "a credential with no type"),        ]    );}#[test]fn unknown_fields_are_ignored() {    let mut value = first_passkey(|c| {        c.insert("somethingNew".into(), json!({ "a": 1 }));    });    value["futureHeaderField"] = json!(true);    value["accounts"][0]["futureAccountField"] = json!([1]);    value["version"]["minor"] = json!(3);    assert_eq!(read_value(&value).unwrap().passkeys.len(), 2);}type Edit<'a> = &'a dyn Fn(&mut Value);#[test]fn a_broken_frame_refuses_the_whole_export() {    assert!(matches!(read("{"), Err(CxfError::NotJson(_))));    assert_eq!(read("[]").unwrap_err(), CxfError::BadFrame("the export is not a JSON object".into()));    let refused = |edit: &dyn Fn(&mut Value)| {        let mut value = minimal();        edit(&mut value);        read_value(&value).unwrap_err()    };    assert_eq!(refused(&|v| v["version"] = json!(0)), CxfError::DraftVersion(0));    assert!(refused(&|v| v["version"] = json!(0)).to_string().contains("2024 CXF working draft"));    assert_eq!(        refused(&|v| v["version"] = json!({ "major": 2, "minor": 0 })),        CxfError::UnsupportedVersion { major: 2, minor: 0 }    );    let cases: [(Edit, &str); 12] = [        (&|v| drop(v.as_object_mut().unwrap().remove("version")), "the export has no version"),        (&|v| v["version"] = json!("1.0"), "the export's version is not { major, minor }"),        (&|v| v["version"] = json!({ "major": 1 }), "the export's version has no minor"),        (&|v| drop(v.as_object_mut().unwrap().remove("exporterRpId")), "the export has no exporterRpId"),        (&|v| v["exporterDisplayName"] = json!(1), "the export's exporterDisplayName is not text"),        (&|v| drop(v.as_object_mut().unwrap().remove("timestamp")), "the export has no timestamp"),        (&|v| v["timestamp"] = json!(-1), "the export's timestamp is not UNIX seconds"),        (&|v| drop(v.as_object_mut().unwrap().remove("accounts")), "the export has no accounts list"),        (&|v| v["accounts"] = json!([1]), "account 1 is not an object"),        (&|v| drop(v["accounts"][0].as_object_mut().unwrap().remove("email")), "account 1 has no email"),        (            &|v| drop(v["accounts"][0].as_object_mut().unwrap().remove("collections")),            "account 1 has no collections list",        ),        (&|v| v["accounts"][0]["items"] = json!({}), "account 1's items is not a list"),    ];    for (edit, words) in cases {        assert_eq!(refused(edit), CxfError::BadFrame(words.into()), "{words}");    }}#[test]fn an_empty_export_reads_to_nothing() {    let mut value = minimal();    value["accounts"] = json!([]);    let export = read_value(&value).unwrap();    assert!(export.passkeys.is_empty() && export.skipped.is_empty());}// RULE (keys-cxf-phone, 8 Nov 2026): the field names an export used that CXF// 1.0 does not name are listed by place, names only, so the first real export// teaches its shape; the spec's own example and the minimal fixture name none.#[test]fn unnamed_fields_name_what_the_spec_does_not() {    assert_eq!(unnamed_fields(APPENDIX_A), Vec::<String>::new());    let minimal = std::fs::read_to_string(fixture_path(MINIMAL)).unwrap();    assert_eq!(unnamed_fields(&minimal), Vec::<String>::new());    let odd = json!({        "version": {"major": 1, "minor": 0}, "formatVersion": "v1", "exporterRpId": "x.example",        "exporterDisplayName": "X", "timestamp": 1, "accounts": [{"id": "a", "username": "", "email": "",        "collections": [], "items": [{"id": "i", "title": "T", "lastModified": 2, "credentials": [            {"type": "passkey", "credentialID": "c", "relyingPartyIdentifier": "r", "key": "SECRET"},            {"type": "totp", "secret": "SECRET"}]}]}],    });    let named = unnamed_fields(&odd.to_string());    assert_eq!(named, vec!["header.formatVersion", "item.lastModified", "passkey.credentialID", "passkey.relyingPartyIdentifier"]);    assert!(!named.concat().contains("SECRET"));    assert_eq!(unnamed_fields("not json"), Vec::<String>::new());}/// A synthetic export of logins: each basic-auth credential is a login named/// by its item, sited by its scope's first address, a note beside it as its/// notes; a login with no password is skipped in words; a field CXF does not/// name on a basic-auth credential is reported by name. No real credential.#[test]fn basic_auth_credentials_read_as_logins() {    let export = json!({        "version": {"major": 1, "minor": 0},        "exporterRpId": "exporter.invented.test",        "exporterDisplayName": "Synthetic Exporter",        "timestamp": 1_735_689_600u64,        "accounts": [{            "id": "YWNjb3VudA", "username": "", "email": "ada@invented.test", "collections": [],            "items": [                {"id": "aXRlbS0x", "title": "Invented Mail", "creationAt": 1_735_689_600u64,                 "scope": {"urls": ["https://mail.invented.test/login"], "androidApps": []},                 "credentials": [                    {"type": "basic-auth", "username": {"fieldType": "string", "value": "ada@invented.test"},                     "password": {"fieldType": "concealed-string", "value": "SYNTHETIC-pass-0001"}, "strength": "weak"},                    {"type": "note", "content": {"fieldType": "string", "value": "SYNTHETIC note"}}]},                {"id": "aXRlbS0y", "title": "No password", "credentials": [                    {"type": "basic-auth", "username": {"fieldType": "string", "value": "ada"}}]},                {"id": "aXRlbS0z", "title": "", "scope": {"urls": ["shop.invented.test"]}, "credentials": [                    {"type": "basic-auth", "password": {"fieldType": "concealed-string", "value": "SYNTHETIC-pass-0002"}}]},                {"id": "aXRlbS00", "title": "Lonely note", "credentials": [                    {"type": "note", "content": {"fieldType": "string", "value": "SYNTHETIC"}}]}            ]        }]    })    .to_string();    let read = read(&export).unwrap();    assert!(read.passkeys.is_empty());    assert_eq!(read.passwords.len(), 2);    let mail = &read.passwords[0];    assert_eq!((mail.name.as_str(), mail.site.as_deref(), mail.username.as_deref()), ("Invented Mail", Some("mail.invented.test"), Some("ada@invented.test")));    assert_eq!(mail.created_at, Some(1_735_689_600));    assert!(        mail.payload == crate::vault::payload::SecretPayload::Login { password: "SYNTHETIC-pass-0001".into(), notes: Some("SYNTHETIC note".into()), totp: None, urls: None },        "the password and the item's note"    );    let shop = &read.passwords[1];    assert_eq!((shop.name.as_str(), shop.site.as_deref(), shop.username.as_deref()), ("shop.invented.test", Some("shop.invented.test"), None));    let skipped: Vec<(&str, &str, &str)> = read.skipped.iter().map(|s| (s.title.as_str(), s.kind.as_str(), s.reason.as_str())).collect();    assert_eq!(        skipped,        [            ("No password", "basic-auth", "it has no password"),            ("Lonely note", "note", "a note credential: Cotton Vault imports passkeys and passwords only"),        ]    );    assert_eq!(unnamed_fields(&export), ["basic-auth.strength"]);}