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 22, 2024
1 parent dff5de7 commit 81776df
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
6 changes: 3 additions & 3 deletions packages/snaps-controllers/coverage.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"branches": 92.67,
"branches": 92.73,
"functions": 96.65,
"lines": 97.98,
"statements": 97.68
"lines": 97.99,
"statements": 97.69
}
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 @@ -1747,6 +1747,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 @@ -1761,7 +1772,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 81776df

Please sign in to comment.