-
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
Open
marc0olo
wants to merge
6
commits into
main
Choose a base branch
from
fix/encrypted-maps-key-cache-hardening
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
3aa4815
fix(encrypted_maps): harden derived key material caching
marc0olo 6bd734f
fix(encrypted_maps): satisfy eslint require-await and no-unnecessary-…
marc0olo 6c19d2a
docs(encrypted_maps): add upgrade note for legacy IndexedDB key material
marc0olo c695787
refactor(encrypted_maps): address review feedback on naming and docs
marc0olo 9b3c89f
refactor(encrypted_maps): scope key cache by instance/namespace, not …
marc0olo 2084194
docs(encrypted_maps): fix nested backticks in IndexedDb cache JSDoc
marc0olo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(() => Promise.resolve(caller)), | ||
| } 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"); | ||
| if (!restored) throw new Error("expected a cached key handle"); | ||
| expect(restored.extractable).toBe(false); | ||
| // The raw bytes must remain unrecoverable even after persistence. | ||
| await expect( | ||
| crypto.subtle.exportKey("raw", restored), | ||
| ).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); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| /** | ||
| * @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>(); | ||
|
|
||
| get(key: string): Promise<CryptoKey | undefined> { | ||
| return Promise.resolve(this.#entries.get(key)); | ||
| } | ||
|
|
||
| set(key: string, value: CryptoKey): Promise<void> { | ||
| this.#entries.set(key, value); | ||
| return Promise.resolve(); | ||
| } | ||
|
|
||
| clear(): Promise<void> { | ||
| this.#entries.clear(); | ||
| return Promise.resolve(); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * 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); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.