diff --git a/internal/auth/auth.go b/internal/auth/auth.go index e9d6fb59..20af4f49 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -5,7 +5,6 @@ package auth import ( "context" - "errors" "github.com/gin-gonic/gin" "github.com/google/uuid" @@ -46,20 +45,3 @@ func RequireUser(users UserLookup) gin.HandlerFunc { c.Next() } } - -// UserHandler is a handler that needs the identified caller. -type UserHandler func(c *gin.Context, actor uuid.UUID) - -// WithUser adapts a UserHandler to gin. Reaching it without RequireUser in -// front is a wiring mistake, so it is reported as an internal error rather -// than blamed on the client with a 401. -func WithUser(h UserHandler) gin.HandlerFunc { - return func(c *gin.Context) { - actor, ok := httpx.UserID(c) - if !ok { - httpx.Error(c, errors.New("route is missing the RequireUser middleware")) - return - } - h(c, actor) - } -} diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go index aedfb6da..7630c4a5 100644 --- a/internal/auth/auth_test.go +++ b/internal/auth/auth_test.go @@ -28,13 +28,9 @@ func echoActor(c *gin.Context, actor uuid.UUID) { httpx.JSON(c, http.StatusOK, map[string]string{"id": actor.String()}) } -func newEngine(users lookup, guarded bool) *gin.Engine { +func newEngine(users lookup) *gin.Engine { e := httpx.NewEngine(slog.New(slog.NewTextHandler(io.Discard, nil)), 1024) - if guarded { - e.GET("/me", auth.RequireUser(users), auth.WithUser(echoActor)) - } else { - e.GET("/me", auth.WithUser(echoActor)) - } + e.GET("/me", auth.RequireUser(users), httpx.WithUser(echoActor)) return e } @@ -60,7 +56,7 @@ func call(e *gin.Engine, header string) (*httptest.ResponseRecorder, string) { func TestKnownUserReachesHandlerWithItsID(t *testing.T) { alice := ident.New() - rec, got := call(newEngine(lookup{alice: {}}, true), alice.String()) + rec, got := call(newEngine(lookup{alice: {}}), alice.String()) if rec.Code != http.StatusOK || got != alice.String() { t.Fatalf("status %d, handler saw %q, want %s", rec.Code, got, alice) } @@ -68,7 +64,7 @@ func TestKnownUserReachesHandlerWithItsID(t *testing.T) { func TestMiddlewareRejectsMissingMalformedAndUnknownWith401(t *testing.T) { alice := ident.New() - e := newEngine(lookup{alice: {}}, true) + e := newEngine(lookup{alice: {}}) for name, header := range map[string]string{ "missing": "", "malformed": "not-a-uuid", @@ -81,11 +77,3 @@ func TestMiddlewareRejectsMissingMalformedAndUnknownWith401(t *testing.T) { } } } - -func TestWithUserWithoutMiddlewareIsAWiringError(t *testing.T) { - alice := ident.New() - rec, code := call(newEngine(lookup{alice: {}}, false), alice.String()) - if rec.Code != http.StatusInternalServerError || code != "internal_error" { - t.Fatalf("status = %d code = %q, want 500 internal_error", rec.Code, code) - } -} diff --git a/internal/chat/handler.go b/internal/chat/handler.go index b18504c9..9a2c2cc9 100644 --- a/internal/chat/handler.go +++ b/internal/chat/handler.go @@ -6,7 +6,6 @@ import ( "github.com/gin-gonic/gin" "github.com/google/uuid" - "messenger/internal/auth" "messenger/internal/platform/apperr" "messenger/internal/platform/httpx" "messenger/internal/platform/ident" @@ -21,13 +20,13 @@ func NewHandler(chats *Service) *Handler { return &Handler{chats: chats} } -// Register mounts the chat endpoints on a router guarded by RequireUser. +// Register mounts the chat endpoints on a router guarded by the authentication middleware. func (h *Handler) Register(protected gin.IRouter) { - protected.POST("/chats", auth.WithUser(h.create)) - protected.GET("/chats", auth.WithUser(h.list)) - protected.GET("/chats/:chat_id", auth.WithUser(h.get)) - protected.POST("/chats/:chat_id/messages", auth.WithUser(h.send)) - protected.GET("/chats/:chat_id/messages", auth.WithUser(h.history)) + protected.POST("/chats", httpx.WithUser(h.create)) + protected.GET("/chats", httpx.WithUser(h.list)) + protected.GET("/chats/:chat_id", httpx.WithUser(h.get)) + protected.POST("/chats/:chat_id/messages", httpx.WithUser(h.send)) + protected.GET("/chats/:chat_id/messages", httpx.WithUser(h.history)) } type createChatRequest struct { diff --git a/internal/platform/httpx/httpx_test.go b/internal/platform/httpx/httpx_test.go index 2683bea9..f57fdedf 100644 --- a/internal/platform/httpx/httpx_test.go +++ b/internal/platform/httpx/httpx_test.go @@ -282,6 +282,31 @@ func TestUserIDRoundTripAndAccessLogAttribution(t *testing.T) { } } +func TestWithUserPassesTheIdentifiedCaller(t *testing.T) { + actor := uuid.MustParse("22222222-2222-4222-8222-222222222222") + e := newEngine(t, nil) + e.GET("/actor", + func(c *gin.Context) { httpx.SetUserID(c, actor) }, + httpx.WithUser(func(c *gin.Context, got uuid.UUID) { + httpx.JSON(c, http.StatusOK, gin.H{"id": got.String()}) + })) + rec, _ := do(t, e, http.MethodGet, "/actor", "", nil) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), actor.String()) { + t.Fatalf("handler did not receive the caller: %d %s", rec.Code, rec.Body.String()) + } +} + +// Reaching WithUser without an authentication middleware in front is a +// wiring mistake, so it must not be blamed on the client with a 401. +func TestWithUserWithoutIdentityIsAWiringError(t *testing.T) { + e := newEngine(t, nil) + e.GET("/actor", httpx.WithUser(func(c *gin.Context, _ uuid.UUID) { + httpx.JSON(c, http.StatusOK, gin.H{}) + })) + rec, eb := do(t, e, http.MethodGet, "/actor", "", nil) + assertError(t, rec, eb, http.StatusInternalServerError, "internal_error") +} + func logEntry(t *testing.T, logs *bytes.Buffer) map[string]any { t.Helper() var entry map[string]any diff --git a/internal/platform/httpx/identity.go b/internal/platform/httpx/identity.go index 231d67e8..6a4b6fcf 100644 --- a/internal/platform/httpx/identity.go +++ b/internal/platform/httpx/identity.go @@ -1,16 +1,18 @@ package httpx import ( + "errors" + "github.com/gin-gonic/gin" "github.com/google/uuid" ) const keyUserID = "messenger.user_id" -// SetUserID records the identified caller for the handlers behind the -// identification middleware and for the access log. It lives here rather -// than in the auth package because the access log needs it and auth already -// depends on this package. +// SetUserID records the authenticated caller for the handlers behind the +// authentication middleware and for the access log. It lives here rather +// than in the auth package because the access log needs it and the business +// modules must not depend on auth. func SetUserID(c *gin.Context, id uuid.UUID) { c.Set(keyUserID, id) } @@ -23,3 +25,20 @@ func UserID(c *gin.Context) (uuid.UUID, bool) { id, ok := v.(uuid.UUID) return id, ok } + +// UserHandler is a handler that needs the authenticated caller. +type UserHandler func(c *gin.Context, actor uuid.UUID) + +// WithUser adapts a UserHandler to gin. Reaching it without the +// authentication middleware in front is a wiring mistake, so it is reported +// as an internal error rather than blamed on the client with a 401. +func WithUser(h UserHandler) gin.HandlerFunc { + return func(c *gin.Context) { + actor, ok := UserID(c) + if !ok { + Error(c, errors.New("route is missing the authentication middleware")) + return + } + h(c, actor) + } +} diff --git a/internal/user/handler.go b/internal/user/handler.go index af8dcbdc..0531bb3e 100644 --- a/internal/user/handler.go +++ b/internal/user/handler.go @@ -6,7 +6,6 @@ import ( "github.com/gin-gonic/gin" "github.com/google/uuid" - "messenger/internal/auth" "messenger/internal/platform/httpx" ) @@ -19,10 +18,10 @@ func NewHandler(users *Service) *Handler { } // Register mounts registration on the public router and the current-user -// endpoint on the router guarded by RequireUser. +// endpoint on the router guarded by the authentication middleware. func (h *Handler) Register(public, protected gin.IRouter) { public.POST("/users", h.register) - protected.GET("/users/me", auth.WithUser(h.me)) + protected.GET("/users/me", httpx.WithUser(h.me)) } type createRequest struct {