package csrf
import (
"net/http"
"testing"
)
// nullWriter is a ResponseWriter that keeps nothing. httptest.NewRecorder grows
// a buffer and a header map per request, and this measurement is of the guard
// rather than of the recorder.
type nullWriter struct{ header http.Header }
func (w *nullWriter) Header() http.Header { return w.header }
func (w *nullWriter) Write(b []byte) (int, error) { return len(b), nil }
func (w *nullWriter) WriteHeader(int) {}
// The sink keeps a benchmarked predicate from being discarded as dead code.
var sinkBool bool
// BenchmarkRequire measures the middleware as it is installed — in front of the
// whole router, on every request, so the safe-method case below is what the
// overwhelming majority of an instance's traffic pays.
//
// The four cases are the four paths through claimMatches: a method that is
// exempt without looking at a header, a POST that names us in Origin, a POST
// that only carries a Referer (which is one more Get and one more parse), and a
// POST from somewhere else, which reaches the deny handler.
func BenchmarkRequire(b *testing.B) {
// A handler that does nothing: what is measured is the chain above it.
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
guarded := Require(selfOrigin, nil)(next)
cases := []struct {
name string
req *http.Request
}{
{"safe_method", request(http.MethodGet, nil)},
{"origin_match", request(http.MethodPost, map[string]string{"Origin": selfOrigin})},
{"referer_only", request(http.MethodPost, map[string]string{
"Referer": selfOrigin + "/settings/tokens",
})},
{"denied", request(http.MethodPost, map[string]string{"Origin": "https://evil.example.net"})},
}
for _, c := range cases {
b.Run(c.name, func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
// A fresh header map per iteration: the deny path writes into
// it, and reusing one would measure a second write to a map
// that already has the key.
guarded.ServeHTTP(&nullWriter{header: make(http.Header, 4)}, c.req)
}
})
}
}
// BenchmarkSameOrigin is the exported predicate, and it is here to be read next
// to BenchmarkRequire: the middleware parses selfOrigin once at construction
// and this one parses it again on every call. That difference is the argument
// the package comment makes for preferring Require, in nanoseconds.
func BenchmarkSameOrigin(b *testing.B) {
r := request(http.MethodPost, map[string]string{"Origin": selfOrigin})
b.ReportAllocs()
for b.Loop() {
sinkBool = SameOrigin(r, selfOrigin)
}
}
// BenchmarkSafeMethod is the first thing every request meets. It is a switch,
// so the number is expected to be uninteresting — which is the point: if it
// ever stops being uninteresting, something grew a map or a string compare on
// the path in front of the whole router.
func BenchmarkSafeMethod(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
sinkBool = SafeMethod(http.MethodGet)
}
}