Documentation
¶
Overview ¶
Package middleware holds the HTTP middleware that no module owns: request IDs, the access log, panic recovery, the management body limit, vendor media type normalisation, trailing-slash collection paths, a HEAD answered through its GET route, and the error handler of the generated strict servers.
Role ¶
platform layer, httpkit/middleware: the request handling around every route. Each decision that belongs to an ecosystem or to the server's configuration arrives as a hook: AccessLog and RecoverPanic log a path through a redactor, NormalizeContentType leaves alone the requests a keep predicate accepts, CollectionSlash rewrites the paths of a map, and HeadAsGet answers a HEAD through the GET routes its predicate accepts. Error responses take their profile from the rules on the request context (httpkit.ErrorProfile), so no middleware here names a path prefix.
Inputs ¶
- Driving: the server's router, which installs RequestID, RecoverPanic, AccessLog, NormalizeContentType, CollectionSlash and HeadAsGet on every request, BodyLimit on its JSON management groups, and BindingError as the request and response error handler of each generated strict server.
- Hooks: the redactor of AccessLog and RecoverPanic, the keep predicate of NormalizeContentType, the path map of CollectionSlash and the served and runs-the-GET predicates of HeadAsGet.
- The request context: the error profile rules (httpkit.ErrorProfiles) and the slots AccessLog gives its handlers (httpkit.NoteCause and httpkit.NoteUser).
- Driven: a *slog.Logger, the only thing it writes besides the response.
Outputs ¶
- RequestID and RequestIDHeader, AccessLog, RecoverPanic, BodyLimit and BodyTooLarge, NormalizeContentType, BindingError, CollectionSlash, HeadAsGet and HeadLengthUnknown.
Invariants ¶
- AccessLog writes one line per request with its method, redacted path, status, bytes, duration and request ID; a request that authenticated names its user, never the credential, and one whose handler noted a cause logs at ERROR with it. A response its handler aborted with http.ErrAbortHandler, as a streamed list does when its store fails after the first byte, is logged too, at ERROR with "aborted":true, before the panic goes on to net/http.
- A panic answers 500 "internal error" in the request's profile and is logged; http.ErrAbortHandler is re-raised, as net/http expects.
- A body over BodyLimit's limit answers 413 with BodyTooLarge's text, whether its length was declared or not.
- A HEAD that HeadAsGet answers sends its GET's status and header fields, with the length of the body it drops, and no body; every middleware between Enter and Route sees it as the GET, and the handler as a HEAD unless RunsGet names its route. A handler that sees the HEAD and skips a streamed body sends no length through HeadLengthUnknown.
- It imports no module, as the platform layer must not.
References ¶
- Decision 0002: docs/research/decisions/0002-spec-first-flat-crud-handwritten-item-paths.md (the error response profiles of the strict servers' errors, and a HEAD of a generated GET).
- Decision 0016: docs/research/decisions/0016-observability-and-health.md (request IDs, and the access log line that names the user, never the credential).
- Decision 0044: docs/research/decisions/0044-modular-monolith-migration.md ("Dependency rules": the platform imports no module).
- Target layout: docs/research/architecture-options/5-modular-monolith.md, lines 158 to 163 (platform/httpkit/middleware) and lines 40 and 41 (dependency rule 4).
- https://github.com/weaveplatform/artifactweave/issues/1069
Status ¶
Implemented P0 to P9c, as the server root's middleware.go: request IDs, the access log, recovery, the body limit, content-type normalisation and the binding errors from the baseline, the access log's cause and user in later phases, and the Terraform provider's trailing-slash collections. P9d (WEB-03) moved it here and turned its ecosystem decisions into hooks.
Testing ¶
middleware_test.go checks request ID reuse and minting, the access log's fields, level and cause, the line of an aborted response, panic recovery in two envelopes, the body limit with declared and undeclared lengths, content-type normalisation and the binding errors, each with its hooks passed explicitly. The router's guards in app hold TestAccStrictBindingErrorThroughRouter, which builds the router, and TestAccRegistryKeepsContentType, which checks its Docker keep predicate.
Index ¶
- Constants
- func AccessLog(logger *slog.Logger, redact func(path string) string) func(http.Handler) http.Handler
- func BindingError(status int) func(w http.ResponseWriter, r *http.Request, err error)
- func BodyLimit(limit int64) func(http.Handler) http.Handler
- func BodyTooLarge(limit int64) *apierror.Error
- func CollectionSlash(m map[string]string) func(http.Handler) http.Handler
- func HeadLengthUnknown(w http.ResponseWriter)
- func NormalizeContentType(keep func(*http.Request) bool) func(http.Handler) http.Handler
- func RecoverPanic(logger *slog.Logger, redact func(path string) string) func(http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- type HeadAsGet
Constants ¶
const ManagementBodyLimit = 64 << 20
ManagementBodyLimit is the BodyLimit every JSON management group mounts, in the router and in the handler packages that register their own groups, so that one figure bounds them all. 64 MiB covers the largest documented payloads (batch repository creation, build-info) with room to spare.
const RequestIDHeader = "X-Request-ID"
RequestIDHeader lines up artifactweave's logs with a reverse proxy's. It is artifactweave's choice, not Artifactory's: Artifactory's correlation header is X-Artifactory-Trace-Id, sent only when artifactory.trace.id.response.header is true, from 7.79 (JFrog KB "How to correlate Artifactory and NGINX logs").
Variables ¶
This section is empty.
Functions ¶
func AccessLog ¶
func AccessLog( logger *slog.Logger, redact func(path string) string, ) func(http.Handler) http.Handler
AccessLog writes one slog line per request. It wraps the writer so the status and byte count are known after the handler returns. A request whose handler noted a cause (NoteCause) logs at ERROR with it, and one that authenticated names its user (NoteUser). The path is logged as redact returns it, so a credential that a path names never reaches the log.
A handler that aborts a response it has begun (http.ErrAbortHandler, as a streamed download or list does when its source fails) is logged too, at ERROR with aborted=true and the cause it noted, before the abort goes on to net/http: without the line, the cause such a handler notes would reach no log at all.
func BindingError ¶
BindingError renders request binding and response rendering failures from the generated strict handlers in the right envelope. A MaxBytesError from BodyLimit becomes 413 rather than the generic 400.
func BodyLimit ¶
BodyLimit rejects management request bodies above limit. It is mounted only on JSON management groups; artifact uploads are streamed and must never pass through it. A declared Content-Length above the limit is refused up front; an undeclared body is capped by MaxBytesReader so a strict decoder sees an error instead of an unbounded read.
func BodyTooLarge ¶
BodyTooLarge is BodyLimit's 413. A handler that meets the MaxBytesReader BodyLimit installs answers with it too, so a body over the limit gets the same answer whether its length was declared or not.
func CollectionSlash ¶
CollectionSlash routes each path that is a key of m as the value m gives it, for the collection paths clients call with a trailing slash, which chi would otherwise read as a member with an empty key. Only the exact paths of m are rewritten, because a trailing slash elsewhere can name a folder.
func HeadLengthUnknown ¶
func HeadLengthUnknown(w http.ResponseWriter)
HeadLengthUnknown has the HEAD that w answers through its GET route go without a Content-Length, for a handler that sees the HEAD and skips a streamed body whose length it learns only by building it, such as a folder archive. Without it the HEAD would send the 0 of the body it skipped, where the GET sends none; RFC 9110 section 8.6 lets a HEAD omit it. On any other writer it does nothing.
func NormalizeContentType ¶
NormalizeContentType maps the vendor media types Artifactory clients send, such as application/vnd.org.jfrog.artifactory.repositories.LocalRepositoryConfiguration+json, onto application/json so the generated strict decoders accept them. The original value is kept in a context value (OriginalContentType) for handlers that care about the exact type. application/yaml is left alone; the descriptor PATCH handler is hand-written and reads it directly. A request keep accepts retains its media type, for protocols whose vendor types are part of the exchange or of the content stored and served back.
func RecoverPanic ¶
func RecoverPanic( logger *slog.Logger, redact func(path string) string, ) func(http.Handler) http.Handler
RecoverPanic turns a panic into a 500 using the request's error response profile, so a bug in one handler never leaks a Go stack trace to a client. The panic's log line names the path as redact returns it, as AccessLog's does.
Types ¶
type HeadAsGet ¶
type HeadAsGet struct {
// Serves reports whether the GET route with this chi pattern answers a
// HEAD too. It is asked "" for a path no GET route serves.
Serves func(pattern string) bool
// RunsGet reports whether the handler of a GET route Serves accepts
// runs the HEAD as the GET, as Jersey runs a resource's @GET for one:
// it answers in full and HeadAsGet drops the body and sends its length.
// That suits a handler written for the GET alone, whose own HEAD branch,
// if it has one, would drop the body and with it the length the HEAD
// must send. Any other handler sees the HEAD. Nil names none.
RunsGet func(pattern string) bool
}
HeadAsGet answers a HEAD through the GET route of its path, for the GET routes Serves accepts, where no route claims the HEAD itself. 7.x serves its REST API with Jersey, which hands a HEAD to the resource's @HEAD method or, when there is none, to its @GET method and leaves the entity out (JAX-RS 2.1, section 3.3.5). chi routes a HEAD only to a route that registers HEAD, so without this a HEAD of a GET-only operation answers 405.
The router installs it in two places. Enter decides, and from there on the request is its GET: the key gate, the recovery mark, admission, authentication's public routes and the restriction check all read the method, and each must decide a HEAD as it decides the GET, or the HEAD would answer a status or rate header the GET does not. Route, the last middleware before routing, gives the handler its HEAD back, because a file download reads it: a HEAD ignores Range and is no delivery of the file (the VCS downloads). A handler RunsGet names keeps the GET instead.
func (HeadAsGet) Enter ¶
Enter turns a HEAD whose path no HEAD route serves, and whose GET route Serves accepts, into that GET for the middleware after it, and answers it without a body. It looks the routes up on the path as it stands, so it must follow every middleware that rewrites the path. Any other request passes as it was, so a HEAD that a route of its own serves keeps that route, and one with no GET route keeps its 404 or 405.