fix(proxy): Correct hop-by-hop header handling per RFC 9110 (#4459)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* chore: fix hop-by-headers * test(proxy): fix test for hop-by-hop headers * Update src/helper/proxy/index.ts * reflect comments * ci: apply automated fixes * handling invalid header * throw error ---------
authored by sugar-cat · committed by GitHub · parent 4b796cf · Browse files · 2 files·+115 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Taku Amano <taku@taaas.jp>
- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Diff stats
2 files+115 added−7 removed
- tests:+59 added−2 removed
- other:+56 added−5 removed
Provenance
- Commit
9ae98c9- Tree
69ff625- Author
sugar-cat <69241625+sugar-cat7@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
4b796cf
2 files changed+115 added−7 removed
modified:src/helper/proxy/index.test.ts+59 added-2 removed
138 unmodified lines139 })140 141 it('remove hop-by-hop headers', async () => {142 const app = new Hono()143- app.get('/proxy/:path', (c) => proxy(`https://example.com/${c.req.param('path')}`))143+ app.get('/proxy/:path', (c) => proxy(`https://example.com/${c.req.param('path')}`, c.req))144 145 const res = await app.request('/proxy/hop-by-hop', {146 headers: {147+ Host: 'example.com',147- Connection: 'keep-alive',148+ Connection: 'keep-alive, custom-header',149 'Keep-Alive': 'timeout=5, max=1000',150 'Proxy-Authorization': 'Basic 123456',151+ 'Custom-Header': 'test',152+ 'Allowed-Custom-Header': 'test',153 },154 })155 const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]156 157+ expect(req.headers.get('Host')).toBe('example.com')158 expect(req.headers.get('Connection')).toBeNull()159 expect(req.headers.get('Keep-Alive')).toBeNull()160 expect(req.headers.get('Proxy-Authorization')).toBeNull()161+ expect(req.headers.get('Custom-Header')).toBe('test')162+ expect(req.headers.get('Allowed-Custom-Header')).toBe('test')163 164 expect(res.headers.get('Transfer-Encoding')).toBeNull()165 })166 167+ it('remove hop-by-hop headers with strictConnectionProcessing', async () => {168+ const app = new Hono()169+ app.get('/proxy/:path', (c) =>170+ proxy(`https://example.com/${c.req.param('path')}`, {171+ ...c.req,172+ strictConnectionProcessing: true,173+ })174+ )175+176+ const res = await app.request('/proxy/hop-by-hop', {177+ headers: {178+ Host: 'example.com',179+ Connection: 'keep-alive, custom-header',180+ 'Keep-Alive': 'timeout=5, max=1000',181+ 'Proxy-Authorization': 'Basic 123456',182+ 'Custom-Header': 'test',183+ 'Allowed-Custom-Header': 'test',184+ },185+ })186+ const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]187+188+ expect(req.headers.get('Host')).toBe('example.com')189+ expect(req.headers.get('Connection')).toBeNull()190+ expect(req.headers.get('Keep-Alive')).toBeNull()191+ expect(req.headers.get('Proxy-Authorization')).toBeNull()192+ expect(req.headers.get('Custom-Header')).toBeNull()193+ expect(req.headers.get('Allowed-Custom-Header')).toBe('test')194+195+ expect(res.headers.get('Transfer-Encoding')).toBeNull()196+ })197+198+ it('invalid hop-by-hop headers with strictConnectionProcessing', async () => {199+ const app = new Hono()200+ app.get('/proxy/:path', (c) =>201+ proxy(`https://example.com/${c.req.param('path')}`, {202+ ...c.req,203+ strictConnectionProcessing: true,204+ })205+ )206+207+ const res = await app.request('/proxy/hop-by-hop', {208+ headers: {209+ Host: 'example.com',210+ Connection: 'keep-alive, invalid-header invalid-header',211+ 'Keep-Alive': 'timeout=5, max=1000',212+ },213+ })214+215+ expect(res.status).toBe(400)216+ })217+218 it('specify hop-by-hop header by options', async () => {219 const app = new Hono()220 app.get('/proxy/:path', (c) =>221 proxy(`https://example.com/${c.req.param('path')}`, {115 unmodified linesmodified:src/helper/proxy/index.ts+56 added-5 removed
1234567891011121314151516171819202122232425262728293031323334353637383940414243444546474849503451525354555657585960616263646566676869707172737475767778798081828362 unmodified lines14614714814915015115215315415515615715815916011411516116216316416516616716811816917017117217317 unmodified lines/** * @module * Proxy Helper for Hono. */
import { HTTPException } from '../../http-exception'import type { RequestHeader } from '../../utils/headers'
// https://datatracker.ietf.org/doc/html/rfc2616#section-13.5.1const hopByHopHeaders = [ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'trailer', 'transfer-encoding', 'upgrade',]
// https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.2const ALLOWED_TOKEN_PATTERN = /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/
interface ProxyRequestInit extends Omit<RequestInit, 'headers'> { raw?: Request headers?: | HeadersInit | [string, string][] | Record<RequestHeader, string | undefined> | Record<string, string | undefined> customFetch?: (request: Request) => Promise<Response> /** * Enable strict RFC 9110 compliance for Connection header processing. * * - `false` (default): Ignores Connection header to prevent potential * Hop-by-Hop Header Injection attacks. Recommended for untrusted clients. * - `true`: Processes Connection header per RFC 9110 and removes listed headers. * Only use in trusted environments. * * @default false * @see https://datatracker.ietf.org/doc/html/rfc9110#section-7.6.1 */ strictConnectionProcessing?: boolean}
interface ProxyFetch { (input: string | URL | Request, init?: ProxyRequestInit): Promise<Response>}
const buildRequestInitFromRequest = ( request: Request | undefined request: Request | undefined, strictConnectionProcessing: boolean): RequestInit & { duplex?: 'half' } => { if (!request) { return {} }
const headers = new Headers(request.headers)
if (strictConnectionProcessing) { // https://datatracker.ietf.org/doc/html/rfc9110#section-7.6.1 // Parse Connection header and remove listed headers (MUST per RFC 9110) const connectionValue = headers.get('connection') if (connectionValue) { const headerNames = connectionValue.split(',').map((h) => h.trim()) // Validate header names per RFC 9110 Section 5.6.2 (token syntax) const invalidHeaders = headerNames.filter((h) => !ALLOWED_TOKEN_PATTERN.test(h))
if (invalidHeaders.length > 0) { throw new HTTPException(400, { message: `Invalid Connection header value: ${invalidHeaders.join(', ')}`, }) } headerNames.forEach((headerName) => { headers.delete(headerName) }) } }
hopByHopHeaders.forEach((header) => { headers.delete(header) })
62 unmodified lines * Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization') * }, * }) * }) * * // Strict RFC compliance mode (use only in trusted environments) * app.get('/internal-proxy/:path', (c) => { * return proxy(`http://${internalServer}/${c.req.param('path')}`, { * ...c.req, * strictConnectionProcessing: true, * }) * }) * ``` */export const proxy: ProxyFetch = async (input, proxyInit) => { const { raw, customFetch, ...requestInit } = proxyInit instanceof Request ? { raw: proxyInit } : proxyInit ?? {} const { raw, customFetch, strictConnectionProcessing = false, ...requestInit } = proxyInit instanceof Request ? { raw: proxyInit } : proxyInit ?? {}
const req = new Request(input, { ...buildRequestInitFromRequest(raw), ...buildRequestInitFromRequest(raw, strictConnectionProcessing), ...preprocessRequestInit(requestInit as RequestInit), }) req.headers.delete('accept-encoding')
17 unmodified lines