|
| 1 | +// Copyright (c) 2026 Cloudflare, Inc. |
| 2 | +// Licensed under the MIT license found in the LICENSE.txt file or at: |
| 3 | +// https://opensource.org/license/mit |
| 4 | + |
| 5 | +// Tests for the receive-side resource limits that guard against untrusted-peer resource |
| 6 | +// exhaustion (issue #184): bigint length cap + numeric validation, message nesting depth, and |
| 7 | +// max message size. See `RpcLimits` / `DEFAULT_LIMITS` in src/serialize.ts. |
| 8 | + |
| 9 | +import { expect, it, describe } from "vitest" |
| 10 | +import { deserialize, serialize, RpcSession, RpcTransport, RpcTarget, DEFAULT_LIMITS, |
| 11 | + DEFAULT_MAX_DEPTH, type RpcLimits } from "../src/index.js" |
| 12 | + |
| 13 | +// Builds the wire string for a value nested inside `depth` escaped-array layers. Each escaped |
| 14 | +// array `[[ inner ]]` adds one level of recursion to the deserializer (evaluateImpl recurses into |
| 15 | +// its single element). The innermost value is the number 1. |
| 16 | +function nestedEscapedArrays(depth: number): string { |
| 17 | + let s = "1"; |
| 18 | + for (let i = 0; i < depth; i++) { |
| 19 | + s = `[[${s}]]`; |
| 20 | + } |
| 21 | + return s; |
| 22 | +} |
| 23 | + |
| 24 | +// Builds a pipeline call whose sole argument is another pipeline call, repeated `depth` times. |
| 25 | +// This crosses the call-argument RpcPayload boundary at every level. |
| 26 | +function nestedCallArgs(depth: number): string { |
| 27 | + let s = "1"; |
| 28 | + for (let i = 0; i < depth; i++) { |
| 29 | + s = `["pipeline",0,["echo"],[${s}]]`; |
| 30 | + } |
| 31 | + return s; |
| 32 | +} |
| 33 | + |
| 34 | +// A one-shot transport that feeds a single pre-baked frame to the session and then blocks, while |
| 35 | +// capturing everything the session sends back. Lets us assert exactly how the session reacts to a |
| 36 | +// hostile incoming message. |
| 37 | +class ScriptedTransport implements RpcTransport { |
| 38 | + sent: string[] = []; |
| 39 | + aborted = false; |
| 40 | + private toReceive: string[]; |
| 41 | + private blockForever = new Promise<string>(() => {}); |
| 42 | + |
| 43 | + constructor(frames: string[]) { |
| 44 | + this.toReceive = [...frames]; |
| 45 | + } |
| 46 | + |
| 47 | + async send(message: string): Promise<void> { |
| 48 | + this.sent.push(message); |
| 49 | + } |
| 50 | + |
| 51 | + async receive(): Promise<string> { |
| 52 | + let next = this.toReceive.shift(); |
| 53 | + return next === undefined ? this.blockForever : next; |
| 54 | + } |
| 55 | + |
| 56 | + abort(reason: any): void { |
| 57 | + this.aborted = true; |
| 58 | + } |
| 59 | + |
| 60 | + // Resolves once the session has sent an ["abort", ...] frame, or rejects after a spin budget. |
| 61 | + async waitForAbort(): Promise<string> { |
| 62 | + for (let i = 0; i < 200; i++) { |
| 63 | + let abortFrame = this.sent.find(m => m.startsWith('["abort"')); |
| 64 | + if (abortFrame !== undefined) return abortFrame; |
| 65 | + await Promise.resolve(); |
| 66 | + } |
| 67 | + throw new Error(`session did not abort; sent: ${JSON.stringify(this.sent)}`); |
| 68 | + } |
| 69 | + |
| 70 | + async expectNoAbort(): Promise<void> { |
| 71 | + for (let i = 0; i < 50; i++) await Promise.resolve(); |
| 72 | + let abortFrame = this.sent.find(m => m.startsWith('["abort"')); |
| 73 | + expect(abortFrame, "session unexpectedly aborted").toBeUndefined(); |
| 74 | + expect(this.aborted, "transport unexpectedly aborted").toBe(false); |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +// Drives a server session that processes a single ["push", expr] frame, returning the transport so |
| 79 | +// the caller can inspect the reaction. |
| 80 | +function pushFrame(expr: string, limits?: Partial<RpcLimits>): ScriptedTransport { |
| 81 | + let transport = new ScriptedTransport([`["push",${expr}]`]); |
| 82 | + new RpcSession(transport, new EchoTarget(), limits ? { limits } : undefined); |
| 83 | + return transport; |
| 84 | +} |
| 85 | + |
| 86 | +class EchoTarget extends RpcTarget { |
| 87 | + echo(value: unknown) { return value; } |
| 88 | +} |
| 89 | + |
| 90 | +describe("bigint deserialization limits", () => { |
| 91 | + it("accepts a legacy decimal bigint at the default digit limit", () => { |
| 92 | + let digits = "9".repeat(DEFAULT_LIMITS.maxBigIntDigits); |
| 93 | + let value = deserialize(`["bigint","${digits}"]`); |
| 94 | + expect(value).toBe(BigInt(digits)); |
| 95 | + }); |
| 96 | + |
| 97 | + it("rejects a bigint over the default digit limit", () => { |
| 98 | + let digits = "9".repeat(DEFAULT_LIMITS.maxBigIntDigits + 1); |
| 99 | + expect(() => deserialize(`["bigint","${digits}"]`)) |
| 100 | + .toThrowError(/bigint exceeds maximum length/); |
| 101 | + }); |
| 102 | + |
| 103 | + it("round-trips bigints through the hex wire format", () => { |
| 104 | + let values = [ |
| 105 | + 0n, |
| 106 | + 255n, |
| 107 | + -255n, |
| 108 | + (1n << 4096n) + 123456789n, |
| 109 | + -((1n << 4096n) + 123456789n), |
| 110 | + ]; |
| 111 | + |
| 112 | + for (let value of values) { |
| 113 | + let wire = serialize(value); |
| 114 | + expect(wire).toMatch(/^\["bigint","-?0x[0-9a-f]+"\]$/); |
| 115 | + expect(deserialize(wire)).toBe(value); |
| 116 | + } |
| 117 | + }); |
| 118 | + |
| 119 | + it("accepts legacy decimal bigint strings", () => { |
| 120 | + expect(deserialize('["bigint","123"]')).toBe(123n); |
| 121 | + expect(deserialize('["bigint","-123"]')).toBe(-123n); |
| 122 | + }); |
| 123 | + |
| 124 | + it("accepts signed and unsigned hex bigint strings", () => { |
| 125 | + expect(deserialize('["bigint","0xff"]')).toBe(255n); |
| 126 | + expect(deserialize('["bigint","-0xff"]')).toBe(-255n); |
| 127 | + expect(deserialize('["bigint","0xFF"]')).toBe(255n); |
| 128 | + }); |
| 129 | + |
| 130 | + it("rejects malformed bigint strings before calling BigInt()", () => { |
| 131 | + expect(() => deserialize('["bigint","0xg"]')).toThrowError(/invalid characters/); |
| 132 | + expect(() => deserialize('["bigint","0x"]')).toThrowError(/invalid characters/); |
| 133 | + expect(() => deserialize('["bigint","-0x"]')).toThrowError(/invalid characters/); |
| 134 | + expect(() => deserialize('["bigint","+0xff"]')).toThrowError(/invalid characters/); |
| 135 | + expect(() => deserialize('["bigint","12n"]')).toThrowError(/invalid characters/); |
| 136 | + expect(() => deserialize('["bigint","1 2"]')).toThrowError(/invalid characters/); |
| 137 | + expect(() => deserialize('["bigint",""]')).toThrowError(/invalid characters/); |
| 138 | + expect(() => deserialize('["bigint","abc"]')).toThrowError(/invalid characters/); |
| 139 | + }); |
| 140 | + |
| 141 | + it("honors a per-session override of maxBigIntDigits", async () => { |
| 142 | + let underLimit = '["bigint","0xff"]'; |
| 143 | + let overLimit = '["bigint","0xfff"]'; |
| 144 | + |
| 145 | + // The cap is applied to the whole bigint string, regardless of radix. |
| 146 | + await pushFrame(underLimit, { maxBigIntDigits: 4 }).expectNoAbort(); |
| 147 | + |
| 148 | + let aborted = await pushFrame(overLimit, { maxBigIntDigits: 4 }).waitForAbort(); |
| 149 | + expect(aborted).toMatch(/bigint exceeds maximum length/); |
| 150 | + |
| 151 | + // The same 5-digit bigint is well under the default limit, so it does NOT abort by default. |
| 152 | + await pushFrame(overLimit).expectNoAbort(); |
| 153 | + }); |
| 154 | +}); |
| 155 | + |
| 156 | +describe("message depth limits", () => { |
| 157 | + it("accepts nesting just under the default depth limit", () => { |
| 158 | + // The top value sits at depth 0, so maxDepth-1 escaped-array layers stay within the limit. |
| 159 | + let value = deserialize(nestedEscapedArrays(DEFAULT_LIMITS.maxDepth - 1)); |
| 160 | + expect(value).toBeInstanceOf(Array); |
| 161 | + }); |
| 162 | + |
| 163 | + it("rejects nesting over the default depth limit", () => { |
| 164 | + expect(() => deserialize(nestedEscapedArrays(DEFAULT_LIMITS.maxDepth + 5))) |
| 165 | + .toThrowError(/maximum allowed message depth/); |
| 166 | + }); |
| 167 | + |
| 168 | + it("honors a per-session override of maxDepth", async () => { |
| 169 | + // Override depth to a small value; nesting beyond it aborts the session. |
| 170 | + let deep = nestedEscapedArrays(10); |
| 171 | + let aborted = await pushFrame(deep, { maxDepth: 4 }).waitForAbort(); |
| 172 | + expect(aborted).toMatch(/maximum allowed message depth/); |
| 173 | + |
| 174 | + // The same depth is well within the default, so by default it does not abort. |
| 175 | + await pushFrame(deep).expectNoAbort(); |
| 176 | + }); |
| 177 | + |
| 178 | + it("does not reset depth across nested call arguments", async () => { |
| 179 | + let aborted = await pushFrame(nestedCallArgs(8), { maxDepth: 8 }).waitForAbort(); |
| 180 | + expect(aborted).toMatch(/maximum allowed message depth/); |
| 181 | + }); |
| 182 | + |
| 183 | + it("accepts nested call arguments within the default depth limit", async () => { |
| 184 | + await pushFrame(nestedCallArgs(64)).expectNoAbort(); |
| 185 | + }); |
| 186 | + |
| 187 | + it("accepts near-limit call arguments that the default sender can serialize", async () => { |
| 188 | + let appArg = deserialize(nestedEscapedArrays(DEFAULT_MAX_DEPTH - 2)); |
| 189 | + let wireArgs = JSON.parse(serialize([appArg]))[0]; |
| 190 | + await pushFrame(`["pipeline",0,["echo"],${JSON.stringify(wireArgs)}]`).expectNoAbort(); |
| 191 | + }); |
| 192 | +}); |
| 193 | + |
| 194 | +describe("message size limits", () => { |
| 195 | + it("aborts the session on a message over the size limit", async () => { |
| 196 | + // The pushed expression is a long-but-valid JSON string literal, so the resulting frame is |
| 197 | + // valid JSON and well over the 64-char override. The size check runs (and aborts) before |
| 198 | + // JSON.parse, so this exercises the size guard specifically, not a parse error. |
| 199 | + let aborted = await pushFrame(`"${"a".repeat(200)}"`, { maxMessageSize: 64 }).waitForAbort(); |
| 200 | + expect(aborted).toMatch(/exceeds maximum size/); |
| 201 | + }); |
| 202 | + |
| 203 | + it("does not abort on a message under the size limit", async () => { |
| 204 | + await pushFrame('"small"', { maxMessageSize: 1024 }).expectNoAbort(); |
| 205 | + }); |
| 206 | +}); |
| 207 | + |
| 208 | +describe("limits backwards compatibility", () => { |
| 209 | + it("DEFAULT_LIMITS has the documented values", () => { |
| 210 | + expect(DEFAULT_MAX_DEPTH).toBe(256); |
| 211 | + expect(DEFAULT_LIMITS).toStrictEqual({ |
| 212 | + maxBigIntDigits: 16384, |
| 213 | + maxDepth: DEFAULT_MAX_DEPTH, |
| 214 | + maxMessageSize: 32 * 1024 * 1024, |
| 215 | + }); |
| 216 | + }); |
| 217 | + |
| 218 | + it("standalone deserialize round-trips normal values unchanged with no config", () => { |
| 219 | + expect(deserialize('["bigint","123"]')).toBe(123n); |
| 220 | + expect(deserialize(serialize(12345678901234567890n))).toBe(12345678901234567890n); |
| 221 | + expect(deserialize('[[[[123,456]]]]')).toStrictEqual([[123, 456]]); |
| 222 | + expect(deserialize('{"foo":{"bar":123}}')).toStrictEqual({foo: {bar: 123}}); |
| 223 | + }); |
| 224 | + |
| 225 | + it("a session constructed with no options behaves exactly as before", async () => { |
| 226 | + // A legitimate bigint, normal nesting, and a normal call all flow through a default session |
| 227 | + // without aborting. |
| 228 | + using harness = new SessionPair(new EchoTarget()); |
| 229 | + |
| 230 | + let stub = harness.stub as any; |
| 231 | + expect(await stub.echo(123n)).toBe(123n); |
| 232 | + expect(await stub.echo([[1, 2, 3]])).toStrictEqual([[1, 2, 3]]); |
| 233 | + expect(await stub.echo({a: {b: {c: 1}}})).toStrictEqual({a: {b: {c: 1}}}); |
| 234 | + |
| 235 | + await harness.dispose(); |
| 236 | + }); |
| 237 | + |
| 238 | + it("a session constructed with an empty options object behaves identically", async () => { |
| 239 | + using harness = new SessionPair(new EchoTarget(), {}); |
| 240 | + let stub = harness.stub as any; |
| 241 | + expect(await stub.echo(999n)).toBe(999n); |
| 242 | + await harness.dispose(); |
| 243 | + }); |
| 244 | +}); |
| 245 | + |
| 246 | +// A minimal in-memory bidirectional session pair, sufficient for the round-trip checks above. |
| 247 | +class PairTransport implements RpcTransport { |
| 248 | + partner!: PairTransport; |
| 249 | + private queue: string[] = []; |
| 250 | + private waiter?: () => void; |
| 251 | + |
| 252 | + async send(message: string): Promise<void> { |
| 253 | + this.partner.queue.push(message); |
| 254 | + this.partner.waiter?.(); |
| 255 | + this.partner.waiter = undefined; |
| 256 | + } |
| 257 | + |
| 258 | + async receive(): Promise<string> { |
| 259 | + while (this.queue.length === 0) { |
| 260 | + await new Promise<void>(resolve => { this.waiter = resolve; }); |
| 261 | + } |
| 262 | + return this.queue.shift()!; |
| 263 | + } |
| 264 | +} |
| 265 | + |
| 266 | +class SessionPair { |
| 267 | + private clientTransport = new PairTransport(); |
| 268 | + private serverTransport = new PairTransport(); |
| 269 | + private client: RpcSession; |
| 270 | + private server: RpcSession; |
| 271 | + stub: ReturnType<RpcSession["getRemoteMain"]>; |
| 272 | + |
| 273 | + constructor(target: RpcTarget, options?: { limits?: Partial<RpcLimits> }) { |
| 274 | + this.clientTransport.partner = this.serverTransport; |
| 275 | + this.serverTransport.partner = this.clientTransport; |
| 276 | + this.client = new RpcSession(this.clientTransport); |
| 277 | + this.server = new RpcSession(this.serverTransport, target, options); |
| 278 | + this.stub = this.client.getRemoteMain(); |
| 279 | + } |
| 280 | + |
| 281 | + async dispose() { |
| 282 | + for (let i = 0; i < 16; i++) await Promise.resolve(); |
| 283 | + } |
| 284 | + |
| 285 | + [Symbol.dispose]() {} |
| 286 | +} |
0 commit comments