-
Notifications
You must be signed in to change notification settings - Fork 0
Add zip-free decrypt + re-wrap primitives for decomposed results #26
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
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
0e892f0
Add override-key reader + re-wrap primitives, preserve zip format
chrisbendel b2f9aac
Merge branch 'main' into researcher-keys
chrisbendel b0fbf05
Pin esbuild/vite/ws to patched versions for Trivy HIGH CVEs
chrisbendel b5b94eb
Add decryptFile test to satisfy Sonar new-code coverage gate
chrisbendel 0b6f71b
Switch file-body encryption from AES-CBC to AES-GCM
chrisbendel 8d4acdd
TEMP: print failing SonarQube quality-gate conditions
chrisbendel c4eaee8
TEMP: also print new-code issues from SonarQube
chrisbendel 7524e20
Mark reader overrideKeys readonly; remove temp Sonar diagnostics
chrisbendel 523e649
Revert "Switch file-body encryption from AES-CBC to AES-GCM"
chrisbendel eb2228d
Trim verbose doc comments on crypto/reader primitives
chrisbendel 4f31a89
Simplify researcher key access; document CBC; add negative tests
chrisbendel d721998
Address PR review: manifest-missing detection, path-keyed test
chrisbendel 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| import { describe, it, expect } from 'vitest' | ||
| import { readPublicKey, readPrivateKey } from '../testing' | ||
| import { fingerprintKeyData, pemToArrayBuffer, generateKeyPair } from '../util' | ||
| import { ResultsWriter } from './writer' | ||
| import { ResultsReader } from './reader' | ||
| import { unwrapAesKey, wrapAesKey, decryptFile } from './crypto' | ||
|
|
||
| const toArrayBuffer = (str: string): ArrayBuffer => { | ||
| const buf = Buffer.from(str, 'utf-8') | ||
| return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) | ||
| } | ||
|
|
||
| describe('wrapAesKey / unwrapAesKey', () => { | ||
| it('round-trips a raw AES key through an RSA keypair', async () => { | ||
| const publicKey = pemToArrayBuffer(readPublicKey()) | ||
| const privateKey = pemToArrayBuffer(readPrivateKey()) | ||
|
|
||
| const aesKey = await crypto.subtle.generateKey({ name: 'AES-CBC', length: 256 }, true, ['encrypt']) | ||
| const rawAesKey = await crypto.subtle.exportKey('raw', aesKey) | ||
|
|
||
| const crypt = await wrapAesKey(rawAesKey, publicKey) | ||
| const { rawAesKey: unwrapped } = await unwrapAesKey(crypt, privateKey) | ||
|
|
||
| expect(new Uint8Array(unwrapped)).toEqual(new Uint8Array(rawAesKey)) | ||
| }) | ||
| }) | ||
|
|
||
| describe('decryptFile', () => { | ||
| it('decrypts a standalone body + metadata and returns the raw AES key', async () => { | ||
| const publicKey = pemToArrayBuffer(readPublicKey()) | ||
| const privateKey = pemToArrayBuffer(readPrivateKey()) | ||
|
|
||
| // Encrypt a body with AES-CBC, then RSA-wrap the AES key. | ||
| const aesKey = await crypto.subtle.generateKey({ name: 'AES-CBC', length: 256 }, true, ['encrypt']) | ||
| const rawAesKey = await crypto.subtle.exportKey('raw', aesKey) | ||
| const iv = crypto.getRandomValues(new Uint8Array(16)) | ||
| const plaintext = toArrayBuffer('secret,data') | ||
| const body = await crypto.subtle.encrypt({ name: 'AES-CBC', iv }, aesKey, plaintext) | ||
| const crypt = await wrapAesKey(rawAesKey, publicKey) | ||
|
|
||
| const { contents, rawAesKey: recovered } = await decryptFile({ | ||
| body, | ||
| iv: Buffer.from(iv).toString('base64'), | ||
| crypt, | ||
| privateKey, | ||
| }) | ||
|
|
||
| expect(new TextDecoder().decode(contents)).toBe('secret,data') | ||
| expect(new Uint8Array(recovered)).toEqual(new Uint8Array(rawAesKey)) | ||
| }) | ||
| }) | ||
|
|
||
| describe('ResultsReader override keys (researcher re-wrap)', () => { | ||
| it('lets a researcher decrypt with a re-wrapped key absent from the manifest', async () => { | ||
| // Data owner encrypts results for their own key only. | ||
| const doPublic = pemToArrayBuffer(readPublicKey()) | ||
| const doFingerprint = await fingerprintKeyData(doPublic) | ||
| const doPrivate = pemToArrayBuffer(readPrivateKey()) | ||
|
|
||
| const writer = new ResultsWriter([{ publicKey: doPublic, fingerprint: doFingerprint }]) | ||
| await writer.addFile('result.csv', toArrayBuffer('secret,data')) | ||
| const zip = await writer.generate() | ||
|
|
||
| // Reviewer reads with their manifest key and recovers each file's raw AES key. | ||
| const reviewer = new ResultsReader(zip, doPrivate, doFingerprint) | ||
| const [entry] = await reviewer.extractFilesWithKeys() | ||
| expect(new TextDecoder().decode(entry.contents)).toBe('secret,data') | ||
| expect(entry.rawAesKey.byteLength).toBe(32) | ||
|
|
||
| // Researcher: brand-new keypair, NOT an original manifest recipient. | ||
| const researcher = await generateKeyPair() | ||
| const researcherFp = await fingerprintKeyData(researcher.exportedPublicKey) | ||
| const crypt = await wrapAesKey(entry.rawAesKey, researcher.exportedPublicKey) | ||
|
|
||
| // Same ciphertext + IV; only the wrapped key differs, supplied as an override. | ||
| const reader = new ResultsReader(zip, researcher.exportedPrivateKey, researcherFp, { | ||
| 'result.csv': crypt, | ||
| }) | ||
| const [out] = await reader.extractFiles() | ||
| expect(new TextDecoder().decode(out.contents)).toBe('secret,data') | ||
| }) | ||
|
|
||
| it('throws cleanly when an override is wrapped for a different keypair', async () => { | ||
| const doPublic = pemToArrayBuffer(readPublicKey()) | ||
| const doFingerprint = await fingerprintKeyData(doPublic) | ||
|
|
||
| const writer = new ResultsWriter([{ publicKey: doPublic, fingerprint: doFingerprint }]) | ||
| await writer.addFile('result.csv', toArrayBuffer('secret,data')) | ||
| const zip = await writer.generate() | ||
|
|
||
| const reviewer = new ResultsReader(zip, pemToArrayBuffer(readPrivateKey()), doFingerprint) | ||
| const [entry] = await reviewer.extractFilesWithKeys() | ||
|
|
||
| // Wrap the raw key for researcher A, but hand the reader researcher B's private key. | ||
| const researcherA = await generateKeyPair() | ||
| const researcherB = await generateKeyPair() | ||
| const crypt = await wrapAesKey(entry.rawAesKey, researcherA.exportedPublicKey) | ||
|
|
||
| const reader = new ResultsReader(zip, researcherB.exportedPrivateKey, researcherB.fingerprint, { | ||
| 'result.csv': crypt, | ||
| }) | ||
| // RSA-OAEP unwrap fails on the mismatched key — deterministic throw, never garbage plaintext. | ||
| await expect(reader.extractFiles()).rejects.toThrow() | ||
| }) | ||
|
|
||
| it('throws when a manifest file has neither a fingerprint match nor an override', async () => { | ||
| const doPublic = pemToArrayBuffer(readPublicKey()) | ||
| const doFingerprint = await fingerprintKeyData(doPublic) | ||
|
|
||
| const writer = new ResultsWriter([{ publicKey: doPublic, fingerprint: doFingerprint }]) | ||
| await writer.addFile('a.csv', toArrayBuffer('alpha')) | ||
| await writer.addFile('b.csv', toArrayBuffer('beta')) | ||
| const zip = await writer.generate() | ||
|
|
||
| const researcher = await generateKeyPair() | ||
| // Override supplied for a.csv only; b.csv has no key for this researcher. | ||
| const decrypted = await new ResultsReader( | ||
| zip, | ||
| pemToArrayBuffer(readPrivateKey()), | ||
| doFingerprint, | ||
| ).extractFilesWithKeys() | ||
| const aEntry = decrypted.find((e) => e.path === 'a.csv')! | ||
| const crypt = await wrapAesKey(aEntry.rawAesKey, researcher.exportedPublicKey) | ||
|
|
||
| const reader = new ResultsReader(zip, researcher.exportedPrivateKey, researcher.fingerprint, { | ||
| 'a.csv': crypt, | ||
| }) | ||
| await expect(reader.extractFiles()).rejects.toThrow(/key signature/) | ||
| }) | ||
|
|
||
| it('still reads with the manifest fingerprint when no override is supplied', async () => { | ||
| const publicKey = pemToArrayBuffer(readPublicKey()) | ||
| const fingerprint = await fingerprintKeyData(publicKey) | ||
| const privateKey = pemToArrayBuffer(readPrivateKey()) | ||
|
|
||
| const writer = new ResultsWriter([{ publicKey, fingerprint }]) | ||
| await writer.addFile('a.txt', toArrayBuffer('alpha')) | ||
| const zip = await writer.generate() | ||
|
|
||
| const reader = new ResultsReader(zip, privateKey, fingerprint) | ||
| const [out] = await reader.extractFiles() | ||
| expect(new TextDecoder().decode(out.contents)).toBe('alpha') | ||
| }) | ||
| }) |
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,65 @@ | ||
| import { privateKeyFromBuffer } from '../util' | ||
| import logger from '../lib/logger' | ||
|
|
||
| /** | ||
| * Unwrap a file's RSA-encrypted AES key. Returns the AES `CryptoKey` plus its raw | ||
| * bytes — re-wrap needs the bytes to grant other recipients access (see {@link wrapAesKey}). | ||
| */ | ||
| export async function unwrapAesKey( | ||
| crypt: string, | ||
| privateKey: ArrayBuffer, | ||
| ): Promise<{ aesKey: CryptoKey; rawAesKey: ArrayBuffer }> { | ||
| const encryptedKey = Buffer.from(crypt, 'base64') | ||
|
|
||
| const rawAesKey = await crypto.subtle.decrypt( | ||
| { name: 'RSA-OAEP' }, | ||
| await privateKeyFromBuffer(privateKey), | ||
| encryptedKey, | ||
| ) | ||
|
|
||
| const aesKey = await crypto.subtle.importKey('raw', rawAesKey, { name: 'AES-CBC' }, false, ['decrypt']) | ||
|
|
||
| return { aesKey, rawAesKey } | ||
| } | ||
|
|
||
| /** Re-wrap a raw AES key for a recipient's RSA public key. Body and IV are untouched. */ | ||
| export async function wrapAesKey(rawAesKey: ArrayBuffer, publicKey: ArrayBuffer): Promise<string> { | ||
| const key = await crypto.subtle.importKey('spki', publicKey, { name: 'RSA-OAEP', hash: 'SHA-256' }, false, [ | ||
| 'encrypt', | ||
| ]) | ||
|
|
||
| const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, key, rawAesKey) | ||
|
|
||
| return Buffer.from(encryptedKey).toString('base64') | ||
| } | ||
|
|
||
| // AES-CBC kept for backward-compat with existing production results (see writer.addFile). | ||
| // CBC is unauthenticated: a wrong-but-valid key usually trips PKCS#7 padding and throws, but not | ||
| // guaranteed (~1/256 yields garbage, no error), and tampered ciphertext is not detected. | ||
| export async function decryptFileBody(body: ArrayBuffer, iv: BufferSource, aesKey: CryptoKey): Promise<ArrayBuffer> { | ||
| return crypto.subtle.decrypt({ name: 'AES-CBC', iv }, aesKey, body) | ||
| } | ||
|
|
||
| /** | ||
| * Decrypt a standalone file body + metadata (vs {@link ResultsReader}'s zip iteration). | ||
| * Returns the raw AES key too, so the caller can re-wrap without decrypting again. | ||
| */ | ||
| export async function decryptFile({ | ||
| body, | ||
| iv, | ||
| crypt, | ||
| privateKey, | ||
| }: { | ||
| body: ArrayBuffer | ||
| iv: string | ||
| crypt: string | ||
| privateKey: ArrayBuffer | ||
| }): Promise<{ contents: ArrayBuffer; rawAesKey: ArrayBuffer }> { | ||
| logger.info(`Decrypting file`) | ||
|
|
||
| const { aesKey, rawAesKey } = await unwrapAesKey(crypt, privateKey) | ||
| const contents = await decryptFileBody(body, Buffer.from(iv, 'base64'), aesKey) | ||
|
|
||
| logger.info(`Finished decrypting file`) | ||
| return { contents, rawAesKey } | ||
| } |
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 |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| export * from './reader' | ||
| export * from './writer' | ||
| export * from './crypto' | ||
| export type { FileInfo } from './types' | ||
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.