Repository navigation
KVolt v2.5.0 – Production-Readiness Release
Production-readiness release: a full security and reliability review plus load testing with the race detector (about 17 million requests, 2 hours). Fixes about 25 bugs, including routes returning 404 for valid paths, an open redirect, a data race in Timeout, and lost jobs in the Redis queue. Adds SetLogFunc, BindError, and a CI coverage gate. Contains behaviour changes listed under "Changed (breaking)".
Changed (breaking)
pkg/validator:requirednow rejects the zero value of numbers, booleans, structs (time.Time) and arrays, not only empty strings, slices and maps. An omitted JSON field decodes to the zero value and used to pass. A non-nil pointer counts as present, so use*int/*boolwhere0orfalseis a valid value that must still be sent.- Router: An empty path segment no longer matches a parameter.
/users//postsand/items/no longer reach/users/:id/postsand/items/:idwithid == ""; they answer 404. HEADrequests: AGETroute now answersHEAD(same handler, body discarded bynet/http) unless aHEADroute is registered for the path. These previously answered 405, which broke load-balancer health checks that useHEAD. TheAllowheader listsHEADwhereverGETexists.pkg/swagger: The docs page loads a pinned Scalar release (@scalar/api-reference@1.78.1) with a Subresource Integrity hash instead of the latest version from the CDN, so a change on the CDN cannot alter the page.Config.ScriptURL/Config.ScriptIntegrityoverride it.pkg/test:Request.Dofails the test when theTesterhas no engine. It used to returnnil, which turned every followingExpect*into a no-op and let the test pass without sending a request.
Security
context.Context.Redirect: Rejects every ASCII control character in the location. Browsers strip tab / CR / LF while parsing a URL, so/<tab>/evil.examplewas followed as the protocol-relative//evil.example(open redirect). The location is now trimmed before validation and the trimmed value is what is sent.RedirectURLrejects control characters too.
Added
context.BindError: Marks an error caused by request content.Bind,BindJSON,BindQuery,BindForm,BindURIandBindHeaderreturn it for bad input.Error()returns the original text and the original error stays reachable througherrors.As/errors.Is; a direct type assertion on the returned error (err.(*json.SyntaxError)) no longer matches and should useerrors.As.context.Context.Fork/Join: For middleware that runs the rest of the chain on another goroutine and may stop waiting for it.Forkreturns an independent, never-pooled copy of the Context;Joincopies its outcome back once it has finished.kvolt.SetLogFunc: Sends the framework's own status messages (server started / shutting down, gRPC server and interceptors, queue workers, API docs notice) to a function of your choice instead of standard output, so they can go throughslog,zapor any structured logger. Default output is unchanged.middleware.LoggerConfig.Output: Writes the access log to anyio.Writerinstead of standard output.redislimit.Config.FailOpen: Lets requests through when Redis cannot be reached. The default still answers 500.swagger.Config.ScriptURL/ScriptIntegrity: Override the Scalar script loaded by the docs page, to use another version or a self-hosted copy.- CI coverage gate: The Linux test job fails when library coverage (examples, benchmarks and the CLI excluded) drops below 90%. It is 93.3% at the time of writing.
pkg/test,pkg/testkit: Assertion failures are reported at the calling test's line (t.Helper), andtestkitfails the test when a request body cannot be encoded..gitattributes: Go sources are checked out with LF on every platform, sogofmtandgolangci-lintno longer flag every file on Windows checkouts withcore.autocrlf=true. Existing Windows checkouts pick this up on a fresh clone orgit add --renormalize ..middleware.IdempotencyConfig.MaxResponseBytes: Caps the response body kept for replay (default 1MB, negative for no limit). Larger responses are sent normally but not stored.
Fixed
Found by running a real server under concurrent load with the race detector (about 350,000 requests per run):
middleware.Timeout: A handler that ignored the deadline kept sharing the requestContextwith the middleware unwinding on the request goroutine. That was a data race on the Context, and with any writer-wrapping middleware outsideTimeout(Gzip,Idempotency) the late handler wrote to the realResponseWriterafter the request had been answered. The rest of the chain now runs on a private copy of the Context (Context.Fork) with a writer that discards late output; the outcome is copied back (Context.Join) only when the handler finishes in time. The request Context is no longer marked detached on timeout, since nothing else holds it.middleware.Timeout: Headers set by a handler that wrote no body (c.Status(204)) are no longer lost, and upstream middleware sees the request's own context afterTimeoutreturns rather than the cancelled timeout context.middleware.Gzip: A panic was answered200instead of500wheneverGzipwas in the chain: it committed the headers while the panic unwound, beforeRecoverycould respond.Gzipno longer commits anything when the handler wrote nothing.middleware.Gzip: A streamed response (SSE) was corrupted when a chunk larger than the gzip threshold followed an earlier flush: the stream switched to gzip after the headers had gone out uncompressed. A flush before the threshold now keeps the whole response uncompressed. A pendingc.Status()is also no longer written twice.middleware.Idempotency: Under concurrent requests with the same key the handler could run twice. A request that missed the store, then took the gate just after the first request had stored its result and released it, ran the handler again. The gate holder now checks the store once more before running.
Found by review:
- Router: A static route no longer hides a param or catch-all route that shares a prefix with the request. With
/user/newand/user/:idregistered,/user/next,/user/nand/user/new/postsreturned 404; so did/a/b/cwith/a/b/dand/a/:x/c. Lookup now falls back to the wildcard when the static branch does not lead to a handler. Static routes still win when both match. context.Bindand the otherBind*methods: A handler that returns the bind error now answers400 invalid_requestfor malformed JSON, an empty body, a wrong value type or an unparseable parameter, and422 validation_failed(withfield/ruledetails) for a failedvalidaterule. These previously answered500and were logged as handler errors. An oversized body is still413.pkg/session:MaxAgeis now enforced across restarts and across instances sharing a store. The creation time was kept only in process memory, so after a restart (or on another instance) a session lived for as long as it stayed active. It is now stored beside the session under<token>:created, with a TTL ofMaxAgethat activity does not extend. Sessions that have no marker — created before this change withMaxAgeset, or whileMaxAgewas 0 — are rejected onceMaxAgeis on, so those users sign in again once after upgrading.middleware/redislimit: The default key groups IPv6 clients by /64, matchingmiddleware.Limiter. Limiting per IPv6 address let a client get a fresh bucket for every address it rotated through.kvolt new/kvolt docker: The scaffoldedmain.goexits 0 after a graceful shutdown;log.Fatal(app.Run(addr))exited 1 on every SIGTERM becauseRunreturnsnil. The scaffold now also writes a.gitignorefor.envand serves API docs only whenDEBUG=true. The generated Dockerfile runs as a non-root user, copiesgo.sumbefore downloading modules, and usesalpine:3.22.pkg/cache/redis:Touchwith no TTL on a key that already has no expiry returnedErrKeyNotFound, so a session created with a zero TTL could never be read back from Redis.middleware/prometheus: Themethodlabel is limited to the standard HTTP methods; anything else is recorded asOTHER. A client could previously create an unlimited number of time series by sending made-up methods.middleware.Idempotency: A replay no longer duplicates headers set by middleware that runs before it (CORS,RequestID,Secure). Only headers the handler added or changed are stored, and they replace rather than append on replay. Previously a replayed response carried twoAccess-Control-Allow-Originvalues, which browsers reject.middleware.Idempotency:408,425and429responses are no longer cached, so a retry with the same key runs the handler again.pkg/queue/redis: Promoting delayed jobs, reclaiming expired jobs and reclaiming orphans now run as atomic Lua scripts, and acknowledgement runs in one transaction. A crash between the individual commands could previously lose a retrying job or redeliver a finished one. Backlogs are moved in batches of 100.middleware.Logger: Thejsonformat now emits valid JSON for any request path. Control bytes and invalid UTF-8 were written with Go escapes (\x01) that JSON parsers reject.middleware.Timeout: A handler panic after the deadline is now logged. It cannot reachRecoveryonce the 504 has been sent and was previously dropped silently.middleware.CORS:Vary: Originis set on every response when an allow-list is configured, including responses to refused origins, so shared caches do not serve one origin's response to another.middleware.Gzip: Responses that already carry aContent-Encodingare no longer compressed a second time.Accept-Encodingparsing now readsqvalues numerically (gzip;q=0.05is accepted), matches thegzipcoding exactly, and lets an explicitgzip;q=0override*.
Docs
- README: Replaced the "100% test coverage gates" claim with what CI actually runs, including the new 90% gate.
- README and examples: The quick start and the
full_app/tenant_appexamples no longer wrapapp.Runinlog.Fatal, which exited 1 after a graceful shutdown. - SECURITY.md: Supported versions updated to 2.4.x / 2.3.x; added hardening notes for redirects and session
MaxAge.