Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

contacts: only cache root key after confirmation

Neeraj Guptafcf995292d03
diff --git a/mobile/packages/contacts/lib/src/service/contacts_service.dart b/mobile/packages/contacts/lib/src/service/contacts_service.dart
index 1cf124fcab..3fbf9d087f 100644
--- a/mobile/packages/contacts/lib/src/service/contacts_service.dart
+++ b/mobile/packages/contacts/lib/src/service/contacts_service.dart
@@ -34,31 +34,33 @@ class ContactsService {
final cachedRootKey = _cachedRootKey(session.userId);
final opened = await _rustApi
.open(
- OpenContactsContextInput(
- baseUrl: session.baseUrl,
- authToken: session.authToken,
- userId: session.userId,
- accountKey: accountKey,
- cachedRootKey: cachedRootKey,
- userAgent: session.userAgent,
- clientPackage: session.clientPackage,
- clientVersion: session.clientVersion,
- ),
- )
+ OpenContactsContextInput(
+ baseUrl: session.baseUrl,
+ authToken: session.authToken,
+ userId: session.userId,
+ accountKey: accountKey,
+ cachedRootKey: cachedRootKey,
+ userAgent: session.userAgent,
+ clientPackage: session.clientPackage,
+ clientVersion: session.clientVersion,
+ ),
+ )
.catchError((Object error, StackTrace stackTrace) {
- _logger.warning(
- "Failed to open contacts context for account user ${session.userId} "
- "at ${session.baseUrl} (hasCachedRootKey: ${cachedRootKey != null})",
- error,
- stackTrace,
- );
- throw error;
- });
+ _logger.warning(
+ "Failed to open contacts context for account user ${session.userId} "
+ "at ${session.baseUrl} (hasCachedRootKey: ${cachedRootKey != null})",
+ error,
+ stackTrace,
+ );
+ throw error;
+ });
_ctx = opened.ctx;
_session = session;
await _database.configure(userId: session.userId);
- await _persistWrappedRootKey(session.userId, opened.wrappedRootKey);
+ if (opened.rootKeySource != RootKeySource.created) {
+ await _persistWrappedRootKey(session.userId, opened.wrappedRootKey);
+ }
_logger.info('Opened contacts context for user ${session.userId}');
}
@@ -141,7 +143,9 @@ class ContactsService {
}
Future<ContactRecord> createContact(ContactData data) async {
- final created = await _requireCtx().createContact(data);
+ final ctx = _requireCtx();
+ final created = await ctx.createContact(data);
+ await _persistConfirmedWrappedRootKey();
await _database.upsertContacts([created]);
return created;
}
@@ -150,7 +154,9 @@ class ContactsService {
String contactId,
ContactData data,
) async {
- final updated = await _requireCtx().updateContact(contactId, data);
+ final ctx = _requireCtx();
+ final updated = await ctx.updateContact(contactId, data);
+ await _persistConfirmedWrappedRootKey();
await _database.upsertContacts([updated]);
return updated;
}
@@ -158,6 +164,7 @@ class ContactsService {
Future<void> deleteContact(String contactId) async {
final ctx = _requireCtx();
await ctx.deleteContact(contactId);
+ await _persistConfirmedWrappedRootKey();
final deleted = await ctx.getDiff(0, _syncLimit);
final matching =
deleted.where((element) => element.id == contactId).toList();
@@ -201,6 +208,7 @@ class ContactsService {
attachmentType,
bytes,
);
+ await _persistConfirmedWrappedRootKey();
await _database.upsertContacts([updated]);
final nextAttachmentId = updated.profilePictureAttachmentId;
if (nextAttachmentId != null) {
@@ -238,6 +246,7 @@ class ContactsService {
?.profilePictureAttachmentId;
final updated =
await _requireCtx().deleteAttachment(contactId, attachmentType);
+ await _persistConfirmedWrappedRootKey();
await _database.upsertContacts([updated]);
if (previousAttachmentId != null) {
await _database.deleteCachedAttachment(previousAttachmentId);
@@ -295,6 +304,15 @@ class ContactsService {
await _preferences.setString(_entityHeaderPref(userId), key.header);
}
+ Future<void> _persistConfirmedWrappedRootKey() async {
+ final session = _session;
+ final ctx = _ctx;
+ if (session == null || ctx == null) {
+ return;
+ }
+ await _persistWrappedRootKey(session.userId, ctx.currentWrappedRootKey());
+ }
+
String _entityKeyPref(int userId) => 'entity_key_contact_$userId';
String _entityHeaderPref(int userId) => 'entity_key_header_contact_$userId';
diff --git a/mobile/packages/contacts/test/contacts_service_test.dart b/mobile/packages/contacts/test/contacts_service_test.dart
index ba147f2ccd..71654d09e0 100644
--- a/mobile/packages/contacts/test/contacts_service_test.dart
+++ b/mobile/packages/contacts/test/contacts_service_test.dart
@@ -40,6 +40,7 @@ void main() {
});
test('open persists wrapped root key and sync caches contacts', () async {
+ rustApi.rootKeySource = RootKeySource.server;
rustApi.diffPages = [
[
const ContactRecord(
@@ -82,7 +83,24 @@ void main() {
expect(cached.single.profilePictureAttachmentId, 'att_1');
});
+ test('open does not persist a newly created root key', () async {
+ rustApi.rootKeySource = RootKeySource.created;
+
+ await service.open(
+ ContactsSession(
+ baseUrl: 'http://localhost:8080',
+ authToken: 'token',
+ userId: 1,
+ accountKey: Uint8List.fromList([1, 2, 3]),
+ ),
+ );
+
+ expect(preferences.getString('entity_key_contact_1'), isNull);
+ expect(preferences.getString('entity_key_header_contact_1'), isNull);
+ });
+
test('create and profile-picture changes update local cache', () async {
+ rustApi.rootKeySource = RootKeySource.created;
await service.open(
ContactsSession(
baseUrl: 'http://localhost:8080',
@@ -91,10 +109,17 @@ void main() {
accountKey: Uint8List.fromList([1, 2, 3]),
),
);
+ expect(preferences.getString('entity_key_contact_1'), isNull);
+ expect(preferences.getString('entity_key_header_contact_1'), isNull);
final created = await service.createContact(
const ContactData(contactUserId: 2, name: 'B'),
);
+ expect(preferences.getString('entity_key_contact_1'), 'enc-key');
+ expect(
+ preferences.getString('entity_key_header_contact_1'),
+ 'enc-header',
+ );
expect((await service.getContact(created.id))!.data!.name, 'B');
expect((await service.getContactByUserId(2))!.id, created.id);
@@ -331,6 +356,7 @@ class FakeContactsRustApi implements ContactsRustApi {
FakeContactsRustContext ctx = FakeContactsRustContext();
List<List<ContactRecord>> diffPages = const [];
Uint8List? lastAccountKey;
+ RootKeySource rootKeySource = RootKeySource.server;
@override
Future<OpenContactsContextResult> open(OpenContactsContextInput input) async {
@@ -343,7 +369,7 @@ class FakeContactsRustApi implements ContactsRustApi {
encryptedKey: 'enc-key',
header: 'enc-header',
),
- rootKeySource: RootKeySource.created,
+ rootKeySource: rootKeySource,
);
}
}
diff --git a/web/packages/contacts/index.test.ts b/web/packages/contacts/index.test.ts
index 01a67bd0fb..e3a34f9e7f 100644
--- a/web/packages/contacts/index.test.ts
+++ b/web/packages/contacts/index.test.ts
@@ -75,6 +75,7 @@ interface SetupOptions {
legacyInfo?: object;
getProfilePictureError?: Error;
getProfilePictureBytes?: Uint8Array;
+ rootKeySource?: "cache" | "server" | "created";
}
const setupContactsModule = async (options: SetupOptions = {}) => {
@@ -94,11 +95,6 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
const warn = vi.fn();
const error = vi.fn();
const update_auth_token = vi.fn();
- const current_wrapped_root_key = vi.fn(() => ({
- encryptedKey: "wrapped-root-key",
- header: "wrapped-header",
- }));
-
const diff = options.diff ?? [
{
id: "ct_1",
@@ -152,11 +148,17 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
}));
vi.doMock("ente-wasm", () => ({
contacts_open_ctx: vi.fn(() => ({
- update_auth_token,
- current_wrapped_root_key,
- get_diff,
- get_profile_picture,
- legacy_get_info,
+ ctx: {
+ update_auth_token,
+ get_diff,
+ get_profile_picture,
+ legacy_get_info,
+ },
+ wrappedRootKey: {
+ encryptedKey: "wrapped-root-key",
+ header: "wrapped-header",
+ },
+ rootKeySource: options.rootKeySource ?? "server",
})),
}));
@@ -194,6 +196,24 @@ describe("ensureContactsReady", () => {
const resolved = contacts.resolveContactDisplay({ userID: 101 });
expect(resolved.profilePictureAttachmentID).toBe("ua_1");
});
+
+ test("does not persist an unconfirmed locally created root key", async () => {
+ const { contacts, setKV } = await setupContactsModule({
+ rootKeySource: "created",
+ });
+
+ await contacts.ensureContactsReady({
+ userID: 101,
+ masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST",
+ });
+
+ const persisted = setKV.mock.calls
+ .map(([key, value]) => `${String(key)}:${JSON.stringify(value)}`)
+ .join("\n");
+
+ expect(persisted).toContain("contacts/");
+ expect(persisted).not.toContain("wrapped-root-key");
+ });
});
describe("profile picture loading", () => {
diff --git a/web/packages/contacts/index.ts b/web/packages/contacts/index.ts
index 903421e89a..8eadb6d10f 100644
--- a/web/packages/contacts/index.ts
+++ b/web/packages/contacts/index.ts
@@ -99,6 +99,14 @@ interface ContactsReadyInput {
masterKeyB64: string;
}
+type RootKeySource = "cache" | "server" | "created";
+
+interface OpenedContactsCtx {
+ ctx: ContactsCtxHandle;
+ wrappedRootKey: WrappedRootContactKey;
+ rootKeySource: RootKeySource;
+}
+
interface ContactsState {
snapshot: ContactsDisplaySnapshot;
listeners: Set<() => void>;
@@ -367,17 +375,20 @@ const ensureContactsCtxOpen = async ({
cachedRootKey,
clientPackage: clientPackageName,
clientVersion: isDesktop ? desktopAppVersion : undefined,
- });
+ }) as OpenedContactsCtx;
if (!isCurrentSession(sessionKey, generation)) {
return;
}
- state.ctx = openedCtx;
- ctx = openedCtx;
- const wrappedRootKey =
- openedCtx.current_wrapped_root_key() as WrappedRootContactKey;
- await saveWrappedRootContactKey(sessionKey, wrappedRootKey);
- if (!isCurrentSession(sessionKey, generation)) {
- return;
+ state.ctx = openedCtx.ctx;
+ ctx = openedCtx.ctx;
+ if (openedCtx.rootKeySource !== "created") {
+ await saveWrappedRootContactKey(
+ sessionKey,
+ openedCtx.wrappedRootKey,
+ );
+ if (!isCurrentSession(sessionKey, generation)) {
+ return;
+ }
}
} else if (state.currentAuthToken !== authToken) {
ctx.update_auth_token(authToken);
diff --git a/web/packages/wasm/Cargo.lock b/web/packages/wasm/Cargo.lock
index 36b5e35a28..ccb35e3bc9 100644
--- a/web/packages/wasm/Cargo.lock
+++ b/web/packages/wasm/Cargo.lock
@@ -354,6 +354,7 @@ version = "0.0.1"
dependencies = [
"ente-contacts",
"ente-core",
+ "js-sys",
"md-5",
"serde",
"serde-wasm-bindgen",
diff --git a/web/packages/wasm/Cargo.toml b/web/packages/wasm/Cargo.toml
index 82937d629c..edb71e239b 100644
--- a/web/packages/wasm/Cargo.toml
+++ b/web/packages/wasm/Cargo.toml
@@ -10,6 +10,7 @@ crate-type = ["cdylib"]
ente-contacts = { path = "../../../rust/contacts" }
ente-core = { path = "../../../rust/core", features = ["srp"] }
md-5 = "0.10"
+js-sys = "0.3"
serde = { version = "1", features = ["derive"] }
serde-wasm-bindgen = "0.6"
wasm-bindgen = "0.2"
diff --git a/web/packages/wasm/src/contacts.rs b/web/packages/wasm/src/contacts.rs
index e21e02aee5..5304700a32 100644
--- a/web/packages/wasm/src/contacts.rs
+++ b/web/packages/wasm/src/contacts.rs
@@ -2,9 +2,10 @@
use ente_contacts::{
ContactsCtx, ContactsError as CoreContactsError, LegacyContactState, OpenContactsCtxInput,
- WrappedRootContactKey,
+ RootKeySource, WrappedRootContactKey,
};
use ente_core::{auth::KeyAttributes, crypto};
+use js_sys::{Object, Reflect};
use serde::{Deserialize, Serialize};
use serde_wasm_bindgen as swb;
use wasm_bindgen::prelude::*;
@@ -106,7 +107,7 @@ impl From<ente_contacts::ContactRecord> for ContactRecordJs {
/// Open contacts context for web.
#[wasm_bindgen]
-pub async fn contacts_open_ctx(input: JsValue) -> Result<ContactsCtxHandle, ContactsError> {
+pub async fn contacts_open_ctx(input: JsValue) -> Result<JsValue, ContactsError> {
let input: OpenContactsCtxJsInput = swb::from_value(input)?;
let master_key = crypto::decode_b64(&input.master_key_b64).map_err(|e| ContactsError {
code: "decode".to_string(),
@@ -125,7 +126,31 @@ pub async fn contacts_open_ctx(input: JsValue) -> Result<ContactsCtxHandle, Cont
})
.await?;
- Ok(ContactsCtxHandle { inner: result.ctx })
+ let output = Object::new();
+ Reflect::set(
+ &output,
+ &JsValue::from_str("ctx"),
+ &JsValue::from(ContactsCtxHandle { inner: result.ctx }),
+ )
+ .expect("setting ctx should not fail");
+ Reflect::set(
+ &output,
+ &JsValue::from_str("wrappedRootKey"),
+ &swb::to_value(&result.wrapped_root_key).map_err(ContactsError::from)?,
+ )
+ .expect("setting wrappedRootKey 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",
+ }),
+ )
+ .expect("setting rootKeySource should not fail");
+
+ Ok(output.into())
}
/// Handle to an open contacts context.