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) } }