Skip to content

Fix middleware defects, close Profiler by default, correct the README - #59

Open
paskal wants to merge 3 commits into
masterfrom
audit-fixes
Open

paskal wants to merge 3 commits into
masterfrom
audit-fixes

Conversation

@paskal

@paskal paskal commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Previously, error logging could panic, the hashed BasicAuth variants exposed valid user names through response timing, Profiler() served the process command line to every source, and several README sections described headers, fields and methods the package does not have. After this change, these defects are fixed, the behaviours below change, and the README documents the corrected behaviour and the configuration it left out.

Fixes:

  • Security: BasicAuthWithBcryptHash, BasicAuthWithBcryptHashAndPrompt and BasicAuthWithArgon2Hash returned before verifying the password when the user name was wrong, so the response time told valid user names apart. They now verify the password whatever user name is supplied, and compare the user name with subtle.ConstantTimeCompare.
  • SendErrorJSON and ErrorLogger.Log no longer panic when the caller's file path has fewer than three elements, as for a file in the root of a single-element module built with -trimpath, and log an IPv6 client address whole instead of [2001.
  • Profiler serves every profile under /pprof/{name}, including allocs, mutex and profiles the application registers; previously any profile without its own route returned the pprof index page.
  • CrossOriginProtection.Check built with Go 1.25 or newer no longer calls the custom deny handler. It returns the result of the stdlib Check, so its error text is now the stdlib's, such as "cross-origin request detected from Sec-Fetch-Site header".
  • Throttle with a negative limit no longer panics; any limit of 0 or less disables it, as the handler already assumed.
  • CORS adds Vary: Origin to every response, including responses for a disallowed origin and requests without Origin. Previously only an allowed origin got it, so a shared cache could hand a response stored without CORS headers to an allowed origin.
  • NoCache sends Expires with the GMT suffix that HTTP dates require, and its doc comment lists the headers it actually sets and removes.

Behaviour changes:

  • Security: Profiler() called without addresses rejects every request with 403, as Metrics() does. Previously it served /pprof/cmdline and /vars, which carry the command line, to every source. A caller that wants it open lists every source explicitly: Profiler("0.0.0.0/0", "::/0").
  • The default logger format includes request IDs generated by Trace. It takes the first non-empty ID from the request header, the Trace context value and the response header, in that order, and replaces line breaks in it with spaces.
  • logger.AnonymizeIP masks native IPv6 addresses to their /48 network and IPv4-mapped addresses to /24 in every spelling, including hexadecimal forms such as ::ffff:808:404; its output drops ports, brackets and zones. Previously native IPv6 and hexadecimal IPv4-mapped addresses were returned unchanged. Plain IPv4 output is the same as before.
  • Handlers behind the logger see http.Flusher and http.Hijacker only when the writer beneath supports them, as with Gzip. Under Timeout these assertions now fail instead of returning a Flush that does nothing, and http.ResponseController reaches the writer beneath through Unwrap and receives flush errors.
  • Headers splits each entry on its first colon, so a value containing colons, such as X-Upstream:http://10.0.0.1:8080, is set instead of silently dropped.

Documentation:

  • Security: the RealIP section now explains that the headers are read from any peer and that the proxy must overwrite all three of X-Real-IP, CF-Connecting-IP and X-Forwarded-For, since a client-supplied header the proxy leaves in place can spoof the source address, including for OnlyFrom.
  • The README examples that did not compile (Benchmarks, CSRF, Profiler) are corrected, the documented headers, status codes and log fields match the code, and the missing helpers and options are documented. CLAUDE.md is renamed to AGENTS.md.
  • CI moves from golangci-lint latest with golangci-lint-action v7 to golangci-lint v2.15.0 with golangci-lint-action v9.

Regression tests: TestShortCallerPath, TestErrorDetailsMsgRemoteAddr, TestProfiler_AllocsAndMutex, TestProfiler_AnyNamedProfile, TestBasicAuthHashedWrongUserStillHashes, TestCSRF_CheckDoesNotCallDenyHandler, TestThrottleNegativeLimit, TestCORS_VaryOriginOnEveryResponse, TestNoCache, TestProfiler_NoAddressesDeniesAll, TestProfiler_NoAddressesInvalidRemote, TestTraceIDLogged, TestLogger_TraceIDOnOneLine, TestAnonymizeIP, TestLogger_WriterCapabilities, TestLogger_WriterPassesCallsThrough, TestLogger_ResponseController, TestLogger_ResponseControllerFlushError and TestHeadersValueWithColon. Each fails without its fix.

Validation: race tests on Go 1.27 and on Go 1.24.0, which builds the pre-1.25 CSRF implementation; golangci-lint v2.15.0 with no issues; statement coverage unchanged from master at 97.6%; the README code blocks compile against this branch.

Please publish a release after merging. The Profiler() default is a breaking change: callers must now pass the source addresses they allow. remark42 does not call Profiler.

…aders

SendErrorJSON and ErrorLogger.Log cut the caller's path to its last
three elements without checking the length, so a caller file with a
shorter path, as in the root of a single-element module built with
-trimpath, panicked before the error response was written. The remote
address was cut at the first colon, which logged an IPv6 client as
"[2001"; it is now split with net.SplitHostPort, and a bare address
left by RealIP is logged whole.

Profiler routed only a fixed list of profile names, and pprof.Index
resolves names only under /debug/pprof/, so /pprof/allocs, /pprof/mutex
and any profile the application registers returned the index page.
Every /pprof/{name} is now served with pprof.Handler(name).

The bcrypt and Argon2 BasicAuth variants compared the user name with !=
and returned before verifying the password, so a wrong user name was
rejected in about a microsecond and a valid one took a full hash, which
told valid names apart. They now verify the password whatever user name
is supplied and compare the name with subtle.ConstantTimeCompare.

CrossOriginProtection.Check ran the stdlib handler to find out whether
a request passes, which called a custom deny handler on every rejected
Check. It now returns the stdlib Check result.

Throttle with a negative limit panicked when the channel was created,
although the handler treats a limit of 0 or less as no limit.

CORS added Vary: Origin only to responses for an allowed origin, so a
shared cache could store the response for a disallowed origin or one
without Origin, which carries no CORS headers, and hand it to an
allowed origin. Every response now carries it.

NoCache sent Expires with a UTC suffix, and HTTP dates must end in GMT;
its doc comment now lists the headers it actually sets and removes.
Profiler() without addresses served /pprof/cmdline and /vars to every
source, because OnlyFrom with an empty list lets everything through,
while Metrics() without addresses rejects every request. Profiler now
does the same; Profiler("0.0.0.0/0", "::/0") serves every source on
purpose.

The logger read X-Request-ID from the request only, so an ID that Trace
generated never reached the log line, whichever side of the logger
Trace was on. It now falls back from the request header to the Trace
context value and then the response header, replacing line breaks with
spaces.

AnonymizeIP left native IPv6 and hexadecimal IPv4-mapped addresses
unchanged. It now masks native IPv6 to /48 and IPv4-mapped addresses to
/24, removing ports, brackets and zones from the output.

The logger's response writer always offered Flush and Hijack and had no
Unwrap, so under Timeout a handler got an http.Flusher whose Flush did
nothing, and http.ResponseController could not reach the server's
writer. It now offers each interface only when the writer beneath does,
as Gzip does, unwraps, and reports a failed flush through FlushError.

Headers split each entry on every colon and dropped an entry whose
value contained one, such as a URL. It now splits on the first colon.
The README named wrong headers, status codes and log fields, and some
of its examples did not compile. It also left out public helpers and
options, and that RealIP and OnlyFrom trust proxy headers from any
peer, so a proxy has to overwrite all of them.

The agent instructions move to AGENTS.md, with the CSRF note and the
test commands corrected.

CI moves to golangci-lint v2.15.0 with golangci-lint-action v9.
@paskal
paskal requested a review from umputun as a code owner November 27, 2026 20:38
@coveralls

Copy link
Copy Markdown

Coverage Report for CI Build 46064956569

Coverage increased (+0.2%) to 97.053%

Details

  • Coverage increased (+0.2%) from the base build.
  • Patch coverage: 92 of 92 lines across 10 files are fully covered (100%).
  • No coverage regressions found.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 1493
Covered Lines: 1449
Line Coverage: 97.05%
Coverage Strength: 42.4 hits per line

💛 - Coveralls

@paskal
paskal requested a balanced review from Copilot November 27, 2026 21:20

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants