feat(mesh): carry the caller's identity across the wire, and bound what an unauthenticated peer can do
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 18s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 18s

The observability release gave every request an id and lost it at the process
boundary — in the one place a distributed trace is the entire point. The RPC
envelope now carries requestId, traceId and url, and the teapot adopts them
instead of opening its own investigation.

Both fields are optional on the wire, so the protocol version does not move.
That decision needed a rule rather than a judgement call, so the rule is now
written beside the constant: bump when an old peer would misparse or misbehave
silently, not when work happened. Bumping per change would make the number
mean the opposite of what it is for.

Three things found while in here:

- mesh:rpc:error emitted the per-link counter where every other emitter puts a
  name, so the two sides of one failure could not be matched up.
- The teapot had no handshake deadline, so an unauthenticated peer could hold
  a socket by saying nothing, and no frame size cap, so it could make the
  process JSON.parse up to whatever the socket layer allowed — 100 MiB with
  the ws defaults, before authenticating.
- The remote-route envelope was cast from the internal request object, putting
  ip and protocol on the wire as fields the protocol never declared.

The cleartext warning is a warning and not a refusal on purpose: a private
network already doing mutual TLS is legitimate, and green-tea cannot tell it
apart from an exposed one.

4 of the 8 new tests verified to fail against the old code; the rest are the
negative cases, which should pass both before and after. The Deno test drives
the teapot's frame loop with a raw client, because server-side close codes are
where these runtimes have already differed once.

431 vitest / 12 Deno / 7 Bun / edge / JSR dry run.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-18 11:15:54 -05:00
1 parent 1ccbf6cadf
commit f2cb411eac
8 files changed
+472 -10

No files matched your search

+49 -2
View File
@@ -615,6 +615,26 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
}
}
/**
* Warn when a teapot's shared secret would cross a network in cleartext.
*
* The `hello` frame carries the secret verbatim, so `ws://` to anywhere but this machine puts it on
* the wire for anyone in the path to read. Loopback is exempt because there is no path.
*
* A warning rather than a refusal: a private network behind a service mesh that already does mutual
* TLS is a legitimate deployment, and green-tea cannot tell it apart from an exposed one.
*/
function warnIfCleartext(url: string, logger: Logger): void {
if (!url.startsWith('ws://')) return;
const host = url.slice('ws://'.length).split('/')[0].split(':')[0];
if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]') return;
logger.warn(
`mesh: ${url} is not encrypted, and the shared secret is sent in the handshake — ` +
'use wss:// unless the link already runs inside an encrypted network.',
);
}
/**
* Re-register a link's app-scope bindings after it reconnects, so their next resolve re-runs the RPC.
*
@@ -642,6 +662,7 @@ async function spliceRemoteScopes(
try {
for (const teapot of mesh.teapots ?? []) {
warnIfCleartext(teapot.url, logger);
// Deferred so the reconnect callback can name this link's provider tokens, which are only
// known once its manifest arrives — the callback is registered before the link can drop.
const rebind: Array<() => void> = [];
@@ -717,7 +738,19 @@ async function spliceRemoteScopes(
method: route.method,
pattern: route.pattern,
transport: 'buffer',
handler: async (req) => route.handler(req as RequestEnvelope),
// Built explicitly rather than cast from the handler argument. The cast put the whole
// internal request on the wire — `ip` and `protocol` included — and sent fields the
// protocol never declared, so a teapot could come to rely on something we never promised.
handler: async (req) =>
route.handler({
method: req.method,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId },
}),
});
}
}
@@ -867,7 +900,14 @@ function buildMeshControl(
if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name));
const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! }));
const context = await runSteps(steps, seed, bus);
// The caller's identity, adopted rather than replaced — the same rule an incoming
// `x-request-id` gets, applied at the process boundary where it matters most. No `route`:
// resolving a scope is not a route, and inventing one would put a token in a route label.
const context = await runSteps(steps, seed, bus, {
requestId: env.correlation?.requestId,
traceId: env.correlation?.traceId,
method: env.method,
});
return context[name];
};
@@ -889,6 +929,13 @@ function buildMeshControl(
bus,
onError,
transport: plan.transport,
correlation: {
requestId: env.correlation?.requestId,
traceId: env.correlation?.traceId,
route: plan.pattern,
method: plan.method,
transport: plan.transport,
},
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
});
+7 -2
View File
@@ -32,6 +32,8 @@ export type ManifestPolicy = 'refuse';
/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
type PendingEntry = {
/** The token or route asked for. Kept so an error can be reported by name — the frame only carries the id. */
name: string;
resolve: (v: unknown) => void;
reject: (e: unknown) => void;
timer: ReturnType<typeof setTimeout>;
@@ -94,7 +96,7 @@ function sendRpc(
rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
}, timeoutMs);
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer });
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
});
}
@@ -113,7 +115,10 @@ function settleRpcResponse(
if (frame.ok) {
entry.resolve(frame.result);
} else {
bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
// `entry.name`, not `frame.id`: the id is a per-link counter, so this event used to report
// "0" or "1" where every other emitter reports what failed — including the teapot's own
// emit for the same call, which made the two sides of one failure impossible to line up.
bus?.emit('mesh:rpc:error', { name: entry.name, error: frame.error });
entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
}
}
+31 -3
View File
@@ -1,18 +1,46 @@
/**
* Version of the mesh wire protocol. Peers are separate processes on separate deploy
* cadences — possibly on different runtimes — so the frame shapes are a contract between
* green-tea versions, not an internal detail. Bump on any breaking frame change; peers
* refuse each other on mismatch rather than misparsing downstream.
* green-tea versions, not an internal detail. Peers refuse each other on mismatch rather
* than misparsing downstream.
*
* **This is a compatibility boundary, not a changelog.** Bump it only when a peer running the
* old version would *misparse a frame or misbehave silently*:
*
* - removing or renaming a field, or changing its type or meaning;
* - adding a **required** field;
* - adding a frame type that expects an answer — an old peer cannot decode it, drops it as
* undecodable, and the sender waits for a reply that will never come.
*
* Adding an **optional** field is not one of those: `decode` validates only the fields a frame
* type requires and passes extras through untouched, so an old peer ignores what it does not
* know and keeps answering. That is degraded, not broken, and does not earn a bump.
*
* Bumping per change would make the number mean "work happened" rather than "we are
* incompatible", which is the one thing it is here to say.
*/
export const MESH_PROTOCOL_VERSION = 1;
/** Serialized request context sent across the mesh for a scope or route RPC. */
/**
* Serialized request context sent across the mesh for a scope or route RPC.
*
* `correlation` and `url` are optional by protocol, not by intent: a teapot running an older
* green-tea simply ignores them, which costs the correlation of that hop and nothing else.
*/
export interface RequestEnvelope {
method: string;
params: Record<string, string>;
query: Record<string, string>;
body: unknown;
headers: Record<string, string | string[] | undefined>;
/** The requested URL, so a teapot's handler sees the same path its caller did. */
url?: string;
/**
* The caller's request identity, so a request that crosses the mesh keeps one id end to end.
* Without it every hop opens a new investigation, in the one place a distributed trace is
* the whole point.
*/
correlation?: { requestId?: string; traceId?: string };
}
/** Manifest entry for an exported scope token and its lifetime. */
+14 -2
View File
@@ -14,14 +14,26 @@ export interface RemoteRoute {
handler: (req: RequestEnvelope) => Promise<ResponseShape>;
}
/** Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh. */
/**
* Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh.
*
* `url` and `correlation` are read off `ctx.req`, the handler argument the pipeline seeds the
* context with — so a request that crosses to a teapot arrives carrying the id it already had,
* and its events on the far side join the same trace instead of starting a new one.
*/
export function envelopeFrom(ctx: any): RequestEnvelope {
const req = ctx?.req;
const correlation = { requestId: req?.requestId, traceId: req?.traceId };
return {
method: ctx?.req?.method ?? ctx?.method ?? 'GET',
method: req?.method ?? ctx?.method ?? 'GET',
params: ctx?.params ?? {},
query: ctx?.query ?? {},
body: ctx?.body,
headers: ctx?.headers ?? {},
url: req?.url,
// omitted rather than sent empty: an envelope with no identity should look like one
...(correlation.requestId || correlation.traceId ? { correlation } : {}),
};
}
+39 -1
View File
@@ -19,6 +19,28 @@ import {
/** WebSocket path where a teapot exposes its mesh control channel. */
export const MESH_CONTROL_PATH = '/__mesh__/control';
/**
* How long an unauthenticated peer may hold the control channel open before it is hung up on.
*
* The teacup has always bounded its side of the handshake; the teapot had no equivalent, so a peer
* could connect and simply never send `hello`, holding a socket indefinitely without proving
* anything. Generous on purpose — this is a deadline against silence, not a latency budget.
*/
const HANDSHAKE_TIMEOUT_MS = 10_000;
/**
* Largest control frame the teapot will parse, in characters.
*
* `decode` runs `JSON.parse` on peer-controlled input, and until the handshake succeeds that peer
* is *unauthenticated* — so without a cap, anyone who can reach the port can make the process parse
* as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no
* documented ceiling on the platform sockets Deno and Bun provide).
*
* Sized above the 1 MB default body limit an RPC can legitimately carry, with room for the JSON
* overhead of the envelope around it.
*/
const MAX_FRAME_CHARS = 4_000_000;
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
export function buildManifest(args: {
providers: string[]; // exported provider tokens (app-scope)
@@ -151,19 +173,34 @@ async function serveFrames(
exportedRoutes: Set<string>,
): Promise<void> {
let authed = false;
// Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply
// says nothing is indistinguishable from a slow one until this fires.
const handshakeTimer = setTimeout(() => {
if (!authed) socket.close(1008, 'mesh handshake timeout');
}, HANDSHAKE_TIMEOUT_MS);
handshakeTimer.unref?.();
try {
for await (const data of socket.inbound) {
const raw = String(data);
// Checked before `decode`, because decoding is the expensive part being defended.
if (raw.length > MAX_FRAME_CHARS) {
socket.close(1009, 'mesh frame too large');
break;
}
let frame: Frame;
try {
frame = decode(String(data));
frame = decode(raw);
} catch {
continue; // undecodable frames are ignored, as before
}
if (!authed) {
authed = handleHandshake(socket, frame, deps);
if (authed) clearTimeout(handshakeTimer);
continue;
}
@@ -183,6 +220,7 @@ async function serveFrames(
} catch {
/* socket failed; the disconnect emit below is the same signal a clean close gives */
} finally {
clearTimeout(handshakeTimer);
deps.bus?.emit('mesh:disconnect', { name: 'teapot' });
}
}