Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions internal/phpheaders/phpheaders.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ var CommonRequestHeaders = map[string]string{
// Cache up to 256 uncommon headers
// This is ~2.5x faster than converting the header each time
var (
headerKeyCache = otter.Must[string, string](&otter.Options[string, string]{MaximumSize: 256})
headerNameReplacer = strings.NewReplacer(" ", "_", "-", "_")
headerKeyCache = otter.Must(&otter.Options[string, string]{MaximumSize: 256})
headerNameReplacer = strings.NewReplacer("-", "_")
loader = otter.LoaderFunc[string, string](func(_ context.Context, key string) (string, error) {
return "HTTP_" + headerNameReplacer.Replace(strings.ToUpper(key)) + "\x00", nil
})
Expand Down
27 changes: 27 additions & 0 deletions internal/phpheaders/phpheaders_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package phpheaders

import (
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestAllCommonHeadersAreCorrect(t *testing.T) {
Expand All @@ -20,3 +25,25 @@ func TestAllCommonHeadersAreCorrect(t *testing.T) {
assert.Contains(t, fakeRequest.Header, header, "header is not correctly capitalized: "+header)
}
}

// Go's net/http server rejects header names containing spaces with a 400 response
// before the request reaches the handler, so headerNameReplacer does not need to
// translate spaces to underscores.
func TestHeaderWithSpaceIsRejectedByNetHTTP(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("handler should not be reached, got headers: %v", r.Header)
}))
t.Cleanup(ts.Close)

conn, err := net.Dial("tcp", strings.TrimPrefix(ts.URL, "http://"))
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, conn.Close()) })

_, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: localhost\r\nBad Header: x\r\nConnection: close\r\n\r\n"))
require.NoError(t, err)

resp, err := io.ReadAll(conn)
require.NoError(t, err)
Comment on lines +38 to +46
assert.Contains(t, string(resp), "400 Bad Request")
assert.Contains(t, string(resp), "invalid header name")
}
Loading