Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions apps/web/__tests__/unit/database-crypto.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { afterEach, describe, expect, it, vi } from "vitest";

const env = vi.hoisted(() => ({ key: "11".repeat(32) }));
vi.mock("@cap/env", () => ({
serverEnv: () => ({ DATABASE_ENCRYPTION_KEY: env.key }),
}));

import { decrypt, encrypt } from "@cap/database/crypto";

afterEach(() => {
vi.restoreAllMocks();
env.key = "11".repeat(32);
});

describe("database encryption", () => {
it("derives a stored value's key once and decrypts it again from the cached key", async () => {
const stored = await encrypt("drive-config");
const derive = vi.spyOn(crypto.subtle, "deriveKey");
await expect(
Promise.all([decrypt(stored), decrypt(stored)]),
).resolves.toEqual(["drive-config", "drive-config"]);
await expect(decrypt(stored)).resolves.toBe("drive-config");
await expect(decrypt(stored)).resolves.toBe("drive-config");
expect(derive).toHaveBeenCalledTimes(1);
});

it("derives a separate key for each salt", async () => {
const first = await encrypt("first");
const second = await encrypt("second");
const derive = vi.spyOn(crypto.subtle, "deriveKey");
await expect(decrypt(first)).resolves.toBe("first");
await expect(decrypt(second)).resolves.toBe("second");
expect(derive).toHaveBeenCalledTimes(2);
});

it("still rejects a tampered value after its key is cached", async () => {
const stored = await encrypt("drive-config");
await decrypt(stored);
const bytes = Buffer.from(stored, "base64");
bytes.writeUInt8(
bytes.readUInt8(bytes.length - 1) ^ 0xff,
bytes.length - 1,
);
await expect(decrypt(bytes.toString("base64"))).rejects.toThrow(
"Decryption failed",
);
});

it("does not reuse a cached key after the encryption key changes", async () => {
const stored = await encrypt("drive-config");
await decrypt(stored);
env.key = "22".repeat(32);
await expect(decrypt(stored)).rejects.toThrow("Decryption failed");
});
});
25 changes: 24 additions & 1 deletion packages/database/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,29 @@ export async function encrypt(text: string): Promise<string> {
}
}

// A stored ciphertext keeps its salt, so decrypting the same value again (a storage integration's config
// on every Drive request) would repeat the same 100,000-iteration PBKDF2; the key only depends on the salt.
const DECRYPT_KEY_CACHE_SIZE = 256;
const decryptKeys = new Map<string, Promise<CryptoKey>>();

function decryptKey(salt: Uint8Array<ArrayBuffer>): Promise<CryptoKey> {
const id = `${ENCRYPTION_KEY() ?? ""}:${Buffer.from(salt).toString("hex")}`;
const cached = decryptKeys.get(id);
if (cached) {
decryptKeys.delete(id);
decryptKeys.set(id, cached);
return cached;
}
const key = deriveKey(salt);
decryptKeys.set(id, key);
key.catch(() => decryptKeys.delete(id));
if (decryptKeys.size > DECRYPT_KEY_CACHE_SIZE) {
const oldest = decryptKeys.keys().next().value;
if (oldest !== undefined) decryptKeys.delete(oldest);
}
return key;
}

export async function decrypt(encryptedText: string): Promise<string> {
if (!encryptedText) {
throw new Error("Cannot decrypt empty or null text");
Expand All @@ -107,7 +130,7 @@ export async function decrypt(encryptedText: string): Promise<string> {
const iv = encrypted.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
const content = encrypted.subarray(SALT_LENGTH + IV_LENGTH);

const key = await deriveKey(salt);
const key = await decryptKey(salt);

const decrypted = await crypto.subtle.decrypt(
{
Expand Down
Loading