diff --git a/packages/filecoin-encryption-envelope/README.md b/packages/filecoin-encryption-envelope/README.md index 0053a2188..6265eb38e 100644 --- a/packages/filecoin-encryption-envelope/README.md +++ b/packages/filecoin-encryption-envelope/README.md @@ -68,6 +68,17 @@ commits to that length in the protected header and fails the stream if the source supplies a different number of bytes. Omit it when the length cannot be guaranteed. +When decrypting an object that declares `plaintext_length`, receiving fewer +ciphertext bytes than declared fails with `errors.TruncatedCiphertextError` +and receiving more fails with `errors.ExcessCiphertextError` (both extend +`errors.InvalidCiphertextLengthError`). Because the header is unauthenticated +until a chunk tag verifies, these errors report a mismatch with the declared +length rather than proof of a transport failure or which side was altered. In +streaming decryption `TruncatedCiphertextError` means the input stream ended +early; in range decryption (`decryptRange` / `decryptRangeWith`) it means the +reported `source.size` itself is shorter than declared (a short stored object +rather than a transient read cutoff). + For a browser `File` and a file handle supplied by the application: ```ts @@ -127,10 +138,11 @@ response before handing it over. function httpSource(versionedUrl: string, size: number): fee.RandomAccessSource { return { size, - async openRange(offset, length) { + async openRange(offset, length, signal) { const end = offset + length - 1 const response = await fetch(versionedUrl, { headers: { Range: `bytes=${offset}-${end}` }, + signal, }) if ( response.status !== 206 || @@ -146,14 +158,17 @@ function httpSource(versionedUrl: string, size: number): fee.RandomAccessSource } const source = httpSource(versionedUrl, exactEncodedLength) -const info = await fee.parse(source) +// Optional cancellation signal, e.g. from an incoming request or AbortSignal.timeout(...) +const controller = new AbortController() +const { signal } = controller +const info = await fee.parse(source, { signal }) if (info.scheme !== 'chunked') throw new Error('Range reads require a chunked object') const result = await fee.decryptRange( source, cek, { offset: 100_000, length: 50_000 }, - { params: info.params } + { params: info.params, signal } ) await result.stream.pipeTo(rangeSink) ``` @@ -171,40 +186,99 @@ validate any scope or identifier before using it for a key lookup. ```ts // allowedScope and keyStore are supplied by your application. -const resolver: fee.KeyResolver = async (info) => { +const resolver: fee.KeyResolver = async (info, signal) => { const scope = info.appMetadata?.scope const salt = info.appMetadata?.salt if (scope !== allowedScope || typeof salt !== 'string' || !/^[0-9a-f]{32}$/.test(salt)) { throw new Error('Envelope metadata is not allowed for this key lookup') } // keyStore is your application or key-management library. - return keyStore.deriveCek({ scope, salt }) + const cek = await keyStore.deriveCek({ scope, salt, signal }) + if (signal.aborted) { + cek.fill(0) + throw signal.reason + } + return cek } await encryptedSource.pipeThrough(fee.decrypt(resolver)).pipeTo(plaintextSink) ``` The resolver runs at most once, before any chunk is decrypted. Its checks control -which key may be requested; they do not authenticate the metadata. For a range -read, call `parse(source)`, validate its metadata, derive the CEK, then pass -that key and `info.params` to `decryptRange()`. +which key may be requested; they do not authenticate the metadata. The `signal` +argument aborts if the stream is cancelled, aborted (including via +`options.signal`), or fails, and does not abort on successful completion. + +The library borrows the returned key bytes only long enough to import them into +a non-extractable `CryptoKey` and never zeroes the caller's buffer. Your +application owns every key it returns — including one the library discards +after cancellation (when `signal.aborted` becomes `true` before import and the +library skips validation and import) — and should zero it once the stream +settles. + +For a range read, call `parse(source)`, validate its metadata, derive the CEK, +then pass that key and `info.params` to `decryptRange()`. ## Security and limits - CEKs and A256KW KEKs must be 32-byte `Uint8Array` values and cannot be all zero. The library validates their shape but cannot tell whether they are secret, unpredictable, or fresh. -- Streaming options, including keys and metadata, are borrowed until the stream - closes or errors. Do not modify or clear them while it is running. A plaintext - block may be reused once its `write()` resolves. For a range read, the CEK is - borrowed until the `decryptRange()` promise settles, and the source until the - result stream closes or errors. +- Streaming options, including keys and metadata, may be read lazily (as late as + the stream's first read), so they stay borrowed until the stream closes or + errors. When imported, raw key bytes are imported into a `CryptoKey` + (non-extractable unless recipient wrapping requires extractability) and the + library never zeroes caller-owned buffers; do not modify or clear them while + the stream is running, and zero them once the stream settles if desired. A + plaintext block may be reused once its `write()` resolves. For a range read, + the CEK is borrowed until the `decryptRange()` promise settles, and the source + until the result stream closes or errors. +- When passing `options.signal` to `decrypt()`, `decryptWith()`, + `decryptRange()`, or `decryptRangeWith()`, the listener on `signal` retains + the stream (and, for range reads, its `source`) until the stream settles or + `signal` aborts so pending reads and `writer.closed` remain abortable. When + reusing a long-lived `AbortSignal`, consume or explicitly cancel unused + streams (or use an operation-scoped signal). - Application metadata is visible without a key. Its values are authenticated only after a content tag verifies. Content tags do not authenticate the recipient list or establish sender identity. - A failed stream may already have emitted bytes. Discard them all. Successful decryption of an entire object requires reading through the final chunk. -The chunked scheme permits an encoded object of at most 64 GiB. Scheme 1 -permits at most 64 MiB of plaintext. For the wire profile, range rules, and -other limits, see the [implementation guide](https://github.com/FilOzone/synapse-sdk/blob/master/packages/filecoin-encryption-envelope/docs/implementation-guide.md). +The chunked scheme permits an encoded object of at most 64 GiB +(`fee.constants.MAX_ENCODED_OBJECT_SIZE`), covering both the COSE envelope and +the detached ciphertext. Scheme 1 permits at most 64 MiB of plaintext +(`fee.constants.MAX_AES_GCM_PLAINTEXT_SIZE`). + +To preflight-check whether a plaintext length fits before reading or encrypting, +call `ciphertextLengthForPlaintext(plaintextLength, chunkSize)`. It returns the +detached ciphertext length in bytes — including one 16-byte +(`fee.constants.TAG_SIZE`) authentication tag per chunk, and one tag even for +empty input (`0`) — and throws `InvalidPlaintextLengthError` if the detached +ciphertext alone exceeds `MAX_ENCODED_OBJECT_SIZE` or `ChunkCountExceededError` +if the chunk count exceeds the 32-bit chunk-index limit. For a full-object +check, add the actual encoded envelope length, or +`fee.constants.MAX_ENVELOPE_SIZE` (1 MiB) as a conservative upper bound when +the envelope length is not known yet: + +```ts +function fitsChunkedLimit( + plaintextLength: number, + chunkSize = fee.constants.DEFAULT_CHUNK_SIZE +): boolean { + try { + const ciphertextLength = fee.ciphertextLengthForPlaintext(plaintextLength, chunkSize) + return ciphertextLength + fee.constants.MAX_ENVELOPE_SIZE <= fee.constants.MAX_ENCODED_OBJECT_SIZE + } catch (error) { + if ( + error instanceof fee.errors.InvalidPlaintextLengthError || + error instanceof fee.errors.ChunkCountExceededError + ) { + return false + } + throw error + } +} +``` + +For the wire profile, range rules, and other limits, see the [implementation guide](https://github.com/FilOzone/synapse-sdk/blob/master/packages/filecoin-encryption-envelope/docs/implementation-guide.md). diff --git a/packages/filecoin-encryption-envelope/docs/implementation-guide.md b/packages/filecoin-encryption-envelope/docs/implementation-guide.md index 06829bf38..34eeb0558 100644 --- a/packages/filecoin-encryption-envelope/docs/implementation-guide.md +++ b/packages/filecoin-encryption-envelope/docs/implementation-guide.md @@ -330,7 +330,13 @@ transfer; omit it when unsure and the object is valid, just without the commitme When the field is present, recompute `N` and `C` from `P` and compare `C` against the observed detached ciphertext length for the same object version. Reject a negative, non-integer or unsafe `P`, a derived count outside the format range of 1 … 2³² − 1, an unsafe derived length -or offset, and any mismatch. The mapping is unambiguous: +or offset, and any mismatch. A shorter ciphertext than `C` raises `TruncatedCiphertextError` and a +longer one raises `ExcessCiphertextError` (both subclasses of `InvalidCiphertextLengthError`); as +`P` is unauthenticated until a chunk tag verifies, these report a mismatch with the declared length +rather than proof of a transport failure. In streaming decryption `TruncatedCiphertextError` means +the input stream ended early; in range planning (`planRange` / `decryptRange`) it means the reported +`source.size` itself is shorter than declared (a short stored object rather than a transient read +cutoff). The mapping is unambiguous: `P + 16 × max(1, ceil(P / S))` is strictly increasing in `P`, so one ciphertext length admits exactly one valid `P`. @@ -409,7 +415,8 @@ namespace recipients { } type Unwrapper = ( - recipients: readonly RecipientInfo[] + recipients: readonly RecipientInfo[], + signal?: AbortSignal ) => Promise interface A256KWKey { @@ -443,16 +450,32 @@ interface ChunkedEncryptOptions { // ── chunked decryption, exported at the root as fee.decrypt / fee.decryptWith // Use as encrypted.pipeThrough(fee.decrypt(cek)). -function decrypt(key: Uint8Array | KeyResolver): ReadableWritablePair -function decryptWith(unwrapper: recipients.Unwrapper): ReadableWritablePair +interface DecryptOptions { + signal?: AbortSignal +} + +function decrypt( + key: Uint8Array | KeyResolver, + options?: DecryptOptions +): ReadableWritablePair +function decryptWith( + unwrapper: recipients.Unwrapper, + options?: DecryptOptions +): ReadableWritablePair // Derives or fetches the CEK from the decoded envelope, e.g. from a salt and // scope in appMetadata. Called at most once, after the envelope decodes and -// before any chunk is decrypted, with the same EnvelopeInfo parse() returns. -// That info is unauthenticated: check it (an allowed scope, say) before -// fetching a key. A returned key is borrowed until the stream settles. A -// resolver failure becomes KeyResolutionError; an invalid key, InvalidKeyError. -type KeyResolver = (info: EnvelopeInfo) => Promise | Uint8Array +// before any chunk is decrypted, with the same EnvelopeInfo parse() returns +// and an AbortSignal that aborts if the stream is cancelled, aborted (including +// via options.signal), or fails (never on successful EOF). That info is +// unauthenticated: check it (an allowed scope, say) before fetching a key. FEE +// borrows the returned bytes only long enough to import them into a +// non-extractable CryptoKey and never zeroes the caller's buffer; the caller +// owns every key it returns — including one FEE discards after cancellation — +// and should zero it once the stream settles. +// A resolver failure becomes KeyResolutionError unless the signal aborted; an +// invalid key, InvalidKeyError. +type KeyResolver = (info: EnvelopeInfo, signal: AbortSignal) => Promise | Uint8Array // ── whole-object AES-GCM (scheme 1), exported as fee.aesGcm ───────────────── namespace aesGcm { @@ -473,7 +496,11 @@ namespace aesGcm { } // ── inspection, no key required, exported at the root as fee.parse ────────── -function parse(source: Uint8Array | RandomAccessSource): Promise +interface ParseOptions { + signal?: AbortSignal +} + +function parse(source: Uint8Array | RandomAccessSource, options?: ParseOptions): Promise interface EnvelopeInfoBase { contentType?: string | number // tstr / uint; a number must be a non-negative safe integer @@ -488,11 +515,16 @@ type EnvelopeInfo = | (EnvelopeInfoBase & { scheme: 'chunked'; params: ChunkedEnvelopeParams }) // ── range decryption, exported at the root ────────────────────────────────── +interface RangeDecryptOptions { + params?: ChunkedEnvelopeParams + signal?: AbortSignal +} + function decryptRange( source: RandomAccessSource | Uint8Array, cek: Uint8Array, range: ByteRange, - options?: { params?: ChunkedEnvelopeParams } + options?: RangeDecryptOptions ): Promise // Same, recovering the CEK through an unwrapper (tag 96 only), like decryptWith. @@ -500,7 +532,7 @@ function decryptRangeWith( source: RandomAccessSource | Uint8Array, unwrapper: recipients.Unwrapper, range: ByteRange, - options?: { params?: ChunkedEnvelopeParams } + options?: RangeDecryptOptions ): Promise interface ByteRange { @@ -528,7 +560,7 @@ interface RandomAccessSource { readonly size: number /** Open the half-open byte range [offset, offset + length). */ - openRange(offset: number, length: number): Promise> + openRange(offset: number, length: number, signal?: AbortSignal): Promise> } // ── cached chunked-envelope parameters ────────────────────────────────────── @@ -581,8 +613,10 @@ the unwrapper; it is not an unsupported content scheme. Operations borrow caller inputs while they may still read them. Callers MUST NOT modify plaintext, encoded bytes, keys, recipient objects, or metadata until the returned promise settles. The library -does not modify caller-owned inputs or retain key bytes after the operation settles; callers may -clear their keys afterward. Values retained +does not modify or zero caller-owned inputs and does not retain key bytes after the operation +settles; raw keys are borrowed only long enough to import them into a non-extractable `CryptoKey` +(unless recipient wrapping requires extractability), and callers own the buffers and may zero them +afterward. Values retained beyond a call or passed to an unwrapper are copied where needed. Byte inputs passed to Web Crypto MUST be backed by an ordinary `ArrayBuffer`; a `SharedArrayBuffer`-backed view is rejected with the relevant input error. @@ -590,10 +624,22 @@ relevant input error. Streaming operations follow the same rule, with the stream in place of the promise: option buffers (CEK, recipient KEKs and kids, metadata) stay borrowed until the returned stream closes or errors, and may be read as late as its first read. A source block may be reused once its `write()` resolves. A key -returned by a `KeyResolver` is borrowed the same way as a directly passed one. +returned by a `KeyResolver` or custom `Unwrapper` is caller-owned and borrowed the same way as a +directly passed one: the library borrows the bytes only long enough to import them into a +non-extractable `CryptoKey`, never zeroes the buffer, and skips validation and import if the stream +or signal aborted before recovery settled. The caller owns every key it returns — including one the +library discards after cancellation — and should zero it once the operation settles. When the +built-in unwrapper from `recipients.createA256KWUnwrapper` +is passed directly to `decryptWith`, `decryptRangeWith`, or `aesGcm.decryptWith`, the library zeroes +its own temporary unwrapped key buffer after importing it (and on any abort or validation discard +path), and skips raw export if aborted before export. Range reads split the two: the CEK is borrowed until the `decryptRange` promise settles, since the key is imported before it resolves, and the source is borrowed until the result stream closes or errors. +When `options.signal` is supplied to `decrypt`, `decryptWith`, `decryptRange`, or `decryptRangeWith`, +its abort listener retains the stream (and, for range reads, its `source`) until the stream settles +or `signal` aborts; callers sharing a long-lived `AbortSignal` should consume or explicitly cancel +unused streams (or use an operation-scoped signal). ### Random-access source contract @@ -621,8 +667,14 @@ A response with extra bytes after the requested length is rejected before the la is released. Errors from the source's own stream propagate unchanged, and a failure while reading an opened range cancels that stream. An `openRange` that fails before returning a stream has nothing to cancel. Cancelling a range read never waits on a pending `openRange`; a stream that arrives -after cancellation is cancelled too. Stopping a hung open itself is left to the adapter, for example -with a fetch timeout. +after cancellation is cancelled too. When `options.signal` is passed to `parse`, `decryptRange`, or +`decryptRangeWith`, that signal is forwarded to `openRange` during envelope setup (omitted when +none is provided) and to any `Unwrapper`, aborts setup or errors an active result stream with the +exact `signal.reason`, cancels active or late-arriving source streams, and discards late key results +without importing them. For ciphertext spans opened by `RangeResult.stream`, the stream always passes +its own stream-scoped `AbortSignal` to `openRange`, which mirrors `options.signal` when supplied and +also aborts if the result stream is cancelled or fails. Adapters that ignore the third `signal` +argument remain supported; stopping a hung transport request itself is still up to the adapter. The source contract provides consistent layout input; it does not authenticate the source. The library still treats `size` and returned bytes as untrusted, validates all derived offsets, and diff --git a/packages/filecoin-encryption-envelope/src/aes-gcm-stream.ts b/packages/filecoin-encryption-envelope/src/aes-gcm-stream.ts index fea357556..702a10152 100644 --- a/packages/filecoin-encryption-envelope/src/aes-gcm-stream.ts +++ b/packages/filecoin-encryption-envelope/src/aes-gcm-stream.ts @@ -26,18 +26,21 @@ import { createEnvelopeScanner } from './cose/envelope-scanner.ts' import type { AppMetadata } from './cose/headers.ts' import { describeCborType, encodeProtectedHeader } from './cose/headers.ts' import { + ExcessCiphertextError, InvalidCiphertextLengthError, KeyResolutionError, MalformedEnvelopeError, + TruncatedCiphertextError, UnsupportedSchemeError, } from './errors.ts' +import { assertOptionalAbortSignal, onAbort } from './internal/abort.ts' import { type ChunkFramer, createChunkFramer } from './internal/chunk-framer.ts' import { assertAes256Key, assertArrayBufferBacked } from './internal/keys.ts' import { aesGcmDecrypt, aesGcmEncrypt, importAesGcmKey, randomBytes } from './internal/web-crypto.ts' import { deriveChunkNonce } from './nonce.ts' import { type EnvelopeInfo, toEnvelopeInfo } from './range/inspect.ts' import { createRecipientRecords, prepareRecipientInputs } from './recipients/prepare.ts' -import { recoverCek } from './recipients/recover.ts' +import { recoverCekKey } from './recipients/recover.ts' import type { Recipient, Unwrapper } from './recipients/types.ts' /** Options for one chunked AES-256-GCM STREAM encryption using a direct CEK. */ @@ -219,6 +222,34 @@ function assertValidEncodedBlock(value: unknown): asserts value is Uint8Array new MalformedEnvelopeError(message)) } +/** Options for {@link decrypt} and {@link decryptWith}. */ +export interface DecryptOptions { + /** + * Optional cancellation signal. Aborting it errors both sides of the + * returned pair with the exact `signal.reason`, unblocking pending writes + * and reads, and aborts the `AbortSignal` passed to a `KeyResolver` or + * `Unwrapper`. + * + * While the stream is unsettled, the listener on `signal` keeps the stream + * reachable so pending reads and `writer.closed` remain abortable. When + * reusing a long-lived signal, consume or explicitly cancel/abort unused + * streams (or use an operation-scoped signal). + */ + signal?: AbortSignal +} + +function readDecryptOptions(options: DecryptOptions | undefined): AbortSignal | undefined { + if (options === undefined) return undefined + if (options === null || typeof options !== 'object' || Array.isArray(options)) { + throw new MalformedEnvelopeError( + `Invalid decryption options: expected an object, got ${describeCborType(options)}.` + ) + } + const { signal } = options + assertOptionalAbortSignal(signal) + return signal +} + /** * Create a streaming decryption pipeline for an encoded FEE object. * @@ -228,16 +259,23 @@ function assertValidEncodedBlock(value: unknown): asserts value is Uint8Array Promise + getCekKey: (decoded: DecodedEnvelope, resolverSignal: AbortSignal) => Promise, + signal?: AbortSignal ): ReadableWritablePair { const scanner = createEnvelopeScanner() + const resolverAbortController = new AbortController() let receivedTotal = 0 // Only known once the envelope completes and declares plaintext_length. - let expectedTotal: number | undefined + let expectedLength: { total: number; plaintext: number; ciphertext: number; envelope: number } | undefined // Set once the envelope completes: the framer for the ciphertext after it. let input: { framer: ChunkFramer; writer: WritableStreamDefaultWriter } | undefined let outerController: WritableStreamDefaultController | undefined + let readableController: ReadableStreamDefaultController | undefined + + let failed = false + let failReason: unknown + let readableErrored = false let resolveHandoff: ((opened: OpenedEnvelope) => void) | undefined let rejectHandoff: ((reason: unknown) => void) | undefined @@ -260,34 +298,75 @@ function createDecryptStream( // Only raced against key recovery; an unread stream must not surface this. }) + let cleanupAbort: (() => void) | undefined + + function cleanupSignal(): void { + cleanupAbort?.() + cleanupAbort = undefined + } + + function abortResolverSignal(reason: unknown): void { + if (!resolverAbortController.signal.aborted) { + resolverAbortController.abort(reason) + } + } + + function errorReadable(reason: unknown): void { + if (!readableErrored) { + readableErrored = true + readableController?.error(reason) + } + } + /** - * Used when the writable side is already failing on its own (the abort - * signal, or a write()/close() throw, which auto-errors the stream it - * throws from) -- must NOT also call `outerController.error()` here, or - * it reenters that same stream's own abort machinery mid-abort. + * Commit the first failure reason and cancel internal state before any + * external abort listeners (which may call back into the streams) run. */ - function failInput(reason: unknown): void { + function failInputState(reason: unknown): void { + if (!failed) { + failed = true + failReason = reason + } + cleanupSignal() if (!handoffSettled) { handoffSettled = true - rejectHandoff?.(reason) + rejectHandoff?.(failReason) } - rejectFailure?.(reason) - input?.framer.cancel(reason) + rejectFailure?.(failReason) + input?.framer.cancel(failReason) + } + + /** + * Used when the writable side is already transitioning via native abort + * (`controller.signal`) -- must NOT call `outerController.error()` here, or + * it reenters that same stream's own abort machinery mid-abort. Still errors + * the readable BEFORE notifying the resolver signal so re-entrant cleanup + * calling `reader.cancel()` cannot turn a failed read into a clean EOF. + */ + function failInput(reason: unknown): void { + failInputState(reason) + errorReadable(failReason) + abortResolverSignal(failReason) } function assertWithinDeclaredLength(): void { - if (expectedTotal !== undefined && receivedTotal > expectedTotal) { - throw new InvalidCiphertextLengthError( - `Invalid encoded object: received ${receivedTotal} bytes, but the declared plaintext_length implies a total of at most ${expectedTotal} bytes.` + if (expectedLength !== undefined && receivedTotal > expectedLength.total) { + throw new ExcessCiphertextError( + `Invalid encoded object: received ${receivedTotal} bytes, but the declared plaintext_length implies a total of at most ${expectedLength.total} bytes.` ) } } - /** Used when the failure originates on the read side and needs to reach an otherwise-healthy writable. */ + /** + * Propagate a failure originating on the read side or from `options.signal` + * through both sides of the pair before notifying the resolver signal. + */ function fail(reason: unknown): void { - failInput(reason) + failInputState(reason) // A no-op on an already errored or closed stream, per the Streams spec. - outerController?.error(reason) + outerController?.error(failReason) + errorReadable(failReason) + abortResolverSignal(failReason) } const writable = new WritableStream({ @@ -302,14 +381,17 @@ function createDecryptStream( // also rejects a read still waiting on the envelope handoff, instead // of leaving it pending forever. try { + if (failed) { + throw failReason + } assertValidEncodedBlock(block) receivedTotal += block.length + assertWithinDeclaredLength() if (receivedTotal > MAX_ENCODED_OBJECT_SIZE) { throw new InvalidCiphertextLengthError( `Invalid encoded object: received ${receivedTotal} bytes, exceeding the ${MAX_ENCODED_OBJECT_SIZE}-byte limit.` ) } - assertWithinDeclaredLength() if (input === undefined) { // Still scanning for the envelope. `scanner.push` copies whatever @@ -332,17 +414,28 @@ function createDecryptStream( } const { plaintextLength } = decoded.protectedHeader if (plaintextLength !== undefined) { - expectedTotal = decoded.envelopeLength + ciphertextLengthForPlaintext(plaintextLength, chunkSize) - if (expectedTotal > MAX_ENCODED_OBJECT_SIZE) { + const expectedCiphertextLength = ciphertextLengthForPlaintext(plaintextLength, chunkSize) + const total = decoded.envelopeLength + expectedCiphertextLength + if (total > MAX_ENCODED_OBJECT_SIZE) { throw new InvalidCiphertextLengthError( - `Invalid encoded object: the declared plaintext_length implies ${expectedTotal} bytes, exceeding the ${MAX_ENCODED_OBJECT_SIZE}-byte limit.` + `Invalid encoded object: the declared plaintext_length implies ${total} bytes, exceeding the ${MAX_ENCODED_OBJECT_SIZE}-byte limit.` ) } + expectedLength = { + total, + plaintext: plaintextLength, + ciphertext: expectedCiphertextLength, + envelope: decoded.envelopeLength, + } assertWithinDeclaredLength() } + if (failed) { + throw failReason + } const framer = createChunkFramer(chunkSize + TAG_SIZE) input = { framer, writer: framer.writable.getWriter() } + handoffSettled = true resolveHandoff?.({ decoded, framer, chunkSize }) if (rest.length > 0) { @@ -353,25 +446,40 @@ function createDecryptStream( await input.writer.write(block) } catch (cause) { - // The throw below auto-errors this writable; failInput just needs - // to reject a still-pending envelope handoff and stop the framer. - failInput(cause) + // Latch the error on both controllers BEFORE notifying resolver/unwrapper + // abort listeners so re-entrant `writer.abort(other)` cannot mask `cause`. + fail(cause) throw cause } }, async close() { + if (failed) { + throw failReason + } if (input === undefined) { // Always throws: input would already be set otherwise. Routed - // through `failInput` too, so a read still waiting on the envelope - // handoff rejects instead of hanging forever. + // through `fail` so both controllers latch `cause` and a read still + // waiting on the envelope handoff rejects instead of hanging forever. try { scanner.finish() } catch (cause) { - failInput(cause) + fail(cause) throw cause } return } + // Compare against the declared ciphertext length at EOF before closing + // the framer so a known-short stream fails immediately (aborting any + // pending KeyResolver or Unwrapper) and reports TruncatedCiphertextError + // even when truncated mid-tag, at zero bytes, or with a bare tag. + if (expectedLength !== undefined && receivedTotal < expectedLength.total) { + const receivedCiphertext = receivedTotal - expectedLength.envelope + const cause = new TruncatedCiphertextError( + `Invalid encoded object: received ${receivedCiphertext} ciphertext bytes, but the declared plaintext_length (${expectedLength.plaintext}) implies ${expectedLength.ciphertext} bytes.` + ) + fail(cause) + throw cause + } await input.writer.close() }, }) @@ -383,7 +491,6 @@ function createDecryptStream( additionalData: Uint8Array baseNonce: Uint8Array chunkSize: number - plaintextLength: number | undefined } | undefined let chunkIndex = 0 @@ -391,14 +498,31 @@ function createDecryptStream( const readable = new ReadableStream( { + start(controller) { + readableController = controller + if (signal !== undefined) { + cleanupAbort = onAbort(signal, (reason) => fail(reason)) + } + }, async pull(controller) { try { + if (failed) { + throw failReason + } if (keyed === undefined) { const { decoded, framer, chunkSize } = await handoff // Do not start key work for input that has already failed. + if (failed) { + throw failReason + } framer.throwIfFailed() // Caller code can take forever; a stream failure still ends this read. - const cekKey = await Promise.race([getCekKey(decoded), failure]) + // `failure` is first so a re-entrant abort inside `getCekKey` still + // preserves the original stream error. + const cekKey = await Promise.race([failure, getCekKey(decoded, resolverAbortController.signal)]) + if (failed) { + throw failReason + } keyed = { framer, cekKey, @@ -406,44 +530,46 @@ function createDecryptStream( // Copied: retained for every chunk over the life of the stream. baseNonce: new Uint8Array(decoded.protectedHeader.iv), chunkSize, - plaintextLength: decoded.protectedHeader.plaintextLength, } // Fall through into the chunk step below, in the same pull. } - const { framer, cekKey, additionalData, baseNonce, chunkSize, plaintextLength } = keyed + const { framer, cekKey, additionalData, baseNonce, chunkSize } = keyed const { bytes, isLast } = await framer.next() + if (failed) { + throw failReason + } receivedCiphertext += bytes.length if (isLast) { // Validates the total shape (a bare tag, a short remainder, and // so on) before anything about this last chunk is trusted. - const layout = chunkLayout(receivedCiphertext, chunkSize) - if (plaintextLength !== undefined && layout.plaintextLength !== plaintextLength) { - throw new InvalidCiphertextLengthError( - `Invalid encoded object: the ciphertext implies a plaintext of ${layout.plaintextLength} bytes, but the declared plaintext_length is ${plaintextLength}.` - ) - } + chunkLayout(receivedCiphertext, chunkSize) } // The header never picks the final chunk; only running out of // input (the framer's own `isLast`) does. const nonce = deriveChunkNonce(baseNonce, chunkIndex, isLast) const plaintext = await aesGcmDecrypt(cekKey, nonce, additionalData, bytes) + if (failed) { + throw failReason + } if (plaintext.length > 0) { controller.enqueue(plaintext) } chunkIndex++ if (isLast) { + cleanupSignal() controller.close() } } catch (cause) { - // Propagate to the writable side too: rejects a pending write, and - // errors it so an upstream `pipeThrough` source stops. + // Propagate to both sides: errors the readable and writable, rejects + // any pending write, and notifies the resolver/unwrapper signal. fail(cause) - throw cause } }, cancel(reason) { + // Readable is already cancelling; do not call `readableController.error()`. + readableErrored = true fail(reason) }, }, @@ -453,8 +579,23 @@ function createDecryptStream( return { writable, readable } } -/** Derives or fetches the CEK for a chunked object, given its `EnvelopeInfo`. Called once, after the envelope decodes. */ -export type KeyResolver = (info: EnvelopeInfo) => Promise | Uint8Array +/** + * Derives or fetches the CEK for a chunked object, given its `EnvelopeInfo` + * and an `AbortSignal`. + * + * Called at most once, after the envelope decodes and before any ciphertext is + * decrypted. `signal` aborts if the stream is cancelled, aborted (including + * via `options.signal`), or fails, and stays un-aborted on successful + * completion. + * + * Ownership: FEE borrows the returned key bytes only long enough to import + * them into a non-extractable `CryptoKey` and never zeroes or mutates the + * caller's buffer. The caller owns every key it returns — including one FEE + * discards after cancellation (when `signal.aborted` becomes `true` before + * import and FEE skips validation and import) — and should zero it once the + * stream settles. + */ +export type KeyResolver = (info: EnvelopeInfo, signal: AbortSignal) => Promise | Uint8Array /** * Creates a streaming decryptor for a scheme-2 object using either a direct @@ -465,53 +606,86 @@ export type KeyResolver = (info: EnvelopeInfo) => Promise | Uint8Arr * * A `KeyResolver` is called at most once, after the envelope is decoded and * before any ciphertext is decrypted. It receives the same `EnvelopeInfo` - * reported by `parse`. The resolver is not called if the stream fails before - * that point or the readable side is never consumed. + * reported by `parse` and an `AbortSignal` that aborts if the stream is + * cancelled, aborted (including via `options.signal`), or fails (but not on + * successful EOF). The resolver is not called if the stream fails or + * `options.signal` aborts before that point, or if the readable side is never + * consumed. * * `EnvelopeInfo` is derived from unauthenticated envelope data, so a resolver * must treat it as untrusted input when deciding which key to derive or fetch. * Plaintext remains protected by the AEAD authentication performed afterward. * - * Resolver failures are wrapped in `KeyResolutionError`; an invalid resolved - * key is rejected as an invalid CEK. + * FEE borrows the key bytes (whether passed directly or returned by a + * `KeyResolver`) only long enough to import them into a non-extractable + * `CryptoKey` and never zeroes the caller's buffer. The caller owns every key + * it returns — including one FEE discards after cancellation — and should zero + * it once the stream settles. + * + * Resolver failures are wrapped in `KeyResolutionError` unless the stream + * aborted; an invalid resolved key is rejected as an invalid CEK. When + * `options.signal` aborts, both sides of the returned pair error with the exact + * `signal.reason`, pending writes are unblocked, and any late key result is + * discarded without validating or importing it. * * Input blocks may be reused once their corresponding `write()` resolves. * If decryption later fails, any plaintext already emitted belongs to an * incomplete object and must be discarded. */ -export function decrypt(key: Uint8Array | KeyResolver): ReadableWritablePair { +export function decrypt( + key: Uint8Array | KeyResolver, + options?: DecryptOptions +): ReadableWritablePair { if (typeof key === 'function') { - return createDecryptStream(async (decoded) => { + const signal = readDecryptOptions(options) + return createDecryptStream(async (decoded, resolverSignal) => { + resolverSignal.throwIfAborted() // Built outside the try: only the resolver's own failures are KeyResolutionError. const info = toEnvelopeInfo(decoded) let resolved: Uint8Array try { - resolved = await key(info) + resolved = await key(info, resolverSignal) } catch (cause) { + if (resolverSignal.aborted) { + throw resolverSignal.reason + } throw new KeyResolutionError('Key resolution failed.', { cause }) } + if (resolverSignal.aborted) { + throw resolverSignal.reason + } assertAes256Key(resolved, 'resolved CEK') return importAesGcmKey(resolved, 'decrypt', false) - }) + }, signal) } assertAes256Key(key, 'CEK') - return createDecryptStream(() => importAesGcmKey(key, 'decrypt', false)) + const signal = readDecryptOptions(options) + return createDecryptStream(async () => importAesGcmKey(key, 'decrypt', false), signal) } /** * Decrypt a scheme-2 object using a CEK recovered by `unwrapper`. * * For tag 96, the unwrapper is called once with isolated copies of all - * recipients in wire order. A tag-16 object has no recipients and fails - * without calling it. The returned CEK is validated before any chunk is - * decrypted. As with `decrypt`, discard plaintext already read if the stream fails. + * recipients in wire order and an `AbortSignal` that aborts if the stream is + * cancelled, aborted (including via `options.signal`), or fails (but not on + * successful EOF). A tag-16 object has no recipients and fails without calling + * it. The returned CEK is validated before any chunk is decrypted. When + * `options.signal` aborts, both sides of the returned pair error with the exact + * `signal.reason`, pending writes are unblocked, and any late key result is + * discarded without importing it. As with `decrypt`, discard plaintext already + * read if the stream fails. */ -export function decryptWith(unwrapper: Unwrapper): ReadableWritablePair { +export function decryptWith( + unwrapper: Unwrapper, + options?: DecryptOptions +): ReadableWritablePair { if (typeof unwrapper !== 'function') { throw new MalformedEnvelopeError(`Invalid unwrapper: expected a function, got ${describeCborType(unwrapper)}.`) } - return createDecryptStream(async (decoded) => { - const cek = await recoverCek(decoded, unwrapper) - return importAesGcmKey(cek, 'decrypt', false) - }) + const signal = readDecryptOptions(options) + return createDecryptStream( + async (decoded, resolverSignal) => recoverCekKey(decoded, unwrapper, resolverSignal), + signal + ) } diff --git a/packages/filecoin-encryption-envelope/src/aes-gcm.ts b/packages/filecoin-encryption-envelope/src/aes-gcm.ts index c148d4506..b057c0444 100644 --- a/packages/filecoin-encryption-envelope/src/aes-gcm.ts +++ b/packages/filecoin-encryption-envelope/src/aes-gcm.ts @@ -23,7 +23,7 @@ import { import { assertAes256Key, assertArrayBufferBacked } from './internal/keys.ts' import { aesGcmDecrypt, aesGcmEncrypt, importAesGcmKey, randomBytes } from './internal/web-crypto.ts' import { createRecipientRecords, prepareRecipientInputs } from './recipients/prepare.ts' -import { recoverCek } from './recipients/recover.ts' +import { recoverCekKey } from './recipients/recover.ts' import type { Recipient, Unwrapper } from './recipients/types.ts' const MAX_AES_GCM_CIPHERTEXT_SIZE = MAX_AES_GCM_PLAINTEXT_SIZE + TAG_SIZE @@ -180,7 +180,6 @@ export async function decryptWith(encoded: Uint8Array, unwrapper: Unwrapper): Pr } const { decoded, ciphertext, additionalData, iv } = prepareDecryption(encoded) - const cek = await recoverCek(decoded, unwrapper) - const key = await importAesGcmKey(cek, 'decrypt', false) + const key = await recoverCekKey(decoded, unwrapper) return await aesGcmDecrypt(key, iv, additionalData, ciphertext) } diff --git a/packages/filecoin-encryption-envelope/src/chunk-layout.ts b/packages/filecoin-encryption-envelope/src/chunk-layout.ts index 7619353d7..224c35bc2 100644 --- a/packages/filecoin-encryption-envelope/src/chunk-layout.ts +++ b/packages/filecoin-encryption-envelope/src/chunk-layout.ts @@ -151,14 +151,26 @@ export function chunkCountForPlaintext(plaintextLength: number, chunkSize: numbe /** * Detached ciphertext length a plaintext of `plaintextLength` bytes produces - * at `chunkSize`: `P + 16 × max(1, ceil(P / S))`, one tag per chunk. + * at `chunkSize`: `P + 16 × max(1, ceil(P / S))`, adding one 16-byte + * (`TAG_SIZE`) authentication tag per chunk — including one tag even for empty + * input (`0`). * - * This is what makes a declared `plaintext_length` checkable. The mapping is - * strictly increasing in `P`, so one ciphertext length admits exactly one - * valid `P` — which holds only because the profile permits a single - * final-chunk form (see {@link chunkLayout}). An unsafe result is rejected - * rather than returned: past `Number.MAX_SAFE_INTEGER` a length rounds - * silently instead of failing. + * Throws `InvalidPlaintextLengthError` if `plaintextLength` is not a + * non-negative safe integer, if the implied ciphertext length is not a safe + * integer, or if the detached ciphertext alone exceeds + * `MAX_ENCODED_OBJECT_SIZE`. Throws `InvalidChunkSizeError` if `chunkSize` is + * outside `[MIN_CHUNK_SIZE, MAX_CHUNK_SIZE]`, or `ChunkCountExceededError` if + * the chunk count exceeds `MAX_CHUNK_COUNT`. + * + * The returned length covers only the detached ciphertext, not the COSE + * envelope. For a full-object check against `MAX_ENCODED_OBJECT_SIZE`, add the + * actual encoded envelope length (or `MAX_ENVELOPE_SIZE` as a conservative + * upper bound when the envelope length is not known yet). + * + * Internally, this is also what makes a declared `plaintext_length` checkable: + * the mapping is strictly increasing in `P`, so one ciphertext length admits + * exactly one valid `P` — which holds only because the profile permits a single + * final-chunk form (see {@link chunkLayout}). */ export function ciphertextLengthForPlaintext(plaintextLength: number, chunkSize: number): number { const chunkCount = chunkCountForPlaintext(plaintextLength, chunkSize) diff --git a/packages/filecoin-encryption-envelope/src/errors.ts b/packages/filecoin-encryption-envelope/src/errors.ts index 6e4270043..5f10acc22 100644 --- a/packages/filecoin-encryption-envelope/src/errors.ts +++ b/packages/filecoin-encryption-envelope/src/errors.ts @@ -63,6 +63,32 @@ export class InvalidCiphertextLengthError extends EnvelopeError { override name = 'InvalidCiphertextLengthError' } +/** + * The ciphertext has fewer bytes than the envelope's declared `plaintext_length` + * requires. + * + * Describes a mismatch between the observed byte count and the unauthenticated + * header value, not proof of a transport failure or which side was altered. In + * streaming decryption this means the input stream ended early; in range + * planning (`planRange` / `decryptRange`) it means the reported `source.size` + * itself is shorter than declared (a short stored object rather than a + * transient read cutoff). + */ +export class TruncatedCiphertextError extends InvalidCiphertextLengthError { + override name = 'TruncatedCiphertextError' +} + +/** + * The ciphertext has more bytes than the envelope's declared `plaintext_length` + * allows. + * + * Describes a mismatch between the observed byte count and the unauthenticated + * header value, not proof of tampering or which side was altered. + */ +export class ExcessCiphertextError extends InvalidCiphertextLengthError { + override name = 'ExcessCiphertextError' +} + /** A chunk count derived from a plaintext or ciphertext length exceeds `MAX_CHUNK_COUNT`. */ export class ChunkCountExceededError extends EnvelopeError { override name = 'ChunkCountExceededError' diff --git a/packages/filecoin-encryption-envelope/src/index.ts b/packages/filecoin-encryption-envelope/src/index.ts index cd63a11fe..f0a1f9ba1 100644 --- a/packages/filecoin-encryption-envelope/src/index.ts +++ b/packages/filecoin-encryption-envelope/src/index.ts @@ -18,7 +18,15 @@ * @module filecoin-encryption-envelope */ export * as aesGcm from './aes-gcm.ts' -export { type ChunkedEncryptOptions, decrypt, decryptWith, encrypt, type KeyResolver } from './aes-gcm-stream.ts' +export { + type ChunkedEncryptOptions, + type DecryptOptions, + decrypt, + decryptWith, + encrypt, + type KeyResolver, +} from './aes-gcm-stream.ts' +export { ciphertextLengthForPlaintext } from './chunk-layout.ts' export type { AppMetadata, CborValue } from './cose/headers.ts' export * as cose from './cose/index.ts' export * as errors from './errors.ts' @@ -29,8 +37,10 @@ export { decryptRange, decryptRangeWith, type EnvelopeInfo, + type ParseOptions, parse, type RandomAccessSource, + type RangeDecryptOptions, type RangeResult, } from './range/index.ts' export * as recipients from './recipients/index.ts' diff --git a/packages/filecoin-encryption-envelope/src/internal/abort.ts b/packages/filecoin-encryption-envelope/src/internal/abort.ts new file mode 100644 index 000000000..285b32e29 --- /dev/null +++ b/packages/filecoin-encryption-envelope/src/internal/abort.ts @@ -0,0 +1,77 @@ +/** + * Internal `AbortSignal` helpers shared by streaming and range decryption. + */ +import { describeCborType } from '../cose/headers.ts' +import { MalformedEnvelopeError } from '../errors.ts' + +/** Validate an optional caller-supplied `AbortSignal` (including cross-realm signals). */ +export function assertOptionalAbortSignal(value: unknown): asserts value is AbortSignal | undefined { + if (value === undefined) return + try { + AbortSignal.any([value as AbortSignal]) + } catch { + throw new MalformedEnvelopeError(`Invalid options.signal: expected an AbortSignal, got ${describeCborType(value)}.`) + } +} + +/** + * Invoke `callback` once with `signal.reason` if `signal` is already aborted + * or when it aborts; returns a cleanup function that removes the listener. + * + * Retains `callback` strongly until `cleanup()` is called so callers holding + * only a pending stream promise (`reader.read()`, `writer.closed`, etc.) still + * receive cancellation. + */ +export function onAbort(signal: AbortSignal, callback: (reason: unknown) => void): () => void { + if (signal.aborted) { + callback(signal.reason) + return () => { + // Already aborted before attaching a listener. + } + } + const cleanup = () => signal.removeEventListener('abort', listener) + const listener = () => { + cleanup() + callback(signal.reason) + } + signal.addEventListener('abort', listener, { once: true }) + return cleanup +} + +/** + * Race `promise` against `signal` aborting, rejecting with `signal.reason`. + * Removes its listener on settlement and suppresses late rejections from `promise`. + */ +export function raceAbort( + promise: Promise, + signal: AbortSignal | undefined, + onAbortCallback?: (reason: unknown) => void +): Promise { + if (signal === undefined) return promise + if (signal.aborted) { + promise.catch(() => undefined) + onAbortCallback?.(signal.reason) + return Promise.reject(signal.reason) + } + + return new Promise((resolve, reject) => { + const cleanup = onAbort(signal, (reason) => { + onAbortCallback?.(reason) + reject(reason) + }) + promise.then( + (value) => { + cleanup() + if (signal.aborted) { + reject(signal.reason) + return + } + resolve(value) + }, + (cause) => { + cleanup() + reject(signal.aborted ? signal.reason : cause) + } + ) + }) +} diff --git a/packages/filecoin-encryption-envelope/src/internal/web-crypto.ts b/packages/filecoin-encryption-envelope/src/internal/web-crypto.ts index 0ba6718a4..3491de23d 100644 --- a/packages/filecoin-encryption-envelope/src/internal/web-crypto.ts +++ b/packages/filecoin-encryption-envelope/src/internal/web-crypto.ts @@ -110,10 +110,15 @@ export async function aesKwWrap(cekKey: CryptoKey, kekKey: CryptoKey): Promise, - kekKey: CryptoKey + kekKey: CryptoKey, + signal?: AbortSignal ): Promise { let cekKey: CryptoKey try { @@ -127,9 +132,21 @@ export async function aesKwUnwrap( throw new CryptoOperationError('AES-256 key unwrap failed before integrity could be checked.', { cause }) } + signal?.throwIfAborted() + + let raw: Uint8Array try { - return new Uint8Array(await globalThis.crypto.subtle.exportKey('raw', cekKey)) + raw = new Uint8Array(await globalThis.crypto.subtle.exportKey('raw', cekKey)) } catch (cause) { + if (signal?.aborted) { + throw signal.reason + } throw new CryptoOperationError('Could not export the unwrapped CEK.', { cause }) } + + if (signal?.aborted) { + raw.fill(0) + throw signal.reason + } + return raw } diff --git a/packages/filecoin-encryption-envelope/src/public-constants.ts b/packages/filecoin-encryption-envelope/src/public-constants.ts index f5a0c78a1..1ebfc0045 100644 --- a/packages/filecoin-encryption-envelope/src/public-constants.ts +++ b/packages/filecoin-encryption-envelope/src/public-constants.ts @@ -10,5 +10,6 @@ export { MAX_CHUNK_SIZE, MAX_ENCODED_OBJECT_SIZE, MIN_CHUNK_SIZE, + TAG_SIZE, } from './constants.ts' -export { ALG_A256KW, ENVELOPE_TYPE } from './cose/constants.ts' +export { ALG_A256KW, ENVELOPE_TYPE, MAX_ENVELOPE_SIZE } from './cose/constants.ts' diff --git a/packages/filecoin-encryption-envelope/src/range/decrypt.ts b/packages/filecoin-encryption-envelope/src/range/decrypt.ts index 39c98c97f..f5630be97 100644 --- a/packages/filecoin-encryption-envelope/src/range/decrypt.ts +++ b/packages/filecoin-encryption-envelope/src/range/decrypt.ts @@ -8,10 +8,11 @@ import type { DecodedEnvelope } from '../cose/decode.ts' import { encStructure } from '../cose/enc-structure.ts' import { describeCborType } from '../cose/headers.ts' import { InvalidSourceLengthError, MalformedEnvelopeError, UnsupportedSchemeError } from '../errors.ts' +import { assertOptionalAbortSignal, onAbort, raceAbort } from '../internal/abort.ts' import { assertAes256Key } from '../internal/keys.ts' import { aesGcmDecrypt, importAesGcmKey } from '../internal/web-crypto.ts' import { deriveChunkNonce } from '../nonce.ts' -import { recoverCek } from '../recipients/recover.ts' +import { recoverCekKey } from '../recipients/recover.ts' import type { Unwrapper } from '../recipients/types.ts' import { type ChunkedEnvelopeParams, paramsState } from './inspect.ts' import { type ByteRange, planRange, type RangePlan } from './plan.ts' @@ -40,20 +41,36 @@ export interface RangeResult { includesFinalChunk: boolean } -interface RangeDecryptOptions { +/** Options for {@link decryptRange} and {@link decryptRangeWith}. */ +export interface RangeDecryptOptions { + /** Cached envelope parameters from `parse()` on this same object version. */ params?: ChunkedEnvelopeParams + /** + * Optional cancellation signal covering setup (envelope read, key recovery/import) + * and the lifetime of the returned `RangeResult.stream`. + * + * While `stream` is unsettled, the listener on `signal` keeps the stream (and + * its `source`) reachable so pending reads remain abortable. When reusing a + * long-lived signal, consume or explicitly cancel unused streams (or use an + * operation-scoped signal). + */ + signal?: AbortSignal } -function readParams(options: RangeDecryptOptions | undefined): ChunkedEnvelopeParams | undefined { - if (options === undefined) return undefined +function readRangeOptions(options: RangeDecryptOptions | undefined): { + params: ChunkedEnvelopeParams | undefined + signal: AbortSignal | undefined +} { + if (options === undefined) return { params: undefined, signal: undefined } // An array passes typeof 'object' but isn't a valid options shape. if (options === null || typeof options !== 'object' || Array.isArray(options)) { throw new MalformedEnvelopeError( `Invalid range decryption options: expected an object, got ${describeCborType(options)}.` ) } - const { params } = options - return params + const { params, signal } = options + assertOptionalAbortSignal(signal) + return { params, signal } } /** @@ -127,39 +144,91 @@ function createRangeStream( source: RandomAccessSource, plan: RangePlan, chunkSize: number, - keyed: KeyedRangePlan + keyed: KeyedRangePlan, + signal?: AbortSignal ): ReadableStream { const stride = chunkSize + TAG_SIZE - let opened: { reader: ExactRangeReader; pieces: ReturnType } | undefined + const streamAbortController = new AbortController() + const streamSignal = streamAbortController.signal let index = plan.firstChunk let remainingToEmit = plan.rangeLength + const state = { + opened: undefined as { reader: ExactRangeReader; pieces: ReturnType } | undefined, + streamController: undefined as ReadableStreamDefaultController | undefined, + cleanupAbort: undefined as (() => void) | undefined, + settled: false, + aborted: false, + cleanup() { + if (this.settled) return + this.settled = true + this.cleanupAbort?.() + this.cleanupAbort = undefined + }, + abortStreamSignal(reason: unknown) { + if (!streamSignal.aborted) { + streamAbortController.abort(reason) + } + }, + handleAbort(reason: unknown) { + if (this.settled) return + this.aborted = true + this.cleanup() + // Error the output stream BEFORE cancelling the source or notifying the + // adapter signal, so re-entrant cleanup calling `reader.cancel()` cannot + // turn an aborted read into a clean EOF. + this.streamController?.error(reason) + void this.opened?.reader.cancel(reason) + this.abortStreamSignal(reason) + }, + } + return new ReadableStream( { + start(controller) { + state.streamController = controller + if (signal !== undefined) { + state.cleanupAbort = onAbort(signal, (reason) => state.handleAbort(reason)) + } + }, async pull(controller) { let reader: ExactRangeReader | undefined try { - if (opened === undefined) { - const newReader = openExactRange(source, plan.ciphertextSpan.offset, plan.ciphertextSpan.length) - opened = { reader: newReader, pieces: createPieceReader(newReader, stride) } + streamSignal.throwIfAborted() + + if (state.opened === undefined) { + // `cancelOnError: false` lets this stream's catch error the output + // stream BEFORE invoking source `cancel()`, so re-entrant cleanup + // cannot turn a read failure into a clean EOF. + const newReader = openExactRange( + source, + plan.ciphertextSpan.offset, + plan.ciphertextSpan.length, + streamSignal, + false + ) + state.opened = { reader: newReader, pieces: createPieceReader(newReader, stride) } } - reader = opened.reader + reader = state.opened.reader const isLastPiece = index === plan.lastChunk const pieceLength = isLastPiece ? plan.lastChunkCipherLength : stride - const piece = await opened.pieces.readPiece(pieceLength) + const piece = await state.opened.pieces.readPiece(pieceLength) + streamSignal.throwIfAborted() // The size-derived layout decides finality, never "last piece of this span". const isFinalChunk = index === plan.chunkCount - 1 const nonce = deriveChunkNonce(keyed.baseNonce, index, isFinalChunk) // Decrypt before reading again: `piece` may be a view into a block // the source could reuse or overwrite on the next read. - let plaintext = await aesGcmDecrypt(keyed.cekKey, nonce, keyed.additionalData, piece) + let plaintext = await raceAbort(aesGcmDecrypt(keyed.cekKey, nonce, keyed.additionalData, piece), streamSignal) + streamSignal.throwIfAborted() if (isLastPiece) { // Confirms the source has nothing left beyond the planned span, // before this final piece's plaintext is ever released. const extra = await reader.read() + streamSignal.throwIfAborted() if (extra !== undefined) { throw new InvalidSourceLengthError('Invalid range source: produced extra bytes beyond the planned span.') } @@ -178,15 +247,28 @@ function createRangeStream( } index++ if (isLastPiece) { + state.cleanup() controller.close() } } catch (cause) { - await reader?.cancel(cause) - throw cause + state.cleanup() + if (state.aborted) { + void reader?.cancel(streamSignal.reason) + return + } + const error = streamSignal.aborted ? streamSignal.reason : cause + // Error the output stream BEFORE cancelling the source or aborting + // the adapter signal, so neither re-entrant `reader.cancel()` nor a + // hung source `cancel()` can turn a failure into a clean EOF or hang. + state.streamController?.error(error) + void reader?.cancel(error) + state.abortStreamSignal(error) } }, cancel(reason) { - return opened?.reader.cancel(reason) + state.cleanup() + state.abortStreamSignal(reason) + return state.opened?.reader.cancel(reason) }, }, { highWaterMark: 0 } @@ -202,14 +284,16 @@ async function createRangeResult( source: Uint8Array | RandomAccessSource, range: unknown, options: RangeDecryptOptions | undefined, - getCekKey: (decoded: DecodedEnvelope) => Promise + getCekKey: (decoded: DecodedEnvelope, signal: AbortSignal | undefined) => Promise ): Promise { + const { params, signal } = readRangeOptions(options) + signal?.throwIfAborted() const randomAccessSource = toRandomAccessSource(source) - const params = readParams(options) // With params, the envelope is never read: `paramsState` hands back the // one this package already decoded when it created them. - const decoded = params === undefined ? await readEnvelope(randomAccessSource) : paramsState(params).decoded + const decoded = params === undefined ? await readEnvelope(randomAccessSource, signal) : paramsState(params).decoded + signal?.throwIfAborted() if (decoded.protectedHeader.alg !== ALG_CHUNKED_AES_256_GCM_STREAM) { throw new UnsupportedSchemeError( `Unsupported content algorithm ${decoded.protectedHeader.alg}: range decryption requires alg ${ALG_CHUNKED_AES_256_GCM_STREAM}.` @@ -225,13 +309,15 @@ async function createRangeResult( range ) - const cekKey = await getCekKey(decoded) + signal?.throwIfAborted() + const cekKey = await raceAbort(getCekKey(decoded, signal), signal) + signal?.throwIfAborted() const additionalData = encStructure(decoded.tag, decoded.protectedHeader.bytes) // Copied: retained for every chunk over the life of the stream. const baseNonce = new Uint8Array(decoded.protectedHeader.iv) return { - stream: createRangeStream(randomAccessSource, plan, chunkSize, { cekKey, additionalData, baseNonce }), + stream: createRangeStream(randomAccessSource, plan, chunkSize, { cekKey, additionalData, baseNonce }, signal), rangeLength: plan.rangeLength, totalPlaintextLength: plan.totalPlaintextLength, // A copy: the stream opens `plan.ciphertextSpan` later, so a caller @@ -257,6 +343,13 @@ async function createRangeResult( * guaranteed to be caught: most fail authentication, but versions that differ * only outside the protected header and the chunks read can still decrypt. * + * Pass `options.signal` to cancel setup (envelope reads and key import) or the + * returned `stream`. Aborting rejects setup or errors `stream` with the exact + * `signal.reason`, forwards `signal` to `source.openRange` during envelope + * setup, mirrors it onto the stream-scoped `AbortSignal` passed to + * `source.openRange` for ciphertext reads (which also aborts if `stream` is + * cancelled or fails), and cancels any active or late-arriving source stream. + * * Truncation: a declared `plaintext_length` catches a size mismatch before * any fetch. A range that includes the presumed final chunk catches * truncation via that chunk's authenticated `last_flag`. A range stopping @@ -271,7 +364,7 @@ export async function decryptRange( options?: RangeDecryptOptions ): Promise { assertAes256Key(cek, 'CEK') - return createRangeResult(source, range, options, () => importAesGcmKey(cek, 'decrypt', false)) + return createRangeResult(source, range, options, async () => importAesGcmKey(cek, 'decrypt', false)) } /** @@ -280,10 +373,14 @@ export async function decryptRange( * * - Tag 96 only: a tag-16 object fails with `NoUsableRecipientError` without * calling `unwrapper`. - * - `unwrapper` is called once, with copies of every recipient in wire order, - * also when `options.params` skips the envelope read; its CEK is validated. + * - `unwrapper` is called once, with copies of every recipient in wire order + * (and `options.signal` when provided), also when `options.params` skips + * the envelope read; its CEK is validated. * - The range is planned first and the key recovered before the promise * settles, so recipient failures reject it, never the stream. + * - When `options.signal` aborts during setup or streaming, setup rejects or + * `stream` errors with the exact `signal.reason`, active or late source + * streams are cancelled, and any late key result is discarded without import. */ export async function decryptRangeWith( source: RandomAccessSource | Uint8Array, @@ -294,8 +391,5 @@ export async function decryptRangeWith( if (typeof unwrapper !== 'function') { throw new MalformedEnvelopeError(`Invalid unwrapper: expected a function, got ${describeCborType(unwrapper)}.`) } - return createRangeResult(source, range, options, async (decoded) => { - const cek = await recoverCek(decoded, unwrapper) - return importAesGcmKey(cek, 'decrypt', false) - }) + return createRangeResult(source, range, options, async (decoded, signal) => recoverCekKey(decoded, unwrapper, signal)) } diff --git a/packages/filecoin-encryption-envelope/src/range/index.ts b/packages/filecoin-encryption-envelope/src/range/index.ts index fa055bc18..534ab3600 100644 --- a/packages/filecoin-encryption-envelope/src/range/index.ts +++ b/packages/filecoin-encryption-envelope/src/range/index.ts @@ -9,7 +9,7 @@ * The implementation details used by these APIs (`paramsState`, `planRange`, * `readEnvelope`, and `openExactRange`) are kept in separate modules. */ -export { decryptRange, decryptRangeWith, type RangeResult } from './decrypt.ts' -export { type ChunkedEnvelopeParams, type EnvelopeInfo, parse } from './inspect.ts' +export { decryptRange, decryptRangeWith, type RangeDecryptOptions, type RangeResult } from './decrypt.ts' +export { type ChunkedEnvelopeParams, type EnvelopeInfo, type ParseOptions, parse } from './inspect.ts' export type { ByteRange } from './plan.ts' export type { RandomAccessSource } from './source.ts' diff --git a/packages/filecoin-encryption-envelope/src/range/inspect.ts b/packages/filecoin-encryption-envelope/src/range/inspect.ts index 2d5093432..9c1bf8af0 100644 --- a/packages/filecoin-encryption-envelope/src/range/inspect.ts +++ b/packages/filecoin-encryption-envelope/src/range/inspect.ts @@ -18,8 +18,9 @@ */ import { ALG_AES_256_GCM } from '../constants.ts' import type { DecodedEnvelope } from '../cose/decode.ts' -import type { AppMetadata } from '../cose/headers.ts' +import { type AppMetadata, describeCborType } from '../cose/headers.ts' import { MalformedEnvelopeError } from '../errors.ts' +import { assertOptionalAbortSignal } from '../internal/abort.ts' import { toRecipientInfo } from '../recipients/info.ts' import type { RecipientInfo } from '../recipients/types.ts' import { type RandomAccessSource, readEnvelope, toRandomAccessSource } from './source.ts' @@ -107,14 +108,34 @@ export function toEnvelopeInfo(decoded: DecodedEnvelope): EnvelopeInfo { return { ...base, scheme: 'chunked', params: createChunkedParams(decoded) } } +/** Options for {@link parse}. */ +export interface ParseOptions { + /** Optional cancellation signal covering the envelope read. */ + signal?: AbortSignal +} + +function readParseOptions(options: ParseOptions | undefined): AbortSignal | undefined { + if (options === undefined) return undefined + if (options === null || typeof options !== 'object' || Array.isArray(options)) { + throw new MalformedEnvelopeError(`Invalid parse options: expected an object, got ${describeCborType(options)}.`) + } + const { signal } = options + assertOptionalAbortSignal(signal) + return signal +} + /** * Inspect an encoded FEE object without a key: scheme, content type, * application metadata, and recipients. Unauthenticated -- see above. * * Reads only as much of `source` as it takes to find the envelope boundary - * (see `readEnvelope`), never the detached ciphertext. + * (see `readEnvelope`), never the detached ciphertext. Pass `options.signal` + * to cancel envelope reads (forwarding `signal` to `source.openRange`). */ -export async function parse(source: Uint8Array | RandomAccessSource): Promise { - const decoded = await readEnvelope(toRandomAccessSource(source)) +export async function parse(source: Uint8Array | RandomAccessSource, options?: ParseOptions): Promise { + const signal = readParseOptions(options) + signal?.throwIfAborted() + const decoded = await readEnvelope(toRandomAccessSource(source), signal) + signal?.throwIfAborted() return toEnvelopeInfo(decoded) } diff --git a/packages/filecoin-encryption-envelope/src/range/plan.ts b/packages/filecoin-encryption-envelope/src/range/plan.ts index 90b3c410c..20352ee67 100644 --- a/packages/filecoin-encryption-envelope/src/range/plan.ts +++ b/packages/filecoin-encryption-envelope/src/range/plan.ts @@ -20,10 +20,16 @@ * It carries no `length`. An overlong suffix clamps to the whole object * rather than failing. */ -import { chunkLayout } from '../chunk-layout.ts' -import { TAG_SIZE } from '../constants.ts' +import { chunkLayout, ciphertextLengthForPlaintext } from '../chunk-layout.ts' +import { MAX_ENCODED_OBJECT_SIZE, TAG_SIZE } from '../constants.ts' import { describeCborType } from '../cose/headers.ts' -import { InvalidCiphertextLengthError, InvalidRangeError, InvalidSourceLengthError } from '../errors.ts' +import { + ExcessCiphertextError, + InvalidCiphertextLengthError, + InvalidRangeError, + InvalidSourceLengthError, + TruncatedCiphertextError, +} from '../errors.ts' /** A byte range over an object's plaintext, HTTP `Range`-header style. */ export interface ByteRange { @@ -102,12 +108,31 @@ export function planRange(layoutInput: ChunkedRangeLayoutInput, range: unknown): ) } - const layout = chunkLayout(sourceSize - headerLength, chunkSize) - if (declaredPlaintextLength !== undefined && layout.plaintextLength !== declaredPlaintextLength) { - throw new InvalidCiphertextLengthError( - `Invalid encoded object: the ciphertext implies a plaintext of ${layout.plaintextLength} bytes, but the declared plaintext_length is ${declaredPlaintextLength}.` - ) + const ciphertextLength = sourceSize - headerLength + if (declaredPlaintextLength !== undefined) { + const expectedCiphertextLength = ciphertextLengthForPlaintext(declaredPlaintextLength, chunkSize) + const expectedTotal = headerLength + expectedCiphertextLength + if (expectedTotal > MAX_ENCODED_OBJECT_SIZE) { + throw new InvalidCiphertextLengthError( + `Invalid encoded object: the declared plaintext_length implies ${expectedTotal} bytes, exceeding the ${MAX_ENCODED_OBJECT_SIZE}-byte limit.` + ) + } + // Compare against the declared ciphertext length before `chunkLayout` so a + // short or overlong source size that lands on an impossible chunk shape + // still reports `TruncatedCiphertextError` or `ExcessCiphertextError`. + if (ciphertextLength < expectedCiphertextLength) { + throw new TruncatedCiphertextError( + `Invalid encoded object: the source reports ${ciphertextLength} ciphertext bytes, but the declared plaintext_length (${declaredPlaintextLength}) implies ${expectedCiphertextLength} bytes.` + ) + } + if (ciphertextLength > expectedCiphertextLength) { + throw new ExcessCiphertextError( + `Invalid encoded object: the source reports ${ciphertextLength} ciphertext bytes, but the declared plaintext_length (${declaredPlaintextLength}) implies ${expectedCiphertextLength} bytes.` + ) + } } + + const layout = chunkLayout(ciphertextLength, chunkSize) const total = layout.plaintextLength // One snapshot: a getter must not answer differently after validation. diff --git a/packages/filecoin-encryption-envelope/src/range/source.ts b/packages/filecoin-encryption-envelope/src/range/source.ts index 6af4897c2..2baa91393 100644 --- a/packages/filecoin-encryption-envelope/src/range/source.ts +++ b/packages/filecoin-encryption-envelope/src/range/source.ts @@ -12,6 +12,7 @@ import type { DecodedEnvelope } from '../cose/decode.ts' import { createEnvelopeScanner } from '../cose/envelope-scanner.ts' import { describeCborType } from '../cose/headers.ts' import { InvalidSourceLengthError, MalformedEnvelopeError } from '../errors.ts' +import { raceAbort } from '../internal/abort.ts' import { assertArrayBufferBacked } from '../internal/keys.ts' /** One immutable encoded FEE object, readable by byte range. */ @@ -23,8 +24,17 @@ export interface RandomAccessSource { * stream must produce exactly `length` bytes and then close; a short or long * response is rejected rather than reinterpreted, and a stream error * propagates unchanged. + * + * During envelope setup (`parse`, `decryptRange`, `decryptRangeWith`), the + * caller's `options.signal` is passed as the third argument when provided. + * For ciphertext spans opened by `RangeResult.stream`, the stream always + * passes its own stream-scoped `AbortSignal`, which mirrors `options.signal` + * when supplied and also aborts if the range stream is cancelled or fails. + * Adapters that ignore the third argument remain supported: range operations + * still reject promptly with `signal.reason` and cancel any active or + * late-arriving stream. */ - openRange(offset: number, length: number): Promise> + openRange(offset: number, length: number, signal?: AbortSignal): Promise> } function assertValidSourceSize(size: unknown): asserts size is number { @@ -51,7 +61,10 @@ export function toRandomAccessSource(input: unknown): RandomAccessSource { const bytes = input return { size: bytes.length, - openRange(offset, length) { + openRange(offset, length, signal) { + if (signal?.aborted) { + return Promise.reject(signal.reason) + } return Promise.resolve( new ReadableStream({ start(controller) { @@ -82,7 +95,10 @@ export function toRandomAccessSource(input: unknown): RandomAccessSource { const boundOpenRange = openRange as RandomAccessSource['openRange'] return { size, - openRange: (offset, length) => boundOpenRange.call(input, offset, length), + openRange: (offset, length, signal) => + signal === undefined + ? boundOpenRange.call(input, offset, length) + : boundOpenRange.call(input, offset, length, signal), } } @@ -124,36 +140,64 @@ export interface ExactRangeReader { * from the stream it returns, propagates unchanged -- those are the source's * own transport errors, not this reader's to interpret. */ -export function openExactRange(source: RandomAccessSource, offset: number, length: number): ExactRangeReader { +export function openExactRange( + source: RandomAccessSource, + offset: number, + length: number, + signal?: AbortSignal, + cancelOnError = true +): ExactRangeReader { let readerPromise: Promise> | undefined - let opened = false + let activeReader: ReadableStreamDefaultReader | undefined + let cancelPromise: Promise | undefined let received = 0 let finished = false function getReader(): Promise> { if (readerPromise === undefined) { readerPromise = (async () => { - const stream = await source.openRange(offset, length) + const stream = + signal === undefined ? await source.openRange(offset, length) : await source.openRange(offset, length, signal) + if (signal?.aborted) { + if (stream instanceof ReadableStream) { + void stream.cancel(signal.reason).catch(() => undefined) + } + throw signal.reason + } if (!(stream instanceof ReadableStream)) { throw new MalformedEnvelopeError( `Invalid range source: openRange(${offset}, ${length}) must resolve to a ReadableStream, got ${describeCborType(stream)}.` ) } - opened = true - return stream.getReader() + const reader = stream.getReader() + activeReader = reader + return reader })() } return readerPromise } async function read(): Promise | undefined> { + signal?.throwIfAborted() if (finished) return undefined - const reader = await getReader() try { - return await readValidated(reader) + const reader = await raceAbort(getReader(), signal, (reason) => { + void cancel(reason) + }) + signal?.throwIfAborted() + return await raceAbort(readValidated(reader), signal, (reason) => { + void cancel(reason) + }) } catch (cause) { - // Release the source (e.g. an HTTP body) instead of leaving it open. - await reader.cancel(cause).catch(() => undefined) + if (signal?.aborted) { + void cancel(signal.reason) + throw signal.reason + } + if (cancelOnError) { + // Release the source (e.g. an HTTP body) without blocking error + // reporting if the source's cancel() hangs. + void cancel(cause) + } throw cause } } @@ -196,14 +240,21 @@ export function openExactRange(source: RandomAccessSource, offset: number, lengt function cancel(reason?: unknown): Promise { if (readerPromise === undefined) return Promise.resolve() + if (cancelPromise !== undefined) { + return activeReader === undefined ? Promise.resolve() : cancelPromise + } + if (activeReader !== undefined) { + cancelPromise = activeReader.cancel(reason).catch(() => undefined) + return cancelPromise + } // Nothing useful to report if the source fails to cancel. - const cancelled = readerPromise.then( + cancelPromise = readerPromise.then( (reader) => reader.cancel(reason).catch(() => undefined), () => undefined ) - // A pending openRange has no abort signal: don't let a hung open hang - // cancellation. Its stream is still cancelled whenever it arrives. - return opened ? cancelled : Promise.resolve() + // Don't let a hung openRange hang cancellation; its stream is still + // cancelled whenever it arrives. + return Promise.resolve() } return { read, cancel } @@ -220,25 +271,32 @@ export function openExactRange(source: RandomAccessSource, offset: number, lengt * span of the wrong length (`InvalidSourceLengthError`), fails immediately -- * no further span is opened after one. */ -export async function readEnvelope(source: RandomAccessSource): Promise { +export async function readEnvelope(source: RandomAccessSource, signal?: AbortSignal): Promise { + signal?.throwIfAborted() const scanner = createEnvelopeScanner() let offset = 0 let length = Math.min(4096, source.size, MAX_ENVELOPE_SIZE) while (offset < source.size) { - const range = openExactRange(source, offset, length) + const range = openExactRange(source, offset, length, signal) for (;;) { const block = await range.read() + if (signal?.aborted) { + void range.cancel(signal.reason) + throw signal.reason + } if (block === undefined) break let result: ReturnType try { result = scanner.push(block) } catch (cause) { - await range.cancel(cause) + void range.cancel(cause) throw cause } if (result !== undefined) { - await range.cancel() + // Release the remaining probe span without blocking on a hung source cancel(). + void range.cancel() + signal?.throwIfAborted() return result.decoded } } diff --git a/packages/filecoin-encryption-envelope/src/recipients/a256kw.ts b/packages/filecoin-encryption-envelope/src/recipients/a256kw.ts index 1f994456d..433bdbc48 100644 --- a/packages/filecoin-encryption-envelope/src/recipients/a256kw.ts +++ b/packages/filecoin-encryption-envelope/src/recipients/a256kw.ts @@ -13,6 +13,7 @@ import { MalformedEnvelopeError, RecipientAttemptLimitError } from '../errors.ts import { bytesEqual } from '../internal/bytes.ts' import { assertAes256Key } from '../internal/keys.ts' import { aesKwUnwrap, aesKwWrap, importAesKwKey } from '../internal/web-crypto.ts' +import { markBuiltInUnwrapper } from './recover.ts' import type { A256KWKey, A256KWUnwrapperOptions, RecipientInfo, Unwrapper } from './types.ts' /** Default cap on AES-KW unwrap attempts per {@link createA256KWUnwrapper} call. */ @@ -168,25 +169,34 @@ export async function createA256KWUnwrapper( preparedKeys.push(key.kid === undefined ? { kekKey } : { kekKey, kid: key.kid }) } - return async (recipients: readonly RecipientInfo[]): Promise => { - let attempts = 0 - for (const recipient of recipients) { - if (recipient.alg !== ALG_A256KW) { - continue - } - for (const candidate of selectCandidates(preparedKeys, recipient.kid)) { - if (attempts === maxAttempts) { - throw new RecipientAttemptLimitError(`Recipient unwrap attempt limit reached: ${maxAttempts} attempts.`) + return markBuiltInUnwrapper( + async (recipients: readonly RecipientInfo[], signal?: AbortSignal): Promise => { + let attempts = 0 + for (const recipient of recipients) { + signal?.throwIfAborted() + if (recipient.alg !== ALG_A256KW) { + continue } - attempts++ - // Trusts its input: `recipients` comes from the decoder via - // `decryptWith`, already structurally validated. - const cek = await aesKwUnwrap(recipient.wrappedKey as Uint8Array, candidate.kekKey) - if (cek !== undefined) { - return cek + for (const candidate of selectCandidates(preparedKeys, recipient.kid)) { + signal?.throwIfAborted() + if (attempts === maxAttempts) { + throw new RecipientAttemptLimitError(`Recipient unwrap attempt limit reached: ${maxAttempts} attempts.`) + } + attempts++ + // Trusts its input: `recipients` comes from the decoder via + // `decryptWith`, already structurally validated. + const cek = await aesKwUnwrap(recipient.wrappedKey as Uint8Array, candidate.kekKey, signal) + if (signal?.aborted) { + cek?.fill(0) + throw signal.reason + } + if (cek !== undefined) { + return cek + } } } + signal?.throwIfAborted() + return undefined } - return undefined - } + ) } diff --git a/packages/filecoin-encryption-envelope/src/recipients/recover.ts b/packages/filecoin-encryption-envelope/src/recipients/recover.ts index 3a377afe6..96f909065 100644 --- a/packages/filecoin-encryption-envelope/src/recipients/recover.ts +++ b/packages/filecoin-encryption-envelope/src/recipients/recover.ts @@ -2,18 +2,40 @@ import { TAG_ENCRYPT0 } from '../cose/constants.ts' import type { DecodedEnvelope } from '../cose/decode.ts' import { NoUsableRecipientError, RecipientUnwrapError } from '../errors.ts' import { assertAes256Key } from '../internal/keys.ts' +import { importAesGcmKey } from '../internal/web-crypto.ts' import { toRecipientInfo } from './info.ts' import type { Unwrapper } from './types.ts' +/** + * Tracks built-in unwrappers created by this package so `recoverCekKey` can + * zero their temporary unwrapped CEK buffers after import or discard without + * ever mutating buffers returned by custom caller-supplied unwrappers. + */ +const builtInUnwrappers = new WeakSet() + +/** Mark `unwrapper` as returning package-owned CEK bytes. */ +export function markBuiltInUnwrapper(unwrapper: Unwrapper): Unwrapper { + builtInUnwrappers.add(unwrapper) + return unwrapper +} + /** * Recover and validate a CEK from a decoded envelope's recipients. * * For tag 96, calls `unwrapper` once with isolated copies of every recipient - * in wire order. A tag-16 envelope or an unmatched recipient list fails with - * `NoUsableRecipientError`; an unwrapper failure becomes - * `RecipientUnwrapError`. The returned key must be a nonzero 32-byte CEK. + * in wire order (forwarding `signal` when provided). A tag-16 envelope or an + * unmatched recipient list fails with `NoUsableRecipientError`; an unwrapper + * failure becomes `RecipientUnwrapError` unless `signal` aborted, in which + * case the exact `signal.reason` propagates. The returned key must be a + * nonzero 32-byte CEK. */ -export async function recoverCek(decoded: DecodedEnvelope, unwrapper: Unwrapper): Promise> { +async function recoverCek( + decoded: DecodedEnvelope, + unwrapper: Unwrapper, + ownedByPackage: boolean, + signal?: AbortSignal +): Promise> { + signal?.throwIfAborted() if (decoded.tag === TAG_ENCRYPT0) { throw new NoUsableRecipientError( 'No usable recipient: this envelope is COSE_Encrypt0 and carries no recipients; supply the CEK directly instead.' @@ -23,15 +45,54 @@ export async function recoverCek(decoded: DecodedEnvelope, unwrapper: Unwrapper) const infos = decoded.recipients.map(toRecipientInfo) let cek: Uint8Array | undefined try { - cek = await unwrapper(infos) + cek = signal === undefined ? await unwrapper(infos) : await unwrapper(infos, signal) } catch (cause) { + if (signal?.aborted) { + throw signal.reason + } throw new RecipientUnwrapError('Recipient key recovery failed.', { cause }) } + if (signal?.aborted) { + if (ownedByPackage && cek instanceof Uint8Array) { + cek.fill(0) + } + throw signal.reason + } if (cek === undefined) { throw new NoUsableRecipientError( `No usable recipient: none of the ${infos.length} recipients offered a usable key.` ) } - assertAes256Key(cek, 'recovered CEK') + try { + assertAes256Key(cek, 'recovered CEK') + } catch (cause) { + if (ownedByPackage && cek instanceof Uint8Array) { + cek.fill(0) + } + throw cause + } return cek } + +/** + * Recover, validate, and import the CEK as a non-extractable AES-GCM + * `CryptoKey`. When `unwrapper` is a built-in package unwrapper, zeroes the + * temporary raw CEK buffer once import completes or fails; custom unwrappers + * retain ownership of their returned buffer. + */ +export async function recoverCekKey( + decoded: DecodedEnvelope, + unwrapper: Unwrapper, + signal?: AbortSignal +): Promise { + const ownedByPackage = builtInUnwrappers.has(unwrapper) + const cek = await recoverCek(decoded, unwrapper, ownedByPackage, signal) + try { + signal?.throwIfAborted() + return await importAesGcmKey(cek, 'decrypt', false) + } finally { + if (ownedByPackage) { + cek.fill(0) + } + } +} diff --git a/packages/filecoin-encryption-envelope/src/recipients/types.ts b/packages/filecoin-encryption-envelope/src/recipients/types.ts index 384d31a1f..4cfca7e9b 100644 --- a/packages/filecoin-encryption-envelope/src/recipients/types.ts +++ b/packages/filecoin-encryption-envelope/src/recipients/types.ts @@ -45,7 +45,17 @@ export interface RecipientInfo { * Recover a CEK from an ordered, structurally validated recipient list. * * Return `undefined` when none of the recipients can be handled. Throwing - * aborts key recovery; `decryptWith` reports it as `RecipientUnwrapError` - * with the original error as its cause. + * aborts key recovery; `decryptWith`, `decryptRangeWith`, and + * `aesGcm.decryptWith` report it as `RecipientUnwrapError` with the original + * error as its cause, unless `signal` aborted. + * + * Ownership: for a custom unwrapper, FEE borrows the returned key bytes only + * long enough to import them into a non-extractable `CryptoKey` and never + * zeroes or mutates the caller's buffer. The caller owns every key it returns, + * including one FEE discards after cancellation (when `signal?.aborted` + * becomes `true` before recovery settles and FEE skips validation and import), + * and should zero it once the operation settles. When the built-in unwrapper + * from `createA256KWUnwrapper` is passed directly, FEE zeroes its own + * temporary unwrapped buffer after import or on abort/failure. */ -export type Unwrapper = (recipients: readonly RecipientInfo[]) => Promise +export type Unwrapper = (recipients: readonly RecipientInfo[], signal?: AbortSignal) => Promise diff --git a/packages/filecoin-encryption-envelope/test/abort-signal.test.ts b/packages/filecoin-encryption-envelope/test/abort-signal.test.ts new file mode 100644 index 000000000..49fa8f3d7 --- /dev/null +++ b/packages/filecoin-encryption-envelope/test/abort-signal.test.ts @@ -0,0 +1,2241 @@ +import assert from 'assert' +import { + type ChunkedEncryptOptions, + type DecryptOptions, + decrypt, + decryptWith, + encrypt, + type KeyResolver, +} from '../src/aes-gcm-stream.ts' +import { KEY_SIZE, MIN_CHUNK_SIZE, TAG_SIZE } from '../src/constants.ts' +import { decodeEnvelope } from '../src/cose/decode.ts' +import { + AuthenticationError, + ExcessCiphertextError, + InvalidRangeError, + InvalidSourceLengthError, + KeyResolutionError, + MalformedEnvelopeError, + NoUsableRecipientError, + RecipientUnwrapError, + TruncatedCiphertextError, +} from '../src/errors.ts' +import { decryptRange, decryptRangeWith, type RangeDecryptOptions } from '../src/range/decrypt.ts' +import { type ParseOptions, parse } from '../src/range/inspect.ts' +import { openExactRange, type RandomAccessSource, readEnvelope } from '../src/range/source.ts' +import { createA256KWUnwrapper } from '../src/recipients/index.ts' +import type { Unwrapper } from '../src/recipients/types.ts' +import { FIXED_CEK } from './aes-gcm-fixtures.ts' +import { deterministicPlaintext, readAllChunks, sourceOf } from './aes-gcm-stream-fixtures.ts' +import { concatBytes } from './cose-fixtures.ts' +import { neverCalledUnwrapper, pipeBytes, a256kwRecipient as recipient } from './helpers.ts' + +const CHUNK_SIZE = MIN_CHUNK_SIZE +const STRIDE = CHUNK_SIZE + TAG_SIZE +const KEK_A = Uint8Array.from({ length: KEY_SIZE }, (_, i) => 0x40 + i) +const KID_A = Uint8Array.from([0xa1, 0xa2]) +const KEK_B = Uint8Array.from({ length: KEY_SIZE }, (_, i) => 0x80 + i) +const KID_B = Uint8Array.from([0xb1, 0xb2]) + +function deferred(): { + promise: Promise + resolve: (value: T) => void + reject: (reason?: unknown) => void +} { + let resolveFn: ((value: T) => void) | undefined + let rejectFn: ((reason?: unknown) => void) | undefined + const promise = new Promise((res, rej) => { + resolveFn = res + rejectFn = rej + }) + return { + promise, + resolve: (value: T) => resolveFn?.(value), + reject: (reason?: unknown) => rejectFn?.(reason), + } +} + +/** Flush queued microtasks and a macrotask so any stray late work would surface. */ +function flushTasks(): Promise { + return new Promise((resolve) => setTimeout(resolve, 0)) +} + +async function encryptChunked(plaintext: Uint8Array, extra: Partial = {}): Promise { + return pipeBytes(encrypt({ cek: new Uint8Array(FIXED_CEK), chunkSize: CHUNK_SIZE, ...extra }), plaintext) +} + +function instrumentSignal(signal: AbortSignal, active: Set): void { + const originalAdd = signal.addEventListener.bind(signal) + const originalRemove = signal.removeEventListener.bind(signal) + + signal.addEventListener = (( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ) => { + if (type === 'abort') { + active.add(listener) + } + return originalAdd(type, listener, options) + }) as AbortSignal['addEventListener'] + + signal.removeEventListener = (( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ) => { + if (type === 'abort') { + active.delete(listener) + } + return originalRemove(type, listener, options) + }) as AbortSignal['removeEventListener'] +} + +/** + * Wrap an AbortController's signal so tests can count active `'abort'` + * listeners and prove none leak after operations settle. + */ +function trackedAbortController(): { + controller: AbortController + signal: AbortSignal + activeAbortListeners: () => number +} { + const controller = new AbortController() + const { signal } = controller + const active = new Set() + instrumentSignal(signal, active) + + return { controller, signal, activeAbortListeners: () => active.size } +} + +/** Spy on `crypto.subtle.importKey` calls for the duration of `fn`. */ +async function countImportKeyCalls(fn: (getCount: () => number) => Promise): Promise { + let calls = 0 + const original = globalThis.crypto.subtle.importKey + globalThis.crypto.subtle.importKey = ((...args: Parameters) => { + calls++ + return original.apply(globalThis.crypto.subtle, args) + }) as SubtleCrypto['importKey'] + try { + return await fn(() => calls) + } finally { + globalThis.crypto.subtle.importKey = original + } +} + +describe('AbortSignal support', () => { + describe('options validation', () => { + it('rejects non-object options on all four entry points', async () => { + const encoded = await encryptChunked(deterministicPlaintext(100), { recipients: [recipient(KEK_A, KID_A)] }) + const unwrapper = await createA256KWUnwrapper([{ kek: KEK_A, kid: KID_A }]) + + for (const bad of [null, 'nope', 42, []] as unknown[]) { + assert.throws(() => decrypt(new Uint8Array(FIXED_CEK), bad as DecryptOptions), MalformedEnvelopeError) + assert.throws(() => decryptWith(unwrapper, bad as DecryptOptions), MalformedEnvelopeError) + await assert.rejects( + decryptRange(encoded, new Uint8Array(FIXED_CEK), { offset: 0 }, bad as RangeDecryptOptions), + MalformedEnvelopeError + ) + await assert.rejects( + decryptRangeWith(encoded, unwrapper, { offset: 0 }, bad as RangeDecryptOptions), + MalformedEnvelopeError + ) + } + }) + + it('rejects non-AbortSignal values in options.signal on all four entry points', async () => { + const encoded = await encryptChunked(deterministicPlaintext(100), { recipients: [recipient(KEK_A, KID_A)] }) + const unwrapper = await createA256KWUnwrapper([{ kek: KEK_A, kid: KID_A }]) + + for (const badSignal of [ + null, + 'abort', + 123, + {}, + { aborted: false }, + Object.create(AbortSignal.prototype), + ] as unknown[]) { + assert.throws( + () => decrypt(new Uint8Array(FIXED_CEK), { signal: badSignal as AbortSignal }), + MalformedEnvelopeError + ) + assert.throws(() => decryptWith(unwrapper, { signal: badSignal as AbortSignal }), MalformedEnvelopeError) + await assert.rejects( + decryptRange(encoded, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal: badSignal as AbortSignal }), + MalformedEnvelopeError + ) + await assert.rejects( + decryptRangeWith(encoded, unwrapper, { offset: 0 }, { signal: badSignal as AbortSignal }), + MalformedEnvelopeError + ) + } + }) + + it('reads options.signal exactly once on each entry point', async () => { + const encoded = await encryptChunked(deterministicPlaintext(100), { recipients: [recipient(KEK_A, KID_A)] }) + const unwrapper = await createA256KWUnwrapper([{ kek: KEK_A, kid: KID_A }]) + + function countingOptions(): { options: DecryptOptions & RangeDecryptOptions; reads: () => number } { + let reads = 0 + const { signal } = new AbortController() + return { + options: { + get signal() { + reads++ + return signal + }, + }, + reads: () => reads, + } + } + + const o1 = countingOptions() + await pipeBytes(decrypt(new Uint8Array(FIXED_CEK), o1.options), encoded) + assert.strictEqual(o1.reads(), 1) + + const o2 = countingOptions() + await pipeBytes(decryptWith(unwrapper, o2.options), encoded) + assert.strictEqual(o2.reads(), 1) + + const o3 = countingOptions() + const r3 = await decryptRange(encoded, new Uint8Array(FIXED_CEK), { offset: 0 }, o3.options) + await readAllChunks(r3.stream) + assert.strictEqual(o3.reads(), 1) + + const o4 = countingOptions() + const r4 = await decryptRangeWith(encoded, unwrapper, { offset: 0 }, o4.options) + await readAllChunks(r4.stream) + assert.strictEqual(o4.reads(), 1) + }) + }) + + describe('pre-aborted signal on all four entry points', () => { + const reasons: Array<[string, () => unknown]> = [ + ['a custom Error', () => new Error('custom abort error')], + ['a string reason', () => 'cancelled by user'], + ['null reason', () => null], + ['default AbortError DOMException', () => undefined], + ] + + for (const [label, makeReason] of reasons) { + it(`decryptRange rejects immediately with exact signal.reason (${label}), without opening source or importing key`, async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2)) + const info = await parse(encoded) + assert.strictEqual(info.scheme, 'chunked') + if (info.scheme !== 'chunked') return + + let openCalls = 0 + const source: RandomAccessSource = { + size: encoded.length, + async openRange() { + openCalls++ + return sourceOf([]) + }, + } + + const controller = new AbortController() + const custom = makeReason() + if (custom === undefined) { + controller.abort() + } else { + controller.abort(custom) + } + const expectedReason = controller.signal.reason + + await countImportKeyCalls(async (getImportCalls) => { + await assert.rejects( + decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal: controller.signal }), + (err) => err === expectedReason + ) + await assert.rejects( + decryptRange( + source, + new Uint8Array(FIXED_CEK), + { offset: 0 }, + { params: info.params, signal: controller.signal } + ), + (err) => err === expectedReason + ) + assert.strictEqual(openCalls, 0) + assert.strictEqual(getImportCalls(), 0) + }) + }) + + it(`decryptRangeWith rejects immediately with exact signal.reason (${label}), without opening source or calling unwrapper`, async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2), { + recipients: [recipient(KEK_A, KID_A)], + }) + const info = await parse(encoded) + assert.strictEqual(info.scheme, 'chunked') + if (info.scheme !== 'chunked') return + + let openCalls = 0 + const source: RandomAccessSource = { + size: encoded.length, + async openRange() { + openCalls++ + return sourceOf([]) + }, + } + const { unwrapper, assertNeverCalled } = neverCalledUnwrapper() + + const controller = new AbortController() + const custom = makeReason() + if (custom === undefined) { + controller.abort() + } else { + controller.abort(custom) + } + const expectedReason = controller.signal.reason + + await countImportKeyCalls(async (getImportCalls) => { + await assert.rejects( + decryptRangeWith(source, unwrapper, { offset: 0 }, { signal: controller.signal }), + (err) => err === expectedReason + ) + await assert.rejects( + decryptRangeWith(source, unwrapper, { offset: 0 }, { params: info.params, signal: controller.signal }), + (err) => err === expectedReason + ) + assert.strictEqual(openCalls, 0) + assertNeverCalled() + assert.strictEqual(getImportCalls(), 0) + }) + }) + + it(`decrypt (direct CEK and KeyResolver) errors immediately with exact signal.reason (${label})`, async () => { + const encoded = await encryptChunked(deterministicPlaintext(200)) + const controller = new AbortController() + const custom = makeReason() + if (custom === undefined) { + controller.abort() + } else { + controller.abort(custom) + } + const expectedReason = controller.signal.reason + + let resolverCalls = 0 + const resolver: KeyResolver = () => { + resolverCalls++ + return new Uint8Array(FIXED_CEK) + } + + await countImportKeyCalls(async (getImportCalls) => { + for (const key of [new Uint8Array(FIXED_CEK), resolver] as const) { + const pair = decrypt(key, { signal: controller.signal }) + await assert.rejects(pair.readable.getReader().read(), (err) => err === expectedReason) + await assert.rejects(pair.writable.getWriter().write(encoded), (err) => err === expectedReason) + + const upstreamCancelled = deferred() + const upstream = new ReadableStream( + { + pull(c) { + c.enqueue(encoded) + }, + cancel(reason) { + upstreamCancelled.resolve(reason) + }, + }, + { highWaterMark: 0 } + ) + const piped = upstream.pipeThrough(decrypt(key, { signal: controller.signal })) + await assert.rejects(readAllChunks(piped), (err) => err === expectedReason) + assert.strictEqual(await upstreamCancelled.promise, expectedReason) + } + assert.strictEqual(resolverCalls, 0) + assert.strictEqual(getImportCalls(), 0) + }) + }) + + it(`decryptWith errors immediately with exact signal.reason (${label}), without calling unwrapper`, async () => { + const encoded = await encryptChunked(deterministicPlaintext(200), { + recipients: [recipient(KEK_A, KID_A)], + }) + const controller = new AbortController() + const custom = makeReason() + if (custom === undefined) { + controller.abort() + } else { + controller.abort(custom) + } + const expectedReason = controller.signal.reason + + const { unwrapper, assertNeverCalled } = neverCalledUnwrapper() + + await countImportKeyCalls(async (getImportCalls) => { + const pair = decryptWith(unwrapper, { signal: controller.signal }) + await assert.rejects(pair.readable.getReader().read(), (err) => err === expectedReason) + await assert.rejects(pair.writable.getWriter().write(encoded), (err) => err === expectedReason) + + const upstreamCancelled = deferred() + const upstream = new ReadableStream( + { + pull(c) { + c.enqueue(encoded) + }, + cancel(reason) { + upstreamCancelled.resolve(reason) + }, + }, + { highWaterMark: 0 } + ) + const piped = upstream.pipeThrough(decryptWith(unwrapper, { signal: controller.signal })) + await assert.rejects(readAllChunks(piped), (err) => err === expectedReason) + assert.strictEqual(await upstreamCancelled.promise, expectedReason) + + assertNeverCalled() + assert.strictEqual(getImportCalls(), 0) + }) + }) + } + }) + + describe('decryptRange and decryptRangeWith setup aborts', () => { + it('forwards signal to openRange, rejects promptly on abort while openRange hangs, and cancels late stream', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2)) + const openStarted = deferred() + const openGate = deferred>() + const lateCancelled = deferred() + let receivedSignal: AbortSignal | undefined + + const source: RandomAccessSource = { + size: encoded.length, + openRange(_offset, _length, signal) { + receivedSignal = signal + openStarted.resolve() + return openGate.promise + }, + } + + const { controller, signal, activeAbortListeners } = trackedAbortController() + const pending = decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal }) + await openStarted.promise + assert.strictEqual(receivedSignal, signal) + + const reason = new Error('abort during pending envelope open') + controller.abort(reason) + await assert.rejects(pending, (err) => err === reason) + assert.strictEqual(activeAbortListeners(), 0) + + // Source ignores signal and resolves late: late stream must still be cancelled. + openGate.resolve( + new ReadableStream({ + cancel(cancelReason) { + lateCancelled.resolve(cancelReason) + }, + }) + ) + assert.strictEqual(await lateCancelled.promise, reason) + }) + + it('aborts during a multi-span envelope read without opening subsequent spans and cancels active span stream', async () => { + // Envelope larger than 4096 bytes so readEnvelope probes multiple spans. + const encoded = await encryptChunked(deterministicPlaintext(100), { + appMetadata: { note: 'x'.repeat(14800) }, + }) + const firstBlockSent = deferred() + const secondBlockGate = deferred() + const spanCancelled = deferred() + const openCalls: Array<{ offset: number; length: number; signal: AbortSignal | undefined }> = [] + + const source: RandomAccessSource = { + size: encoded.length, + async openRange(offset, length, signal) { + openCalls.push({ offset, length, signal }) + const slice = encoded.subarray(offset, offset + length) + let step = 0 + return new ReadableStream( + { + async pull(streamController) { + if (step === 0) { + step++ + streamController.enqueue(slice.subarray(0, 128)) + firstBlockSent.resolve() + return + } + await secondBlockGate.promise + streamController.enqueue(slice.subarray(128)) + streamController.close() + }, + cancel(cancelReason) { + spanCancelled.resolve(cancelReason) + }, + }, + { highWaterMark: 0 } + ) + }, + } + + const { controller, signal, activeAbortListeners } = trackedAbortController() + const pending = decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal }) + await firstBlockSent.promise + + const reason = new Error('abort mid-envelope read') + controller.abort(reason) + await assert.rejects(pending, (err) => err === reason) + assert.strictEqual(await spanCancelled.promise, reason) + assert.strictEqual(openCalls.length, 1) + assert.strictEqual(openCalls[0].signal, signal) + assert.strictEqual(activeAbortListeners(), 0) + + secondBlockGate.resolve() + await flushTasks() + }) + + it('rejects promptly on abort during pending unwrapper in decryptRangeWith, discards late key without import, and preserves signal.reason', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2), { + recipients: [recipient(KEK_A, KID_A)], + }) + const info = await parse(encoded) + assert.strictEqual(info.scheme, 'chunked') + if (info.scheme !== 'chunked') return + + const unwrapperEntered = deferred() + const unwrapperGate = deferred() + let seenSignal: AbortSignal | undefined + + const unwrapper: Unwrapper = async (_recipients, signal) => { + seenSignal = signal + unwrapperEntered.resolve() + return unwrapperGate.promise + } + + const { controller, signal, activeAbortListeners } = trackedAbortController() + await countImportKeyCalls(async (getImportCalls) => { + const pending = decryptRangeWith(encoded, unwrapper, { offset: 0 }, { params: info.params, signal }) + await unwrapperEntered.promise + assert.strictEqual(seenSignal, signal) + + const reason = new Error('abort while unwrapper pending') + controller.abort(reason) + await assert.rejects(pending, (err) => err === reason) + assert.strictEqual(activeAbortListeners(), 0) + + // Unwrapper ignores signal and resolves late with a valid CEK: must NOT be imported. + unwrapperGate.resolve(new Uint8Array(FIXED_CEK)) + await flushTasks() + assert.strictEqual(getImportCalls(), 0) + }) + }) + + it('does not wrap an unwrapper rejection in RecipientUnwrapError when signal aborted', async () => { + const encoded = await encryptChunked(deterministicPlaintext(200), { + recipients: [recipient(KEK_A, KID_A)], + }) + const { controller, signal } = trackedAbortController() + const reason = new Error('abort inside unwrapper') + const unwrapper: Unwrapper = async (_recipients, sig) => { + controller.abort(reason) + throw sig?.reason ?? new Error('unexpected') + } + + await assert.rejects(decryptRangeWith(encoded, unwrapper, { offset: 0 }, { signal }), (err) => err === reason) + }) + + it('built-in createA256KWUnwrapper stops remaining attempts when signal aborts', async () => { + const encoded = await encryptChunked(deterministicPlaintext(200), { + recipients: [recipient(KEK_A, KID_A), recipient(KEK_B, KID_B)], + }) + const wrongKey1 = Uint8Array.from({ length: KEY_SIZE }, (_, i) => 0x10 + i) + const wrongKey2 = Uint8Array.from({ length: KEY_SIZE }, (_, i) => 0x20 + i) + const unwrapper = await createA256KWUnwrapper([{ kek: wrongKey1 }, { kek: wrongKey2 }, { kek: KEK_B }]) + + const controller = new AbortController() + const reason = new Error('abort during a256kw unwrap loop') + let unwrapCalls = 0 + const originalUnwrapKey = globalThis.crypto.subtle.unwrapKey + globalThis.crypto.subtle.unwrapKey = ((...args: Parameters) => { + unwrapCalls++ + if (unwrapCalls === 1) { + controller.abort(reason) + } + return originalUnwrapKey.apply(globalThis.crypto.subtle, args) + }) as SubtleCrypto['unwrapKey'] + + try { + await assert.rejects( + decryptRangeWith(encoded, unwrapper, { offset: 0 }, { signal: controller.signal }), + (err) => err === reason + ) + await flushTasks() + assert.strictEqual(unwrapCalls, 1) + } finally { + globalThis.crypto.subtle.unwrapKey = originalUnwrapKey + } + }) + }) + + describe('decryptRange and decryptRangeWith aborts after RangeResult is returned', () => { + it('errors the returned stream immediately if aborted before the first read, never opening ciphertext span', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2)) + const info = await parse(encoded) + assert.strictEqual(info.scheme, 'chunked') + if (info.scheme !== 'chunked') return + + let openCalls = 0 + const source: RandomAccessSource = { + size: encoded.length, + async openRange() { + openCalls++ + return sourceOf([]) + }, + } + + const { controller, signal, activeAbortListeners } = trackedAbortController() + const result = await decryptRange( + source, + new Uint8Array(FIXED_CEK), + { offset: 0 }, + { params: info.params, signal } + ) + assert.strictEqual(activeAbortListeners(), 1) + + const reason = new Error('abort before first range read') + controller.abort(reason) + assert.strictEqual(activeAbortListeners(), 0) + + await assert.rejects(result.stream.getReader().read(), (err) => err === reason) + assert.strictEqual(openCalls, 0) + }) + + it('rejects promptly when aborted during pending lazy ciphertext openRange and cancels late stream', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2)) + const info = await parse(encoded) + assert.strictEqual(info.scheme, 'chunked') + if (info.scheme !== 'chunked') return + + const openStarted = deferred() + const openGate = deferred>() + const lateCancelled = deferred() + let seenSignal: AbortSignal | undefined + + const source: RandomAccessSource = { + size: encoded.length, + openRange(_offset, _length, signal) { + seenSignal = signal + openStarted.resolve() + return openGate.promise + }, + } + + const { controller, signal, activeAbortListeners } = trackedAbortController() + const result = await decryptRange( + source, + new Uint8Array(FIXED_CEK), + { offset: 0 }, + { params: info.params, signal } + ) + const pendingRead = result.stream.getReader().read() + await openStarted.promise + assert.ok(seenSignal instanceof AbortSignal) + assert.strictEqual(seenSignal.aborted, false) + + const reason = new Error('abort during lazy ciphertext open') + controller.abort(reason) + await assert.rejects(pendingRead, (err) => err === reason) + assert.strictEqual(seenSignal.aborted, true) + assert.strictEqual(seenSignal.reason, reason) + assert.strictEqual(activeAbortListeners(), 0) + + openGate.resolve( + new ReadableStream({ + cancel(cancelReason) { + lateCancelled.resolve(cancelReason) + }, + }) + ) + assert.strictEqual(await lateCancelled.promise, reason) + }) + + it('errors an already-open range stream while reading chunk 1, cancels the source, and emits no post-abort plaintext', async () => { + const plaintext = deterministicPlaintext(CHUNK_SIZE * 3) + const encoded = await encryptChunked(plaintext, { recipients: [recipient(KEK_A, KID_A)] }) + const unwrapper = await createA256KWUnwrapper([{ kek: KEK_A, kid: KID_A }]) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + + for (const mode of ['direct', 'with'] as const) { + const chunk1Started = deferred() + const chunk1Gate = deferred() + let cancelReason: unknown = Symbol('not-cancelled') + let seenSignal: AbortSignal | undefined + + const source: RandomAccessSource = { + size: encoded.length, + async openRange(offset, length, signal) { + seenSignal = signal + const slice = encoded.subarray(offset, offset + length) + if (offset < envelopeLength) { + return sourceOf([slice]) + } + let chunkIndex = 0 + return new ReadableStream( + { + async pull(streamController) { + if (chunkIndex === 0) { + chunkIndex++ + streamController.enqueue(slice.subarray(0, STRIDE)) + return + } + chunk1Started.resolve() + await chunk1Gate.promise + streamController.enqueue(slice.subarray(STRIDE)) + streamController.close() + }, + cancel(reason) { + cancelReason = reason + }, + }, + { highWaterMark: 0 } + ) + }, + } + + const { controller, signal, activeAbortListeners } = trackedAbortController() + const result = + mode === 'direct' + ? await decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal }) + : await decryptRangeWith(source, unwrapper, { offset: 0 }, { signal }) + + const reader = result.stream.getReader() + const first = await reader.read() + assert.strictEqual(first.done, false) + assert.deepStrictEqual(first.value, plaintext.subarray(0, CHUNK_SIZE)) + assert.ok(seenSignal instanceof AbortSignal) + assert.strictEqual(seenSignal.aborted, false) + + const secondRead = reader.read() + await chunk1Started.promise + + const reason = new Error(`abort active range stream (${mode})`) + controller.abort(reason) + await assert.rejects(secondRead, (err) => err === reason) + assert.strictEqual(seenSignal.aborted, true) + assert.strictEqual(seenSignal.reason, reason) + assert.strictEqual(cancelReason, reason) + assert.strictEqual(activeAbortListeners(), 0) + + chunk1Gate.resolve() + await flushTasks() + } + }) + + it('cancels an already-open range source immediately when aborted while idle between reads', async () => { + const plaintext = deterministicPlaintext(CHUNK_SIZE * 3) + const encoded = await encryptChunked(plaintext) + const info = await parse(encoded) + assert.strictEqual(info.scheme, 'chunked') + if (info.scheme !== 'chunked') return + + let cancelReason: unknown = Symbol('not-cancelled') + // Intentionally a 2-argument adapter (ignores signal). + const source: RandomAccessSource = { + size: encoded.length, + async openRange(offset, length) { + const slice = encoded.subarray(offset, offset + length) + let sent = 0 + return new ReadableStream( + { + pull(streamController) { + if (sent >= slice.length) { + streamController.close() + return + } + const next = Math.min(sent + STRIDE, slice.length) + streamController.enqueue(slice.subarray(sent, next)) + sent = next + }, + cancel(reason) { + cancelReason = reason + }, + }, + { highWaterMark: 0 } + ) + }, + } + + const { controller, signal, activeAbortListeners } = trackedAbortController() + const result = await decryptRange( + source, + new Uint8Array(FIXED_CEK), + { offset: 0 }, + { params: info.params, signal } + ) + const reader = result.stream.getReader() + + // Read chunk 0, then stay idle before reading chunk 1. + const first = await reader.read() + assert.strictEqual(first.done, false) + assert.deepStrictEqual(first.value, plaintext.subarray(0, CHUNK_SIZE)) + + const reason = new Error('abort idle open range stream') + controller.abort(reason) + // Source stream is cancelled right away without waiting for another read(). + assert.strictEqual(cancelReason, reason) + assert.strictEqual(activeAbortListeners(), 0) + + await assert.rejects(reader.read(), (err) => err === reason) + }) + + it('emits no plaintext when aborted while crypto.subtle.decrypt is in flight on a range stream', async () => { + const plaintext = deterministicPlaintext(CHUNK_SIZE * 2) + const encoded = await encryptChunked(plaintext) + const decryptEntered = deferred() + const decryptGate = deferred() + + const originalDecrypt = globalThis.crypto.subtle.decrypt + globalThis.crypto.subtle.decrypt = (async (...args: Parameters) => { + decryptEntered.resolve() + await decryptGate.promise + return originalDecrypt.apply(globalThis.crypto.subtle, args) + }) as SubtleCrypto['decrypt'] + + try { + const { controller, signal, activeAbortListeners } = trackedAbortController() + const result = await decryptRange(encoded, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal }) + const reader = result.stream.getReader() + const pendingRead = reader.read() + await decryptEntered.promise + + const reason = new Error('abort mid-decrypt') + controller.abort(reason) + await assert.rejects(pendingRead, (err) => err === reason) + assert.strictEqual(activeAbortListeners(), 0) + + decryptGate.resolve() + await flushTasks() + } finally { + globalThis.crypto.subtle.decrypt = originalDecrypt + } + }) + }) + + describe('decrypt and decryptWith active stream aborts', () => { + it('errors both sides and unblocks a pending write when aborted before envelope completes', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2)) + const { controller, signal, activeAbortListeners } = trackedAbortController() + const { writable, readable } = decrypt(new Uint8Array(FIXED_CEK), { signal }) + + const writer = writable.getWriter() + const reader = readable.getReader() + await writer.write(encoded.subarray(0, 4)) // partial envelope + + const pendingRead = reader.read() + const reason = new Error('abort during envelope intake') + controller.abort(reason) + + await assert.rejects(pendingRead, (err) => err === reason) + await assert.rejects(writer.write(encoded.subarray(4, 10)), (err) => err === reason) + assert.strictEqual(activeAbortListeners(), 0) + }) + + it('unblocks a backpressured write immediately on abort', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 3)) + const { controller, signal, activeAbortListeners } = trackedAbortController() + const { writable, readable } = decrypt(new Uint8Array(FIXED_CEK), { signal }) + + const writer = writable.getWriter() + // Writing multiple chunks without a reader leaves write() pending on framer backpressure. + const pendingWrite = writer.write(encoded) + await flushTasks() + + const reason = new Error('abort while write is backpressured') + controller.abort(reason) + + await assert.rejects(pendingWrite, (err) => err === reason) + await assert.rejects(readable.getReader().read(), (err) => err === reason) + assert.strictEqual(activeAbortListeners(), 0) + }) + + it('aborts decrypt while KeyResolver is pending, aborts resolver signal with reason, unblocks write, and discards late key without import', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 3)) + const resolverEntered = deferred() + const resolverGate = deferred() + let seenSignal: AbortSignal | undefined + + const resolver: KeyResolver = async (_info, sig) => { + seenSignal = sig + resolverEntered.resolve() + return resolverGate.promise + } + + const { controller, signal, activeAbortListeners } = trackedAbortController() + await countImportKeyCalls(async (getImportCalls) => { + const { writable, readable } = decrypt(resolver, { signal }) + const writer = writable.getWriter() + const reader = readable.getReader() + + const pendingWrite = writer.write(encoded) + pendingWrite.catch(() => undefined) + const pendingRead = reader.read() + await resolverEntered.promise + assert.ok(seenSignal instanceof AbortSignal) + assert.strictEqual(seenSignal.aborted, false) + + const reason = new Error('abort while KeyResolver pending') + controller.abort(reason) + + await assert.rejects(pendingRead, (err) => err === reason) + await assert.rejects(pendingWrite, (err) => err === reason) + assert.strictEqual(seenSignal.aborted, true) + assert.strictEqual(seenSignal.reason, reason) + assert.strictEqual(activeAbortListeners(), 0) + + // Resolver ignores signal and resolves late: key must not be imported or zeroed. + const lateKey = new Uint8Array(FIXED_CEK) + const lateKeySnapshot = new Uint8Array(lateKey) + resolverGate.resolve(lateKey) + await flushTasks() + assert.strictEqual(getImportCalls(), 0) + assert.deepStrictEqual(lateKey, lateKeySnapshot) + }) + }) + + it('aborts the KeyResolver signal on reader cancel even when options.signal stays unaborted, cleaning up listeners', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2)) + const resolverEntered = deferred() + let seenSignal: AbortSignal | undefined + + const resolver: KeyResolver = (_info, sig) => { + seenSignal = sig + resolverEntered.resolve() + return new Promise(() => { + // Stays pending until cancel. + }) + } + + const { signal, activeAbortListeners } = trackedAbortController() + const { writable, readable } = decrypt(resolver, { signal }) + const writer = writable.getWriter() + await writer.write(encoded.subarray(0, decodeEnvelope(encoded).envelopeLength)) + + const reader = readable.getReader() + const pendingRead = reader.read() + await resolverEntered.promise + + const cancelReason = new Error('cancel with unaborted options.signal') + await reader.cancel(cancelReason) + await pendingRead + + assert.ok(seenSignal instanceof AbortSignal) + assert.strictEqual(seenSignal.aborted, true) + assert.strictEqual(seenSignal.reason, cancelReason) + assert.strictEqual(signal.aborted, false) + assert.strictEqual(activeAbortListeners(), 0) + }) + + it('does not wrap KeyResolver rejection in KeyResolutionError when signal aborted', async () => { + const encoded = await encryptChunked(deterministicPlaintext(100)) + const { controller, signal } = trackedAbortController() + const reason = new Error('abort inside KeyResolver') + const resolver: KeyResolver = (_info, sig) => { + controller.abort(reason) + throw sig.reason + } + + await assert.rejects(pipeBytes(decrypt(resolver, { signal }), encoded), (err) => err === reason) + }) + + it('aborts decryptWith while Unwrapper is pending, aborts unwrapper signal with reason, unblocks write, and discards late key without import', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 3), { + recipients: [recipient(KEK_A, KID_A)], + }) + const unwrapperEntered = deferred() + const unwrapperGate = deferred() + let seenSignal: AbortSignal | undefined + + const unwrapper: Unwrapper = async (_recipients, sig) => { + seenSignal = sig + unwrapperEntered.resolve() + return unwrapperGate.promise + } + + const { controller, signal, activeAbortListeners } = trackedAbortController() + await countImportKeyCalls(async (getImportCalls) => { + const { writable, readable } = decryptWith(unwrapper, { signal }) + const writer = writable.getWriter() + const reader = readable.getReader() + + const pendingWrite = writer.write(encoded) + pendingWrite.catch(() => undefined) + const pendingRead = reader.read() + await unwrapperEntered.promise + assert.ok(seenSignal instanceof AbortSignal) + assert.strictEqual(seenSignal.aborted, false) + + const reason = new Error('abort while Unwrapper pending') + controller.abort(reason) + + await assert.rejects(pendingRead, (err) => err === reason) + await assert.rejects(pendingWrite, (err) => err === reason) + assert.strictEqual(seenSignal.aborted, true) + assert.strictEqual(seenSignal.reason, reason) + assert.strictEqual(activeAbortListeners(), 0) + + // Unwrapper ignores signal and resolves late: key must not be imported or zeroed. + const lateKey = new Uint8Array(FIXED_CEK) + const lateKeySnapshot = new Uint8Array(lateKey) + unwrapperGate.resolve(lateKey) + await flushTasks() + assert.strictEqual(getImportCalls(), 0) + assert.deepStrictEqual(lateKey, lateKeySnapshot) + }) + }) + + it('aborts active decrypt and decryptWith mid-stream after chunk 0, cancelling upstream source and emitting no further plaintext', async () => { + const plaintext = deterministicPlaintext(CHUNK_SIZE * 3) + const encoded = await encryptChunked(plaintext, { recipients: [recipient(KEK_A, KID_A)] }) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + const unwrapper = await createA256KWUnwrapper([{ kek: KEK_A, kid: KID_A }]) + + for (const mode of ['decrypt', 'decryptWith'] as const) { + const chunk1Requested = deferred() + const upstreamCancelled = deferred() + let step = 0 + const upstream = new ReadableStream( + { + pull(streamController) { + if (step === 0) { + step++ + // Deliver envelope + chunk 0 + first byte of chunk 1 so chunk 0 is known non-final. + streamController.enqueue(encoded.subarray(0, envelopeLength + STRIDE + 1)) + return + } + // Leave the stream open with no data yet so cancel() fires immediately on abort. + chunk1Requested.resolve() + }, + cancel(reason) { + upstreamCancelled.resolve(reason) + }, + }, + { highWaterMark: 0 } + ) + + const { controller, signal, activeAbortListeners } = trackedAbortController() + const transform = + mode === 'decrypt' ? decrypt(new Uint8Array(FIXED_CEK), { signal }) : decryptWith(unwrapper, { signal }) + const reader = upstream.pipeThrough(transform).getReader() + + const first = await reader.read() + assert.strictEqual(first.done, false) + assert.deepStrictEqual(first.value, plaintext.subarray(0, CHUNK_SIZE)) + + const secondRead = reader.read() + await chunk1Requested.promise + + const reason = new Error(`abort active ${mode} mid-stream`) + controller.abort(reason) + await assert.rejects(secondRead, (err) => err === reason) + assert.strictEqual(await upstreamCancelled.promise, reason) + assert.strictEqual(activeAbortListeners(), 0) + } + }) + + it('emits no plaintext when aborted while crypto.subtle.decrypt is in flight on decrypt()', async () => { + const plaintext = deterministicPlaintext(CHUNK_SIZE * 2) + const encoded = await encryptChunked(plaintext) + const decryptEntered = deferred() + const decryptGate = deferred() + + const originalDecrypt = globalThis.crypto.subtle.decrypt + globalThis.crypto.subtle.decrypt = (async (...args: Parameters) => { + decryptEntered.resolve() + await decryptGate.promise + return originalDecrypt.apply(globalThis.crypto.subtle, args) + }) as SubtleCrypto['decrypt'] + + try { + const { controller, signal, activeAbortListeners } = trackedAbortController() + const { writable, readable } = decrypt(new Uint8Array(FIXED_CEK), { signal }) + const writer = writable.getWriter() + const writeDone = writer.write(encoded) + writeDone.catch(() => undefined) + const closeDone = writer.close() + closeDone.catch(() => undefined) + + const pendingRead = readable.getReader().read() + await decryptEntered.promise + + const reason = new Error('abort mid-stream decrypt') + controller.abort(reason) + await assert.rejects(pendingRead, (err) => err === reason) + assert.strictEqual(activeAbortListeners(), 0) + + decryptGate.resolve() + await flushTasks() + } finally { + globalThis.crypto.subtle.decrypt = originalDecrypt + } + }) + }) + + describe('non-abort behavior, backward compatibility, and listener cleanup', () => { + it('omits trailing undefined signal for setup openRange/decryptRangeWith and passes an AbortSignal to streaming callbacks', async () => { + const plaintext = deterministicPlaintext(200) + const encoded = await encryptChunked(plaintext, { recipients: [recipient(KEK_A, KID_A)] }) + const realUnwrapper = await createA256KWUnwrapper([{ kek: KEK_A, kid: KID_A }]) + + const openRangeArgCounts: number[] = [] + let ciphertextSignal: AbortSignal | undefined + const source: RandomAccessSource = { + size: encoded.length, + async openRange(...args) { + openRangeArgCounts.push(args.length) + if (args.length === 3) { + ciphertextSignal = args[2] + } + return sourceOf([encoded.subarray(args[0], args[0] + args[1])]) + }, + } + const rangeRes = await decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }) + assert.deepStrictEqual(concatBytes(...(await readAllChunks(rangeRes.stream))), plaintext) + // Envelope read (setup) omits signal when none is supplied; ciphertext stream supplies its cancel-aware signal. + assert.deepStrictEqual(openRangeArgCounts, [2, 3]) + assert.ok(ciphertextSignal instanceof AbortSignal) + assert.strictEqual(ciphertextSignal.aborted, false) + + let rangeUnwrapperArgCount = -1 + const rangeUnwrapper: Unwrapper = async (...args) => { + rangeUnwrapperArgCount = args.length + return realUnwrapper(args[0]) + } + const rangeWithRes = await decryptRangeWith(encoded, rangeUnwrapper, { offset: 0 }) + assert.deepStrictEqual(concatBytes(...(await readAllChunks(rangeWithRes.stream))), plaintext) + assert.strictEqual(rangeUnwrapperArgCount, 1) + + let resolverArgCount = -1 + let resolverSignal: AbortSignal | undefined + const resolver: KeyResolver = (...args) => { + resolverArgCount = args.length + resolverSignal = args[1] + return new Uint8Array(FIXED_CEK) + } + assert.deepStrictEqual(await pipeBytes(decrypt(resolver), encoded), plaintext) + assert.strictEqual(resolverArgCount, 2) + assert.ok(resolverSignal instanceof AbortSignal) + assert.strictEqual(resolverSignal.aborted, false) + + let unwrapperArgCount = -1 + let unwrapperSignal: AbortSignal | undefined + const unwrapper: Unwrapper = async (...args) => { + unwrapperArgCount = args.length + unwrapperSignal = args[1] + return realUnwrapper(args[0]) + } + assert.deepStrictEqual(await pipeBytes(decryptWith(unwrapper), encoded), plaintext) + assert.strictEqual(unwrapperArgCount, 2) + assert.ok(unwrapperSignal instanceof AbortSignal) + assert.strictEqual(unwrapperSignal.aborted, false) + }) + + it('preserves existing error wrappers when failures occur while an unaborted signal is active', async () => { + const encoded = await encryptChunked(deterministicPlaintext(200), { + recipients: [recipient(KEK_A, KID_A)], + }) + const tag16 = await encryptChunked(deterministicPlaintext(200)) + const wrongCek = Uint8Array.from(FIXED_CEK, (b) => b ^ 0xff) + const boom = new Error('boom') + + const { signal, activeAbortListeners } = trackedAbortController() + + // KeyResolutionError + await assert.rejects( + pipeBytes( + decrypt( + async () => { + throw boom + }, + { signal } + ), + encoded + ), + (err: unknown) => err instanceof KeyResolutionError && err.cause === boom + ) + assert.strictEqual(activeAbortListeners(), 0) + + // RecipientUnwrapError (stream + range) + await assert.rejects( + pipeBytes( + decryptWith( + async () => { + throw boom + }, + { signal } + ), + encoded + ), + (err: unknown) => err instanceof RecipientUnwrapError && err.cause === boom + ) + assert.strictEqual(activeAbortListeners(), 0) + + await assert.rejects( + decryptRangeWith( + encoded, + async () => { + throw boom + }, + { offset: 0 }, + { signal } + ), + (err: unknown) => err instanceof RecipientUnwrapError && err.cause === boom + ) + assert.strictEqual(activeAbortListeners(), 0) + + // NoUsableRecipientError (tag-16) + await assert.rejects( + decryptRangeWith(tag16, async () => new Uint8Array(FIXED_CEK), { offset: 0 }, { signal }), + NoUsableRecipientError + ) + assert.strictEqual(activeAbortListeners(), 0) + + // AuthenticationError (stream + range) + await assert.rejects(pipeBytes(decrypt(wrongCek, { signal }), encoded), AuthenticationError) + assert.strictEqual(activeAbortListeners(), 0) + + const badRange = await decryptRange(encoded, wrongCek, { offset: 0 }, { signal }) + await assert.rejects(readAllChunks(badRange.stream), AuthenticationError) + assert.strictEqual(activeAbortListeners(), 0) + + // InvalidRangeError + await assert.rejects( + decryptRange(encoded, new Uint8Array(FIXED_CEK), { offset: -1, length: 5 }, { signal }), + InvalidRangeError + ) + assert.strictEqual(activeAbortListeners(), 0) + + // Transport error from source.openRange propagates unchanged + const transportError = new Error('network down') + const failingSource: RandomAccessSource = { + size: encoded.length, + openRange: () => Promise.reject(transportError), + } + await assert.rejects( + decryptRange(failingSource, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal }), + (err) => err === transportError + ) + assert.strictEqual(activeAbortListeners(), 0) + }) + + it('cleans up abort listeners on normal completion, consumer cancel, and writable abort', async () => { + const plaintext = deterministicPlaintext(CHUNK_SIZE * 2) + const encoded = await encryptChunked(plaintext, { recipients: [recipient(KEK_A, KID_A)] }) + const unwrapper = await createA256KWUnwrapper([{ kek: KEK_A, kid: KID_A }]) + const { signal, activeAbortListeners } = trackedAbortController() + + // Normal completion across all four entry points. + assert.deepStrictEqual(await pipeBytes(decrypt(new Uint8Array(FIXED_CEK), { signal }), encoded), plaintext) + assert.strictEqual(activeAbortListeners(), 0) + + assert.deepStrictEqual(await pipeBytes(decryptWith(unwrapper, { signal }), encoded), plaintext) + assert.strictEqual(activeAbortListeners(), 0) + + const range1 = await decryptRange(encoded, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal }) + assert.deepStrictEqual(concatBytes(...(await readAllChunks(range1.stream))), plaintext) + assert.strictEqual(activeAbortListeners(), 0) + + const range2 = await decryptRangeWith(encoded, unwrapper, { offset: 0 }, { signal }) + assert.deepStrictEqual(concatBytes(...(await readAllChunks(range2.stream))), plaintext) + assert.strictEqual(activeAbortListeners(), 0) + + // Consumer reader.cancel() on range stream and decrypt stream. + const range3 = await decryptRange(encoded, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal }) + await range3.stream.getReader().cancel(new Error('done early')) + assert.strictEqual(activeAbortListeners(), 0) + + const stream1 = decrypt(new Uint8Array(FIXED_CEK), { signal }) + await stream1.readable.getReader().cancel(new Error('done early')) + assert.strictEqual(activeAbortListeners(), 0) + + // Writable writer.abort() on decrypt stream. + const stream2 = decrypt(new Uint8Array(FIXED_CEK), { signal }) + await stream2.writable.getWriter().abort(new Error('writer stopped')) + assert.strictEqual(activeAbortListeners(), 0) + }) + + it('openExactRange and readEnvelope reject with exact signal.reason and clean up listeners', async () => { + const encoded = await encryptChunked(deterministicPlaintext(200)) + const { controller, signal, activeAbortListeners } = trackedAbortController() + + // Pre-aborted readEnvelope and openExactRange. + const reason = new Error('already aborted') + controller.abort(reason) + let openCalls = 0 + const source: RandomAccessSource = { + size: encoded.length, + async openRange() { + openCalls++ + return sourceOf([]) + }, + } + await assert.rejects(readEnvelope(source, signal), (err) => err === reason) + const range = openExactRange(source, 0, 10, signal) + await assert.rejects(range.read(), (err) => err === reason) + assert.strictEqual(openCalls, 0) + assert.strictEqual(activeAbortListeners(), 0) + }) + }) + + describe('edge cases: hung cancel, short EOF, event spoofing, re-entrancy, A256KW zeroing, parse, and cross-realm signals', () => { + it('parse and decryptRange without cached params settle promptly without waiting on a hung source cancel() after envelope decode', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2)) + + for (const mode of ['parse', 'decryptRange-no-signal', 'decryptRange-live-signal'] as const) { + const cancelEntered = deferred() + const cancelGate = deferred() + const source: RandomAccessSource = { + size: encoded.length, + async openRange(offset, length) { + const slice = encoded.subarray(offset, offset + length) + return new ReadableStream({ + start(streamController) { + streamController.enqueue(slice) + }, + async cancel() { + cancelEntered.resolve() + await cancelGate.promise + }, + }) + }, + } + + if (mode === 'parse') { + const info = await parse(source) + assert.strictEqual(info.scheme, 'chunked') + } else if (mode === 'decryptRange-no-signal') { + const result = await decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }) + assert.strictEqual(result.totalPlaintextLength, CHUNK_SIZE * 2) + } else { + const { signal, activeAbortListeners } = trackedAbortController() + const result = await decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal }) + assert.strictEqual(result.totalPlaintextLength, CHUNK_SIZE * 2) + assert.strictEqual(activeAbortListeners(), 1) + await result.stream.cancel() + assert.strictEqual(activeAbortListeners(), 0) + } + + await cancelEntered.promise + cancelGate.resolve() + await flushTasks() + } + }) + + it('decryptRange rejects immediately with InvalidSourceLengthError on oversized block without waiting on a hung source cancel()', async () => { + const encoded = await encryptChunked(deterministicPlaintext(200)) + const cancelEntered = deferred() + const cancelGate = deferred() + + const source: RandomAccessSource = { + size: encoded.length, + async openRange(_offset, length) { + return new ReadableStream({ + start(streamController) { + // Oversized block (> requested length) triggers InvalidSourceLengthError + cancel(). + streamController.enqueue(new Uint8Array(length + 10)) + }, + async cancel() { + cancelEntered.resolve() + await cancelGate.promise + }, + }) + }, + } + + const controller = new AbortController() + await assert.rejects( + decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal: controller.signal }), + InvalidSourceLengthError + ) + await cancelEntered.promise + + cancelGate.resolve() + await flushTasks() + }) + + it('cancels the opened source when abort fires in the microtask between getReader() and read()', async () => { + const encoded = await encryptChunked(deterministicPlaintext(200)) + const controller = new AbortController() + const reason = new Error('abort between open and read') + const cancelled = deferred() + + const source: RandomAccessSource = { + size: encoded.length, + async openRange() { + const stream = new ReadableStream({ + pull() { + return new Promise(() => { + // Stays pending until cancelled. + }) + }, + cancel(cancelReason) { + cancelled.resolve(cancelReason) + }, + }) + // Intercept getReader() so abort runs immediately after reader acquisition, + // before openExactRange.read() resumes to call readValidated(reader). + const originalGetReader = stream.getReader.bind(stream) + stream.getReader = (() => { + const reader = originalGetReader() + queueMicrotask(() => controller.abort(reason)) + return reader + }) as typeof stream.getReader + return stream + }, + } + + await assert.rejects( + decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal: controller.signal }), + (err) => err === reason + ) + assert.strictEqual(await cancelled.promise, reason) + }) + + it('aborts a pending KeyResolver immediately when writable closes with fewer ciphertext bytes than declared', async () => { + const encoded = await encryptChunked(deterministicPlaintext(1), { contentLength: 1 }) + const truncated = encoded.subarray(0, encoded.length - 1) + const resolverEntered = deferred() + let seenSignal: AbortSignal | undefined + + const resolver: KeyResolver = (_info, sig) => { + seenSignal = sig + resolverEntered.resolve() + return new Promise(() => { + // Never resolves on its own. + }) + } + + const { writable, readable } = decrypt(resolver) + const writer = writable.getWriter() + const reader = readable.getReader() + await writer.write(truncated) + const pendingRead = reader.read() + await resolverEntered.promise + + await assert.rejects(writer.close(), TruncatedCiphertextError) + await assert.rejects(pendingRead, TruncatedCiphertextError) + assert.ok(seenSignal instanceof AbortSignal) + assert.strictEqual(seenSignal.aborted, true) + assert.ok(seenSignal.reason instanceof TruncatedCiphertextError) + }) + + it('preserves exact signal.reason on both sides even if a resolver abort listener calls writer.abort() or reader.cancel()', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2)) + + for (const action of ['writerAbort', 'readerCancel'] as const) { + const resolverEntered = deferred() + const controller = new AbortController() + let writerRef: WritableStreamDefaultWriter | undefined + let readerRef: ReadableStreamDefaultReader | undefined + + const resolver: KeyResolver = (_info, sig) => { + sig.addEventListener('abort', () => { + if (action === 'writerAbort') { + void writerRef?.abort(new Error('resolver cleanup abort')).catch(() => undefined) + } else { + void readerRef?.cancel(new Error('resolver cleanup cancel')).catch(() => undefined) + } + }) + resolverEntered.resolve() + return new Promise(() => { + // Stays pending until aborted. + }) + } + + const { writable, readable } = decrypt(resolver, { signal: controller.signal }) + writerRef = writable.getWriter() + readerRef = readable.getReader() + const pendingWrite = writerRef.write(encoded) + pendingWrite.catch(() => undefined) + const pendingRead = readerRef.read() + await resolverEntered.promise + + const callerReason = new Error(`caller abort (${action})`) + controller.abort(callerReason) + + await assert.rejects(pendingRead, (err) => err === callerReason) + await assert.rejects(pendingWrite, (err) => err === callerReason) + await assert.rejects(writerRef.closed, (err) => err === callerReason) + } + }) + + it('decryptWith aborts the Unwrapper signal on reader.cancel() with or without options.signal', async () => { + const encoded = await encryptChunked(deterministicPlaintext(200), { + recipients: [recipient(KEK_A, KID_A)], + }) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + + for (const withOptionsSignal of [false, true]) { + const unwrapperEntered = deferred() + let seenSignal: AbortSignal | undefined + const unwrapper: Unwrapper = (_recipients, sig) => { + seenSignal = sig + unwrapperEntered.resolve() + return new Promise(() => { + // Stays pending until cancelled. + }) + } + + const externalController = new AbortController() + const { writable, readable } = withOptionsSignal + ? decryptWith(unwrapper, { signal: externalController.signal }) + : decryptWith(unwrapper) + const writer = writable.getWriter() + await writer.write(encoded.subarray(0, envelopeLength)) + + const reader = readable.getReader() + const pendingRead = reader.read() + await unwrapperEntered.promise + + const cancelReason = new Error(`cancel decryptWith (${withOptionsSignal})`) + await reader.cancel(cancelReason) + await pendingRead + + assert.ok(seenSignal instanceof AbortSignal) + assert.strictEqual(seenSignal.aborted, true) + assert.strictEqual(seenSignal.reason, cancelReason) + assert.strictEqual(externalController.signal.aborted, false) + } + }) + + it('built-in createA256KWUnwrapper skips exportKey when aborted during unwrapKey and zeroes exported bytes on abort or after import', async () => { + const encoded = await encryptChunked(deterministicPlaintext(200), { + recipients: [recipient(KEK_A, KID_A)], + }) + const unwrapper = await createA256KWUnwrapper([{ kek: KEK_A, kid: KID_A }]) + + // 1. Abort while unwrapKey is in flight: exportKey must never be called. + { + const unwrapEntered = deferred() + const unwrapGate = deferred() + let exportCalls = 0 + const originalUnwrap = globalThis.crypto.subtle.unwrapKey + const originalExport = globalThis.crypto.subtle.exportKey + globalThis.crypto.subtle.unwrapKey = (async (...args: Parameters) => { + const result = await originalUnwrap.apply(globalThis.crypto.subtle, args) + unwrapEntered.resolve() + await unwrapGate.promise + return result + }) as SubtleCrypto['unwrapKey'] + globalThis.crypto.subtle.exportKey = ((...args: Parameters) => { + exportCalls++ + return originalExport.apply(globalThis.crypto.subtle, args) + }) as SubtleCrypto['exportKey'] + + try { + const controller = new AbortController() + const pending = decryptRangeWith(encoded, unwrapper, { offset: 0 }, { signal: controller.signal }) + await unwrapEntered.promise + controller.abort(null) + await assert.rejects(pending, (err) => err === null) + unwrapGate.resolve() + await flushTasks() + assert.strictEqual(exportCalls, 0) + } finally { + globalThis.crypto.subtle.unwrapKey = originalUnwrap + globalThis.crypto.subtle.exportKey = originalExport + } + } + + // 2. Abort while exportKey is in flight: exported buffer must be zeroed. + { + const exportEntered = deferred() + const exportGate = deferred() + let exportedBuffer: ArrayBuffer | undefined + const originalExport = globalThis.crypto.subtle.exportKey + globalThis.crypto.subtle.exportKey = (async (...args: Parameters) => { + const result = (await originalExport.apply(globalThis.crypto.subtle, args)) as ArrayBuffer + exportedBuffer = result + exportEntered.resolve() + await exportGate.promise + return result + }) as SubtleCrypto['exportKey'] + + try { + const controller = new AbortController() + const pending = decryptRangeWith(encoded, unwrapper, { offset: 0 }, { signal: controller.signal }) + await exportEntered.promise + controller.abort(null) + await assert.rejects(pending, (err) => err === null) + exportGate.resolve() + await flushTasks() + assert.ok(exportedBuffer !== undefined) + assert.deepStrictEqual(new Uint8Array(exportedBuffer), new Uint8Array(KEY_SIZE)) + } finally { + globalThis.crypto.subtle.exportKey = originalExport + } + } + + // 3. Normal decryptWith(createA256KWUnwrapper): temporary exported buffer is zeroed after import. + { + let exportedBuffer: ArrayBuffer | undefined + const originalExport = globalThis.crypto.subtle.exportKey + globalThis.crypto.subtle.exportKey = (async (...args: Parameters) => { + const result = (await originalExport.apply(globalThis.crypto.subtle, args)) as ArrayBuffer + exportedBuffer = result + return result + }) as SubtleCrypto['exportKey'] + + try { + await pipeBytes(decryptWith(unwrapper), encoded) + assert.ok(exportedBuffer !== undefined) + assert.deepStrictEqual(new Uint8Array(exportedBuffer), new Uint8Array(KEY_SIZE)) + } finally { + globalThis.crypto.subtle.exportKey = originalExport + } + } + }) + + it('parse() validates options, handles pre-aborted signals, and aborts pending envelope reads', async () => { + const encoded = await encryptChunked(deterministicPlaintext(200)) + + for (const bad of [null, 'nope', 42, []] as unknown[]) { + await assert.rejects(parse(encoded, bad as ParseOptions), MalformedEnvelopeError) + } + for (const badSignal of [ + null, + 'abort', + 123, + {}, + { aborted: false }, + Object.create(AbortSignal.prototype), + ] as unknown[]) { + await assert.rejects(parse(encoded, { signal: badSignal as AbortSignal }), MalformedEnvelopeError) + } + + // Pre-aborted signal never opens source. + let openCalls = 0 + const neverSource: RandomAccessSource = { + size: encoded.length, + async openRange() { + openCalls++ + return sourceOf([]) + }, + } + const preAborted = new AbortController() + const preReason = new Error('parse pre-aborted') + preAborted.abort(preReason) + await assert.rejects(parse(neverSource, { signal: preAborted.signal }), (err) => err === preReason) + assert.strictEqual(openCalls, 0) + + // Active abort forwards signal and cancels late stream. + const openStarted = deferred() + const openGate = deferred>() + const lateCancelled = deferred() + let seenSignal: AbortSignal | undefined + const slowSource: RandomAccessSource = { + size: encoded.length, + openRange(_offset, _length, signal) { + seenSignal = signal + openStarted.resolve() + return openGate.promise + }, + } + const controller = new AbortController() + const pending = parse(slowSource, { signal: controller.signal }) + await openStarted.promise + assert.strictEqual(seenSignal, controller.signal) + + const abortReason = new Error('parse aborted mid-flight') + controller.abort(abortReason) + await assert.rejects(pending, (err) => err === abortReason) + + openGate.resolve( + new ReadableStream({ + cancel(cancelReason) { + lateCancelled.resolve(cancelReason) + }, + }) + ) + assert.strictEqual(await lateCancelled.promise, abortReason) + }) + + it('re-entrant reader.cancel() in resolver abort listener during writable failure never turns an error into clean EOF', async () => { + const encoded = await encryptChunked(deterministicPlaintext(100), { contentLength: 100 }) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + + // 1. Truncated EOF (writer.close() throws TruncatedCiphertextError). + { + let readerRef: ReadableStreamDefaultReader | undefined + const entered = deferred() + const { writable, readable } = decrypt((_info, sig) => { + sig.addEventListener('abort', () => { + void readerRef?.cancel().catch(() => undefined) + }) + entered.resolve() + return new Promise(() => { + // Stays pending until close fails. + }) + }) + const writer = writable.getWriter() + readerRef = readable.getReader() + await writer.write(encoded.subarray(0, encoded.length - 1)) + const pendingRead = readerRef.read() + await entered.promise + + await assert.rejects(writer.close(), TruncatedCiphertextError) + await assert.rejects(pendingRead, TruncatedCiphertextError) + } + + // 2. Excess bytes (writer.write() throws ExcessCiphertextError). + { + let readerRef: ReadableStreamDefaultReader | undefined + const entered = deferred() + const { writable, readable } = decrypt((_info, sig) => { + sig.addEventListener('abort', () => { + void readerRef?.cancel().catch(() => undefined) + }) + entered.resolve() + return new Promise(() => { + // Stays pending until write fails. + }) + }) + const writer = writable.getWriter() + readerRef = readable.getReader() + await writer.write(encoded.subarray(0, envelopeLength)) + const pendingRead = readerRef.read() + await entered.promise + + await assert.rejects(writer.write(new Uint8Array(500)), ExcessCiphertextError) + await assert.rejects(pendingRead, ExcessCiphertextError) + } + + // 3. Explicit writer.abort(reason). + { + let readerRef: ReadableStreamDefaultReader | undefined + const entered = deferred() + const { writable, readable } = decrypt((_info, sig) => { + sig.addEventListener('abort', () => { + void readerRef?.cancel().catch(() => undefined) + }) + entered.resolve() + return new Promise(() => { + // Stays pending until writer aborts. + }) + }) + const writer = writable.getWriter() + readerRef = readable.getReader() + await writer.write(encoded.subarray(0, envelopeLength)) + const pendingRead = readerRef.read() + await entered.promise + + const reason = new Error('writer abort with re-entrant cancel') + await writer.abort(reason) + await assert.rejects(pendingRead, (err) => err === reason) + } + }) + + it('re-entrant rangeReader.cancel() in source cancel() or adapter abort listener never turns range abort into clean EOF', async () => { + const encoded = await encryptChunked(deterministicPlaintext(100), { contentLength: 100 }) + const info = await parse(encoded) + assert.strictEqual(info.scheme, 'chunked') + if (info.scheme !== 'chunked') return + + for (const trigger of ['sourceCancel', 'signalAbort'] as const) { + let rangeReaderRef: ReadableStreamDefaultReader | undefined + const pullStarted = deferred() + const source: RandomAccessSource = { + size: encoded.length, + async openRange(_offset, _length, sig) { + if (trigger === 'signalAbort') { + sig?.addEventListener('abort', () => { + void rangeReaderRef?.cancel().catch(() => undefined) + }) + } + return new ReadableStream({ + pull() { + pullStarted.resolve() + return new Promise(() => { + // Stays pending until abort. + }) + }, + cancel() { + if (trigger === 'sourceCancel') { + void rangeReaderRef?.cancel().catch(() => undefined) + } + }, + }) + }, + } + + const controller = new AbortController() + const result = await decryptRange( + source, + new Uint8Array(FIXED_CEK), + { offset: 0 }, + { params: info.params, signal: controller.signal } + ) + rangeReaderRef = result.stream.getReader() + const pendingRead = rangeReaderRef.read() + await pullStarted.promise + + const reason = new Error(`range abort with re-entrant cancel (${trigger})`) + controller.abort(reason) + await assert.rejects(pendingRead, (err) => err === reason) + } + }) + + it('cancelling RangeResult.stream aborts the AbortSignal passed to openRange without aborting options.signal', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2)) + const info = await parse(encoded) + assert.strictEqual(info.scheme, 'chunked') + if (info.scheme !== 'chunked') return + + for (const withOptionsSignal of [false, true]) { + const openStarted = deferred() + let seenSignal: AbortSignal | undefined + const source: RandomAccessSource = { + size: encoded.length, + openRange(_offset, _length, sig) { + seenSignal = sig + openStarted.resolve() + return new Promise>(() => { + // Simulates a fetch still waiting for HTTP response headers. + }) + }, + } + + const external = new AbortController() + const result = await decryptRange( + source, + new Uint8Array(FIXED_CEK), + { offset: 0 }, + withOptionsSignal ? { params: info.params, signal: external.signal } : { params: info.params } + ) + const reader = result.stream.getReader() + const pendingRead = reader.read() + await openStarted.promise + assert.ok(seenSignal instanceof AbortSignal) + assert.strictEqual(seenSignal.aborted, false) + + const cancelReason = new Error(`cancel range stream (${withOptionsSignal})`) + await reader.cancel(cancelReason) + await pendingRead + + assert.strictEqual(seenSignal.aborted, true) + assert.strictEqual(seenSignal.reason, cancelReason) + assert.strictEqual(external.signal.aborted, false) + } + }) + + it('non-abort range failures (tampered final chunk, extra bytes) never turn into clean EOF on re-entrant source cancel() and never hang on hung cancel()', async () => { + const plaintext = deterministicPlaintext(CHUNK_SIZE * 3) + const encoded = await encryptChunked(plaintext) + const info = await parse(encoded) + assert.strictEqual(info.scheme, 'chunked') + if (info.scheme !== 'chunked') return + + // 1. Tampered final chunk + source.cancel() calls rangeReader.cancel(): must reject with AuthenticationError. + { + const tampered = new Uint8Array(encoded) + tampered[tampered.length - 1] ^= 0x01 + let rangeReaderRef: ReadableStreamDefaultReader | undefined + let sourceCancelCalled = false + const source: RandomAccessSource = { + size: tampered.length, + async openRange(offset, length) { + const slice = tampered.subarray(offset, offset + length) + return new ReadableStream({ + start(streamController) { + // Leave the stream open after enqueuing the span, like an HTTP body. + streamController.enqueue(slice) + }, + cancel() { + sourceCancelCalled = true + void rangeReaderRef?.cancel().catch(() => undefined) + }, + }) + }, + } + const result = await decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }, { params: info.params }) + assert.strictEqual(result.includesFinalChunk, true) + rangeReaderRef = result.stream.getReader() + const chunk0 = await rangeReaderRef.read() + assert.strictEqual(chunk0.done, false) + const chunk1 = await rangeReaderRef.read() + assert.strictEqual(chunk1.done, false) + await assert.rejects(rangeReaderRef.read(), AuthenticationError) + assert.strictEqual(sourceCancelCalled, true) + } + + // 2. Extra trailing byte after span + source.cancel() calls rangeReader.cancel(): must reject with InvalidSourceLengthError. + { + let rangeReaderRef: ReadableStreamDefaultReader | undefined + let sourceCancelCalled = false + const source: RandomAccessSource = { + size: encoded.length, + async openRange(offset, length) { + const slice = encoded.subarray(offset, offset + length) + return new ReadableStream({ + start(streamController) { + streamController.enqueue(slice) + streamController.enqueue(new Uint8Array([0xff])) + }, + cancel() { + sourceCancelCalled = true + void rangeReaderRef?.cancel().catch(() => undefined) + }, + }) + }, + } + const result = await decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }, { params: info.params }) + assert.strictEqual(result.includesFinalChunk, true) + rangeReaderRef = result.stream.getReader() + assert.strictEqual((await rangeReaderRef.read()).done, false) + assert.strictEqual((await rangeReaderRef.read()).done, false) + await assert.rejects(rangeReaderRef.read(), InvalidSourceLengthError) + assert.strictEqual(sourceCancelCalled, true) + } + + // 3. Tampered final chunk + hung source.cancel() (with and without options.signal): must reject promptly without hanging. + for (const withSignal of [false, true]) { + const tampered = new Uint8Array(encoded) + tampered[tampered.length - 1] ^= 0x01 + const cancelStarted = deferred() + const cancelGate = deferred() + const source: RandomAccessSource = { + size: tampered.length, + async openRange(offset, length) { + const slice = tampered.subarray(offset, offset + length) + return new ReadableStream({ + start(streamController) { + streamController.enqueue(slice) + }, + async cancel() { + cancelStarted.resolve() + await cancelGate.promise + }, + }) + }, + } + const result = await decryptRange( + source, + new Uint8Array(FIXED_CEK), + { offset: 0 }, + withSignal ? { params: info.params, signal: new AbortController().signal } : { params: info.params } + ) + const reader = result.stream.getReader() + assert.strictEqual((await reader.read()).done, false) + assert.strictEqual((await reader.read()).done, false) + await assert.rejects(reader.read(), AuthenticationError) + await cancelStarted.promise + cancelGate.resolve() + await flushTasks() + } + }) + + it('keeps pending stream promises abortable even when only the promise is retained across GC', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE * 2)) + const info = await parse(encoded) + assert.strictEqual(info.scheme, 'chunked') + if (info.scheme !== 'chunked') return + const { params } = info + + const { controller, signal } = trackedAbortController() + const reason = new Error('abort retained promises') + + async function spawnRetainedPromises() { + const pairForRead = decrypt(new Uint8Array(FIXED_CEK), { signal }) + const pendingRead = pairForRead.readable.getReader().read() + + const pairForClosed = decrypt(new Uint8Array(FIXED_CEK), { signal }) + const pendingClosed = pairForClosed.writable.getWriter().closed + + const stalledSource: RandomAccessSource = { + size: encoded.length, + openRange() { + return new Promise(() => { + // Stalled transport openRange(). + }) + }, + } + const rangeResult = await decryptRange( + stalledSource, + new Uint8Array(FIXED_CEK), + { offset: 0 }, + { params, signal } + ) + const pendingRangeRead = rangeResult.stream.getReader().read() + + return { pendingRead, pendingClosed, pendingRangeRead } + } + + const { pendingRead, pendingClosed, pendingRangeRead } = await spawnRetainedPromises() + await flushTasks() + + const gc = (globalThis as { gc?: () => void }).gc + if (typeof gc === 'function') { + for (let i = 0; i < 10; i++) { + gc() + await new Promise((resolve) => setTimeout(resolve, 10)) + } + } + + controller.abort(reason) + await assert.rejects(pendingRead, (err) => err === reason) + await assert.rejects(pendingClosed, (err) => err === reason) + await assert.rejects(pendingRangeRead, (err) => err === reason) + }) + + it('latches TruncatedCiphertextError on writable before notifying resolver abort listeners on short EOF', async () => { + const plaintext = deterministicPlaintext(CHUNK_SIZE) + const encoded = await encryptChunked(plaintext, { contentLength: plaintext.length }) + const truncated = encoded.subarray(0, encoded.length - 10) + const cleanupError = new Error('re-entrant writer cleanup') + + let resolverAbortSeen = false + const resolverReady = deferred() + let writerRef: WritableStreamDefaultWriter | undefined + + const pair = decrypt((_info, resolverSignal) => { + resolverSignal.addEventListener('abort', () => { + resolverAbortSeen = true + // Synchronously call writer.abort with a different reason during short-EOF teardown. + void writerRef?.abort(cleanupError).catch(() => undefined) + }) + resolverReady.resolve() + return new Promise(() => { + // Stays pending until short EOF aborts the resolver. + }) + }) + + const writer = pair.writable.getWriter() + writerRef = writer + const reader = pair.readable.getReader() + const closedPromise = writer.closed.catch((err) => err) + const readPromise = reader.read().catch((err) => err) + + await writer.write(truncated) + await resolverReady.promise + + let closeErr: unknown + try { + await writer.close() + } catch (err) { + closeErr = err + } + + assert.strictEqual(resolverAbortSeen, true) + assert.ok(closeErr instanceof TruncatedCiphertextError) + const closedErr = await closedPromise + const readErr = await readPromise + assert.strictEqual(closedErr, closeErr) + assert.strictEqual(readErr, closeErr) + }) + + it('latches ExcessCiphertextError on writable before notifying resolver abort listeners on overrun write', async () => { + const plaintext = deterministicPlaintext(CHUNK_SIZE) + const encoded = await encryptChunked(plaintext, { contentLength: plaintext.length }) + const { envelopeLength } = decodeEnvelope(encoded) + const cleanupError = new Error('re-entrant writer cleanup on excess') + + let resolverAbortSeen = false + const resolverReady = deferred() + let writerRef: WritableStreamDefaultWriter | undefined + + const pair = decrypt((_info, resolverSignal) => { + resolverSignal.addEventListener('abort', () => { + resolverAbortSeen = true + void writerRef?.abort(cleanupError).catch(() => undefined) + }) + resolverReady.resolve() + return new Promise(() => { + // Stays pending until overrun write aborts the resolver. + }) + }) + + const writer = pair.writable.getWriter() + writerRef = writer + const reader = pair.readable.getReader() + const closedPromise = writer.closed.catch((err) => err) + const readPromise = reader.read().catch((err) => err) + + // Deliver envelope first so the resolver starts running. + await writer.write(encoded.subarray(0, envelopeLength)) + await resolverReady.promise + + // Write more ciphertext bytes than declared. + let writeErr: unknown + try { + await writer.write(concatBytes(encoded.subarray(envelopeLength), Uint8Array.of(0x00))) + } catch (err) { + writeErr = err + } + + assert.strictEqual(resolverAbortSeen, true) + assert.ok(writeErr instanceof ExcessCiphertextError) + const closedErr = await closedPromise + const readErr = await readPromise + assert.strictEqual(closedErr, writeErr) + assert.strictEqual(readErr, writeErr) + }) + + it('parse() rechecks signal after readEnvelope when probe stream cancel() aborts the signal', async () => { + const encoded = await encryptChunked(deterministicPlaintext(CHUNK_SIZE)) + const { envelopeLength } = decodeEnvelope(encoded) + const { controller, signal } = trackedAbortController() + const reason = new Error('aborted during probe cancel') + const cancelGate = deferred() + let cancelCalled = false + + const source: RandomAccessSource = { + size: encoded.length, + async openRange(offset, length) { + let sent = false + return new ReadableStream({ + pull(streamController) { + if (sent) { + return new Promise(() => { + // Keep the probe stream open with unread remaining bytes so readEnvelope cancels it. + }) + } + sent = true + // Deliver just the complete envelope bytes while keeping the span open. + streamController.enqueue(encoded.subarray(offset, Math.min(offset + length, envelopeLength))) + }, + cancel() { + cancelCalled = true + controller.abort(reason) + return cancelGate.promise + }, + }) + }, + } + + try { + await assert.rejects(parse(source, { signal }), (err) => err === reason) + assert.strictEqual(cancelCalled, true) + } finally { + cancelGate.resolve() + await flushTasks() + } + }) + + it('createA256KWUnwrapper rejects with signal.reason after last wrong-key attempt or post-export abort and zeroes discarded CEK', async () => { + const encoded = await encryptChunked(deterministicPlaintext(128), { recipients: [recipient(KEK_A, KID_A)] }) + const info = await parse(encoded) + + // Case 1: empty recipients with pre-aborted signal rejects instead of returning undefined. + const unwrapperA = await createA256KWUnwrapper([{ kek: KEK_A, kid: KID_A }]) + const preAborted = new AbortController() + const preReason = new Error('pre-aborted empty recipients') + preAborted.abort(preReason) + await assert.rejects(unwrapperA([], preAborted.signal), (err) => err === preReason) + + // Case 2: abort during the last wrong-key attempt rejects instead of resolving undefined. + const wrongUnwrapper = await createA256KWUnwrapper([{ kek: KEK_B }]) + const originalUnwrapKey = globalThis.crypto.subtle.unwrapKey.bind(globalThis.crypto.subtle) + const originalExportKey = globalThis.crypto.subtle.exportKey.bind(globalThis.crypto.subtle) + const subtleProto = Object.getPrototypeOf(globalThis.crypto.subtle) as SubtleCrypto + const unwrapDesc = Object.getOwnPropertyDescriptor(subtleProto, 'unwrapKey') + const exportDesc = Object.getOwnPropertyDescriptor(subtleProto, 'exportKey') + try { + const wrongController = new AbortController() + const wrongReason = new Error('aborted during last wrong-key unwrap') + Object.defineProperty(globalThis.crypto.subtle, 'unwrapKey', { + configurable: true, + value: async (...args: Parameters) => { + wrongController.abort(wrongReason) + return originalUnwrapKey(...args) + }, + }) + await assert.rejects(wrongUnwrapper(info.recipients, wrongController.signal), (err) => err === wrongReason) + + // Restore unwrapKey for Case 3. + if (unwrapDesc) { + Object.defineProperty(globalThis.crypto.subtle, 'unwrapKey', unwrapDesc) + } else { + delete (globalThis.crypto.subtle as { unwrapKey?: unknown }).unwrapKey + } + + // Case 3: abort right after exportKey resolves (microtask between aesKwUnwrap and unwrapper) + // zeroes the exported CEK buffer and rejects with exact signal.reason. + const postExportController = new AbortController() + const postExportReason = new Error('aborted after exportKey') + let exportedBuf: ArrayBuffer | undefined + Object.defineProperty(globalThis.crypto.subtle, 'exportKey', { + configurable: true, + value: async (...args: Parameters) => { + const buf = (await originalExportKey(...args)) as ArrayBuffer + exportedBuf = buf + // Schedule abort on the microtask right after aesKwUnwrap checks signal.aborted. + queueMicrotask(() => { + queueMicrotask(() => { + postExportController.abort(postExportReason) + }) + }) + return buf + }, + }) + await assert.rejects( + unwrapperA(info.recipients, postExportController.signal), + (err) => err === postExportReason + ) + assert.ok(exportedBuf !== undefined) + assert.deepStrictEqual(new Uint8Array(exportedBuf), new Uint8Array(KEY_SIZE)) + } finally { + if (unwrapDesc) { + Object.defineProperty(globalThis.crypto.subtle, 'unwrapKey', unwrapDesc) + } else { + delete (globalThis.crypto.subtle as { unwrapKey?: unknown }).unwrapKey + } + if (exportDesc) { + Object.defineProperty(globalThis.crypto.subtle, 'exportKey', exportDesc) + } else { + delete (globalThis.crypto.subtle as { exportKey?: unknown }).exportKey + } + } + }) + + ;(typeof document === 'undefined' ? it.skip : it)( + 'accepts cross-realm AbortSignal from a same-origin iframe across all entry points', + async () => { + const plaintext = deterministicPlaintext(200) + const encoded = await encryptChunked(plaintext, { recipients: [recipient(KEK_A, KID_A)] }) + const unwrapper = await createA256KWUnwrapper([{ kek: KEK_A, kid: KID_A }]) + + const iframe = document.createElement('iframe') + document.body.appendChild(iframe) + try { + const iframeWindow = iframe.contentWindow as (Window & { AbortController: typeof AbortController }) | null + assert.ok(iframeWindow !== null) + const IframeAbortController = iframeWindow.AbortController + const live = new IframeAbortController() + assert.strictEqual(live.signal instanceof AbortSignal, false) + + const parsed = await parse(encoded, { signal: live.signal }) + assert.strictEqual(parsed.scheme, 'chunked') + assert.deepStrictEqual( + await pipeBytes(decrypt(new Uint8Array(FIXED_CEK), { signal: live.signal }), encoded), + plaintext + ) + assert.deepStrictEqual(await pipeBytes(decryptWith(unwrapper, { signal: live.signal }), encoded), plaintext) + const r1 = await decryptRange(encoded, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal: live.signal }) + assert.deepStrictEqual(concatBytes(...(await readAllChunks(r1.stream))), plaintext) + const r2 = await decryptRangeWith(encoded, unwrapper, { offset: 0 }, { signal: live.signal }) + assert.deepStrictEqual(concatBytes(...(await readAllChunks(r2.stream))), plaintext) + + // Verify cross-realm abort(null) propagates exact null reason. + const aborted = new IframeAbortController() + aborted.abort(null) + await assert.rejects(parse(encoded, { signal: aborted.signal }), (err) => err === null) + await assert.rejects( + decryptRange(encoded, new Uint8Array(FIXED_CEK), { offset: 0 }, { signal: aborted.signal }), + (err) => err === null + ) + await assert.rejects( + decryptRangeWith(encoded, unwrapper, { offset: 0 }, { signal: aborted.signal }), + (err) => err === null + ) + await assert.rejects( + decrypt(new Uint8Array(FIXED_CEK), { signal: aborted.signal }).readable.getReader().read(), + (err) => err === null + ) + await assert.rejects( + decryptWith(unwrapper, { signal: aborted.signal }).readable.getReader().read(), + (err) => err === null + ) + } finally { + iframe.remove() + } + } + ) + }) +}) diff --git a/packages/filecoin-encryption-envelope/test/aes-gcm-stream-decrypt-resolver.test.ts b/packages/filecoin-encryption-envelope/test/aes-gcm-stream-decrypt-resolver.test.ts index c1744b8bb..bb570a597 100644 --- a/packages/filecoin-encryption-envelope/test/aes-gcm-stream-decrypt-resolver.test.ts +++ b/packages/filecoin-encryption-envelope/test/aes-gcm-stream-decrypt-resolver.test.ts @@ -2,7 +2,12 @@ import assert from 'assert' import { type ChunkedEncryptOptions, decrypt, encrypt, type KeyResolver } from '../src/aes-gcm-stream.ts' import { KEY_SIZE, MIN_CHUNK_SIZE } from '../src/constants.ts' import { decodeEnvelope } from '../src/cose/decode.ts' -import { AuthenticationError, InvalidKeyError, KeyResolutionError } from '../src/errors.ts' +import { + AuthenticationError, + InvalidCiphertextLengthError, + InvalidKeyError, + KeyResolutionError, +} from '../src/errors.ts' import { type EnvelopeInfo, parse } from '../src/range/inspect.ts' import { deterministicPlaintext } from './aes-gcm-stream-fixtures.ts' import { concatBytes } from './cose-fixtures.ts' @@ -225,18 +230,339 @@ describe('aesGcmStream.decrypt with a KeyResolver', () => { await abortDone assert.strictEqual(calls, 1) }) + + it('passes an AbortSignal that stays un-aborted through successful EOF and leaves the returned key untouched', async () => { + const cek = testKey(11) + const snapshot = new Uint8Array(cek) + const plaintext = deterministicPlaintext(CHUNK_SIZE + 50) + const encoded = await encryptFull(plaintext, cek) + + let receivedSignal: AbortSignal | undefined + let abortEvents = 0 + const resolver: KeyResolver = (_info, signal) => { + receivedSignal = signal + assert.ok(signal instanceof AbortSignal) + assert.strictEqual(signal.aborted, false) + signal.addEventListener('abort', () => { + abortEvents++ + }) + return cek + } + + assert.deepStrictEqual(await decryptBytes(encoded, resolver), plaintext) + assert.ok(receivedSignal !== undefined) + assert.strictEqual(receivedSignal.aborted, false) + assert.strictEqual(abortEvents, 0) + assert.deepStrictEqual(cek, snapshot) + }) + + it('aborts the signal when the readable is cancelled while the resolver is pending', async () => { + const cek = testKey(12) + const encoded = await encryptFull(deterministicPlaintext(20), cek) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + + let resolveEntered: (() => void) | undefined + const entered = new Promise((resolve) => { + resolveEntered = resolve + }) + let receivedSignal: AbortSignal | undefined + let abortEvents = 0 + const resolver: KeyResolver = (_info, signal) => { + receivedSignal = signal + assert.strictEqual(signal.aborted, false) + signal.addEventListener('abort', () => { + abortEvents++ + }) + resolveEntered?.() + return new Promise(() => { + // Stays pending until cancel. + }) + } + + const { writable, readable } = decrypt(resolver) + const writer = writable.getWriter() + await writer.write(encoded.subarray(0, envelopeLength)) + + const reader = readable.getReader() + const pending = reader.read() + await entered + + const reason = new Error('cancel while resolver pending') + await reader.cancel(reason) + const readResult = await pending + + assert.deepStrictEqual(readResult, { value: undefined, done: true }) + assert.ok(receivedSignal !== undefined) + assert.strictEqual(receivedSignal.aborted, true) + assert.strictEqual(receivedSignal.reason, reason) + assert.strictEqual(abortEvents, 1) + }) + + it('aborts the signal when the readable is cancelled without a reason while the resolver is pending', async () => { + const cek = testKey(13) + const encoded = await encryptFull(deterministicPlaintext(20), cek) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + + let resolveEntered: (() => void) | undefined + const entered = new Promise((resolve) => { + resolveEntered = resolve + }) + let receivedSignal: AbortSignal | undefined + const resolver: KeyResolver = (_info, signal) => { + receivedSignal = signal + resolveEntered?.() + return new Promise(() => { + // Stays pending until cancel. + }) + } + + const { writable, readable } = decrypt(resolver) + const writer = writable.getWriter() + await writer.write(encoded.subarray(0, envelopeLength)) + + const reader = readable.getReader() + const pending = reader.read() + await entered + + await reader.cancel() + await pending + + assert.ok(receivedSignal !== undefined) + assert.strictEqual(receivedSignal.aborted, true) + }) + + it('aborts the signal on writable abort and preserves the original stream error when the resolver rejects on abort', async () => { + const cek = testKey(14) + const encoded = await encryptFull(deterministicPlaintext(20), cek) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + + let resolveEntered: (() => void) | undefined + const entered = new Promise((resolve) => { + resolveEntered = resolve + }) + let receivedSignal: AbortSignal | undefined + let abortEvents = 0 + const resolver: KeyResolver = (_info, signal) => { + receivedSignal = signal + assert.strictEqual(signal.aborted, false) + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { + abortEvents++ + reject(new Error('resolver aborted cleanly')) + }) + resolveEntered?.() + }) + } + + const { writable, readable } = decrypt(resolver) + const writer = writable.getWriter() + await writer.write(encoded.subarray(0, envelopeLength)) + + const reader = readable.getReader() + const pending = reader.read() + await entered + + const reason = new Error('writable abort while resolver pending') + const abortDone = writer.abort(reason) + + await assert.rejects(pending, (err) => err === reason) + await abortDone + assert.ok(receivedSignal !== undefined) + assert.strictEqual(receivedSignal.aborted, true) + assert.strictEqual(receivedSignal.reason, reason) + assert.strictEqual(abortEvents, 1) + }) + + it('aborts the signal when a stream failure occurs on the writable while the resolver is pending', async () => { + const cek = testKey(15) + const encoded = await encryptFull(deterministicPlaintext(20), cek, { contentLength: 20 }) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + + let resolveEntered: (() => void) | undefined + const entered = new Promise((resolve) => { + resolveEntered = resolve + }) + let receivedSignal: AbortSignal | undefined + let abortEvents = 0 + const resolver: KeyResolver = (_info, signal) => { + receivedSignal = signal + signal.addEventListener('abort', () => { + abortEvents++ + }) + resolveEntered?.() + return new Promise(() => { + // Stays pending until the write fails. + }) + } + + const { writable, readable } = decrypt(resolver) + const writer = writable.getWriter() + await writer.write(encoded.subarray(0, envelopeLength)) + + const reader = readable.getReader() + const pending = reader.read() + await entered + + // Exceed the declared plaintext_length (20 bytes + 16-byte tag = 36 ciphertext bytes). + let writeError: unknown + await assert.rejects(writer.write(new Uint8Array(100)), (err) => { + writeError = err + return err instanceof InvalidCiphertextLengthError + }) + await assert.rejects(pending, (err) => err === writeError) + assert.ok(receivedSignal !== undefined) + assert.strictEqual(receivedSignal.aborted, true) + assert.strictEqual(receivedSignal.reason, writeError) + assert.strictEqual(abortEvents, 1) + }) + + it('leaves a late key returned after readable cancel untouched (not zeroed, not validated, never imported)', async () => { + const cek = testKey(16) + const encoded = await encryptFull(deterministicPlaintext(20), cek) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + + const lateKey = testKey(0x50) + const snapshot = new Uint8Array(lateKey) + const touchedProps: Array = [] + const instrumentedLateKey = new Proxy(lateKey, { + get(target, prop, receiver) { + // Promise resolution checks `.then` to detect thenables before returning to FEE. + if (prop !== 'then') { + touchedProps.push(prop) + } + return Reflect.get(target, prop, receiver) + }, + }) + + let releaseResolver: ((value: Uint8Array) => void) | undefined + let resolveEntered: (() => void) | undefined + const entered = new Promise((resolve) => { + resolveEntered = resolve + }) + const resolver: KeyResolver = () => { + resolveEntered?.() + return new Promise((resolve) => { + releaseResolver = resolve + }) + } + + const originalImportKey = globalThis.crypto.subtle.importKey + let importCalls = 0 + globalThis.crypto.subtle.importKey = ((...args: Parameters) => { + importCalls++ + return originalImportKey.apply(globalThis.crypto.subtle, args) + }) as SubtleCrypto['importKey'] + + try { + const { writable, readable } = decrypt(resolver) + const writer = writable.getWriter() + await writer.write(encoded.subarray(0, envelopeLength)) + + const reader = readable.getReader() + const pending = reader.read() + await entered + + await reader.cancel(new Error('cancel before late key')) + await pending + + // Deliver the late key after cancellation and let any follow-up microtasks run. + releaseResolver?.(instrumentedLateKey) + await new Promise((resolve) => setTimeout(resolve, 0)) + + assert.strictEqual(importCalls, 0) + assert.deepStrictEqual(touchedProps, []) + assert.deepStrictEqual(lateKey, snapshot) + } finally { + globalThis.crypto.subtle.importKey = originalImportKey + } + }) + + it('leaves a late key returned after writable abort untouched (not zeroed, not validated, never imported)', async () => { + const cek = testKey(17) + const encoded = await encryptFull(deterministicPlaintext(20), cek) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + + // Wrong length with non-zero bytes: verifies neither validation nor zeroing runs. + const lateKey = testKey(0x60).subarray(0, KEY_SIZE - 1) + const snapshot = new Uint8Array(lateKey) + const touchedProps: Array = [] + const instrumentedLateKey = new Proxy(lateKey, { + get(target, prop, receiver) { + if (prop !== 'then') { + touchedProps.push(prop) + } + return Reflect.get(target, prop, receiver) + }, + }) + + let releaseResolver: ((value: Uint8Array) => void) | undefined + let resolveEntered: (() => void) | undefined + const entered = new Promise((resolve) => { + resolveEntered = resolve + }) + const resolver: KeyResolver = () => { + resolveEntered?.() + return new Promise((resolve) => { + releaseResolver = resolve + }) + } + + const originalImportKey = globalThis.crypto.subtle.importKey + let importCalls = 0 + globalThis.crypto.subtle.importKey = ((...args: Parameters) => { + importCalls++ + return originalImportKey.apply(globalThis.crypto.subtle, args) + }) as SubtleCrypto['importKey'] + + try { + const { writable, readable } = decrypt(resolver) + const writer = writable.getWriter() + await writer.write(encoded.subarray(0, envelopeLength)) + + const reader = readable.getReader() + const pending = reader.read() + await entered + + const reason = new Error('abort before late key') + const abortDone = writer.abort(reason) + await assert.rejects(pending, (err) => err === reason) + await abortDone + + releaseResolver?.(instrumentedLateKey) + await new Promise((resolve) => setTimeout(resolve, 0)) + + assert.strictEqual(importCalls, 0) + assert.deepStrictEqual(touchedProps, []) + assert.deepStrictEqual(lateKey, snapshot) + } finally { + globalThis.crypto.subtle.importKey = originalImportKey + } + }) + + it('keeps working with a 1-argument resolver that ignores the signal parameter', async () => { + const cek = testKey(18) + const plaintext = deterministicPlaintext(64) + const encoded = await encryptFull(plaintext, cek) + const oneArgResolver: KeyResolver = (info) => { + assert.strictEqual(info.scheme, 'chunked') + return cek + } + assert.deepStrictEqual(await decryptBytes(encoded, oneArgResolver), plaintext) + }) }) }) describe('aesGcmStream.decrypt with a resolver that never settles', () => { - it('still ends a pending read when the writable is aborted', async () => { + it('still ends a pending read and aborts the signal when the writable is aborted', async () => { const cek = testKey(10) const encoded = await encryptFull(deterministicPlaintext(100), cek) let signalEntered: (() => void) | undefined const entered = new Promise((resolve) => { signalEntered = resolve }) - const { writable, readable } = decrypt(() => { + let receivedSignal: AbortSignal | undefined + const { writable, readable } = decrypt((_info, signal) => { + receivedSignal = signal signalEntered?.() return new Promise(() => { // A KMS call that never answers. @@ -250,5 +576,8 @@ describe('aesGcmStream.decrypt with a resolver that never settles', () => { const reason = new Error('abort while the resolver hangs') await writer.abort(reason) await assert.rejects(read, (err) => err === reason) + assert.ok(receivedSignal !== undefined) + assert.strictEqual(receivedSignal.aborted, true) + assert.strictEqual(receivedSignal.reason, reason) }) }) diff --git a/packages/filecoin-encryption-envelope/test/aes-gcm-stream-decrypt.test.ts b/packages/filecoin-encryption-envelope/test/aes-gcm-stream-decrypt.test.ts index 7a7e02d87..af6e9b565 100644 --- a/packages/filecoin-encryption-envelope/test/aes-gcm-stream-decrypt.test.ts +++ b/packages/filecoin-encryption-envelope/test/aes-gcm-stream-decrypt.test.ts @@ -7,9 +7,11 @@ import { decodeEnvelope } from '../src/cose/decode.ts' import { encStructure } from '../src/cose/enc-structure.ts' import { AuthenticationError, + ExcessCiphertextError, InvalidCiphertextLengthError, InvalidKeyError, MalformedEnvelopeError, + TruncatedCiphertextError, UnsupportedSchemeError, } from '../src/errors.ts' import { FIXED_CEK, fixedBaseNonceRandomValues, withRandomValues } from './aes-gcm-fixtures.ts' @@ -216,6 +218,7 @@ describe('aesGcmStream.decrypt', () => { const { chunks, error } = await decryptUntilFailure(droppedFinalChunk) assert.strictEqual(chunks.length, 0) + assert.ok(error instanceof TruncatedCiphertextError) assert.ok(error instanceof InvalidCiphertextLengthError) }) }) @@ -290,13 +293,19 @@ describe('aesGcmStream.decrypt', () => { await assert.rejects(decryptBytes(dropped), AuthenticationError) }) - it('rejects truncation leaving fewer than 16 trailing bytes with InvalidCiphertextLengthError', async () => { + it('rejects truncation leaving fewer than 16 trailing bytes with InvalidCiphertextLengthError when no plaintext_length is declared', async () => { const plaintext = deterministicPlaintext(CHUNK_SIZE * 2) const encoded = await encryptFull(plaintext) const decodedEnvelope = decodeEnvelope(encoded) const stride = CHUNK_SIZE + TAG_SIZE const truncated = encoded.subarray(0, decodedEnvelope.envelopeLength + stride + 10) - await assert.rejects(decryptBytes(truncated), InvalidCiphertextLengthError) + await assert.rejects( + decryptBytes(truncated), + (error: unknown) => + error instanceof InvalidCiphertextLengthError && + !(error instanceof TruncatedCiphertextError) && + !(error instanceof ExcessCiphertextError) + ) }) it('rejects appended trailing bytes with AuthenticationError', async () => { @@ -321,52 +330,116 @@ describe('aesGcmStream.decrypt', () => { } }) - it('rejects zero ciphertext bytes after the envelope with InvalidCiphertextLengthError', async () => { + it('rejects zero ciphertext bytes after the envelope with InvalidCiphertextLengthError when no plaintext_length is declared', async () => { const encoded = await encryptFull(deterministicPlaintext(0)) const decodedEnvelope = decodeEnvelope(encoded) const envelopeOnly = encoded.subarray(0, decodedEnvelope.envelopeLength) - await assert.rejects(decryptBytes(envelopeOnly), InvalidCiphertextLengthError) + await assert.rejects( + decryptBytes(envelopeOnly), + (error: unknown) => + error instanceof InvalidCiphertextLengthError && + !(error instanceof TruncatedCiphertextError) && + !(error instanceof ExcessCiphertextError) + ) }) - it('rejects received bytes exceeding what the declared plaintext_length allows, immediately on write', async () => { + it('rejects received bytes exceeding what the declared plaintext_length allows, immediately on write, with ExcessCiphertextError', async () => { const encoded = await encryptFull(deterministicPlaintext(100), { contentLength: 100 }) const withExtra = concatBytes( encoded, Uint8Array.from({ length: 50 }, () => 0xaa) ) - const { writable } = decrypt(new Uint8Array(FIXED_CEK)) + const { writable, readable } = decrypt(new Uint8Array(FIXED_CEK)) const writer = writable.getWriter() - await assert.rejects(writer.write(withExtra), InvalidCiphertextLengthError) + const isExcess = (error: unknown) => + error instanceof ExcessCiphertextError && + error instanceof InvalidCiphertextLengthError && + !(error instanceof TruncatedCiphertextError) + await assert.rejects(writer.write(withExtra), isExcess) + await assert.rejects(readAllChunks(readable), isExcess) }) - it('rejects an overrun on a later write, after the envelope was already parsed', async () => { + it('rejects a 1-byte overrun on a later write, after the envelope and valid ciphertext were already written, with ExcessCiphertextError', async () => { // Distinct from the "immediately on write" case above: there, the // whole envelope, ciphertext, and overrun arrive in one write() call, // so the overrun is only ever caught by the check made right after // computing expectedTotal for the first time. Splitting the envelope - // into its own write() call exercises the *separate* check that runs - // on every write() using the already-computed expectedTotal. + // and ciphertext into separate write() calls exercises the check that + // runs on every write() using the already-computed expectedTotal. const encoded = await encryptFull(deterministicPlaintext(100), { contentLength: 100 }) const decodedEnvelope = decodeEnvelope(encoded) const envelopeBytes = encoded.subarray(0, decodedEnvelope.envelopeLength) - const rest = encoded.subarray(decodedEnvelope.envelopeLength) - const withExtra = concatBytes( - rest, - Uint8Array.from({ length: 50 }, () => 0xaa) - ) - const { writable } = decrypt(new Uint8Array(FIXED_CEK)) - const writer = writable.getWriter() - await writer.write(envelopeBytes) - await assert.rejects(writer.write(withExtra), InvalidCiphertextLengthError) - }) - - it('rejects when the declared plaintext_length is larger than what arrives, at EOF', async () => { + const ciphertext = encoded.subarray(decodedEnvelope.envelopeLength) + const isExcess = (error: unknown) => + error instanceof ExcessCiphertextError && + error instanceof InvalidCiphertextLengthError && + !(error instanceof TruncatedCiphertextError) + + const firstSplit = decrypt(new Uint8Array(FIXED_CEK)) + const firstWriter = firstSplit.writable.getWriter() + await firstWriter.write(envelopeBytes) + await assert.rejects(firstWriter.write(concatBytes(ciphertext, Uint8Array.from([0xaa]))), isExcess) + await assert.rejects(readAllChunks(firstSplit.readable), isExcess) + + const secondSplit = decrypt(new Uint8Array(FIXED_CEK)) + const secondWriter = secondSplit.writable.getWriter() + await secondWriter.write(envelopeBytes) + await secondWriter.write(ciphertext) + await assert.rejects(secondWriter.write(Uint8Array.from([0xaa])), isExcess) + await assert.rejects(readAllChunks(secondSplit.readable), isExcess) + }) + + it('rejects EOF with a missing chunk against a declared plaintext_length with TruncatedCiphertextError', async () => { const plaintext = deterministicPlaintext(CHUNK_SIZE + 50) const encoded = await encryptFull(plaintext, { contentLength: CHUNK_SIZE + 50 }) const decodedEnvelope = decodeEnvelope(encoded) const stride = CHUNK_SIZE + TAG_SIZE const truncated = encoded.subarray(0, decodedEnvelope.envelopeLength + stride) - await assert.rejects(decryptBytes(truncated), InvalidCiphertextLengthError) + await assert.rejects( + decryptBytes(truncated), + (error: unknown) => + error instanceof TruncatedCiphertextError && + error instanceof InvalidCiphertextLengthError && + !(error instanceof ExcessCiphertextError) + ) + }) + + it('rejects EOF with missing bytes inside the final chunk against a declared plaintext_length with TruncatedCiphertextError', async () => { + const encoded = await encryptFull(deterministicPlaintext(100), { contentLength: 100 }) + const truncated = encoded.subarray(0, encoded.length - 1) + await assert.rejects( + decryptBytes(truncated), + (error: unknown) => + error instanceof TruncatedCiphertextError && + error instanceof InvalidCiphertextLengthError && + !(error instanceof ExcessCiphertextError) + ) + }) + + it('rejects EOF with an incomplete tag, bare tag, or zero ciphertext bytes against a declared plaintext_length with TruncatedCiphertextError', async () => { + const isTruncated = (error: unknown) => + error instanceof TruncatedCiphertextError && + error instanceof InvalidCiphertextLengthError && + !(error instanceof ExcessCiphertextError) + + // Single-chunk object: zero ciphertext bytes, incomplete tag (< 16 bytes) + const single = await encryptFull(deterministicPlaintext(100), { contentLength: 100 }) + const singleHeaderLen = decodeEnvelope(single).envelopeLength + await assert.rejects(decryptBytes(single.subarray(0, singleHeaderLen)), isTruncated) + await assert.rejects(decryptBytes(single.subarray(0, singleHeaderLen + TAG_SIZE - 1)), isTruncated) + + // Empty declared object: zero ciphertext bytes or incomplete tag + const empty = await encryptFull(deterministicPlaintext(0), { contentLength: 0 }) + const emptyHeaderLen = decodeEnvelope(empty).envelopeLength + await assert.rejects(decryptBytes(empty.subarray(0, emptyHeaderLen)), isTruncated) + await assert.rejects(decryptBytes(empty.subarray(0, emptyHeaderLen + 10)), isTruncated) + + // Multi-chunk object: incomplete tag or bare 16-byte tag after chunk 0 + const multi = await encryptFull(deterministicPlaintext(CHUNK_SIZE + 50), { contentLength: CHUNK_SIZE + 50 }) + const multiHeaderLen = decodeEnvelope(multi).envelopeLength + const stride = CHUNK_SIZE + TAG_SIZE + await assert.rejects(decryptBytes(multi.subarray(0, multiHeaderLen + stride + 10)), isTruncated) + await assert.rejects(decryptBytes(multi.subarray(0, multiHeaderLen + stride + TAG_SIZE)), isTruncated) }) it('rejects a scheme-1 (whole-object AES-GCM) object with UnsupportedSchemeError', async () => { @@ -692,6 +765,12 @@ describe('aesGcmStream.decrypt declared total', () => { const over = decrypt(new Uint8Array(FIXED_CEK)) const overWrite = over.writable.getWriter().write(rewritePlaintextLength(envelope, atLimit, atLimit + 1)) - await assert.rejects(overWrite, InvalidCiphertextLengthError) + await assert.rejects( + overWrite, + (error: unknown) => + error instanceof InvalidCiphertextLengthError && + !(error instanceof TruncatedCiphertextError) && + !(error instanceof ExcessCiphertextError) + ) }) }) diff --git a/packages/filecoin-encryption-envelope/test/key-resolver-flow.test.ts b/packages/filecoin-encryption-envelope/test/key-resolver-flow.test.ts index ad3672cea..41812c0cc 100644 --- a/packages/filecoin-encryption-envelope/test/key-resolver-flow.test.ts +++ b/packages/filecoin-encryption-envelope/test/key-resolver-flow.test.ts @@ -131,7 +131,7 @@ describe('key resolver flow (tag 16, through the public API)', () => { const callsAfterParse = calls.length assert.ok(info.appMetadata !== undefined) - const key = await lib.resolver(info) + const key = await lib.resolver(info, new AbortController().signal) const result = await fee.decryptRange(source, key, range, { params: info.params }) const bytes = concatBytes(...(await readAllChunks(result.stream))) diff --git a/packages/filecoin-encryption-envelope/test/public-surface.test.ts b/packages/filecoin-encryption-envelope/test/public-surface.test.ts index 9d22001c6..38146edaf 100644 --- a/packages/filecoin-encryption-envelope/test/public-surface.test.ts +++ b/packages/filecoin-encryption-envelope/test/public-surface.test.ts @@ -6,8 +6,9 @@ import { MAX_CHUNK_SIZE, MAX_ENCODED_OBJECT_SIZE, MIN_CHUNK_SIZE, + TAG_SIZE, } from '../src/constants.ts' -import { ALG_A256KW, ENVELOPE_TYPE } from '../src/cose/constants.ts' +import { ALG_A256KW, ENVELOPE_TYPE, MAX_ENVELOPE_SIZE } from '../src/cose/constants.ts' import { EnvelopeError } from '../src/errors.ts' // `../src/index.ts` (the root barrel) is the file under test here; every // other test file in this package imports source files directly instead. @@ -22,13 +23,16 @@ const EXPECTED_PUBLIC_CONSTANTS: Record = { MAX_AES_GCM_PLAINTEXT_SIZE, MAX_CHUNK_SIZE, MAX_ENCODED_OBJECT_SIZE, + MAX_ENVELOPE_SIZE, MIN_CHUNK_SIZE, + TAG_SIZE, } describe('public surface (src/index.ts)', () => { it('exposes exactly the allowlisted root runtime exports', () => { assert.deepStrictEqual(Object.keys(fee).sort(), [ 'aesGcm', + 'ciphertextLengthForPlaintext', 'constants', 'cose', 'decrypt', @@ -60,19 +64,21 @@ describe('public surface (src/index.ts)', () => { } const object = concatBytes(...encoded) - const info = await fee.parse(object) + const parseOptions: fee.ParseOptions = { signal: new AbortController().signal } + const info = await fee.parse(object, parseOptions) assert.strictEqual(info.scheme, 'chunked') if (info.scheme !== 'chunked') return const range = { offset: MIN_CHUNK_SIZE - 10, length: 20 } // crosses the first chunk boundary const expected = plaintext.subarray(range.offset, range.offset + range.length) - const direct = await fee.decryptRange(object, cek, range, { params: info.params }) + const directOptions: fee.RangeDecryptOptions = { params: info.params, signal: new AbortController().signal } + const direct = await fee.decryptRange(object, cek, range, directOptions) const directBytes: Uint8Array[] = [] for await (const chunk of direct.stream) directBytes.push(chunk) assert.deepStrictEqual(concatBytes(...directBytes), expected) const unwrapper = await fee.recipients.createA256KWUnwrapper([{ kek }]) - const viaRecipient = await fee.decryptRangeWith(object, unwrapper, range) + const viaRecipient = await fee.decryptRangeWith(object, unwrapper, range, { signal: new AbortController().signal }) const recipientBytes: Uint8Array[] = [] for await (const chunk of viaRecipient.stream) recipientBytes.push(chunk) assert.deepStrictEqual(concatBytes(...recipientBytes), expected) @@ -105,10 +111,11 @@ describe('public surface (src/index.ts)', () => { controller.close() }, }) + const options: fee.DecryptOptions = { signal: new AbortController().signal } const chunks: Uint8Array[] = [] for await (const chunk of source .pipeThrough(fee.encrypt({ cek, chunkSize: MIN_CHUNK_SIZE })) - .pipeThrough(fee.decrypt(cek))) { + .pipeThrough(fee.decrypt(cek, options))) { chunks.push(chunk) } assert.deepStrictEqual(concatBytes(...chunks), plaintext) @@ -125,10 +132,11 @@ describe('public surface (src/index.ts)', () => { }, }) const unwrapper = await fee.recipients.createA256KWUnwrapper([{ kek }]) + const options: fee.DecryptOptions = { signal: new AbortController().signal } const chunks: Uint8Array[] = [] for await (const chunk of source .pipeThrough(fee.encrypt({ cek, chunkSize: MIN_CHUNK_SIZE, recipients: [{ alg: ALG_A256KW, kek }] })) - .pipeThrough(fee.decryptWith(unwrapper))) { + .pipeThrough(fee.decryptWith(unwrapper, options))) { chunks.push(chunk) } assert.deepStrictEqual(concatBytes(...chunks), plaintext) @@ -161,6 +169,7 @@ describe('public surface (src/index.ts)', () => { 'CriticalHeaderError', 'CryptoOperationError', 'EnvelopeError', + 'ExcessCiphertextError', 'InvalidChunkSizeError', 'InvalidCiphertextLengthError', 'InvalidKeyError', @@ -174,6 +183,7 @@ describe('public surface (src/index.ts)', () => { 'NoUsableRecipientError', 'RecipientAttemptLimitError', 'RecipientUnwrapError', + 'TruncatedCiphertextError', 'UnsupportedSchemeError', ]) assert.strictEqual('hasErrorName' in errors, false) @@ -183,5 +193,78 @@ describe('public surface (src/index.ts)', () => { const ctor = value as new (...args: never[]) => unknown assert.ok(ctor === EnvelopeError || ctor.prototype instanceof EnvelopeError, `${name} must extend EnvelopeError`) } + + const truncated = new fee.errors.TruncatedCiphertextError('short') + assert.ok(truncated instanceof fee.errors.TruncatedCiphertextError) + assert.ok(truncated instanceof fee.errors.InvalidCiphertextLengthError) + assert.strictEqual(truncated instanceof fee.errors.ExcessCiphertextError, false) + assert.strictEqual(truncated.name, 'TruncatedCiphertextError') + + const excess = new fee.errors.ExcessCiphertextError('long') + assert.ok(excess instanceof fee.errors.ExcessCiphertextError) + assert.ok(excess instanceof fee.errors.InvalidCiphertextLengthError) + assert.strictEqual(excess instanceof fee.errors.TruncatedCiphertextError, false) + assert.strictEqual(excess.name, 'ExcessCiphertextError') + }) + + describe('size preflight helpers (root public API)', () => { + function maxPlaintextForCiphertextBudget(budget: number, chunkSize: number): number { + const stride = chunkSize + fee.constants.TAG_SIZE + const fullChunks = Math.floor(budget / stride) + const remainder = budget % stride + assert.ok(remainder > fee.constants.TAG_SIZE, 'test requires a partial final chunk so +1 byte stays in the chunk') + return fullChunks * chunkSize + (remainder - fee.constants.TAG_SIZE) + } + + it('computes detached ciphertext length for empty input and chunk boundaries', () => { + const chunkSize = fee.constants.DEFAULT_CHUNK_SIZE + const tagSize = fee.constants.TAG_SIZE + + // Empty plaintext still produces one final chunk carrying only its tag. + assert.strictEqual(fee.ciphertextLengthForPlaintext(0, chunkSize), tagSize) + assert.strictEqual(fee.ciphertextLengthForPlaintext(0, fee.constants.MIN_CHUNK_SIZE), tagSize) + + // Chunk boundaries: one tag per chunk, no trailing empty chunk at exact multiples. + assert.strictEqual(fee.ciphertextLengthForPlaintext(1, chunkSize), 1 + tagSize) + assert.strictEqual(fee.ciphertextLengthForPlaintext(chunkSize - 1, chunkSize), chunkSize - 1 + tagSize) + assert.strictEqual(fee.ciphertextLengthForPlaintext(chunkSize, chunkSize), chunkSize + tagSize) + assert.strictEqual(fee.ciphertextLengthForPlaintext(chunkSize + 1, chunkSize), chunkSize + 1 + 2 * tagSize) + assert.strictEqual(fee.ciphertextLengthForPlaintext(chunkSize * 2, chunkSize), chunkSize * 2 + 2 * tagSize) + assert.strictEqual( + fee.ciphertextLengthForPlaintext(chunkSize * 2 + 1, chunkSize), + chunkSize * 2 + 1 + 3 * tagSize + ) + }) + + it('accepts detached ciphertext at MAX_ENCODED_OBJECT_SIZE and throws 1 byte over', () => { + const chunkSize = fee.constants.DEFAULT_CHUNK_SIZE + const maxPlaintext = maxPlaintextForCiphertextBudget(fee.constants.MAX_ENCODED_OBJECT_SIZE, chunkSize) + + assert.strictEqual( + fee.ciphertextLengthForPlaintext(maxPlaintext, chunkSize), + fee.constants.MAX_ENCODED_OBJECT_SIZE + ) + assert.throws( + () => fee.ciphertextLengthForPlaintext(maxPlaintext + 1, chunkSize), + fee.errors.InvalidPlaintextLengthError + ) + }) + + it('checks full-object totals with MAX_ENVELOPE_SIZE and exact envelope lengths at and 1 byte over MAX_ENCODED_OBJECT_SIZE', () => { + const chunkSize = fee.constants.DEFAULT_CHUNK_SIZE + + for (const envelopeLength of [fee.constants.MAX_ENVELOPE_SIZE, 100]) { + const budget = fee.constants.MAX_ENCODED_OBJECT_SIZE - envelopeLength + const maxPlaintext = maxPlaintextForCiphertextBudget(budget, chunkSize) + + const totalAtLimit = envelopeLength + fee.ciphertextLengthForPlaintext(maxPlaintext, chunkSize) + assert.strictEqual(totalAtLimit, fee.constants.MAX_ENCODED_OBJECT_SIZE) + assert.strictEqual(totalAtLimit <= fee.constants.MAX_ENCODED_OBJECT_SIZE, true) + + const totalOneOver = envelopeLength + fee.ciphertextLengthForPlaintext(maxPlaintext + 1, chunkSize) + assert.strictEqual(totalOneOver, fee.constants.MAX_ENCODED_OBJECT_SIZE + 1) + assert.strictEqual(totalOneOver <= fee.constants.MAX_ENCODED_OBJECT_SIZE, false) + } + }) }) }) diff --git a/packages/filecoin-encryption-envelope/test/range-decrypt.test.ts b/packages/filecoin-encryption-envelope/test/range-decrypt.test.ts index e0b41493f..9891f7c33 100644 --- a/packages/filecoin-encryption-envelope/test/range-decrypt.test.ts +++ b/packages/filecoin-encryption-envelope/test/range-decrypt.test.ts @@ -5,11 +5,13 @@ import { KEY_SIZE, MIN_CHUNK_SIZE, TAG_SIZE } from '../src/constants.ts' import { decodeEnvelope } from '../src/cose/decode.ts' import { AuthenticationError, + ExcessCiphertextError, InvalidCiphertextLengthError, InvalidKeyError, InvalidRangeError, InvalidSourceLengthError, MalformedEnvelopeError, + TruncatedCiphertextError, UnsupportedSchemeError, } from '../src/errors.ts' import { decryptRange } from '../src/range/decrypt.ts' @@ -419,15 +421,40 @@ describe('decryptRange', () => { await assert.rejects(readAllChunks(result.stream), AuthenticationError) }) - it('rejects a truncated source with plaintext_length before opening any ciphertext span', async () => { + it('rejects a truncated source with plaintext_length as TruncatedCiphertextError before opening any ciphertext span', async () => { const plaintext = deterministicPlaintext(CHUNK_SIZE * 3) const encoded = await encryptChunkedFull(plaintext, { contentLength: plaintext.length }) const envelopeLength = decodeEnvelope(encoded).envelopeLength - const truncated = encoded.subarray(0, envelopeLength + STRIDE * 2) - const { source, calls } = recordingSource(truncated) - await assert.rejects(decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }), InvalidCiphertextLengthError) - const bytesRequested = calls.reduce((sum, call) => sum + call.length, 0) - assert.ok(bytesRequested < envelopeLength + CHUNK_SIZE, 'must not have opened a ciphertext span') + const isTruncated = (error: unknown) => + error instanceof TruncatedCiphertextError && + error instanceof InvalidCiphertextLengthError && + !(error instanceof ExcessCiphertextError) + + for (const cutLength of [envelopeLength, envelopeLength + 10, envelopeLength + STRIDE * 2]) { + const truncated = encoded.subarray(0, cutLength) + const { source, calls } = recordingSource(truncated) + await assert.rejects(decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }), isTruncated) + const bytesRequested = calls.reduce((sum, call) => sum + call.length, 0) + assert.ok(bytesRequested < envelopeLength + CHUNK_SIZE, 'must not have opened a ciphertext span') + } + }) + + it('rejects an oversized source with plaintext_length as ExcessCiphertextError before opening any ciphertext span', async () => { + const plaintext = deterministicPlaintext(CHUNK_SIZE * 2) + const encoded = await encryptChunkedFull(plaintext, { contentLength: plaintext.length }) + const envelopeLength = decodeEnvelope(encoded).envelopeLength + const isExcess = (error: unknown) => + error instanceof ExcessCiphertextError && + error instanceof InvalidCiphertextLengthError && + !(error instanceof TruncatedCiphertextError) + + for (const extra of [1, 10, 100]) { + const oversized = concatBytes(encoded, new Uint8Array(extra)) + const { source, calls } = recordingSource(oversized) + await assert.rejects(decryptRange(source, new Uint8Array(FIXED_CEK), { offset: 0 }), isExcess) + const bytesRequested = calls.reduce((sum, call) => sum + call.length, 0) + assert.ok(bytesRequested < envelopeLength + CHUNK_SIZE, 'must not have opened a ciphertext span') + } }) }) diff --git a/packages/filecoin-encryption-envelope/test/range-plan.test.ts b/packages/filecoin-encryption-envelope/test/range-plan.test.ts index a13005363..0dec5f222 100644 --- a/packages/filecoin-encryption-envelope/test/range-plan.test.ts +++ b/packages/filecoin-encryption-envelope/test/range-plan.test.ts @@ -1,6 +1,12 @@ import assert from 'assert' import { TAG_SIZE } from '../src/constants.ts' -import { InvalidCiphertextLengthError, InvalidRangeError, InvalidSourceLengthError } from '../src/errors.ts' +import { + ExcessCiphertextError, + InvalidCiphertextLengthError, + InvalidRangeError, + InvalidSourceLengthError, + TruncatedCiphertextError, +} from '../src/errors.ts' import { type ChunkedRangeLayoutInput, planRange, type RangePlan } from '../src/range/plan.ts' const HEADER_LENGTH = 200 @@ -407,25 +413,119 @@ describe('planRange', () => { }) } - it('rejects sourceSize < headerLength', () => { + it('rejects sourceSize < headerLength even when plaintextLength is declared', () => { assert.throws( () => planRange({ sourceSize: 100, headerLength: 200, chunkSize: CHUNK_SIZE }, { offset: 0 }), InvalidSourceLengthError ) + assert.throws( + () => + planRange({ sourceSize: 100, headerLength: 200, chunkSize: CHUNK_SIZE, plaintextLength: 100 }, { offset: 0 }), + InvalidSourceLengthError + ) }) - it('rejects an impossible ciphertext length (remainder below the tag size)', () => { + it('rejects an impossible ciphertext length (remainder below the tag size) without plaintextLength as InvalidCiphertextLengthError', () => { const layout: ChunkedRangeLayoutInput = { sourceSize: HEADER_LENGTH + STRIDE + 5, headerLength: HEADER_LENGTH, chunkSize: CHUNK_SIZE, } - assert.throws(() => planRange(layout, { offset: 0 }), InvalidCiphertextLengthError) + assert.throws( + () => planRange(layout, { offset: 0 }), + (error: unknown) => + error instanceof InvalidCiphertextLengthError && + !(error instanceof TruncatedCiphertextError) && + !(error instanceof ExcessCiphertextError) + ) }) - it('rejects a plaintextLength that disagrees with the derived layout', () => { - const layout: ChunkedRangeLayoutInput = { ...LAYOUT_A, plaintextLength: TOTAL_A - 1 } - assert.throws(() => planRange(layout, { offset: 0 }), InvalidCiphertextLengthError) + it('rejects a source size smaller than declared plaintextLength with TruncatedCiphertextError', () => { + const isTruncated = (error: unknown) => + error instanceof TruncatedCiphertextError && + error instanceof InvalidCiphertextLengthError && + !(error instanceof ExcessCiphertextError) + + // Valid chunk shape, short by 1 byte or by a whole chunk + assert.throws(() => planRange({ ...LAYOUT_A, plaintextLength: TOTAL_A + 1 }, { offset: 0 }), isTruncated) + assert.throws( + () => + planRange( + { + sourceSize: HEADER_LENGTH + STRIDE, + headerLength: HEADER_LENGTH, + chunkSize: CHUNK_SIZE, + plaintextLength: TOTAL_A, + }, + { offset: 0 } + ), + isTruncated + ) + // Impossible chunk shapes (zero ciphertext, incomplete tag, bare tag) are not masked by chunkLayout + for (const shortCipherLen of [0, 5, STRIDE + 5, STRIDE + TAG_SIZE]) { + assert.throws( + () => + planRange( + { + sourceSize: HEADER_LENGTH + shortCipherLen, + headerLength: HEADER_LENGTH, + chunkSize: CHUNK_SIZE, + plaintextLength: TOTAL_A, + }, + { offset: 0 } + ), + isTruncated, + `shortCipherLen=${shortCipherLen}` + ) + } + }) + + it('rejects a source size larger than declared plaintextLength with ExcessCiphertextError', () => { + const isExcess = (error: unknown) => + error instanceof ExcessCiphertextError && + error instanceof InvalidCiphertextLengthError && + !(error instanceof TruncatedCiphertextError) + + // Valid chunk shape, 1 byte over or whole chunk over + assert.throws(() => planRange({ ...LAYOUT_A, plaintextLength: TOTAL_A - 1 }, { offset: 0 }), isExcess) + assert.throws(() => planRange({ ...LAYOUT_B, plaintextLength: CHUNK_SIZE }, { offset: 0 }), isExcess) + // Impossible chunk shapes (incomplete tag, bare tag after full chunk) are not masked by chunkLayout + for (const extraBytes of [1, 5, TAG_SIZE]) { + assert.throws( + () => + planRange( + { + sourceSize: HEADER_LENGTH + STRIDE + extraBytes, + headerLength: HEADER_LENGTH, + chunkSize: CHUNK_SIZE, + plaintextLength: CHUNK_SIZE, + }, + { offset: 0 } + ), + isExcess, + `extraBytes=${extraBytes}` + ) + } + }) + + it('rejects a declared plaintextLength implying more than 64 GiB total with InvalidCiphertextLengthError', () => { + // At chunk size 4096 and headerLength 83, 68_452_085_693 puts total at 2^36; +1 is one over. + assert.throws( + () => + planRange( + { + sourceSize: 83 + STRIDE, + headerLength: 83, + chunkSize: CHUNK_SIZE, + plaintextLength: 68_452_085_694, + }, + { offset: 0 } + ), + (error: unknown) => + error instanceof InvalidCiphertextLengthError && + !(error instanceof TruncatedCiphertextError) && + !(error instanceof ExcessCiphertextError) + ) }) })