-
Notifications
You must be signed in to change notification settings - Fork 879
feat(ipv6): support literal IPv6 addresses in 'target' and 'forward' options #1206
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
Merged
+361
−0
Merged
Changes from all commits
Commits
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,69 @@ | ||
| import type * as http from 'node:http'; | ||
|
|
||
| import { Debug } from '../debug.js'; | ||
| import type { Options } from '../types.js'; | ||
|
|
||
| const debug = Debug.extend('ipv6'); | ||
|
|
||
| /** | ||
| * Normalize bracketed IPv6 URL targets into unbracketed host options. | ||
| * | ||
| * RFC 2732 defines the URL syntax for literal IPv6 addresses as bracketed | ||
| * host references (for example `http://[::1]:8080/path` where host is | ||
| * `[::1]`). | ||
| * | ||
| * `httpxy` resolves bracketed hostnames (for example `[::1]`) via DNS, | ||
| * which can fail for IPv6 literals. This converts string/URL `target` and | ||
| * `forward` values into object form with `hostname: ::1` (brackets removed) | ||
| * so the address can be connected directly. | ||
| * | ||
| * Reference: RFC 2732, Section 2 (Literal IPv6 Address Format in URL's) | ||
| * https://www.ietf.org/rfc/rfc2732.txt | ||
| * | ||
| * The provided options object is mutated in place. | ||
| */ | ||
| export function normalizeIPv6LiteralTargets< | ||
| TReq extends http.IncomingMessage = http.IncomingMessage, | ||
| TRes extends http.ServerResponse = http.ServerResponse, | ||
| >(options: Options<TReq, TRes>): void { | ||
| options.target = normalizeIPv6ProxyTarget(options.target, 'target'); | ||
| options.forward = normalizeIPv6ProxyTarget(options.forward, 'forward'); | ||
| } | ||
|
|
||
| function normalizeIPv6ProxyTarget(target: Options['target'], optionName: 'target' | 'forward') { | ||
| const targetUrl = toTargetUrl(target); | ||
|
|
||
| if (targetUrl && isBracketedIPv6Hostname(targetUrl.hostname)) { | ||
| debug('normalized IPv6 "%s" %s', optionName, target); | ||
|
|
||
| return { | ||
| hostname: stripBrackets(targetUrl.hostname), | ||
| pathname: targetUrl.pathname, | ||
| port: targetUrl.port, | ||
| protocol: targetUrl.protocol, | ||
| search: targetUrl.search, | ||
| }; | ||
| } | ||
|
|
||
| return target; | ||
| } | ||
|
|
||
| function toTargetUrl(target: Options['target']): URL | undefined { | ||
| if (typeof target === 'string') { | ||
| return new URL(target); | ||
| } | ||
|
|
||
| if (target instanceof URL) { | ||
| return target; | ||
| } | ||
|
|
||
| return undefined; | ||
| } | ||
|
|
||
| function isBracketedIPv6Hostname(hostname: string): boolean { | ||
| return hostname.startsWith('[') && hostname.endsWith(']'); | ||
| } | ||
|
|
||
| function stripBrackets(hostname: string): string { | ||
| return hostname.replace(/^\[|\]$/g, ''); | ||
| } | ||
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,182 @@ | ||
| import type { Mockttp } from 'mockttp'; | ||
| import { getLocal } from 'mockttp'; | ||
| import request from 'supertest'; | ||
| import { afterEach, beforeEach, describe, expect, it } from 'vitest'; | ||
|
|
||
| import { createApp, createProxyMiddleware } from './test-kit.js'; | ||
|
|
||
| describe('ipv6 integration', () => { | ||
| let targetServer: Mockttp; | ||
|
|
||
| beforeEach(async () => { | ||
| targetServer = getLocal(); | ||
| await targetServer.start(); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| await targetServer.stop(); | ||
| }); | ||
|
|
||
| it('should proxy to ipv6 target using bracket notation with port', async () => { | ||
| await targetServer.forGet('/api').thenCallback((req) => ({ | ||
| statusCode: 200, | ||
| body: req.path, | ||
| })); | ||
|
|
||
| const proxy = createProxyMiddleware({ | ||
| changeOrigin: true, | ||
| target: `http://[::1]:${targetServer.port}`, | ||
| }); | ||
|
|
||
| const app = createApp(proxy); | ||
| const response = await request(app).get('/api').expect(200); | ||
|
|
||
| expect(response.text).toBe('/api'); | ||
| }); | ||
|
|
||
| it('should proxy to unspecified ipv6 target using bracket notation with port', async () => { | ||
| await targetServer.forGet('/api').thenCallback((req) => ({ | ||
| statusCode: 200, | ||
| body: req.path, | ||
| })); | ||
|
|
||
| const proxy = createProxyMiddleware({ | ||
| changeOrigin: true, | ||
| target: `http://[::]:${targetServer.port}`, | ||
| }); | ||
|
|
||
| const app = createApp(proxy); | ||
| const response = await request(app).get('/api').expect(200); | ||
|
|
||
| expect(response.text).toBe('/api'); | ||
| }); | ||
|
|
||
| it('should proxy to ipv6 target and preserve query params', async () => { | ||
| let receivedPath: string | undefined; | ||
|
|
||
| await targetServer.forGet('/api').thenCallback((req) => { | ||
| receivedPath = req.path; | ||
| return { | ||
| statusCode: 200, | ||
| body: req.url.includes('?') ? req.url.split('?')[1] : '', | ||
| }; | ||
| }); | ||
|
|
||
| const proxy = createProxyMiddleware({ | ||
| changeOrigin: true, | ||
| target: `http://[::1]:${targetServer.port}`, | ||
| }); | ||
|
|
||
| const app = createApp(proxy); | ||
| const response = await request(app).get('/api?foo=bar&baz=qux').expect(200); | ||
|
|
||
| expect(receivedPath).toBe('/api?foo=bar&baz=qux'); | ||
| expect(response.text).toBe('foo=bar&baz=qux'); | ||
| }); | ||
|
|
||
| it('should proxy to ipv6 target and preserve search params with special characters', async () => { | ||
| let receivedPath: string | undefined; | ||
|
|
||
| await targetServer.forGet('/api').thenCallback((req) => { | ||
| receivedPath = req.path; | ||
| return { | ||
| statusCode: 200, | ||
| body: req.url.includes('?') ? req.url.split('?')[1] : '', | ||
| }; | ||
| }); | ||
|
|
||
| const proxy = createProxyMiddleware({ | ||
| changeOrigin: true, | ||
| target: `http://[::1]:${targetServer.port}`, | ||
| }); | ||
|
|
||
| const app = createApp(proxy); | ||
| const response = await request(app).get('/api?q=hello%20world&page=1').expect(200); | ||
|
|
||
| expect(receivedPath).toBe('/api?q=hello%20world&page=1'); | ||
| expect(response.text).toBe('q=hello%20world&page=1'); | ||
| }); | ||
|
|
||
| it('should forward requests to ipv6 target using forward option', async () => { | ||
| let forwardedPath: string | undefined; | ||
|
|
||
| await targetServer.forPost('/api').thenCallback((req) => { | ||
| forwardedPath = req.path; | ||
| return { statusCode: 200 }; | ||
| }); | ||
|
|
||
| const proxy = createProxyMiddleware({ | ||
| changeOrigin: true, | ||
| target: `http://[::1]:${targetServer.port}`, | ||
| forward: `http://[::1]:${targetServer.port}`, | ||
| }); | ||
|
|
||
| const app = createApp(proxy); | ||
| await request(app).post('/api').expect(200); | ||
|
|
||
| expect(forwardedPath).toBe('/api'); | ||
| }); | ||
|
|
||
| it('should proxy to ipv6 target resolved via router function (no static target)', async () => { | ||
| await targetServer.forGet('/api').thenCallback((req) => ({ | ||
| statusCode: 200, | ||
| body: req.path, | ||
| })); | ||
|
|
||
| const proxy = createProxyMiddleware({ | ||
| changeOrigin: true, | ||
| target: 'http://example.com', // dummy target, will be overridden by router | ||
| router: () => `http://[::1]:${targetServer.port}`, | ||
| }); | ||
|
|
||
| const app = createApp(proxy); | ||
| const response = await request(app).get('/api').expect(200); | ||
|
|
||
| expect(response.text).toBe('/api'); | ||
| }); | ||
|
|
||
| it('should proxy to ipv6 target resolved via async router function', async () => { | ||
| await targetServer.forGet('/api').thenCallback((req) => ({ | ||
| statusCode: 200, | ||
| body: req.path, | ||
| })); | ||
|
|
||
| const proxy = createProxyMiddleware({ | ||
| changeOrigin: true, | ||
| target: 'http://example.com', // dummy target, will be overridden by router | ||
| router: async () => `http://[::1]:${targetServer.port}`, | ||
| }); | ||
|
|
||
| const app = createApp(proxy); | ||
| const response = await request(app).get('/api').expect(200); | ||
|
|
||
| expect(response.text).toBe('/api'); | ||
| }); | ||
|
|
||
| it('should proxy to ipv6 target with base path and auth option', async () => { | ||
| let receivedPath: string | undefined; | ||
| let authorizationHeader: string | undefined; | ||
|
|
||
| await targetServer.forGet('/api').thenCallback((req) => { | ||
| receivedPath = req.path; | ||
| const authHeader = req.headers.authorization; | ||
| authorizationHeader = Array.isArray(authHeader) ? authHeader[0] : authHeader; | ||
|
|
||
| return { | ||
| statusCode: 200, | ||
| }; | ||
| }); | ||
|
|
||
| const proxy = createProxyMiddleware({ | ||
| changeOrigin: true, | ||
| target: `http://[::1]:${targetServer.port}/api`, | ||
| auth: 'user:pass', | ||
| }); | ||
|
|
||
| const app = createApp(proxy); | ||
| await request(app).get('/').expect(200); | ||
|
|
||
| expect(receivedPath).toBe('/api'); | ||
| expect(authorizationHeader).toBe('Basic dXNlcjpwYXNz'); // cspell:disable-line | ||
| }); | ||
| }); |
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,107 @@ | ||
| import { describe, expect, it } from 'vitest'; | ||
|
|
||
| import type { Options } from '../../../src/types.js'; | ||
| import { normalizeIPv6LiteralTargets } from '../../../src/utils/ipv6.js'; | ||
|
|
||
| describe('normalizeIPv6Targets()', () => { | ||
| it('should mutate the same options object', () => { | ||
| const options: Options = { | ||
| target: 'http://[::1]:8888/api?foo=bar', | ||
| }; | ||
|
|
||
| const originalOptions = options; | ||
| normalizeIPv6LiteralTargets(options); | ||
|
|
||
| expect(options).toBe(originalOptions); | ||
| }); | ||
|
|
||
| it('should normalize bracketed IPv6 target string without port into a target object', () => { | ||
| const options: Options = { | ||
| target: 'http://[::1]/api', | ||
| }; | ||
|
|
||
| normalizeIPv6LiteralTargets(options); | ||
|
|
||
| expect(options.target).toEqual({ | ||
| hostname: '::1', | ||
| pathname: '/api', | ||
| port: '', | ||
| protocol: 'http:', | ||
| search: '', | ||
| }); | ||
| }); | ||
|
|
||
| it('should normalize bracketed IPv6 target string into a target object', () => { | ||
| const options: Options = { | ||
| target: 'http://[::1]:8888/api?foo=bar', | ||
| }; | ||
|
|
||
| normalizeIPv6LiteralTargets(options); | ||
|
|
||
| expect(options.target).toEqual({ | ||
| hostname: '::1', | ||
| pathname: '/api', | ||
| port: '8888', | ||
| protocol: 'http:', | ||
| search: '?foo=bar', | ||
| }); | ||
| }); | ||
|
|
||
| it('should normalize bracketed IPv6 target URL into a target object', () => { | ||
| const options: Options = { | ||
| target: new URL('http://[::1]:8888/api'), | ||
| }; | ||
|
|
||
| normalizeIPv6LiteralTargets(options); | ||
|
|
||
| expect(options.target).toEqual({ | ||
| hostname: '::1', | ||
| pathname: '/api', | ||
| port: '8888', | ||
| protocol: 'http:', | ||
| search: '', | ||
| }); | ||
| }); | ||
|
|
||
| it('should normalize bracketed IPv6 forward string into a forward object', () => { | ||
| const options: Options = { | ||
| forward: 'http://[::1]:9999/', | ||
| }; | ||
|
|
||
| normalizeIPv6LiteralTargets(options); | ||
|
|
||
| expect(options.forward).toEqual({ | ||
| hostname: '::1', | ||
| pathname: '/', | ||
| port: '9999', | ||
| protocol: 'http:', | ||
| search: '', | ||
| }); | ||
| }); | ||
|
|
||
| it('should leave non-IPv6 string targets unchanged', () => { | ||
| const options: Options = { | ||
| target: 'http://127.0.0.1:8888/api', | ||
| }; | ||
|
|
||
| normalizeIPv6LiteralTargets(options); | ||
|
|
||
| expect(options.target).toBe('http://127.0.0.1:8888/api'); | ||
| }); | ||
|
|
||
| it('should leave object targets unchanged', () => { | ||
| const target: Options['target'] = { | ||
| hostname: '::1', | ||
| port: 8888, | ||
| protocol: 'http:', | ||
| }; | ||
|
|
||
| const options: Options = { | ||
| target, | ||
| }; | ||
|
|
||
| normalizeIPv6LiteralTargets(options); | ||
|
|
||
| expect(options.target).toBe(target); | ||
| }); | ||
| }); |
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.