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 .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ jobs:

- name: golangci-lint
if: matrix.go == 'stable'
uses: golangci/golangci-lint-action@v7
uses: golangci/golangci-lint-action@v9
with:
version: latest
version: v2.15.0

- name: install goveralls
if: matrix.go == 'stable'
Expand Down
15 changes: 7 additions & 8 deletions CLAUDE.md → AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# CLAUDE.md
# AGENTS.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
This file provides guidance to coding agents working with code in this repository.

## What this is

Expand All @@ -11,18 +11,17 @@ Dependencies are deliberately tiny: only `stretchr/testify` (tests) and `golang.
## Commands

- Test everything: `go test ./...`
- Single test: `go test -run TestName ./...` (e.g. `go test -run TestPing ./...`)
- Single test: `go test -run TestName ./...` (e.g. `go test -run TestMiddleware_Ping ./...`)
- Race + coverage (mirrors CI): `TZ="America/Chicago" go test -timeout=60s -race -covermode=atomic ./...`
- Lint (run from repo root): `golangci-lint run --max-issues-per-linter=0 --max-same-issues=0`

Time-parsing tests (`ParseFromTo`) are timezone-sensitive; CI runs with `TZ=America/Chicago`. Set it locally if a from/to test behaves oddly.

## Architecture

Three packages:
Three public packages and one internal:
- **`rest`** (root) — all middlewares plus JSON/error/file-server helpers.
- **`logger`** — request-logging middleware, split out so it can be wired to any backend via the `logger.Backend` interface (`Logf(format, args...)`). Configured with functional options (`logger.New(logger.Prefix(...), logger.WithBody, ...)`).
- **`realip`** — `realip.Get(r)` extracts the client IP from proxy headers. Used by both `rest.RealIP` and the `logger` package. Only public IPs are accepted from headers.
- **`internal/requestid`**: the request ID that `Trace` keeps in the request context, shared with the `logger` package, which can't import `rest` because `rest` imports it.

### Middleware conventions

Expand All @@ -41,11 +40,11 @@ CSRF protection has **two implementations behind one identical public API**, sel
- `csrf_go125.go` (`//go:build go1.25`) — thin wrapper over stdlib `http.CrossOriginProtection`.
- `csrf.go` (`//go:build !go1.25`) — self-contained equivalent for older Go.

`NewCrossOriginProtection`, `AddTrustedOrigin`, `AddBypassPattern`, `SetDenyHandler`, `Check`, `Handler` must exist with the **same signatures and behavior in both files**. When you change the CSRF API or behavior, edit both files and keep `csrf_test.go` passing under both build tags. go.mod targets go 1.24, so by default the `!go1.25` path compiles unless building with a 1.25 toolchain.
`NewCrossOriginProtection`, `AddTrustedOrigin`, `AddBypassPattern`, `SetDenyHandler`, `Check`, `Handler` must exist with the **same signatures in both files**. When you change the CSRF API or behavior, edit both files and keep `csrf_test.go` passing under both build tags. The toolchain's version selects the file, not go.mod: any 1.25+ toolchain builds `csrf_go125.go`, and only a 1.24 toolchain (the `go.mod` entry of the CI matrix) builds `csrf.go`. The two differ in bypass-pattern syntax and conflict handling: the stdlib takes `http.ServeMux` patterns and panics on a conflicting one, the fallback matches exact paths and `/prefix/` only and accepts repeats. Run the tests with `GOTOOLCHAIN=go1.24.0` too when touching either file.

### Helpers

`rest.go` holds the JSON render/encode/decode helpers (`RenderJSON`, `EncodeJSON`/`DecodeJSON` generics, `RenderJSONWithHTML`) and `ParseFromTo`. `httperrors.go` has `SendErrorJSON`/`NewErrorLogger`. `file_server.go` has `FileServer` (directory listing disabled by design). `benchmarks.go` keeps an in-memory ring of up to 900 per-second data points (15 min) queried via `Stats(duration)`.
`rest.go` holds the JSON render/encode/decode helpers (`RenderJSON`, `EncodeJSON`/`DecodeJSON` generics, `RenderJSONWithHTML`) and `ParseFromTo`. `httperrors.go` has `SendErrorJSON`/`NewErrorLogger`. `file_server.go` has `NewFileServer` with `FsOpt*` options (`FsOptSPA`, `FsOptListing`, `FsOptCustom404`), listing off by default; `FileServer` and `FileServerSPA` are deprecated shortcuts. `benchmarks.go` keeps in memory one data point per second for the last 15 minutes by default (`WithTimeRange` changes it), queried via `Stats(duration)`.

## Conventions

Expand Down
189 changes: 138 additions & 51 deletions README.md

Large diffs are not rendered by default.

34 changes: 15 additions & 19 deletions basic_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,25 +46,24 @@ func BasicAuthWithUserPasswd(user, passwd string) func(http.Handler) http.Handle

// BasicAuthWithBcryptHash middleware requires basic auth and matches user & bcrypt hashed password
func BasicAuthWithBcryptHash(user, hashedPassword string) func(http.Handler) http.Handler {
checkFn := func(reqUser, reqPasswd string) bool {
if reqUser != user {
return false
}
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(reqPasswd))
return err == nil
return BasicAuth(bcryptChecker(user, hashedPassword))
}

// bcryptChecker compares the user in constant time and runs the bcrypt comparison for every request,
// so a wrong user name takes as long to reject as a wrong password and valid names can't be told apart
func bcryptChecker(user, hashedPassword string) func(reqUser, reqPasswd string) bool {
return func(reqUser, reqPasswd string) bool {
matchUser := subtle.ConstantTimeCompare([]byte(user), []byte(reqUser)) == 1
matchPass := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(reqPasswd)) == nil
return matchUser && matchPass
}
return BasicAuth(checkFn)
}

// BasicAuthWithArgon2Hash middleware requires basic auth and matches user & argon2 hashed password
// both hashedPassword and salt must be base64 encoded strings
// Uses Argon2id with parameters: t=1, m=64*1024 KB, p=4 threads
func BasicAuthWithArgon2Hash(user, hashedPassword, salt string) func(http.Handler) http.Handler {
checkFn := func(reqUser, reqPasswd string) bool {
if reqUser != user {
return false
}

saltBytes, err := base64.StdEncoding.DecodeString(salt)
if err != nil {
return false
Expand All @@ -74,8 +73,11 @@ func BasicAuthWithArgon2Hash(user, hashedPassword, salt string) func(http.Handle
return false
}

// the hash is computed for every user name, so a wrong one takes as long to reject as a wrong password
matchUser := subtle.ConstantTimeCompare([]byte(user), []byte(reqUser)) == 1
hash := argon2.IDKey([]byte(reqPasswd), saltBytes, 1, 64*1024, 4, 32)
return subtle.ConstantTimeCompare(hash, storedHashBytes) == 1
matchPass := subtle.ConstantTimeCompare(hash, storedHashBytes) == 1
return matchUser && matchPass
}
return BasicAuth(checkFn)
}
Expand Down Expand Up @@ -116,13 +118,7 @@ func BasicAuthWithPrompt(user, passwd string) func(http.Handler) http.Handler {
// BasicAuthWithBcryptHashAndPrompt middleware requires basic auth and matches user & bcrypt hashed password
// If the user is not authorized, it will prompt for basic auth
func BasicAuthWithBcryptHashAndPrompt(user, hashedPassword string) func(http.Handler) http.Handler {
checkFn := func(reqUser, reqPasswd string) bool {
if reqUser != user {
return false
}
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(reqPasswd))
return err == nil
}
checkFn := bcryptChecker(user, hashedPassword)

return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
Expand Down
35 changes: 35 additions & 0 deletions basic_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,3 +444,38 @@ func TestBasicAuthWithBcryptHashAndPrompt(t *testing.T) {
})
}
}

func TestBasicAuthHashedWrongUserStillHashes(t *testing.T) {
bcryptHash, err := GenerateBcryptHash("good")
require.NoError(t, err)
argonHash, argonSalt, err := GenerateArgon2Hash("good")
require.NoError(t, err)

tbl := []struct {
name string
mw func(http.Handler) http.Handler
status int
}{
{name: "bcrypt", mw: BasicAuthWithBcryptHash("dev", bcryptHash), status: http.StatusForbidden},
{name: "bcrypt with prompt", mw: BasicAuthWithBcryptHashAndPrompt("dev", bcryptHash), status: http.StatusUnauthorized},
{name: "argon2", mw: BasicAuthWithArgon2Hash("dev", argonHash, argonSalt), status: http.StatusForbidden},
}
for _, tt := range tbl {
t.Run(tt.name, func(t *testing.T) {
h := tt.mw(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }))
// a wrong user name must cost a hash comparison too, otherwise the response time tells valid
// user names apart; only a lower bound is checked, as a loaded machine can only make it slower
fastest := time.Duration(1<<63 - 1)
for range 3 {
req := httptest.NewRequest("GET", "/something", http.NoBody)
req.SetBasicAuth("wrong", "good")
rr := httptest.NewRecorder()
st := time.Now()
h.ServeHTTP(rr, req)
fastest = min(fastest, time.Since(st))
assert.Equal(t, tt.status, rr.Code)
}
assert.GreaterOrEqual(t, fastest, time.Millisecond, "wrong user answered without hashing")
})
}
}
3 changes: 2 additions & 1 deletion blackwords.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ func BlackWords(words ...string) func(http.Handler) http.Handler {
}
}

// BlackWordsFn middleware uses func to get the list and doesn't allow some words in the request body
// BlackWordsFn middleware doesn't allow some words in the request body, taking the list from fn.
// fn is called once, when the middleware is created; a list it would return later is not used.
func BlackWordsFn(fn func() []string) func(http.Handler) http.Handler {
return BlackWords(fn()...)
}
6 changes: 3 additions & 3 deletions cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,9 @@ func CORS(opts ...CorsOpt) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
// the CORS headers depend on Origin, and the response without Origin carries none of them,
// so every response, including one for a disallowed origin, has to tell caches to key on it
w.Header().Add("Vary", "Origin")

// no origin header means same-origin or non-browser request
if origin == "" {
Expand All @@ -165,9 +168,6 @@ func CORS(opts ...CorsOpt) func(http.Handler) http.Handler {
return
}

// set Vary header for caching
w.Header().Add("Vary", "Origin")

// set allowed origin
if allowAll && !cfg.AllowCredentials {
w.Header().Set("Access-Control-Allow-Origin", "*")
Expand Down
38 changes: 38 additions & 0 deletions cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -408,3 +408,41 @@ func TestCORS_UnsafeAnyOriginWithCredentials(t *testing.T) {
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Credentials"))
})
}

func TestCORS_VaryOriginOnEveryResponse(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
listed := CORS(CorsAllowedOrigins("https://allowed.com"))
anyWithCredentials := CORS(CorsAllowedOrigins("*"), CorsAllowCredentials(true), CorsUnsafeAnyOriginWithCredentials(true))

tbl := []struct {
name string
mw func(http.Handler) http.Handler
origin string
vary []string
}{
{name: "listed, allowed origin", mw: listed, origin: "https://allowed.com", vary: []string{"Origin"}},
{name: "listed, disallowed origin", mw: listed, origin: "https://evil.com", vary: []string{"Origin"}},
{name: "listed, no origin", mw: listed, origin: "", vary: []string{"Origin"}},
{name: "any with credentials, no origin", mw: anyWithCredentials, origin: "", vary: []string{"Origin"}},
{name: "any with credentials, origin", mw: anyWithCredentials, origin: "https://x.com", vary: []string{"Origin"}},
// with "*" the response to a request with Origin carries Access-Control-Allow-Origin and the one
// without does not, so caches have to key on Origin here too
{name: "any, no origin", mw: CORS(), origin: "", vary: []string{"Origin"}},
{name: "any, origin", mw: CORS(), origin: "https://x.com", vary: []string{"Origin"}},
}
for _, tt := range tbl {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "/test", http.NoBody)
if tt.origin != "" {
req.Header.Set("Origin", tt.origin)
}
w := httptest.NewRecorder()
tt.mw(handler).ServeHTTP(w, req)
resp := w.Result()
defer resp.Body.Close()
assert.Equal(t, tt.vary, resp.Header.Values("Vary"))
})
}
}
7 changes: 4 additions & 3 deletions csrf.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import (
// It validates requests using Sec-Fetch-Site and Origin headers, rejecting cross-origin
// state-changing requests. Safe methods (GET, HEAD, OPTIONS) are always allowed.
//
// For Go 1.25+, this wraps the stdlib http.CrossOriginProtection.
// For earlier versions, it provides an equivalent custom implementation.
// Built with a Go 1.25+ toolchain, this wraps the stdlib http.CrossOriginProtection.
// With an earlier toolchain, it provides a custom implementation with simpler bypass patterns.
type CrossOriginProtection struct {
mu sync.RWMutex
trustedOrigins map[string]bool
Expand Down Expand Up @@ -57,7 +57,8 @@ func (c *CrossOriginProtection) AddTrustedOrigin(origin string) error {
}

// AddBypassPattern adds a URL pattern that should bypass CSRF protection.
// Patterns follow the same syntax as http.ServeMux (e.g., "/api/webhook", "/oauth/").
// A pattern is an exact path ("/api/webhook") or a prefix ending in "/" ("/oauth/"); unlike the Go 1.25+
// implementation, http.ServeMux methods and wildcards are not supported and repeated patterns are accepted.
// Use sparingly and only for endpoints that have alternative authentication.
func (c *CrossOriginProtection) AddBypassPattern(pattern string) {
c.mu.Lock()
Expand Down
46 changes: 6 additions & 40 deletions csrf_go125.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import (
// It validates requests using Sec-Fetch-Site and Origin headers, rejecting cross-origin
// state-changing requests. Safe methods (GET, HEAD, OPTIONS) are always allowed.
//
// For Go 1.25+, this wraps the stdlib http.CrossOriginProtection.
// For earlier versions, it provides an equivalent custom implementation.
// Built with a Go 1.25+ toolchain, this wraps the stdlib http.CrossOriginProtection.
// With an earlier toolchain, it provides a custom implementation with simpler bypass patterns.
type CrossOriginProtection struct {
stdlib *http.CrossOriginProtection
}
Expand Down Expand Up @@ -50,7 +50,8 @@ func (c *CrossOriginProtection) AddTrustedOrigin(origin string) error {
}

// AddBypassPattern adds a URL pattern that should bypass CSRF protection.
// Patterns follow the same syntax as http.ServeMux (e.g., "/api/webhook", "/oauth/").
// Patterns follow the same syntax as http.ServeMux (e.g., "/api/webhook", "/oauth/", "POST /hooks/{id}"),
// and it panics if the pattern conflicts with one already added.
// Use sparingly and only for endpoints that have alternative authentication.
func (c *CrossOriginProtection) AddBypassPattern(pattern string) {
c.stdlib.AddInsecureBypassPattern(pattern)
Expand All @@ -64,48 +65,13 @@ func (c *CrossOriginProtection) SetDenyHandler(h http.Handler) {

// Check validates a request against CSRF protection rules.
// Returns nil if the request is allowed, or an error describing why it was rejected.
// It only reports the result; the deny handler is used by Handler alone.
func (c *CrossOriginProtection) Check(r *http.Request) error {
// the stdlib Check method panics or returns void, so we use our own check logic
// by creating a test handler and seeing if it gets called

// safe methods are always allowed
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
return nil
}

// use a test to determine if request would be allowed
allowed := false
testHandler := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
allowed = true
})

// create a response recorder to capture the result
rec := &discardResponseWriter{}
c.stdlib.Handler(testHandler).ServeHTTP(rec, r)

if !allowed {
return fmt.Errorf("cross-origin request blocked by CSRF protection")
}
return nil
return c.stdlib.Check(r)
}

// Handler wraps an http.Handler with CSRF protection.
// Rejected requests receive a 403 Forbidden response (or custom deny handler).
func (c *CrossOriginProtection) Handler(h http.Handler) http.Handler {
return c.stdlib.Handler(h)
}

// discardResponseWriter is a minimal ResponseWriter for testing.
type discardResponseWriter struct {
header http.Header
}

func (d *discardResponseWriter) Header() http.Header {
if d.header == nil {
d.header = make(http.Header)
}
return d.header
}
func (d *discardResponseWriter) Write(b []byte) (int, error) { return len(b), nil }
func (d *discardResponseWriter) WriteHeader(_ int) {}
15 changes: 15 additions & 0 deletions csrf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,3 +322,18 @@ func TestCSRF_Integration(t *testing.T) {
assert.Equal(t, http.StatusOK, resp.StatusCode)
})
}

func TestCSRF_CheckDoesNotCallDenyHandler(t *testing.T) {
protection := NewCrossOriginProtection()
denyCalls := 0
protection.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
denyCalls++
w.WriteHeader(http.StatusTeapot)
}))

req := httptest.NewRequest(http.MethodPost, "/api/data", http.NoBody)
req.Header.Set("Sec-Fetch-Site", "cross-site")

require.Error(t, protection.Check(req))
assert.Equal(t, 0, denyCalls, "Check must only report, the deny handler belongs to Handler")
}
17 changes: 12 additions & 5 deletions httperrors.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package rest
import (
"errors"
"fmt"
"net"
"net/http"
"net/url"
"runtime"
Expand Down Expand Up @@ -50,18 +51,24 @@ func errDetailsMsg(r *http.Request, code int, err error, msg string) string {

srcFileInfo := ""
if pc, file, line, ok := runtime.Caller(2); ok {
fnameElems := strings.Split(file, "/")
funcNameElems := strings.Split(runtime.FuncForPC(pc).Name(), "/")
srcFileInfo = fmt.Sprintf(" [caused by %s:%d %s]", strings.Join(fnameElems[len(fnameElems)-3:], "/"),
line, funcNameElems[len(funcNameElems)-1])
srcFileInfo = fmt.Sprintf(" [caused by %s:%d %s]", shortCallerPath(file), line, funcNameElems[len(funcNameElems)-1])
}

// RemoteAddr is host:port as set by the server, or a bare address once RealIP has rewritten it
remoteIP := r.RemoteAddr
if pos := strings.Index(remoteIP, ":"); pos >= 0 {
remoteIP = remoteIP[:pos]
if host, _, splitErr := net.SplitHostPort(remoteIP); splitErr == nil {
remoteIP = host
}
if err == nil {
err = errors.New("no error")
}
return fmt.Sprintf("%s - %v - %d - %s - %s%s", msg, err, code, remoteIP, q, srcFileInfo)
}

// shortCallerPath keeps the last three elements of the caller's file path, or all of them if there are fewer,
// as for a file in the root of a single-element module built with -trimpath
func shortCallerPath(file string) string {
elems := strings.Split(file, "/")
return strings.Join(elems[max(0, len(elems)-3):], "/")
}
Loading
Loading