Skip to content

armgit / ente

Public Imported from GitHub
0

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

Reuse sessions across Locker mutations and simplify service calls

Manav Rathif9024648d3be
diff --git a/web/apps/locker/src/services/collection-membership.ts b/web/apps/locker/src/services/collection-membership.ts
index 0c597d8e80..c6af606c11 100644
--- a/web/apps/locker/src/services/collection-membership.ts
+++ b/web/apps/locker/src/services/collection-membership.ts
@@ -2,66 +2,23 @@ import type { LockerCollection } from "@/types";
import { ensureLocalUser } from "ente-accounts/services/user";
import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { apiURL } from "ente-base/origins";
-import { decryptBox, encryptBox } from "ente-locker-wasm";
+import { decryptBox, encryptBox, type Session } from "ente-locker-wasm";
+import { ensureAuthenticatedSession } from "./authenticated-session";
import { deleteCollection, ensureUncategorizedCollection } from "./collections";
import {
getCollectionIDsForFile,
getCollectionRecord,
getEncryptedFileRecord,
+ type EncryptedCollectionRecord,
} from "./locker-cache";
-import { decryptCollectionKey } from "./sync/decrypt";
+import { openCollectionKeyForRecord } from "./sync/decrypt";
-interface CollectionRecordLike {
- id: number;
- ownerID: number;
- type: string;
-}
-
-export interface EncryptedCollectionFileItem {
+interface EncryptedCollectionFileItem {
id: number;
encryptedKey: string;
keyDecryptionNonce: string;
}
-interface CollectionMutationDeps {
- getCollectionIDsForFile: (fileID: number) => number[];
- getCollectionRecord: (
- collectionID: number,
- ) => CollectionRecordLike | undefined;
- ensureUncategorizedCollection: (
- masterKey: string,
- ) => Promise<CollectionRecordLike>;
- decryptFileKeyForCollection: (
- fileID: number,
- collectionID: number,
- ) => Promise<string>;
- buildEncryptedFileMoveItem: (
- fileID: number,
- fromCollectionID: number,
- toCollectionID: number,
- ) => Promise<EncryptedCollectionFileItem>;
- removeFilesFromCollection: (
- collectionID: number,
- fileIDs: number[],
- ) => Promise<void>;
- moveFilesBetweenCollections: (
- fromCollectionID: number,
- toCollectionID: number,
- files: EncryptedCollectionFileItem[],
- ) => Promise<void>;
- addFileToCollections: (
- fileID: number,
- fileKey: string,
- targetCollectionIDs: number[],
- ) => Promise<void>;
-}
-
-interface CollectionMutationContext {
- currentUserID: number;
- masterKey: string;
- deps: CollectionMutationDeps;
-}
-
const AUTO_MOVE_EXCLUDED_COLLECTION_TYPES = new Set([
"favorites",
"uncategorized",
@@ -76,12 +33,11 @@ const appendMapValue = <K, V>(map: Map<K, V[]>, key: K, value: V) => {
map.set(key, [value]);
};
-const createCachedUncategorizedResolver = (
- loadUncategorizedCollection: () => Promise<CollectionRecordLike>,
-) => {
- let uncategorizedCollection: CollectionRecordLike | undefined;
+const createCachedUncategorizedResolver = (masterKey: string) => {
+ let uncategorizedCollection: EncryptedCollectionRecord | undefined;
return async () => {
- uncategorizedCollection ??= await loadUncategorizedCollection();
+ uncategorizedCollection ??=
+ await ensureUncategorizedCollection(masterKey);
return uncategorizedCollection;
};
};
@@ -89,9 +45,6 @@ const createCachedUncategorizedResolver = (
const isAutoMoveCandidateCollection = (
collectionID: number,
currentUserID: number,
- getCollectionRecord: (
- collectionID: number,
- ) => CollectionRecordLike | undefined,
sourceCollectionID?: number,
) => {
if (collectionID === sourceCollectionID) {
@@ -110,23 +63,18 @@ const resolveAutoMoveTargetCollectionID = async ({
currentUserID,
sourceCollectionID,
preferredCollectionIDs,
- getCollectionRecord,
getUncategorizedCollection,
}: {
currentUserID: number;
sourceCollectionID: number;
preferredCollectionIDs: number[];
- getCollectionRecord: (
- collectionID: number,
- ) => CollectionRecordLike | undefined;
- getUncategorizedCollection: () => Promise<CollectionRecordLike>;
+ getUncategorizedCollection: () => Promise<EncryptedCollectionRecord>;
}) => {
const existingTargetCollectionID = preferredCollectionIDs.find(
(candidateCollectionID) =>
isAutoMoveCandidateCollection(
candidateCollectionID,
currentUserID,
- getCollectionRecord,
sourceCollectionID,
),
);
@@ -137,26 +85,16 @@ const resolveAutoMoveTargetCollectionID = async ({
return (await getUncategorizedCollection()).id;
};
-export const updateItemCollectionsWithDeps = async (
+export const updateItemCollections = async (
fileID: number,
collectionIDs: number[],
- context: CollectionMutationContext,
+ masterKey: string,
): Promise<void> => {
- const { currentUserID, masterKey, deps } = context;
- const {
- getCollectionIDsForFile,
- getCollectionRecord,
- ensureUncategorizedCollection,
- decryptFileKeyForCollection,
- buildEncryptedFileMoveItem,
- removeFilesFromCollection,
- moveFilesBetweenCollections,
- addFileToCollections,
- } = deps;
+ const currentUserID = ensureLocalUser().id;
+ const session = await ensureAuthenticatedSession();
const currentCollectionIDs = getCollectionIDsForFile(fileID);
- const getUncategorizedCollection = createCachedUncategorizedResolver(() =>
- ensureUncategorizedCollection(masterKey),
- );
+ const getUncategorizedCollection =
+ createCachedUncategorizedResolver(masterKey);
const nextCollectionIDs = Array.from(
new Set(
collectionIDs.length > 0
@@ -179,7 +117,11 @@ export const updateItemCollectionsWithDeps = async (
) ?? currentCollectionIDs[0])
: undefined;
const sourceFileKeyForAdd = sourceCollectionIDForAdd
- ? await decryptFileKeyForCollection(fileID, sourceCollectionIDForAdd)
+ ? await decryptFileKeyForCollection(
+ session,
+ fileID,
+ sourceCollectionIDForAdd,
+ )
: null;
// Add the new memberships before removing existing ones so the file
@@ -188,7 +130,8 @@ export const updateItemCollectionsWithDeps = async (
if (!sourceFileKeyForAdd) {
throw new Error(`File ${fileID} has no source collection`);
}
- await addFileToCollections(
+ await addFileToCollectionsWithSession(
+ session,
fileID,
sourceFileKeyForAdd,
collectionIDsToAdd,
@@ -210,7 +153,6 @@ export const updateItemCollectionsWithDeps = async (
currentUserID,
sourceCollectionID: collectionID,
preferredCollectionIDs: nextCollectionIDs,
- getCollectionRecord,
getUncategorizedCollection,
});
if (targetCollectionID === collectionID) {
@@ -218,6 +160,7 @@ export const updateItemCollectionsWithDeps = async (
}
await moveFilesBetweenCollections(collectionID, targetCollectionID, [
await buildEncryptedFileMoveItem(
+ session,
fileID,
collectionID,
targetCollectionID,
@@ -226,25 +169,15 @@ export const updateItemCollectionsWithDeps = async (
}
};
-// This helper only rehomes or detaches the collection's files; the caller is
-// responsible for issuing the final collection delete request.
-export const deleteCollectionKeepingFilesWithDeps = async (
+export const deleteCollectionKeepingFiles = async (
collection: LockerCollection,
- context: CollectionMutationContext,
+ masterKey: string,
): Promise<void> => {
- const { currentUserID, masterKey, deps } = context;
- const {
- getCollectionIDsForFile,
- getCollectionRecord,
- ensureUncategorizedCollection,
- buildEncryptedFileMoveItem,
- removeFilesFromCollection,
- moveFilesBetweenCollections,
- } = deps;
+ const currentUserID = ensureLocalUser().id;
+ const session = await ensureAuthenticatedSession();
const collectionID = collection.id;
- const getUncategorizedCollection = createCachedUncategorizedResolver(() =>
- ensureUncategorizedCollection(masterKey),
- );
+ const getUncategorizedCollection =
+ createCachedUncategorizedResolver(masterKey);
const fileIDsToRemove: number[] = [];
const filesToMoveByTargetCollectionID = new Map<
@@ -264,13 +197,13 @@ export const deleteCollectionKeepingFilesWithDeps = async (
currentUserID,
sourceCollectionID: collectionID,
preferredCollectionIDs: getCollectionIDsForFile(item.id),
- getCollectionRecord,
getUncategorizedCollection,
});
appendMapValue(
filesToMoveByTargetCollectionID,
targetCollectionID,
await buildEncryptedFileMoveItem(
+ session,
item.id,
collectionID,
targetCollectionID,
@@ -287,21 +220,23 @@ export const deleteCollectionKeepingFilesWithDeps = async (
}
await removeFilesFromCollection(collectionID, fileIDsToRemove);
+ await deleteCollection(collectionID, { keepFiles: true });
};
-export const updateItemCollections = async (
+export const addFileToCollections = async (
fileID: number,
- collectionIDs: number[],
- masterKey: string,
-): Promise<void> => {
- await updateItemCollectionsWithDeps(fileID, collectionIDs, {
- currentUserID: ensureLocalUser().id,
- masterKey,
- deps: createCollectionMutationDeps(),
- });
-};
+ fileKey: string,
+ targetCollectionIDs: number[],
+): Promise<void> =>
+ addFileToCollectionsWithSession(
+ await ensureAuthenticatedSession(),
+ fileID,
+ fileKey,
+ targetCollectionIDs,
+ );
-export const addFileToCollections = async (
+const addFileToCollectionsWithSession = async (
+ session: Session,
fileID: number,
fileKey: string,
targetCollectionIDs: number[],
@@ -312,7 +247,10 @@ export const addFileToCollections = async (
throw new Error(`Collection ${targetCollectionID} not in cache`);
}
- const collectionKey = await decryptCollectionKey(collectionRecord);
+ const collectionKey = await openCollectionKeyForRecord(
+ session,
+ collectionRecord,
+ );
const encryptedFileKey = await encryptBox(fileKey, collectionKey);
const res = await fetch(await apiURL("/collections/add-files"), {
@@ -350,6 +288,7 @@ const batchValues = <T>(
};
const decryptFileKeyForCollection = async (
+ session: Session,
fileID: number,
collectionID: number,
): Promise<string> => {
@@ -365,7 +304,10 @@ const decryptFileKeyForCollection = async (
throw new Error(`Collection ${collectionID} not in cache`);
}
- const collectionKey = await decryptCollectionKey(collectionRecord);
+ const collectionKey = await openCollectionKeyForRecord(
+ session,
+ collectionRecord,
+ );
return await decryptBox(
{
encryptedData: fileRecord.encryptedKey,
@@ -376,16 +318,22 @@ const decryptFileKeyForCollection = async (
};
const buildEncryptedFileMoveItem = async (
+ session: Session,
fileID: number,
fromCollectionID: number,
toCollectionID: number,
): Promise<EncryptedCollectionFileItem> => {
- const fileKey = await decryptFileKeyForCollection(fileID, fromCollectionID);
+ const fileKey = await decryptFileKeyForCollection(
+ session,
+ fileID,
+ fromCollectionID,
+ );
const targetCollectionRecord = getCollectionRecord(toCollectionID);
if (!targetCollectionRecord) {
throw new Error(`Collection ${toCollectionID} not in cache`);
}
- const targetCollectionKey = await decryptCollectionKey(
+ const targetCollectionKey = await openCollectionKeyForRecord(
+ session,
targetCollectionRecord,
);
const encryptedFileKey = await encryptBox(fileKey, targetCollectionKey);
@@ -443,26 +391,3 @@ const moveFilesBetweenCollections = async (
ensureOk(res);
}
};
-
-export const createCollectionMutationDeps = () => ({
- getCollectionIDsForFile,
- getCollectionRecord,
- ensureUncategorizedCollection,
- decryptFileKeyForCollection,
- buildEncryptedFileMoveItem,
- removeFilesFromCollection,
- moveFilesBetweenCollections,
- addFileToCollections,
-});
-
-export const deleteCollectionKeepingFiles = async (
- collection: LockerCollection,
- masterKey: string,
-): Promise<void> => {
- await deleteCollectionKeepingFilesWithDeps(collection, {
- currentUserID: ensureLocalUser().id,
- masterKey,
- deps: createCollectionMutationDeps(),
- });
- await deleteCollection(collection.id, { keepFiles: true });
-};
diff --git a/web/apps/locker/src/services/items.ts b/web/apps/locker/src/services/items.ts
index 20332f1f54..b14ff31904 100644
--- a/web/apps/locker/src/services/items.ts
+++ b/web/apps/locker/src/services/items.ts
@@ -11,8 +11,7 @@ import {
} from "ente-locker-wasm";
import {
addFileToCollections,
- createCollectionMutationDeps,
- updateItemCollectionsWithDeps,
+ updateItemCollections,
} from "./collection-membership";
import {
ensureFavoritesCollection,
@@ -261,10 +260,6 @@ export const setItemImportant = async (
return false;
}
- await updateItemCollectionsWithDeps(fileID, nextCollectionIDs, {
- currentUserID,
- masterKey,
- deps: createCollectionMutationDeps(),
- });
+ await updateItemCollections(fileID, nextCollectionIDs, masterKey);
return true;
};
diff --git a/web/apps/locker/src/services/sync/decrypt.ts b/web/apps/locker/src/services/sync/decrypt.ts
index fd690ae540..807e3f3b4d 100644
--- a/web/apps/locker/src/services/sync/decrypt.ts
+++ b/web/apps/locker/src/services/sync/decrypt.ts
@@ -349,7 +349,7 @@ export const decryptCollectionKey = async (
): Promise<string> =>
openCollectionKeyForRecord(await ensureAuthenticatedSession(), record);
-const openCollectionKeyForRecord = (
+export const openCollectionKeyForRecord = (
session: Session,
record: EncryptedCollectionRecord,
) =>
diff --git a/web/apps/locker/src/services/trash.ts b/web/apps/locker/src/services/trash.ts
index 9f9971a1ba..c15c28e763 100644
--- a/web/apps/locker/src/services/trash.ts
+++ b/web/apps/locker/src/services/trash.ts
@@ -3,8 +3,9 @@ import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import log from "ente-base/log";
import { apiURL } from "ente-base/origins";
import { decryptBox, encryptBox } from "ente-locker-wasm";
+import { ensureAuthenticatedSession } from "./authenticated-session";
import { getCollectionRecord, getEncryptedFileRecord } from "./locker-cache";
-import { decryptCollectionKey } from "./sync/decrypt";
+import { openCollectionKeyForRecord } from "./sync/decrypt";
import { fetchLockerTrash } from "./sync/sync";
export const trashFiles = async (
@@ -58,7 +59,11 @@ export const restoreFromTrash = async (
if (!collectionRecord)
throw new Error(`Collection ${targetCollectionID} not in cache`);
- const collectionKey = await decryptCollectionKey(collectionRecord);
+ const session = await ensureAuthenticatedSession();
+ const collectionKey = await openCollectionKeyForRecord(
+ session,
+ collectionRecord,
+ );
const buildRestorePayload = async (
candidateItems: Pick<LockerItem, "id" | "collectionID">[],
@@ -88,8 +93,10 @@ export const restoreFromTrash = async (
continue;
}
- const origCollectionKey =
- await decryptCollectionKey(origCollectionRecord);
+ const origCollectionKey = await openCollectionKeyForRecord(
+ session,
+ origCollectionRecord,
+ );
const fileKey = await decryptBox(
{
encryptedData: fileRecord.encryptedKey,
diff --git a/web/apps/locker/src/services/uploads.ts b/web/apps/locker/src/services/uploads.ts
index 3d97280969..c69eaaa9da 100644
--- a/web/apps/locker/src/services/uploads.ts
+++ b/web/apps/locker/src/services/uploads.ts
@@ -54,20 +54,6 @@ export type LockerUploadProgress =
| { phase: "uploading"; loaded: number; total: number }
| { phase: "finalizing" };
-interface UploadDeps<TCollectionRecord> {
- getCollectionRecord: (
- collectionID: number,
- ) => TCollectionRecord | undefined;
- decryptCollectionKey: (
- collectionRecord: TCollectionRecord,
- ) => Promise<string>;
- addFileToCollections: (
- fileID: number,
- fileKey: string,
- targetCollectionIDs: number[],
- ) => Promise<void>;
-}
-
const fetchUploadURL = async (
contentLength: number,
contentMd5: string,
@@ -280,13 +266,17 @@ const createAggregateUploadProgressReporter = (
};
};
-export const uploadLockerFileWithDeps = async <TCollectionRecord>(
+export const uploadLockerFile = async (
file: File,
collectionIDs: number[],
- deps: UploadDeps<TCollectionRecord>,
+ masterKey: string,
onProgress?: (progress: LockerUploadProgress) => void,
): Promise<number> => {
- const [collectionID, ...additionalCollectionIDs] = collectionIDs;
+ const [collectionID, ...additionalCollectionIDs] =
+ await resolveCollectionIDsWithUncategorizedFallback(
+ collectionIDs,
+ masterKey,
+ );
if (collectionID === undefined) {
throw new Error("No collection selected");
}
@@ -437,11 +427,11 @@ export const uploadLockerFileWithDeps = async <TCollectionRecord>(
encryptedThumb.md5Hash,
);
- const collectionRecord = deps.getCollectionRecord(collectionID);
+ const collectionRecord = getCollectionRecord(collectionID);
if (!collectionRecord) {
throw new Error(`Collection ${collectionID} not in cache`);
}
- const collectionKey = await deps.decryptCollectionKey(collectionRecord);
+ const collectionKey = await decryptCollectionKey(collectionRecord);
const encryptedKey = await encryptBox(fileKey, collectionKey);
const now = Date.now();
@@ -500,7 +490,7 @@ export const uploadLockerFileWithDeps = async <TCollectionRecord>(
ensureOk(res);
const created = RemoteIDResponseSchema.parse(await res.json());
if (additionalCollectionIDs.length > 0) {
- await deps.addFileToCollections(
+ await addFileToCollections(
created.id,
fileKey,
additionalCollectionIDs,
@@ -508,22 +498,3 @@ export const uploadLockerFileWithDeps = async <TCollectionRecord>(
}
return created.id;
};
-
-export const uploadLockerFile = async (
- file: File,
- collectionIDs: number[],
- masterKey: string,
- onProgress?: (progress: LockerUploadProgress) => void,
-): Promise<number> => {
- const targetCollectionIDs =
- await resolveCollectionIDsWithUncategorizedFallback(
- collectionIDs,
- masterKey,
- );
- return uploadLockerFileWithDeps(
- file,
- targetCollectionIDs,
- { getCollectionRecord, decryptCollectionKey, addFileToCollections },
- onProgress,
- );
-};
diff --git a/web/apps/locker/tests/collection-membership.test.ts b/web/apps/locker/tests/collection-membership.test.ts
index 79e8a5c0c9..7e634cb76f 100644
--- a/web/apps/locker/tests/collection-membership.test.ts
+++ b/web/apps/locker/tests/collection-membership.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import {
+ addFileToCollections,
deleteCollectionKeepingFiles,
updateItemCollections,
} from "../src/services/collection-membership";
@@ -10,6 +11,9 @@ import {
} from "../src/services/locker-cache";
import type { LockerCollection, LockerItem } from "../src/types";
+const { ensureAuthenticatedSession } = vi.hoisted(() => ({
+ ensureAuthenticatedSession: vi.fn(() => Promise.resolve({})),
+}));
vi.mock("ente-accounts/services/user", () => ({
ensureLocalUser: () => ({ id: 1 }),
}));
@@ -26,7 +30,9 @@ vi.mock("ente-base/origins", () => ({
: path,
}));
vi.mock("ente-base/log", () => ({ default: {} }));
-vi.mock("../src/services/authenticated-session", () => ({}));
+vi.mock("../src/services/authenticated-session", () => ({
+ ensureAuthenticatedSession,
+}));
vi.mock("ente-locker-wasm", () => ({
decryptBox: () => "file-key",
encryptBox: (_fileKey: string, collectionKey: string) => ({
@@ -35,8 +41,10 @@ vi.mock("ente-locker-wasm", () => ({
}),
}));
vi.mock("../src/services/sync/decrypt", () => ({
- decryptCollectionKey: (record: EncryptedCollectionRecord) =>
- `collection-${record.id}`,
+ openCollectionKeyForRecord: (
+ _session: unknown,
+ record: EncryptedCollectionRecord,
+ ) => `collection-${record.id}`,
}));
vi.mock("../src/services/sync/sync", () => ({}));
@@ -124,6 +132,7 @@ afterEach(() => vi.unstubAllGlobals());
test("membership updates deduplicate targets and add before moving the removed owned membership", async () => {
await updateItemCollections(10, [2, 3, 3], "master-key");
+ expect(ensureAuthenticatedSession).toHaveBeenCalledOnce();
expect(requests()).toEqual([
{
url: "/collections/add-files",
@@ -157,6 +166,23 @@ test("membership updates deduplicate targets and add before moving the removed o
]);
});
+test("adding to multiple collections acquires one session", async () => {
+ await addFileToCollections(10, "file-key", [2, 3]);
+ expect(ensureAuthenticatedSession).toHaveBeenCalledOnce();
+ expect(requests().map((request) => request.body)).toEqual(
+ [2, 3].map((collectionID) => ({
+ collectionID,
+ files: [
+ {
+ id: 10,
+ encryptedKey: `encrypted-for-collection-${collectionID}`,
+ keyDecryptionNonce: "nonce",
+ },
+ ],
+ })),
+ );
+});
+
test("removing a shared membership detaches it without moving the file", async () => {
seed([10], true);
await updateItemCollections(10, [2], "master-key");
@@ -224,6 +250,7 @@ test("keeping files batches owned moves, detaches other owners' files, then dele
source([...ids.map((id) => item(id)), item(200, 2)]),
"master-key",
);
+ expect(ensureAuthenticatedSession).toHaveBeenCalledOnce();
const calls = requests();
expect(calls.map((call) => call.url)).toEqual([
"/collections/move-files",
diff --git a/web/apps/locker/tests/trash.test.ts b/web/apps/locker/tests/trash.test.ts
index 70697e6321..b3c4a40588 100644
--- a/web/apps/locker/tests/trash.test.ts
+++ b/web/apps/locker/tests/trash.test.ts
@@ -7,12 +7,14 @@ import {
} from "../src/services/trash";
const {
+ ensureAuthenticatedSession,
getCollectionRecord,
getEncryptedFileRecord,
fetchLockerTrash,
encryptBox,
warn,
} = vi.hoisted(() => ({
+ ensureAuthenticatedSession: vi.fn(),
getCollectionRecord: vi.fn(),
getEncryptedFileRecord: vi.fn(),
fetchLockerTrash: vi.fn(),
@@ -24,7 +26,8 @@ vi.mock("../src/services/locker-cache", () => ({
getEncryptedFileRecord,
}));
vi.mock("../src/services/sync/decrypt", () => ({
- decryptCollectionKey: (record: { id: number }) => `collection-${record.id}`,
+ openCollectionKeyForRecord: (_session: unknown, record: { id: number }) =>
+ `collection-${record.id}`,
}));
vi.mock("../src/services/sync/sync", () => ({ fetchLockerTrash }));
vi.mock("ente-locker-wasm", () => ({
@@ -40,11 +43,14 @@ vi.mock("ente-base/http", () => ({
vi.mock("ente-base/origins", () => ({ apiURL: (path: string) => path }));
vi.mock("ente-base/log", () => ({ default: { warn } }));
vi.mock("ente-accounts/services/user", () => ({}));
-vi.mock("../src/services/authenticated-session", () => ({}));
+vi.mock("../src/services/authenticated-session", () => ({
+ ensureAuthenticatedSession,
+}));
const fetchMock = vi.fn<typeof fetch>();
const items = [{ id: 1, collectionID: 2 }];
beforeEach(() => {
vi.resetAllMocks();
+ ensureAuthenticatedSession.mockResolvedValue({});
vi.stubGlobal("fetch", fetchMock);
fetchMock.mockResolvedValue(new Response(null, { status: 200 }));
getCollectionRecord.mockImplementation((id: number) => ({ id }));
@@ -85,22 +91,22 @@ test("trash mutations preserve endpoints and payloads", async () => {
["/trash/empty", "POST", { lastUpdatedAt: 123 }],
]);
});
-test("restore rewraps the original file key for the chosen destination", async () => {
- await restoreFromTrash(items, 9);
+test("restore reuses one session to rewrap file keys for the chosen destination", async () => {
+ await restoreFromTrash([...items, { id: 3, collectionID: 2 }], 9);
+ expect(ensureAuthenticatedSession).toHaveBeenCalledOnce();
expect(getEncryptedFileRecord).toHaveBeenCalledWith(1, 2);
+ expect(getEncryptedFileRecord).toHaveBeenCalledWith(3, 2);
expect(encryptBox).toHaveBeenCalledWith("file-key", "collection-9");
expect(fetchMock).toHaveBeenCalledWith(
"/collections/restore-files",
expect.objectContaining({
body: JSON.stringify({
collectionID: 9,
- files: [
- {
- id: 1,
- encryptedKey: "rewrapped",
- keyDecryptionNonce: "new-nonce",
- },
- ],
+ files: [1, 3].map((id) => ({
+ id,
+ encryptedKey: "rewrapped",
+ keyDecryptionNonce: "new-nonce",
+ })),
}),
}),
);
@@ -108,6 +114,7 @@ test("restore rewraps the original file key for the chosen destination", async (
test("restore refreshes missing cache records once before retrying", async () => {
getEncryptedFileRecord.mockReturnValueOnce(undefined);
await restoreFromTrash(items, 9);
+ expect(ensureAuthenticatedSession).toHaveBeenCalledOnce();
expect(fetchLockerTrash).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledTimes(1);
});