diff --git a/.changeset/gold-llamas-eat.md b/.changeset/gold-llamas-eat.md new file mode 100644 index 0000000..e43d9e2 --- /dev/null +++ b/.changeset/gold-llamas-eat.md @@ -0,0 +1,5 @@ +--- +"hyperfly": patch +--- + +Encode bytes subclasses using their actual bytes and lengths across row, columnar and packed encodings. Safely wrap hostile error proxies with coded errors when checking options and profiles. diff --git a/packages/hyperfly/src/codec.ts b/packages/hyperfly/src/codec.ts index 652aea9..9a82f9c 100644 --- a/packages/hyperfly/src/codec.ts +++ b/packages/hyperfly/src/codec.ts @@ -3,7 +3,7 @@ import { defaultPackHooks } from "./pack.js"; import { checkedProfile, indexProfile, type Profile } from "./profile.js"; import { decodeNode } from "./decode.js"; import { checkByteBudget, checkItemBudget, encodeNode, type EncodeCtx } from "./encode.js"; -import { DecodeError, FingerprintMismatchError, HyperflyError, isInstance } from "./errors.js"; +import { DecodeError, FingerprintMismatchError, hasErrorCode, HyperflyError } from "./errors.js"; import { validateIR, withinStack, type IRNode } from "./ir.js"; import { DEFAULT_LIMITS, Reader, type Limits } from "./reader.js"; import { Writer } from "./writer.js"; @@ -153,7 +153,7 @@ export function checkedOptions(options: CompileOptions & { validate?: boolean }) } return { limits: checkedLimits, plan: plan ?? "row", pack: checkedPack, profile, validate }; } catch (cause) { - if (isInstance(cause, HyperflyError) && cause.code === "options") throw cause; + if (hasErrorCode(cause, "options")) throw cause; throw new HyperflyError("options", "options: could not read compile options", { cause }); } } diff --git a/packages/hyperfly/src/columnar.ts b/packages/hyperfly/src/columnar.ts index ba57b02..f356cb9 100644 --- a/packages/hyperfly/src/columnar.ts +++ b/packages/hyperfly/src/columnar.ts @@ -4,7 +4,7 @@ import { DecodeError, EncodeError } from "./errors.js"; import { literalBytes, utf8Length, utf8Lengths, type IRField, type IRNode } from "./ir.js"; import type { GrammarToken, ProfileIndex } from "./profile.js"; import type { Reader } from "./reader.js"; -import { isUint8Array } from "./typed-array.js"; +import { byteLengthOf, copyBytes, isUint8Array } from "./typed-array.js"; import { INT_MAX, INT_MIN, readUleb, ulebLen, unzigzag, writeUleb, zigzag } from "./varint.js"; import { Writer } from "./writer.js"; @@ -783,6 +783,7 @@ function encodeStringColumn( } let packed: Uint8Array | null = null; + let packedLength = 0; let packedCost = Infinity; const totalBytes = bytes.reduce((n, value) => n + value.length, 0); // §3: the deflate mode's total length obeys the byte limits, so a @@ -792,7 +793,7 @@ function encodeStringColumn( const concat = new Uint8Array(total); let offset = 0; for (const value of bytes) { - concat.set(value, offset); + copyBytes(concat, value, offset); offset += value.length; } try { @@ -803,10 +804,11 @@ function encodeStringColumn( if (!isUint8Array(packed)) { throw new EncodeError("packed", `${path}: deflate hook must return a Uint8Array`); } + packedLength = byteLengthOf(packed); packedCost = bytes.reduce((n, value) => n + ulebLen(BigInt(value.length)), 0) + - ulebLen(BigInt(packed.length)) + - packed.length; + ulebLen(BigInt(packedLength)) + + packedLength; } const grammar = ctx.profile.grammarOf(ordinal); @@ -867,8 +869,8 @@ function encodeStringColumn( } if (mode === 0x02) { for (const value of bytes) writeUleb(w, BigInt(value.length)); - writeUleb(w, BigInt(packed!.length)); - w.bytes(packed!); + writeUleb(w, BigInt(packedLength)); + w.bytes(packed!, packedLength); return; } if (mode === 0x03) { diff --git a/packages/hyperfly/src/encode.ts b/packages/hyperfly/src/encode.ts index 14bd987..7bc4508 100644 --- a/packages/hyperfly/src/encode.ts +++ b/packages/hyperfly/src/encode.ts @@ -2,7 +2,7 @@ import { columnarEligible, encodeColumnarArray } from "./columnar.js"; import { columnCount, type ProfileIndex } from "./profile.js"; import { EncodeError, type ErrorCode } from "./errors.js"; import { hasPayload, literalBytes, utf8Lengths, type IRNode } from "./ir.js"; -import { isUint8Array } from "./typed-array.js"; +import { byteLengthOf, isUint8Array } from "./typed-array.js"; import { INT_MAX, INT_MIN, writeUleb, zigzag } from "./varint.js"; import { Writer } from "./writer.js"; @@ -15,7 +15,7 @@ function fail(code: ErrorCode, path: string, message: string): never { /** The byte length of a Uint8Array of any realm, or undefined for anything else, a Proxy included. */ function bytesLength(value: unknown): number | undefined { try { - if (value instanceof Uint8Array || isUint8Array(value)) return value.length; + if (value instanceof Uint8Array || isUint8Array(value)) return byteLengthOf(value); } catch { // a proxy, or a value whose prototype cannot be read, is not bytes } @@ -184,8 +184,10 @@ export function encodeNode( if (length === undefined) fail("type", path, "expected Uint8Array"); if (length > ctx.maxByteLength) fail("limit", path, `bytes of ${length} exceeds the codec limit`); chargeBytes(length, ctx, path); - writeUleb(w, BigInt(length)); - w.bytes(value as Uint8Array); + // Most bytes fields fit in one ULEB byte; avoid a BigInt conversion for that prefix. + if (length < 0x80) w.u8(length); + else writeUleb(w, BigInt(length)); + w.bytes(value as Uint8Array, length); return; } case "literal": { diff --git a/packages/hyperfly/src/errors.ts b/packages/hyperfly/src/errors.ts index 93142bf..1f7343a 100644 --- a/packages/hyperfly/src/errors.ts +++ b/packages/hyperfly/src/errors.ts @@ -45,6 +45,8 @@ export type ErrorCode = | "validation" | "options"; +const createdErrors = new WeakMap(); + /** Base error carrying a stable failure code (wire-v0 §9). */ export class HyperflyError extends Error { /** Machine-readable failure category; message text may vary (wire-v0 §9). */ @@ -55,12 +57,19 @@ export class HyperflyError extends Error { super(message, options); this.name = new.target.name; this.code = code; + createdErrors.set(this, code); } } -/** `instanceof` for caught values: one whose prototype cannot be read, such as a revoked proxy, is not an instance. */ +/** Match a locally created error's original code without reading properties or invoking proxy traps. */ +export function hasErrorCode(value: unknown, code: ErrorCode): value is HyperflyError { + return createdErrors.get(value as HyperflyError) === code; +} + +/** Only locally created Hyperfly errors may pass; uninspectable caught values are not instances. */ export function isInstance(value: unknown, type: abstract new (...args: never[]) => T): value is T { try { + if ((type.prototype === HyperflyError.prototype || type.prototype instanceof HyperflyError) && !createdErrors.has(value as HyperflyError)) return false; return value instanceof type; } catch { return false; diff --git a/packages/hyperfly/src/profile.ts b/packages/hyperfly/src/profile.ts index 98afd5f..4c152c1 100644 --- a/packages/hyperfly/src/profile.ts +++ b/packages/hyperfly/src/profile.ts @@ -1,5 +1,5 @@ import { columnarEligible, flattenLeaves } from "./columnar.js"; -import { HyperflyError, isInstance } from "./errors.js"; +import { hasErrorCode, HyperflyError } from "./errors.js"; import { describeValue, hasLoneSurrogate, validateIR, withinStack } from "./ir.js"; import type { IRNode } from "./ir.js"; @@ -189,7 +189,7 @@ function snapshotProfile(profile: Profile): Profile { } return result; } catch (cause) { - if (isInstance(cause, HyperflyError) && cause.code === "ir") throw cause; + if (hasErrorCode(cause, "ir")) throw cause; throw new HyperflyError("ir", "profile: could not read JSON data", { cause }); } } diff --git a/packages/hyperfly/src/train.ts b/packages/hyperfly/src/train.ts index cdeb9f0..50593ea 100644 --- a/packages/hyperfly/src/train.ts +++ b/packages/hyperfly/src/train.ts @@ -1,5 +1,5 @@ import { columnarEligible, flattenLeaves, intColumnEncodedLength, matchGrammar } from "./columnar.js"; -import { HyperflyError } from "./errors.js"; +import { hasErrorCode, HyperflyError } from "./errors.js"; import { defaultPackHooks } from "./pack.js"; import { hasLoneSurrogate, validateIR, withinStack, type IRNode } from "./ir.js"; import { @@ -60,13 +60,7 @@ function checkedTrainOptions(options: TrainOptions): Required { maxEntries: Math.min(MAX_DICT_ENTRIES, maxEntries ?? MAX_DICT_ENTRIES), }; } catch (cause) { - let isOurs = false; - try { - isOurs = cause instanceof HyperflyError && cause.code === "options"; - } catch { - isOurs = false; - } - if (isOurs) throw cause; + if (hasErrorCode(cause, "options")) throw cause; throw new HyperflyError("options", "options: could not read train options", { cause }); } } diff --git a/packages/hyperfly/src/typed-array.ts b/packages/hyperfly/src/typed-array.ts index 2bffb49..9fa1856 100644 --- a/packages/hyperfly/src/typed-array.ts +++ b/packages/hyperfly/src/typed-array.ts @@ -2,6 +2,7 @@ const TYPED_ARRAY_PROTOTYPE = Object.getPrototypeOf(Uint8Array.prototype) as object; const typedArrayTag = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTOTYPE, Symbol.toStringTag)!.get!; const typedArrayByteLength = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTOTYPE, "byteLength")!.get!; +const typedArraySet = Uint8Array.prototype.set; /** Whether `value` is a Uint8Array of any realm, subclasses included. */ export function isUint8Array(value: unknown): value is Uint8Array { @@ -12,3 +13,8 @@ export function isUint8Array(value: unknown): value is Uint8Array { export function byteLengthOf(value: Uint8Array): number { return typedArrayByteLength.call(value) as number; } + +/** Copy internal bytes, ignoring subclass accessors, iterators and methods in either realm. */ +export function copyBytes(target: Uint8Array, source: Uint8Array, offset: number): void { + typedArraySet.call(target, source, offset); +} diff --git a/packages/hyperfly/src/writer.ts b/packages/hyperfly/src/writer.ts index 40a31fa..f80d5b3 100644 --- a/packages/hyperfly/src/writer.ts +++ b/packages/hyperfly/src/writer.ts @@ -1,3 +1,5 @@ +import { byteLengthOf, copyBytes } from "./typed-array.js"; + export class Writer { private buf: Uint8Array; private len = 0; @@ -17,7 +19,7 @@ export class Writer { let next = this.buf.length * 2; while (next < this.len + extra) next *= 2; const grown = new Uint8Array(next); - grown.set(this.buf.subarray(0, this.len)); + copyBytes(grown, this.buf.subarray(0, this.len), 0); this.buf = grown; this.view = new DataView(grown.buffer); } @@ -27,10 +29,10 @@ export class Writer { this.buf[this.len++] = byte; } - bytes(data: Uint8Array): void { - this.ensure(data.length); - this.buf.set(data, this.len); - this.len += data.length; + bytes(data: Uint8Array, length = byteLengthOf(data)): void { + this.ensure(length); + copyBytes(this.buf, data, this.len); + this.len += length; } f64le(value: number): void { diff --git a/packages/hyperfly/test/bytes-subclasses.ts b/packages/hyperfly/test/bytes-subclasses.ts new file mode 100644 index 0000000..c33d8a6 --- /dev/null +++ b/packages/hyperfly/test/bytes-subclasses.ts @@ -0,0 +1,26 @@ +import { runInNewContext } from "node:vm"; + +/** Hostile accessors and methods must never be consulted when measuring or copying bytes. */ +export const bytesSubclasses: [string, (bytes: Uint8Array) => Uint8Array][] = [ + ...["length", "byteLength", "byteOffset", "buffer", "subarray", "set"].map((key): [string, (bytes: Uint8Array) => Uint8Array] => [ + key, + (bytes) => { + class Hostile extends Uint8Array {} + Object.defineProperty(Hostile.prototype, key, { + get() { throw new Error(`must not read ${key}`); }, + }); + // Include surrounding bytes so reading the wrong offset or buffer corrupts the result. + const backing = new Uint8Array(bytes.length + 2); + backing.set(bytes, 1); + return new Hostile(backing.buffer, 1, bytes.length); + }, + ]), + ["cross-realm subclass", runInNewContext(`(bytes) => new (class extends Uint8Array { + get length() { throw new Error("length"); } + get byteLength() { throw new Error("byteLength"); } + get byteOffset() { throw new Error("byteOffset"); } + get buffer() { throw new Error("buffer"); } + subarray() { throw new Error("subarray"); } + set() { throw new Error("set"); } + })(bytes)`) as (bytes: Uint8Array) => Uint8Array], +]; diff --git a/packages/hyperfly/test/bytes.test.ts b/packages/hyperfly/test/bytes.test.ts index 6d9e119..3d576b9 100644 --- a/packages/hyperfly/test/bytes.test.ts +++ b/packages/hyperfly/test/bytes.test.ts @@ -4,6 +4,31 @@ import { compileIR, DEFAULT_LIMITS, type Limits, type IRNode, type Profile } fro import { toHex } from "../src/canonical.js"; import { HyperflyError } from "../src/errors.js"; import { fromHex, revive } from "./vector-values.js"; +import { bytesSubclasses } from "./bytes-subclasses.js"; + +describe.each(["row", "columnar"] as const)("%s bytes subclasses", (plan) => { + test.each(bytesSubclasses)("ignores overridden %s", (_, make) => { + const plain = new Uint8Array([1, 2]); + const hostile = make(plain); + const shapes: [IRNode, (bytes: Uint8Array) => unknown][] = [ + [{ kind: "bytes" }, (b) => b], + [{ kind: "array", element: { kind: "bytes" } }, (b) => [b, b]], + [{ kind: "array", element: { kind: "struct", fields: [{ name: "b", type: { kind: "bytes" } }] } }, (b) => [{ b }, { b }]], + [{ kind: "array", element: { kind: "struct", fields: [{ name: "b", type: { kind: "bytes" }, optional: true, nullable: true }] } }, (b) => [{}, { b: null }, { b }]], + ]; + for (const [ir, value] of shapes) { + const codec = compileIR(ir, { plan }); + expect(codec.encodeBody(value(hostile))).toEqual(codec.encodeBody(value(plain))); + expect(codec.decode(codec.encode(value(hostile)))).toEqual(value(plain)); + for (const limits of [{ maxByteLength: 1 }, { maxTotalBytes: 1 }]) { + expect(() => compileIR(ir, { plan, limits }).encodeBody(value(hostile))) + .toThrow(expect.objectContaining({ code: "limit" })); + } + } + const codec = compileIR({ kind: "bytes" }, { plan }); + expect(codec.encodeBody(make(new Uint8Array()))).toEqual(new Uint8Array([0])); + }); +}); interface ByteVector { name: string; diff --git a/packages/hyperfly/test/caught-errors.test.ts b/packages/hyperfly/test/caught-errors.test.ts new file mode 100644 index 0000000..149d335 --- /dev/null +++ b/packages/hyperfly/test/caught-errors.test.ts @@ -0,0 +1,87 @@ +import { expect, test } from "bun:test"; +import { z } from "zod"; +import { CodecRegistry, compileIR, serializeArtifact, train, type IRNode } from "../src/index.js"; +import { DecodeError, EncodeError, HyperflyError, isInstance, type ErrorCode } from "../src/errors.js"; +import { decodeResponse, encodeFor, negotiate } from "../src/http.js"; +import { compile } from "../src/zod.js"; + +const rows: IRNode = { + kind: "array", + element: { kind: "struct", fields: [{ name: "s", type: { kind: "string" } }] }, +}; + +function revokingError(error: HyperflyError) { + let codeReads = 0; + const { proxy, revoke } = Proxy.revocable(error, { + get(target, key, receiver) { + if (key === "code") { + codeReads++; + revoke(); + // Reading the revoked receiver would leak a native TypeError from an unsafe code check. + return Reflect.get(receiver, key); + } + return Reflect.get(target, key, receiver); + }, + }); + return { proxy, codeReads: () => codeReads }; +} + +const entries: [string, ErrorCode, (cause: HyperflyError) => unknown][] = [ + ["compileIR options prototype", "options", (cause) => compileIR(rows, new Proxy({}, { getPrototypeOf() { throw cause; } }))], + ["compileIR limits keys", "options", (cause) => compileIR(rows, { limits: new Proxy({}, { ownKeys() { throw cause; } }) })], + ["Zod compile options", "options", (cause) => compile(z.string(), new Proxy({}, { getPrototypeOf() { throw cause; } }))], + ["train options prototype", "options", (cause) => train(rows, [], new Proxy({}, { getPrototypeOf() { throw cause; } }))], + ["train options keys", "options", (cause) => train(rows, [], new Proxy({}, { ownKeys() { throw cause; } }))], + ["compileIR profile", "ir", (cause) => compileIR(rows, { + plan: "columnar", profile: { version: 1, shared: { columns: [] }, hints: { get value() { throw cause; } } }, + })], + ["serializeArtifact profile", "ir", (cause) => serializeArtifact(rows, "columnar", { + shared: { get columns(): never { throw cause; } }, + })], + ["JSON encoding", "json", (cause) => encodeFor(negotiate(null, new CodecRegistry([compileIR(rows)])), { + toJSON() { throw cause; }, + })], + ["JSON decoding", "json", (cause) => decodeResponse("application/json", "[]", new CodecRegistry([{ + ...compileIR(rows), get ir(): never { throw cause; }, + }]))], +]; + +test.each(entries)("%s wraps a revoking error proxy with %s", (name, code, run) => { + const ErrorClass = name === "JSON encoding" ? EncodeError : name === "JSON decoding" ? DecodeError : HyperflyError; + const hostile = revokingError(new ErrorClass(code, "hostile")); + let caught: unknown; + try { run(hostile.proxy); } catch (error) { caught = error; } + expect(caught).toBeInstanceOf(HyperflyError); + expect((caught as HyperflyError).code).toBe(code); + expect((caught as HyperflyError).cause).toBe(hostile.proxy); + expect(hostile.codeReads()).toBe(0); +}); + +test.each(["encode", "encodeBody", "decode", "decodeBody"] as const)("Zod %s wraps a revoking parse error", (method) => { + const hostile = revokingError(new HyperflyError("validation", "hostile")); + const schema = z.string(); + const codec = compile(schema, { validate: true }); + const plain = compileIR({ kind: "string" }); + schema.parse = () => { throw hostile.proxy; }; + let caught: unknown; + try { + if (method === "encode" || method === "encodeBody") codec[method]("value"); + else codec[method](method === "decode" ? plain.encode("value") : plain.encodeBody("value")); + } catch (error) { caught = error; } + expect(caught).toBeInstanceOf(method.startsWith("encode") ? EncodeError : DecodeError); + expect((caught as HyperflyError).code).toBe("validation"); + expect((caught as HyperflyError).cause).toBe(hostile.proxy); + expect(hostile.codeReads()).toBe(0); +}); + +test("caught Hyperfly error classification never inspects proxies or forged prototypes", () => { + for (const ErrorClass of [HyperflyError, EncodeError, DecodeError]) { + const original = new ErrorClass("json", "original"); + let prototypeReads = 0; + const proxy = new Proxy(original, { getPrototypeOf() { prototypeReads++; throw new Error("must not inspect prototype"); } }); + expect(isInstance(original, ErrorClass)).toBe(true); + expect(isInstance(proxy, ErrorClass)).toBe(false); + expect(isInstance(Object.create(ErrorClass.prototype), ErrorClass)).toBe(false); + expect(prototypeReads).toBe(0); + } +}); diff --git a/packages/hyperfly/test/codec.test.ts b/packages/hyperfly/test/codec.test.ts index 0b5d0d9..c1eafea 100644 --- a/packages/hyperfly/test/codec.test.ts +++ b/packages/hyperfly/test/codec.test.ts @@ -751,7 +751,7 @@ describe("struct values", () => { expect(() => bytes.encode(make() as never)).toThrow(expect.objectContaining({ code: "type", message: "$: expected Uint8Array" })); }); - test.todo("a bytes subclass with an overridden length is measured by its real length (deferred: PR #85 Deferred)", () => { + test("a bytes subclass with an overridden length is measured by its real length", () => { class Lying extends Uint8Array { override get length(): number { return 0; } } @@ -759,6 +759,18 @@ describe("struct values", () => { expect(bytes.decode(bytes.encode(new Lying([1, 2])))).toEqual(new Uint8Array([1, 2])); }); + test.each([ + [127, [0x7f]], [128, [0x80, 0x01]], [16383, [0xff, 0x7f]], [16384, [0x80, 0x80, 0x01]], + ] as const)("bytes subclasses preserve ULEB length boundaries at %i", (length, prefix) => { + class Lying extends Uint8Array { + override get length(): number { return 0; } + } + const codec = compileIR({ kind: "bytes" }); + const encoded = codec.encodeBody(new Lying(length).fill(7)); + expect(encoded.subarray(0, prefix.length)).toEqual(new Uint8Array(prefix)); + expect(codec.decodeBody(encoded)).toEqual(new Uint8Array(length).fill(7)); + }); + test("encodes a bytes value from another realm", () => { const foreign = runInNewContext("new Uint8Array([1, 2])") as Uint8Array; expect(foreign instanceof Uint8Array).toBe(false); diff --git a/packages/hyperfly/test/columnar.test.ts b/packages/hyperfly/test/columnar.test.ts index a3336fb..97373f4 100644 --- a/packages/hyperfly/test/columnar.test.ts +++ b/packages/hyperfly/test/columnar.test.ts @@ -6,6 +6,8 @@ import { compileIR, FingerprintMismatchError, train, type IRNode } from "../src/ import { toHex } from "../src/canonical.js"; import { EncodeError, HyperflyError } from "../src/errors.js"; import { compile } from "../src/zod.js"; +import { defaultPackHooks } from "../src/pack.js"; +import { bytesSubclasses } from "./bytes-subclasses.js"; function fromHex(hex: string): Uint8Array { const out = new Uint8Array(hex.length / 2); @@ -82,6 +84,19 @@ describe("packed string columns", () => { body: `the quick brown fox jumps over the lazy dog and files report number ${i} about the same fox again`, })); + test.each(bytesSubclasses)("packed lengths and copies ignore overridden %s", (_, make) => { + const hooks = defaultPackHooks(); + const normal = compileIR(IR, { plan: "columnar" }); + const codec = compileIR(IR, { + plan: "columnar", + pack: { ...hooks, deflate: (bytes) => make(hooks.deflate!(bytes)) }, + }); + const encoded = codec.encodeBody(prose); + expect(encoded[1]).toBe(0x02); + expect(encoded).toEqual(normal.encodeBody(prose)); + expect(codec.decodeBody(encoded)).toEqual(prose); + }); + test("prose columns pack, shrink, and round-trip", () => { const packedCodec = compileIR(IR, { plan: "columnar" }); const plainCodec = compileIR(IR, { plan: "columnar", pack: false });