Skip to content

Commit

Permalink
Short-circuit when cached encryption key already exists
Browse files Browse the repository at this point in the history
  • Loading branch information
FrederikBolding committed Oct 18, 2024
1 parent 54df384 commit 1adf53c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/snaps-controllers/coverage.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"branches": 92.63,
"branches": 92.69,
"functions": 96.65,
"lines": 97.97,
"statements": 97.67
Expand Down
17 changes: 16 additions & 1 deletion packages/snaps-controllers/src/snaps/SnapController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1734,6 +1734,17 @@ export class SnapController extends BaseController<
return { key: encryptionKey, salt };
}

/**
* Check if a given Snap has a cached encryption key stored in the runtime.
*
* @param snapId - The Snap ID.
* @returns True if the Snap has a cached encryption key, otherwise false.
*/
#hasCachedEncryptionKey(snapId: SnapId) {
const runtime = this.#getRuntimeExpect(snapId);
return runtime.encryptionKey !== null && runtime.encryptionSalt !== null;
}

/**
* Decrypt the encrypted state for a given Snap.
*
Expand All @@ -1748,7 +1759,11 @@ export class SnapController extends BaseController<
// This lets us skip JSON validation.
const parsed = JSON.parse(state) as EncryptionResult;
const { salt, keyMetadata } = parsed;
const useCache = this.#encryptor.isVaultUpdated(state);

// We only cache encryption keys if they are already cached or if the encryption key is using the latest key derivation params.
const useCache =
this.#hasCachedEncryptionKey(snapId) ||
this.#encryptor.isVaultUpdated(state);
const { key } = await this.#getSnapEncryptionKey({
snapId,
salt,
Expand Down

0 comments on commit 1adf53c

Please sign in to comment.