Skip to content
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

feat(helper/proxy): introduce proxy helper #3589

Open
wants to merge 16 commits into
base: main
Choose a base branch
from

Conversation

usualoma
Copy link
Member

fixes #3518

Naming

The name proxyFetch seems a little redundant, but I rejected the other candidates for the following reasons.

  • proxy : The name proxy is simple but is avoided because it is confusing with the JavaScript Proxy object.
  • fetch : The name fetch is also good. Although it is in the helper/proxy namespace, so it can be distinguished, when it is used by being incorporated into the application, from the standpoint of reading the code, it looks like globalThis.fetch is being called, so I decided to avoid it because of the cognitive load.

Usage

app.get('/proxy/:path', (c) => {
  return proxyFetch(new Request(`http://${originServer}/${c.req.param('path')}`, c.req.raw), {
    proxySetRequestHeaders: {
      'X-Forwarded-For': '127.0.0.1',
      'X-Forwarded-Host': c.req.header('host'),
      Authorization: undefined, // prevent propagating "Authorization" request headers in c.req.raw
    },
    proxyDeleteResponseHeaderNames: ['Cookie'],
  })
})

The author should do the following, if applicable

  • Add tests
  • Run tests
  • bun run format:fix && bun run lint:fix to format the code
  • Add TSDoc/JSDoc to document the code

Copy link

codecov bot commented Oct 30, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.37%. Comparing base (d40fffb) to head (8a81633).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3589      +/-   ##
==========================================
+ Coverage   91.32%   91.37%   +0.05%     
==========================================
  Files         161      163       +2     
  Lines       10242    10308      +66     
  Branches     2889     2874      -15     
==========================================
+ Hits         9353     9419      +66     
  Misses        888      888              
  Partials        1        1              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@haochenx haochenx left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all looks good to me except regarding the handling of range request and deletion of the Content-Length header from the response

* * Content-Length
* * Content-Range
*/
const forceDeleteResponseHeaderNames = ['Content-Encoding', 'Content-Length', 'Content-Range']

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not sure about Content-Length and Content-Range, as if the original request is for a byte range, the semantics is not preserved. a probable semantically correct implementation:

  1. if the original request contains Range header, fast-fail with 400 status code
  2. strip Accept-Range from response header
  3. indicate upstream error if response header contain Content-Range

Content-Length should be left alone in all case IMO

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! This certainly needs fixing.

Content-Length

As you can see from the results below, in the case of a compressed response, Content-Length is the “size after compression”, so it cannot be returned as is.

% curl -I 'https://example.com/'
HTTP/2 200
accept-ranges: bytes
age: 526496
cache-control: max-age=604800
content-type: text/html; charset=UTF-8
date: Wed, 30 Oct 2024 21:13:42 GMT
etag: "3147526947"
expires: Wed, 06 Nov 2024 21:13:42 GMT
last-modified: Thu, 17 Oct 2019 07:18:26 GMT
server: ECAcc (lac/55F5)
x-cache: HIT
content-length: 1256
% curl --compressed --raw -i 'https://example.com/'
HTTP/2 200
content-encoding: gzip
age: 527039
cache-control: max-age=604800
content-type: text/html; charset=UTF-8
date: Wed, 30 Oct 2024 21:07:12 GMT
etag: "3147526947+gzip"
expires: Wed, 06 Nov 2024 21:07:12 GMT
last-modified: Thu, 17 Oct 2019 07:18:26 GMT
server: ECAcc (lac/55AA)
vary: Accept-Encoding
x-cache: HIT
content-length: 648
  • Delete <- This is the current implementation
  • Load the body and reset it <- There is an overhead because you have to clone() and load all the data

Some people may expect the latter, but since hono does not actively add Content-Length to other requests either, I think this is a reasonable response for hono.

However, if there is no Content-Encoding in the first place, there is no need to delete the Content-Length. I think this should be improved.

Content-Range

I think the current implementation is incorrect.
It seems that this will not change depending on Content-Encoding (although in a real environment, it seems that the result of compression will almost never be returned in a request with Range), so I think it is correct to always return it as is.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5998770 and 3a5ef0f.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Content-Length is the “size after compression”, so it cannot be returned as is.

Oh, in that case I am in favor of unconditionally deleting it.

It seems that this will not change depending on Content-Encoding (although in a real environment, it seems that the result of compression will almost never be returned in a request with Range), so I think it is correct to always return it as is.

I have no reason to believe the new implementation is incorrect and this seems to be a suitable strategy.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

Copy link

@haochenx haochenx left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me.

@yusukebe
Copy link
Member

yusukebe commented Nov 5, 2024

Hey @usualoma ! Thank you for the PR. I'll try to use this and comment later.

@haochenx
Copy link

haochenx commented Nov 6, 2024

@usualoma @yusukebe many thanks for your amazing works again!

just fyi we ended up using a pre/process combo like the following to mitigate

  1. somehow (I guess when http/2 is enabled? we observed this when enabling https on vite's devserver) creating RequestInit using { ...resq } (also for ResponseInit) does not work sometime, and fields needs to be assembled manually
  2. "connection" and "transfer-encoding" header needs to be filtered to avoid node throwing ERR_HTTP2_INVALID_CONNECTION_HEADERS

we are only using this particular proxying method in dev server, so there might be other catches..

    const response = await fetch(
      new Request(target, {
        body: c.req.raw.body,
        method: c.req.raw.method,
        headers: [...c.req.raw.headers.entries()].filter(
          ([k]) => !["connection", "accept-encoding"].includes(k.toLocaleLowerCase()),
        ),
      }),
    );
    return new Response(response.body, {
      ...response,
      status: response.status,
      statusText: response.statusText,
      headers: [...response.headers.entries()].filter(
        ([k]) =>
          !["content-encoding", "transfer-encoding", "content-length"].includes(
            k.toLocaleLowerCase(),
          ),
      ),
    });

@haochenx
Copy link

haochenx commented Nov 6, 2024

also, on node v22.11.0, it seems that duplex: "half" is needed on the RequestInit passed to fetch when the incoming request contains body (e.g. a POST request)

@usualoma
Copy link
Member Author

usualoma commented Nov 7, 2024

@haochenx Thank you!

Note: We probably need to delete “Hop-by-hop Headers."
https://datatracker.ietf.org/doc/html/rfc2616#section-13.5.1

@john-griffin
Copy link

Looking forward to this one, we use http-proxy-middleware in express and it's super helpful.

@yusukebe
Copy link
Member

@john-griffin Thanks for the information! We can refer to it.

@jbergstroem
Copy link

Happy to sponsor to see this land; it would help me migrate an app to Hono.

@yusukebe
Copy link
Member

Hi @usualoma

Sorry for my super late response!

I've said, "Proxy helper is good," but is there any reason not to make it as middleware? I think making it as middleware is good because the user should not pass the params such as c.req.raw:

import { Hono } from 'hono'
import { createProxy } from 'hono/proxy'

const app = new Hono()

app.use(
  '/proxy/*',
  createProxy({
    target: 'https://example.com/',
  })
)

This API is inspired by http-proxy-middleware. What do you think of this?

@usualoma
Copy link
Member Author

Hi @yusukebe

Well, proxying is essentially a pretty dangerous operation, and if the implementation is such that c.req.raw is forwarded by default, I think that if you use it carelessly, your cookies and Authorization headers will leak to external sites.

I didn't want that to happen, so I made it so that you could ‘explicitly see that c.req.raw is being passed’.

That said, in general, proxy servers pass things on as they are, so I think it's fine to say that if there's an accident, it's the developer's responsibility.

My concern is that if this is provided as middleware, there will be cases where it would have been sufficient (and safe) to simply use fetch

app.get(‘/’, () => fetch(‘https://example.com/’))

there will be users who use middleware without thinking carefully and pass on unnecessary information.

With this PR's implementation, if there is no need to pass c.req.raw, it is not necessary to do so. The aim is to solve issues such as range when using fetch to proxy.

@usualoma
Copy link
Member Author

This was the idea behind the creation of this PR, but even so, I don't think that explicitly passing c.req.raw makes it any more secure.

There is no problem with proxying to the backend you manage, so if the use case you have in mind is something like that, there is no problem even if c.req.raw is forwarded, and as you pointed out, I think it would be a good API design to implement it as middleware.

@yusukebe
Copy link
Member

@usualoma

Thank you for the explanation! I was able to understand your concern well. I'll consider it.

@yusukebe yusukebe added the v4.7 label Jan 20, 2025
* @example
* ```ts
* app.get('/proxy/:path', (c) => {
* return proxyFetch(new Request(`http://${originServer}/${c.req.param('path')}`, c.req.raw), {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like not using new Request() style like this:

app.get('/proxy/:path', (c) => {
  return proxyFetch(`https://example.com/${c.req.param('path')}`, {
    ...c.req.raw,
    proxySetRequestHeaders: {
      'X-Forwarded-For': '127.0.0.1',
    },
  })
})

Then, if you have the following code:

app.get('/proxy/:path', (c) =>
  proxyFetch(
    new Request(`https://example.com/${c.req.param('path')}`, {
      headers: {
        'X-Request-Id': '123',
        'Accept-Encoding': 'gzip',
      },
    }),
    {
      proxyDeleteResponseHeaderNames: ['X-Response-Id'],
    }
  )
)

you can also write it with not using new Request() style:

app.get('/proxy/:path', (c) =>
  proxyFetch(`https://example.com/${c.req.param('path')}`, {
    headers: {
      'X-Request-Id': '123',
      'Accept-Encoding': 'gzip',
    },
    proxyDeleteResponseHeaderNames: ['X-Response-Id'],
  })
)

These are short and user does not have to call new Request(). Both are okay, but I would like to write all cases in the code or examples with not using new Request() style. What do you think of it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yusukebe
Sorry for the late reply. I understand your point.

I also think that it would be better not to show the raw part of c.req.raw if possible. I think that there is a risk in the statement that ‘all headers are transferred by default’, but I think that it would be best not to write raw.

And, because proxySetRequestHeaders and proxyDeleteResponseHeaderNames are also difficult to understand, I feel that it would be good to be able to write the following for proxies for GET requests.

app.get('/proxy/:path', (c) => {
  return proxyFetch(`http://${originServer}/${c.req.param('path')}`, {
    headers: {
      ...c.req.header(), // optional, specify only when header forwarding is truly necessary.
      'X-Forwarded-For': '127.0.0.1',
      'X-Forwarded-Host': c.req.header('host'),
      Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')
    },
  }).then((res) => {
    res.headers.delete('Cookie')
    return res
  })
})

I wish it were possible to write a proxy for arbitrary requests, including POST, in a simpler way.

@yusukebe
Copy link
Member

Hey @usualoma

I've considered it, and I found out that this Proxy Helper is so good! This is because it is just a wrapper of fetch but will resolve @haochenx 's problem simply. As you said, the help does not always need c.req.raw or a Context, so this should not be middleware.

I've left a comment. Please check it!

@usualoma
Copy link
Member Author

usualoma commented Jan 26, 2025

Hi @yusukebe

I've reconsidered the API, and I think it would be good to add b6eb510 and fb54227 so that it can be written as follows.

I was worried about confusion with the Proxy object when I was writing this issue, but I think it's fine now, and I think it's easier to write with a short name.

app.get('/proxy/:path', (c) =>
  proxy(`http://${originServer}/${c.req.param('path')}`, {
    headers: {
      ...c.req.header(), // optional, specify only when forwarding all the request data (including credentials) is necessary.
      'X-Forwarded-For': '127.0.0.1',
      'X-Forwarded-Host': c.req.header('host'),
      Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')
    },
  }).then((res) => {
    res.headers.delete('Cookie')
    return res
  })

app.any('/proxy/:path', (c) =>
  proxy(`http://${originServer}/${c.req.param('path')}`, {
    ...c.req, // optional, specify only when forwarding all the request data (including credentials) is necessary
    headers: {
      ...c.req.header(),
      'X-Forwarded-For': '127.0.0.1',
      'X-Forwarded-Host': c.req.header('host'),
      Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')
    },
  })

@usualoma
Copy link
Member Author

dc24de3 also allows you to write as follows.

app.any('/proxy/:path', (c) => proxy(`http://${originServer}/${c.req.param('path')}`, c.req))

@usualoma
Copy link
Member Author

But now that I think about it, since serveStatic is middleware, it might be appropriate to think of proxy as middleware too.

@usualoma
Copy link
Member Author

No, I was wrong, serveStatic wasn't in the list of middleware.

CleanShot 2025-01-26 at 21 01 45@2x

If that's the case, I think it's more appropriate to think of proxy in this category as a helper rather than middleware, so I think the way of this PR, which can simply replace the fetch API, is good.

@usualoma
Copy link
Member Author

It is now ready to be merged.

@yusukebe
Copy link
Member

@usualoma Thanks! I'll check it tomorrow.

@usualoma
Copy link
Member Author

🙇 One refactoring commit has been added.

2e8e250

@yusukebe
Copy link
Member

Hey @usualoma !

Looks good! The only things are about TypeScript-type issues. I've got the following type errors with the examples:

CleanShot 2025-01-27 at 19 37 58@2x

I updated the code, and I think this is good. The diff is the following:

diff --git a/src/helper/proxy/index.ts b/src/helper/proxy/index.ts
index 03fd7240..6c0f87e6 100644
--- a/src/helper/proxy/index.ts
+++ b/src/helper/proxy/index.ts
@@ -3,7 +3,7 @@
  * Proxy Helper for Hono.
  */

-import type { HonoRequest } from '../../request'
+import type { RequestHeader } from '../../utils/headers'

 // https://datatracker.ietf.org/doc/html/rfc2616#section-13.5.1
 const hopByHopHeaders = [
@@ -16,16 +16,17 @@ const hopByHopHeaders = [
   'transfer-encoding',
 ]

-interface ProxyRequestInit extends RequestInit {
+interface ProxyRequestInit extends Omit<RequestInit, 'headers'> {
   raw?: Request
+  headers?:
+    | HeadersInit
+    | [string, string][]
+    | Record<RequestHeader, string | undefined>
+    | Record<string, string | undefined>
 }

 interface ProxyFetch {
-  (input: RequestInfo | URL, init?: ProxyRequestInit | HonoRequest): Promise<Response>
-  (
-    input: string | URL | globalThis.Request,
-    init?: ProxyRequestInit | HonoRequest
-  ): Promise<Response>
+  (input: string | URL | Request, init?: ProxyRequestInit): Promise<Response>
 }

 const buildRequestInitFromRequest = (
@@ -72,7 +73,7 @@ const buildRequestInitFromRequest = (
  *   })
  * })
  *
- * app.any('/proxy/:path', (c) => {
+ * app.all('/proxy/:path', (c) => {
  *   return proxy(`http://${originServer}/${c.req.param('path')}`, {
  *     ...c.req, // optional, specify only when forwarding all the request data (including credentials) is necessary.

  *     headers: {
@@ -88,10 +89,14 @@ const buildRequestInitFromRequest = (
 export const proxy: ProxyFetch = async (input, proxyInit) => {
   const { raw, ...requestInit } = proxyInit ?? {}

-  const req = new Request(input, {
-    ...buildRequestInitFromRequest(raw),
-    ...requestInit,
-  })
+  const req = new Request(
+    input,
+    // @ts-expect-error `headers` in `requestInit` is not compatible with HeadersInit
+    {
+      ...buildRequestInitFromRequest(raw),
+      ...requestInit,
+    }
+  )
   req.headers.delete('accept-encoding')

   const res = await fetch(req)
   const res = await fetch(req)

Perhaps you can revise the code patched with this, but it can fix the type error. And the interesting point is using the following types for the headers in ProxyRequestInit:

Record<RequestHeader, string | undefined>

This can be helpful. After merging this PR, we can add X-Forwarded-For and X-Forwarded-Host and other proxy-related headers to RequestHeader.

@usualoma
Copy link
Member Author

@yusukebe Thank you! As you pointed out, the type was not set correctly.
I applied your patch with 832532c.
It also seems like adding X-Forwarded-For and X-Forwarded-Host would be a good idea.

Can the header of the Response object we created be changed?

When I came to think of it, I made the following specification for deletion without thinking much about it, but can we consider this possible?

return proxy(`http://${originServer}/${c.req.param('path')}`, {
  headers: {
    ...c.req.header(), // optional, specify only when forwarding all the request data (including credentials) is necessary.
    'X-Forwarded-For': '127.0.0.1',
    'X-Forwarded-Host': c.req.header('host'),
    Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')
  },
}).then((res) => {
  res.headers.delete('Cookie')
  return res
})

According to MDN, the headers property itself is read-only. However, it does not say whether the headers themselves are immutable.
https://developer.mozilla.org/en-US/docs/Web/API/Response/headers

Also, here, if we try to directly modify the headers of the Response object returned from fetch in Node.js or bun, an error will occur.

> await (async () => { const resp = await fetch('https://google.com'); resp.headers.delete('server'); resp.headers.get('server') })()
Uncaught TypeError: Cannot change headers: headers are immutable
    at Headers.delete (ext:deno_fetch/20_headers.js:336:13)
    at <anonymous>:3:22
    at eventLoopTick (ext:core/01_core.js:175:7)
    at async <anonymous>:1:22
>

However, the Response object created with the new operator does not cause an error and the changes are reflected. The following code produced the same results for Node.js, Deno, bun and Google Chrome.

> (() => { const resp = new Response("test", { headers: { x: "1" } }); console.log(resp.headers.get("x")); resp.headers.delete("x"); return resp.headers.get("x")})();
1
null

If we don't use this behavior, we may need to consider other ways to remove headers. However, it works fine in all the runtimes I've checked, so I think the current PR method is fine. It's also a clean API.

@yusukebe
Copy link
Member

@usualoma Thank you for handling this!

As you said, the headers in the Response are immutable if fetched.

// ❌️ headers are immutable
const res = await fetch('https://google.com')
res.headers.delete('server')
// ⭕️ OK
const res = new Response('http://foo', { headers: { x: '1' } })
res.headers.delete('x')

If the Response returned by proxy is to have the same behavior as the Response of fetch, it should be immutable. But you are right, as the API spec is often confusing and not good for users, including me. So, I think this PR API is good. That's the whole point of creating this proxy helper.

@usualoma
Copy link
Member Author

@yusukebe Thank you for checking. Let's move on with the current content.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Proxying compressed response do not work out of the box
5 participants