feat(mesh): carry the caller's identity across the wire, and bound what an unauthenticated peer can do #48
No files matched your search
@@ -8,6 +8,23 @@ npm treats versions as semver and semver forbids leading zeros.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
|
||||
- **A request that crosses the mesh keeps its identity.** The RPC envelope now carries the caller's
|
||||
`requestId` and `traceId`, and a teapot adopts them rather than opening a new investigation — the
|
||||
same rule an incoming `x-request-id` already got, applied at the process boundary where a trace
|
||||
matters most. It also carries `url`, so a proxied handler sees the path its caller asked for.
|
||||
|
||||
Both fields are **optional on the wire and the protocol version does not move**: `decode` validates
|
||||
only what a frame type requires and passes extras through, so a teapot on an older green-tea
|
||||
ignores them and keeps answering. That is degraded, not broken. The rule for when the version
|
||||
*does* move is now written next to the constant, because "bump on any breaking change" never said
|
||||
what counts as breaking.
|
||||
|
||||
The remote-route envelope is also built explicitly instead of cast from the internal request
|
||||
object, which had been putting `ip` and `protocol` on the wire — fields the protocol never
|
||||
declared and a teapot could have come to depend on.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A mesh teacup now reconnects to a teapot that came back.** A dropped link used to stay dead for
|
||||
@@ -30,6 +47,22 @@ npm treats versions as semver and semver forbids leading zeros.
|
||||
|
||||
Mesh remains **alpha** and behind `experimental: true`.
|
||||
|
||||
- **`mesh:rpc:error` reported the wire id where every other emitter reports a name.** A failing
|
||||
remote call emitted `name: "0"` — the per-link request counter — so the teacup's event could not be
|
||||
lined up with the teapot's event for the same failure. It now names the token or route.
|
||||
|
||||
- **A teapot now bounds its own handshake and caps the size of a control frame.** The teacup has
|
||||
always timed out its side; the teapot had no equivalent, so an unauthenticated peer could hold a
|
||||
socket open forever by simply never sending `hello`. And `decode` runs `JSON.parse` on
|
||||
peer-controlled input *before* authentication, with no ceiling below whatever the WebSocket layer
|
||||
allowed — 100 MiB under the `ws` package's defaults. Frames above 4,000,000 characters are now
|
||||
refused with close code 1009, sized above the 1 MB default body limit a legitimate RPC can carry.
|
||||
|
||||
- **A `ws://` teapot on a non-loopback host now warns at boot.** The shared secret travels verbatim
|
||||
in the `hello` frame, so an unencrypted link puts it in front of anyone on the path. A warning
|
||||
rather than a refusal, since a private network doing its own mutual TLS is a real deployment and
|
||||
green-tea cannot tell the two apart.
|
||||
|
||||
## [26.8.0-beta.1] - 2026-08-17
|
||||
|
||||
### Added
|
||||
|
||||
+49
-2
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// The teapot's frame loop under Deno, driven by a raw client rather than by another green-tea.
|
||||
//
|
||||
// The two guards here are close-code behaviour, and close codes are exactly where the runtimes
|
||||
// have already differed once — a client may only send 1000 or 3000-4999, which is why the mesh
|
||||
// heartbeat uses 4011 instead of 1011. Server-side closes deserve the same suspicion.
|
||||
//
|
||||
// Run with: npm run test:deno
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals } from 'jsr:@std/assert';
|
||||
import { createApp, Step, Module } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run() {
|
||||
return { auth: { ok: true } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
async function startTeapot() {
|
||||
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||
let port = 0;
|
||||
const server = serveDeno(app, { port: 0, onListen: (addr) => (port = addr.port) });
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
|
||||
return { port: () => port, stop: async () => { await server.shutdown(); await app.close(); } };
|
||||
}
|
||||
|
||||
/** Opens a raw control-channel socket and resolves with how it ended. */
|
||||
function rawClient(port: number, send: string): Promise<{ code: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/__mesh__/control`);
|
||||
ws.onopen = () => ws.send(send);
|
||||
ws.onclose = (event) => resolve({ code: event.code });
|
||||
ws.onerror = () => reject(new Error('socket errored'));
|
||||
});
|
||||
}
|
||||
|
||||
Deno.test('mesh on Deno: the teapot hangs up on an oversized control frame', async () => {
|
||||
const teapot = await startTeapot();
|
||||
|
||||
try {
|
||||
// over the 4,000,000-character cap, and sent by a peer that has not authenticated
|
||||
const oversized = `{"type":"hello","v":1,"secret":"${'a'.repeat(4_000_001)}"}`;
|
||||
const { code } = await rawClient(teapot.port(), oversized);
|
||||
|
||||
assertEquals(code, 1009);
|
||||
} finally {
|
||||
await teapot.stop();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,246 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import { connectLink } from '../../src/mesh/link';
|
||||
import { envelopeFrom } from '../../src/mesh/teacup';
|
||||
import { createMeshControl } from '../../src/mesh/teapot';
|
||||
import { encode, decode, MESH_PROTOCOL_VERSION, type RequestEnvelope } from '../../src/mesh/protocol';
|
||||
import { Bus } from '../../src/bus';
|
||||
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
||||
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run(ctx: any) {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('auth') auth: any) {
|
||||
return { auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
const V = MESH_PROTOCOL_VERSION;
|
||||
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
|
||||
|
||||
/** Drives a control handler with a scripted socket, capturing what it sends and how it closes. */
|
||||
function fakeSocket() {
|
||||
const queue: string[] = [];
|
||||
let push: ((v: string) => void) | undefined;
|
||||
let done = false;
|
||||
const sent: string[] = [];
|
||||
const closes: Array<{ code?: number; reason?: string }> = [];
|
||||
|
||||
return {
|
||||
sent,
|
||||
closes,
|
||||
feed: (frame: string) => (push ? push(frame) : queue.push(frame)),
|
||||
end: () => {
|
||||
done = true;
|
||||
push?.('');
|
||||
},
|
||||
socket: {
|
||||
get isOpen() {
|
||||
return !done;
|
||||
},
|
||||
abort: new AbortController().signal,
|
||||
send: (data: string) => sent.push(data),
|
||||
close: (code?: number, reason?: string) => {
|
||||
closes.push({ code, reason });
|
||||
done = true;
|
||||
},
|
||||
terminate: () => undefined,
|
||||
inbound: {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
while (!done) {
|
||||
if (queue.length) {
|
||||
yield queue.shift()!;
|
||||
continue;
|
||||
}
|
||||
const next = await new Promise<string>((resolve) => (push = resolve));
|
||||
if (done) return;
|
||||
yield next;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
describe('envelopeFrom', () => {
|
||||
it('carries the url and the caller correlation off ctx.req', () => {
|
||||
const envelope = envelopeFrom({
|
||||
req: { method: 'POST', url: '/orders/7?x=1', requestId: 'req-1', traceId: 'trace-1' },
|
||||
params: { id: '7' },
|
||||
query: { x: '1' },
|
||||
headers: { 'x-token': 'abc' },
|
||||
body: { total: 10 },
|
||||
});
|
||||
|
||||
expect(envelope.url).toBe('/orders/7?x=1');
|
||||
expect(envelope.correlation).toEqual({ requestId: 'req-1', traceId: 'trace-1' });
|
||||
expect(envelope.method).toBe('POST');
|
||||
});
|
||||
|
||||
it('omits correlation entirely when the caller has none, rather than sending an empty one', () => {
|
||||
expect(envelopeFrom({ req: { method: 'GET', url: '/x' } })).not.toHaveProperty('correlation');
|
||||
});
|
||||
});
|
||||
|
||||
describe('mesh rpc errors', () => {
|
||||
it('reports the token that failed, not the wire id', async () => {
|
||||
const wss = new WebSocketServer({ port: 0 });
|
||||
wss.on('connection', (ws) => {
|
||||
let authed = false;
|
||||
ws.on('message', (data) => {
|
||||
const frame = decode(data.toString());
|
||||
if (!authed && frame.type === 'hello') {
|
||||
authed = true;
|
||||
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'billing', scope: 'request' }], routes: [] }));
|
||||
return;
|
||||
}
|
||||
if (frame.type === 'rpc-req') {
|
||||
ws.send(encode({ type: 'rpc-res', id: frame.id, ok: false, error: { message: 'nope', status: 403 } }));
|
||||
}
|
||||
});
|
||||
});
|
||||
const port = (wss.address() as { port: number }).port;
|
||||
const bus = new Bus();
|
||||
const seen: string[] = [];
|
||||
bus.on('mesh:rpc:error', (payload) => seen.push(String(payload.name)));
|
||||
|
||||
const link = await connectLink({ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'x', bus });
|
||||
await expect(link.rpc('scope', 'billing', env)).rejects.toMatchObject({ status: 403 });
|
||||
|
||||
// used to be "0" — the per-link counter — which no operator could match to anything
|
||||
expect(seen).toEqual(['billing']);
|
||||
link.close();
|
||||
wss.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('teapot hardening', () => {
|
||||
const control = () =>
|
||||
createMeshControl({
|
||||
secret: 'good',
|
||||
manifest: { scopes: [{ token: 'auth', scope: 'request' }], routes: [] },
|
||||
resolveScope: async () => 'value',
|
||||
resolveRoute: async () => ({ status: 200, headers: {}, body: '' }),
|
||||
});
|
||||
|
||||
it('hangs up on an oversized frame before parsing it', async () => {
|
||||
const fake = fakeSocket();
|
||||
const running = control().handle(fake.socket as never);
|
||||
|
||||
fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(4_000_001)}"}`);
|
||||
await running;
|
||||
|
||||
expect(fake.closes[0]?.code).toBe(1009);
|
||||
// never answered: the frame died before decode, so no manifest went out
|
||||
expect(fake.sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('serves normally when a frame is under the cap', async () => {
|
||||
const fake = fakeSocket();
|
||||
const running = control().handle(fake.socket as never);
|
||||
|
||||
fake.feed(encode({ type: 'hello', v: V, secret: 'good' }));
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
fake.end();
|
||||
await running;
|
||||
|
||||
expect(JSON.parse(fake.sent[0]).type).toBe('manifest');
|
||||
});
|
||||
});
|
||||
|
||||
describe('correlation across the mesh', () => {
|
||||
it("the teapot's own events carry the caller's request id, not one it opened itself", async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||
const server = await teapot.listen(0);
|
||||
const port = (server.address() as { port: number }).port;
|
||||
|
||||
// what the teapot reports about its *own* work — the far end of the trace
|
||||
const far: Array<string | undefined> = [];
|
||||
teapot.bus.on('request:step:leave', (payload) => far.push(payload.requestId));
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }] },
|
||||
});
|
||||
|
||||
try {
|
||||
// the id a gateway would have set; core adopts it rather than minting a new one
|
||||
const res = await teacup.fetch(
|
||||
new Request('http://x/api/local/who', { headers: { 'x-request-id': 'from-the-gateway' } }),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
expect(far.length).toBeGreaterThan(0);
|
||||
// before this change the teapot saw no id at all, so a request crossing the mesh
|
||||
// became two unrelated investigations
|
||||
expect(new Set(far)).toEqual(new Set(['from-the-gateway']));
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await teapot.close();
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleartext secret warning', () => {
|
||||
it('warns for a remote ws:// teapot, and stays quiet for loopback', async () => {
|
||||
const remote: string[] = [];
|
||||
const logger = { debug() {}, info() {}, warn: (m: string) => remote.push(m), error() {} };
|
||||
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||
const server = await teapot.listen(0);
|
||||
const port = (server.address() as { port: number }).port;
|
||||
|
||||
// loopback: there is no network path, so nothing to warn about
|
||||
const local = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
logger,
|
||||
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }] },
|
||||
});
|
||||
|
||||
try {
|
||||
await local.fetch(new Request('http://x/api/local/who'));
|
||||
expect(remote.filter((m) => m.includes('not encrypted'))).toEqual([]);
|
||||
} finally {
|
||||
await local.close();
|
||||
await teapot.close();
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('warns when the secret would cross a network in cleartext', async () => {
|
||||
const warned: string[] = [];
|
||||
const logger = { debug() {}, info() {}, warn: (m: string) => warned.push(m), error() {} };
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
logger,
|
||||
// unreachable on purpose: the warning is emitted before the connection is attempted,
|
||||
// because it is about what would be sent, not about what succeeded
|
||||
mesh: { teapots: [{ url: 'ws://10.255.255.1:9/__mesh__/control', secret: 'good' }], timeoutMs: 300 },
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow();
|
||||
} finally {
|
||||
await teacup.close();
|
||||
}
|
||||
|
||||
expect(warned.some((m) => m.includes('not encrypted') && m.includes('wss://'))).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user