Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Lx9FNLG2CqeBbVGGd9bFsP
96 lines
3.0 KiB
Go
96 lines
3.0 KiB
Go
package auth
|
|
|
|
import (
|
|
"crypto/subtle"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// CSRFHeader carries the per-session CSRF token on state-changing cookie requests.
|
|
const CSRFHeader = "X-CSRF-Token"
|
|
|
|
// Middleware authenticates and authorises every request, then passes the Principal down in the context.
|
|
// In order it: resolves the client address (honouring X-Forwarded-* only from a trusted proxy); lets
|
|
// ingest paths through untouched (ingest authenticates push tokens itself); lets Public routes through;
|
|
// authenticates a bearer API token or a cookie session; requires the CSRF token on a state-changing
|
|
// cookie request; and checks the route Policy's minimum role. Push tokens get 403 here.
|
|
func (a *Auth) Middleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
client := a.proxies.Resolve(r)
|
|
if !client.ViaProxy {
|
|
scrub(r)
|
|
}
|
|
r = r.WithContext(withClient(r.Context(), client))
|
|
if hasPrefix(r.URL.Path, a.opts.IngestPrefixes) {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
ru := a.opts.Policy.lookup(r)
|
|
if ru.public {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
p, err := a.authenticate(r)
|
|
if err != nil {
|
|
a.deny(w, err)
|
|
return
|
|
}
|
|
if !p.Role.AtLeast(ru.min) {
|
|
writeProblem(w, http.StatusForbidden, "requires role "+string(ru.min))
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r.WithContext(WithPrincipal(r.Context(), p)))
|
|
})
|
|
}
|
|
|
|
// authenticate resolves the caller from a bearer token or a cookie session and applies CSRF.
|
|
func (a *Auth) authenticate(r *http.Request) (*Principal, error) {
|
|
if secret, ok := bearer(r); ok {
|
|
return a.Tokens.Authenticate(r.Context(), secret)
|
|
}
|
|
p, err := a.Sessions.Load(r.Context(), r)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !IsSafeMethod(r.Method) && !validCSRF(p.CSRF, r.Header.Get(CSRFHeader)) {
|
|
return nil, ErrCSRF
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
func validCSRF(want, got string) bool {
|
|
return want != "" && subtle.ConstantTimeCompare([]byte(want), []byte(got)) == 1
|
|
}
|
|
|
|
func (a *Auth) deny(w http.ResponseWriter, err error) {
|
|
switch {
|
|
case errors.Is(err, ErrForbidden):
|
|
writeProblem(w, http.StatusForbidden, "this token is not valid for this API")
|
|
case errors.Is(err, ErrCSRF):
|
|
writeProblem(w, http.StatusForbidden, "missing or wrong "+CSRFHeader)
|
|
case errors.Is(err, ErrUnauthenticated):
|
|
w.Header().Set("WWW-Authenticate", `Bearer realm="nmon"`)
|
|
writeProblem(w, http.StatusUnauthorized, "authentication required")
|
|
default:
|
|
a.opts.Logger.Error("authenticate", slog.Any("err", err))
|
|
writeProblem(w, http.StatusInternalServerError, "authentication failed")
|
|
}
|
|
}
|
|
|
|
// bearer extracts a token from "Authorization: Bearer x" or the password of Basic auth (what
|
|
// Prometheus-style clients send). Anything else is not a token request.
|
|
func bearer(r *http.Request) (string, bool) {
|
|
h := r.Header.Get("Authorization")
|
|
if v, ok := strings.CutPrefix(h, "Bearer "); ok {
|
|
return strings.TrimSpace(v), true
|
|
}
|
|
if strings.HasPrefix(h, "Basic ") {
|
|
if _, pw, ok := r.BasicAuth(); ok {
|
|
return pw, true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|