Documentation
¶
Overview ¶
Package middleware holds the HTTP middleware of the API server. "The path of a request" in docs/architecture.md says where each one runs and why. A middleware's handler type is exported, as CrossSiteCheck is, where the test of the router's middleware order (internal/api) recognises that middleware by its type.
Index ¶
- func AuditCoverage(route func(*http.Request) (pattern string, exempt bool)) func(http.Handler) http.Handler
- func AuditUncoveredMutationsByRoute() map[string]float64
- func CORS(allowedOrigins []string) func(http.Handler) http.Handler
- func CSRFGuard(allowedOrigins []string) func(http.Handler) http.Handler
- func Idempotency(db *postgres.DB, ignore func(*http.Request) bool) func(http.Handler) http.Handler
- func Metrics() func(http.Handler) http.Handler
- func MetricsAuth(appEnv, token string, next http.Handler) http.Handler
- func MetricsHandler() http.Handler
- func OpenRedis(ctx context.Context, url string) (*goredis.Client, error)
- func Recoverer(path func(*http.Request) string) func(http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- func SecurityHeaders(appEnv string) func(http.Handler) http.Handler
- func Timeout(d time.Duration) func(http.Handler) http.Handler
- func TraceRequestAttrs(path func(*http.Request) string) func(http.Handler) http.Handler
- func Tracing() func(http.Handler) http.Handler
- func TrustedClientIP(trusted []*net.IPNet) func(http.Handler) http.Handler
- type CrossSiteCheck
- type IdempotencyCleaner
- type IdempotencyGuard
- type OutageMode
- type RateLimited
- type RateLimiter
- type TimeLimit
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AuditCoverage ¶
func AuditCoverage(route func(*http.Request) (pattern string, exempt bool)) func(http.Handler) http.Handler
AuditCoverage returns the middleware that counts uncovered mutations: mutating requests that succeeded, wrote no audit row, called no audit.MarkSkip, and are on a route that routeTable (internal/api) does not mark auditExempt. route returns the request's route pattern, which is the counter's label, and whether routeTable marks the route auditExempt. It is a parameter because package api imports this package, so this package cannot import routeTable.
It only observes. It never changes the answer: the change has committed, so another answer would be false, and a client told that a committed change failed may make it again (ADR-089). It wraps no ResponseWriter either: it reads the status from the request's record (request.Of).
func AuditUncoveredMutationsByRoute ¶
AuditUncoveredMutationsByRoute returns the uncovered-mutation counter's values by route pattern, so a test can assert that the routes it drove left none. It collects only this counter: gathering the default registry would run every collector there, such as the server's queue-depth gauges, which query the database.
func CORS ¶
CORS lets browser pages on the allowed origins call the API and read its answers. github.com/rs/cors answers preflights and sets the headers; Hardcount decides which origins match. allowedOrigins comes from config.ParseCORSOrigins:
- A bare "*" allows every origin without credentials, so browsers send no sign-in cookie: another site's page can call the API with a key but cannot read a signed-in operator's data.
- Otherwise each listed origin matches as in CSRFGuard (originSet) and may send the sign-in cookie, so a dashboard on another address can sign in.
Hardcount matches origins itself because rs/cors's AllowedOrigins reads an empty list as every origin, and an entry with a * inside as a pattern: "h*" would allow every https origin. The boot check refuses such entries, and here they match nothing.
An OPTIONS request without Access-Control-Request-Method is not a preflight and goes on to the router.
func CSRFGuard ¶
CSRFGuard refuses a write a browser sent from another site, before the session cookie the browser attached on its own can act. CORS cannot do this: it decides whether a page may read an answer, not whether the request runs. A cross-site sign-in matters most, because sign-in sets the session cookie.
GET, HEAD, OPTIONS and TRACE pass. Any other method passes or answers 403 "cross-site request blocked", by the first rule that applies:
- A Bearer Authorization header with no session cookie passes: a browser never attaches a key on its own. With a session cookie too, the rules below apply, or a junk Bearer header would let the cookie through.
- Sec-Fetch-Site same-origin or none passes, and cross-site is refused. same-site passes only from a listed origin, so a sibling subdomain is refused.
- With no Sec-Fetch-Site, or a value it does not know, a listed Origin passes and any other Origin is refused. A request with neither header passes: every browser sends one of them on a cross-site write, and page script cannot remove them, so it did not come from a browser.
allowedOrigins is CORS_ALLOWED_ORIGINS: each listed origin matches as in CORS (originSet), and a bare "*" allows no origin here. Mount the guard on every group that accepts the session cookie. ADR-093 has the threat model.
func Idempotency ¶
Idempotency returns the middleware that makes a retried write safe: the first request with an Idempotency-Key runs, and a retry of it gets the first request's answer instead of running again.
It guards a POST, PUT or PATCH that a tenant sends with an Idempotency-Key. Every other request passes through, as if it sent no key. So does a request the ignore function returns true for; a nil ignore skips none. The server passes keepsNoKey (internal/api) as ignore.
A key is remembered for 24 hours (the expires_at default on idempotency_keys), per tenant and per mode (test or live). A request is the same request as the first one with the key when its caller (the API key, or the dashboard user), method, path, query string and body match.
What a request with the key gets:
- The first request runs to its end, even if its client hangs up. Its answer is stored. The exception is an answer freesKey returns true for: the key's row is deleted, and the next request with the key runs.
- The same request again gets the stored answer, with Idempotent-Replayed: true. While the first still runs, it gets 409 conflict_idempotency at once, and the client retries with the key.
- A different request with the key gets 422 idempotency_error at once, whether the first has finished or not. A stored answer is therefore replayed only to the caller that made the first request, never to another API key or user of the same tenant.
Its other answers are in docs/architecture.md, "Where a refusal comes from".
func MetricsAuth ¶
MetricsAuth protects the /metrics endpoint with a bearer token. Without METRICS_TOKEN the endpoint is open outside production, for local dev. In production it answers 401 to everyone: the scrape is operational data and costs database queries, and an address allowlist in front of it stops holding once a load balancer makes every caller a private address. It refuses the scrape rather than the boot, so an install that does not scrape metrics still starts. appEnv is config.Config.Env, and token is METRICS_TOKEN (config.Server.MetricsToken).
func MetricsHandler ¶
MetricsHandler returns the Prometheus metrics HTTP handler.
func OpenRedis ¶
OpenRedis parses url, opens a client and checks it with a Ping bounded by ctx. An empty url is not an error: it returns (nil, nil), and every limiter then follows its OutageMode. The caller decides what an error means: cmd/hardcount refuses to start on one in production.
func Recoverer ¶
Recoverer turns a handler panic into the JSON 500 every other internal error answers (respond.InternalError), where chi's Recoverer answers an empty 500, and logs the panic with its stack.
The log line's path is path(r), never the raw path, because some public links carry a link token in the path that works like a password. path(r) must return a path that holds no link token.
http.ErrAbortHandler is re-panicked, as net/http expects: it aborts the response on purpose. A panic after the handler started its answer, or on a connection upgrade, writes nothing, but the log still records it.
func RequestID ¶
RequestID gives every request a new id, "req_" and an xid, and never takes one from the client: the id is stamped on the request's audit rows and log lines, so a client that chose it could forge or collide that evidence. A client matches its request to them by the Hardcount-Request-Id header, and cross-service tracing uses W3C Trace Context (Tracing).
The id is stored under chi's RequestIDKey, so chimw.GetReqID returns it, and it is the Hardcount-Request-Id response header, set before the handler runs, so every answer carries it, even one with no body.
func SecurityHeaders ¶
SecurityHeaders adds standard security headers to every response. They are defense in depth, which enterprise security audits expect. appEnv is config.Config.Env.
func Timeout ¶
Timeout ends the request's context after d. A handler that has written nothing when the time runs out gets the JSON 504 (respond.Timeout). One that already started its answer keeps it; chi's Timeout answers an empty 504.
func TraceRequestAttrs ¶
TraceRequestAttrs corrects the request span before it ends. otelhttp sets url.path to the raw path, which on the public pages carries a link token, and client.address to the left-most X-Forwarded-For entry, which any client can write. After the handler returns, this sets:
- the span name to "{method} {route}" (method alone when nothing routed),
- http.route to the route pattern on the request's record (request.Of),
- url.path to path(r), which must return the path with any link token removed.
- client.address to the client address on that record, which is the trusted one.
Mount it after Tracing and TrustedClientIP and before anything that can answer without routing (CORS preflight), so every span passes through it.
func Tracing ¶
Tracing returns middleware that creates an OpenTelemetry span for each HTTP request. It propagates trace context from incoming headers (W3C Trace Context). When tracing is off (the noop provider), it adds negligible overhead.
The span starts before routing, so it is named by method alone; TraceRequestAttrs renames it once the route is known.
func TrustedClientIP ¶
TrustedClientIP resolves the client IP with chi's ClientIPFrom* middleware and stores it on the request context, where the request's record takes it (request.Record.ClientIP). r.RemoteAddr is left as the TCP peer.
- With trusted proxies, chi's ClientIPFromXFF reads X-Forwarded-For only when the TCP peer is inside one of them. It merges every header line, walks right to left past trusted hops and takes the first untrusted address. An entry that is not a bare IP ends the walk with no result.
- With none, chi's ClientIPFromRemoteAddr uses the TCP peer.
No other header (X-Real-IP, True-Client-IP) is read. When chi resolves nothing, the record falls back to the TCP peer.
Types ¶
type CrossSiteCheck ¶ added in v0.10.0
type CrossSiteCheck struct {
// contains filtered or unexported fields
}
CrossSiteCheck refuses a cross-site browser write. CSRFGuard makes it; its doc has the rule.
func (CrossSiteCheck) ServeHTTP ¶ added in v0.10.0
func (c CrossSiteCheck) ServeHTTP(w http.ResponseWriter, r *http.Request)
type IdempotencyCleaner ¶
type IdempotencyCleaner struct {
// contains filtered or unexported fields
}
IdempotencyCleaner deletes expired keys, in the shape of the scheduler's cleaners (billing.IdempotencyCleaner), so the scheduler does not import this package.
func NewIdempotencyCleaner ¶
func NewIdempotencyCleaner(db *postgres.DB) *IdempotencyCleaner
NewIdempotencyCleaner returns an IdempotencyCleaner for the keys in db.
type IdempotencyGuard ¶ added in v0.10.0
type IdempotencyGuard struct {
// contains filtered or unexported fields
}
IdempotencyGuard is the handler Idempotency wraps a route in. Idempotency's doc has the rules it keeps.
func (IdempotencyGuard) ServeHTTP ¶ added in v0.10.0
func (g IdempotencyGuard) ServeHTTP(w http.ResponseWriter, r *http.Request)
type OutageMode ¶ added in v0.10.0
type OutageMode int
OutageMode is what a limiter does while Redis is not configured or a Redis call fails.
const ( // FailOpen allows every request while Redis is unavailable. It suits // local development. It also suits a limiter where refusing real // requests would cost more than letting the extra traffic through. FailOpen OutageMode = iota // FailClosed answers every request 429. Use it in production, where // serving without a limit is a DDoS vector. FailClosed // CountLocally counts in this process with the same rate and burst. The // count is per replica: with N replicas behind a balancer, one key gets // up to N times the limit while Redis is down. CountLocally )
type RateLimited ¶ added in v0.10.0
type RateLimited struct {
// contains filtered or unexported fields
}
RateLimited counts each request against its limiter. RateLimiter.Middleware makes it; its doc has the rule.
func (RateLimited) ServeHTTP ¶ added in v0.10.0
func (l RateLimited) ServeHTTP(w http.ResponseWriter, r *http.Request)
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter is a distributed rate limiter that runs GCRA (Generic Cell Rate Algorithm) in Redis, through go-redis/redis_rate. GCRA is a leaky-bucket variant. It smooths traffic, instead of allowing a burst and then blocking at each window boundary.
func NewRateLimiter ¶
func NewRateLimiter(rdb *goredis.Client, name string, rate int, window time.Duration, outage OutageMode) *RateLimiter
NewRateLimiter returns a limiter that allows rate requests per window, with a burst of rate. name namespaces its Redis keys, such as "general". outage says what it does while rdb is nil or a Redis call fails.
func (*RateLimiter) AllowKey ¶
AllowKey spends one request from key's bucket, for a handler that limits by a key of its own, such as a per-customer cooldown. It returns (remaining, resetAt, allowed) and follows the same outage mode as the middleware.
func (*RateLimiter) Middleware ¶
func (rl *RateLimiter) Middleware() func(http.Handler) http.Handler
Middleware answers 429 to a request over the limiter's rate, or to every request while a FailClosed limiter cannot reach Redis. The bucket (rateLimitKey) is the first of these that the request has:
- its API key;
- its tenant and mode (test or live), for a dashboard session;
- its client IP, before sign-in.