core/auth/trustedheaders_test.go
Alex Dunmow 314a25353d feat(abi,auth): first-class uuid[] DbValue + trusted identity headers (WZ-016)
Two shared wasm-boundary fixes surfaced by the messenger port (WZ-013):

1. uuid[] DbValue variant. bnwasm had no uuid-array bind/scan, so every
   ANY($1::uuid[]) query broke in the guest ("unsupported argument type
   []uuid.UUID") and messenger worked around it with a ::text[]::uuid[] cast.
   Adds a dedicated DbValue.uuid_array_value (abiv1.UuidArray) — distinct from
   text[] so the host binds a native uuid[] param (queries keep ::uuid[]) and
   scans a uuid[] column straight into []uuid.UUID. Guest toDbValue marshals
   []uuid.UUID; naturalValue/assign parse the canonical strings back into
   []uuid.UUID (nil→NULL, empty stays empty). Pinned by the uuid_array entry in
   the shared DbValueFixtures contract (round-trip + driver-value tests green).

2. Trusted identity headers (auth/trustedheaders.go). Context does not cross
   the ABI, so guests cannot see the host's verified principal. The SECURE
   contract: the host runs its RBAC guard against the signature-verified JWT,
   strips any client-supplied copy of the X-Bn-Verified-* headers, and sets
   them itself from auth.Get{Public,}UserFromContext; the guest reconstructs
   context via auth.TrustedHeaderMiddleware and trusts ONLY those headers.
   Guests MUST NOT decode a client cookie/Bearer token for identity — that is a
   privilege-escalation bug (a verified public user forging an admin JWT the
   guest would honour on a RolePublic method). Documented in docs/wasm-abi.md,
   replacing the ambiguous "auth context reaches the guest via HttpRequest
   headers" line that invited the insecure decode.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 00:43:13 +08:00

83 lines
2.7 KiB
Go

package auth
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/google/uuid"
)
func TestContextFromTrustedHeaders(t *testing.T) {
adminID := uuid.New()
pubID := uuid.New()
h := http.Header{}
h.Set(HeaderVerifiedUserID, adminID.String())
h.Set(HeaderVerifiedRole, "superadmin")
h.Set(HeaderVerifiedEmail, "admin@example.com")
h.Set(HeaderVerifiedPublicUserID, pubID.String())
h.Set(HeaderVerifiedPublicUsername, "ninja")
h.Set(HeaderVerifiedPublicEmail, "ninja@example.com")
ctx := ContextFromTrustedHeaders(context.Background(), h)
c, ok := GetUserFromContext(ctx)
if !ok {
t.Fatal("admin claims missing")
}
if c.UserID != adminID || c.Role != "superadmin" || c.Email != "admin@example.com" {
t.Fatalf("admin claims mismatch: %+v", c)
}
p, ok := GetPublicUserFromContext(ctx)
if !ok {
t.Fatal("public claims missing")
}
if p.UserID != pubID || p.Username != "ninja" || p.Email != "ninja@example.com" {
t.Fatalf("public claims mismatch: %+v", p)
}
}
// TestContextFromTrustedHeaders_NoneWhenAbsent proves an anonymous request (no
// trusted headers) yields no principals — nothing is fabricated.
func TestContextFromTrustedHeaders_NoneWhenAbsent(t *testing.T) {
ctx := ContextFromTrustedHeaders(context.Background(), http.Header{})
if _, ok := GetUserFromContext(ctx); ok {
t.Fatal("unexpected admin claims for anonymous request")
}
if _, ok := GetPublicUserFromContext(ctx); ok {
t.Fatal("unexpected public claims for anonymous request")
}
}
// TestContextFromTrustedHeaders_BadUUIDIgnored proves a malformed id header is
// ignored rather than trusted (no panic, no principal).
func TestContextFromTrustedHeaders_BadUUIDIgnored(t *testing.T) {
h := http.Header{}
h.Set(HeaderVerifiedUserID, "not-a-uuid")
h.Set(HeaderVerifiedRole, "superadmin")
ctx := ContextFromTrustedHeaders(context.Background(), h)
if _, ok := GetUserFromContext(ctx); ok {
t.Fatal("malformed user-id header must not yield a principal")
}
}
// TestTrustedHeaderMiddleware proves the middleware installs the principal into
// the downstream handler's request context, keyed by the canonical header form.
func TestTrustedHeaderMiddleware(t *testing.T) {
adminID := uuid.New()
var got *Claims
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, _ = GetUserFromContext(r.Context())
})
req := httptest.NewRequest(http.MethodGet, "/x", nil)
// lower-case on the way in — net/http canonicalizes, middleware must still see it.
req.Header.Set("x-bn-verified-user-id", adminID.String())
req.Header.Set("x-bn-verified-role", "admin")
TrustedHeaderMiddleware(next).ServeHTTP(httptest.NewRecorder(), req)
if got == nil || got.UserID != adminID || got.Role != "admin" {
t.Fatalf("middleware did not install principal: %+v", got)
}
}