Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update vault sync with signed key checks (#2536)
Leendert de Borst630e1481939a
diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rsindex 2a47b7fa4..19e4f034d 100644--- a/core/rust/src/bindings/uniffi_api.rs+++ b/core/rust/src/bindings/uniffi_api.rs@@ -205,6 +205,13 @@ pub fn symmetric_encrypt_bytes(plaintext: Vec<u8>, key_base64: String) -> Resultcrate::crypto::symmetric_encrypt_raw_with_aad(&plaintext, &key_base64, &[])}+/// The fingerprint of the account's own signing key, derived from its private key encrypted with the Account Key.+#[uniffi::export]+pub fn account_signing_key_fingerprint(encrypted_signing_private_key: String, account_key: Vec<u8>) -> Result<String, VaultError> {+ let account_key = zeroize::Zeroizing::new(crate::common::encoding::base64_encode(&account_key));+ crate::crypto::account_signing_key_fingerprint(&encrypted_signing_private_key, &account_key)+}+/// A fresh random salt for a new PIN wrap.#[uniffi::export]pub fn pin_generate_salt() -> Vec<u8> {diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rsindex 286f3200c..ee398a627 100644--- a/core/rust/src/bindings/wasm.rs+++ b/core/rust/src/bindings/wasm.rs@@ -216,6 +216,12 @@ pub fn symmetric_encrypt_bytes_js(plaintext: &[u8], key_base64: &str) -> Result<crate::crypto::symmetric_encrypt_raw_with_aad(plaintext, key_base64, &[]).map_err(js_err)}+/// The fingerprint of the account's own signing key, derived from its private key encrypted with the Account Key.+#[wasm_bindgen(js_name = accountSigningKeyFingerprint)]+pub fn account_signing_key_fingerprint_js(encrypted_signing_private_key: &str, account_key_base64: &str) -> Result<String, JsValue> {+ crate::crypto::account_signing_key_fingerprint(encrypted_signing_private_key, account_key_base64).map_err(js_err)+}+/// RSA-OAEP-256 decrypt base64 ciphertext with a JWK private key.#[wasm_bindgen(js_name = rsaDecrypt)]pub fn rsa_decrypt_js(base64_ciphertext: &str, private_key_jwk: &str) -> Result<Vec<u8>, JsValue> {diff --git a/core/rust/src/vault_sync/engine.rs b/core/rust/src/vault_sync/engine.rsindex a063396fd..ace60da29 100644--- a/core/rust/src/vault_sync/engine.rs+++ b/core/rust/src/vault_sync/engine.rs@@ -35,6 +35,10 @@ pub(crate) async fn run(host: Host, request: SyncRequest) -> Value {SyncOperation::CreateSharedManifest => serde_json::to_value(sharing::create_shared_manifest_operation(&mut ctx).await),SyncOperation::InviteToSharedManifest => serde_json::to_value(sharing::invite_to_shared_manifest_operation(&mut ctx).await),SyncOperation::UpdateSharedManifest => serde_json::to_value(sharing::update_shared_manifest_operation(&mut ctx).await),+ SyncOperation::LookupIdentityCode => serde_json::to_value(sharing::lookup_identity_code_operation(&mut ctx).await),+ SyncOperation::InviteToGroup => serde_json::to_value(sharing::invite_to_group_operation(&mut ctx).await),+ SyncOperation::AcceptGroupInvitation => serde_json::to_value(sharing::accept_group_invitation_operation(&mut ctx).await),+ SyncOperation::AcceptSharedManifestInvitation => serde_json::to_value(sharing::accept_shared_manifest_invitation_operation(&mut ctx).await),SyncOperation::RotateAccountKeys => serde_json::to_value(rotation::rotate_account_keys_operation(&mut ctx).await),};finish(&ctx, result.unwrap_or(Value::Null))diff --git a/core/rust/src/vault_sync/errors.rs b/core/rust/src/vault_sync/errors.rsindex a7062175d..d1f0d638f 100644--- a/core/rust/src/vault_sync/errors.rs+++ b/core/rust/src/vault_sync/errors.rs@@ -24,6 +24,9 @@ pub enum ErrorCode {/// The session key does not open the key chain the server holds; only a re-login recovers.#[serde(rename = "E-208")]KeyOutOfSync,+ /// The account public key the server serves does not belong to the account private key this session holds.+ #[serde(rename = "E-217")]+ AccountKeyMismatch,/// The server's snapshot cannot be assembled into a vault.#[serde(rename = "E-502")]SyncVaultFetchFailed,@@ -135,6 +138,9 @@ pub enum SyncError {/// The session key opens neither the server's chain nor its VEK; only a re-login recovers.#[error("Vault encryption key out of sync with the server; log in again")]KeyOutOfSync,+ /// The account public key the server serves is not the public half of the account private key this session holds.+ #[error("The account public key the server serves does not belong to this account's private key")]+ AccountKeyMismatch,/// A server manifest or bucket failed its hash check or did not decrypt.#[error("Server vault could not be opened: {0}")]ServerVaultUnreadable(String),@@ -209,6 +215,7 @@ impl SyncError {SyncError::UnlockKeyRejected => Failure::Coded(ErrorCode::UnlockKeyRejected),SyncError::KeyChainUnreadable(_) => Failure::Coded(ErrorCode::KeyChainUnreadable),SyncError::KeyOutOfSync => Failure::Logout(LogoutReason::PasswordChanged),+ SyncError::AccountKeyMismatch => Failure::Coded(ErrorCode::AccountKeyMismatch),SyncError::ServerVaultUnreadable(_) => Failure::Coded(ErrorCode::SyncVaultDecryptFailed),SyncError::Snapshot(_) => Failure::Coded(ErrorCode::SyncVaultFetchFailed),SyncError::VaultDataRejected(_) => Failure::Coded(ErrorCode::SyncCodecFailed),diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rsindex df5a058f5..ef257c778 100644--- a/core/rust/src/vault_sync/keys.rs+++ b/core/rust/src/vault_sync/keys.rs@@ -73,10 +73,36 @@ async fn open_chain(ctx: &mut Ctx, encrypted_account_key: &str, encrypted_vek: &Ok(from_zeroizing(std::mem::take(&mut opened.vault_encryption_key)))}-/// Open the chain of a server vault-key response with `unlock_key`, refusing an unknown unlock algorithm first.+/// Open the chain of a server vault-key response with `unlock_key`, refusing an unknown unlock algorithm first and a+/// served account public key that is not the public half of the private key.async fn open_server_chain(ctx: &mut Ctx, vault_key: &VaultKeyResponse, unlock_key: &str) -> SyncResult<SecretString> {ensure_known_unlock_algorithm(vault_key)?;- open_chain(ctx, &vault_key.encrypted_account_key, vault_key.encrypted_vek.as_deref().unwrap_or_default(), vault_key.encrypted_account_private_key.as_deref(), unlock_key).await+ let vek = open_chain(ctx, &vault_key.encrypted_account_key, vault_key.encrypted_vek.as_deref().unwrap_or_default(), vault_key.encrypted_account_private_key.as_deref(), unlock_key).await?;+ if let (Some(public_key), Some(private_key)) = (&vault_key.account_public_key, &ctx.account_private_key) {+ ensure_own_key_pair(public_key, private_key.expose_secret())?;+ ctx.account_public_key = Some(public_key.clone());+ }+ Ok(vek)+}++/// Refuse an account public key the server serves as this account's unless it is the public half of the held private key.+fn ensure_own_key_pair(public_key: &str, private_key: &str) -> SyncResult<()> {+ let pair = crypto::RsaKeyPair { public_key: public_key.to_string(), private_key: private_key.to_string() };+ crypto::rsa_oaep::validate_rsa_key_pair(&pair).map_err(|_| SyncError::AccountKeyMismatch)+}++/// This account's public key, checked against the private key this session holds; `None` when either is missing.+pub(crate) async fn own_account_public_key(ctx: &Ctx) -> SyncResult<Option<String>> {+ let public_key = match &ctx.account_public_key {+ Some(key) => key.clone(),+ None => match state::get::<String>(&ctx.host, state::ACCOUNT_PUBLIC_KEY).await? {+ Some(key) => key,+ None => return Ok(None),+ },+ };+ let Some(private_key) = &ctx.account_private_key else { return Ok(None) };+ ensure_own_key_pair(&public_key, private_key.expose_secret())?;+ Ok(Some(public_key))}/// The login-time key resolution (the `resolveVaultKey` operation): open the server's chain with the session key,@@ -155,6 +181,14 @@ pub(crate) async fn ensure_key_chain_accepted(ctx: &mut Ctx) -> SyncResult<bool>has_cached_key_chain(&ctx.host).await}+/// This account's signing public key, derived from the private key so that it never depends on what the server serves.+pub(crate) async fn own_signing_public_key(ctx: &mut Ctx) -> SyncResult<Option<String>> {+ match signing_private_key(ctx).await? {+ Some(private_key) => Ok(Some(crypto::signing::signing_public_key_of(private_key.expose_secret())?)),+ None => Ok(None),+ }+}+/// The account signing private key, opened on first use from the cached encrypted copy with the session's Account Key./// None when that key or the cached copy is missing or does not open it.pub(crate) async fn signing_private_key(ctx: &mut Ctx) -> SyncResult<Option<SecretString>> {@@ -204,11 +238,11 @@ pub(crate) async fn re_encrypt_shared_manifest_records(ctx: &Ctx, new_key: &str)}/// The private key that opens a grant made out to `public_key`.-pub(crate) fn resolve_grant_private_key(ctx: &Ctx, public_key: &str) -> Option<SecretString> {- if ctx.account_public_key.as_deref() != Some(public_key) {- return None;+pub(crate) async fn resolve_grant_private_key(ctx: &Ctx, public_key: &str) -> SyncResult<Option<SecretString>> {+ if own_account_public_key(ctx).await?.as_deref() != Some(public_key) {+ return Ok(None);}- ctx.account_private_key.clone()+ Ok(ctx.account_private_key.clone())}/// Encrypt a manifest's VEK for one recipient key, bound to the manifest (see [`crypto::aad::grant`]).@@ -228,7 +262,7 @@ pub(crate) async fn open_shared_manifest_vek(ctx: &Ctx, record: &SharedManifestDctx.warn(format!("[Sharing] Manifest {} grants its key under an unsupported algorithm \"{}\" (newer server?); leaving it closed.", record.manifest_id, record.algorithm)).await;return Ok(None);}- let Some(private_key) = resolve_grant_private_key(ctx, &record.account_public_key) else {+ let Some(private_key) = resolve_grant_private_key(ctx, &record.account_public_key).await? else {ctx.warn(format!("[Sharing] This session holds no account private key that opens the grant on manifest {}; leaving it closed.", record.manifest_id)).await;return Ok(None);};@@ -256,9 +290,9 @@ pub(crate) async fn open_shared_manifest_veks(ctx: &Ctx) -> SyncResult<HashMap<SOk(veks)}-/// Whether the grant a manifest was served with carries a valid signature by its signer.-pub(crate) fn grant_signature_verifies(dto: &ManifestDto, recipient_public_key: &str, algorithm: &str, encrypted_vek: &str) -> bool {- let (Some(signer_user_id), Some(signer_public_key), Some(signature)) = (dto.grant_signer_user_id.as_deref(), dto.grant_signer_public_key.as_deref(), dto.grant_signature.as_deref()) else { return false };+/// Whether the grant a manifest was served with is signed by this account itself; a grant signed by anyone else does not open.+pub(crate) fn grant_signed_by_self(dto: &ManifestDto, own_signing_public_key: &str, recipient_public_key: &str, algorithm: &str, encrypted_vek: &str) -> bool {+ let (Some(signer_user_id), Some(signature)) = (dto.grant_signer_user_id.as_deref(), dto.grant_signature.as_deref()) else { return false };let message = crypto::signing::grant_message(&dto.manifest_id, dto.key_version, signer_user_id, recipient_public_key, algorithm, encrypted_vek);- crypto::signing::verify(signer_public_key, &message, signature)+ crypto::signing::verify(own_signing_public_key, &message, signature)}diff --git a/core/rust/src/vault_sync/pull.rs b/core/rust/src/vault_sync/pull.rsindex b84eed807..714c9bd3c 100644--- a/core/rust/src/vault_sync/pull.rs+++ b/core/rust/src/vault_sync/pull.rs@@ -154,11 +154,12 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshotlet mut contentless_revisions: HashMap<String, i64> = HashMap::new();let mut manifest_names: HashMap<String, String> = HashMap::new();let previous_records = keys::shared_manifest_records(ctx).await?;+ let own_signing_public_key = keys::own_signing_public_key(ctx).await?;let ordered: Vec<&ManifestDto> = std::iter::once(personal_dto).chain(snapshot.manifests.iter().filter(|m| m.manifest_id != personal_dto.manifest_id)).collect();for dto in ordered {let is_personal = dto.manifest_id == personal_dto.manifest_id;- let manifest_key = resolve_manifest_vek(ctx, dto, &personal_dto.manifest_id, vek, is_personal).await?;+ let manifest_key = resolve_manifest_vek(ctx, dto, &personal_dto.manifest_id, vek, is_personal, own_signing_public_key.as_deref()).await?;if is_personal {let entry = if personal_needs_first_write {ctx.log("[Pull] Personal manifest has no content yet (new account); starting from an empty vault.").await;@@ -173,6 +174,9 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshot}if !dto.has_content() {// A shared manifest served without content yet (created but never written); its grant and revision are still tracked.+ if dto.revision != 0 {+ return Err(SyncError::Snapshot(format!("shared manifest {} was served without content at revision {}, nothing to assemble", dto.manifest_id, dto.revision)));+ }let (encrypted_vek, account_public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} was served without content and without a grant, refusing to assemble", dto.manifest_id)))?;let encrypted_name = served_encrypted_name(ctx, &previous_records, &dto.manifest_id);shared_records.insert(dto.manifest_id.clone(), SharedManifestDto { manifest_id: dto.manifest_id.clone(), encrypted_vek, account_public_key, algorithm, salt: vault_codec::generate_manifest_salt(), encrypted_name, can_administer: dto.can_administer, key_version: dto.key_version });@@ -399,7 +403,7 @@ async fn empty_personal_manifest(ctx: &Ctx, dto: &ManifestDto, vek: &str) -> Syn}/// The key that opens one snapshot manifest.-async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_id: &str, personal_vek: &str, is_personal: bool) -> SyncResult<SecretString> {+async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_id: &str, personal_vek: &str, is_personal: bool, own_signing_public_key: Option<&str>) -> SyncResult<SecretString> {// Only a personal manifest that predates the account key hierarchy has no key type; a shared one always states it.let key_type = match dto.key_type.clone() {Some(key_type) => key_type,@@ -415,19 +419,20 @@ async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_idif key_type != types::KEY_TYPE_GRANT_KEY {return Err(SyncError::VaultVersionIncompatible(format!("manifest {} states an unknown key type \"{}\"; update the app", dto.manifest_id, key_type)));}- resolve_granted_vek(ctx, dto).await+ resolve_granted_vek(ctx, dto, own_signing_public_key).await}-async fn resolve_granted_vek(ctx: &Ctx, dto: &ManifestDto) -> SyncResult<SecretString> {+/// The VEK of a shared manifest from the grant it was served with, which has to be signed by this account itself.+async fn resolve_granted_vek(ctx: &Ctx, dto: &ManifestDto, own_signing_public_key: Option<&str>) -> SyncResult<SecretString> {let (encrypted_vek, public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} carries no grant to open it with, refusing to assemble", dto.manifest_id)))?;if algorithm != types::ALGORITHM_RSA_OAEP_SHA256 {return Err(SyncError::VaultVersionIncompatible(format!("shared manifest {} grants its VEK under an unsupported algorithm \"{}\"; update the app", dto.manifest_id, algorithm)));}- // Require the grant to be signed by the account's private key.- if !keys::grant_signature_verifies(dto, &public_key, &algorithm, &encrypted_vek) {- return Err(SyncError::ServerVaultUnreadable(format!("the grant on shared manifest {} carries no valid signature, refusing to assemble", dto.manifest_id)));+ let signing_public_key = own_signing_public_key.ok_or_else(|| SyncError::ServerVaultUnreadable(format!("this session holds no signing key to check the grant on shared manifest {} with, refusing to assemble", dto.manifest_id)))?;+ if !keys::grant_signed_by_self(dto, signing_public_key, &public_key, &algorithm, &encrypted_vek) {+ return Err(SyncError::ServerVaultUnreadable(format!("the grant on shared manifest {} is not signed by this account, refusing to assemble", dto.manifest_id)));}// Sanity check: no key this session holds opens the grant, so the session is behind the server.- let private_key = keys::resolve_grant_private_key(ctx, &public_key).ok_or(SyncError::KeyOutOfSync)?;+ let private_key = keys::resolve_grant_private_key(ctx, &public_key).await?.ok_or(SyncError::KeyOutOfSync)?;keys::decrypt_manifest_vek(&encrypted_vek, &dto.manifest_id, private_key.expose_secret()).map_err(|e| SyncError::ServerVaultUnreadable(format!("failed to decrypt the VEK of shared manifest {}, refusing to assemble: {}", dto.manifest_id, e)))}diff --git a/core/rust/src/vault_sync/rotation.rs b/core/rust/src/vault_sync/rotation.rsindex dc43d95a7..e5780e60b 100644--- a/core/rust/src/vault_sync/rotation.rs+++ b/core/rust/src/vault_sync/rotation.rs@@ -34,6 +34,16 @@ struct BlobKeyEntry {encrypted_blob_key: String,}+/// `GET v2/Groups/certifications`: one key certification this account made, with its signature by the current signing key.+#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+struct CertificationEntry {+ subject_user_id: String,+ subject_signing_public_key: String,+ #[serde(default)]+ signature: String,+}+/// `POST v2/KeyRotation`.#[derive(Serialize)]#[serde(rename_all = "camelCase")]@@ -47,6 +57,7 @@ struct KeyRotationRequest {buckets: Vec<BucketWrite>,blob_keys: Vec<BlobKeyWrite>,grants: Vec<GrantWrite>,+ certifications: Vec<CertificationWrite>,}impl FrameBody for KeyRotationRequest {@@ -105,6 +116,15 @@ struct GrantWrite {signature: String,}+/// A key certification this account made, signed again with the new signing key.+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct CertificationWrite {+ subject_user_id: String,+ subject_signing_public_key: String,+ signature: String,+}+#[derive(Debug, Default, Deserialize)]#[serde(rename_all = "camelCase")]struct KeyRotationResponse {@@ -176,6 +196,7 @@ async fn rotate(ctx: &mut Ctx) -> Outcome {}let blob_keys: BlobKeysResponse = http::with_outdated_server_guard(http::get(&ctx.host, &format!("Vault/blob-keys/{}", personal_manifest_id), false).await)?;+ let certifications: Vec<CertificationEntry> = http::with_outdated_server_guard(http::get(&ctx.host, "Groups/certifications", false).await)?;let key_pair = crypto::RsaKeyPair { public_key: params.new_account_public_key.clone(), private_key: params.new_account_private_key.expose_secret().to_string() };let rotated = crypto::rotate_account_keys(signing_key.expose_secret(), ¶ms.user_id, params.new_unlock_key.expose_secret(), &key_pair)?;@@ -186,7 +207,7 @@ async fn rotate(ctx: &mut Ctx) -> Outcome {let delivery_pair = crypto::generate_rsa_key_pair()?;let delivery_change = db::rotate_active_key_for_manifest(&ctx.host, &personal_manifest_id, &delivery_pair.public_key, &delivery_pair.private_key).await?;- let posted = build_and_post(ctx, ¶ms, &personal_manifest_id, &rotated, &new_vek, &vek, &shared_records, &shared_veks, &blob_keys.blob_keys, &delivery_pair.public_key).await;+ let posted = build_and_post(ctx, ¶ms, &personal_manifest_id, &rotated, signing_key.expose_secret(), &new_vek, &vek, &shared_records, &shared_veks, &blob_keys.blob_keys, &certifications, &delivery_pair.public_key).await;match posted {Ok(Ok((applied, rewrapped_blob_keys, rewrapped_grants, fingerprints))) => {adopt(ctx, ¶ms, &personal_manifest_id, &rotated, &new_vek, &applied, &rewrapped_blob_keys, &rewrapped_grants, &fingerprints).await?;@@ -211,7 +232,7 @@ type Built = (Applied, HashMap<String, String>, HashMap<String, SharedManifestDt/// Encrypt everything under the new keys, send it, and read the server's answer.#[allow(clippy::too_many_arguments)]-async fn build_and_post(ctx: &mut Ctx, params: &KeyRotationParams, personal_manifest_id: &str, rotated: &crypto::RotatedAccountKeys, new_vek: &SecretString, old_vek: &SecretString, shared_records: &HashMap<String, SharedManifestDto>, shared_veks: &HashMap<String, SecretString>, server_blob_keys: &[BlobKeyEntry], delivery_public_key: &str) -> SyncResult<Result<Built, KeyRotationRefusal>> {+async fn build_and_post(ctx: &mut Ctx, params: &KeyRotationParams, personal_manifest_id: &str, rotated: &crypto::RotatedAccountKeys, current_signing_key: &str, new_vek: &SecretString, old_vek: &SecretString, shared_records: &HashMap<String, SharedManifestDto>, shared_veks: &HashMap<String, SecretString>, server_blob_keys: &[BlobKeyEntry], server_certifications: &[CertificationEntry], delivery_public_key: &str) -> SyncResult<Result<Built, KeyRotationRefusal>> {let manifest_revisions: HashMap<String, i64> = state::get(&ctx.host, state::SERVER_MANIFEST_REVISIONS).await?.unwrap_or_default();let bucket_revisions: HashMap<String, i64> = state::get(&ctx.host, state::VAULT_BUCKET_REVISIONS).await?.unwrap_or_default();let current_revision = manifest_revisions.get(personal_manifest_id).copied().unwrap_or(0);@@ -279,6 +300,21 @@ async fn build_and_post(ctx: &mut Ctx, params: &KeyRotationParams, personal_manirecord.algorithm = ALGORITHM_RSA_OAEP_SHA256.to_string();}+ // Every key certification this account made, signed again with the new signing key, so the people it vouched for stay+ // verified. An entry is signed again only when the current key signed it.+ let current_signing_public_key = crypto::signing::signing_public_key_of(current_signing_key)?;+ let certifications = server_certifications+ .iter()+ .map(|entry| {+ let message = crypto::signing::key_certification_message(¶ms.user_id, &entry.subject_user_id, &entry.subject_signing_public_key);+ if !crypto::signing::verify(¤t_signing_public_key, &message, &entry.signature) {+ return Err(SyncError::Other(format!("The rotation was not sent: the server lists a certification of {} this account did not sign.", entry.subject_user_id)));+ }+ let signature = crypto::signing::sign(&rotated.signing_private_key, &message)?;+ Ok(CertificationWrite { subject_user_id: entry.subject_user_id.clone(), subject_signing_public_key: entry.subject_signing_public_key.clone(), signature })+ })+ .collect::<SyncResult<Vec<_>>>()?;+ensure_key_chain_opens(params, rotated, new_vek)?;let delivery_key_signature = crypto::signing::sign(&rotated.signing_private_key, &crypto::signing::delivery_key_message(personal_manifest_id, delivery_public_key, current_revision))?;@@ -317,8 +353,9 @@ async fn build_and_post(ctx: &mut Ctx, params: &KeyRotationParams, personal_manibuckets,blob_keys,grants,+ certifications,};- ctx.log(format!("[KeyRotation] Sending the rotation: {} bucket(s), {} blob key(s), {} grant(s).", request.buckets.len(), request.blob_keys.len(), request.grants.len())).await;+ ctx.log(format!("[KeyRotation] Sending the rotation: {} bucket(s), {} blob key(s), {} grant(s), {} certification(s).", request.buckets.len(), request.blob_keys.len(), request.grants.len(), request.certifications.len())).await;let response: KeyRotationResponse = match http::with_outdated_server_guard(http::post_frame(&ctx.host, KEY_ROTATION_ENDPOINT, &mut request).await) {Ok(response) => response,diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rsindex 7ce5dadf7..5c06d19bb 100644--- a/core/rust/src/vault_sync/sharing.rs+++ b/core/rust/src/vault_sync/sharing.rs@@ -1,4 +1,11 @@-//! The sharing operations that take vault keys: creating a group's shared manifest, updating one and inviting a member to one.+//! The sharing operations that take vault keys or sign something: creating a group's shared manifest, updating one,+//! inviting to a group or a shared manifest, and accepting those invitations.+//!+//! Trust between two accounts rests on key certifications: once a user has checked another account's signing key (outside+//! AliasVault) against that account's identity code (the key's fingerprint, the family code in the apps), a client signs a+//! statement that the served key belongs to that account. A certification is only ever checked under the certifier's own signing key,+//! derived from their private key, so the server can hide one but not forge one. An admin certifies a member before inviting them anywhere;+//! a member certifies the admin before accepting anything from them. A grant opens only once signed by its holder.use std::collections::HashMap;use secrecy::ExposeSecret;@@ -19,14 +26,105 @@ const ROLE_MEMBER: &str = "member";/// The API error code for a recipient whose account has no keypair yet (legacy non-migrated user account).const INVITE_RECIPIENT_NOT_READY: &str = "INVITE_RECIPIENT_NOT_READY";+/// The API error code for a member whose signing key this account has not certified with their identity code.+const MEMBER_NOT_VERIFIED: &str = "MEMBER_NOT_VERIFIED";++/// The API error code for an inviter whose signing key this account has not certified with their identity code.+const INVITER_NOT_VERIFIED: &str = "INVITER_NOT_VERIFIED";++/// The refusal code for an identity code that is not the fingerprint of the key the server served.+const IDENTITY_CODE_MISMATCH: &str = "IDENTITY_CODE_MISMATCH";+/// The longest name an invitation can carry: RSA-2048 OAEP-SHA256 fits 190 bytes. The UI caps names well below this.const MAX_SHARED_MANIFEST_NAME_BYTES: usize = 190;#[derive(Debug, Clone, Default, Deserialize)]#[serde(rename_all = "camelCase")]struct GroupOverview {+ /// The caller's own user id, which the certifications and grants it signs name.+ #[serde(default)]+ user_id: String,#[serde(default)]groups: Vec<GroupInfo>,+ #[serde(default)]+ received_invitations: Vec<ReceivedManifestInvitation>,+ #[serde(default)]+ received_group_invitations: Vec<ReceivedGroupInvitation>,+}++#[derive(Debug, Clone, Default, Deserialize)]+#[serde(rename_all = "camelCase")]+struct ReceivedManifestInvitation {+ id: String,+ manifest_id: String,+ inviter_user_id: String,+ #[serde(default)]+ key_version: i64,+ #[serde(default)]+ encrypted_vek: Option<String>,+ #[serde(default)]+ encrypted_name: Option<String>,+ #[serde(default)]+ encrypted_name_signature: Option<String>,+ #[serde(default)]+ grant_signature: Option<String>,+ /// The inviter's signing key as the server serves it; trusted only through `inviter_certification`.+ #[serde(default)]+ signer_public_key: Option<String>,+ #[serde(default)]+ recipient_account_public_key: Option<String>,+ #[serde(default)]+ algorithm: String,+ /// This account's certification of `signer_public_key`, when it certified the inviter before.+ #[serde(default)]+ inviter_certification: Option<String>,+}++#[derive(Debug, Clone, Default, Deserialize)]+#[serde(rename_all = "camelCase")]+struct ReceivedGroupInvitation {+ id: String,+ inviter_user_id: String,+ #[serde(default)]+ inviter_signing_public_key: Option<String>,+ #[serde(default)]+ inviter_certification: Option<String>,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+struct IdentityCodeLookupRequest<'a> {+ code: &'a str,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+struct IdentityCodeLookupResponse {+ user_id: String,+ #[serde(default)]+ username: String,+ signing_public_key: String,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+struct CertifyKeyRequest<'a> {+ subject_user_id: &'a str,+ subject_signing_public_key: &'a str,+ signature: &'a str,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+struct InviteToGroupRequest<'a> {+ user_id: &'a str,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+struct AcceptInvitationRequest<'a> {+ #[serde(skip_serializing_if = "Option::is_none")]+ grant_signature: Option<&'a str>,}#[derive(Debug, Clone, Default, Deserialize)]@@ -53,8 +151,6 @@ struct GroupManifestInfo {struct GroupMemberInfo {user_id: String,#[serde(default)]- username: String,- #[serde(default)]account_public_key_id: Option<String>,#[serde(default)]account_public_key: Option<String>,@@ -62,6 +158,9 @@ struct GroupMemberInfo {account_public_key_signature: Option<String>,#[serde(default)]signing_public_key: Option<String>,+ /// This account's certification of `signing_public_key`, made when it checked the member's identity code.+ #[serde(default)]+ key_certification: Option<String>,}#[derive(Debug, Serialize)]@@ -116,8 +215,22 @@ enum Refusal {VaultUpgradeRequired,}+/// What a successful sharing operation reports.+#[derive(Default)]+struct Done {+ manifest_id: Option<String>,+ username: Option<String>,+ already_member: bool,+}++impl Done {+ fn manifest(manifest_id: String) -> Self {+ Done { manifest_id: Some(manifest_id), ..Default::default() }+ }+}+/// What a sharing operation came to before its result is built.-type Outcome = SyncResult<Result<String, Refusal>>;+type Outcome = SyncResult<Result<Done, Refusal>>;/// Create a group's shared manifest.pub(crate) async fn create_shared_manifest_operation(ctx: &mut Ctx) -> SharingOperationResult {@@ -137,10 +250,34 @@ pub(crate) async fn update_shared_manifest_operation(ctx: &mut Ctx) -> SharingOpfinish(ctx, "update shared manifest", outcome).await}+/// Find the account behind an identity code, before inviting it.+pub(crate) async fn lookup_identity_code_operation(ctx: &mut Ctx) -> SharingOperationResult {+ let outcome = lookup_identity_code(ctx).await;+ finish(ctx, "look up identity code", outcome).await+}++/// Invite an account to a group by its identity code.+pub(crate) async fn invite_to_group_operation(ctx: &mut Ctx) -> SharingOperationResult {+ let outcome = invite_to_group(ctx).await;+ finish(ctx, "invite to group", outcome).await+}++/// Accept an invitation to join a group.+pub(crate) async fn accept_group_invitation_operation(ctx: &mut Ctx) -> SharingOperationResult {+ let outcome = accept_group_invitation(ctx).await;+ finish(ctx, "accept group invitation", outcome).await+}++/// Accept an invitation to a shared manifest.+pub(crate) async fn accept_shared_manifest_invitation_operation(ctx: &mut Ctx) -> SharingOperationResult {+ let outcome = accept_shared_manifest_invitation(ctx).await;+ finish(ctx, "accept shared manifest invitation", outcome).await+}+/// Turn an operation's outcome into the result the host acts on.async fn finish(ctx: &Ctx, what: &str, outcome: Outcome) -> SharingOperationResult {match outcome {- Ok(Ok(manifest_id)) => SharingOperationResult { success: true, manifest_id: Some(manifest_id), ..Default::default() },+ Ok(Ok(done)) => SharingOperationResult { success: true, manifest_id: done.manifest_id, username: done.username, already_member: done.already_member, ..Default::default() },Ok(Err(Refusal::Api(code))) => refused(code),Ok(Err(Refusal::VaultUpgradeRequired)) => SharingOperationResult { vault_upgrade_required: true, ..Default::default() },Err(error) => {@@ -163,22 +300,36 @@ fn params(ctx: &Ctx) -> SyncResult<SharingParams> {ctx.request.sharing.clone().ok_or_else(|| SyncError::Other("The sharing operation carries no target".to_string()))}-/// The group with the given id, when this account administers it.-async fn administered_group(ctx: &Ctx, group_id: &str) -> SyncResult<GroupInfo> {+/// The group a sharing operation names.+fn group_id(target: &SharingParams) -> SyncResult<String> {+ target.group_id.clone().ok_or_else(|| SyncError::Other("The sharing operation names no group".to_string()))+}++/// The invitation a sharing operation names.+fn invitation_id(target: &SharingParams) -> SyncResult<String> {+ target.invitation_id.clone().ok_or_else(|| SyncError::Other("The sharing operation names no invitation".to_string()))+}++/// `GET Groups`: the caller's groups and open invitations, with the caller's own user id.+async fn fetch_overview(ctx: &Ctx) -> SyncResult<GroupOverview> {let overview: GroupOverview = http::get(&ctx.host, "Groups", false).await?;+ if overview.user_id.is_empty() {+ return Err(SyncError::Other("The server did not name this account's user id".to_string()));+ }+ Ok(overview)+}++/// The group with the given id, when this account administers it.+fn administered_group(overview: &GroupOverview, group_id: &str) -> SyncResult<GroupInfo> {overview.groups- .into_iter()+ .iter().find(|group| ids_equal(&group.group_id, group_id)).filter(|group| group.role != ROLE_MEMBER)+ .cloned().ok_or_else(|| SyncError::Other(format!("Group {} is not one this account administers", group_id)))}-/// This account's user id in a group, which the grants it signs name.-fn own_user_id(ctx: &Ctx, group: &GroupInfo) -> SyncResult<String> {- group.members.iter().find(|member| member.username.eq_ignore_ascii_case(&ctx.request.username)).map(|member| member.user_id.clone()).ok_or_else(|| SyncError::Other("This account is not a member of the group".to_string()))-}-/// Refuse a name too long for an invitation to carry.fn check_name_length(name: &str) -> SyncResult<()> {if name.len() > MAX_SHARED_MANIFEST_NAME_BYTES {@@ -187,11 +338,51 @@ fn check_name_length(name: &str) -> SyncResult<()> {Ok(())}-/// This account's public key, which a new shared manifest's key is encrypted for.-async fn own_public_key(ctx: &Ctx) -> SyncResult<Option<String>> {- match &ctx.account_public_key {- Some(key) => Ok(Some(key.clone())),- None => state::get::<String>(&ctx.host, state::ACCOUNT_PUBLIC_KEY).await,+/// This account as a signer: its user id, which everything it signs names, and its signing keys (public key derived from the private one).+struct OwnIdentity {+ user_id: String,+ signing_key: secrecy::SecretString,+ signing_public_key: String,+}++impl OwnIdentity {+ /// `None` until the account's key hierarchy has reached this device.+ async fn open(ctx: &mut Ctx, overview: &GroupOverview) -> SyncResult<Option<Self>> {+ let Some(signing_key) = keys::signing_private_key(ctx).await? else { return Ok(None) };+ let signing_public_key = crypto::signing::signing_public_key_of(signing_key.expose_secret())?;+ Ok(Some(OwnIdentity { user_id: overview.user_id.clone(), signing_key, signing_public_key }))+ }++ fn sign(&self, message: &[u8]) -> SyncResult<String> {+ Ok(crypto::signing::sign(self.signing_key.expose_secret(), message)?)+ }++ /// Whether `certification` is this account's own signed statement that `subject_key` belongs to `subject_user_id`.+ fn certified(&self, subject_user_id: &str, subject_key: &str, certification: Option<&str>) -> bool {+ certification.is_some_and(|certification| crypto::signing::verify(&self.signing_public_key, &crypto::signing::key_certification_message(&self.user_id, subject_user_id, subject_key), certification))+ }++ /// Make sure this account certified `subject_key` as `subject_user_id`'s: before (`certification`), or now from the+ /// typed `identity_code`. Without either, the refusal says whose code is needed (`not_verified`).+ async fn ensure_certified(&self, ctx: &Ctx, subject_user_id: &str, subject_key: &str, certification: Option<&str>, identity_code: Option<&str>, not_verified: &str) -> SyncResult<Result<(), Refusal>> {+ if self.certified(subject_user_id, subject_key, certification) {+ return Ok(Ok(()));+ }+ match identity_code.map(str::trim).filter(|code| !code.is_empty()) {+ Some(code) => self.certify_with_code(ctx, subject_user_id, subject_key, code).await,+ None => Ok(Err(Refusal::Api(not_verified.to_string()))),+ }+ }++ /// Certify `subject_key` as `subject_user_id`'s after checking it against the identity code the user typed, and store the certification.+ async fn certify_with_code(&self, ctx: &Ctx, subject_user_id: &str, subject_key: &str, code: &str) -> SyncResult<Result<(), Refusal>> {+ if !crypto::signing::fingerprint_matches(subject_key, code) {+ return Ok(Err(Refusal::Api(IDENTITY_CODE_MISMATCH.to_string())));+ }+ let signature = self.sign(&crypto::signing::key_certification_message(&self.user_id, subject_user_id, subject_key))?;+ http::post_no_content(&ctx.host, "Groups/certifications", &CertifyKeyRequest { subject_user_id, subject_signing_public_key: subject_key, signature: &signature }).await?;+ ctx.log(format!("[Sharing] Certified the signing key of {} with their identity code.", subject_user_id)).await;+ Ok(Ok(()))}}@@ -204,11 +395,12 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {let name = target.name.as_deref().map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| SyncError::Other("A shared manifest needs a name".to_string()))?.to_string();check_name_length(&name)?;- let group = administered_group(ctx, &target.group_id).await?;+ let overview = fetch_overview(ctx).await?;+ let group = administered_group(&overview, &group_id(&target)?)?;// The new manifest's VEK is encrypted only for this account's own public key upon creation, other users are invited separately.- let Some(self_public_key) = own_public_key(ctx).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };- let Some(signing_key) = keys::signing_private_key(ctx).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };+ let Some(self_public_key) = keys::own_account_public_key(ctx).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };+ let Some(me) = OwnIdentity::open(ctx, &overview).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };if state::get::<String>(&ctx.host, state::VAULT_PERSONAL_MANIFEST_ID).await?.is_none() {return Ok(Err(Refusal::VaultUpgradeRequired));}@@ -219,7 +411,7 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {let manifest_vek = crypto::generate_key_base64();let requested_id = db::new_id();let self_encrypted_vek = keys::encrypt_manifest_vek(&manifest_vek, &requested_id, &self_public_key)?;- let self_grant_signature = crypto::signing::sign(signing_key.expose_secret(), &crypto::signing::grant_message(&requested_id, NEW_MANIFEST_KEY_VERSION, &own_user_id(ctx, &group)?, &self_public_key, ALGORITHM_RSA_OAEP_SHA256, &self_encrypted_vek))?;+ let self_grant_signature = me.sign(&crypto::signing::grant_message(&requested_id, NEW_MANIFEST_KEY_VERSION, &me.user_id, &self_public_key, ALGORITHM_RSA_OAEP_SHA256, &self_encrypted_vek))?;let encrypted_name = pull::encrypt_manifest_name(&name, &requested_id, &manifest_vek)?;let response: CreateSharedManifestResponse = http::post(&ctx.host,@@ -263,7 +455,7 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {ctx.persist_local_vault(true).await?;ctx.log(format!("[Sharing] Created shared manifest {} for group {}.", manifest_id, group.group_id)).await;- Ok(Ok(manifest_id))+ Ok(Ok(Done::manifest(manifest_id)))}/// The details an update can change (e.g. the name of a shared manifest).@@ -279,7 +471,7 @@ async fn update_shared_manifest(ctx: &mut Ctx) -> Outcome {// The server decides who may change a shared manifest; it only ever sees the name encrypted.let encrypted_name = pull::encrypt_manifest_name(&name, &record.manifest_id, manifest_vek.expose_secret())?;- http::post_no_content(&ctx.host, &format!("Groups/{}/manifests/{}", target.group_id, record.manifest_id), &UpdateSharedManifestRequest { encrypted_name: Some(&encrypted_name) }).await?;+ http::post_no_content(&ctx.host, &format!("Groups/{}/manifests/{}", group_id(&target)?, record.manifest_id), &UpdateSharedManifestRequest { encrypted_name: Some(&encrypted_name) }).await?;let mut records = keys::shared_manifest_records(ctx).await?;if let Some(held) = records.get_mut(&record.manifest_id) {@@ -294,7 +486,7 @@ async fn update_shared_manifest(ctx: &mut Ctx) -> Outcome {}ctx.log(format!("[Sharing] Updated shared manifest {}.", record.manifest_id)).await;- Ok(Ok(record.manifest_id))+ Ok(Ok(Done::manifest(record.manifest_id)))}async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {@@ -303,7 +495,8 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {let manifest_id = target.manifest_id.clone().ok_or_else(|| SyncError::Other("The invitation names no shared manifest".to_string()))?;let user_id = target.user_id.clone().ok_or_else(|| SyncError::Other("The invitation names no recipient".to_string()))?;- let group = administered_group(ctx, &target.group_id).await?;+ let overview = fetch_overview(ctx).await?;+ let group = administered_group(&overview, &group_id(&target)?)?;let manifest = group.manifests.iter().find(|candidate| ids_equal(&candidate.manifest_id, &manifest_id)).ok_or_else(|| SyncError::Other("The shared manifest does not belong to the group".to_string()))?;let member = group.members.iter().find(|candidate| candidate.user_id == user_id).ok_or_else(|| SyncError::Other("The recipient is not a member of the group".to_string()))?;let (Some(recipient_public_key), Some(recipient_public_key_id), Some(signature), Some(signing_public_key)) = (member.account_public_key.clone(), member.account_public_key_id.clone(), member.account_public_key_signature.as_deref(), member.signing_public_key.as_deref()) else {@@ -314,7 +507,12 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {if !crypto::signing::verify(signing_public_key, &crypto::signing::account_public_key_message(&recipient_public_key), signature) {return Err(SyncError::Other(format!("The public key of {} carries no valid signature by their signing key", member.user_id)));}- let Some(signing_key) = keys::signing_private_key(ctx).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };+ let Some(me) = OwnIdentity::open(ctx, &overview).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };++ // The served signing key is trusted only through this account's own certification of it, made with the member's identity code.+ if !me.certified(&member.user_id, signing_public_key, member.key_certification.as_deref()) {+ return Ok(Err(Refusal::Api(MEMBER_NOT_VERIFIED.to_string())));+ }// Find this account's own grant on the manifest.let mut record = held_record(ctx, &manifest.manifest_id).await?;@@ -329,14 +527,13 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {// The name travels encrypted in the invitation, so the recipient sees what they are invited to; one too long to fit is left out.let name = db::manifest_display_names(&ctx.host).await?.get(&id_key(&manifest.manifest_id)).cloned().filter(|name| !name.is_empty() && name.len() <= MAX_SHARED_MANIFEST_NAME_BYTES);- let own_user_id = own_user_id(ctx, &group)?;let encrypted_vek = keys::encrypt_manifest_vek(manifest_vek.expose_secret(), &manifest.manifest_id, &recipient_public_key)?;let encrypted_name = name.map(|name| crypto::encrypt_with_public_key(name.as_bytes(), &recipient_public_key)).transpose()?;let grant = ManifestGrant {recipient_user_id: member.user_id.clone(),recipient_account_public_key_id: recipient_public_key_id,- signature: crypto::signing::sign(signing_key.expose_secret(), &crypto::signing::grant_message(&manifest.manifest_id, manifest.key_version, &own_user_id, &recipient_public_key, ALGORITHM_RSA_OAEP_SHA256, &encrypted_vek))?,- encrypted_name_signature: encrypted_name.as_deref().map(|name| crypto::signing::sign(signing_key.expose_secret(), &crypto::signing::invitation_name_message(&manifest.manifest_id, &own_user_id, &recipient_public_key, name))).transpose()?,+ signature: me.sign(&crypto::signing::grant_message(&manifest.manifest_id, manifest.key_version, &me.user_id, &recipient_public_key, ALGORITHM_RSA_OAEP_SHA256, &encrypted_vek))?,+ encrypted_name_signature: encrypted_name.as_deref().map(|name| me.sign(&crypto::signing::invitation_name_message(&manifest.manifest_id, &me.user_id, &recipient_public_key, name))).transpose()?,encrypted_vek,encrypted_name,};@@ -349,7 +546,115 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {.await?;ctx.log(format!("[Sharing] Invited {} to shared manifest {} with its key encrypted for them.", member.user_id, manifest.manifest_id)).await;- Ok(Ok(manifest.manifest_id.clone()))+ Ok(Ok(Done::manifest(manifest.manifest_id.clone())))+}++/// Look up the account behind an identity code and check the code against the key the server returns, so the admin can+/// confirm who they invite. Nothing is certified or invited; `invite_to_group` looks the code up again.+async fn lookup_identity_code(ctx: &mut Ctx) -> Outcome {+ let target = params(ctx)?;+ let group_id = group_id(&target)?;+ let code = target.identity_code.as_deref().map(str::trim).filter(|code| !code.is_empty()).ok_or_else(|| SyncError::Other("The lookup carries no identity code".to_string()))?;++ let overview = fetch_overview(ctx).await?;+ let group = administered_group(&overview, &group_id)?;+ let account: IdentityCodeLookupResponse = http::post(&ctx.host, &format!("Groups/{}/members/lookup", group.group_id), &IdentityCodeLookupRequest { code }, false).await?;+ if !crypto::signing::fingerprint_matches(&account.signing_public_key, code) {+ return Ok(Err(Refusal::Api(IDENTITY_CODE_MISMATCH.to_string())));+ }++ let already_member = group.members.iter().any(|member| member.user_id == account.user_id);+ Ok(Ok(Done { username: Some(account.username), already_member, ..Default::default() }))+}++/// Invite an account to a group by its identity code: look it up, certify its key with the code, and invite. An account+/// already in the group is only certified.+async fn invite_to_group(ctx: &mut Ctx) -> Outcome {+ ctx.encryption_key()?;+ let target = params(ctx)?;+ let group_id = group_id(&target)?;+ let code = target.identity_code.as_deref().map(str::trim).filter(|code| !code.is_empty()).ok_or_else(|| SyncError::Other("The invitation carries no identity code".to_string()))?;++ let overview = fetch_overview(ctx).await?;+ let group = administered_group(&overview, &group_id)?;+ let Some(me) = OwnIdentity::open(ctx, &overview).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };++ let account: IdentityCodeLookupResponse = http::post(&ctx.host, &format!("Groups/{}/members/lookup", group.group_id), &IdentityCodeLookupRequest { code }, false).await?;+ if let Err(refusal) = me.certify_with_code(ctx, &account.user_id, &account.signing_public_key, code).await? {+ return Ok(Err(refusal));+ }++ let already_member = group.members.iter().any(|member| member.user_id == account.user_id);+ if !already_member {+ http::post_no_content(&ctx.host, &format!("Groups/{}/invitations", group.group_id), &InviteToGroupRequest { user_id: &account.user_id }).await?;+ ctx.log(format!("[Sharing] Invited {} to group {}.", account.user_id, group.group_id)).await;+ }+ Ok(Ok(Done { username: Some(account.username), already_member, ..Default::default() }))+}++/// Accept an invitation to join a group, after certifying the inviter's signing key with their identity code.+async fn accept_group_invitation(ctx: &mut Ctx) -> Outcome {+ ctx.encryption_key()?;+ let target = params(ctx)?;+ let invitation_id = invitation_id(&target)?;++ let overview = fetch_overview(ctx).await?;+ let invitation = overview.received_group_invitations.iter().find(|candidate| ids_equal(&candidate.id, &invitation_id)).ok_or_else(|| SyncError::Other("The group invitation is not open to this account".to_string()))?;+ let Some(inviter_key) = invitation.inviter_signing_public_key.as_deref() else { return Ok(Err(Refusal::Api(INVITER_NOT_VERIFIED.to_string()))) };+ let Some(me) = OwnIdentity::open(ctx, &overview).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };++ if let Err(refusal) = me.ensure_certified(ctx, &invitation.inviter_user_id, inviter_key, invitation.inviter_certification.as_deref(), target.identity_code.as_deref(), INVITER_NOT_VERIFIED).await? {+ return Ok(Err(refusal));+ }++ http::post_no_content(&ctx.host, &format!("Groups/invitations/{}/accept", invitation.id), &AcceptInvitationRequest { grant_signature: None }).await?;+ ctx.log(format!("[Sharing] Joined the group of {} (invitation {}).", invitation.inviter_user_id, invitation.id)).await;+ Ok(Ok(Done::default()))+}++/// Accept an invitation to a shared manifest: check the certified inviter signed it and the key inside opens for this+/// account, then sign the grant as this account's own.+async fn accept_shared_manifest_invitation(ctx: &mut Ctx) -> Outcome {+ ctx.encryption_key()?;+ let target = params(ctx)?;+ let invitation_id = invitation_id(&target)?;++ let overview = fetch_overview(ctx).await?;+ let invitation = overview.received_invitations.iter().find(|candidate| ids_equal(&candidate.id, &invitation_id)).ok_or_else(|| SyncError::Other("The invitation is not open to this account".to_string()))?;+ let (Some(encrypted_vek), Some(recipient_public_key), Some(grant_signature), Some(signer_public_key)) = (invitation.encrypted_vek.as_deref(), invitation.recipient_account_public_key.as_deref(), invitation.grant_signature.as_deref(), invitation.signer_public_key.as_deref()) else {+ return Err(SyncError::Other("The invitation carries no complete grant".to_string()));+ };+ if invitation.algorithm != ALGORITHM_RSA_OAEP_SHA256 {+ return Err(SyncError::VaultVersionIncompatible(format!("the invitation grants its key under an unsupported algorithm \"{}\"; update the app", invitation.algorithm)));+ }+ let Some(me) = OwnIdentity::open(ctx, &overview).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };+ let Some(own_public_key) = keys::own_account_public_key(ctx).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };++ if let Err(refusal) = me.ensure_certified(ctx, &invitation.inviter_user_id, signer_public_key, invitation.inviter_certification.as_deref(), target.identity_code.as_deref(), INVITER_NOT_VERIFIED).await? {+ return Ok(Err(refusal));+ }++ // The offer has to be the certified inviter's own work, made out to this account's key, and the key inside has to open.+ let grant_message = crypto::signing::grant_message(&invitation.manifest_id, invitation.key_version, &invitation.inviter_user_id, recipient_public_key, &invitation.algorithm, encrypted_vek);+ if !crypto::signing::verify(signer_public_key, &grant_message, grant_signature) {+ return Err(SyncError::Other(format!("The grant in invitation {} is not signed by the inviter", invitation.id)));+ }+ if let Some(encrypted_name) = invitation.encrypted_name.as_deref() {+ let name_is_signed = invitation.encrypted_name_signature.as_deref().is_some_and(|signature| crypto::signing::verify(signer_public_key, &crypto::signing::invitation_name_message(&invitation.manifest_id, &invitation.inviter_user_id, recipient_public_key, encrypted_name), signature));+ if !name_is_signed {+ return Err(SyncError::Other(format!("The name in invitation {} is not signed by the inviter", invitation.id)));+ }+ }+ if recipient_public_key != own_public_key {+ return Err(SyncError::Other(format!("Invitation {} is encrypted for a key that is not this account's", invitation.id)));+ }+ let private_key = ctx.account_private_key.clone().ok_or_else(|| SyncError::Other("This session holds no account private key".to_string()))?;+ keys::decrypt_manifest_vek(encrypted_vek, &invitation.manifest_id, private_key.expose_secret()).map_err(|e| SyncError::Other(format!("The key in invitation {} does not open with this account's private key: {}", invitation.id, e)))?;++ let own_grant_signature = me.sign(&crypto::signing::grant_message(&invitation.manifest_id, invitation.key_version, &me.user_id, recipient_public_key, &invitation.algorithm, encrypted_vek))?;+ http::post_no_content(&ctx.host, &format!("Groups/invitations/{}/accept", invitation.id), &AcceptInvitationRequest { grant_signature: Some(&own_grant_signature) }).await?;+ ctx.log(format!("[Sharing] Accepted the invitation to shared manifest {} and signed its grant.", invitation.manifest_id)).await;+ Ok(Ok(Done::manifest(invitation.manifest_id.clone())))}/// The key record this account holds on a shared manifest.diff --git a/core/rust/src/vault_sync/types.rs b/core/rust/src/vault_sync/types.rsindex 648b05d61..13a70d959 100644--- a/core/rust/src/vault_sync/types.rs+++ b/core/rust/src/vault_sync/types.rs@@ -31,6 +31,14 @@ pub enum SyncOperation {InviteToSharedManifest,/// Change the details of a shared manifest (its name); the server refuses anyone but an administrator of its group.UpdateSharedManifest,+ /// Find the account behind an identity code and check the code against its key, without certifying or inviting it.+ LookupIdentityCode,+ /// Invite an account to a group by its identity code, certifying its signing key first.+ InviteToGroup,+ /// Accept an invitation to join a group, certifying the inviter's signing key with their identity code first.+ AcceptGroupInvitation,+ /// Accept an invitation to a shared manifest, signing the grant with this account's own key.+ AcceptSharedManifestInvitation,/// Rotate the account's keys and re-encrypt the personal vault under them; see `KeyRotationParams`.RotateAccountKeys,}@@ -59,13 +67,19 @@ pub struct KeyRotationParams {#[derive(Debug, Clone, Default, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SharingParams {- pub group_id: String,+ #[serde(default)]+ pub group_id: Option<String>,#[serde(default)]pub manifest_id: Option<String>,#[serde(default)]pub user_id: Option<String>,#[serde(default)]pub name: Option<String>,+ #[serde(default)]+ pub invitation_id: Option<String>,+ /// The other party's identity code as the user typed it, for the operations that certify a key.+ #[serde(default)]+ pub identity_code: Option<String>,}/// Sync request.@@ -213,6 +227,11 @@ pub struct SharingOperationResult {/// The manifest the operation created or invited to.#[serde(skip_serializing_if = "Option::is_none")]pub manifest_id: Option<String>,+ /// The account an identity code belonged to.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub username: Option<String>,+ /// The account was already a member, so only its key was certified.+ pub already_member: bool,/// The vault (or the account's key hierarchy) has to finish upgrading before it can be shared.pub vault_upgrade_required: bool,/// A refusal carries only `failure.api_error_code` (e.g. `GROUP_MANIFEST_LIMIT_REACHED`), which the sharing screen has@@ -550,8 +569,6 @@ pub struct ManifestDto {#[serde(default)]pub grant_signer_user_id: Option<String>,#[serde(default)]- pub grant_signer_public_key: Option<String>,- #[serde(default)]pub key_version: i64,}