π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
contacts: make open local-only and rename root key APIs
Neeraj Gupta850b874a32cd
diff --git a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dartindex 06467ca6ac..99d19e2b29 100644--- a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart+++ b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart@@ -16,14 +16,14 @@ class WrappedRootContactKey {enum ContactAttachmentType { profilePicture }-enum RootKeySource { cache, server, created }+enum RootKeySource { cache, unresolved }class OpenContactsContextInput {final String baseUrl;final String authToken;final int userId;final Uint8List accountKey;- final WrappedRootContactKey? cachedRootKey;+ final WrappedRootContactKey? cachedWrappedRootContactKey;final String? userAgent;final String? clientPackage;final String? clientVersion;@@ -33,7 +33,7 @@ class OpenContactsContextInput {required this.authToken,required this.userId,required this.accountKey,- this.cachedRootKey,+ this.cachedWrappedRootContactKey,this.userAgent,this.clientPackage,this.clientVersion,@@ -42,12 +42,12 @@ class OpenContactsContextInput {class OpenContactsContextResult {final ContactsRustContext ctx;- final WrappedRootContactKey wrappedRootKey;+ final WrappedRootContactKey? wrappedRootContactKey;final RootKeySource rootKeySource;const OpenContactsContextResult({required this.ctx,- required this.wrappedRootKey,+ required this.wrappedRootContactKey,required this.rootKeySource,});}@@ -57,7 +57,7 @@ abstract class ContactsRustContext {Future<void> updateAuthToken(String authToken);- WrappedRootContactKey currentWrappedRootKey();+ WrappedRootContactKey? currentWrappedRootContactKey();Future<ContactRecord> createContact(ContactData data);@@ -110,11 +110,11 @@ class FrbContactsRustApi implements ContactsRustApi {authToken: input.authToken,userId: input.userId,masterKey: input.accountKey,- cachedRootKey: input.cachedRootKey == null+ cachedWrappedRootContactKey: input.cachedWrappedRootContactKey == null? null: rust.WrappedRootContactKey(- encryptedKey: input.cachedRootKey!.encryptedKey,- header: input.cachedRootKey!.header,+ encryptedKey: input.cachedWrappedRootContactKey!.encryptedKey,+ header: input.cachedWrappedRootContactKey!.header,),userAgent: input.userAgent,clientPackage: input.clientPackage,@@ -124,14 +124,15 @@ class FrbContactsRustApi implements ContactsRustApi {return OpenContactsContextResult(ctx: _FrbContactsRustContext(result.ctx),- wrappedRootKey: WrappedRootContactKey(- encryptedKey: result.wrappedRootKey.encryptedKey,- header: result.wrappedRootKey.header,- ),+ wrappedRootContactKey: result.wrappedRootContactKey == null+ ? null+ : WrappedRootContactKey(+ encryptedKey: result.wrappedRootContactKey!.encryptedKey,+ header: result.wrappedRootContactKey!.header,+ ),rootKeySource: switch (result.rootKeySource) {rust.RootKeySource.cache => RootKeySource.cache,- rust.RootKeySource.server => RootKeySource.server,- rust.RootKeySource.created => RootKeySource.created,+ rust.RootKeySource.unresolved => RootKeySource.unresolved,},);}@@ -151,8 +152,11 @@ class _FrbContactsRustContext implements ContactsRustContext {}@override- WrappedRootContactKey currentWrappedRootKey() {- final current = _inner.currentWrappedRootKey();+ WrappedRootContactKey? currentWrappedRootContactKey() {+ final current = _inner.currentWrappedRootContactKey();+ if (current == null) {+ return null;+ }return WrappedRootContactKey(encryptedKey: current.encryptedKey,header: current.header,diff --git a/mobile/packages/contacts/lib/src/service/contacts_service.dart b/mobile/packages/contacts/lib/src/service/contacts_service.dartindex 3fbf9d087f..783ab31d2f 100644--- a/mobile/packages/contacts/lib/src/service/contacts_service.dart+++ b/mobile/packages/contacts/lib/src/service/contacts_service.dart@@ -31,7 +31,8 @@ class ContactsService {Future<void> open(ContactsSession session) async {final accountKey = await session.resolveAccountKey();- final cachedRootKey = _cachedRootKey(session.userId);+ final cachedWrappedRootContactKey =+ _cachedWrappedRootContactKey(session.userId);final opened = await _rustApi.open(OpenContactsContextInput(@@ -39,7 +40,7 @@ class ContactsService {authToken: session.authToken,userId: session.userId,accountKey: accountKey,- cachedRootKey: cachedRootKey,+ cachedWrappedRootContactKey: cachedWrappedRootContactKey,userAgent: session.userAgent,clientPackage: session.clientPackage,clientVersion: session.clientVersion,@@ -48,7 +49,7 @@ class ContactsService {.catchError((Object error, StackTrace stackTrace) {_logger.warning("Failed to open contacts context for account user ${session.userId} "- "at ${session.baseUrl} (hasCachedRootKey: ${cachedRootKey != null})",+ "at ${session.baseUrl} (hasCachedRootKey: ${cachedWrappedRootContactKey != null})",error,stackTrace,);@@ -58,8 +59,11 @@ class ContactsService {_ctx = opened.ctx;_session = session;await _database.configure(userId: session.userId);- if (opened.rootKeySource != RootKeySource.created) {- await _persistWrappedRootKey(session.userId, opened.wrappedRootKey);+ if (opened.wrappedRootContactKey != null) {+ await _persistWrappedRootContactKey(+ session.userId,+ opened.wrappedRootContactKey!,+ );}_logger.info('Opened contacts context for user ${session.userId}');}@@ -287,7 +291,7 @@ class ContactsService {return ctx;}- WrappedRootContactKey? _cachedRootKey(int userId) {+ WrappedRootContactKey? _cachedWrappedRootContactKey(int userId) {final encryptedKey = _preferences.getString(_entityKeyPref(userId));final header = _preferences.getString(_entityHeaderPref(userId));if (encryptedKey == null || header == null) {@@ -296,7 +300,7 @@ class ContactsService {return WrappedRootContactKey(encryptedKey: encryptedKey, header: header);}- Future<void> _persistWrappedRootKey(+ Future<void> _persistWrappedRootContactKey(int userId,WrappedRootContactKey key,) async {@@ -310,7 +314,14 @@ class ContactsService {if (session == null || ctx == null) {return;}- await _persistWrappedRootKey(session.userId, ctx.currentWrappedRootKey());+ final currentWrappedRootContactKey = ctx.currentWrappedRootContactKey();+ if (currentWrappedRootContactKey == null) {+ return;+ }+ await _persistWrappedRootContactKey(+ session.userId,+ currentWrappedRootContactKey,+ );}String _entityKeyPref(int userId) => 'entity_key_contact_$userId';diff --git a/mobile/packages/contacts/test/contacts_display_service_test.dart b/mobile/packages/contacts/test/contacts_display_service_test.dartindex d04cede549..94d745ec8e 100644--- a/mobile/packages/contacts/test/contacts_display_service_test.dart+++ b/mobile/packages/contacts/test/contacts_display_service_test.dart@@ -330,11 +330,11 @@ class FakeContactsRustApi implements ContactsRustApi {context.diffPages = List<List<ContactRecord>>.from(diffPages);return OpenContactsContextResult(ctx: context,- wrappedRootKey: const WrappedRootContactKey(+ wrappedRootContactKey: const WrappedRootContactKey(encryptedKey: 'enc-key',header: 'enc-header',),- rootKeySource: RootKeySource.created,+ rootKeySource: RootKeySource.cache,);}}@@ -372,7 +372,8 @@ class FakeContactsRustContext implements ContactsRustContext {}@override- WrappedRootContactKey currentWrappedRootKey() => const WrappedRootContactKey(+ WrappedRootContactKey currentWrappedRootContactKey() =>+ const WrappedRootContactKey(encryptedKey: 'enc-key',header: 'enc-header',);diff --git a/mobile/packages/contacts/test/contacts_service_test.dart b/mobile/packages/contacts/test/contacts_service_test.dartindex 71654d09e0..c7cfa70b3a 100644--- a/mobile/packages/contacts/test/contacts_service_test.dart+++ b/mobile/packages/contacts/test/contacts_service_test.dart@@ -40,7 +40,7 @@ void main() {});test('open persists wrapped root key and sync caches contacts', () async {- rustApi.rootKeySource = RootKeySource.server;+ rustApi.rootKeySource = RootKeySource.cache;rustApi.diffPages = [[const ContactRecord(@@ -83,8 +83,10 @@ void main() {expect(cached.single.profilePictureAttachmentId, 'att_1');});- test('open does not persist a newly created root key', () async {- rustApi.rootKeySource = RootKeySource.created;+ test('open does not persist an unresolved wrapped root contact key',+ () async {+ rustApi.rootKeySource = RootKeySource.unresolved;+ rustApi.openWrappedRootContactKey = null;await service.open(ContactsSession(@@ -100,7 +102,8 @@ void main() {});test('create and profile-picture changes update local cache', () async {- rustApi.rootKeySource = RootKeySource.created;+ rustApi.rootKeySource = RootKeySource.unresolved;+ rustApi.openWrappedRootContactKey = null;await service.open(ContactsSession(baseUrl: 'http://localhost:8080',@@ -356,7 +359,12 @@ class FakeContactsRustApi implements ContactsRustApi {FakeContactsRustContext ctx = FakeContactsRustContext();List<List<ContactRecord>> diffPages = const [];Uint8List? lastAccountKey;- RootKeySource rootKeySource = RootKeySource.server;+ RootKeySource rootKeySource = RootKeySource.cache;+ WrappedRootContactKey? openWrappedRootContactKey =+ const WrappedRootContactKey(+ encryptedKey: 'enc-key',+ header: 'enc-header',+ );@overrideFuture<OpenContactsContextResult> open(OpenContactsContextInput input) async {@@ -365,10 +373,7 @@ class FakeContactsRustApi implements ContactsRustApi {lastAccountKey = input.accountKey;return OpenContactsContextResult(ctx: ctx,- wrappedRootKey: const WrappedRootContactKey(- encryptedKey: 'enc-key',- header: 'enc-header',- ),+ wrappedRootContactKey: openWrappedRootContactKey,rootKeySource: rootKeySource,);}@@ -404,7 +409,8 @@ class FakeContactsRustContext implements ContactsRustContext {}@override- WrappedRootContactKey currentWrappedRootKey() => const WrappedRootContactKey(+ WrappedRootContactKey currentWrappedRootContactKey() =>+ const WrappedRootContactKey(encryptedKey: 'enc-key',header: 'enc-header',);diff --git a/mobile/packages/rust/rust/src/api/contacts.rs b/mobile/packages/rust/rust/src/api/contacts.rsindex 58b04144fc..e2322fab40 100644--- a/mobile/packages/rust/rust/src/api/contacts.rs+++ b/mobile/packages/rust/rust/src/api/contacts.rs@@ -183,18 +183,15 @@ impl From<CoreContactRecord> for ContactRecord {pub enum RootKeySource {/// Reused the caller-provided cached wrapped root key.Cache,- /// Fetched the wrapped root key from the server.- Server,- /// Created a new wrapped root key locally; it is confirmed on first write.- Created,+ /// Opened without a cached wrapped root key; Rust will resolve it lazily.+ Unresolved,}impl From<CoreRootKeySource> for RootKeySource {fn from(value: CoreRootKeySource) -> Self {match value {CoreRootKeySource::Cache => RootKeySource::Cache,- CoreRootKeySource::Server => RootKeySource::Server,- CoreRootKeySource::Created => RootKeySource::Created,+ CoreRootKeySource::Unresolved => RootKeySource::Unresolved,}}}@@ -227,7 +224,7 @@ pub struct OpenContactsCtxInput {/// Logged-in account key used to unwrap or create the root contact key.pub master_key: Vec<u8>,/// Optional cached wrapped root key for the current user.- pub cached_root_key: Option<WrappedRootContactKey>,+ pub cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,/// Optional user agent to send to Ente API endpoints.pub user_agent: Option<String>,/// Optional client package header to send to Ente API endpoints.@@ -241,9 +238,9 @@ pub struct OpenContactsCtxInput {pub struct OpenContactsCtxResult {/// Opaque contacts context bound to the current account/session.pub ctx: ContactsCtx,- /// Current wrapped root key that the caller may persist.- pub wrapped_root_key: WrappedRootContactKey,- /// Source used to obtain the root key during open.+ /// Current wrapped root key that the caller may persist, if already resolved.+ pub wrapped_root_contact_key: Option<WrappedRootContactKey>,+ /// State of the root key during open.pub root_key_source: RootKeySource,}@@ -264,7 +261,7 @@ pub async fn open_contacts_ctx(auth_token: input.auth_token,user_id: input.user_id,master_key: input.master_key,- cached_root_key: input.cached_root_key.map(Into::into),+ cached_wrapped_root_contact_key: input.cached_wrapped_root_contact_key.map(Into::into),user_agent: input.user_agent,client_package: input.client_package,client_version: input.client_version,@@ -276,7 +273,7 @@ pub async fn open_contacts_ctx(ctx: ContactsCtx {inner: Arc::new(opened.ctx),},- wrapped_root_key: opened.wrapped_root_key.into(),+ wrapped_root_contact_key: opened.wrapped_root_contact_key.map(Into::into),root_key_source: opened.root_key_source.into(),})}@@ -294,9 +291,11 @@ impl ContactsCtx {}#[frb(sync)]- /// Return the current wrapped root key for caller-managed persistence.- pub fn current_wrapped_root_key(&self) -> WrappedRootContactKey {- self.inner.current_wrapped_root_key().into()+ /// Return the current wrapped root key for caller-managed persistence, if resolved.+ pub fn current_wrapped_root_contact_key(&self) -> Option<WrappedRootContactKey> {+ self.inner+ .current_wrapped_root_contact_key()+ .map(Into::into)}/// Create a contact for the referenced user.diff --git a/rust/contacts/src/client.rs b/rust/contacts/src/client.rsindex 9eb6b4a74b..a7325d1eff 100644--- a/rust/contacts/src/client.rs+++ b/rust/contacts/src/client.rs@@ -1,4 +1,3 @@-use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, RwLock};use ente_core::auth::{self, KeyAttributes, SrpSession};@@ -29,8 +28,7 @@ const CONTACT_TYPE: &str = "contact";#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum RootKeySource {Cache,- Server,- Created,+ Unresolved,}pub struct OpenContactsCtxInput {@@ -38,7 +36,7 @@ pub struct OpenContactsCtxInput {pub auth_token: String,pub user_id: i64,pub master_key: Vec<u8>,- pub cached_root_key: Option<WrappedRootContactKey>,+ pub cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,pub user_agent: Option<String>,pub client_package: Option<String>,pub client_version: Option<String>,@@ -46,7 +44,7 @@ pub struct OpenContactsCtxInput {pub struct OpenContactsCtxResult {pub ctx: ContactsCtx,- pub wrapped_root_key: WrappedRootContactKey,+ pub wrapped_root_contact_key: Option<WrappedRootContactKey>,pub root_key_source: RootKeySource,}@@ -55,13 +53,13 @@ pub struct ContactsCtx {http: HttpClient,object_store_http: ente_core::http::ObjectStoreHttpClient,master_key: Arc<RwLock<SecretVec>>,- root_contact_key: Arc<RwLock<SecretVec>>,- wrapped_root_key: Arc<RwLock<WrappedRootContactKey>>,- opened_with_cached_root_key: bool,- root_key_confirmed: AtomicBool,+ root_contact_key: Arc<RwLock<Option<SecretVec>>>,+ wrapped_root_contact_key: Arc<RwLock<Option<WrappedRootContactKey>>>,}-fn wrapped_root_key_from_response(remote_root_key: RootKeyResponse) -> WrappedRootContactKey {+fn wrapped_root_contact_key_from_response(+ remote_root_key: RootKeyResponse,+) -> WrappedRootContactKey {WrappedRootContactKey {encrypted_key: remote_root_key.encrypted_key,header: remote_root_key.header,@@ -79,57 +77,32 @@ impl ContactsCtx {timeout_secs: Some(30),})?;- let (root_contact_key, wrapped_root_key, root_key_source, root_key_confirmed) =- if let Some(cached_root_key) = input.cached_root_key {- let root_contact_key =- contacts_crypto::decrypt_root_contact_key(&cached_root_key, &input.master_key)?;- (- root_contact_key,- cached_root_key,- RootKeySource::Cache,- false,- )- } else if let Some(remote_root_key) = fetch_root_key(&http).await? {- let wrapped_root_key = wrapped_root_key_from_response(remote_root_key);+ let (root_contact_key, wrapped_root_contact_key, root_key_source) =+ if let Some(cached_wrapped_root_contact_key) = input.cached_wrapped_root_contact_key {let root_contact_key = contacts_crypto::decrypt_root_contact_key(- &wrapped_root_key,+ &cached_wrapped_root_contact_key,&input.master_key,)?;(- root_contact_key,- wrapped_root_key,- RootKeySource::Server,- true,+ Some(SecretVec::new(root_contact_key)),+ Some(cached_wrapped_root_contact_key),+ RootKeySource::Cache,)} else {- let generated_root_contact_key = keys::generate_key();- let generated_wrapped_root_key = contacts_crypto::encrypt_root_contact_key(- &generated_root_contact_key,- &input.master_key,- )?;- (- generated_root_contact_key,- generated_wrapped_root_key,- RootKeySource::Created,- false,- )+ (None, None, RootKeySource::Unresolved)};-- let opened_with_cached_root_key = root_key_source == RootKeySource::Cache;let ctx = Self {user_id: input.user_id,object_store_http: http.object_store(),http,master_key: Arc::new(RwLock::new(SecretVec::new(input.master_key))),- root_contact_key: Arc::new(RwLock::new(SecretVec::new(root_contact_key))),- wrapped_root_key: Arc::new(RwLock::new(wrapped_root_key.clone())),- opened_with_cached_root_key,- root_key_confirmed: AtomicBool::new(root_key_confirmed),+ root_contact_key: Arc::new(RwLock::new(root_contact_key)),+ wrapped_root_contact_key: Arc::new(RwLock::new(wrapped_root_contact_key.clone())),};Ok(OpenContactsCtxResult {ctx,- wrapped_root_key,+ wrapped_root_contact_key,root_key_source,})}@@ -142,39 +115,45 @@ impl ContactsCtx {self.http.set_auth_token(Some(auth_token));}- pub fn current_wrapped_root_key(&self) -> WrappedRootContactKey {- self.wrapped_root_key+ pub fn current_wrapped_root_contact_key(&self) -> Option<WrappedRootContactKey> {+ self.wrapped_root_contact_key.read().expect("wrapped root key lock poisoned").clone()}- fn apply_wrapped_root_key(&self, wrapped_root_key: WrappedRootContactKey) -> Result<()> {+ fn apply_wrapped_root_contact_key(+ &self,+ wrapped_root_contact_key: WrappedRootContactKey,+ ) -> Result<()> {let master_key = self.master_key.read().expect("master key lock poisoned");let decrypted_root_key =- contacts_crypto::decrypt_root_contact_key(&wrapped_root_key, &master_key)?;+ contacts_crypto::decrypt_root_contact_key(&wrapped_root_contact_key, &master_key)?;*self.root_contact_key.write()- .expect("root contact key lock poisoned") = SecretVec::new(decrypted_root_key);+ .expect("root contact key lock poisoned") = Some(SecretVec::new(decrypted_root_key));*self- .wrapped_root_key+ .wrapped_root_contact_key.write()- .expect("wrapped root key lock poisoned") = wrapped_root_key;+ .expect("wrapped root key lock poisoned") = Some(wrapped_root_contact_key);Ok(())}pub async fn create_contact(&self, data: &ContactData) -> Result<ContactRecord> {contacts_crypto::validate_contact_data(data)?;- self.ensure_root_key_confirmed().await?;+ self.ensure_root_key_available().await?;let contact_key = keys::generate_stream_key();let wrapped_contact_key = {- let root_contact_key = self+ let root_contact_key_guard = self.root_contact_key.read().expect("root contact key lock poisoned");- contacts_crypto::wrap_contact_key(&contact_key, &root_contact_key)?+ let root_contact_key = root_contact_key_guard.as_ref().ok_or_else(|| {+ ContactsError::InvalidInput("contacts root key is unresolved".into())+ })?;+ contacts_crypto::wrap_contact_key(&contact_key, root_contact_key)?};let encrypted_data = contacts_crypto::encrypt_contact_data(data, &contact_key)?;let response = self@@ -193,16 +172,17 @@ impl ContactsCtx {}pub async fn get_contact(&self, contact_id: &str) -> Result<ContactRecord> {- self.ensure_remote_root_key_for_read().await?;let response = self.http.get_json::<ContactEntityResponse>(&format!("/contacts/{contact_id}"), &[]).await?;+ if !response.is_deleted {+ self.ensure_root_key_available().await?;+ }self.decode_contact(response)}pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<Vec<ContactRecord>> {- self.ensure_remote_root_key_for_read().await?;let response = self.http.get_json::<ContactDiffResponse>(@@ -213,6 +193,9 @@ impl ContactsCtx {],).await?;+ if response.diff.iter().any(|entity| !entity.is_deleted) {+ self.ensure_root_key_available().await?;+ }response.diff@@ -227,7 +210,7 @@ impl ContactsCtx {data: &ContactData,) -> Result<ContactRecord> {contacts_crypto::validate_contact_data(data)?;- self.ensure_root_key_confirmed().await?;+ self.ensure_root_key_available().await?;let current = self.http@@ -238,11 +221,14 @@ impl ContactsCtx {.as_deref().ok_or(ContactsError::MissingEncryptedKey)?;let contact_key = {- let root_contact_key = self+ let root_contact_key_guard = self.root_contact_key.read().expect("root contact key lock poisoned");- contacts_crypto::unwrap_contact_key(encrypted_key, &root_contact_key)?+ let root_contact_key = root_contact_key_guard.as_ref().ok_or_else(|| {+ ContactsError::InvalidInput("contacts root key is unresolved".into())+ })?;+ contacts_crypto::unwrap_contact_key(encrypted_key, root_contact_key)?};let encrypted_data = contacts_crypto::encrypt_contact_data(data, &contact_key)?;@@ -261,7 +247,6 @@ impl ContactsCtx {}pub async fn delete_contact(&self, contact_id: &str) -> Result<()> {- self.ensure_root_key_confirmed().await?;self.http.delete_empty(&format!("/contacts/{contact_id}"), &[]).await?;@@ -274,7 +259,7 @@ impl ContactsCtx {attachment_type: AttachmentType,attachment_bytes: &[u8],) -> Result<ContactRecord> {- self.ensure_root_key_confirmed().await?;+ self.ensure_root_key_available().await?;let current = self.http@@ -285,11 +270,14 @@ impl ContactsCtx {.as_deref().ok_or(ContactsError::MissingEncryptedKey)?;let contact_key = {- let root_contact_key = self+ let root_contact_key_guard = self.root_contact_key.read().expect("root contact key lock poisoned");- contacts_crypto::unwrap_contact_key(encrypted_key, &root_contact_key)?+ let root_contact_key = root_contact_key_guard.as_ref().ok_or_else(|| {+ ContactsError::InvalidInput("contacts root key is unresolved".into())+ })?;+ contacts_crypto::unwrap_contact_key(encrypted_key, root_contact_key)?};let encrypted_attachment =contacts_crypto::encrypt_profile_picture(attachment_bytes, &contact_key)?;@@ -350,7 +338,6 @@ impl ContactsCtx {}pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>> {- self.ensure_remote_root_key_for_read().await?;let current = self.http.get_json::<ContactEntityResponse>(&format!("/contacts/{contact_id}"), &[])@@ -358,17 +345,21 @@ impl ContactsCtx {if current.is_deleted || current.profile_picture_attachment_id.is_none() {return Err(ContactsError::ProfilePictureNotFound);}+ self.ensure_root_key_available().await?;let encrypted_key = current.encrypted_key.as_deref().ok_or(ContactsError::MissingEncryptedKey)?;let contact_key = {- let root_contact_key = self+ let root_contact_key_guard = self.root_contact_key.read().expect("root contact key lock poisoned");- contacts_crypto::unwrap_contact_key(encrypted_key, &root_contact_key)?+ let root_contact_key = root_contact_key_guard.as_ref().ok_or_else(|| {+ ContactsError::InvalidInput("contacts root key is unresolved".into())+ })?;+ contacts_crypto::unwrap_contact_key(encrypted_key, root_contact_key)?};let encrypted_picture = self.get_attachment_encrypted(@@ -384,7 +375,6 @@ impl ContactsCtx {contact_id: &str,attachment_type: AttachmentType,) -> Result<ContactRecord> {- self.ensure_root_key_confirmed().await?;let response = self.http.delete_json::<ContactEntityResponse>(@@ -674,11 +664,14 @@ impl ContactsCtx {.encrypted_data.as_deref().ok_or(ContactsError::MissingEncryptedData)?;- let root_contact_key = self+ let root_contact_key_guard = self.root_contact_key.read().expect("root contact key lock poisoned");- let contact_key = contacts_crypto::unwrap_contact_key(encrypted_key, &root_contact_key)?;+ let root_contact_key = root_contact_key_guard+ .as_ref()+ .ok_or_else(|| ContactsError::InvalidInput("contacts root key is unresolved".into()))?;+ let contact_key = contacts_crypto::unwrap_contact_key(encrypted_key, root_contact_key)?;let data = contacts_crypto::decrypt_contact_data(encrypted_data, &contact_key)?;Ok(ContactRecord {@@ -694,37 +687,37 @@ impl ContactsCtx {})}- async fn ensure_root_key_confirmed(&self) -> Result<()> {- if self.root_key_confirmed.load(Ordering::Acquire) {+ async fn ensure_root_key_available(&self) -> Result<()> {+ if self+ .root_contact_key+ .read()+ .expect("root contact key lock poisoned")+ .is_some()+ {return Ok(());}if let Some(remote_root_key) = fetch_root_key(&self.http).await? {- self.apply_wrapped_root_key(wrapped_root_key_from_response(remote_root_key))?;+ self.apply_wrapped_root_contact_key(wrapped_root_contact_key_from_response(+ remote_root_key,+ ))?;} else {- let wrapped_root_key = self.current_wrapped_root_key();- if let Some(remote_root_key) = create_root_key(&self.http, &wrapped_root_key).await? {- self.apply_wrapped_root_key(wrapped_root_key_from_response(remote_root_key))?;+ let generated_root_contact_key = keys::generate_key();+ let generated_wrapped_root_contact_key = {+ let master_key = self.master_key.read().expect("master key lock poisoned");+ contacts_crypto::encrypt_root_contact_key(&generated_root_contact_key, &master_key)?+ };+ if let Some(remote_root_key) =+ create_root_key(&self.http, &generated_wrapped_root_contact_key).await?+ {+ self.apply_wrapped_root_contact_key(wrapped_root_contact_key_from_response(+ remote_root_key,+ ))?;+ } else {+ self.apply_wrapped_root_contact_key(generated_wrapped_root_contact_key)?;}}- self.root_key_confirmed.store(true, Ordering::Release);- Ok(())- }-- async fn ensure_remote_root_key_for_read(&self) -> Result<()> {- if self.root_key_confirmed.load(Ordering::Acquire) {- return Ok(());- }- if self.opened_with_cached_root_key {- return Ok(());- }-- if let Some(remote_root_key) = fetch_root_key(&self.http).await? {- self.apply_wrapped_root_key(wrapped_root_key_from_response(remote_root_key))?;- self.root_key_confirmed.store(true, Ordering::Release);- }-Ok(())}@@ -799,12 +792,12 @@ impl ContactsCtx {}fn current_secret_key(&self, current_user_key_attrs: &KeyAttributes) -> Result<SecretVec> {- let encrypted_secret_key = crypto::decode_b64(¤t_user_key_attrs.encrypted_secret_key)?;+ let encrypted_secret_key =+ crypto::decode_b64(¤t_user_key_attrs.encrypted_secret_key)?;let secret_key_nonce =crypto::decode_b64(¤t_user_key_attrs.secret_key_decryption_nonce)?;let master_key = self.master_key.read().expect("master key lock poisoned");- let secret_key =- secretbox::decrypt(&encrypted_secret_key, &secret_key_nonce, &master_key)?;+ let secret_key = secretbox::decrypt(&encrypted_secret_key, &secret_key_nonce, &master_key)?;Ok(SecretVec::new(secret_key))}}@@ -818,12 +811,12 @@ async fn fetch_root_key(http: &HttpClient) -> Result<Option<RootKeyResponse>> {async fn create_root_key(http: &HttpClient,- wrapped_root_key: &WrappedRootContactKey,+ wrapped_root_contact_key: &WrappedRootContactKey,) -> Result<Option<RootKeyResponse>> {let request = CreateRootKeyRequest {r#type: CONTACT_TYPE,- encrypted_key: &wrapped_root_key.encrypted_key,- header: &wrapped_root_key.header,+ encrypted_key: &wrapped_root_contact_key.encrypted_key,+ header: &wrapped_root_contact_key.header,};match http.post_empty("/user-entity/key", &request).await {@@ -902,13 +895,18 @@ fn password_reset_setup_request(new_password: &str,updated_key_attrs: &KeyAttributes,) -> Result<(SrpSession, LegacySetupSrpRequest)> {- let mem_limit = updated_key_attrs- .mem_limit- .ok_or_else(|| ContactsError::InvalidInput("updated key attributes missing memLimit".into()))?;- let ops_limit = updated_key_attrs- .ops_limit- .ok_or_else(|| ContactsError::InvalidInput("updated key attributes missing opsLimit".into()))?;- let kek = auth::derive_kek(new_password, &updated_key_attrs.kek_salt, mem_limit, ops_limit)?;+ let mem_limit = updated_key_attrs.mem_limit.ok_or_else(|| {+ ContactsError::InvalidInput("updated key attributes missing memLimit".into())+ })?;+ let ops_limit = updated_key_attrs.ops_limit.ok_or_else(|| {+ ContactsError::InvalidInput("updated key attributes missing opsLimit".into())+ })?;+ let kek = auth::derive_kek(+ new_password,+ &updated_key_attrs.kek_salt,+ mem_limit,+ ops_limit,+ )?;let generated_srp = auth::generate_srp_setup(&kek, srp_user_id)?;let srp_session = SrpSession::new(srp_user_id,diff --git a/rust/contacts/src/crypto.rs b/rust/contacts/src/crypto.rsindex 425caac3bf..22ca0a1061 100644--- a/rust/contacts/src/crypto.rs+++ b/rust/contacts/src/crypto.rs@@ -17,11 +17,11 @@ pub fn encrypt_root_contact_key(}pub fn decrypt_root_contact_key(- wrapped_root_key: &WrappedRootContactKey,+ wrapped_root_contact_key: &WrappedRootContactKey,master_key: &[u8],) -> Result<Vec<u8>> {- let encrypted_key = crypto::decode_b64(&wrapped_root_key.encrypted_key)?;- let header = crypto::decode_b64(&wrapped_root_key.header)?;+ let encrypted_key = crypto::decode_b64(&wrapped_root_contact_key.encrypted_key)?;+ let header = crypto::decode_b64(&wrapped_root_contact_key.header)?;Ok(secretbox::decrypt(&encrypted_key, &header, master_key)?)}diff --git a/rust/contacts/tests/contacts_mock.rs b/rust/contacts/tests/contacts_mock.rsindex 3ef0efd526..af1c2c001b 100644--- a/rust/contacts/tests/contacts_mock.rs+++ b/rust/contacts/tests/contacts_mock.rs@@ -19,7 +19,7 @@ fn open_input(base_url: String, master_key: Vec<u8>) -> OpenContactsCtxInput {auth_token: "auth-token".to_string(),user_id: 7,master_key,- cached_root_key: None,+ cached_wrapped_root_contact_key: None,user_agent: Some("ente-contacts-test".to_string()),client_package: Some("io.ente.photos".to_string()),client_version: Some("1.0.0".to_string()),@@ -55,7 +55,7 @@ fn live_entity_json(}#[tokio::test]-async fn open_fetches_existing_root_key_from_server() {+async fn open_without_cached_wrapped_root_contact_key_is_unresolved() {let mut server = Server::new_async().await;let master_key = keys::generate_key();let root_key = keys::generate_key();@@ -75,6 +75,7 @@ async fn open_fetches_existing_root_key_from_server() {}).to_string(),)+ .expect(0).create_async().await;@@ -83,27 +84,19 @@ async fn open_fetches_existing_root_key_from_server() {.unwrap();root_mock.assert_async().await;- assert_eq!(opened.root_key_source, RootKeySource::Server);- assert_eq!(opened.wrapped_root_key, wrapped_root);+ assert_eq!(opened.root_key_source, RootKeySource::Unresolved);+ assert_eq!(opened.wrapped_root_contact_key, None);}#[tokio::test]-async fn get_contact_refreshes_generated_root_key_when_server_key_appears_later() {+async fn get_contact_fetches_root_key_when_unresolved_context_reads_live_contact() {let mut server = Server::new_async().await;let master_key = keys::generate_key();let server_root_key = keys::generate_key();let server_wrapped_root = wrap_root(&server_root_key, &master_key);let contact = sample_contact();- let initial_fetch_mock = server- .mock("GET", "/user-entity/key")- .match_query(Matcher::UrlEncoded("type".into(), "contact".into()))- .with_status(404)- .expect(1)- .create_async()- .await;-- let refresh_root_mock = server+ let root_fetch_mock = server.mock("GET", "/user-entity/key").match_query(Matcher::UrlEncoded("type".into(), "contact".into())).with_status(200)@@ -143,16 +136,18 @@ async fn get_contact_refreshes_generated_root_key_when_server_key_appears_later(.unwrap();let fetched = opened.ctx.get_contact("ct_contact1").await.unwrap();- initial_fetch_mock.assert_async().await;- refresh_root_mock.assert_async().await;+ root_fetch_mock.assert_async().await;get_contact_mock.assert_async().await;- assert_eq!(opened.root_key_source, RootKeySource::Created);- assert_eq!(opened.ctx.current_wrapped_root_key(), server_wrapped_root);+ assert_eq!(opened.root_key_source, RootKeySource::Unresolved);+ assert_eq!(+ opened.ctx.current_wrapped_root_contact_key(),+ Some(server_wrapped_root)+ );assert_eq!(fetched.name.as_deref(), Some(contact.name.as_str()));}#[tokio::test]-async fn create_contact_uses_cached_root_key_but_confirms_before_write() {+async fn create_contact_uses_cached_wrapped_root_contact_key_without_fetching_remote_key() {let mut server = Server::new_async().await;let master_key = keys::generate_key();let root_key = keys::generate_key();@@ -174,7 +169,7 @@ async fn create_contact_uses_cached_root_key_but_confirms_before_write() {}).to_string(),)- .expect(1)+ .expect(0).create_async().await;@@ -200,7 +195,7 @@ async fn create_contact_uses_cached_root_key_but_confirms_before_write() {.await;let ctx = ContactsCtx::open(OpenContactsCtxInput {- cached_root_key: Some(wrapped_root),+ cached_wrapped_root_contact_key: Some(wrapped_root),..open_input(server.url(), master_key)}).await@@ -437,6 +432,7 @@ async fn get_attachment_uses_generic_signed_download_url() {}).to_string(),)+ .expect(0).create_async().await;@@ -503,6 +499,7 @@ async fn deleted_contacts_surface_as_tombstones() {}).to_string(),)+ .expect(0).create_async().await;@@ -548,11 +545,11 @@ async fn deleted_contacts_surface_as_tombstones() {}#[tokio::test]-async fn get_diff_uses_cached_root_key_for_reads_without_fetching_remote_key() {+async fn get_diff_uses_cached_wrapped_root_contact_key_for_reads_without_fetching_remote_key() {let mut server = Server::new_async().await;let master_key = keys::generate_key();- let cached_root_key = keys::generate_key();- let cached_wrapped_root = wrap_root(&cached_root_key, &master_key);+ let cached_wrapped_root_contact_key = keys::generate_key();+ let cached_wrapped_root = wrap_root(&cached_wrapped_root_contact_key, &master_key);let contact = sample_contact();let no_fetch_root_mock = server@@ -576,7 +573,7 @@ async fn get_diff_uses_cached_root_key_for_reads_without_fetching_remote_key() {"ct_contact1",&contact,Some("[email protected]"),- &cached_root_key,+ &cached_wrapped_root_contact_key,None,)]})@@ -587,7 +584,7 @@ async fn get_diff_uses_cached_root_key_for_reads_without_fetching_remote_key() {.await;let ctx = ContactsCtx::open(OpenContactsCtxInput {- cached_root_key: Some(cached_wrapped_root),+ cached_wrapped_root_contact_key: Some(cached_wrapped_root),..open_input(server.url(), master_key)}).awaitdiff --git a/rust/contacts/tests/live_contacts.rs b/rust/contacts/tests/live_contacts.rsindex c1b5d20525..ed047451eb 100644--- a/rust/contacts/tests/live_contacts.rs+++ b/rust/contacts/tests/live_contacts.rs@@ -175,7 +175,7 @@ async fn open_ctx(endpoint: &str, account: &TestAccount) -> ContactsCtx {auth_token: account.auth_token.clone(),user_id: account.user_id,master_key: account.master_key.clone(),- cached_root_key: None,+ cached_wrapped_root_contact_key: None,user_agent: Some("ente-contacts-live-test".to_string()),client_package: Some(App::Photos.client_package().to_string()),client_version: Some("0.0.1".to_string()),diff --git a/web/packages/contacts/db.ts b/web/packages/contacts/db.tsindex e765cba0fe..e0b1177783 100644--- a/web/packages/contacts/db.ts+++ b/web/packages/contacts/db.ts@@ -3,7 +3,7 @@ import { z } from "zod";import type { ContactDisplayRecord, WrappedRootContactKey } from "./types";const contactsKey = (sessionKey: string) => `contacts/${sessionKey}/records`;-const wrappedRootKeyKey = (sessionKey: string) =>+const wrappedRootContactKeyKey = (sessionKey: string) =>`contacts/${sessionKey}/root-key`;const sinceTimeKey = (sessionKey: string) =>`contacts/${sessionKey}/since-time`;@@ -44,14 +44,14 @@ export const saveContactDisplayRecords = (export const savedWrappedRootContactKey = async (sessionKey: string,): Promise<WrappedRootContactKey | undefined> => {- const saved = await getKV(wrappedRootKeyKey(sessionKey));+ const saved = await getKV(wrappedRootContactKeyKey(sessionKey));return saved ? WrappedRootContactKeyZ.parse(saved) : undefined;};export const saveWrappedRootContactKey = (sessionKey: string,- wrappedRootKey: WrappedRootContactKey,-) => setKV(wrappedRootKeyKey(sessionKey), wrappedRootKey);+ wrappedRootContactKey: WrappedRootContactKey,+) => setKV(wrappedRootContactKeyKey(sessionKey), wrappedRootContactKey);export const savedContactsSinceTime = (sessionKey: string) =>getKVN(sinceTimeKey(sessionKey));diff --git a/web/packages/contacts/index.test.ts b/web/packages/contacts/index.test.tsindex e3a34f9e7f..41c951ec1d 100644--- a/web/packages/contacts/index.test.ts+++ b/web/packages/contacts/index.test.ts@@ -75,7 +75,8 @@ interface SetupOptions {legacyInfo?: object;getProfilePictureError?: Error;getProfilePictureBytes?: Uint8Array;- rootKeySource?: "cache" | "server" | "created";+ rootKeySource?: "cache" | "unresolved";+ wrappedRootContactKey?: { encryptedKey: string; header: string };}const setupContactsModule = async (options: SetupOptions = {}) => {@@ -154,11 +155,15 @@ const setupContactsModule = async (options: SetupOptions = {}) => {get_profile_picture,legacy_get_info,},- wrappedRootKey: {- encryptedKey: "wrapped-root-key",- header: "wrapped-header",- },- rootKeySource: options.rootKeySource ?? "server",+ wrappedRootContactKey:+ options.wrappedRootContactKey ??+ (options.rootKeySource === "unresolved"+ ? undefined+ : {+ encryptedKey: "wrapped-root-key",+ header: "wrapped-header",+ }),+ rootKeySource: options.rootKeySource ?? "cache",})),}));@@ -197,9 +202,9 @@ describe("ensureContactsReady", () => {expect(resolved.profilePictureAttachmentID).toBe("ua_1");});- test("does not persist an unconfirmed locally created root key", async () => {+ test("does not persist an unresolved wrapped root contact key", async () => {const { contacts, setKV } = await setupContactsModule({- rootKeySource: "created",+ rootKeySource: "unresolved",});await contacts.ensureContactsReady({diff --git a/web/packages/contacts/index.ts b/web/packages/contacts/index.tsindex a44ae2085d..5810fc8e2a 100644--- a/web/packages/contacts/index.ts+++ b/web/packages/contacts/index.ts@@ -99,11 +99,11 @@ interface ContactsReadyInput {masterKeyB64: string;}-type RootKeySource = "cache" | "server" | "created";+type RootKeySource = "cache" | "unresolved";interface OpenedContactsCtx {ctx: ContactsCtxHandle;- wrappedRootKey: WrappedRootContactKey;+ wrappedRootContactKey?: WrappedRootContactKey;rootKeySource: RootKeySource;}@@ -362,7 +362,8 @@ const ensureContactsCtxOpen = async ({const generation = state.sessionGeneration;if (!ctx) {- const cachedRootKey = await savedWrappedRootContactKey(sessionKey);+ const cachedWrappedRootContactKey =+ await savedWrappedRootContactKey(sessionKey);if (!isCurrentSession(sessionKey, generation)) {return;}@@ -372,7 +373,7 @@ const ensureContactsCtxOpen = async ({authToken,userId: userID,masterKeyB64,- cachedRootKey,+ cachedWrappedRootContactKey,clientPackage: clientPackageName,clientVersion: isDesktop ? desktopAppVersion : undefined,})) as OpenedContactsCtx;@@ -381,10 +382,10 @@ const ensureContactsCtxOpen = async ({}state.ctx = openedCtx.ctx;ctx = openedCtx.ctx;- if (openedCtx.rootKeySource !== "created") {+ if (openedCtx.wrappedRootContactKey) {await saveWrappedRootContactKey(sessionKey,- openedCtx.wrappedRootKey,+ openedCtx.wrappedRootContactKey,);if (!isCurrentSession(sessionKey, generation)) {return;diff --git a/web/packages/wasm/src/contacts.rs b/web/packages/wasm/src/contacts.rsindex 5304700a32..fe951f4bdd 100644--- a/web/packages/wasm/src/contacts.rs+++ b/web/packages/wasm/src/contacts.rs@@ -68,7 +68,7 @@ struct OpenContactsCtxJsInput {auth_token: String,user_id: i64,master_key_b64: String,- cached_root_key: Option<WrappedRootContactKey>,+ cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,user_agent: Option<String>,client_package: Option<String>,client_version: Option<String>,@@ -119,7 +119,7 @@ pub async fn contacts_open_ctx(input: JsValue) -> Result<JsValue, ContactsError>auth_token: input.auth_token,user_id: input.user_id,master_key,- cached_root_key: input.cached_root_key,+ cached_wrapped_root_contact_key: input.cached_wrapped_root_contact_key,user_agent: input.user_agent,client_package: input.client_package,client_version: input.client_version,@@ -135,17 +135,16 @@ pub async fn contacts_open_ctx(input: JsValue) -> Result<JsValue, ContactsError>.expect("setting ctx should not fail");Reflect::set(&output,- &JsValue::from_str("wrappedRootKey"),- &swb::to_value(&result.wrapped_root_key).map_err(ContactsError::from)?,+ &JsValue::from_str("wrappedRootContactKey"),+ &swb::to_value(&result.wrapped_root_contact_key).map_err(ContactsError::from)?,)- .expect("setting wrappedRootKey should not fail");+ .expect("setting wrappedRootContactKey should not fail");Reflect::set(&output,&JsValue::from_str("rootKeySource"),&JsValue::from_str(match result.root_key_source {RootKeySource::Cache => "cache",- RootKeySource::Server => "server",- RootKeySource::Created => "created",+ RootKeySource::Unresolved => "unresolved",}),).expect("setting rootKeySource should not fail");@@ -166,9 +165,9 @@ impl ContactsCtxHandle {self.inner.update_auth_token(auth_token);}- /// Return the wrapped root key currently held by this context.- pub fn current_wrapped_root_key(&self) -> Result<JsValue, ContactsError> {- swb::to_value(&self.inner.current_wrapped_root_key()).map_err(Into::into)+ /// Return the wrapped root key currently held by this context, if resolved.+ pub fn current_wrapped_root_contact_key(&self) -> Result<JsValue, ContactsError> {+ swb::to_value(&self.inner.current_wrapped_root_contact_key()).map_err(Into::into)}/// Pull a diff page of contacts.