-
Notifications
You must be signed in to change notification settings - Fork 6
fix(encrypted_maps): harden derived key material caching #401
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 1 commit
3aa4815
6bd734f
6c19d2a
c695787
9b3c89f
2084194
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| import { describe, expect, test, vi } from "vitest"; | ||
| import { Principal } from "@icp-sdk/core/principal"; | ||
| import { DerivedKeyMaterial } from "../utils/utils"; | ||
| import { | ||
| EncryptedMaps, | ||
| InMemoryDerivedKeyMaterialCache, | ||
| IndexedDbDerivedKeyMaterialCache, | ||
| type EncryptedMapsClient, | ||
| } from "./index"; | ||
|
|
||
| /** | ||
| * Builds a `DerivedKeyMaterial` backed by a fresh, non-extractable HKDF key, | ||
| * matching what the canister flow produces — without needing a replica. | ||
| */ | ||
| async function newDerivedKeyMaterial( | ||
| seed: number, | ||
| ): Promise<DerivedKeyMaterial> { | ||
| const keyBytes = new Uint8Array(32).fill(seed); | ||
| const raw = await crypto.subtle.importKey( | ||
| "raw", | ||
| keyBytes, | ||
| "HKDF", | ||
| false, // non-extractable | ||
| ["deriveKey", "deriveBits"], | ||
| ); | ||
| return DerivedKeyMaterial.fromCryptoKey(raw); | ||
| } | ||
|
|
||
| const PRINCIPAL_A = Principal.fromText("aaaaa-aa"); | ||
| const PRINCIPAL_B = Principal.fromText("rrkah-fqaaa-aaaaa-aaaaq-cai"); | ||
|
|
||
| /** | ||
| * Minimal client that only supports the calls the caching path needs. The | ||
| * remaining `EncryptedMapsClient` methods are never invoked in these tests. | ||
| */ | ||
| function mockClient(caller: Principal): EncryptedMapsClient { | ||
| return { | ||
| getCallerPrincipal: vi.fn(async () => caller), | ||
|
Check failure on line 38 in frontend/ic_vetkeys/src/encrypted_maps/cache.test.ts
|
||
| } as unknown as EncryptedMapsClient; | ||
| } | ||
|
|
||
| describe("InMemoryDerivedKeyMaterialCache", () => { | ||
| test("round-trips a stored key handle", async () => { | ||
| const cache = new InMemoryDerivedKeyMaterialCache(); | ||
| const dkm = await newDerivedKeyMaterial(1); | ||
| const key = dkm.getCryptoKey(); | ||
|
|
||
| expect(await cache.get("k")).toBeUndefined(); | ||
| await cache.set("k", key); | ||
| expect(await cache.get("k")).toBe(key); | ||
| }); | ||
|
|
||
| test("clear() drops all entries", async () => { | ||
| const cache = new InMemoryDerivedKeyMaterialCache(); | ||
| await cache.set("k", (await newDerivedKeyMaterial(1)).getCryptoKey()); | ||
| await cache.clear(); | ||
| expect(await cache.get("k")).toBeUndefined(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("IndexedDbDerivedKeyMaterialCache", () => { | ||
| test("persists a non-extractable key handle that cannot be exported", async () => { | ||
| // Use a unique database per test to avoid cross-test interference. | ||
| const cache = new IndexedDbDerivedKeyMaterialCache( | ||
| "ic-vetkeys-test-persist", | ||
| "store", | ||
| ); | ||
| const key = (await newDerivedKeyMaterial(7)).getCryptoKey(); | ||
|
|
||
| await cache.set("k", key); | ||
| const restored = await cache.get("k"); | ||
| expect(restored).toBeDefined(); | ||
| expect(restored?.extractable).toBe(false); | ||
| // The raw bytes must remain unrecoverable even after persistence. | ||
| await expect( | ||
| crypto.subtle.exportKey("raw", restored as CryptoKey), | ||
|
Check failure on line 76 in frontend/ic_vetkeys/src/encrypted_maps/cache.test.ts
|
||
| ).rejects.toThrow(); | ||
| }); | ||
|
|
||
| test("clear() empties the store", async () => { | ||
| const cache = new IndexedDbDerivedKeyMaterialCache( | ||
| "ic-vetkeys-test-clear", | ||
| "store", | ||
| ); | ||
| await cache.set("k", (await newDerivedKeyMaterial(7)).getCryptoKey()); | ||
| expect(await cache.get("k")).toBeDefined(); | ||
| await cache.clear(); | ||
| expect(await cache.get("k")).toBeUndefined(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("EncryptedMaps derived key caching", () => { | ||
| test("fetches once, then serves subsequent calls from cache", async () => { | ||
| const maps = new EncryptedMaps(mockClient(PRINCIPAL_A)); | ||
| const fetchSpy = vi | ||
| .spyOn(maps, "getDerivedKeyMaterial") | ||
| .mockImplementation(() => newDerivedKeyMaterial(1)); | ||
| const mapName = new TextEncoder().encode("some map"); | ||
|
|
||
| await maps.getDerivedKeyMaterialOrFetchIfNeeded(PRINCIPAL_A, mapName); | ||
| await maps.getDerivedKeyMaterialOrFetchIfNeeded(PRINCIPAL_A, mapName); | ||
|
|
||
| expect(fetchSpy).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| test("does not serve a key cached by a different caller (caller-scoped)", async () => { | ||
| const client = mockClient(PRINCIPAL_A); | ||
| const maps = new EncryptedMaps(client); | ||
| const fetchSpy = vi | ||
| .spyOn(maps, "getDerivedKeyMaterial") | ||
| .mockImplementation(() => newDerivedKeyMaterial(1)); | ||
| const mapName = new TextEncoder().encode("some map"); | ||
|
|
||
| // Caller A populates the cache. | ||
| await maps.getDerivedKeyMaterialOrFetchIfNeeded(PRINCIPAL_A, mapName); | ||
| expect(fetchSpy).toHaveBeenCalledTimes(1); | ||
|
|
||
| // The authenticated identity changes to B on the same instance. | ||
| ( | ||
| client.getCallerPrincipal as ReturnType<typeof vi.fn> | ||
| ).mockResolvedValue(PRINCIPAL_B); | ||
|
|
||
| // Same map owner + name, but B must NOT get A's cached key. | ||
| await maps.getDerivedKeyMaterialOrFetchIfNeeded(PRINCIPAL_A, mapName); | ||
| expect(fetchSpy).toHaveBeenCalledTimes(2); | ||
| }); | ||
|
|
||
| test("distinguishes maps that share a prefix in their names", async () => { | ||
| const maps = new EncryptedMaps(mockClient(PRINCIPAL_A)); | ||
| const fetchSpy = vi | ||
| .spyOn(maps, "getDerivedKeyMaterial") | ||
| .mockImplementation(() => newDerivedKeyMaterial(1)); | ||
|
|
||
| await maps.getDerivedKeyMaterialOrFetchIfNeeded( | ||
| PRINCIPAL_A, | ||
| Uint8Array.from([1]), | ||
| ); | ||
| await maps.getDerivedKeyMaterialOrFetchIfNeeded( | ||
| PRINCIPAL_A, | ||
| Uint8Array.from([1, 2]), | ||
| ); | ||
|
|
||
| expect(fetchSpy).toHaveBeenCalledTimes(2); | ||
| }); | ||
|
|
||
| test("clearCache() forces a re-fetch", async () => { | ||
| const maps = new EncryptedMaps(mockClient(PRINCIPAL_A)); | ||
| const fetchSpy = vi | ||
| .spyOn(maps, "getDerivedKeyMaterial") | ||
| .mockImplementation(() => newDerivedKeyMaterial(1)); | ||
| const mapName = new TextEncoder().encode("some map"); | ||
|
|
||
| await maps.getDerivedKeyMaterialOrFetchIfNeeded(PRINCIPAL_A, mapName); | ||
| await maps.clearCache(); | ||
| await maps.getDerivedKeyMaterialOrFetchIfNeeded(PRINCIPAL_A, mapName); | ||
|
|
||
| expect(fetchSpy).toHaveBeenCalledTimes(2); | ||
| }); | ||
|
|
||
| test("a cache hit still yields working key material", async () => { | ||
| const shared = await newDerivedKeyMaterial(42); | ||
| const maps = new EncryptedMaps(mockClient(PRINCIPAL_A)); | ||
| vi.spyOn(maps, "getDerivedKeyMaterial").mockResolvedValue(shared); | ||
| const mapName = new TextEncoder().encode("some map"); | ||
|
|
||
| const plaintext = new TextEncoder().encode("hello"); | ||
| const ciphertext = await maps.encryptFor( | ||
| PRINCIPAL_A, | ||
| mapName, | ||
| new TextEncoder().encode("k"), | ||
| plaintext, | ||
| ); | ||
| // Second call resolves the key material from cache, not the fetch. | ||
| const decrypted = await maps.decryptFor( | ||
| PRINCIPAL_A, | ||
| mapName, | ||
| new TextEncoder().encode("k"), | ||
| ciphertext, | ||
| ); | ||
|
|
||
| expect(decrypted).toEqual(plaintext); | ||
| }); | ||
| }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| /** | ||
| * @module @icp-sdk/vetkeys/encrypted_maps | ||
| * | ||
| * @description Caching strategies for derived key material. See | ||
| * {@link DerivedKeyMaterialCache}. | ||
| */ | ||
|
|
||
| import { | ||
| clear as idbClear, | ||
| createStore, | ||
| get as idbGet, | ||
| set as idbSet, | ||
| type UseStore, | ||
| } from "idb-keyval"; | ||
|
|
||
| /** | ||
| * Strategy for caching the per-map derived key material handles used by | ||
| * {@link EncryptedMaps}. | ||
| * | ||
| * Deriving key material requires a canister round-trip and threshold | ||
| * cryptography, so it is cached and reused. The cached value is a | ||
| * non-extractable {@link !CryptoKey} handle: its raw bytes can never be read | ||
|
Copilot marked this conversation as resolved.
Outdated
|
||
| * back (`crypto.subtle.exportKey` throws), but the handle can still be *used* | ||
| * to decrypt. Where that handle lives therefore matters for security — see the | ||
| * provided implementations. | ||
| * | ||
| * Cache entries are keyed by an opaque string that {@link EncryptedMaps} scopes | ||
| * to the authenticated caller, the map owner, and the map name, so a key cached | ||
| * by one identity is never served to another. | ||
| */ | ||
| export interface DerivedKeyMaterialCache { | ||
| /** | ||
| * Returns the cached key handle for the given key, or `undefined` on a miss. | ||
| */ | ||
| get(key: string): Promise<CryptoKey | undefined>; | ||
|
|
||
| /** | ||
| * Stores a key handle under the given key. | ||
| */ | ||
| set(key: string, value: CryptoKey): Promise<void>; | ||
|
|
||
| /** | ||
| * Removes every cached key handle. | ||
| * | ||
| * Call this on logout or whenever the authenticated identity changes to | ||
| * avoid leaving usable decryption capability behind. | ||
| */ | ||
| clear(): Promise<void>; | ||
| } | ||
|
|
||
| /** | ||
| * Default {@link DerivedKeyMaterialCache} that keeps key handles in memory only. | ||
| * | ||
| * Nothing is written to disk, so the cache is discarded when the page is | ||
| * reloaded or the tab is closed and there is no at-rest exposure. The trade-off | ||
| * is one extra key derivation per map per page load. | ||
| */ | ||
| export class InMemoryDerivedKeyMaterialCache implements DerivedKeyMaterialCache { | ||
| readonly #entries = new Map<string, CryptoKey>(); | ||
|
|
||
| async get(key: string): Promise<CryptoKey | undefined> { | ||
|
Check failure on line 61 in frontend/ic_vetkeys/src/encrypted_maps/cache.ts
|
||
| return this.#entries.get(key); | ||
| } | ||
|
|
||
| async set(key: string, value: CryptoKey): Promise<void> { | ||
|
Check failure on line 65 in frontend/ic_vetkeys/src/encrypted_maps/cache.ts
|
||
| this.#entries.set(key, value); | ||
| } | ||
|
|
||
| async clear(): Promise<void> { | ||
|
Check failure on line 69 in frontend/ic_vetkeys/src/encrypted_maps/cache.ts
|
||
| this.#entries.clear(); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Opt-in {@link DerivedKeyMaterialCache} that persists key handles in IndexedDB. | ||
| * | ||
| * Key handles survive page reloads, avoiding repeated key derivation, but this | ||
| * is a deliberate security trade-off: the persisted handle is non-extractable | ||
| * (its raw bytes cannot be stolen), yet any same-origin code — e.g. via XSS, a | ||
| * malicious extension, or a shared browser profile — can read the handle and | ||
| * use it to decrypt the user's data without an authenticated session, for as | ||
| * long as it remains stored. | ||
| * | ||
| * Prefer {@link InMemoryDerivedKeyMaterialCache} (the default) unless you need | ||
| * cross-reload persistence and accept this exposure. When using this cache, be | ||
| * sure to call {@link EncryptedMaps.clearCache} on logout or identity change. | ||
| * | ||
| * Note that an unauthenticated agent resolves to the anonymous principal, so | ||
| * key material derived while anonymous is cached under a shared key and reused | ||
| * across anonymous sessions on the same origin — consistent with the canister's | ||
| * anonymous-access model. | ||
| * | ||
| * A dedicated IndexedDB store is used, so {@link clear} only removes entries | ||
| * written by this cache and never touches other application data. | ||
| */ | ||
| export class IndexedDbDerivedKeyMaterialCache implements DerivedKeyMaterialCache { | ||
| readonly #store: UseStore; | ||
|
|
||
| /** | ||
| * @param dbName - IndexedDB database name. Defaults to `"ic-vetkeys"`. | ||
| * @param storeName - Object store name. Defaults to `"derived-key-material"`. | ||
| */ | ||
| constructor(dbName = "ic-vetkeys", storeName = "derived-key-material") { | ||
| this.#store = createStore(dbName, storeName); | ||
| } | ||
|
|
||
| async get(key: string): Promise<CryptoKey | undefined> { | ||
| return idbGet<CryptoKey>(key, this.#store); | ||
| } | ||
|
|
||
| async set(key: string, value: CryptoKey): Promise<void> { | ||
| await idbSet(key, value, this.#store); | ||
| } | ||
|
|
||
| async clear(): Promise<void> { | ||
| await idbClear(this.#store); | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.