Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
26 changes: 26 additions & 0 deletions frontend/ic_vetkeys/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,32 @@
- `DerivedKeyMaterial` encryption uses a different format for encryption now.
Decryption of old messages is supported, however older versions of this library
will not be able to read messages encrypted by this or newer versions.
- `EncryptedMaps` now accepts an optional `{ cache }` option to control how
derived key material is cached. New exports `DerivedKeyMaterialCache`,
`InMemoryDerivedKeyMaterialCache`, and `IndexedDbDerivedKeyMaterialCache` from
`@icp-sdk/vetkeys/encrypted_maps`.
- `EncryptedMaps.clearCache()` to drop cached derived key material. Strongly
recommended on logout or identity change to drop usable decryption capability
— especially with `IndexedDbDerivedKeyMaterialCache`, where it persists across
sessions otherwise. Not required for correctness, since cached keys are scoped
to the caller.

### Security

- **BREAKING** `EncryptedMaps` no longer persists derived key material to
IndexedDB by default; it now caches in memory only
(`InMemoryDerivedKeyMaterialCache`), so secret-bearing key handles are
discarded on page reload instead of remaining usable at rest indefinitely.
Opt back into persistence with
`new EncryptedMaps(client, { cache: new IndexedDbDerivedKeyMaterialCache() })`,
accepting that a persisted handle can be used by any same-origin code to
decrypt without an authenticated session. The one-time cost of the default is
an extra key derivation per map per page load.
Comment thread
marc0olo marked this conversation as resolved.
- Cached derived key material is now scoped to the authenticated caller's
principal. Previously the cache key was only `[mapOwner, mapName]`, so after an
identity switch on the same origin a different principal could receive key
material cached by a prior one. `EncryptedMapsClient` gains a
`getCallerPrincipal()` method to support this; custom implementations must add it.

### Changed

Expand Down
2 changes: 1 addition & 1 deletion frontend/ic_vetkeys/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"module": "dist/lib/index.es.js",
"typings": "dist/types/index.d.ts",
"dependencies": {
"@icp-sdk/core": "^5.2.1",
"@icp-sdk/core": "^5.4.0",
"idb-keyval": "^6.2.1"
},
"devDependencies": {
Expand Down
183 changes: 183 additions & 0 deletions frontend/ic_vetkeys/src/encrypted_maps/cache.test.ts
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

View workflow job for this annotation

GitHub Actions / frontend_ic_vetkeys_linux

Async arrow function has no 'await' expression

Check failure on line 38 in frontend/ic_vetkeys/src/encrypted_maps/cache.test.ts

View workflow job for this annotation

GitHub Actions / frontend_ic_vetkeys_mac

Async arrow function has no 'await' expression
} 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

View workflow job for this annotation

GitHub Actions / frontend_ic_vetkeys_linux

This assertion is unnecessary since it does not change the type of the expression

Check failure on line 76 in frontend/ic_vetkeys/src/encrypted_maps/cache.test.ts

View workflow job for this annotation

GitHub Actions / frontend_ic_vetkeys_mac

This assertion is unnecessary since it does not change the type of the expression
).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);
});
});
118 changes: 118 additions & 0 deletions frontend/ic_vetkeys/src/encrypted_maps/cache.ts
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
Comment thread
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

View workflow job for this annotation

GitHub Actions / frontend_ic_vetkeys_linux

Async method 'get' has no 'await' expression

Check failure on line 61 in frontend/ic_vetkeys/src/encrypted_maps/cache.ts

View workflow job for this annotation

GitHub Actions / frontend_ic_vetkeys_mac

Async method 'get' has no 'await' expression
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

View workflow job for this annotation

GitHub Actions / frontend_ic_vetkeys_linux

Async method 'set' has no 'await' expression

Check failure on line 65 in frontend/ic_vetkeys/src/encrypted_maps/cache.ts

View workflow job for this annotation

GitHub Actions / frontend_ic_vetkeys_mac

Async method 'set' has no 'await' expression
this.#entries.set(key, value);
}

async clear(): Promise<void> {

Check failure on line 69 in frontend/ic_vetkeys/src/encrypted_maps/cache.ts

View workflow job for this annotation

GitHub Actions / frontend_ic_vetkeys_linux

Async method 'clear' has no 'await' expression

Check failure on line 69 in frontend/ic_vetkeys/src/encrypted_maps/cache.ts

View workflow job for this annotation

GitHub Actions / frontend_ic_vetkeys_mac

Async method 'clear' has no 'await' expression
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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,20 @@ import { EncryptedMapsClient } from "./index";

export class DefaultEncryptedMapsClient implements EncryptedMapsClient {
actor: ActorSubclass<_DEFAULT_ENCRYPTED_MAPS_SERVICE>;
#agent: HttpAgent;

constructor(agent: HttpAgent, canisterId: string) {
this.#agent = agent;
this.actor = Actor.createActor(idlFactory, {
agent,
canisterId,
});
}

getCallerPrincipal(): Promise<Principal> {
return this.#agent.getPrincipal();
}

get_accessible_shared_map_names(): Promise<[Principal, ByteBuf][]> {
return this.actor.get_accessible_shared_map_names();
}
Expand Down
Loading
Loading