π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[locker][web] Validate decrypted shared item data
AswinAsoka605286bdec6
diff --git a/web/apps/locker/src/services/info-type-wire.ts b/web/apps/locker/src/services/info-type-wire.tsindex c57edd154f..4e0d0cd4b7 100644--- a/web/apps/locker/src/services/info-type-wire.ts+++ b/web/apps/locker/src/services/info-type-wire.ts@@ -14,4 +14,4 @@ const internalTypeByWireType = new Map<string, LockerInfoInternalType>([export const fromInfoTypeWireValue = (value: string,-): LockerItemType | undefined => internalTypeByWireType.get(value);+): LockerInfoInternalType | undefined => internalTypeByWireType.get(value);diff --git a/web/apps/locker/src/services/sync/decrypt.ts b/web/apps/locker/src/services/sync/decrypt.tsindex edac7fe602..cf11c00582 100644--- a/web/apps/locker/src/services/sync/decrypt.ts+++ b/web/apps/locker/src/services/sync/decrypt.ts@@ -12,7 +12,7 @@ import {openCollectionKey,type Session,} from "ente-locker-wasm";-import type { z } from "zod";+import { z } from "zod";import { ensureAuthenticatedSession } from "../authenticated-session";import { fromInfoTypeWireValue } from "../info-type-wire";import {@@ -39,6 +39,36 @@ export interface LockerTrashData {const COLLECTION_PAYLOAD_VERSION = 1;+// Mobile metadata can omit empty fields or encode them as null. Normalize+// these while rejecting non-string values before they reach item views.+const itemText = z+ .string()+ .nullish()+ .transform((value) => value ?? "");+const optionalItemText = z+ .string()+ .nullish()+ .transform((value) => value ?? undefined);+const infoDataSchemas = {+ note: z.object({ title: itemText, content: itemText }),+ accountCredential: z.object({+ name: itemText,+ username: optionalItemText,+ password: optionalItemText,+ notes: optionalItemText,+ }),+ physicalRecord: z.object({+ name: itemText,+ location: optionalItemText,+ notes: optionalItemText,+ }),+ emergencyContact: z.object({+ name: itemText,+ contactDetails: itemText,+ notes: optionalItemText,+ }),+};+const collectionTextDecoder = new TextDecoder();const describeCryptoError = (error: unknown) =>@@ -425,19 +455,20 @@ const decryptFileToLockerItem = async (}const info = pubMagicMetadata?.info as- { type?: string; data?: Record<string, unknown> } | undefined;+ { type?: string; data?: unknown } | undefined;const infoType =typeof info?.type === "string"? fromInfoTypeWireValue(info.type): undefined;- const infoData = info?.data;-- if (infoType && infoData) {+ if (infoType) {+ // A malformed item is caught below and skipped individually in+ // both active collections and trash, including cached reloads.+ const data = infoDataSchemas[infoType].parse(info?.data);return {id: record.id,type: infoType,- data: infoData as unknown as LockerItem["data"],+ data,collectionID: record.collectionID,collectionIDs: [record.collectionID],ownerID: record.ownerID ?? collectionOwnerID,diff --git a/web/apps/locker/tests/sync.test.ts b/web/apps/locker/tests/sync.test.tsindex 3992e5e9bf..750461c20d 100644--- a/web/apps/locker/tests/sync.test.ts+++ b/web/apps/locker/tests/sync.test.ts@@ -142,6 +142,119 @@ test("persisted hydration preserves memberships, metadata, trash and cursors witexpect(ensureAuthenticatedSession).toHaveBeenCalledOnce();});+const infoItemCases = [+ { type: "note", data: { title: "Note", content: "Body" } },+ {+ type: "accountCredential",+ data: {+ name: "Account",+ username: "user",+ password: " secret ",+ notes: "Notes",+ },+ },+ {+ type: "physicalRecord",+ data: { name: "Record", location: "Home", notes: "Notes" },+ },+ {+ type: "emergencyContact",+ data: { name: "Contact", contactDetails: "123", notes: "Notes" },+ },+];++test.each(+ infoItemCases.flatMap(({ type, data }) =>+ Object.keys(data).flatMap((field) =>+ [{ unexpected: "object" }, ["array"], 42, true].map((value) => ({+ type,+ field,+ data: { ...data, [field]: value },+ })),+ ),+ ),+)(+ "malformed $type $field is isolated during cached hydration and trash loading: $data",+ async ({ type, data }) => {+ const saved = snapshot();+ saved.files.push({+ ...file(12, 1),+ pubMagicMetadata: { version: 1, data: "bad", header: "header" },+ });+ saved.trashFiles.push({+ ...file(13, 1),+ pubMagicMetadata: { version: 1, data: "bad", header: "header" },+ updatedAt: 40,+ deleteBy: 100,+ });+ vi.mocked(db.loadLockerSnapshotFromDB).mockResolvedValue(saved);+ decryptMetadataJSON.mockImplementation(+ (value: { encryptedData: string }) =>+ value.encryptedData === "bad"+ ? { info: { type, data } }+ : { title: "Healthy file" },+ );++ // The encrypted bad records remain persisted. Reopening must still+ // show the healthy items in both the vault and trash.+ for (let load = 0; load < 2; load++) {+ const result = await loadPersistedLockerState();+ expect(result.collections).toHaveLength(2);+ expect(+ result.collections.map((entry) =>+ entry.items.map((item) => item.id),+ ),+ ).toEqual([[10], [10]]);+ expect(result.trashItems.map((item) => item.id)).toEqual([11]);+ expect(getLockerCacheSnapshot().files.has(12)).toBe(true);+ }+ },+);++test.each([null, undefined, [], "text", 42, true])(+ "invalid info data is skipped rather than admitted as an item: %j",+ async (data) => {+ decryptMetadataJSON.mockResolvedValue({ info: { type: "note", data } });+ const result = await loadPersistedLockerState();+ expect(+ result.collections.every((entry) => entry.items.length === 0),+ ).toBe(true);+ expect(result.trashItems).toEqual([]);+ },+);++test.each([+ ...infoItemCases,+ { type: "account-credential", data: { name: "Account" } },+ { type: "physical-record", data: { name: "Record" } },+ {+ type: "emergency-contact",+ data: { name: "Contact", contactDetails: "123" },+ },+])("valid $type metadata retains its fields", async ({ type, data }) => {+ decryptMetadataJSON.mockResolvedValue({ info: { type, data } });+ const result = await loadPersistedLockerState();+ const expectedType = type.replace(/-([a-z])/g, (_, letter: string) =>+ letter.toUpperCase(),+ );+ expect(result.collections[0]?.items[0]).toMatchObject({+ type: expectedType,+ data,+ });+ expect(result.trashItems[0]).toMatchObject({ type: expectedType, data });+});++test("empty mobile fields are normalized and unknown fields are excluded", async () => {+ decryptMetadataJSON.mockResolvedValue({+ info: { type: "note", data: { title: null, extra: { nested: true } } },+ });+ const result = await loadPersistedLockerState();+ expect(result.collections[0]?.items[0]?.data).toEqual({+ title: "",+ content: "",+ });+});+test("partial decryption failure excludes only the failed collection and its cache records", async () => {openCollectionKey.mockImplementation((_session, _owner, key) => {if (key === "key-2") throw new Error("Bad key");