valyala / fasthttp

Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
MIT License
21.94k stars 1.76k forks source link

Issue with using malformed Header #1548

Closed jayant42 closed 1 year ago

jayant42 commented 1 year ago

The application doesn't work when a malformed header is passed

Header - Host:https://config.test.com

curl -k -H "User-Agent:Mozilla/5.0 (SMART-TV; Linux; Tizen 5.5) AppleWebKit/538.1 (KHTML, like Gecko) Version/5.5 NativeTVAds Safari/538.1" -H "Content-Type:application/json; charset=utf-8" -H "Content-Length:0" -H "Accept:application/json" -H "Host:https://config.test.com" -H "Cache-Control:no-cache" -H "Accept-Encoding:gzip, deflate" -H "SmartTVClient:OTN-FW/T-NKMUABC-0913.21+T-INFOLINK/T-INFOLINK2020-1010" "http://105.160.6.60:51550/"

erikdubbelboer commented 1 year ago

What happens and what would you expect to happen?

jayant42 commented 1 year ago

if a request comes with the wrong Host Header like Host:https://config.test.com/ there should be a way to tell the server to ignore the Host header completely. As of now the Server return 400 Bad request.

I tried creating a middleware handler wrapper to manipulate the Host header but it doesn't work in the actual environment.

func headerMiddleware(next fasthttp.RequestHandler) fasthttp.RequestHandler {
    return func(ctx *fasthttp.RequestCtx) {
        host := ctx.Request.Header.Peek("Host")
        hostString := strings.ToLower(string(host))
        stringToReplace := "https://"

        //if string starts with http not https
        if !strings.HasPrefix(hostString, stringToReplace) {
            stringToReplace = "http://"
        }
        newHost := strings.ReplaceAll(string(host), stringToReplace, "")

        if newHost != hostString {
            ctx.Request.Header.SetHost(newHost) 
        }
        next(ctx)
    }
}

The correct header format would be config.test.com

erikdubbelboer commented 1 year ago

I'm sorry but I don't think we want to support this. We have to draw the line somewhere at handling malformed requests vs returning 400 Bad Request. In this case net/http also returns a 400 Bad Request instead of handling the request so we're going to keep that behavior as well. What you should do is make sure your clients are talking proper HTTP. A request with a host header like that is a Bad Request according to the HTTP spec.

jayant42 commented 1 year ago

@erikdubbelboer Can you please suggest a workaround that I can implement for this? Maybe a custom listener.

erikdubbelboer commented 1 year ago

I would fix the client. It doesn't make sense that a client isn't sending correct HTTP request. The client must be doing something really weird to cause that that should be fixed.