package middleware import ( "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/xlgmokha/x/pkg/test" "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/cfg" "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/db" "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/domain" "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/oidc" "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls" ) func TestUser(t *testing.T) { repository := db.NewRepository[*domain.User]() middleware := User(repository) knownUser := &domain.User{ID: domain.ID(pls.GenerateULID())} require.NoError(t, repository.Save(knownUser)) t.Run("when ID Token is provided", func(t *testing.T) { t.Run("when user is known", func(t *testing.T) { server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user := cfg.CurrentUser.From(r.Context()) require.NotNil(t, user) assert.Equal(t, knownUser.ID, user.ID) w.WriteHeader(http.StatusTeapot) })) ctx := cfg.IDToken.With(t.Context(), &oidc.IDToken{Subject: knownUser.ID.String()}) r, w := test.RequestResponse("GET", "/example", test.WithContext(ctx)) server.ServeHTTP(w, r) assert.Equal(t, http.StatusTeapot, w.Code) }) t.Run("when user is unknown", func(t *testing.T) { unknownID := pls.GenerateULID() server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user := cfg.CurrentUser.From(r.Context()) require.NotNil(t, user) assert.Equal(t, domain.ID(unknownID), user.ID) w.WriteHeader(http.StatusTeapot) })) ctx := cfg.IDToken.With(t.Context(), &oidc.IDToken{Subject: unknownID}) r, w := test.RequestResponse("GET", "/example", test.WithContext(ctx)) server.ServeHTTP(w, r) assert.Equal(t, http.StatusTeapot, w.Code) require.NotNil(t, repository.Find(domain.ID(unknownID))) }) }) t.Run("when ID Token is not provided", func(t *testing.T) { server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user := cfg.CurrentUser.From(r.Context()) require.Nil(t, user) w.WriteHeader(http.StatusTeapot) })) r, w := test.RequestResponse("GET", "/example") server.ServeHTTP(w, r) assert.Equal(t, http.StatusTeapot, w.Code) }) }