Documentation
¶
Overview ¶
Package server provides auth-specific ServerOption factories for github.com/dioad/net/http servers.
Index ¶
- Constants
- func APIMiddlewares(validators []oidc.ValidatorConfig, extractor auth.PrincipalExtractor, ...) ([]nethttp.Middleware, error)
- func AddValidatorCheck(r *lifecycle.Readiness, validators []oidc.ValidatorConfig, ...)
- func OAuth2ValidatorHandler(v []oidc.ValidatorConfig, opts ...ValidatorHandlerOption) (nethttp.Middleware, error)
- func PrincipalKey(r *http.Request) (string, error)
- func PrincipalKeyFunc(resolver *nethttp.ClientIPResolver) nethttp.PrincipalFunc
- func RateLimiter(cfg RateLimitConfig, logger zerolog.Logger, registerer prometheus.Registerer, ...) (nethttp.Middleware, error)
- func WithOAuth2Validator(v []oidc.ValidatorConfig, opts ...ValidatorHandlerOption) nethttp.ServerOption
- func WithServerAuth(cfg authhttp.ServerConfig) nethttp.ServerOption
- type APIOption
- type RateLimitConfig
- type RateLimitOption
- type ValidatorHandlerOption
Examples ¶
Constants ¶
const ( // DefaultRateLimitRPS is the per-principal request rate applied when // RateLimitConfig.RPS is zero. DefaultRateLimitRPS = 10000.0 // DefaultRateLimitBurst is the per-principal burst applied when // RateLimitConfig.Burst is zero. DefaultRateLimitBurst = 1000 )
const ( // ValidatorCheckName is the name AddValidatorCheck registers the check under, // and so the key it has in a readiness report. ValidatorCheckName = "jwt-validators" // DefaultValidatorCheckTimeout caps the check and each of its requests. It is // below the 5s that Fly and lifecycle.DefaultCheckTimeout both use, so a hung // identity provider makes the check report degraded rather than the probe // itself time out. DefaultValidatorCheckTimeout = 2 * time.Second // DefaultValidatorCheckCacheTTL is how long a result is reused, so frequent // probes make at most one discovery and one JWKS request per issuer per // interval per instance. DefaultValidatorCheckCacheTTL = 30 * time.Second )
Variables ¶
This section is empty.
Functions ¶
func APIMiddlewares ¶ added in v0.16.0
func APIMiddlewares(validators []oidc.ValidatorConfig, extractor auth.PrincipalExtractor, opts ...APIOption) ([]nethttp.Middleware, error)
APIMiddlewares returns the authentication half of an API's middleware chain, in order: bearer token validation against validators, then principal extraction with extractor, then, with WithPrincipalACL, the principal ACL. Token validation is left out when there are no validators, which is the allow-unauthenticated case, so every request reaches the principal extractor with no token. A nil extractor leaves extraction out, for an API that authorises with WithPrincipalACL and has no roles to extract.
Put anything that must run before authentication, such as a header check or CORS, ahead of the result, and anything that needs the principal, such as RateLimiter, after it. Options that are ValidatorHandlerOptions are passed to OAuth2ValidatorHandler.
func AddValidatorCheck ¶ added in v0.17.0
func AddValidatorCheck(r *lifecycle.Readiness, validators []oidc.ValidatorConfig, opts ...lifecycle.CheckOption)
AddValidatorCheck adds a readiness check to r that every identity provider behind validators answers OIDC discovery and serves at least one signing key (see oidc.ProbeValidators). It adds nothing when no validator fetches keys: none configured, or all use a static HMAC secret.
The check is degraded, not failing: an identity provider outage affects every instance alike, so failing readiness would take the whole service out of rotation without moving traffic anywhere that could validate tokens. A pass means each issuer was reachable within DefaultValidatorCheckCacheTTL; it does not prove the validators' own key caches are current.
opts follow the defaults, so WithCheckTimeout or WithCacheTTL replaces them.
Example ¶
ExampleAddValidatorCheck reports the identity provider behind a service's token validators as a readiness check. The check is degraded, not failing, so an identity provider outage shows in the report without taking the service out of rotation.
The example serves a minimal discovery document and key set so that it runs without a real provider.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/dioad/lifecycle"
"github.com/dioad/auth/http/server"
"github.com/dioad/auth/oidc"
)
func main() {
var issuer *httptest.Server
issuer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/.well-known/openid-configuration":
_, _ = fmt.Fprintf(w, `{"issuer":%q,"jwks_uri":%q}`, issuer.URL, issuer.URL+"/jwks")
case "/jwks":
_, _ = fmt.Fprint(w, `{"keys":[{"kty":"RSA","kid":"k1"}]}`)
default:
http.NotFound(w, r)
}
}))
defer issuer.Close()
readiness := lifecycle.NewReadiness()
server.AddValidatorCheck(readiness, []oidc.ValidatorConfig{{Issuer: issuer.URL}})
readiness.MarkStarted()
report, err := readiness.Ready(context.Background())
fmt.Println(err)
fmt.Println(report)
}
Output: <nil> map[jwt-validators:ok]
func OAuth2ValidatorHandler ¶
func OAuth2ValidatorHandler(v []oidc.ValidatorConfig, opts ...ValidatorHandlerOption) (nethttp.Middleware, error)
OAuth2ValidatorHandler returns a middleware that validates OAuth2 bearer tokens using the provided configurations. A request without a token is rejected with 401.
The token is read from the Authorization header only. Pass WithCookieTokenName to also accept it from a cookie.
Example ¶
ExampleOAuth2ValidatorHandler protects an API with JWT validation. The token is read from the Authorization header only: a valid token in a cookie is refused, so a browser cannot be made to call the API with credentials it attaches by itself.
The example validates tokens with a shared secret so that it runs without an identity provider. HMACSecret is for local development and tests only. A real configuration names an issuer, and the keys are fetched from it.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/dioad/auth/http/server"
"github.com/dioad/auth/oidc"
)
func main() {
middleware, err := server.OAuth2ValidatorHandler([]oidc.ValidatorConfig{{
HMACSecret: "example-secret",
AllowInsecureHMAC: true,
Audiences: []string{"my-api"},
}})
if err != nil {
fmt.Println(err)
return
}
api := middleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = fmt.Fprintln(w, "hello")
}))
now := time.Now()
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "alice",
"iss": "https://idp.example",
"aud": "my-api",
"iat": now.Unix(),
"exp": now.Add(time.Hour).Unix(),
}).SignedString([]byte("example-secret"))
if err != nil {
fmt.Println(err)
return
}
call := func(modify func(*http.Request)) int {
req := httptest.NewRequest(http.MethodGet, "/", nil)
modify(req)
rr := httptest.NewRecorder()
api.ServeHTTP(rr, req)
return rr.Code
}
fmt.Println("bearer token:", call(func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+token) }))
fmt.Println("no token:", call(func(*http.Request) {}))
fmt.Println("token in a cookie:", call(func(r *http.Request) { r.AddCookie(&http.Cookie{Name: "auth_token", Value: token}) }))
fmt.Println("bad token:", call(func(r *http.Request) { r.Header.Set("Authorization", "Bearer not-a-token") }))
}
Output: bearer token: 200 no token: 401 token in a cookie: 401 bad token: 401
func PrincipalKey ¶ added in v0.19.0
PrincipalKey returns the rate limit key of a request: the ID of the principal extracted by the principal extraction middleware, else the subject of the validated token, else the address of the connection the request arrived on. It never reads a forwarding header, so a caller cannot choose its key. Use PrincipalKeyFunc for a service behind a proxy.
func PrincipalKeyFunc ¶ added in v0.19.0
func PrincipalKeyFunc(resolver *nethttp.ClientIPResolver) nethttp.PrincipalFunc
PrincipalKeyFunc returns a key function like PrincipalKey that falls back to the client address resolver finds, so only the proxies and headers the resolver trusts can say what that address is. A nil resolver selects the address of the connection.
func RateLimiter ¶ added in v0.19.0
func RateLimiter(cfg RateLimitConfig, logger zerolog.Logger, registerer prometheus.Registerer, opts ...RateLimitOption) (nethttp.Middleware, error)
RateLimiter returns a middleware that limits each principal to the request rate in cfg, keyed by PrincipalKey, or a pass-through when cfg disables the limiter. It logs to logger and registers its metrics with registerer; a nil registerer selects the default one, which only one limiter in a process can usefully share.
It must run after token validation and principal extraction, so place it after the result of APIMiddlewares. Ahead of them no request has a principal yet, and every caller is keyed by address instead.
The limiter keeps a background cleanup task for as long as the process runs, so build one per server rather than one per request or route.
Example ¶
ExampleRateLimiter limits each caller of an API to its own request rate. The limiter goes after the authentication chain, so that it keys a request by the principal the chain found. Here there is no authentication, so the key is the address of the connection, whatever forwarding headers say.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/zerolog"
"github.com/dioad/auth/http/server"
)
func main() {
limit, err := server.RateLimiter(
server.RateLimitConfig{RPS: 1, Burst: 2},
zerolog.Nop(),
prometheus.NewRegistry(),
)
if err != nil {
fmt.Println(err)
return
}
api := limit(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = fmt.Fprintln(w, "hello")
}))
call := func(remoteAddr, forwardedFor string) int {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = remoteAddr
req.Header.Set("X-Forwarded-For", forwardedFor)
rr := httptest.NewRecorder()
api.ServeHTTP(rr, req)
return rr.Code
}
fmt.Println(call("192.0.2.1:4711", "198.51.100.1"))
fmt.Println(call("192.0.2.1:4711", "198.51.100.2"))
fmt.Println(call("192.0.2.1:4711", "198.51.100.3"))
fmt.Println(call("192.0.2.2:4711", "198.51.100.1"))
}
Output: 200 200 429 200
func WithOAuth2Validator ¶
func WithOAuth2Validator(v []oidc.ValidatorConfig, opts ...ValidatorHandlerOption) nethttp.ServerOption
WithOAuth2Validator returns a ServerOption that configures the server to validate OAuth2 bearer tokens. See OAuth2ValidatorHandler for opts.
func WithServerAuth ¶
func WithServerAuth(cfg authhttp.ServerConfig) nethttp.ServerOption
WithServerAuth returns a ServerOption that configures the server to use the given authentication configuration. When the resolved auth handler needs additional routes beyond the Wrap middleware chain (currently only OIDC's login/callback/logout flow), those routes are registered on the server's mux automatically.
Types ¶
type APIOption ¶ added in v0.18.0
type APIOption interface {
// contains filtered or unexported methods
}
APIOption configures APIMiddlewares. A ValidatorHandlerOption is an APIOption that configures the token validation step.
func WithPrincipalACL ¶ added in v0.18.0
func WithPrincipalACL(acl authz.PrincipalACLConfig) APIOption
WithPrincipalACL adds a last step that admits only the principals acl allows, by the subject of the validated token, and refuses those it denies. It is for an API that authorises by who the caller is rather than by role, for example one that always admits the owner of a resource. It needs a token validated ahead of it, so use it with validators.
type RateLimitConfig ¶ added in v0.19.0
type RateLimitConfig struct {
// RPS is the sustained per-principal request rate. Zero selects
// DefaultRateLimitRPS.
RPS float64 `desc:"sustained per-principal request rate; 0 selects the default" mapstructure:"rate-limit-rps"`
// Burst is the per-principal burst size. Zero selects
// DefaultRateLimitBurst.
Burst int `desc:"per-principal burst size; 0 selects the default" mapstructure:"rate-limit-burst"`
// Disable turns the limiter off.
Disable bool `desc:"turn the rate limiter off" mapstructure:"disable-rate-limit"`
}
RateLimitConfig configures the per-principal request rate limiter built by RateLimiter. It is meant to be squashed into a service config so the keys stay flat (rate-limit-rps and so on).
func (RateLimitConfig) Check ¶ added in v0.19.0
func (c RateLimitConfig) Check(findings *configcheck.Collector)
Check reports a negative limit to findings, which should be positioned where the config's keys are read from: the root of the service config it is squashed into. A disabled limiter has nothing to report.
type RateLimitOption ¶ added in v0.19.0
type RateLimitOption func(*rateLimitOptions)
RateLimitOption configures RateLimiter.
func WithClientIPResolver ¶ added in v0.19.0
func WithClientIPResolver(resolver *nethttp.ClientIPResolver) RateLimitOption
WithClientIPResolver sets how the limiter finds the client address it keys an unauthenticated request by. Use it for a service behind a proxy, where the connection's own address is the proxy's and every unauthenticated caller would otherwise share one bucket. Without it the key is the connection's address.
type ValidatorHandlerOption ¶ added in v0.15.0
type ValidatorHandlerOption func(*validatorHandlerOptions)
ValidatorHandlerOption configures the middleware built by OAuth2ValidatorHandler and WithOAuth2Validator.
func WithCookieTokenName ¶ added in v0.15.0
func WithCookieTokenName(name string) ValidatorHandlerOption
WithCookieTokenName also accepts a bearer token from the cookie called name. Without it the token is read from the Authorization header only.
Use it only for browser-facing routes. A machine-to-machine API that browsers can reach must not accept a cookie credential: that is a CSRF risk, and it couples the API to the cookie name of any browser app on the same origin.
func WithValidatorDebug ¶ added in v0.15.0
func WithValidatorDebug() ValidatorHandlerOption
WithValidatorDebug logs the outcome of every token validation through the request-scoped logger. See oidc.NewValidatorDebugger.
func WithValidatorOptions ¶ added in v0.15.0
func WithValidatorOptions(opts ...jwtvalidator.Option) ValidatorHandlerOption
WithValidatorOptions passes go-jwt-middleware validator options to every configured validator, for example validator.WithCustomClaims. They are base options: a validator config or provider type that sets the same thing overrides them. See oidc.NewMultiValidatorFromConfig.