Files
nmon/internal/auth/authtest/authtest.go

106 lines
3.7 KiB
Go

// Package authtest holds test utilities for code that sits behind auth.Middleware: credentials for each
// role and the viewer-cannot-mutate check that M6's gate runs against the real API.
package authtest
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/v10networks/nmon/internal/auth"
)
// Creds is one way of calling the API: a cookie session with its CSRF token, or a bearer token.
type Creds struct {
Cookie *http.Cookie
CSRF string
Token string
}
// Mint creates a session and an API token of role and returns both ways in.
func Mint(tb testing.TB, a *auth.Auth, role auth.Role) (session, token Creds) {
tb.Helper()
ctx := context.Background()
cookie, err := a.Sessions.Create(ctx, auth.Identity{Subject: "oidc:authtest-" + string(role), Name: "authtest", Role: role}, nil)
if err != nil {
tb.Fatalf("mint session: %v", err)
}
probe := httptest.NewRequest(http.MethodGet, "/", nil)
probe.AddCookie(cookie)
p, err := a.Sessions.Load(ctx, probe)
if err != nil {
tb.Fatalf("load minted session: %v", err)
}
_, secret, err := a.Tokens.Mint(ctx, "authtest", auth.MintOptions{Name: "authtest-" + string(role), Scope: role})
if err != nil {
tb.Fatalf("mint token: %v", err)
}
return Creds{Cookie: cookie, CSRF: p.CSRF}, Creds{Token: secret}
}
// Route is one route to exercise. Path must be concrete ("/api/v1/devices/r1").
type Route struct {
Method, Path string
// ReadOnly marks a non-GET route that only reads (a POST query endpoint) and is declared viewer-level.
ReadOnly bool
// Body is sent as the request body; empty is fine for most mutating routes, which reject before parsing.
Body string
}
func (c Creds) apply(r *http.Request, withCSRF bool) {
if c.Token != "" {
r.Header.Set("Authorization", "Bearer "+c.Token)
}
if c.Cookie != nil {
r.AddCookie(c.Cookie)
if withCSRF {
r.Header.Set(auth.CSRFHeader, c.CSRF)
}
}
}
func do(h http.Handler, rt Route, c Creds, withCSRF bool) *httptest.ResponseRecorder {
r := httptest.NewRequest(rt.Method, rt.Path, strings.NewReader(rt.Body))
r.Header.Set("Content-Type", "application/json")
c.apply(r, withCSRF)
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
// CheckViewerCannotMutate sends every state-changing route to h with a viewer session (carrying a valid
// CSRF token, so only the role can refuse it) and with a viewer token, and requires 403 each time. It also
// requires that a cookie request without the CSRF token is refused with 403, and, when admin is given,
// that the same routes are not refused with 401 or 403 for an admin, so a handler that denies everything
// cannot pass vacuously. Run it against the real API router.
func CheckViewerCannotMutate(tb testing.TB, h http.Handler, routes []Route, viewerSession, viewerToken Creds, admin *Creds) {
tb.Helper()
checked := 0
for _, rt := range routes {
if auth.IsSafeMethod(rt.Method) || rt.ReadOnly {
continue
}
checked++
name := rt.Method + " " + rt.Path
if w := do(h, rt, viewerSession, true); w.Code != http.StatusForbidden {
tb.Errorf("%s with a viewer session: status %d, want 403", name, w.Code)
}
if w := do(h, rt, viewerToken, false); w.Code != http.StatusForbidden {
tb.Errorf("%s with a viewer token: status %d, want 403", name, w.Code)
}
if w := do(h, rt, viewerSession, false); w.Code != http.StatusForbidden {
tb.Errorf("%s with a viewer session and no CSRF token: status %d, want 403", name, w.Code)
}
if admin != nil {
if w := do(h, rt, *admin, true); w.Code == http.StatusForbidden || w.Code == http.StatusUnauthorized {
tb.Errorf("%s with an admin credential: status %d; the check would pass vacuously", name, w.Code)
}
}
}
if checked == 0 {
tb.Errorf("no state-changing routes were checked (%d given)", len(routes))
}
}