diff --git a/Cargo.lock b/Cargo.lock index 4122e215..e8446a80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9946,8 +9946,7 @@ dependencies = [ [[package]] name = "world-id-authenticator" version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fdfa757c5770fad015442fb548205cddbc44e347cda538c39482d72edb2efd9" +source = "git+https://github.com/worldcoin/world-id-protocol?rev=d1edfd36bf2aca9eef3644cfc6ab073559dbd52c#d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" dependencies = [ "aes-gcm", "alloy", @@ -9992,8 +9991,7 @@ dependencies = [ [[package]] name = "world-id-core" version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e311d8d1c57097e82df60736eef14b4d4e5c78c99954941f890b242935fa201" +source = "git+https://github.com/worldcoin/world-id-protocol?rev=d1edfd36bf2aca9eef3644cfc6ab073559dbd52c#d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" dependencies = [ "taceo-eddsa-babyjubjub", "world-id-authenticator", @@ -10005,8 +10003,7 @@ dependencies = [ [[package]] name = "world-id-flamingo" version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8f3482849aa4ab8e6728366b16591af965b07ffaa61b27fc082e74a2045d66a" +source = "git+https://github.com/worldcoin/world-id-protocol?rev=d1edfd36bf2aca9eef3644cfc6ab073559dbd52c#d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" dependencies = [ "base64 0.22.1", "coset", @@ -10024,8 +10021,7 @@ dependencies = [ [[package]] name = "world-id-primitives" version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e312b40c415f16e4802db3fe203f5097b9ce1e46b68d7c712901b4392573ab57" +source = "git+https://github.com/worldcoin/world-id-protocol?rev=d1edfd36bf2aca9eef3644cfc6ab073559dbd52c#d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" dependencies = [ "alloy", "alloy-primitives", @@ -10064,8 +10060,7 @@ dependencies = [ [[package]] name = "world-id-proof" version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07713e21292f8fe6e9c1658d75bca21885e0e8120c22b12acfd56c74dfce4861" +source = "git+https://github.com/worldcoin/world-id-protocol?rev=d1edfd36bf2aca9eef3644cfc6ab073559dbd52c#d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" dependencies = [ "ark-bn254", "ark-ec", @@ -10106,8 +10101,7 @@ dependencies = [ [[package]] name = "world-id-registries" version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe0cea63b2fa06e41523396934e6dcbd40d9fcb88c4017215c477a8fef25589" +source = "git+https://github.com/worldcoin/world-id-protocol?rev=d1edfd36bf2aca9eef3644cfc6ab073559dbd52c#d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" dependencies = [ "alloy", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 835865b5..add7c86f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -103,6 +103,16 @@ walletkit-sqlite = { version = "0.32.2", path = "crates/walletkit-sqlite" } # Unpublished test helpers walletkit-testkit = { path = "crates/walletkit-testkit" } +# TODO: remove once world-id-protocol#1268 is released +# (https://github.com/worldcoin/world-id-protocol/pull/1268) +[patch.crates-io] +world-id-authenticator = { git = "https://github.com/worldcoin/world-id-protocol", rev = "d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" } +world-id-core = { git = "https://github.com/worldcoin/world-id-protocol", rev = "d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" } +world-id-flamingo = { git = "https://github.com/worldcoin/world-id-protocol", rev = "d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" } +world-id-primitives = { git = "https://github.com/worldcoin/world-id-protocol", rev = "d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" } +world-id-proof = { git = "https://github.com/worldcoin/world-id-protocol", rev = "d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" } +world-id-registries = { git = "https://github.com/worldcoin/world-id-protocol", rev = "d1edfd36bf2aca9eef3644cfc6ab073559dbd52c" } + [workspace.lints.clippy] all = { level = "deny", priority = -1 } pedantic = { level = "deny", priority = -1 } diff --git a/crates/walletkit-core/src/registration/approver.rs b/crates/walletkit-core/src/registration/approver.rs index 1fcaef2c..43940b99 100644 --- a/crates/walletkit-core/src/registration/approver.rs +++ b/crates/walletkit-core/src/registration/approver.rs @@ -5,7 +5,8 @@ //! 1. [`PendingRegistration::receive`] takes the encrypted request before code entry. //! 2. [`PendingRegistration::authenticate`] decrypts and validates it with the entered code. //! 3. [`IncomingRegistration::check`] reads the account state and plans the registration. -//! 4. After the consent screen and the platform's user verification, the host calls +//! 4. After the consent screen, where the user selects the credentials to transfer, and the +//! platform's user verification, the host calls //! [`CheckedRegistration::approve`], or declines with [`CheckedRegistration::reject`] or //! [`CheckedRegistration::abort`]. //! @@ -32,10 +33,10 @@ use world_id_core::{ }, }, registration::{ - EncryptedPayload, KnownAuthenticator, PairingCode, PairingUri, + Attachment, EncryptedPayload, KnownAuthenticator, PairingCode, PairingUri, RegistrationDigest, RegistrationErrorData, RegistrationErrorReason, RegistrationRequest, RegistrationResult, RequestId, ResponsePublicKey, - TransportError, TransportKey, Vault, MAX_VAULT_SIZE, REGISTER_METHOD, + TransportError, TransportKey, Vault, MAX_TRANSFER_SIZE, REGISTER_METHOD, }, AccountAuthenticators, AuthenticatorError, }; @@ -48,7 +49,7 @@ use super::{ log_tag, polling_backoff, sleep, types::{ onchain_address, requested_name, ApprovalOutcome, ApprovalResult, - RegistrationPlan, RequestedClass, + CredentialTransfer, RegistrationPlan, RequestedClass, }, PLAINTEXT_VAULT_FORMAT, SESSION_TTL, }; @@ -57,8 +58,8 @@ use crate::Authenticator; /// The largest encoded request (WIP-109 §3.5). const MAX_REQUEST_SIZE: usize = 4 * 1024; -/// The largest encoded response: a full vault plus 4 KiB for the other fields (WIP-109 §3.5). -const MAX_RESPONSE_SIZE: usize = MAX_VAULT_SIZE + 4 * 1024; +/// The largest encoded response: a full transfer plus 4 KiB for the other fields (WIP-109 §3.5). +const MAX_RESPONSE_SIZE: usize = MAX_TRANSFER_SIZE + 4 * 1024; /// How many times the user may enter the pairing code (WIP-109 §3.7.1 step 3). const MAX_CODE_ATTEMPTS: u8 = 3; @@ -264,6 +265,14 @@ impl IncomingRegistration { requested_name(&self.request) } + /// Returns the issuer schemas the new authenticator declares it supports, or `None` if it + /// declares none. The list is self-reported. If it is present, offer the user only + /// credentials of these issuer schemas to transfer. + #[must_use] + pub fn supported_issuer_schema_ids(&self) -> Option> { + self.request.supported_issuer_schema_ids.clone() + } + /// Returns how many seconds are left until the response is due. #[must_use] pub fn time_remaining_secs(&self) -> u64 { @@ -403,6 +412,14 @@ impl CheckedRegistration { requested_name(&self.request) } + /// Returns the issuer schemas the new authenticator declares it supports, or `None` if it + /// declares none. The list is self-reported. If it is present, offer the user only + /// credentials of these issuer schemas to transfer. + #[must_use] + pub fn supported_issuer_schema_ids(&self) -> Option> { + self.request.supported_issuer_schema_ids.clone() + } + /// Returns how the registration will be carried out. #[must_use] pub const fn plan(&self) -> RegistrationPlan { @@ -440,10 +457,18 @@ impl CheckedRegistration { /// Carries out the registration and sends the response (WIP-109 §3.7.4 and §3.7.5). /// /// Call it only after the user consented and the platform's user verification succeeded, - /// also for an authenticator that is already registered (WIP-109 §3.7.3). `vault` is the - /// `CredentialStore::export_vault_for_backup` output, only if the user chose to share it; a - /// vault over [`MAX_VAULT_SIZE`] is left out. `authenticators` names the account's other - /// authenticators. + /// also for an authenticator that is already registered (WIP-109 §3.7.3). `authenticators` + /// names the account's other authenticators. + /// + /// `transfer` holds the credentials the user selected: the + /// `CredentialStore::export_vault_for_issuer_schemas` output for the selected issuer + /// schemas, and the attachments that the issuers' code produced for them. `None` means that + /// the user selected no credentials, so neither a vault nor attachments are sent. + /// + /// The vault and attachments are opaque here, so the host is responsible for what this + /// cannot check: that the vault holds only credentials of the issuer schemas in + /// [`supported_issuer_schema_ids`](Self::supported_issuer_schema_ids), if the request + /// declares them, and that every attachment belongs to a credential in the vault. /// /// Unless the authenticator is already registered, this submits `InsertAuthenticator` and /// tracks it until it is final on-chain or definitively failed. An insertion is never @@ -456,13 +481,27 @@ impl CheckedRegistration { /// Returns [`ApproverError::ApproverMismatch`] if `approver` is not the authenticator that /// [`IncomingRegistration::check`] checked, or [`ApproverError::AlreadyHandled`] if the /// registration was already decided. + /// + /// Two errors are returned before anything is submitted or sent, and leave the session + /// open, so that the host may retry with another selection or explicitly abort: + /// [`ApproverError::UnsupportedAttachment`] for an attachment whose issuer schema the + /// request does not list as supported, and [`ApproverError::TransferTooLarge`] if the vault + /// and attachments together exceed [`MAX_TRANSFER_SIZE`]. pub async fn approve( &self, approver: &Authenticator, - vault: Option>, + transfer: Option, authenticators: Vec, ) -> Result { - let vault = vault.map(Zeroizing::new); + let (vault, attachments) = transfer.map_or_else(Default::default, |transfer| { + let vault = Vault { + format: PLAINTEXT_VAULT_FORMAT.to_string(), + data: Zeroizing::new(transfer.vault), + }; + let attachments: Vec = + transfer.attachments.into_iter().map(Into::into).collect(); + (Some(vault), attachments) + }); let core = &approver.inner; if core.leaf_index() != self.approver_leaf_index @@ -472,20 +511,16 @@ impl CheckedRegistration { return Err(ApproverError::ApproverMismatch); } + self.check_transfer(vault.as_ref(), &attachments)?; let channel = take(&self.channel)?; - let vault_omitted = vault - .as_ref() - .is_some_and(|data| data.len() > MAX_VAULT_SIZE); let mut result = RegistrationResult { leaf_index: self.approver_leaf_index, // Every valid slot encodes to the same single CBOR byte, so checking the size with // this placeholder holds for the slot that registration assigns. pubkey_id: 0, authenticators, - vault: vault.filter(|_| !vault_omitted).map(|data| Vault { - format: PLAINTEXT_VAULT_FORMAT.to_string(), - data, - }), + vault, + attachments, }; let registered = self.register(approver, &channel, &result).await; @@ -516,7 +551,6 @@ impl CheckedRegistration { reason: refusal.reason, }, }, - vault_omitted, delivered, }) } @@ -539,6 +573,38 @@ impl CheckedRegistration { Ok(channel.answer(Err(reason.into_error(None))).await) } + /// Checks that the request supports every attachment and that the transfer fits in a + /// response. + fn check_transfer( + &self, + vault: Option<&Vault>, + attachments: &[Attachment], + ) -> Result<(), ApproverError> { + if let Some(supported) = &self.request.supported_issuer_schema_ids { + if let Some(unsupported) = attachments + .iter() + .find(|attachment| !supported.contains(&attachment.issuer_schema_id)) + { + return Err(ApproverError::UnsupportedAttachment { + issuer_schema_id: unsupported.issuer_schema_id, + }); + } + } + + let mut sizes = vault + .map(|vault| vault.data.len()) + .into_iter() + .chain(attachments.iter().map(|attachment| attachment.data.len())); + let fits = sizes + .try_fold(0_usize, usize::checked_add) + .is_some_and(|size| size <= MAX_TRANSFER_SIZE); + if !fits { + return Err(ApproverError::TransferTooLarge); + } + + Ok(()) + } + /// Registers the authenticator as planned and returns its slot. async fn register( &self, @@ -1049,13 +1115,16 @@ fn secs_until(deadline: Instant) -> u64 { #[cfg(test)] mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + use axum::{ + extract::State, http::StatusCode, routing::{get, post, put}, Json, Router, }; use secrecy::ExposeSecret as _; - use serde_json::Value; + use serde_json::{json, Value}; use test_case::test_case; use tokio::net::TcpListener; use world_id_core::{ @@ -1067,9 +1136,14 @@ mod tests { }; use super::*; - use crate::storage::{ - tests_utils::{temp_root_path, InMemoryStorageProvider}, - CredentialStore, + use crate::{ + registration::{ + RegistrationAttachment, RegistrationRequester, RequesterStatus, + }, + storage::{ + tests_utils::{temp_root_path, InMemoryStorageProvider}, + CredentialStore, + }, }; #[test_case(Some(&GatewayErrorCode::TransactionReverted), true => RegistrationErrorReason::OperationFailed; "a revert is definitive")] @@ -1094,6 +1168,12 @@ mod tests { async fn make_pending_registration() -> (Arc, String, [u8; 32]) { + make_pending_registration_supporting(None).await + } + + async fn make_pending_registration_supporting( + supported_issuer_schema_ids: Option>, + ) -> (Arc, String, [u8; 32]) { let requester_seed = [11u8; 32]; let signer = Signer::from_seed_bytes(&requester_seed).unwrap(); let pairing_secret = PairingSecret::generate().unwrap(); @@ -1106,6 +1186,7 @@ mod tests { None, response_key.public_key(), None, + supported_issuer_schema_ids, &request_id, ) .unwrap(); @@ -1142,60 +1223,179 @@ mod tests { (Arc::new(pending), code.as_str().to_string(), requester_seed) } - async fn make_authenticator_at_url( - seed: [u8; 32], - leaf_index: u64, - service_url: String, - ) -> Authenticator { - let _ = rustls::crypto::ring::default_provider().install_default(); - let config = Config::new( + fn test_config(service_url: &str) -> Config { + Config::new( None, 480, Address::with_last_byte(1), - ServiceEndpoint::direct(service_url.clone()), - ServiceEndpoint::direct(service_url), + ServiceEndpoint::direct(service_url.to_string()), + ServiceEndpoint::direct(service_url.to_string()), Vec::new(), 0, ) - .unwrap(); + .unwrap() + } + + fn test_store() -> Arc { let root = temp_root_path(); let provider = InMemoryStorageProvider::new(&root); let store = Arc::new(CredentialStore::from_provider(&provider).unwrap()); - let authenticator = Authenticator::init_with_leaf_index_and_config( + let _ = std::fs::remove_dir_all(root); + store + } + + async fn make_authenticator_at_url( + seed: [u8; 32], + leaf_index: u64, + service_url: &str, + ) -> Authenticator { + let _ = rustls::crypto::ring::default_provider().install_default(); + Authenticator::init_with_leaf_index_and_config( &seed, leaf_index, - config, + test_config(service_url), Arc::new(DummyZkArtifactSource), - store, + test_store(), ) .await + .unwrap() + } + + /// An indexer for an account whose slots hold the authenticators derived from `seeds`: an + /// Admin Authenticator first, then Proving Authenticators. + fn account_indexer(seeds: &[[u8; 32]]) -> Router { + let signers: Vec = seeds + .iter() + .map(|seed| Signer::from_seed_bytes(seed).unwrap()) + .collect(); + let pubkeys: Vec<_> = + signers.iter().map(Signer::offchain_signer_pubkey).collect(); + let account = serde_json::to_value(IndexerAuthenticatorsResponse { + authenticator_pubkeys: pubkeys + .iter() + .map(|pubkey| Some(pubkey.to_ethereum_representation().unwrap())) + .collect(), + authenticator_addresses: std::iter::once( + signers[0].onchain_signer_address(), + ) + .chain(std::iter::repeat(Address::ZERO)) + .take(signers.len()) + .map(Some) + .collect(), + offchain_signer_commitment: AuthenticatorPublicKeySet::new(pubkeys) + .unwrap() + .leaf_hash() + .into(), + recovery_counter: 0, + }) .unwrap(); - let _ = std::fs::remove_dir_all(root); - authenticator + + Router::new().route( + "/authenticators", + post(move || { + let account = account.clone(); + async move { Json(account) } + }), + ) } async fn make_test_authenticator(seed: [u8; 32], leaf_index: u64) -> Authenticator { - let signer = Signer::from_seed_bytes(&seed).unwrap(); - let pubkey = signer.offchain_signer_pubkey(); - let encoded = pubkey.to_ethereum_representation().unwrap(); - let commitment = AuthenticatorPublicKeySet::new(vec![pubkey]) - .unwrap() - .leaf_hash() - .into(); - let address = signer.onchain_signer_address(); - let indexer_url = serve(Router::new().route( - "/authenticators", - post(move || async move { - Json(IndexerAuthenticatorsResponse { - authenticator_pubkeys: vec![Some(encoded)], - authenticator_addresses: vec![Some(address)], - offchain_signer_commitment: commitment, - recovery_counter: 0, - }) + let indexer_url = serve(account_indexer(&[seed])).await; + make_authenticator_at_url(seed, leaf_index, &indexer_url).await + } + + fn insertions_counted_by(submissions: Arc) -> Router { + Router::new().route( + "/insert-authenticator", + post(move || { + let submissions = submissions.clone(); + async move { + submissions.fetch_add(1, Ordering::SeqCst); + StatusCode::SERVICE_UNAVAILABLE + } }), - )) - .await; - make_authenticator_at_url(seed, leaf_index, indexer_url).await + ) + } + + fn attachment(issuer_schema_id: u64, data: Vec) -> RegistrationAttachment { + RegistrationAttachment { + issuer_schema_id, + format: "pcp_v1".to_string(), + data, + } + } + + fn vault_only(vault: Vec) -> CredentialTransfer { + CredentialTransfer { + vault, + attachments: Vec::new(), + } + } + + /// A transfer of `size` bytes, split between the vault and one attachment. + fn transfer_of(size: usize) -> CredentialTransfer { + CredentialTransfer { + vault: vec![0x42; size - size / 4], + attachments: vec![attachment(7, vec![0x43; size / 4])], + } + } + + #[derive(Default)] + struct BridgeSession { + request: Option, + taken: bool, + response: Option, + } + + /// A message-bridge that holds one session. + fn mock_bridge() -> Router { + type Session = State>>; + + Router::new() + .route( + "/request", + post( + |State(session): Session, Json(mut body): Json| async move { + body.as_object_mut().unwrap().remove("request_id"); + session.lock().unwrap().request = Some(body); + StatusCode::OK + }, + ), + ) + .route( + "/request/{id}", + get(|State(session): Session| async move { + let mut session = session.lock().unwrap(); + session.taken = true; + session + .request + .take() + .map(Json) + .ok_or(StatusCode::NOT_FOUND) + }), + ) + .route( + "/response/{id}", + put( + |State(session): Session, Json(body): Json| async move { + session.lock().unwrap().response = Some(body); + StatusCode::CREATED + }, + ) + .get(|State(session): Session| async move { + let mut session = session.lock().unwrap(); + Json(match session.response.take() { + Some(response) => { + json!({ "status": "completed", "response": response }) + } + None if session.taken => { + json!({ "status": "retrieved", "response": null }) + } + None => json!({ "status": "initialized", "response": null }), + }) + }), + ) + .with_state(Arc::default()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -1236,7 +1436,7 @@ mod tests { let checked = incoming.check(&approver_a).await.unwrap(); assert!(!format!("{checked:?}").contains(&request_id)); let err = checked - .approve(&approver_b, Some(vec![1, 2, 3]), Vec::new()) + .approve(&approver_b, Some(vault_only(vec![1, 2, 3])), Vec::new()) .await .unwrap_err(); assert!(matches!(err, ApproverError::ApproverMismatch), "{err:?}"); @@ -1245,6 +1445,204 @@ mod tests { assert!(checked.reject().await.unwrap()); } + #[test_case(false ; "new insertion")] + #[test_case(true ; "already registered")] + #[tokio::test] + async fn oversized_transfer_is_rejected_without_consuming_the_session( + already_registered: bool, + ) { + let (pending, code, _) = make_pending_registration().await; + let incoming = pending.authenticate(&code).await.unwrap(); + let seed = [21; 32]; + let submissions = Arc::new(AtomicUsize::new(0)); + let service_url = serve( + account_indexer(&[seed]).merge(insertions_counted_by(submissions.clone())), + ) + .await; + let approver = make_authenticator_at_url(seed, 1, &service_url).await; + let mut checked = + Arc::try_unwrap(incoming.check(&approver).await.unwrap()).unwrap(); + assert!(matches!(checked.plan, RegistrationPlan::Insert { .. })); + if already_registered { + checked.plan = RegistrationPlan::AlreadyRegistered { pubkey_id: 1 }; + } + + let err = checked + .approve( + &approver, + Some(transfer_of(MAX_TRANSFER_SIZE + 1)), + Vec::new(), + ) + .await + .unwrap_err(); + assert!(matches!(err, ApproverError::TransferTooLarge)); + assert_eq!( + err.to_string(), + "the vault and attachments exceed the registration transfer size limit" + ); + assert_eq!(submissions.load(Ordering::SeqCst), 0); + assert!(checked.abort().await.unwrap()); + assert!(matches!( + checked.abort().await, + Err(ApproverError::AlreadyHandled) + )); + } + + #[test_case(None ; "without credentials")] + #[test_case(Some(transfer_of(MAX_TRANSFER_SIZE)) ; "exact size limit")] + #[tokio::test] + async fn supported_transfer_sizes_can_be_approved_after_an_oversize_error( + transfer: Option, + ) { + let (pending, code, _) = make_pending_registration().await; + let incoming = pending.authenticate(&code).await.unwrap(); + let approver = make_test_authenticator([21; 32], 1).await; + let mut checked = + Arc::try_unwrap(incoming.check(&approver).await.unwrap()).unwrap(); + checked.plan = RegistrationPlan::AlreadyRegistered { pubkey_id: 1 }; + assert!(matches!( + checked + .approve( + &approver, + Some(transfer_of(MAX_TRANSFER_SIZE + 1)), + Vec::new() + ) + .await, + Err(ApproverError::TransferTooLarge) + )); + + let outcome = checked + .approve(&approver, transfer, Vec::new()) + .await + .unwrap(); + assert_eq!( + outcome.result, + ApprovalResult::Registered { + leaf_index: 1, + pubkey_id: 1 + } + ); + assert!(outcome.delivered); + assert!(matches!( + checked.abort().await, + Err(ApproverError::AlreadyHandled) + )); + } + + #[tokio::test] + async fn attachment_for_an_undeclared_issuer_schema_is_rejected_without_consuming_the_session( + ) { + let (pending, code, _) = + make_pending_registration_supporting(Some(vec![7, 9])).await; + let incoming = pending.authenticate(&code).await.unwrap(); + let seed = [21; 32]; + let submissions = Arc::new(AtomicUsize::new(0)); + let service_url = serve( + account_indexer(&[seed]).merge(insertions_counted_by(submissions.clone())), + ) + .await; + let approver = make_authenticator_at_url(seed, 1, &service_url).await; + let checked = incoming.check(&approver).await.unwrap(); + assert!(matches!(checked.plan(), RegistrationPlan::Insert { .. })); + + let transfer = CredentialTransfer { + vault: vec![1, 2, 3], + attachments: vec![attachment(9, vec![4]), attachment(8, vec![5])], + }; + let err = checked + .approve(&approver, Some(transfer), Vec::new()) + .await + .unwrap_err(); + assert!( + matches!( + err, + ApproverError::UnsupportedAttachment { + issuer_schema_id: 8 + } + ), + "{err:?}" + ); + assert_eq!(submissions.load(Ordering::SeqCst), 0); + assert!(checked.reject().await.unwrap()); + } + + #[tokio::test] + async fn selected_credentials_and_attachments_reach_the_verified_requester() { + let (approver_seed, requester_seed) = ([23u8; 32], [24u8; 32]); + let bridge_url = serve(mock_bridge()).await; + let bridge = Arc::new( + BridgeClient::with_base_url("bridge.example", &bridge_url).unwrap(), + ); + let requester = RegistrationRequester::start( + requester_seed.to_vec(), + RequestedClass::Proving, + None, + Some(vec![7, 9]), + bridge.clone(), + ) + .await + .unwrap(); + + let uri = requester.pairing_uri().unwrap(); + let pending = PendingRegistration::receive(&uri, vec![bridge]) + .await + .unwrap(); + assert_eq!(requester.poll().await.unwrap(), RequesterStatus::Retrieved); + let code = requester.pairing_code().unwrap(); + let incoming = pending.authenticate(&code).await.unwrap(); + assert_eq!(incoming.supported_issuer_schema_ids(), Some(vec![7, 9])); + + // The account already holds the requester's key, so approving only sends the result. + let service_url = + serve(account_indexer(&[approver_seed, requester_seed])).await; + let approver = make_authenticator_at_url(approver_seed, 1, &service_url).await; + let checked = incoming.check(&approver).await.unwrap(); + assert_eq!( + checked.plan(), + RegistrationPlan::AlreadyRegistered { pubkey_id: 1 } + ); + assert_eq!(checked.supported_issuer_schema_ids(), Some(vec![7, 9])); + + let attachments = vec![ + attachment(7, b"custody package".to_vec()), + attachment(9, Vec::new()), + ]; + let transfer = CredentialTransfer { + vault: b"selected credentials".to_vec(), + attachments: attachments.clone(), + }; + let debug = format!("{transfer:?}"); + assert!(!debug.contains(&format!("{:?}", b"selected credentials"))); + assert!(!debug.contains(&format!("{:?}", b"custody package"))); + let outcome = checked + .approve(&approver, Some(transfer), Vec::new()) + .await + .unwrap(); + assert!(outcome.delivered); + + let RequesterStatus::Approved { result } = requester.poll().await.unwrap() + else { + panic!("the registration was not approved"); + }; + assert!(result.has_vault()); + assert_eq!(result.attachment_count(), 2); + let registered = requester + .verify_with_config( + &requester_seed, + &result, + test_config(&service_url), + Arc::new(DummyZkArtifactSource), + test_store(), + ) + .await + .unwrap(); + assert_eq!( + registered.vault_backup.as_deref(), + Some(b"selected credentials".as_slice()) + ); + assert_eq!(registered.attachments, attachments); + } + fn make_account( slots: &[(world_id_core::EdDSAPublicKey, Address)], ) -> AccountAuthenticators { @@ -1290,6 +1688,7 @@ mod tests { addr, ResponseSecretKey::generate().unwrap().public_key(), None, + None, &request_id, ) .unwrap() @@ -1352,79 +1751,25 @@ mod tests { let incoming = pending.authenticate(&code).await.unwrap(); let seed = [61u8; 32]; - let signer = Signer::from_seed_bytes(&seed).unwrap(); - let pubkey = signer.offchain_signer_pubkey(); - let encoded = pubkey.to_ethereum_representation().unwrap(); - let commitment = AuthenticatorPublicKeySet::new(vec![pubkey]) - .unwrap() - .leaf_hash() - .into(); - let address = signer.onchain_signer_address(); - let submissions = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let submissions_clone = submissions.clone(); + let submissions = Arc::new(AtomicUsize::new(0)); let service_url = serve( - Router::new() - .route( - "/authenticators", - post(move || async move { - Json(IndexerAuthenticatorsResponse { - authenticator_pubkeys: vec![Some(encoded)], - authenticator_addresses: vec![Some(address)], - offchain_signer_commitment: commitment, - recovery_counter: 0, - }) - }), - ) + account_indexer(&[seed]) .route( "/signature-nonce", - post(|| async { - Json(serde_json::json!({ "signature_nonce": "0x0" })) - }), + post(|| async { Json(json!({ "signature_nonce": "0x0" })) }), ) - .route( - "/insert-authenticator", - post(move || { - let submissions = submissions_clone.clone(); - async move { - submissions - .fetch_add(1, std::sync::atomic::Ordering::SeqCst); - StatusCode::SERVICE_UNAVAILABLE - } - }), - ), + .merge(insertions_counted_by(submissions.clone())), ) .await; - let config = Config::new( - None, - 480, - Address::with_last_byte(1), - ServiceEndpoint::direct(service_url.clone()), - ServiceEndpoint::direct(service_url), - Vec::new(), - 0, - ) - .unwrap(); - let root = temp_root_path(); - let provider = InMemoryStorageProvider::new(&root); - let store = Arc::new(CredentialStore::from_provider(&provider).unwrap()); - let approver = Authenticator::init_with_leaf_index_and_config( - &seed, - 1, - config, - Arc::new(DummyZkArtifactSource), - store, - ) - .await - .unwrap(); - let _ = std::fs::remove_dir_all(root); + let approver = make_authenticator_at_url(seed, 1, &service_url).await; let checked = incoming.check(&approver).await.unwrap(); let outcome = checked - .approve(&approver, Some(vec![1, 2, 3]), Vec::new()) + .approve(&approver, Some(vault_only(vec![1, 2, 3])), Vec::new()) .await .unwrap(); assert_eq!( - submissions.load(std::sync::atomic::Ordering::SeqCst), + submissions.load(Ordering::SeqCst), 1, "an ambiguous submission must never be retried" ); @@ -1449,6 +1794,7 @@ mod tests { None, response_pk, None, + None, &request_id, ) .unwrap(); @@ -1498,6 +1844,7 @@ mod tests { None, ResponseSecretKey::generate().unwrap().public_key(), None, + None, &request_id, ) .unwrap(); @@ -1510,7 +1857,6 @@ mod tests { seed: [u8; 32], requester_seed: [u8; 32], ) -> String { - use std::sync::atomic::{AtomicUsize, Ordering}; use world_id_core::api_types::{ GatewayRequestId, GatewayRequestKind, GatewayStatusResponse, }; @@ -1612,11 +1958,11 @@ mod tests { let incoming = pending.authenticate(&code).await.unwrap(); let seed = [62u8; 32]; let service_url = lagging_insert_service(seed, requester_seed).await; - let approver = make_authenticator_at_url(seed, 1, service_url).await; + let approver = make_authenticator_at_url(seed, 1, &service_url).await; let checked = incoming.check(&approver).await.unwrap(); let outcome = checked - .approve(&approver, Some(vec![1, 2, 3]), Vec::new()) + .approve(&approver, Some(vault_only(vec![1, 2, 3])), Vec::new()) .await .unwrap(); assert_eq!( diff --git a/crates/walletkit-core/src/registration/bridge.rs b/crates/walletkit-core/src/registration/bridge.rs index ae3b14a2..2e93658f 100644 --- a/crates/walletkit-core/src/registration/bridge.rs +++ b/crates/walletkit-core/src/registration/bridge.rs @@ -11,11 +11,31 @@ use world_id_core::registration::{BridgeDomain, EncryptedPayload, RequestId}; use super::{before, errors::BridgeError, sleep}; -/// The message-bridge's body limit, which the largest WIP-109 response fits within. -const MAX_BODY_SIZE: usize = 5 * 1024 * 1024; - -/// The time budget of one operation, including its retries and reading the response. -const OPERATION_TIMEOUT: Duration = Duration::from_mins(1); +/// The largest body read from the bridge. The largest WIP-109 response, 15 MiB plus 4 KiB, takes +/// about 20 MiB once it is sealed, encrypted and carried as base64 in JSON. +const MAX_BODY_SIZE: usize = 22 * 1024 * 1024; + +/// The time limits of the operations that carry at most a request or a response state. +const CONTROL_LIMITS: TimeLimits = TimeLimits { + request_timeout: Duration::from_secs(30), + operation_timeout: Duration::from_mins(1), +}; + +/// The time limits of the operations that can carry a full response (`PUT /response/:id` and +/// `GET /response/:id`), sized for a slow mobile connection. +const RESPONSE_TRANSFER_LIMITS: TimeLimits = TimeLimits { + request_timeout: Duration::from_mins(2), + operation_timeout: Duration::from_mins(5), +}; + +/// How long a bridge operation may take. +#[derive(Clone, Copy)] +struct TimeLimits { + /// The timeout of each HTTP request, from sending it to the end of its response body. + request_timeout: Duration, + /// The time budget of the whole operation, including its retries and reading the response. + operation_timeout: Duration, +} /// A client for one bridge deployment. /// @@ -117,9 +137,10 @@ impl BridgeClient { request, }; - bounded(async { + let limits = CONTROL_LIMITS; + bounded(limits, async { let response = self - .send(self.http.post(self.url(&["request"])).json(&body)) + .send(self.http.post(self.url(&["request"])).json(&body), limits) .await?; match response.status() { @@ -136,8 +157,11 @@ impl BridgeClient { &self, request_id: &RequestId, ) -> Result, BridgeError> { - self.read(self.url(&["request", &request_id.to_string()])) - .await + self.read( + self.url(&["request", &request_id.to_string()]), + CONTROL_LIMITS, + ) + .await } /// Reads the state of the response (`GET /response/:id`), consuming a completed one. Returns @@ -146,8 +170,11 @@ impl BridgeClient { &self, request_id: &RequestId, ) -> Result, BridgeError> { - self.read(self.url(&["response", &request_id.to_string()])) - .await + self.read( + self.url(&["response", &request_id.to_string()]), + RESPONSE_TRANSFER_LIMITS, + ) + .await } /// Stores the encrypted response (`PUT /response/:id`). The bridge answers `201` once it @@ -161,8 +188,9 @@ impl BridgeClient { ) -> Result<(), BridgeError> { let url = self.url(&["response", &request_id.to_string()]); - bounded(async { - let reply = self.send(self.http.put(url).json(response)).await?; + let limits = RESPONSE_TRANSFER_LIMITS; + bounded(limits, async { + let reply = self.send(self.http.put(url).json(response), limits).await?; match reply.status() { StatusCode::CREATED => Ok(()), @@ -176,9 +204,10 @@ impl BridgeClient { async fn read( &self, url: Url, + limits: TimeLimits, ) -> Result, BridgeError> { - bounded(async { - let response = self.send(self.http.get(url)).await?; + bounded(limits, async { + let response = self.send(self.http.get(url), limits).await?; match response.status() { StatusCode::OK => read_json(response).await.map(Some), @@ -190,8 +219,12 @@ impl BridgeClient { } /// Sends `request`, retrying transient failures while honoring `Retry-After`. - async fn send(&self, request: RequestBuilder) -> Result { - let request = request.timeout(Duration::from_secs(30)).build()?; + async fn send( + &self, + request: RequestBuilder, + limits: TimeLimits, + ) -> Result { + let request = request.timeout(limits.request_timeout).build()?; let mut delays = retry_backoff().build(); loop { @@ -256,7 +289,7 @@ fn http_client(base_url: &Url) -> Result { let origin = base_url.clone(); builder .connect_timeout(Duration::from_secs(10)) - .timeout(Duration::from_secs(30)) + .timeout(CONTROL_LIMITS.request_timeout) .redirect(reqwest::redirect::Policy::custom(move |attempt| { if attempt.previous().len() >= 10 { return attempt.error("too many redirects"); @@ -350,11 +383,12 @@ fn parse_http_date(value: &str) -> Option { .checked_add(hour * 3_600 + minute * 60 + second.min(59)) } -/// Runs a bridge operation within [`OPERATION_TIMEOUT`]. +/// Runs a bridge operation within the operation timeout of `limits`. async fn bounded( + limits: TimeLimits, operation: impl Future>, ) -> Result { - before(Instant::now() + OPERATION_TIMEOUT, operation) + before(Instant::now() + limits.operation_timeout, operation) .await .unwrap_or(Err(BridgeError::Timeout)) } @@ -434,6 +468,48 @@ mod tests { assert_eq!(err, BridgeError::UnexpectedStatus { status: 409 }); } + #[tokio::test] + async fn fetch_response_reads_a_full_response_and_rejects_a_larger_body() { + fn completed(payload_len: usize) -> Json { + Json(serde_json::json!({ + "status": "completed", + "response": { "iv": "aXY=", "payload": "A".repeat(payload_len) }, + })) + } + + let url = serve( + Router::new() + .route( + "/response/full", + get(|| async { completed(21 * 1024 * 1024) }), + ) + .route( + "/response/oversized", + get(|| async { completed(MAX_BODY_SIZE) }), + ), + ) + .await; + let client = BridgeClient::with_base_url("bridge.example", &url).unwrap(); + let fetch = |id: &'static str| { + let client = &client; + async move { + client + .read::( + client.url(&["response", id]), + RESPONSE_TRANSFER_LIMITS, + ) + .await + } + }; + + assert!(matches!( + fetch("full").await, + Ok(Some(ResponseState::Completed(sealed))) + if sealed.payload.len() == 21 * 1024 * 1024 + )); + assert_eq!(fetch("oversized").await.err(), Some(BridgeError::TooLarge)); + } + #[tokio::test] async fn redirect_policy_follows_same_origin_and_stops_cross_origin() { let other_hits = Arc::new(AtomicUsize::new(0)); diff --git a/crates/walletkit-core/src/registration/errors.rs b/crates/walletkit-core/src/registration/errors.rs index ab05d616..c4114fb5 100644 --- a/crates/walletkit-core/src/registration/errors.rs +++ b/crates/walletkit-core/src/registration/errors.rs @@ -31,8 +31,8 @@ pub enum BridgeError { /// The bridge returned malformed JSON. #[error("invalid bridge response: {0}")] Json(String), - /// The bridge response exceeded the bridge's body limit. - #[error("bridge response exceeds the 5 MiB body limit")] + /// The bridge response exceeded the largest body this client reads. + #[error("bridge response exceeds the body size limit")] TooLarge, /// The operation exhausted its time budget. #[error("bridge operation timed out")] @@ -188,6 +188,21 @@ pub enum ApproverError { /// [`IncomingRegistration::check`](super::IncomingRegistration::check) checked. #[error("the approver does not match the checked account")] ApproverMismatch, + /// The supplied vault and attachments together exceed + /// [`MAX_TRANSFER_SIZE`](super::MAX_TRANSFER_SIZE). Nothing was submitted or sent; the host + /// may retry with a smaller selection or abort the checked session. + #[error("the vault and attachments exceed the registration transfer size limit")] + TransferTooLarge, + /// A supplied attachment belongs to an issuer schema that the request does not list as + /// supported. Nothing was submitted or sent; the host may retry without it or abort the + /// checked session. + #[error( + "the request does not support attachments for issuer schema {issuer_schema_id}" + )] + UnsupportedAttachment { + /// The issuer schema of the offending attachment. + issuer_schema_id: u64, + }, /// This step was already taken, so the registration has moved on or ended. #[error("this registration step was already taken")] AlreadyHandled, diff --git a/crates/walletkit-core/src/registration/mod.rs b/crates/walletkit-core/src/registration/mod.rs index 10af5209..fd11da80 100644 --- a/crates/walletkit-core/src/registration/mod.rs +++ b/crates/walletkit-core/src/registration/mod.rs @@ -12,6 +12,15 @@ //! Every outcome is answered to the Requesting Authenticator, which verifies a successful result //! with [`RegistrationRequester::verify`]. //! +//! The approval carries the credentials the user selected, as a [`CredentialTransfer`]: a vault +//! exported for the selected issuer schemas, and the issuers' [`RegistrationAttachment`]s, which +//! `WalletKit` never interprets. The Requesting Authenticator may declare the issuer schemas it +//! supports; the host should offer only those, and attachments for others are rejected. +//! +//! [`CheckedRegistration::approve`] returns [`ApproverError::TransferTooLarge`] or +//! [`ApproverError::UnsupportedAttachment`] before submission for a transfer that cannot be +//! sent. The session stays open for an explicit retry or abort; nothing is silently omitted. +//! //! The wire format and cryptography come from [`world_id_core::registration`]. //! //! # Blocking key derivation @@ -38,16 +47,17 @@ pub use bridge::BridgeClient; pub use errors::{ApproverError, BridgeError, RegistrationError, RequesterError}; pub use requester::RegistrationRequester; pub use types::{ - ApprovalOutcome, ApprovalResult, Registered, RegistrationPlan, RegistrationResult, - RequestedClass, RequesterStatus, + ApprovalOutcome, ApprovalResult, CredentialTransfer, Registered, + RegistrationAttachment, RegistrationPlan, RegistrationResult, RequestedClass, + RequesterStatus, }; pub use world_id_core::registration::{ AuthenticatorName, BridgeDomain, KnownAuthenticator, PairingCode, PairingUri, RegistrationErrorData, RegistrationErrorReason, RegistrationRequest, - TransportError, MAX_NAME_LEN, MAX_VAULT_SIZE, + TransportError, MAX_NAME_LEN, MAX_TRANSFER_SIZE, }; -/// The format of the shared vault: a `CredentialStore::export_vault_for_backup` export. +/// The format of the shared vault: a `CredentialStore::export_vault_for_issuer_schemas` export. const PLAINTEXT_VAULT_FORMAT: &str = "walletkit_plaintext_v1"; /// The message-bridge session lifetime, from which both sides estimate the session expiry diff --git a/crates/walletkit-core/src/registration/requester.rs b/crates/walletkit-core/src/registration/requester.rs index e7533f19..57a88865 100644 --- a/crates/walletkit-core/src/registration/requester.rs +++ b/crates/walletkit-core/src/registration/requester.rs @@ -64,18 +64,25 @@ impl RegistrationRequester { /// Starts a session for the authenticator derived from `seed` and publishes its request on /// `bridge`, whose domain goes into the Pairing URI. /// + /// `supported_issuer_schema_ids` declares the issuer schemas whose credentials and + /// attachments this authenticator can use, so that the Approving Authenticator offers only + /// those. `None` declares nothing. + /// /// This blocks while it derives the transport key with Argon2id (64 MiB). In a browser, call /// it from a Web Worker. /// /// # Errors /// - /// Returns an error if the seed or name is invalid, the CSPRNG is unavailable, the request - /// cannot be encoded or encrypted, or the bridge does not store it. + /// Returns an error if the seed or name is invalid, `supported_issuer_schema_ids` repeats an + /// ID ([`RequesterError::Authenticator`] with `InvalidInput`) or does not fit in the + /// request, the CSPRNG is unavailable, the request cannot be encoded or encrypted, or the + /// bridge does not store it. #[uniffi::constructor] pub async fn start( seed: Vec, class: RequestedClass, name: Option, + supported_issuer_schema_ids: Option>, bridge: Arc, ) -> Result { let seed = Zeroizing::new(seed); @@ -98,6 +105,7 @@ impl RegistrationRequester { (class == RequestedClass::Admin).then(|| signer.onchain_signer_address()), response_key.public_key(), name, + supported_issuer_schema_ids, &request_id, ) .map_err(AuthenticatorError::from)?; @@ -306,7 +314,7 @@ impl RegistrationRequester { /// /// The indexer must show this session's key at `result.pubkey_id` on `result.leaf_index`, /// with the requested class. Until this succeeds the authenticator must not consider itself - /// registered. The indexer may lag behind the registry, so this retries for up to a minute. + /// registered, and the vault and attachments are not released. The indexer may lag behind the registry, so this retries for up to a minute. /// /// # Errors /// @@ -382,6 +390,7 @@ impl RegistrationRequester { nullifier_reuse_whitelist: RwLock::default(), }), vault_backup: result.0.vault.as_ref().map(|vault| vault.data.to_vec()), + attachments: result.0.attachments.iter().map(Into::into).collect(), }) } @@ -517,12 +526,17 @@ mod tests { api_types::IndexerAuthenticatorsResponse, artifacts::dummy::DummyZkArtifactSource, primitives::{AuthenticatorPublicKeySet, ServiceEndpoint}, - registration::{RegistrationResult as CoreRegistrationResult, Vault}, + registration::{ + Attachment, RegistrationResult as CoreRegistrationResult, Vault, + }, OnchainKeyRepresentable as _, }; use super::*; - use crate::storage::tests_utils::{temp_root_path, InMemoryStorageProvider}; + use crate::{ + registration::RegistrationAttachment, + storage::tests_utils::{temp_root_path, InMemoryStorageProvider}, + }; async fn serve(app: Router) -> String { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -554,6 +568,7 @@ mod tests { vec![7u8; 32], RequestedClass::Proving, None, + None, bridge, ) .await @@ -567,6 +582,32 @@ mod tests { assert!(requester.pairing_code().is_some()); } + #[tokio::test] + async fn start_rejects_repeated_supported_issuer_schema_ids() { + let bridge = Arc::new(BridgeClient::new("bridge.example").unwrap()); + + let err = RegistrationRequester::start( + vec![7u8; 32], + RequestedClass::Proving, + None, + Some(vec![1, 2, 1]), + bridge, + ) + .await + .unwrap_err(); + + assert!( + matches!( + &err, + RequesterError::Authenticator(WalletKitError::InvalidInput { + attribute, + .. + }) if attribute == "supported_issuer_schema_ids" + ), + "{err:?}" + ); + } + #[tokio::test] async fn cancel_during_in_flight_poll_is_not_undone() { let entered = Arc::new(Notify::new()); @@ -596,6 +637,7 @@ mod tests { vec![9u8; 32], RequestedClass::Proving, None, + None, bridge, ) .await @@ -758,6 +800,7 @@ mod tests { seed.to_vec(), RequestedClass::Proving, None, + None, bridge, ) .await @@ -785,7 +828,13 @@ mod tests { format: PLAINTEXT_VAULT_FORMAT.to_string(), data: Zeroizing::new(b"secret-vault-bytes".to_vec()), }), + attachments: vec![Attachment { + issuer_schema_id: 7, + format: "pcp_v1".to_string(), + data: Zeroizing::new(b"secret-attachment-bytes".to_vec()), + }], }); + assert_eq!(result.attachment_count(), 1); let verify = |s: [u8; 32]| { let (config, store, result) = (config.clone(), store.clone(), &result); let requester = &requester; @@ -818,10 +867,19 @@ mod tests { let registered = verify(seed).await.unwrap(); let debug = format!("{registered:?}"); assert!(debug.contains("") && !debug.contains("secret-vault-bytes")); + assert!(!debug.contains(&format!("{:?}", b"secret-attachment-bytes"))); assert_eq!( registered.vault_backup.as_deref(), Some(b"secret-vault-bytes".as_slice()) ); + assert_eq!( + registered.attachments, + [RegistrationAttachment { + issuer_schema_id: 7, + format: "pcp_v1".to_string(), + data: b"secret-attachment-bytes".to_vec(), + }] + ); let _ = std::fs::remove_dir_all(root); } } diff --git a/crates/walletkit-core/src/registration/types.rs b/crates/walletkit-core/src/registration/types.rs index b10a3ad8..4dcc0791 100644 --- a/crates/walletkit-core/src/registration/types.rs +++ b/crates/walletkit-core/src/registration/types.rs @@ -4,9 +4,10 @@ use std::sync::Arc; use alloy_core::primitives::Address; use world_id_core::registration::{ - KnownAuthenticator, RegistrationErrorReason, RegistrationRequest, + Attachment, KnownAuthenticator, RegistrationErrorReason, RegistrationRequest, RegistrationResult as CoreRegistrationResult, }; +use zeroize::Zeroizing; use super::errors::RegistrationError; use crate::Authenticator; @@ -68,7 +69,8 @@ impl RegistrationResult { self.0.authenticators.clone() } - /// Returns whether the Approving Authenticator included a credential vault backup. + /// Returns whether the Approving Authenticator included a vault with the credentials the + /// user selected. /// /// The vault bytes themselves are returned in [`Registered::vault_backup`] only after /// [`RegistrationRequester::verify`](super::RegistrationRequester::verify) confirms the @@ -77,6 +79,85 @@ impl RegistrationResult { pub const fn has_vault(&self) -> bool { self.0.vault.is_some() } + + /// Returns how many attachments the Approving Authenticator included. + /// + /// The attachments themselves are returned in [`Registered::attachments`], together with + /// the vault. + #[must_use] + pub fn attachment_count(&self) -> u64 { + u64::try_from(self.0.attachments.len()).unwrap_or(u64::MAX) + } +} + +/// Data that an issuer's code attaches to a transferred credential, e.g. a Personal Custody +/// Package. +/// +/// `WalletKit` carries `format` and `data` without interpreting them. The host passes both to +/// the code of the issuer of `issuer_schema_id`, which must treat received ones as untrusted +/// input. The data may be biometric: never log it. +#[derive(Clone, PartialEq, Eq, uniffi::Record)] +pub struct RegistrationAttachment { + /// The issuer schema of the credential the attachment belongs to. + pub issuer_schema_id: u64, + /// The format of `data`, defined by the issuer's code. + pub format: String, + /// The attachment bytes. + pub data: Vec, +} + +impl std::fmt::Debug for RegistrationAttachment { + /// Formats [`RegistrationAttachment`] with the length of `data` instead of its bytes. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RegistrationAttachment") + .field("issuer_schema_id", &self.issuer_schema_id) + .field("format", &self.format) + .field("len", &self.data.len()) + .finish_non_exhaustive() + } +} + +impl From for Attachment { + /// Moves the attachment into its wire form, whose bytes are zeroized on drop. + fn from(attachment: RegistrationAttachment) -> Self { + Self { + issuer_schema_id: attachment.issuer_schema_id, + format: attachment.format, + data: Zeroizing::new(attachment.data), + } + } +} + +impl From<&Attachment> for RegistrationAttachment { + /// Copies a received attachment out for the host. + fn from(attachment: &Attachment) -> Self { + Self { + issuer_schema_id: attachment.issuer_schema_id, + format: attachment.format.clone(), + data: attachment.data.to_vec(), + } + } +} + +/// The credentials the user selected to transfer to the new authenticator, passed to +/// [`CheckedRegistration::approve`](super::CheckedRegistration::approve). +#[derive(Clone, PartialEq, Eq, uniffi::Record)] +pub struct CredentialTransfer { + /// The `CredentialStore::export_vault_for_issuer_schemas` output for the issuer schemas the + /// user selected. + pub vault: Vec, + /// Issuer-specific data for the credentials in `vault`. + pub attachments: Vec, +} + +impl std::fmt::Debug for CredentialTransfer { + /// Formats [`CredentialTransfer`] with the length of `vault` instead of its plaintext bytes. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CredentialTransfer") + .field("vault_len", &self.vault.len()) + .field("attachments", &self.attachments) + .finish() + } } /// What [`RegistrationRequester::poll`](super::RegistrationRequester::poll) found on the bridge. @@ -107,13 +188,20 @@ pub enum RequesterStatus { pub struct Registered { /// The new authenticator. Its storage is not initialized yet. pub authenticator: Arc, - /// The shared `CredentialStore::export_vault_for_backup` output, to import with - /// `CredentialStore::merge_vault_from_backup` once storage is initialized. + /// The `CredentialStore::export_vault_for_issuer_schemas` output for the credentials the + /// user selected on the Approving Authenticator, to import with + /// `CredentialStore::merge_vault_from_backup` once storage is initialized. `None` if the + /// user selected none. pub vault_backup: Option>, + /// Issuer-specific data for the credentials in `vault_backup`, to hand to the code of each + /// attachment's issuer as untrusted input. The Approving Authenticator is not bound to the + /// issuer schemas this session declared, so the host should warn the user about an + /// attachment it does not recognize, and drop it. + pub attachments: Vec, } impl std::fmt::Debug for Registered { - /// Formats [`Registered`] without printing the plaintext `vault_backup` bytes. + /// Formats [`Registered`] without printing the plaintext `vault_backup` or attachment bytes. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Registered") .field("authenticator", &self.authenticator) @@ -121,6 +209,7 @@ impl std::fmt::Debug for Registered { "vault_backup", &self.vault_backup.as_ref().map(|_| ""), ) + .field("attachments", &self.attachments) .finish() } } @@ -146,9 +235,6 @@ pub enum RegistrationPlan { pub struct ApprovalOutcome { /// Whether the authenticator was registered. pub result: ApprovalResult, - /// Whether the vault was left out because it exceeds [`MAX_VAULT_SIZE`](super::MAX_VAULT_SIZE). - /// The host must tell the user that the vault was not shared. - pub vault_omitted: bool, /// Whether the response was delivered. pub delivered: bool, } diff --git a/crates/walletkit-core/tests/registration_integration.rs b/crates/walletkit-core/tests/registration_integration.rs index cd5ae104..faa84f7b 100644 --- a/crates/walletkit-core/tests/registration_integration.rs +++ b/crates/walletkit-core/tests/registration_integration.rs @@ -23,10 +23,11 @@ use tempfile::TempDir; use tokio::sync::oneshot; use walletkit_core::{ registration::{ - ApprovalOutcome, ApprovalResult, BridgeClient, KnownAuthenticator, - PendingRegistration, RegistrationPlan, RegistrationRequester, RequestedClass, - RequesterStatus, + ApprovalOutcome, ApprovalResult, BridgeClient, CredentialTransfer, + KnownAuthenticator, PendingRegistration, RegistrationAttachment, + RegistrationPlan, RegistrationRequester, RequestedClass, RequesterStatus, }, + storage::CredentialStore, Authenticator, Environment, Region, }; use walletkit_testkit::{init_and_register_account, TestEnv}; @@ -35,6 +36,9 @@ use world_id_core::artifacts::dummy::DummyZkArtifactSource; /// Staging message-bridge deployment. const STAGING_BRIDGE_DOMAIN: &str = "staging-bridge.worldcoin.org"; +/// The issuer schema the requesting device declares it supports. +const SUPPORTED_ISSUER_SCHEMA_ID: u64 = 1; + #[tokio::test(flavor = "multi_thread")] async fn a_proving_authenticator_registers_through_an_admin_authenticator() { let _ = rustls::crypto::ring::default_provider().install_default(); @@ -52,7 +56,6 @@ async fn a_proving_authenticator_registers_through_an_admin_authenticator() { ) .await .expect("staging account registration should succeed"); - let vault = approver_store.export_vault_for_backup().unwrap(); let leaf_index = approver.leaf_index(); let bridge = Arc::new(BridgeClient::new(STAGING_BRIDGE_DOMAIN).unwrap()); @@ -62,7 +65,7 @@ async fn a_proving_authenticator_registers_through_an_admin_authenticator() { let (code_tx, code_rx) = oneshot::channel(); let approving = tokio::spawn(approving_device( approver, - vault, + approver_store, bridge.clone(), uri_rx, code_rx, @@ -83,7 +86,6 @@ async fn a_proving_authenticator_registers_through_an_admin_authenticator() { let approval = approval.unwrap(); let registered = registered.unwrap(); assert!(approval.delivered); - assert!(!approval.vault_omitted); assert_eq!( approval.result, ApprovalResult::Registered { @@ -108,10 +110,10 @@ async fn a_proving_authenticator_registers_through_an_admin_authenticator() { } /// Takes the request from the scanned QR code, checks it with the code the user typed, and -/// approves it with the vault. +/// approves it with the credentials of the issuer schemas the requesting device supports. async fn approving_device( approver: Authenticator, - vault: Vec, + store: Arc, bridge: Arc, uri: oneshot::Receiver, code: oneshot::Receiver, @@ -128,13 +130,28 @@ async fn approving_device( pubkey_id: 0, name: "iPhone".to_string(), }]; + let supported = checked.supported_issuer_schema_ids().unwrap(); + assert_eq!(supported, [SUPPORTED_ISSUER_SCHEMA_ID]); + let transfer = CredentialTransfer { + vault: store.export_vault_for_issuer_schemas(supported).unwrap(), + attachments: vec![attachment()], + }; checked - .approve(&approver, Some(vault), others) + .approve(&approver, Some(transfer), others) .await .unwrap() } -/// Shows the QR code, then the pairing code, verifies the result and imports the vault. +fn attachment() -> RegistrationAttachment { + RegistrationAttachment { + issuer_schema_id: SUPPORTED_ISSUER_SCHEMA_ID, + format: "test_v1".to_string(), + data: b"issuer-defined bytes".to_vec(), + } +} + +/// Shows the QR code, then the pairing code, verifies the result, imports the vault and receives +/// the attachment. async fn requesting_device( seed: [u8; 32], rpc_url: String, @@ -146,6 +163,7 @@ async fn requesting_device( seed.to_vec(), RequestedClass::Proving, Some("Chrome on MacBook".to_string()), + Some(vec![SUPPORTED_ISSUER_SCHEMA_ID]), bridge, ) .await @@ -164,6 +182,7 @@ async fn requesting_device( }; assert_eq!(result.authenticators()[0].name, "iPhone"); assert!(result.has_vault()); + assert_eq!(result.attachment_count(), 1); let store = common::create_test_credential_store(); let registered = requester .verify_with_defaults( @@ -181,6 +200,7 @@ async fn requesting_device( store .merge_vault_from_backup(®istered.vault_backup.unwrap()) .unwrap(); + assert_eq!(registered.attachments, [attachment()]); registered.authenticator } diff --git a/deny.toml b/deny.toml index 76b251ac..177ba9e0 100644 --- a/deny.toml +++ b/deny.toml @@ -4,6 +4,9 @@ all-features = true [sources] unknown-registry = "deny" +# TODO: remove once world-id-protocol#1268 is released +# (https://github.com/worldcoin/world-id-protocol/pull/1268) +allow-git = ["https://github.com/worldcoin/world-id-protocol"] [bans] deny = [ diff --git a/docs/accounts.md b/docs/accounts.md index 19599c86..4ed28f1d 100644 --- a/docs/accounts.md +++ b/docs/accounts.md @@ -22,6 +22,62 @@ database key in the device keystore; for the types involved, see the In the browser, the app supplies the key itself; see [Protect the database key](web/package.md#protect-the-database-key). +## Transfer credentials to a new authenticator + +In a WIP-109 registration, the user selects on the approving device which +credentials to transfer to the new authenticator, per issuer schema. The transfer +has two parts: + +- **The vault.** `CredentialStore::export_vault_for_issuer_schemas` exports the + credentials of the selected issuer schemas. +- **Attachments.** Issuer-specific data that belongs to a transferred credential, + such as a Personal Custody Package. The code of the credential's issuer produces + and consumes an attachment. WalletKit carries its `format` and `data` as opaque + bytes and never interprets them. + +The requesting device declares the issuer schemas it supports in +`RegistrationRequester::start` (`supported_issuer_schema_ids`). The declaration is +self-reported and optional. + +On the approving device: + +1. Read `supported_issuer_schema_ids` from `IncomingRegistration` or + `CheckedRegistration`. If the list is present, offer the user only credentials + of those issuer schemas. +1. After the user selects and consents, build a `CredentialTransfer` from the + `export_vault_for_issuer_schemas` output for the selected issuer schemas and + the attachments of those credentials, and pass it to + `CheckedRegistration::approve`. Pass `None` if the user selected no + credentials; then neither a vault nor attachments are sent. + +WalletKit doesn't parse the vault. The app is responsible for exporting only +supported issuer schemas, and for attaching only data that belongs to a +credential in the vault. + +`approve` checks the transfer before it submits `InsertAuthenticator`: + +- `ApproverError::TransferTooLarge`: the vault and all attachment data together + exceed `registration::MAX_TRANSFER_SIZE` (15 MiB). +- `ApproverError::UnsupportedAttachment`: an attachment belongs to an issuer + schema that the request doesn't list as supported. + +After either error, nothing was submitted or sent, and the checked session stays +open. The app can call `approve` again with another selection, or call `abort` to +notify the requesting device. Nothing is ever silently omitted from a transfer. + +On the requesting device, `RegistrationRequester::verify` returns the transfer +only after it confirmed the registration on-chain: + +1. Import `Registered::vault_backup` with + `CredentialStore::merge_vault_from_backup` once storage is initialized. +1. Hand each of `Registered::attachments` to the code of the issuer of its + `issuer_schema_id`, which must treat it as untrusted input. If the app doesn't + recognize an attachment's issuer schema or format, warn the user that this + data wasn't transferred, and discard it. + +A full transfer takes several minutes on a slow connection: the bridge client +allows up to five minutes for sending or receiving a response. + ## From registration to stored credential The following diagram shows the calls between the app, WalletKit, and the World ID