#![cfg(feature = "service")]
use p256::ecdsa::SigningKey;
use p256::ecdsa::signature::Signer as _;
use php_std::json::{self, Flags};
use php_std::{Array, Value};
use serde_json::{Value as Json, json};
use sha2::{Digest, Sha256};
use utopia_auth::Error;
use utopia_auth::passkeys::{Ceremony, Credential, Origin, RelyingParty};
const ORIGIN: &str = "http://localhost:3000";
const FLAG_USER_PRESENT: u8 = 0x01;
const FLAG_USER_VERIFIED: u8 = 0x04;
const FLAG_BACKUP_ELIGIBLE: u8 = 0x08;
const FLAG_BACKED_UP: u8 = 0x10;
const FLAG_ATTESTED: u8 = 0x40;
fn random_bytes(n: usize) -> Vec<u8> {
let mut b = vec![0u8; n];
getrandom::fill(&mut b).expect("random bytes");
b
}
fn encode(value: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut out = String::new();
for chunk in value.chunks(3) {
let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
for i in 0..=chunk.len() {
out.push(char::from(ALPHABET[((n >> (18 - 6 * i)) & 63) as usize]));
}
}
out
}
fn decode(value: &str) -> Vec<u8> {
let mut out = Vec::new();
let (mut acc, mut bits) = (0u32, 0);
for c in value.bytes() {
let v = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'-' | b'+' => 62,
b'_' | b'/' => 63,
_ => continue,
};
acc = (acc << 6) | u32::from(v);
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
}
}
out
}
fn cbor_head(major: u8, n: usize) -> Vec<u8> {
let major = major << 5;
match n {
0..=23 => vec![major | n as u8],
24..=0xff => vec![major | 24, n as u8],
_ => {
let mut h = vec![major | 25];
h.extend_from_slice(&u16::try_from(n).expect("short CBOR item").to_be_bytes());
h
}
}
}
fn cbor_bytes(b: &[u8]) -> Vec<u8> {
[cbor_head(2, b.len()), b.to_vec()].concat()
}
fn cbor_text(t: &str) -> Vec<u8> {
[cbor_head(3, t.len()), t.as_bytes().to_vec()].concat()
}
fn string<'a>(data: &'a Json, path: &[&str]) -> &'a str {
let mut value = data;
for key in path {
value = value.get(key).unwrap_or_else(|| panic!("Missing \"{}\"", path.join(".")));
}
value.as_str().unwrap_or_else(|| panic!("\"{}\" is not a string", path.join(".")))
}
fn to_json(options: &Array) -> Json {
let encoded = json::encode(&Value::Array(options.clone()), Flags::THROW_ON_ERROR, json::DEFAULT_DEPTH).unwrap();
serde_json::from_str(&encoded).unwrap()
}
fn to_array(value: &Json) -> Array {
match json::decode(value.to_string().as_bytes(), Some(true), json::DEFAULT_DEPTH, Flags::THROW_ON_ERROR).unwrap() {
Value::Array(a) => a,
other => panic!("not an array: {other:?}"),
}
}
fn merge(extra: Json, options: &Json) -> Json {
let mut merged = options.clone();
for (key, value) in extra.as_object().unwrap() {
merged[key] = value.clone();
}
merged
}
struct Authenticator {
credential_id: Vec<u8>,
user_handle: Vec<u8>,
counter: i64,
backup_eligible: bool,
user_verified: bool,
key: SigningKey,
}
impl Authenticator {
fn new() -> Self {
Self::with(true, true)
}
fn with(backup_eligible: bool, user_verified: bool) -> Self {
let key = loop {
if let Ok(key) = SigningKey::from_slice(&random_bytes(32)) {
break key;
}
};
Self { credential_id: random_bytes(16), user_handle: vec![], counter: 0, backup_eligible, user_verified, key }
}
fn register(&mut self, options: &Json, origin: &str, rp_id: Option<&str>) -> Array {
let rp_id = rp_id.unwrap_or_else(|| string(options, &["rp", "id"]));
self.user_handle = decode(string(options, &["user", "id"]));
let client_data = json!({
"type": "webauthn.create",
"challenge": string(options, &["challenge"]),
"origin": origin,
"crossOrigin": false,
})
.to_string();
let point = self.key.verifying_key().to_sec1_point(false);
let point = point.as_bytes();
let (x, y) = (&point[1..33], &point[33..65]);
let public_key =
[&[0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21][..], &cbor_bytes(x), &[0x22], &cbor_bytes(y)].concat();
let mut authenticator_data = self.authenticator_data(rp_id, FLAG_ATTESTED);
authenticator_data.extend_from_slice(&[0; 16]);
authenticator_data.extend_from_slice(&u16::try_from(self.credential_id.len()).unwrap().to_be_bytes());
authenticator_data.extend_from_slice(&self.credential_id);
authenticator_data.extend_from_slice(&public_key);
let attestation = [
cbor_head(5, 3),
cbor_text("fmt"),
cbor_text("none"),
cbor_text("attStmt"),
cbor_head(5, 0),
cbor_text("authData"),
cbor_bytes(&authenticator_data),
]
.concat();
to_array(&json!({
"id": encode(&self.credential_id),
"rawId": encode(&self.credential_id),
"type": "public-key",
"response": {
"clientDataJSON": encode(client_data.as_bytes()),
"attestationObject": encode(&attestation),
"transports": ["internal"],
},
"clientExtensionResults": {},
}))
}
fn authenticate(&mut self, options: &Json, origin: &str, rp_id: Option<&str>, cross_origin: bool) -> Array {
let rp_id = rp_id.unwrap_or_else(|| string(options, &["rpId"]));
self.counter += 1;
let client_data = json!({
"type": "webauthn.get",
"challenge": string(options, &["challenge"]),
"origin": origin,
"crossOrigin": cross_origin,
})
.to_string();
let authenticator_data = self.authenticator_data(rp_id, 0);
let signed = [&authenticator_data[..], &Sha256::digest(client_data.as_bytes())].concat();
let signature: p256::ecdsa::Signature = self.key.sign(&signed);
to_array(&json!({
"id": encode(&self.credential_id),
"rawId": encode(&self.credential_id),
"type": "public-key",
"response": {
"clientDataJSON": encode(client_data.as_bytes()),
"authenticatorData": encode(&authenticator_data),
"signature": encode(signature.to_der().as_bytes()),
"userHandle": encode(&self.user_handle),
},
"clientExtensionResults": {},
}))
}
fn authenticator_data(&self, rp_id: &str, mut flags: u8) -> Vec<u8> {
flags |= FLAG_USER_PRESENT;
if self.user_verified {
flags |= FLAG_USER_VERIFIED;
}
if self.backup_eligible {
flags |= FLAG_BACKUP_ELIGIBLE | FLAG_BACKED_UP;
}
[&Sha256::digest(rp_id.as_bytes())[..], &[flags], &(self.counter as u32).to_be_bytes()].concat()
}
}
fn ceremony() -> Ceremony {
Ceremony::new(RelyingParty::new("localhost", "Test", vec![ORIGIN.into()]))
}
fn register(ceremony: &Ceremony, authenticator: &mut Authenticator) -> Credential {
let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
let credential = authenticator.register(&to_json(&challenge.options), ORIGIN, None);
ceremony.verify_registration(challenge.state.as_bytes(), &credential).unwrap()
}
fn try_sign_in(
ceremony: &Ceremony,
authenticator: &mut Authenticator,
credential: &Credential,
) -> Result<Credential, Error> {
let challenge = ceremony.authenticate().unwrap();
let response = authenticator.authenticate(&to_json(&challenge.options), ORIGIN, None, false);
ceremony.verify_authentication(challenge.state.as_bytes(), &response, &credential.record)
}
fn sign_in(ceremony: &Ceremony, authenticator: &mut Authenticator, credential: &Credential) -> Credential {
try_sign_in(ceremony, authenticator, credential).unwrap()
}
#[track_caller]
fn assert_rejected<T: std::fmt::Debug>(result: Result<T, Error>) {
match result {
Err(Error::Passkey(_)) => {}
other => panic!("expected a passkey error, got {other:?}"),
}
}
#[test]
fn registration_options() {
let options = to_json(&ceremony().register(b"user@example.com", b"User", &[]).unwrap().options);
assert_eq!(string(&options, &["rp", "id"]), "localhost");
assert_eq!(string(&options, &["user", "name"]), "user@example.com");
assert_eq!(string(&options, &["authenticatorSelection", "residentKey"]), "required");
assert_eq!(string(&options, &["authenticatorSelection", "userVerification"]), "required");
assert_eq!(string(&options, &["attestation"]), "none");
}
#[test]
fn existing_passkeys_are_excluded_and_share_the_user_handle() {
let ceremony = ceremony();
let mut authenticator = Authenticator::new();
let first = register(&ceremony, &mut authenticator);
let options = to_json(&ceremony.register(b"user@example.com", b"User", &[first.record]).unwrap().options);
assert_eq!(
options["excludeCredentials"],
json!([{"type": "public-key", "id": encode(&authenticator.credential_id), "transports": ["internal"]}])
);
assert_eq!(string(&options, &["user", "id"]), encode(&authenticator.user_handle));
}
#[test]
fn excluded_passkey_without_transports_sends_empty_transports() {
let ceremony = ceremony();
let mut authenticator = Authenticator::new();
let mut record = register(&ceremony, &mut authenticator).record;
record.set(php_std::ArrayKey::from_bytes(b"transports"), Value::Array(Array::new()));
let options = to_json(&ceremony.register(b"user@example.com", b"User", &[record]).unwrap().options);
assert_eq!(
options["excludeCredentials"],
json!([{"type": "public-key", "id": encode(&authenticator.credential_id), "transports": []}])
);
}
#[test]
fn register_and_sign_in() {
let ceremony = ceremony();
let mut authenticator = Authenticator::new();
let registered = register(&ceremony, &mut authenticator);
let signed_in = sign_in(&ceremony, &mut authenticator, ®istered);
assert_eq!(registered.identifier, signed_in.identifier);
}
#[test]
fn identify_matches_the_registered_passkey() {
let ceremony = ceremony();
let mut authenticator = Authenticator::new();
let registered = register(&ceremony, &mut authenticator);
let challenge = ceremony.authenticate().unwrap();
let response = authenticator.authenticate(&to_json(&challenge.options), ORIGIN, None, false);
assert_eq!(registered.identifier, ceremony.identify(&response).unwrap());
}
#[test]
fn record_survives_storage() {
let ceremony = ceremony();
let mut authenticator = Authenticator::new();
let registered = register(&ceremony, &mut authenticator);
let stored = to_array(&to_json(®istered.record));
let credential = Credential { identifier: registered.identifier.clone(), record: stored };
assert_eq!(registered.identifier, sign_in(&ceremony, &mut authenticator, &credential).identifier);
}
#[test]
fn synced_passkey_allows_non_increasing_counter() {
let ceremony = ceremony();
let mut authenticator = Authenticator::with(true, true);
let registered = register(&ceremony, &mut authenticator);
let credential = sign_in(&ceremony, &mut authenticator, ®istered);
authenticator.counter = 0;
assert_eq!(credential.identifier, sign_in(&ceremony, &mut authenticator, &credential).identifier);
}
#[test]
fn device_bound_passkey_rejects_non_increasing_counter() {
let ceremony = ceremony();
let mut authenticator = Authenticator::with(false, true);
let registered = register(&ceremony, &mut authenticator);
let credential = sign_in(&ceremony, &mut authenticator, ®istered);
authenticator.counter = 0;
assert_rejected(try_sign_in(&ceremony, &mut authenticator, &credential));
}
#[test]
fn device_bound_passkey_without_counter_signs_in() {
let ceremony = ceremony();
let mut authenticator = Authenticator::with(false, true);
let mut credential = register(&ceremony, &mut authenticator);
for _ in 0..2 {
authenticator.counter = -1;
credential = sign_in(&ceremony, &mut authenticator, &credential);
assert!(!credential.identifier.is_empty());
}
}
#[test]
fn backup_eligibility_cannot_change() {
let ceremony = ceremony();
let mut authenticator = Authenticator::with(false, true);
let credential = register(&ceremony, &mut authenticator);
authenticator.backup_eligible = true;
assert_rejected(try_sign_in(&ceremony, &mut authenticator, &credential));
}
fn rejects_invalid_registration(credential: impl FnOnce(&mut Authenticator, &Json) -> Array) {
let ceremony = ceremony();
let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
let credential = credential(&mut Authenticator::new(), &to_json(&challenge.options));
assert_rejected(ceremony.verify_registration(challenge.state.as_bytes(), &credential));
}
#[test]
fn rejects_invalid_registration_wrong_origin() {
rejects_invalid_registration(|a, o| a.register(o, "http://localhost:4000", None));
}
#[test]
fn rejects_invalid_registration_subdomain_origin() {
rejects_invalid_registration(|a, o| a.register(o, "http://evil.localhost:3000", None));
}
#[test]
fn rejects_invalid_registration_wrong_rp_id() {
rejects_invalid_registration(|a, o| a.register(o, ORIGIN, Some("example.com")));
}
#[test]
fn rejects_invalid_registration_other_challenge() {
rejects_invalid_registration(|a, o| {
a.register(&merge(json!({"challenge": encode(&random_bytes(32))}), o), ORIGIN, None)
});
}
#[test]
fn rejects_invalid_registration_no_user_verification() {
rejects_invalid_registration(|a, o| {
a.user_verified = false;
a.register(o, ORIGIN, None)
});
}
#[test]
fn rejects_invalid_registration_malformed() {
rejects_invalid_registration(|_, _| {
to_array(&json!({"id": "abc", "type": "public-key", "response": {"clientDataJSON": "e30"}}))
});
}
#[test]
fn rejects_invalid_registration_missing_response() {
rejects_invalid_registration(|_, _| to_array(&json!({"id": "abc", "rawId": "abc", "type": "public-key"})));
}
#[test]
fn rejects_sign_in_credential_for_registration() {
let ceremony = ceremony();
let mut authenticator = Authenticator::new();
register(&ceremony, &mut authenticator);
let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
let options = merge(json!({"rpId": "localhost"}), &to_json(&challenge.options));
let credential = authenticator.authenticate(&options, ORIGIN, None, false);
assert_rejected(ceremony.verify_registration(challenge.state.as_bytes(), &credential));
}
fn rejects_invalid_sign_in(origin: &str, rp_id: Option<&str>, cross_origin: bool) {
let ceremony = ceremony();
let mut authenticator = Authenticator::new();
let registered = register(&ceremony, &mut authenticator);
let challenge = ceremony.authenticate().unwrap();
let response = authenticator.authenticate(&to_json(&challenge.options), origin, rp_id, cross_origin);
assert_rejected(ceremony.verify_authentication(challenge.state.as_bytes(), &response, ®istered.record));
}
#[test]
fn rejects_invalid_sign_in_wrong_origin() {
rejects_invalid_sign_in("http://localhost:4000", None, false);
}
#[test]
fn rejects_invalid_sign_in_wrong_rp_id() {
rejects_invalid_sign_in(ORIGIN, Some("example.com"), false);
}
#[test]
fn rejects_invalid_sign_in_cross_origin_iframe() {
rejects_invalid_sign_in(ORIGIN, None, true);
}
#[test]
fn rejects_signature_from_another_key() {
let ceremony = ceremony();
let mut authenticator = Authenticator::new();
let registered = register(&ceremony, &mut authenticator);
let mut impostor = Authenticator::new();
impostor.credential_id = authenticator.credential_id.clone();
impostor.user_handle = authenticator.user_handle.clone();
impostor.counter = 10;
assert_rejected(try_sign_in(&ceremony, &mut impostor, ®istered));
}
#[test]
fn rejects_malformed_state() {
assert_rejected(ceremony().verify_authentication(b"not json", &Array::new(), &Array::new()));
}
#[test]
fn rejects_malformed_credential_when_identifying() {
assert_rejected(ceremony().identify(&to_array(&json!({"id": "abc"}))));
}
#[test]
fn portless_localhost_origin_allows_any_port() {
let ceremony = Ceremony::new(RelyingParty::new("localhost", "Test", vec!["http://localhost".into()]));
let mut authenticator = Authenticator::new();
let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
let credential = authenticator.register(&to_json(&challenge.options), "http://localhost:5173", None);
let registered = ceremony.verify_registration(challenge.state.as_bytes(), &credential).unwrap();
let challenge = ceremony.authenticate().unwrap();
let response = authenticator.authenticate(&to_json(&challenge.options), "http://localhost:3000", None, false);
let signed_in = ceremony.verify_authentication(challenge.state.as_bytes(), &response, ®istered.record).unwrap();
assert_eq!(registered.identifier, signed_in.identifier);
let challenge = ceremony.authenticate().unwrap();
let response = authenticator.authenticate(&to_json(&challenge.options), "https://localhost:3000", None, false);
assert_rejected(ceremony.verify_authentication(challenge.state.as_bytes(), &response, ®istered.record));
}
#[test]
fn portless_localhost_origin_rejects_a_path() {
let ceremony = Ceremony::new(RelyingParty::new("localhost", "Test", vec!["http://localhost".into()]));
let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
let credential = Authenticator::new().register(&to_json(&challenge.options), "http://localhost:5173/login", None);
assert_rejected(ceremony.verify_registration(challenge.state.as_bytes(), &credential));
}
fn wildcard_origin(origin: &str, allowed: bool) {
let ceremony = Ceremony::new(RelyingParty::new("example.com", "Test", vec!["https://*.example.com".into()]));
let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
let credential = Authenticator::new().register(&to_json(&challenge.options), origin, Some("example.com"));
let result = ceremony.verify_registration(challenge.state.as_bytes(), &credential);
if allowed {
assert!(!result.unwrap().identifier.is_empty());
} else {
assert_rejected(result);
}
}
#[test]
fn wildcard_origin_allows_subdomain() {
wildcard_origin("https://app.example.com", true);
}
#[test]
fn wildcard_origin_allows_nested_subdomain() {
wildcard_origin("https://eu.app.example.com", true);
}
#[test]
fn wildcard_origin_rejects_apex() {
wildcard_origin("https://example.com", false);
}
#[test]
fn wildcard_origin_rejects_lookalike() {
wildcard_origin("https://evilexample.com", false);
}
#[test]
fn wildcard_origin_rejects_http() {
wildcard_origin("http://app.example.com", false);
}
#[test]
fn wildcard_origin_rejects_port() {
wildcard_origin("https://app.example.com:8443", false);
}
#[test]
fn wildcard_origin_rejects_path() {
wildcard_origin("https://app.example.com/login", false);
}
#[test]
fn portless_origin_allows_only_default_port_outside_localhost() {
let ceremony = Ceremony::new(RelyingParty::new("example.com", "Test", vec!["https://example.com".into()]));
let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
let credential =
Authenticator::new().register(&to_json(&challenge.options), "https://example.com:8443", Some("example.com"));
assert_rejected(ceremony.verify_registration(challenge.state.as_bytes(), &credential));
}
#[test]
fn android_app_origin_matches_exactly() {
let app = "android:apk-key-hash:FG3pg8VzBlDY7rmVLzT8ZBagg0LmHb6oigSWsj_PROU";
let ceremony =
Ceremony::new(RelyingParty::new("example.com", "Test", vec!["https://example.com".into(), app.into()]));
let mut authenticator = Authenticator::new();
let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
let credential = authenticator.register(&to_json(&challenge.options), app, None);
let registered = ceremony.verify_registration(challenge.state.as_bytes(), &credential).unwrap();
let challenge = ceremony.authenticate().unwrap();
let response = authenticator.authenticate(&to_json(&challenge.options), "https://example.com", None, false);
let signed_in = ceremony.verify_authentication(challenge.state.as_bytes(), &response, ®istered.record).unwrap();
assert_eq!(registered.identifier, signed_in.identifier);
let challenge = ceremony.authenticate().unwrap();
let response = authenticator.authenticate(
&to_json(&challenge.options),
"android:apk-key-hash:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
None,
false,
);
assert_rejected(ceremony.verify_authentication(challenge.state.as_bytes(), &response, ®istered.record));
}
#[test]
fn fingerprint_ignores_origin_order() {
let a = RelyingParty::new("example.com", "A", vec!["https://a.example.com".into(), "https://example.com".into()]);
let b = RelyingParty::new("example.com", "B", vec!["https://example.com".into(), "https://a.example.com".into()]);
let c = RelyingParty::new("example.com", "A", vec!["https://example.com".into()]);
assert_eq!(a.fingerprint(), b.fingerprint());
assert_ne!(a.fingerprint(), c.fingerprint());
}
#[test]
fn origin_normalize() {
let origins: [(&str, &str, &str, Option<&str>); 17] = [
("rp id", "example.com", "https://example.com", Some("https://example.com")),
("trailing slash", "example.com", "https://example.com/", Some("https://example.com")),
("subdomain with default port", "example.com", "https://app.example.com:443", Some("https://app.example.com")),
("custom port", "example.com", "https://example.com:8443", Some("https://example.com:8443")),
("http", "example.com", "http://example.com", None),
("other domain", "example.com", "https://evil.com", None),
("suffix lookalike", "example.com", "https://notexample.com", None),
("path", "example.com", "https://example.com/login", None),
("credentials", "example.com", "https://user:pass@example.com", None),
("query", "example.com", "https://example.com?next=1", None),
("empty fragment", "example.com", "https://example.com#", None),
("uppercase", "example.com", "https://EXAMPLE.com", None),
("no scheme", "example.com", "example.com", None),
("localhost over http", "localhost", "http://localhost:3000", Some("http://localhost:3000")),
("localhost default port", "localhost", "http://localhost:80", Some("http://localhost")),
("localhost over https", "localhost", "https://localhost", Some("https://localhost")),
("loopback ip", "localhost", "http://127.0.0.1:3000", None),
];
for (name, rp_id, origin, expected) in origins {
assert_eq!(Origin::new(rp_id).normalize(origin.as_bytes()).as_deref(), expected, "{name}");
}
}