fix: keep Browser RPC collaborator input and output inside the contract
RPC-RR-02. The server-stream path captured the generation fence outside its protected boundary and raceWithin invoked clock.sleep outside a promise boundary, so a synchronous throw from either escaped the Result contract and skipped the listener and timer release. Both now run inside the boundary, and release moved to finally. RPC-RR-03. The runtime snapshotted its transports only after validating the caller's raw objects, which ran their accessors first. It now decodes the registry from own data descriptors before anything reads it — refusing an accessor without invoking it and rejecting extra, inherited and symbol-keyed fields — and validates that snapshot. Every installed binding registry is a read facade over a private store instead of a frozen Map whose set, delete and clear still worked. RPC-RR-04. Transport results and stream frames are decoded per union variant from own data descriptors into new frozen values. A throwing getter, an inherited or extra field, a symbol key, an unknown failure code and an out-of-range retryAfterMs all close as protocol failures instead of escaping. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
6a8281a941
commit
bd90e0c983
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
createReadOnlyRegistry,
|
||||
type ReadOnlyRegistry,
|
||||
} from "../../contracts/read-only-registry.ts";
|
||||
import type {
|
||||
BrowserRpcGenerationFence,
|
||||
BrowserRpcServerStreamPort,
|
||||
@@ -107,7 +111,11 @@ export function createBrowserRpcRuntime(
|
||||
const clock = dependencies.clock ?? systemClock;
|
||||
const generationFence =
|
||||
dependencies.generationFence ?? stableGenerationFence;
|
||||
validateRuntimeDependencies(dependencies);
|
||||
// RPC-RR-03. Snapshot before validating. Reading the caller's transport
|
||||
// objects first would run their accessors, letting a hostile getter observe
|
||||
// validation and then return something else to the runtime.
|
||||
const installedTransports = snapshotTransports(dependencies.transports);
|
||||
validateRuntimeDependencies(dependencies, installedTransports);
|
||||
// R-04. Install exact immutable snapshots once. Every later `bind()` reads
|
||||
// the snapshot, never the caller's registry objects, so a post-composition
|
||||
// mutation cannot change replay policy, deadlines, byte ceilings or
|
||||
@@ -119,7 +127,6 @@ export function createBrowserRpcRuntime(
|
||||
mappers: dependencies.mappers,
|
||||
requestEncoders: dependencies.requestEncoders,
|
||||
});
|
||||
const installedTransports = snapshotTransports(dependencies.transports);
|
||||
|
||||
function bind(
|
||||
operationId: string,
|
||||
@@ -457,7 +464,6 @@ async function* executeServerStream<Event>(
|
||||
clock: ClockPort,
|
||||
): AsyncIterable<Result<Event, AppFailure>> {
|
||||
const { operation, profile, encoder, transport } = bound;
|
||||
const generation = generationFence.capture();
|
||||
const deadlineAt = safeNowOrDeadline(clock, 0) + operation.totalDeadlineMs;
|
||||
const linked = linkedAbortController(context.signal);
|
||||
let iterator: AsyncIterator<BrowserRpcStreamFrame> | null = null;
|
||||
@@ -470,6 +476,23 @@ async function* executeServerStream<Event>(
|
||||
observe(dependencies, operation, outcome, 1, messageCount);
|
||||
};
|
||||
|
||||
// RPC-RR-02. The fence is a caller collaborator, so a synchronous throw from
|
||||
// it is an ordinary failure of this call. Capturing outside the protected
|
||||
// boundary let that throw escape the stream's Result contract entirely.
|
||||
const generation = safeCapture(generationFence);
|
||||
if (generation === FENCE_FAILURE) {
|
||||
finish("FAILED");
|
||||
yield failureResult(
|
||||
callFailure(
|
||||
operation,
|
||||
0,
|
||||
"SCOPE_GENERATION_CHANGED",
|
||||
"RPC_SCOPE_GENERATION_UNAVAILABLE",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const contextFailure = validateCallContext(operation, context, 0);
|
||||
if (contextFailure) {
|
||||
@@ -711,9 +734,23 @@ async function* executeServerStream<Event>(
|
||||
* R-04. Transports are collaborators, not data rows, so only their identity is
|
||||
* snapshotted; the callable itself is captured once and rebound.
|
||||
*/
|
||||
const TRANSPORT_KEYS: ReadonlySet<string> = new Set([
|
||||
"runtimeProfileId",
|
||||
"providerId",
|
||||
"protocol",
|
||||
"rpcKind",
|
||||
"invokeUnary",
|
||||
"openServerStream",
|
||||
]);
|
||||
|
||||
/**
|
||||
* RPC-RR-03. Decodes the transport registry from own data descriptors only, so
|
||||
* no accessor on a caller's object is ever invoked, and returns a read facade
|
||||
* whose backing store cannot be reached by `set`, `delete` or `clear`.
|
||||
*/
|
||||
function snapshotTransports(
|
||||
source: Readonly<Record<string, BrowserRpcTransport>>,
|
||||
): ReadonlyMap<string, BrowserRpcTransport> {
|
||||
): ReadOnlyRegistry<string, BrowserRpcTransport> {
|
||||
const installed = new Map<string, BrowserRpcTransport>();
|
||||
if (Object.getOwnPropertySymbols(source).length > 0) {
|
||||
throw new TypeError("Browser RPC transport registry has symbol keys.");
|
||||
@@ -725,28 +762,59 @@ function snapshotTransports(
|
||||
`Browser RPC transport registry entry is not a data property: ${key}`,
|
||||
);
|
||||
}
|
||||
const transport = descriptor.value as BrowserRpcTransport;
|
||||
const transport = descriptor.value as unknown;
|
||||
if (!transport || typeof transport !== "object") {
|
||||
throw new TypeError(
|
||||
`Browser RPC transport registry entry is not an object: ${key}`,
|
||||
);
|
||||
}
|
||||
if (Object.getOwnPropertySymbols(transport).length > 0) {
|
||||
throw new TypeError(
|
||||
`Browser RPC transport row has symbol keys: ${key}`,
|
||||
);
|
||||
}
|
||||
const row: Record<string, unknown> = Object.create(null);
|
||||
for (const field of Object.getOwnPropertyNames(transport)) {
|
||||
if (!TRANSPORT_KEYS.has(field)) {
|
||||
throw new TypeError(
|
||||
`Browser RPC transport row has an unexpected key: ${key}.${field}`,
|
||||
);
|
||||
}
|
||||
const fieldDescriptor = Object.getOwnPropertyDescriptor(
|
||||
transport,
|
||||
field,
|
||||
);
|
||||
if (!fieldDescriptor || !("value" in fieldDescriptor)) {
|
||||
throw new TypeError(
|
||||
`Browser RPC transport row key is not a data property: ${key}.${field}`,
|
||||
);
|
||||
}
|
||||
row[field] = fieldDescriptor.value;
|
||||
}
|
||||
const invokeUnary = row.invokeUnary;
|
||||
const openServerStream = row.openServerStream;
|
||||
installed.set(
|
||||
key,
|
||||
Object.freeze({
|
||||
runtimeProfileId: transport.runtimeProfileId,
|
||||
providerId: transport.providerId,
|
||||
protocol: transport.protocol,
|
||||
rpcKind: transport.rpcKind,
|
||||
...(transport.invokeUnary
|
||||
? { invokeUnary: transport.invokeUnary.bind(transport) }
|
||||
runtimeProfileId: row.runtimeProfileId,
|
||||
providerId: row.providerId,
|
||||
protocol: row.protocol,
|
||||
rpcKind: row.rpcKind,
|
||||
...(typeof invokeUnary === "function"
|
||||
? { invokeUnary: invokeUnary.bind(transport) }
|
||||
: {}),
|
||||
...(transport.openServerStream
|
||||
? { openServerStream: transport.openServerStream.bind(transport) }
|
||||
...(typeof openServerStream === "function"
|
||||
? { openServerStream: openServerStream.bind(transport) }
|
||||
: {}),
|
||||
}) as BrowserRpcTransport,
|
||||
);
|
||||
}
|
||||
return Object.freeze(installed) as ReadonlyMap<string, BrowserRpcTransport>;
|
||||
return createReadOnlyRegistry(installed);
|
||||
}
|
||||
|
||||
function validateRuntimeDependencies(
|
||||
dependencies: BrowserRpcRuntimeDependencies,
|
||||
transports: ReadOnlyRegistry<string, BrowserRpcTransport>,
|
||||
): void {
|
||||
const runtimeBindings: Record<
|
||||
string,
|
||||
@@ -755,9 +823,7 @@ function validateRuntimeDependencies(
|
||||
"runtimeProfileId" | "providerId" | "protocol" | "rpcKind"
|
||||
>
|
||||
> = Object.create(null);
|
||||
for (const [profileId, transport] of Object.entries(
|
||||
dependencies.transports,
|
||||
)) {
|
||||
for (const [profileId, transport] of transports.entries()) {
|
||||
if (
|
||||
profileId !== transport.runtimeProfileId ||
|
||||
Object.hasOwn(runtimeBindings, profileId)
|
||||
@@ -782,7 +848,7 @@ function validateRuntimeDependencies(
|
||||
runtimeBindings: Object.freeze(runtimeBindings),
|
||||
});
|
||||
for (const operation of Object.values(dependencies.operations)) {
|
||||
if (!dependencies.transports[operation.runtimeProfileId]) {
|
||||
if (!transports.has(operation.runtimeProfileId)) {
|
||||
throw new TypeError(
|
||||
`Browser RPC transport is missing: ${operation.operationId}`,
|
||||
);
|
||||
@@ -1072,29 +1138,145 @@ function safelyMatches<Output>(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RPC-RR-04. A transport value is decoded, never adopted.
|
||||
*
|
||||
* `in` and a direct property read run accessors, so a throwing getter escapes
|
||||
* the Result contract and an inherited or extra field passes unseen. Each
|
||||
* variant is decoded from own data descriptors into a new frozen value, so a
|
||||
* transport that mutates its own object after returning it cannot change what
|
||||
* the runtime already admitted.
|
||||
*/
|
||||
function ownDataValue(source: unknown, key: string): unknown {
|
||||
if (source === null || typeof source !== "object") return undefined;
|
||||
try {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(source, key);
|
||||
if (!descriptor || !("value" in descriptor)) return undefined;
|
||||
return descriptor.value;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function exactOwnKeys(
|
||||
source: unknown,
|
||||
allowed: ReadonlySet<string>,
|
||||
): boolean {
|
||||
if (source === null || typeof source !== "object") return false;
|
||||
try {
|
||||
if (Object.getOwnPropertySymbols(source).length > 0) return false;
|
||||
for (const key of Object.getOwnPropertyNames(source)) {
|
||||
if (!allowed.has(key)) return false;
|
||||
const descriptor = Object.getOwnPropertyDescriptor(source, key);
|
||||
if (!descriptor || !("value" in descriptor)) return false;
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const UNARY_OK_KEYS: ReadonlySet<string> = new Set([
|
||||
"ok",
|
||||
"message",
|
||||
"encodedBytes",
|
||||
]);
|
||||
const UNARY_FAILED_KEYS: ReadonlySet<string> = new Set(["ok", "failure"]);
|
||||
const FRAME_MESSAGE_KEYS: ReadonlySet<string> = new Set([
|
||||
"kind",
|
||||
"message",
|
||||
"encodedBytes",
|
||||
]);
|
||||
const FRAME_TERMINAL_OK_KEYS: ReadonlySet<string> = new Set(["kind", "ok"]);
|
||||
const FRAME_TERMINAL_FAILED_KEYS: ReadonlySet<string> = new Set([
|
||||
"kind",
|
||||
"ok",
|
||||
"failure",
|
||||
]);
|
||||
const TRANSPORT_FAILURE_KEYS: ReadonlySet<string> = new Set([
|
||||
"code",
|
||||
"retryAfterMs",
|
||||
]);
|
||||
|
||||
function validateUnaryTransportResult(
|
||||
value: unknown,
|
||||
): BrowserRpcUnaryTransportResult | null {
|
||||
if (!value || typeof value !== "object" || !("ok" in value)) return null;
|
||||
const candidate = value as BrowserRpcUnaryTransportResult;
|
||||
if (candidate.ok) {
|
||||
return validEncodedByteCount(candidate.encodedBytes, Number.MAX_SAFE_INTEGER)
|
||||
? candidate
|
||||
: null;
|
||||
const ok = ownDataValue(value, "ok");
|
||||
if (typeof ok !== "boolean") return null;
|
||||
if (ok) {
|
||||
if (!exactOwnKeys(value, UNARY_OK_KEYS)) return null;
|
||||
const encodedBytes = ownDataValue(value, "encodedBytes");
|
||||
if (!validEncodedByteCount(encodedBytes, Number.MAX_SAFE_INTEGER)) {
|
||||
return null;
|
||||
}
|
||||
return Object.freeze({
|
||||
ok: true as const,
|
||||
message: ownDataValue(value, "message"),
|
||||
encodedBytes,
|
||||
});
|
||||
}
|
||||
return validTransportFailure(candidate.failure) ? candidate : null;
|
||||
if (!exactOwnKeys(value, UNARY_FAILED_KEYS)) return null;
|
||||
const failure = decodeTransportFailure(ownDataValue(value, "failure"));
|
||||
return failure === null
|
||||
? null
|
||||
: Object.freeze({ ok: false as const, failure });
|
||||
}
|
||||
|
||||
function validateStreamFrame(value: unknown): BrowserRpcStreamFrame | null {
|
||||
if (!value || typeof value !== "object" || !("kind" in value)) return null;
|
||||
const frame = value as BrowserRpcStreamFrame;
|
||||
if (frame.kind === "MESSAGE") {
|
||||
return validEncodedByteCount(frame.encodedBytes, Number.MAX_SAFE_INTEGER)
|
||||
? frame
|
||||
: null;
|
||||
const kind = ownDataValue(value, "kind");
|
||||
if (kind === "MESSAGE") {
|
||||
if (!exactOwnKeys(value, FRAME_MESSAGE_KEYS)) return null;
|
||||
const encodedBytes = ownDataValue(value, "encodedBytes");
|
||||
if (!validEncodedByteCount(encodedBytes, Number.MAX_SAFE_INTEGER)) {
|
||||
return null;
|
||||
}
|
||||
return Object.freeze({
|
||||
kind: "MESSAGE" as const,
|
||||
message: ownDataValue(value, "message"),
|
||||
encodedBytes,
|
||||
});
|
||||
}
|
||||
if (frame.kind !== "TERMINAL" || typeof frame.ok !== "boolean") return null;
|
||||
return frame.ok || validTransportFailure(frame.failure) ? frame : null;
|
||||
if (kind !== "TERMINAL") return null;
|
||||
const ok = ownDataValue(value, "ok");
|
||||
if (typeof ok !== "boolean") return null;
|
||||
if (ok) {
|
||||
if (!exactOwnKeys(value, FRAME_TERMINAL_OK_KEYS)) return null;
|
||||
return Object.freeze({ kind: "TERMINAL" as const, ok: true as const });
|
||||
}
|
||||
if (!exactOwnKeys(value, FRAME_TERMINAL_FAILED_KEYS)) return null;
|
||||
const failure = decodeTransportFailure(ownDataValue(value, "failure"));
|
||||
return failure === null
|
||||
? null
|
||||
: Object.freeze({
|
||||
kind: "TERMINAL" as const,
|
||||
ok: false as const,
|
||||
failure,
|
||||
});
|
||||
}
|
||||
|
||||
function decodeTransportFailure(
|
||||
value: unknown,
|
||||
): BrowserRpcTransportFailure | null {
|
||||
if (!exactOwnKeys(value, TRANSPORT_FAILURE_KEYS)) return null;
|
||||
const code = ownDataValue(value, "code");
|
||||
const retryAfterMs = ownDataValue(value, "retryAfterMs");
|
||||
if (!TRANSPORT_FAILURE_CODES.has(code as BrowserRpcTransportFailureCode)) {
|
||||
return null;
|
||||
}
|
||||
if (retryAfterMs === undefined) {
|
||||
return Object.freeze({ code: code as BrowserRpcTransportFailureCode });
|
||||
}
|
||||
if (
|
||||
!Number.isSafeInteger(retryAfterMs) ||
|
||||
(retryAfterMs as number) < 0 ||
|
||||
(retryAfterMs as number) > BROWSER_RPC_HARD_LIMITS.maxRetryAfterMs
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return Object.freeze({
|
||||
code: code as BrowserRpcTransportFailureCode,
|
||||
retryAfterMs: retryAfterMs as number,
|
||||
});
|
||||
}
|
||||
|
||||
function validTransportFailure(
|
||||
@@ -1240,8 +1422,12 @@ function failureResult(
|
||||
return Object.freeze({ ok: false, error });
|
||||
}
|
||||
|
||||
function validEncodedByteCount(value: number, maximum: number): boolean {
|
||||
function validEncodedByteCount(
|
||||
value: unknown,
|
||||
maximum: number,
|
||||
): value is number {
|
||||
return (
|
||||
typeof value === "number" &&
|
||||
Number.isSafeInteger(value) &&
|
||||
value >= 0 &&
|
||||
value <= maximum
|
||||
@@ -1274,23 +1460,29 @@ async function raceWithin<Value>(
|
||||
const timerController = new AbortController();
|
||||
const onAbort = () => timerController.abort(signal.reason);
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
const workResult = work.then<TimedResult<Value>, TimedResult<Value>>(
|
||||
(value) => Object.freeze({ kind: "VALUE", value }),
|
||||
() => Object.freeze({ kind: "THREW" }),
|
||||
);
|
||||
const timerResult = clock.sleep(milliseconds, timerController.signal).then<
|
||||
TimedResult<Value>,
|
||||
TimedResult<Value>
|
||||
>(
|
||||
() => Object.freeze({ kind: "TIMEOUT" }),
|
||||
() => Object.freeze({ kind: "ABORTED" }),
|
||||
);
|
||||
const selected = await Promise.race([workResult, timerResult]);
|
||||
timerController.abort("race-complete");
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
return signal.aborted && selected.kind === "VALUE"
|
||||
? Object.freeze({ kind: "ABORTED" })
|
||||
: selected;
|
||||
try {
|
||||
const workResult = work.then<TimedResult<Value>, TimedResult<Value>>(
|
||||
(value) => Object.freeze({ kind: "VALUE", value }),
|
||||
() => Object.freeze({ kind: "THREW" }),
|
||||
);
|
||||
// RPC-RR-02. A clock is an external collaborator: calling `sleep` inside a
|
||||
// promise boundary turns its synchronous throw into a normalized rejection
|
||||
// instead of an exception that escapes the Result contract and skips the
|
||||
// listener and timer release below.
|
||||
const timerResult = Promise.resolve()
|
||||
.then(() => clock.sleep(milliseconds, timerController.signal))
|
||||
.then<TimedResult<Value>, TimedResult<Value>>(
|
||||
() => Object.freeze({ kind: "TIMEOUT" }),
|
||||
() => Object.freeze({ kind: "ABORTED" }),
|
||||
);
|
||||
const selected = await Promise.race([workResult, timerResult]);
|
||||
return signal.aborted && selected.kind === "VALUE"
|
||||
? Object.freeze({ kind: "ABORTED" })
|
||||
: selected;
|
||||
} finally {
|
||||
timerController.abort("race-complete");
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
}
|
||||
|
||||
function observe(
|
||||
|
||||
Reference in New Issue
Block a user