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

Fix: incorrect scheme on proxy.Do (#1762) #1765

Merged
merged 1 commit into from Feb 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions middleware/proxy/proxy.go
@@ -1,6 +1,7 @@
package proxy

import (
"bytes"
"crypto/tls"
"fmt"
"net/url"
Expand Down Expand Up @@ -121,10 +122,25 @@ func Do(c *fiber.Ctx, addr string) error {
req := c.Request()
res := c.Response()
req.SetRequestURI(addr)
// NOTE: if req.isTLS is true, SetRequestURI keeps the scheme as https.
// issue reference:
// https://github.com/gofiber/fiber/issues/1762
if scheme := getScheme(utils.UnsafeBytes(addr)); len(scheme) > 0 {
req.URI().SetSchemeBytes(scheme)
}

req.Header.Del(fiber.HeaderConnection)
if err := client.Do(req, res); err != nil {
return err
}
res.Header.Del(fiber.HeaderConnection)
return nil
}

func getScheme(uri []byte) []byte {
i := bytes.IndexByte(uri, '/')
if i < 1 || uri[i-1] != ':' || i == len(uri)-1 || uri[i+1] != '/' {
return nil
}
return uri[:i-1]
}
34 changes: 34 additions & 0 deletions middleware/proxy/proxy_test.go
Expand Up @@ -122,6 +122,40 @@ func Test_Proxy_Balancer_WithTlsConfig(t *testing.T) {
utils.AssertEqual(t, "tls balancer", body)
}

// go test -run Test_Proxy_Forward_WithTlsConfig_To_Http
func Test_Proxy_Forward_WithTlsConfig_To_Http(t *testing.T) {
t.Parallel()

_, targetAddr := createProxyTestServer(func(c *fiber.Ctx) error {
return c.SendString("hello from target")
}, t)

proxyServerTLSConf, _, err := tlstest.GetTLSConfigs()
utils.AssertEqual(t, nil, err)

proxyServerLn, err := net.Listen(fiber.NetworkTCP4, "127.0.0.1:0")
utils.AssertEqual(t, nil, err)

proxyServerLn = tls.NewListener(proxyServerLn, proxyServerTLSConf)

app := fiber.New(fiber.Config{DisableStartupMessage: true})

proxyAddr := proxyServerLn.Addr().String()

app.Use(Forward("http://" + targetAddr))

go func() { utils.AssertEqual(t, nil, app.Listener(proxyServerLn)) }()

code, body, errs := fiber.Get("https://" + proxyAddr).
InsecureSkipVerify().
Timeout(5 * time.Second).
String()

utils.AssertEqual(t, 0, len(errs))
utils.AssertEqual(t, fiber.StatusOK, code)
utils.AssertEqual(t, "hello from target", body)
}

// go test -run Test_Proxy_Forward
func Test_Proxy_Forward(t *testing.T) {
t.Parallel()
Expand Down