Skip to content

Commit b1e440c

Browse files
committed
fix(aws-lambda): prevent client path and Host header from overriding request.url origin
1 parent a11765b commit b1e440c

2 files changed

Lines changed: 220 additions & 7 deletions

File tree

‎src/adapters/_aws/utils.ts‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { ServerRequest } from "../../types.ts";
22
import type { TrustProxyOption } from "../../_trust-proxy.ts";
3-
import { resolveClientIP, trustedHops, forwardedHopValue } from "../../_trust-proxy.ts";
3+
import { resolveClientIP, trustedHops, forwardedHopValue, HOST_RE } from "../../_trust-proxy.ts";
44
import type { ResponseBody } from "../../types.ts";
55
import type {
66
AWSLambdaContext,
@@ -80,7 +80,17 @@ function awsEventIP(event: AWSLambdaProxyEvent | AWSLambdaProxyEventV2): string
8080
}
8181

8282
function awsEventURL(event: AWSLambdaProxyEvent | AWSLambdaProxyEventV2, hops: number): URL {
83-
const path = (event as AWSLambdaProxyEvent).path || (event as AWSLambdaProxyEventV2).rawPath;
83+
const rawPath =
84+
(event as AWSLambdaProxyEvent).path || (event as AWSLambdaProxyEventV2).rawPath || "/";
85+
86+
// The gateway path is client-controlled and must never contribute the
87+
// authority. Resolving it as a *relative reference* would let `//evil.com/x`
88+
// (a protocol-relative reference) or `https://evil.com/x` (absolute form)
89+
// replace the origin, so it is concatenated after the authority instead and
90+
// is always forced into origin-form. `//` runs are deliberately preserved
91+
// rather than collapsed, so the routed `pathname` keeps matching the raw path
92+
// the gateway saw — same as `NodeRequestURL`.
93+
const path = rawPath[0] === "/" ? rawPath : `/${rawPath}`;
8494

8595
const query = awsEventQuery(event);
8696

@@ -91,12 +101,17 @@ function awsEventURL(event: AWSLambdaProxyEvent | AWSLambdaProxyEventV2, hops: n
91101
event.headers["X-Forwarded-Host"] || event.headers["x-forwarded-host"],
92102
hops,
93103
);
94-
const hostname =
95-
forwardedHost ||
104+
105+
// A malformed host must neither inject an authority/path into the URL built
106+
// below nor throw out of `awsRequest` (which runs before the error
107+
// middleware, so a throw fails the whole invocation). Same `HOST_RE` gate and
108+
// `_invalid_` sentinel as the Node adapter.
109+
const host =
110+
(forwardedHost && HOST_RE.test(forwardedHost) ? forwardedHost : undefined) ||
96111
event.headers.host ||
97112
event.headers.Host ||
98-
event.requestContext?.domainName ||
99-
".";
113+
event.requestContext?.domainName;
114+
const hostname = host && HOST_RE.test(host) ? host : "_invalid_";
100115

101116
// Assume `https` when untrusted (Lambda is always TLS-terminated at the gateway).
102117
const forwardedProto = forwardedHopValue(
@@ -105,7 +120,7 @@ function awsEventURL(event: AWSLambdaProxyEvent | AWSLambdaProxyEventV2, hops: n
105120
);
106121
const protocol = forwardedProto === "http" ? "http" : "https";
107122

108-
return new URL(`${path}${query ? `?${query}` : ""}`, `${protocol}://${hostname}`);
123+
return new URL(`${protocol}://${hostname}${path}${query ? `?${query}` : ""}`);
109124
}
110125

111126
function awsEventQuery(event: AWSLambdaProxyEvent | AWSLambdaProxyEventV2) {

‎test/aws.test.ts‎

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,183 @@ describe("[AWS Lambda] Request Utils", () => {
486486

487487
expect(request.url).toContain("/api/users/123");
488488
});
489+
490+
// -- URL origin hardening --
491+
// The gateway path and the `Host` header are client-controlled and must
492+
// never be able to move `request.url` off the real origin (or throw out of
493+
// `awsRequest`, which runs before the error middleware).
494+
495+
const v1EventWith = (event: Partial<APIGatewayProxyEvent>): APIGatewayProxyEvent =>
496+
({
497+
httpMethod: "GET",
498+
path: "/api/users",
499+
body: null,
500+
isBase64Encoded: false,
501+
multiValueHeaders: {},
502+
multiValueQueryStringParameters: {},
503+
pathParameters: null,
504+
stageVariables: null,
505+
resource: "",
506+
queryStringParameters: null,
507+
...event,
508+
headers: { host: "api.example.com", ...event.headers },
509+
requestContext: { domainName: "api.example.com", ...event.requestContext } as any,
510+
}) as APIGatewayProxyEvent;
511+
512+
const v2EventWith = (event: Partial<APIGatewayProxyEventV2>): APIGatewayProxyEventV2 =>
513+
({
514+
version: "2.0",
515+
rawPath: "/api/users",
516+
rawQueryString: "",
517+
body: undefined,
518+
isBase64Encoded: false,
519+
routeKey: "$default",
520+
...event,
521+
headers: { host: "api.example.com", ...event.headers },
522+
requestContext: {
523+
domainName: "api.example.com",
524+
http: { method: "GET" },
525+
...event.requestContext,
526+
} as any,
527+
}) as APIGatewayProxyEventV2;
528+
529+
// [rawPath/path, resulting pathname]
530+
const hostilePaths: [string, string][] = [
531+
["//evil.com/admin", "//evil.com/admin"],
532+
["///evil.com/x", "///evil.com/x"],
533+
["/\\evil.com/admin", "//evil.com/admin"],
534+
["//evil.com:8080/x", "//evil.com:8080/x"],
535+
["//user:[email protected]/x", "//user:[email protected]/x"],
536+
["https://evil.com/x", "/https://evil.com/x"],
537+
["javascript:alert(1)", "/javascript:alert(1)"],
538+
];
539+
540+
test.each(hostilePaths)(
541+
"client path %j cannot override the URL authority (v2 rawPath)",
542+
(rawPath, pathname) => {
543+
const request = awsRequest(v2EventWith({ rawPath }), createMockContext());
544+
const url = new URL(request.url);
545+
546+
expect(url.host).toBe("api.example.com");
547+
expect(url.origin).toBe("https://api.example.com");
548+
// The path is preserved verbatim (`//` runs are not collapsed) so the
549+
// routed pathname keeps matching what the gateway/WAF authorized,
550+
// matching the Node adapter.
551+
expect(url.pathname).toBe(pathname);
552+
expect(url.username).toBe("");
553+
expect(url.password).toBe("");
554+
},
555+
);
556+
557+
test.each(hostilePaths)(
558+
"client path %j cannot override the URL authority (v1 path)",
559+
(path, pathname) => {
560+
const request = awsRequest(v1EventWith({ path }), createMockContext());
561+
const url = new URL(request.url);
562+
563+
expect(url.host).toBe("api.example.com");
564+
expect(url.origin).toBe("https://api.example.com");
565+
expect(url.pathname).toBe(pathname);
566+
},
567+
);
568+
569+
test("a path with userinfo no longer fails the invocation", async () => {
570+
const fetchHandler = vi.fn().mockResolvedValue(new Response("ok"));
571+
572+
await expect(
573+
handleLambdaEvent(
574+
fetchHandler,
575+
v2EventWith({ rawPath: "//user:[email protected]/x" }),
576+
createMockContext(),
577+
),
578+
).resolves.toMatchObject({ statusCode: 200 });
579+
580+
const request = fetchHandler.mock.calls[0][0] as Request;
581+
expect(new URL(request.url).host).toBe("api.example.com");
582+
});
583+
584+
test.each(["bad host", "a.com/foo?", "api.example.com:3000/zzz", "evil.com:99999999"])(
585+
"malformed Host %j becomes `_invalid_` without throwing",
586+
(host) => {
587+
const request = awsRequest(
588+
v2EventWith({ rawPath: "/x", headers: { host } }),
589+
createMockContext(),
590+
);
591+
592+
expect(new URL(request.url).host).toBe("_invalid_");
593+
},
594+
);
595+
596+
test("a malformed Host does not fail the invocation", async () => {
597+
const fetchHandler = vi.fn().mockResolvedValue(new Response("ok"));
598+
599+
await expect(
600+
handleLambdaEvent(
601+
fetchHandler,
602+
v2EventWith({ rawPath: "/x", headers: { host: "bad host" } }),
603+
createMockContext(),
604+
),
605+
).resolves.toMatchObject({ statusCode: 200 });
606+
});
607+
608+
test("a well-formed Host is still honored", () => {
609+
const request = awsRequest(
610+
v2EventWith({ rawPath: "/x", headers: { host: "api.example.com:3000" } }),
611+
createMockContext(),
612+
);
613+
614+
expect(new URL(request.url).host).toBe("api.example.com:3000");
615+
});
616+
617+
test("invalid X-Forwarded-Host is ignored even when the proxy is trusted", () => {
618+
const request = awsRequest(
619+
v2EventWith({
620+
rawPath: "/x",
621+
headers: { host: "real.example.com", "x-forwarded-host": "evil.com/p?" },
622+
}),
623+
createMockContext(),
624+
true,
625+
);
626+
627+
expect(new URL(request.url).host).toBe("real.example.com");
628+
});
629+
630+
test("missing Host falls back to domainName, then to `_invalid_`", () => {
631+
const withDomainName = awsRequest(
632+
v2EventWith({ rawPath: "/x", headers: {} as any, requestContext: {} as any }),
633+
createMockContext(),
634+
);
635+
expect(new URL(withDomainName.url).host).toBe("api.example.com");
636+
637+
const withoutAnyHost = awsRequest(
638+
{
639+
rawPath: "/x",
640+
rawQueryString: "",
641+
headers: {},
642+
requestContext: { http: { method: "GET" } },
643+
} as any,
644+
createMockContext(),
645+
);
646+
expect(new URL(withoutAnyHost.url).host).toBe("_invalid_");
647+
});
648+
649+
test("a missing path falls back to `/` instead of `/undefined`", () => {
650+
const request = awsRequest(
651+
{ headers: { host: "api.example.com" }, requestContext: {} } as any,
652+
createMockContext(),
653+
);
654+
655+
expect(request.url).toBe("https://api.example.com/");
656+
});
657+
658+
test("benign paths and queries are unchanged", () => {
659+
const request = awsRequest(
660+
v2EventWith({ rawPath: "/api/users", rawQueryString: "page=1&limit=10" }),
661+
createMockContext(),
662+
);
663+
664+
expect(request.url).toBe("https://api.example.com/api/users?page=1&limit=10");
665+
});
489666
});
490667

491668
describe("awsResponseHeaders", () => {
@@ -1052,6 +1229,27 @@ describe("[AWS Lambda] Request Utils", () => {
10521229
expect(response.status).toBe(200);
10531230
expect(await response.text()).toBe("Hello World");
10541231
});
1232+
1233+
test("a `//`-prefixed path round-trips without hijacking the origin", async () => {
1234+
// `requestToAwsEvent` puts `url.pathname` into `rawPath`/`path`, so this
1235+
// reaches the same sink as a real gateway event, with no AWS involvement.
1236+
// Before the fix the handler observed `https://evil.com/x`.
1237+
const observed: string[] = [];
1238+
const handler: AWSLambdaHandler = (event, context) => {
1239+
observed.push(awsRequest(event, context).url);
1240+
return { statusCode: 200, body: "OK" };
1241+
};
1242+
1243+
const response = await invokeLambdaHandler(
1244+
handler,
1245+
new Request("http://localhost:3000//evil.com/x"),
1246+
);
1247+
1248+
expect(response.status).toBe(200);
1249+
const url = new URL(observed[0]);
1250+
expect(url.host).toBe("localhost");
1251+
expect(url.pathname).toBe("//evil.com/x");
1252+
});
10551253
});
10561254

10571255
describe("awsStreamResponse", () => {

0 commit comments

Comments
 (0)