fix(router): reject invalid and ambiguous paths
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
6 files changed
+150
-9
No files matched your search
+35
-8
@@ -35,6 +35,7 @@ import type { MeshControl } from '../http';
|
||||
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
||||
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
||||
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
||||
import { compilePattern } from '../http/router';
|
||||
|
||||
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
|
||||
|
||||
@@ -349,6 +350,7 @@ function collectControllers(
|
||||
const instance: any = new ControllerClass();
|
||||
const argSpecs = getArgs(ControllerClass, route.handlerName);
|
||||
const pattern = joinPath(mountpoint, route.path);
|
||||
const declaration = `${ControllerClass.name}.${route.handlerName}`;
|
||||
|
||||
if (route.export) {
|
||||
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
|
||||
@@ -357,11 +359,12 @@ function collectControllers(
|
||||
|
||||
const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx);
|
||||
|
||||
registry.routePlans.push({
|
||||
const plan: RoutePlan = {
|
||||
pattern,
|
||||
method: route.method,
|
||||
transport: route.transport,
|
||||
origin,
|
||||
declaration,
|
||||
providers: [],
|
||||
steps: [],
|
||||
handlerName: route.handlerName,
|
||||
@@ -372,11 +375,27 @@ function collectControllers(
|
||||
maxBodyBytes: route.maxBodyBytes,
|
||||
maxParts: route.maxParts,
|
||||
args: argSpecs,
|
||||
});
|
||||
};
|
||||
assertRouteAvailable(registry.routePlans, plan);
|
||||
registry.routePlans.push(plan);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Rejects local routes that have the same method and effective match shape. */
|
||||
function assertRouteAvailable(existing: RoutePlan[], candidate: RoutePlan): void {
|
||||
const compiled = compilePattern(candidate.pattern);
|
||||
const conflict = existing.find(
|
||||
(plan) => plan.method === candidate.method && compilePattern(plan.pattern).shape === compiled.shape,
|
||||
);
|
||||
if (!conflict) return;
|
||||
|
||||
throw new Error(
|
||||
`ambiguous route ${candidate.method} ${candidate.pattern} at ${candidate.declaration} conflicts with ` +
|
||||
`${conflict.method} ${conflict.pattern} at ${conflict.declaration}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the response transformer for a route: `@Html` metadata builds an HTML transformer (after
|
||||
* validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the
|
||||
@@ -512,7 +531,7 @@ async function spliceRemoteScopes(
|
||||
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
||||
const remoteRoutes: RouteDef[] = [];
|
||||
const meshLinks: Link[] = [];
|
||||
const routeOwners = new Map<string, string>(); // "METHOD /pattern" -> the teapot that exported it
|
||||
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
|
||||
|
||||
try {
|
||||
for (const teapot of mesh.teapots ?? []) {
|
||||
@@ -539,7 +558,8 @@ async function spliceRemoteScopes(
|
||||
}
|
||||
|
||||
for (const route of routes) {
|
||||
const key = `${route.method} ${route.pattern}`;
|
||||
const display = `${route.method} ${route.pattern}`;
|
||||
const key = `${route.method} ${compilePattern(route.pattern).shape}`;
|
||||
const owner = routeOwners.get(key);
|
||||
|
||||
// Fail the boot rather than pick one. Route matching keeps the first of two identical
|
||||
@@ -548,21 +568,28 @@ async function spliceRemoteScopes(
|
||||
// Scope tokens already fail this way in setRunner; routes now match.
|
||||
if (owner) {
|
||||
throw new Error(
|
||||
`mesh: route '${key}' is exported by more than one teapot (${owner} and ${teapot.url}) — ` +
|
||||
`mesh: ambiguous remote route '${display}' from ${teapot.url} conflicts with ` +
|
||||
`'${route.method} ${owner.pattern}' from ${owner.url} — ` +
|
||||
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
|
||||
'Export it from a single teapot.',
|
||||
);
|
||||
}
|
||||
|
||||
routeOwners.set(key, teapot.url);
|
||||
routeOwners.set(key, { url: teapot.url, pattern: route.pattern });
|
||||
|
||||
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
|
||||
// wins. That precedence is deliberate — your own code beats an imported one, and it is
|
||||
// how you override a teapot — but silently shadowing an export looks exactly like a
|
||||
// broken teapot from the outside. Warn and let the developer decide.
|
||||
if (registry.routePlans.some((plan) => plan.method === route.method && plan.pattern === route.pattern)) {
|
||||
if (
|
||||
registry.routePlans.some(
|
||||
(plan) =>
|
||||
plan.method === route.method &&
|
||||
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
|
||||
)
|
||||
) {
|
||||
console.warn(
|
||||
`[green-tea] mesh: route '${key}' is exported by teapot ${teapot.url} but also declared locally — ` +
|
||||
`[green-tea] mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
|
||||
'the local route takes precedence and the remote one will not be reached. ' +
|
||||
'Remove one if that is not what you meant.',
|
||||
);
|
||||
|
||||
@@ -70,6 +70,7 @@ export interface RoutePlan {
|
||||
method: HttpMethod;
|
||||
transport: Transport;
|
||||
origin: string;
|
||||
declaration: string;
|
||||
providers: GraphNode[];
|
||||
steps: GraphNode[];
|
||||
handlerName: string;
|
||||
|
||||
@@ -19,6 +19,14 @@ const compiledCache = new Map<string, CompiledPattern>();
|
||||
const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
const MAX_CONSTRAINT_LENGTH = 128;
|
||||
|
||||
/** Request-path syntax error. Adapters translate this to the standard 400 response envelope. */
|
||||
export class InvalidRequestPathError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'InvalidRequestPathError';
|
||||
}
|
||||
}
|
||||
|
||||
interface ConstraintToken {
|
||||
length: number;
|
||||
unbounded: boolean;
|
||||
@@ -155,6 +163,21 @@ export function compilePattern(pattern: string): CompiledPattern {
|
||||
return compiled;
|
||||
}
|
||||
|
||||
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */
|
||||
export function normalizeRequestPath(path: string): string {
|
||||
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
|
||||
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
|
||||
const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
|
||||
try {
|
||||
for (const segment of normalized.split('/').slice(1)) decodeURIComponent(segment);
|
||||
} catch {
|
||||
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function decodeSegment(value: string): string {
|
||||
return decodeURIComponent(value);
|
||||
}
|
||||
|
||||
@@ -583,3 +583,39 @@ test('per-route maxBodyBytes overrides the server default', async () => {
|
||||
|
||||
server.close();
|
||||
});
|
||||
|
||||
describe('route table validation', () => {
|
||||
it('rejects routes with the same method and effective pattern', () => {
|
||||
@Route('/users')
|
||||
class DuplicateCtl {
|
||||
@Get('/:id') byId() {
|
||||
return {};
|
||||
}
|
||||
@Get('/:name') byName() {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [DuplicateCtl] })
|
||||
class DuplicateModule {}
|
||||
|
||||
expect(() => createApp({ modules: [DuplicateModule] })).toThrow(
|
||||
/ambiguous route GET.*\/api\/users\/:name.*DuplicateCtl\.byName.*DuplicateCtl\.byId/,
|
||||
);
|
||||
});
|
||||
|
||||
it('allows the same effective pattern under different methods', () => {
|
||||
@Route('/users')
|
||||
class MethodsCtl {
|
||||
@Get('/:id') get() {
|
||||
return {};
|
||||
}
|
||||
@Post('/:name') post() {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [MethodsCtl] })
|
||||
class MethodsModule {}
|
||||
|
||||
expect(() => createApp({ modules: [MethodsModule] })).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,26 @@ class DupCtl {
|
||||
@Module({ mountpoint: '/api', controllers: [DupCtl] })
|
||||
class DupTeapotModule {}
|
||||
|
||||
@Route('/shape')
|
||||
class ParamIdCtl {
|
||||
@Get('/:id', { export: true })
|
||||
get() {
|
||||
return { from: 'id' };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [ParamIdCtl] })
|
||||
class ParamIdTeapotModule {}
|
||||
|
||||
@Route('/shape')
|
||||
class ParamNameCtl {
|
||||
@Get('/:name', { export: true })
|
||||
get() {
|
||||
return { from: 'name' };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [ParamNameCtl] })
|
||||
class ParamNameTeapotModule {}
|
||||
|
||||
@Route('/c')
|
||||
class PlainCtl {
|
||||
@Get('/ok')
|
||||
@@ -112,6 +132,27 @@ describe('mesh skeleton integration', () => {
|
||||
bServer.close();
|
||||
});
|
||||
|
||||
it('refuses ambiguous remote routes that differ only by parameter name', async () => {
|
||||
const a = createApp({ modules: [ParamIdTeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const b = createApp({ modules: [ParamNameTeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const aServer = await a.listen(0);
|
||||
const bServer = await b.listen(0);
|
||||
const url = (s: any) => `ws://127.0.0.1:${(s.address() as any).port}/__mesh__/control`;
|
||||
const teacup = createApp({
|
||||
modules: [PlainTeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: url(aServer), secret: SECRET }, { url: url(bServer), secret: SECRET }] },
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(teacup.ready()).rejects.toThrow(/ambiguous remote route.*GET \/api\/shape\/:name/i);
|
||||
} finally {
|
||||
await teacup.close();
|
||||
aServer.close();
|
||||
bServer.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts the same route from a single teapot (regression: no false positive)', async () => {
|
||||
const a = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const aServer = await a.listen(0);
|
||||
|
||||
+14
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { compilePattern, matchPattern, matchRoute, allowedMethods } from '../src/http/router';
|
||||
import { compilePattern, matchPattern, matchRoute, allowedMethods, normalizeRequestPath } from '../src/http/router';
|
||||
import type { RouteDef } from '../src/http/types';
|
||||
|
||||
const route = (method: string, pattern: string): RouteDef => ({
|
||||
@@ -53,6 +53,19 @@ describe('compilePattern', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeRequestPath', () => {
|
||||
it('treats one trailing slash as equivalent and preserves root', () => {
|
||||
expect(normalizeRequestPath('/users')).toBe('/users');
|
||||
expect(normalizeRequestPath('/users/')).toBe('/users');
|
||||
expect(normalizeRequestPath('/')).toBe('/');
|
||||
});
|
||||
|
||||
it('rejects repeated slashes and malformed percent encoding', () => {
|
||||
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
|
||||
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('matchRoute precedence', () => {
|
||||
it('static beats :param beats catch-all regardless of registration order', () => {
|
||||
const routes = [route('GET', '/a/:rest*'), route('GET', '/a/:id'), route('GET', '/a/b')];
|
||||
|
||||
Reference in new issue
Block a user