-
Notifications
You must be signed in to change notification settings - Fork 28
Normalize URL handling #796
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
timokoessler
wants to merge
12
commits into
main
Choose a base branch
from
normalize-url-handling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
c8707fa
Normalize URL handling
timokoessler 97981a2
Add url path to context
timokoessler a20a0e4
Path url behavior for more frameworks
timokoessler 33fc41d
Fix build & linting
timokoessler 510b748
Merge branch 'main' into normalize-url-handling
timokoessler d130d36
Add tests and change behavior for some frameworks
timokoessler e314675
Support HTTP2 streams
timokoessler f048b54
Fix Hono test
timokoessler cd03f1f
Fix PR comments
timokoessler 43696e4
Fixes
timokoessler 60c54e8
Improve test coverage
timokoessler 8d3086c
Fix hardcoded test
timokoessler File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import * as t from "tap"; | ||
| import { getRawRequestPath } from "./getRawRequestPath"; | ||
|
|
||
| t.test("it returns the raw URL path", async (t) => { | ||
| t.equal(getRawRequestPath(""), "/"); | ||
| t.equal(getRawRequestPath("/"), "/"); | ||
| t.equal(getRawRequestPath("/?test=abc"), "/"); | ||
| t.equal(getRawRequestPath("#"), "/"); | ||
| t.equal(getRawRequestPath("https://example.com"), "/"); | ||
|
|
||
| t.equal( | ||
| getRawRequestPath("https://example.com/path/to/resource"), | ||
| "/path/to/resource" | ||
| ); | ||
| t.equal( | ||
| getRawRequestPath("http://example.com/path/to/resource/"), | ||
| "/path/to/resource/" | ||
| ); | ||
| t.equal( | ||
| getRawRequestPath("https://example.com/path/to/resource/123"), | ||
| "/path/to/resource/123" | ||
| ); | ||
| t.equal( | ||
| getRawRequestPath("https://example.com/path/to/resource/123/456"), | ||
| "/path/to/resource/123/456" | ||
| ); | ||
| t.equal( | ||
| getRawRequestPath("https://example.com/path/to/resource/123/456/789"), | ||
| "/path/to/resource/123/456/789" | ||
| ); | ||
| t.equal( | ||
| getRawRequestPath( | ||
| "https://example.com/path/to/resource/123/456/789?query=string" | ||
| ), | ||
| "/path/to/resource/123/456/789" | ||
| ); | ||
| t.equal( | ||
| getRawRequestPath( | ||
| "https://example.com/path/to/resource/123/456/789#fragment" | ||
| ), | ||
| "/path/to/resource/123/456/789" | ||
| ); | ||
| t.equal( | ||
| getRawRequestPath( | ||
| "https://example.com/path/to/resource/123/456/789?query=string#fragment" | ||
| ), | ||
| "/path/to/resource/123/456/789" | ||
| ); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| export function getRawRequestPath(url: string): string { | ||
| let partialUrl = url; | ||
|
|
||
| // Remove protocol (http://, https://, etc.) | ||
timokoessler marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| const pathStart = partialUrl.indexOf("://"); | ||
| if (pathStart !== -1) partialUrl = partialUrl.slice(pathStart + 3); | ||
|
|
||
| // Remove hostname and port | ||
| const slashIndex = partialUrl.indexOf("/"); | ||
| if (slashIndex === -1) return "/"; // only hostname given | ||
| partialUrl = partialUrl.slice(slashIndex); | ||
|
|
||
| // Remove query and fragment | ||
| const queryIndex = partialUrl.indexOf("?"); | ||
| const hashIndex = partialUrl.indexOf("#"); | ||
|
|
||
| let endIndex = partialUrl.length; | ||
| if (queryIndex !== -1) endIndex = Math.min(endIndex, queryIndex); | ||
| if (hashIndex !== -1) endIndex = Math.min(endIndex, hashIndex); | ||
|
|
||
| return partialUrl.slice(0, endIndex) || "/"; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,200 @@ | ||
| import * as t from "tap"; | ||
| import { getRequestUrl } from "./getRequestUrl"; | ||
|
|
||
| import { get as httpGet, createServer, IncomingMessage } from "node:http"; | ||
|
|
||
| t.beforeEach(() => { | ||
| delete process.env.AIKIDO_TRUST_PROXY; | ||
| }); | ||
|
|
||
| async function getRealRequest(): Promise<IncomingMessage> { | ||
| return new Promise((resolve) => { | ||
| const server = createServer((req, res) => { | ||
| res.statusCode = 200; | ||
| res.end(); | ||
| server.close(); // stop server once we have a request | ||
| resolve(req); | ||
| }); | ||
| server.listen(0, () => { | ||
| const { port } = server.address() as any; | ||
| // Send a real request to trigger IncomingMessage creation | ||
| httpGet({ port, path: "/", headers: {} }, (res) => { | ||
| while (res.read()) { | ||
| // consume body to prevent test from not exiting | ||
| } | ||
|
|
||
| t.same(res.statusCode, 200); | ||
| }).end(); | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| let baseMockRequest: IncomingMessage | null = null; | ||
|
|
||
| async function createMockRequest( | ||
| overrides: Partial<IncomingMessage> = {} | ||
| ): Promise<IncomingMessage> { | ||
| if (!baseMockRequest) { | ||
| baseMockRequest = await getRealRequest(); | ||
| } | ||
| return Object.assign( | ||
| Object.create(Object.getPrototypeOf(baseMockRequest)), | ||
| baseMockRequest, | ||
| overrides | ||
| ); | ||
| } | ||
|
|
||
| t.test("already absolute URL", async (t) => { | ||
| t.equal( | ||
| getRequestUrl(await createMockRequest({ url: "http://example.com/path" })), | ||
| "http://example.com/path" | ||
| ); | ||
|
|
||
| t.equal( | ||
| getRequestUrl( | ||
| await createMockRequest({ url: "https://example.com/path?test=123" }) | ||
| ), | ||
| "https://example.com/path?test=123" | ||
| ); | ||
| }); | ||
|
|
||
| t.test("no url set", async (t) => { | ||
| const mockReq = await createMockRequest({ url: undefined }); | ||
| t.equal(getRequestUrl(mockReq), `http://${mockReq.headers.host}`); | ||
| }); | ||
|
|
||
| t.test("no url and no host set", async (t) => { | ||
| t.equal( | ||
| getRequestUrl( | ||
| await createMockRequest({ | ||
| url: undefined, | ||
| headers: {}, | ||
| }) | ||
| ), | ||
| "" | ||
| ); | ||
| }); | ||
|
|
||
| t.test("no host header", async (t) => { | ||
| t.equal( | ||
| getRequestUrl( | ||
| await createMockRequest({ | ||
| url: "/some/path?query=1", | ||
| headers: {}, | ||
| }) | ||
| ), | ||
| "/some/path?query=1" | ||
| ); | ||
| }); | ||
|
|
||
| t.test("relative URL with host header", async (t) => { | ||
| t.equal( | ||
| getRequestUrl( | ||
| await createMockRequest({ | ||
| url: "/some/path?query=1", | ||
| headers: { host: "example.com" }, | ||
| }) | ||
| ), | ||
| "http://example.com/some/path?query=1" | ||
| ); | ||
| }); | ||
|
|
||
| t.test("With X-Forwarded-Host header and trust proxy disabled", async (t) => { | ||
| process.env.AIKIDO_TRUST_PROXY = "0"; | ||
|
|
||
| t.equal( | ||
| getRequestUrl( | ||
| await createMockRequest({ | ||
| url: "/forwarded/path", | ||
| headers: { | ||
| host: "original.com", | ||
| "x-forwarded-host": "forwarded.com", | ||
| }, | ||
| }) | ||
| ), | ||
| "http://original.com/forwarded/path" | ||
| ); | ||
| }); | ||
|
|
||
| t.test("With X-Forwarded-Host header and trust proxy enabled", async (t) => { | ||
| t.equal( | ||
| getRequestUrl( | ||
| await createMockRequest({ | ||
| url: "/forwarded/path", | ||
| headers: { | ||
| host: "original.com", | ||
| "x-forwarded-host": "forwarded.com", | ||
| }, | ||
| }) | ||
| ), | ||
| "http://forwarded.com/forwarded/path" | ||
| ); | ||
| }); | ||
|
|
||
| t.test("With X-Forwarded-Proto header and trust proxy enabled", async (t) => { | ||
| t.equal( | ||
| getRequestUrl( | ||
| await createMockRequest({ | ||
| url: "/secure/path", | ||
| headers: { | ||
| host: "example.com", | ||
| "x-forwarded-proto": "https", | ||
| }, | ||
| }) | ||
| ), | ||
| "https://example.com/secure/path" | ||
| ); | ||
| }); | ||
|
|
||
| t.test("With X-Forwarded-Proto header set to invalid value", async (t) => { | ||
| t.equal( | ||
| getRequestUrl( | ||
| await createMockRequest({ | ||
| url: "/weird/path", | ||
| headers: { | ||
| host: "example.com", | ||
| "x-forwarded-proto": "abc", | ||
| }, | ||
| }) | ||
| ), | ||
| "http://example.com/weird/path" | ||
| ); | ||
| }); | ||
|
|
||
| t.test("With X-Forwarded-Proto header and trust proxy disabled", async (t) => { | ||
| process.env.AIKIDO_TRUST_PROXY = "0"; | ||
|
|
||
| t.equal( | ||
| getRequestUrl( | ||
| await createMockRequest({ | ||
| url: "/notrust/path", | ||
| headers: { | ||
| host: "example.com", | ||
| "x-forwarded-proto": "https", | ||
| }, | ||
| }) | ||
| ), | ||
| "http://example.com/notrust/path" | ||
| ); | ||
| }); | ||
|
|
||
| t.test("url does not start with slash and is not absolute", async (t) => { | ||
| t.equal( | ||
| getRequestUrl( | ||
| await createMockRequest({ | ||
| url: "noslash/path", | ||
| headers: { host: "example.com" }, | ||
| }) | ||
| ), | ||
| "http://example.com/noslash/path" | ||
| ); | ||
| }); | ||
|
|
||
| t.test("url does not start with http/https but is absolute", async (t) => { | ||
| t.match( | ||
| getRequestUrl( | ||
| await createMockRequest({ url: "ftp://example.com/resource" }) | ||
| ), | ||
| /http:\/\/localhost:\d+\/ftp:\/\/example.com\/resource/ | ||
| ); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| import type { IncomingMessage } from "http"; | ||
| import { Http2ServerRequest } from "http2"; | ||
| import type { TLSSocket } from "tls"; | ||
| import { trustProxy } from "./trustProxy"; | ||
|
|
||
| /** | ||
timokoessler marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| * Get the full request URL including protocol and host. | ||
| * Falls back to relative URL if host is not available. | ||
| * Also respects forwarded headers if proxies are trusted. | ||
| */ | ||
| export function getRequestUrl( | ||
| req: IncomingMessage | Http2ServerRequest | ||
| ): string { | ||
| const reqUrl = req.url || ""; | ||
|
|
||
| // Already absolute URL | ||
| if ( | ||
| reqUrl[0] !== "/" && // performance improvement | ||
| (reqUrl.startsWith("http://") || reqUrl.startsWith("https://")) | ||
| ) { | ||
| return reqUrl; | ||
| } | ||
|
|
||
| // Relative URL | ||
| const host = getHost(req); | ||
| if (!host) { | ||
| // Fallback to relative URL if host is not available | ||
| return reqUrl; | ||
| } | ||
|
|
||
| // Determine protocol, fallback to http if not detectable | ||
| const protocol = getProtocol(req); | ||
|
|
||
| if (reqUrl.length && !reqUrl.startsWith("/")) { | ||
| // Ensure there's a slash between host and path | ||
| return `${protocol}://${host}/${reqUrl}`; | ||
| } | ||
|
|
||
| return `${protocol}://${host}${reqUrl}`; | ||
| } | ||
|
|
||
| function getHost( | ||
timokoessler marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| req: IncomingMessage | Http2ServerRequest | ||
| ): string | undefined { | ||
| const forwardedHost = req.headers?.["x-forwarded-host"]; | ||
|
|
||
| if (typeof forwardedHost === "string" && trustProxy()) { | ||
| return forwardedHost; | ||
| } | ||
|
|
||
| const host = | ||
| req instanceof Http2ServerRequest ? req.authority : req.headers?.host; | ||
| if (typeof host === "string") { | ||
| return host; | ||
| } | ||
|
|
||
| return undefined; | ||
| } | ||
|
|
||
| function getProtocol( | ||
| req: IncomingMessage | Http2ServerRequest | ||
| ): "http" | "https" { | ||
| const forwarded = | ||
| req.headers?.["x-forwarded-proto"] || req.headers?.["x-forwarded-protocol"]; | ||
| if (typeof forwarded === "string" && trustProxy()) { | ||
| const normalized = forwarded.toLowerCase(); | ||
| if (normalized === "https" || normalized === "http") { | ||
| return normalized; | ||
| } | ||
| } | ||
|
|
||
| if (req instanceof Http2ServerRequest && req.scheme === "https") { | ||
| return "https"; | ||
| } | ||
|
|
||
| if (req.socket && (req.socket as TLSSocket).encrypted) { | ||
| return "https"; | ||
| } | ||
|
|
||
| return "http"; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.