ctx: simplify Protocol() (#2217)

* ctx: simplify Protocol()

* ctx: also mention "X-Url-Scheme" header in Protocol()

* ctx: use the same warning comment about enabling Config.EnableTrustedProxyCheck everywhere
pull/2222/head
leonklingele 2022-11-14 08:32:48 +01:00 committed by GitHub
parent b288a9f54e
commit 235cd9df82
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 13 additions and 15 deletions

26
ctx.go
View File

@ -1040,28 +1040,25 @@ func (c *Ctx) Path(override ...string) string {
} }
// Protocol contains the request protocol string: http or https for TLS requests. // Protocol contains the request protocol string: http or https for TLS requests.
// Use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy. // Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
func (c *Ctx) Protocol() string { func (c *Ctx) Protocol() string {
if c.fasthttp.IsTLS() { if c.fasthttp.IsTLS() {
return "https" return "https"
} }
scheme := "http"
if !c.IsProxyTrusted() { if !c.IsProxyTrusted() {
return scheme return "http"
} }
scheme := "http"
c.fasthttp.Request.Header.VisitAll(func(key, val []byte) { c.fasthttp.Request.Header.VisitAll(func(key, val []byte) {
if len(key) < 12 { if len(key) < 12 {
return // X-Forwarded- return // Neither "X-Forwarded-" nor "X-Url-Scheme"
} else if bytes.HasPrefix(key, []byte("X-Forwarded-")) {
v := c.app.getString(val)
if bytes.Equal(key, []byte(HeaderXForwardedProto)) {
commaPos := strings.Index(v, ",")
if commaPos != -1 {
scheme = v[:commaPos]
} else {
scheme = v
} }
} else if bytes.Equal(key, []byte(HeaderXForwardedProtocol)) { switch {
case bytes.HasPrefix(key, []byte("X-Forwarded-")):
if bytes.Equal(key, []byte(HeaderXForwardedProto)) ||
bytes.Equal(key, []byte(HeaderXForwardedProtocol)) {
v := c.app.getString(val)
commaPos := strings.Index(v, ",") commaPos := strings.Index(v, ",")
if commaPos != -1 { if commaPos != -1 {
scheme = v[:commaPos] scheme = v[:commaPos]
@ -1071,7 +1068,8 @@ func (c *Ctx) Protocol() string {
} else if bytes.Equal(key, []byte(HeaderXForwardedSsl)) && bytes.Equal(val, []byte("on")) { } else if bytes.Equal(key, []byte(HeaderXForwardedSsl)) && bytes.Equal(val, []byte("on")) {
scheme = "https" scheme = "https"
} }
} else if bytes.Equal(key, []byte(HeaderXUrlScheme)) {
case bytes.Equal(key, []byte(HeaderXUrlScheme)):
scheme = c.app.getString(val) scheme = c.app.getString(val)
} }
}) })