diff --git a/src/mesh/link.ts b/src/mesh/link.ts index e946e65..caa6f6c 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -1,6 +1,6 @@ import type { Bus } from '../bus'; import { HttpError } from '../signals'; -import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol'; /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ export interface Link { @@ -105,7 +105,7 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num reject(new Error(`mesh connect timeout: ${args.url}`)); }, timeoutMs); - ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret }))); + ws.on('open', () => ws.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret }))); ws.on('error', (error: unknown) => reject(error)); ws.on('close', () => { clearTimeout(connectTimer); @@ -124,8 +124,19 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num } if (frame.type === 'manifest') { - manifest = { scopes: frame.scopes, routes: frame.routes }; clearTimeout(connectTimer); + + if (frame.v !== MESH_PROTOCOL_VERSION) { + ws.close(); + reject( + new Error( + `mesh protocol version mismatch at ${args.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`, + ), + ); + return; + } + + manifest = { scopes: frame.scopes, routes: frame.routes }; args.bus?.emit('mesh:connect', { name: args.url }); resolve(buildLink(ws, pending, manifest, timeoutMs)); return; diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts index e2731b2..5f4b82b 100644 --- a/src/mesh/protocol.ts +++ b/src/mesh/protocol.ts @@ -1,3 +1,11 @@ +/** + * 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. + */ +export const MESH_PROTOCOL_VERSION = 1; + /** Serialized request context sent across the mesh for a scope or route RPC. */ export interface RequestEnvelope { method: string; @@ -23,28 +31,67 @@ export interface Manifest { routes: RouteEntry[]; } -/** Discriminated union of every message on the mesh wire. */ +/** Discriminated union of every message on the mesh wire. The handshake frames carry `v`. */ export type Frame = - | { type: 'hello'; secret: string } - | { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] } + | { type: 'hello'; v: number; secret: string } + | { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] } | { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope } | { type: 'rpc-res'; id: string; ok: true; result: unknown } | { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }; -const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']); +const isString = (value: unknown): value is string => typeof value === 'string'; +const isNumber = (value: unknown): boolean => typeof value === 'number'; +const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null; + +/** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */ +type ShapeCheck = (frame: Record, bad: (why: string) => never) => void; + +/** + * Field checks per frame type. `decode` is the mesh's trust boundary: past it, frames are fed + * straight to the scope/route resolvers, so a bad shape must die here rather than surface as a + * confusing failure downstream. A new frame type must add a row — the compiler fails until it does. + */ +const SHAPE: Record = { + hello: (frame, bad) => { + if (!isNumber(frame.v)) bad('missing protocol version'); + if (!isString(frame.secret)) bad('secret must be a string'); + }, + manifest: (frame, bad) => { + if (!isNumber(frame.v)) bad('missing protocol version'); + if (!Array.isArray(frame.scopes) || !Array.isArray(frame.routes)) bad('scopes and routes must be arrays'); + }, + 'rpc-req': (frame, bad) => { + if (!isString(frame.id)) bad('id must be a string'); + if (frame.kind !== 'scope' && frame.kind !== 'route') bad("kind must be 'scope' or 'route'"); + if (!isString(frame.name)) bad('name must be a string'); + if (!isObject(frame.ctx)) bad('ctx must be an object'); + }, + 'rpc-res': (frame, bad) => { + if (!isString(frame.id)) bad('id must be a string'); + if (typeof frame.ok !== 'boolean') bad('ok must be a boolean'); + if (frame.ok === false && !isObject(frame.error)) bad('error must be an object when ok is false'); + }, +}; /** Serialize a frame to a JSON wire string. */ export function encode(frame: Frame): string { return JSON.stringify(frame); } -/** Parse a wire string into a frame, throwing if the `type` tag is unknown. */ +/** Parse a wire string into a frame, throwing if the `type` tag is unknown or the shape is malformed. */ export function decode(json: string): Frame { - const parsed = JSON.parse(json) as { type?: unknown }; + const parsed = JSON.parse(json) as Record; + const type = parsed.type; + // own-property check, not a bare lookup: `type` is peer-controlled, and SHAPE['constructor'] + // would otherwise resolve up the prototype chain to a truthy non-check. + const known = isString(type) && Object.prototype.hasOwnProperty.call(SHAPE, type); + const check = known ? SHAPE[type as Frame['type']] : undefined; - if (typeof parsed.type !== 'string' || !TYPES.has(parsed.type)) { - throw new Error(`unknown frame type: ${String(parsed.type)}`); - } + if (!check) throw new Error(`unknown frame type: ${String(type)}`); - return parsed as Frame; + check(parsed, (why) => { + throw new Error(`malformed ${String(type)} frame: ${why}`); + }); + + return parsed as unknown as Frame; } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index b7922fa..6561bbf 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -2,7 +2,15 @@ import crypto from 'crypto'; import type { Bus } from '../bus'; import type { ResponseShape } from '../pipeline'; import { isHttpError } from '../signals'; -import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol'; +import { + encode, + decode, + MESH_PROTOCOL_VERSION, + type Manifest, + type RequestEnvelope, + type RouteEntry, + type Frame, +} from './protocol'; /** WebSocket path where a teapot exposes its mesh control channel. */ export const MESH_CONTROL_PATH = '/__mesh__/control'; @@ -49,18 +57,44 @@ function notExported(name: string): Error { return error; } -/** Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. */ +/** + * Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. + * The version is checked *before* the secret: a skewed peer is not an auth failure, and telling it + * "wrong secret" would send its operator hunting the wrong bug. + */ function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean { - if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) { - ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes })); - deps.bus?.emit('mesh:connect', { name: 'teapot' }); + if (frame.type !== 'hello') { + ws.close(1008); - return true; + return false; } - ws.close(1008); + if (frame.v !== MESH_PROTOCOL_VERSION) { + ws.close( + 1008, + `mesh protocol version mismatch: peer speaks v${frame.v}, this teapot speaks v${MESH_PROTOCOL_VERSION}`, + ); - return false; + return false; + } + + if (!safeEqual(frame.secret, deps.secret)) { + ws.close(1008); + + return false; + } + + ws.send( + encode({ + type: 'manifest', + v: MESH_PROTOCOL_VERSION, + scopes: deps.manifest.scopes, + routes: deps.manifest.routes, + }), + ); + deps.bus?.emit('mesh:connect', { name: 'teapot' }); + + return true; } /** Resolve an authenticated rpc-req against the exported scopes/routes, enforcing export gating. */ diff --git a/test/mesh/link.test.ts b/test/mesh/link.test.ts index 69bdd18..888aafd 100644 --- a/test/mesh/link.test.ts +++ b/test/mesh/link.test.ts @@ -1,7 +1,9 @@ import { describe, it, expect } from 'vitest'; import { WebSocketServer } from 'ws'; import { connectLink } from '../../src/mesh/link'; -import { encode, decode } from '../../src/mesh/protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; + +const V = MESH_PROTOCOL_VERSION; const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} }; @@ -13,7 +15,7 @@ function startTeapot(secret = 'good') { ws.on('message', (d) => { const f = decode(d.toString()); if (!authed) { - if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); } + if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); } else ws.close(1008); return; } @@ -33,7 +35,7 @@ function startSilentTeapot(secret = 'good') { wss.on('connection', (ws) => { ws.on('message', (d) => { const f = decode(d.toString()); - if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', scopes: [], routes: [] })); + if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] })); // ignore rpc-req entirely }); }); @@ -41,7 +43,39 @@ function startSilentTeapot(secret = 'good') { return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() }; } +// teapot running a future protocol: handshakes, but answers with a skewed manifest +function startSkewedTeapot() { + const wss = new WebSocketServer({ port: 0 }); + wss.on('connection', (ws) => { + ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, scopes: [], routes: [] } as any))); + }); + const port = (wss.address() as any).port; + return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() }; +} + describe('connectLink', () => { + it('sends its protocol version in the hello', async () => { + const seen: any[] = []; + const wss = new WebSocketServer({ port: 0 }); + wss.on('connection', (ws) => + ws.on('message', (d) => { + seen.push(decode(d.toString())); + ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] })); + }), + ); + const url = `ws://127.0.0.1:${(wss.address() as any).port}/__mesh__/control`; + const link = await connectLink({ url, secret: 'good' }); + expect(seen[0]).toMatchObject({ type: 'hello', v: V }); + link.close(); + wss.close(); + }); + + it('refuses a teapot on a different protocol version', async () => { + const t = startSkewedTeapot(); + await expect(connectLink({ url: t.url, secret: 'good', timeoutMs: 500 })).rejects.toThrow(/version/i); + t.close(); + }); + it('handshakes and exposes the manifest', async () => { const t = startTeapot(); const link = await connectLink({ url: t.url, secret: 'good' }); diff --git a/test/mesh/protocol.test.ts b/test/mesh/protocol.test.ts index f390593..029fe06 100644 --- a/test/mesh/protocol.test.ts +++ b/test/mesh/protocol.test.ts @@ -1,16 +1,22 @@ import { describe, it, expect } from 'vitest'; -import { encode, decode, type Frame, type RequestEnvelope } from '../../src/mesh/protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION, type Frame, type RequestEnvelope } from '../../src/mesh/protocol'; const env: RequestEnvelope = { method: 'GET', params: { id: '1' }, query: {}, body: undefined, headers: {} }; +const V = MESH_PROTOCOL_VERSION; describe('protocol codec', () => { it('round-trips each frame type', () => { const frames: Frame[] = [ - { type: 'hello', secret: 's3cr3t' }, - { type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [{ method: 'GET', pattern: '/u/:id' }] }, - { type: 'rpc-req', id: 'c1:1', kind: 'scope', name: 'auth', ctx: env }, - { type: 'rpc-res', id: 'c1:1', ok: true, result: { id: 'u1' } }, - { type: 'rpc-res', id: 'c1:2', ok: false, error: { message: 'no', status: 401 } }, + { type: 'hello', v: V, secret: 's3cr3t' }, + { + type: 'manifest', + v: V, + scopes: [{ token: 'auth', scope: 'request' }], + routes: [{ method: 'GET', pattern: '/u/:id' }], + }, + { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth', ctx: env }, + { type: 'rpc-res', id: '1', ok: true, result: { id: 'u1' } }, + { type: 'rpc-res', id: '2', ok: false, error: { message: 'no', status: 401 } }, ]; for (const f of frames) expect(decode(encode(f))).toEqual(f); }); @@ -22,4 +28,57 @@ describe('protocol codec', () => { it('throws on unknown frame type', () => { expect(() => decode(JSON.stringify({ type: 'bogus' }))).toThrow(/unknown frame/i); }); + + it.each(['constructor', 'toString', '__proto__', 'hasOwnProperty'])( + 'treats inherited Object property %s as an unknown type, not a validator', + (type) => { + // `type` is peer-controlled; a bare SHAPE[type] lookup would walk the prototype chain + expect(() => decode(JSON.stringify({ type }))).toThrow(/unknown frame/i); + }, + ); + + it('throws on a non-string type tag', () => { + expect(() => decode(JSON.stringify({ type: 42 }))).toThrow(/unknown frame/i); + expect(() => decode(JSON.stringify({}))).toThrow(/unknown frame/i); + }); +}); + +describe('protocol versioning', () => { + it('carries the protocol version on the handshake frames', () => { + const hello = decode(encode({ type: 'hello', v: V, secret: 's' })); + const manifest = decode(encode({ type: 'manifest', v: V, scopes: [], routes: [] })); + + expect(hello).toMatchObject({ v: V }); + expect(manifest).toMatchObject({ v: V }); + }); + + it('rejects a handshake frame with no version — an unversioned peer is not decodable', () => { + expect(() => decode(JSON.stringify({ type: 'hello', secret: 's' }))).toThrow(/malformed hello/i); + expect(() => decode(JSON.stringify({ type: 'manifest', scopes: [], routes: [] }))).toThrow(/malformed manifest/i); + }); +}); + +describe('protocol field validation', () => { + // decode is the trust boundary: past it, teapot.ts feeds frames straight into + // resolveScope/resolveRoute. A bad shape must die here, not downstream. + it.each([ + ['hello without secret', { type: 'hello', v: V }], + ['hello with non-string secret', { type: 'hello', v: V, secret: 42 }], + ['manifest with non-array scopes', { type: 'manifest', v: V, scopes: 'nope', routes: [] }], + ['rpc-req without id', { type: 'rpc-req', kind: 'scope', name: 'auth', ctx: env }], + ['rpc-req without ctx', { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth' }], + ['rpc-req with unknown kind', { type: 'rpc-req', id: '1', kind: 'bogus', name: 'auth', ctx: env }], + ['rpc-req without name', { type: 'rpc-req', id: '1', kind: 'scope', ctx: env }], + ['rpc-res without id', { type: 'rpc-res', ok: true, result: 1 }], + ['rpc-res with non-boolean ok', { type: 'rpc-res', id: '1', ok: 'yes' }], + ['rpc-res error without an error payload', { type: 'rpc-res', id: '1', ok: false }], + ])('rejects %s', (_label, frame) => { + expect(() => decode(JSON.stringify(frame))).toThrow(/malformed/i); + }); + + it('accepts a valid rpc-req unchanged', () => { + const frame: Frame = { type: 'rpc-req', id: '1', kind: 'route', name: '/u/:id', ctx: env }; + + expect(decode(encode(frame))).toEqual(frame); + }); }); diff --git a/test/mesh/teapot.test.ts b/test/mesh/teapot.test.ts index 3ed2746..b2194ce 100644 --- a/test/mesh/teapot.test.ts +++ b/test/mesh/teapot.test.ts @@ -1,7 +1,9 @@ import { describe, it, expect, vi } from 'vitest'; import { EventEmitter } from 'events'; import { buildManifest, createMeshControl } from '../../src/mesh/teapot'; -import { encode, decode } from '../../src/mesh/protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; + +const V = MESH_PROTOCOL_VERSION; import { Unauthorized } from '../../src/signals'; const fakeWs = () => { @@ -36,15 +38,33 @@ describe('createMeshControl', () => { it('rejects a bad secret and closes', () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'wrong' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'wrong' })); expect(ws.close).toHaveBeenCalledWith(1008); expect(ws.sent).toEqual([]); }); - it('answers a good hello with the manifest', () => { + it('answers a good hello with the manifest, stamped with the protocol version', () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); - expect(ws.sent[0]).toMatchObject({ type: 'manifest', scopes: manifest.scopes }); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); + expect(ws.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes }); + }); + + it('rejects a version-skewed peer before checking its secret, naming both versions', () => { + const ws = fakeWs(); make().handle(ws); + // correct secret, wrong protocol: must still be refused — and not as an auth failure + ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'good' } as any)); + expect(ws.sent).toEqual([]); + const [code, reason] = ws.close.mock.calls[0]; + expect(code).toBe(1008); + expect(reason).toContain(String(V)); + expect(reason).toContain(String(V + 1)); + }); + + it('refuses a version-skewed peer even when its secret is also wrong', () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'wrong' } as any)); + expect(ws.sent).toEqual([]); + expect(ws.close).toHaveBeenCalled(); }); it('does NOT process rpc before handshake', async () => { @@ -56,7 +76,7 @@ describe('createMeshControl', () => { it('resolves an exported scope after handshake', async () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); ws.emit('message', encode({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} as any })); await new Promise((r) => setTimeout(r, 5)); expect(ws.sent.find((f: any) => f.type === 'rpc-res')).toEqual({ type: 'rpc-res', id: '7', ok: true, result: { resolved: 'config' } }); @@ -64,7 +84,7 @@ describe('createMeshControl', () => { it('rejects an unexported scope', async () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); ws.emit('message', encode({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} as any })); await new Promise((r) => setTimeout(r, 5)); const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); @@ -75,7 +95,7 @@ describe('createMeshControl', () => { it('propagates a thrown HttpError status in the error frame', async () => { const ws = fakeWs(); make({ resolveScope: async () => { throw new Unauthorized('nope'); } }).handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); ws.emit('message', encode({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} as any })); await new Promise((r) => setTimeout(r, 5)); const res: any = ws.sent.find((f: any) => f.type === 'rpc-res');