Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
tests: work in progress on platform blackbox suites
Claude4e0b7f7f3afa
diff --git a/tests/fixture/suborganization_groups.go b/tests/fixture/suborganization_groups.gonew file mode 100644index 0000000000..1b8f7cf0d2--- /dev/null+++ b/tests/fixture/suborganization_groups.go@@ -0,0 +1,75 @@+package fixture++import (+ "bytes"+ "encoding/json"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++// NewGroup creates a group owned by this sub-organization and returns its id. It is+// not a *Group: a Group manages its members through the root admin, who cannot reach+// a sub-organization's own groups.+func (s *SubOrg) NewGroup(tt *testing.T, name string) uuid.UUID {+ tt.Helper()++ res, err := s.Admin.API.CreateGroupWithResponse(tt.Context(), api.CreateGroupJSONRequestBody{Name: name})+ require.NoErrorf(tt, err, "creating group %s in %s", name, s.Slug)+ require.NotNilf(tt, res.JSON200, "creating group %s in %s returned %d: %s", name, s.Slug, res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.Id+}++// LinkGroup links a root organization group into this sub-organization with+// permanent organization roles.+func (s *SubOrg) LinkGroup(tt *testing.T, g *Group, roles ...string) {+ tt.Helper()++ if len(roles) == 0 {+ roles = []string{"member"}+ }+ items := make([]map[string]any, 0, len(roles))+ for _, slug := range roles {+ items = append(items, map[string]any{"role": slug, "isTemporary": false})+ }+ raw, err := json.Marshal(map[string]any{"roles": items})+ require.NoError(tt, err)++ res, err := s.Admin.API.CreateOrganizationGroupMembershipWithBodyWithResponse(tt.Context(), g.ID,+ "application/json", bytes.NewReader(raw))+ require.NoErrorf(tt, err, "linking group %s into %s", g.Name, s.Slug)+ require.Equalf(tt, http.StatusOK, res.StatusCode(), "linking group %s into %s: %s", g.Name, s.Slug, apierr.Body(res.Body))+}++// NewProject creates a secret-manager project in this sub-organization, with its+// admin as the project admin, and returns the project id.+func (s *SubOrg) NewProject(tt *testing.T) string {+ tt.Helper()++ kind := api.CreateProjectJSONBodyType("secret-manager")+ name := "p-" + id.Short()+ res, err := s.Admin.API.CreateProjectWithResponse(tt.Context(), api.CreateProjectJSONRequestBody{ProjectName: name, Type: &kind})+ require.NoErrorf(tt, err, "creating project %s in %s", name, s.Slug)+ require.NotNilf(tt, res.JSON200, "creating project %s in %s returned %d: %s", name, s.Slug, res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.Project.Id+}++// GroupUserIDs lists the users in a group, as the given client sees it.+func GroupUserIDs(tt *testing.T, client *api.ClientWithResponses, groupID uuid.UUID) []uuid.UUID {+ tt.Helper()++ filter := api.ListGroupUsersParamsFilterExistingMembers+ res, err := client.ListGroupUsersWithResponse(tt.Context(), groupID.String(), &api.ListGroupUsersParams{Filter: &filter})+ require.NoError(tt, err)+ require.NotNilf(tt, res.JSON200, "listing the users of group %s returned %d: %s", groupID, res.StatusCode(), apierr.Body(res.Body))+ out := []uuid.UUID{}+ for _, u := range res.JSON200.Users {+ out = append(out, u.Id)+ }+ return out+}diff --git a/tests/harness/container.go b/tests/harness/container.gonew file mode 100644index 0000000000..dc48223194--- /dev/null+++ b/tests/harness/container.go@@ -0,0 +1,80 @@+package harness++import (+ "context"+ "testing"++ "github.com/Infisical/infisical/tests/infra"+ "github.com/Infisical/infisical/tests/infra/fakenet"+ "github.com/Infisical/infisical/tests/internal/id"+)++// TestContainer is a container one test started, such as a relay or gateway agent.+// It is stopped when the test ends.+type TestContainer struct {+ // Name is its address on the shared network, for Infisical and sibling+ // containers to dial: the spec's Alias when one was given.+ Name string++ c infra.Container+}++// Stop stops the container before the test ends, for a test whose claim is what+// happens when it goes away.+func (c *TestContainer) Stop(t *testing.T) {+ t.Helper()+ if err := c.c.Stop(context.WithoutCancel(t.Context())); err != nil {+ t.Fatalf("harness: stopping %s: %v", c.Name, err)+ }+}++// Logs is the container's output so far.+func (c *TestContainer) Logs(t *testing.T) string {+ t.Helper()+ out, err := c.c.Logs(context.WithoutCancel(t.Context()))+ if err != nil {+ return "harness: reading logs of " + c.Name + ": " + err.Error()+ }+ return out+}++// RunContainer starts a container for one test, on the network Infisical is on and+// resolving through fakenet as Infisical does, and stops it at cleanup. module names+// it; the spec's Name, Network and Labels are filled in here.+//+// Set Alias when the address has to be known before the container starts, such as a+// relay whose host Infisical records before the agent can enroll. It must be unique.+//+// Its output is logged when the test fails, since an agent that never connected is+// usually explained only there.+func (s *Stack) RunContainer(t *testing.T, module string, spec infra.ContainerSpec) *TestContainer {+ t.Helper()++ parts := infra.NameParts{Scope: infra.Test, ScopeID: id.Short() + id.Short(), Module: module}+ spec.Name = infra.ContainerName(parts)+ if spec.Alias == "" {+ spec.Alias = spec.Name+ }+ spec.Network = infra.NetworkName+ spec.Labels = infra.Labels(parts, infra.Workspace())+ if len(spec.DNS) == 0 {+ spec.DNS = []string{fakenet.IP}+ }++ runner := infra.NewRunner(infra.Workspace(), s.log)+ c, err := runner.Run(t.Context(), spec)+ if err != nil {+ t.Fatalf("harness: starting %s: %v", spec.Name, err)+ }+ tc := &TestContainer{Name: spec.Alias, c: c}++ t.Cleanup(func() {+ if t.Failed() {+ t.Logf("harness: output of %s:\n%s", tc.Name, tc.Logs(t))+ }+ // A container the test already stopped answers with an error here, which is+ // the outcome wanted anyway.+ _ = c.Stop(context.WithoutCancel(context.Background()))+ })+ return tc+}diff --git a/tests/suites/admin/admin_test.go b/tests/suites/admin/admin_test.gonew file mode 100644index 0000000000..4769e3e30b--- /dev/null+++ b/tests/suites/admin/admin_test.go@@ -0,0 +1,328 @@+package admin_test++import (+ "context"+ "crypto/rand"+ "fmt"+ "encoding/json"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/harness/infisical"+ "github.com/Infisical/infisical/tests/internal/apierr"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func TestAdminConfig_SignUp(t *testing.T) {+ h := harness.From(t)++ t.Run("should refuse signups when allowSignUp is off and send no code", func(t *testing.T) {+ // Setup+ tn := h.NewTenant(t)+ setConfig(t, h.InstanceAdmin(t), api.UpdateAdminConfigJSONRequestBody{AllowSignUp: new(false)})+ addr := tn.Email("newcomer")++ // Action+ res, err := tn.Anonymous(t).BeginEmailSignupV3WithResponse(t.Context(),+ api.BeginEmailSignupV3JSONRequestBody{Email: openapi_types.Email(addr)})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Signup's are disabled")+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool { return e.Recipient == addr })+ })++ t.Run("should still let an invited user join when allowSignUp is off", func(t *testing.T) {+ // Setup+ tn := h.NewTenant(t)+ setConfig(t, h.InstanceAdmin(t), api.UpdateAdminConfigJSONRequestBody{AllowSignUp: new(false)})++ // Action+ user := tn.NewUser(t, harness.OrgRole("member"))++ // Assert+ m := fixture.MembershipOf(t, tn, user.Email)+ require.NotNil(t, m)+ require.Equal(t, "accepted", m.Status)+ })+}++func TestAdminConfig_LoginMethods(t *testing.T) {+ h := harness.From(t)++ t.Run("should refuse email login for a member when email is not an enabled method", func(t *testing.T) {+ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))+ setLoginMethods(t, h, api.UpdateAdminConfigJSONBodyEnabledLoginMethodsGoogle)++ // Action+ res := login(t, tn, member.Email)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Invalid credentials")+ })++ t.Run("should let an org admin log in with email when email is not an enabled method", func(t *testing.T) {+ // Setup+ tn := h.NewTenant(t)+ setLoginMethods(t, h, api.UpdateAdminConfigJSONBodyEnabledLoginMethodsGoogle)++ // Action+ res := login(t, tn, tn.Admin.Email)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.NotEmpty(t, res.JSON200.AccessToken)+ })++ t.Run("should refuse disabling every login method and keep the config", func(t *testing.T) {+ // Setup+ admin := h.InstanceAdmin(t)+ before := config(t, admin.API)++ // Action+ res, err := admin.API.UpdateAdminConfigWithResponse(t.Context(), api.UpdateAdminConfigJSONRequestBody{+ EnabledLoginMethods: &[]api.UpdateAdminConfigJSONBodyEnabledLoginMethods{},+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnprocessableEntity, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "At least one login method should be enabled")+ require.Equal(t, before["enabledLoginMethods"], config(t, admin.API)["enabledLoginMethods"])+ })+}++func TestAdminUsers_Delete(t *testing.T) {+ h := harness.From(t)++ t.Run("should refuse deleting the last server admin and keep them", func(t *testing.T) {+ // Setup+ admin := h.InstanceAdmin(t)+ root := serverAdminUserIDs(t, admin.API)+ require.Len(t, root, 1)++ // Action+ res, err := admin.API.DeleteAdminUserWithResponse(t.Context(), root[0])++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Cannot delete the only server admin on this instance")+ require.Equal(t, root, serverAdminUserIDs(t, admin.API))+ })++ t.Run("should delete a user and cut off their sessions", func(t *testing.T) {+ // Setup+ admin := h.InstanceAdmin(t)+ tn := h.NewTenant(t)+ user := tn.NewUser(t, harness.OrgRole("member"))+ before, err := user.API.GetCurrentUserWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, before.StatusCode(), before.Body)++ // Action+ res, err := admin.API.DeleteAdminUserWithResponse(t.Context(), user.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ after, err := user.API.GetCurrentUserWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusUnauthorized, after.StatusCode(), after.Body)+ require.Nil(t, fixture.MembershipOf(t, tn, user.Email))+ })+}++func TestAdminConfig_Read(t *testing.T) {+ h := harness.From(t)+ private := []string{"instanceId", "adminIdentityIds", "fipsEnabled"}++ t.Run("should hide private config fields from a tenant admin", func(t *testing.T) {+ // Setup+ tn := h.NewTenant(t)++ // Action+ got := config(t, tn.Admin.API)++ // Assert+ require.Contains(t, got, "enabledLoginMethods")+ for _, field := range private {+ require.NotContains(t, got, field)+ }+ })++ t.Run("should hide private config fields from an anonymous caller", func(t *testing.T) {+ // Setup+ tn := h.NewTenant(t)++ // Action+ got := config(t, tn.Anonymous(t))++ // Assert+ require.Contains(t, got, "allowSignUp")+ for _, field := range private {+ require.NotContains(t, got, field)+ }+ })++ t.Run("should show private config fields to the instance admin", func(t *testing.T) {+ // Setup+ admin := h.InstanceAdmin(t)++ // Action+ got := config(t, admin.API)++ // Assert+ for _, field := range private {+ require.Contains(t, got, field)+ }+ })+}++func requireStatus(t *testing.T, want, got int, body []byte) {+ t.Helper()+ require.Equalf(t, want, got, "answered %d: %s", got, apierr.Body(body))+}++// config is GET /admin/config as the caller sees it.+func config(t *testing.T, c *api.ClientWithResponses) map[string]any {+ t.Helper()+ res, err := c.GetAdminConfigWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ var out struct {+ Config map[string]any `json:"config"`+ }+ require.NoError(t, json.Unmarshal(res.Body, &out))+ return out.Config+}++// setConfig writes instance config and puts back what it changed when the test ends.+func setConfig(t *testing.T, admin *harness.Principal, body api.UpdateAdminConfigJSONRequestBody) {+ t.Helper()+ before := config(t, admin.API)++ res, err := admin.API.UpdateAdminConfigWithResponse(t.Context(), body)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)++ t.Cleanup(func() {+ restore := api.UpdateAdminConfigJSONRequestBody{}+ if body.AllowSignUp != nil {+ allow, _ := before["allowSignUp"].(bool)+ restore.AllowSignUp = &allow+ }+ if body.EnabledLoginMethods != nil {+ methods := allLoginMethods()+ if raw, ok := before["enabledLoginMethods"].([]any); ok && len(raw) > 0 {+ methods = methods[:0]+ for _, m := range raw {+ methods = append(methods, api.UpdateAdminConfigJSONBodyEnabledLoginMethods(m.(string)))+ }+ }+ restore.EnabledLoginMethods = &methods+ }+ res, err := admin.API.UpdateAdminConfigWithResponse(context.WithoutCancel(t.Context()), restore)+ if err != nil || res.StatusCode() != http.StatusOK {+ t.Errorf("restoring instance config: %v %s", err, res.Body)+ }+ })+}++// setLoginMethods writes the enabled login methods as a user server admin who can+// also sign in with Google, so the lockout guard lets email be switched off. The+// machine identity instance admin cannot do it (see TestAdminConfig_KnownIssues).+func setLoginMethods(t *testing.T, h *harness.Stack, methods ...api.UpdateAdminConfigJSONBodyEnabledLoginMethods) {+ t.Helper()+ setConfig(t, userServerAdmin(t, h), api.UpdateAdminConfigJSONRequestBody{EnabledLoginMethods: &methods})+}++// userServerAdmin is a user in its own tenant, granted server admin for the test.+func userServerAdmin(t *testing.T, h *harness.Stack) *harness.Principal {+ t.Helper()+ admin := h.InstanceAdmin(t)+ operator := h.NewTenant(t).Admin++ methods, err := operator.API.UpdateUserAuthMethodsWithResponse(t.Context(), api.UpdateUserAuthMethodsJSONRequestBody{+ AuthMethods: []api.UpdateUserAuthMethodsJSONBodyAuthMethods{+ api.UpdateUserAuthMethodsJSONBodyAuthMethodsEmail,+ api.UpdateUserAuthMethodsJSONBodyAuthMethodsGoogle,+ },+ })+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, methods.StatusCode(), methods.Body)++ granted, err := admin.API.GrantAdminAccessToUserWithResponse(t.Context(), operator.ID.String())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, granted.StatusCode(), granted.Body)+ t.Cleanup(func() {+ _, _ = admin.API.RevokeAdminAccessFromUserWithResponse(context.WithoutCancel(t.Context()), operator.ID.String())+ })+ return operator+}++func allLoginMethods() []api.UpdateAdminConfigJSONBodyEnabledLoginMethods {+ return []api.UpdateAdminConfigJSONBodyEnabledLoginMethods{+ api.UpdateAdminConfigJSONBodyEnabledLoginMethodsEmail,+ api.UpdateAdminConfigJSONBodyEnabledLoginMethodsGoogle,+ api.UpdateAdminConfigJSONBodyEnabledLoginMethodsGithub,+ api.UpdateAdminConfigJSONBodyEnabledLoginMethodsGitlab,+ api.UpdateAdminConfigJSONBodyEnabledLoginMethodsSaml,+ api.UpdateAdminConfigJSONBodyEnabledLoginMethodsLdap,+ api.UpdateAdminConfigJSONBodyEnabledLoginMethodsOidc,+ }+}++func login(t *testing.T, tn *harness.Tenant, email string) *api.LoginV3Response {+ t.Helper()+ res, err := tn.Anonymous(t, infisical.ForwardedFor(sourceIP())).LoginV3WithResponse(t.Context(),+ api.LoginV3JSONRequestBody{Email: email, Password: harness.UserPassword})+ require.NoError(t, err)+ return res+}++func serverAdminUserIDs(t *testing.T, c *api.ClientWithResponses) []string {+ t.Helper()+ res, err := c.ListAdminUsersWithResponse(t.Context(), &api.ListAdminUsersParams{AdminsOnly: new("true")})+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ var ids []string+ for _, u := range res.JSON200.Users {+ if u.SuperAdmin != nil && *u.SuperAdmin {+ ids = append(ids, u.Id.String())+ }+ }+ return ids+}++func sourceIP() string {+ b := make([]byte, 3)+ _, _ = rand.Read(b)+ return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])+}++func TestAdminConfig_KnownIssues(t *testing.T) {+ h := harness.From(t)++ t.Run("should let the machine identity instance admin set the enabled login methods", func(t *testing.T) {+ // Setup+ admin := h.InstanceAdmin(t)+ methods := allLoginMethods()++ // Action+ res, err := admin.API.UpdateAdminConfigWithResponse(t.Context(), api.UpdateAdminConfigJSONRequestBody{EnabledLoginMethods: &methods})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ })+}diff --git a/tests/suites/admin/main_test.go b/tests/suites/admin/main_test.gonew file mode 100644index 0000000000..1551940d59--- /dev/null+++ b/tests/suites/admin/main_test.go@@ -0,0 +1,12 @@+// Package admin_test covers instance administration: signup, login methods, server+// admins and the instance config. Isolated because every test writes instance-wide+// configuration.+package admin_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/harness"+)++func TestMain(m *testing.M) { harness.Main(m, harness.Isolated) }diff --git a/tests/suites/alert/alert_test.go b/tests/suites/alert/alert_test.gonew file mode 100644index 0000000000..afc9909fb0--- /dev/null+++ b/tests/suites/alert/alert_test.go@@ -0,0 +1,174 @@+package alert_test++import (+ "encoding/json"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/fakes/webhook"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra/fakenet"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++// Event alerts are dispatched by the event outbox relay after the change commits.+const alertDispatch = 30 * time.Second++func TestAlert_AuthMethodChanged(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should post the change to the webhook when a client secret is added to the identity", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ bot := tn.NewMachineIdentity(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ alertID := newAlert(t, tn.Admin, alertBody{+ Name: "auth changes", ResourceType: identityAuthentication, ResourceID: bot.ID.String(),+ EventType: authMethodChanged, Channels: []channel{webhookChannel(sink.URL)},+ })++ // Action+ addClientSecret(t, tn, bot, "ci-deploy")++ // Assert+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, nil, fakenet.Within(alertDispatch))+ require.Equal(t, http.MethodPost, got.Method)+ var d alertDelivery+ require.NoError(t, json.Unmarshal([]byte(got.Body), &d), got.Body)+ require.Equal(t, "com.infisical.identity.authentication.auth-method-changed", d.Type)+ require.Equal(t, authMethodChanged, d.Subject)+ require.Equal(t, alertID.String(), d.Data.Alert.ID)+ require.Equal(t, bot.Name, d.Data.Items[0].Title)+ fields := fieldsOf(t, d)+ require.Equal(t, "Universal Auth", fields["Auth Method"])+ require.Equal(t, "Credential Added", fields["Change"])+ require.Equal(t, "ci-deploy", fields["Credential"])+ require.Equal(t, tn.Admin.Email+" (user)", fields["Changed By"])+ })++ t.Run("should not post a change to another identity", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ watched := tn.NewMachineIdentity(t)+ other := tn.NewMachineIdentity(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ newAlert(t, tn.Admin, alertBody{+ Name: "auth changes", ResourceType: identityAuthentication, ResourceID: watched.ID.String(),+ EventType: authMethodChanged, Channels: []channel{webhookChannel(sink.URL)},+ })++ // Action+ addClientSecret(t, tn, other, "unwatched")+ addClientSecret(t, tn, watched, "watched")++ // Assert+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, nil, fakenet.Within(alertDispatch))+ require.Contains(t, got.Body, watched.Name)+ sink.ExpectNoEvent[webhook.DeliveryReceived](t, func(d webhook.DeliveryReceived) bool {+ return strings.Contains(d.Body, other.Name)+ })+ })+}++func TestAlert_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a second alert for the same resource and event and keep the first", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ bot := tn.NewMachineIdentity(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ body := alertBody{+ Name: "auth changes", ResourceType: identityAuthentication, ResourceID: bot.ID.String(),+ EventType: authMethodChanged, Channels: []channel{webhookChannel(sink.URL)},+ }+ first := newAlert(t, tn.Admin, body)+ body.Name = "auth changes again"++ // Action+ res := createAlert(t, tn.Admin, body)++ // Assert+ require.Equalf(t, http.StatusBadRequest, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.Equal(t, "An alert for this resource and event already exists", res.JSON400.Message)+ require.Equal(t, []uuid.UUID{first}, alertsOn(t, tn, bot.ID))+ })++ t.Run("should refuse an alert with no channels and store nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ bot := tn.NewMachineIdentity(t)++ // Action+ res := createAlert(t, tn.Admin, alertBody{+ Name: "silent", ResourceType: identityAuthentication, ResourceID: bot.ID.String(),+ EventType: authMethodChanged, Channels: []channel{},+ })++ // Assert+ require.Equalf(t, http.StatusUnprocessableEntity, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.Contains(t, string(res.Body), "channels")+ require.Empty(t, alertsOn(t, tn, bot.ID))+ })++ t.Run("should refuse an expiry alert warning more than 90 days ahead and store nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ bot := tn.NewMachineIdentity(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)++ // Action+ res := createAlert(t, tn.Admin, alertBody{+ Name: "expiry", ResourceType: identityAuthentication, ResourceID: bot.ID.String(),+ EventType: authExpiry, Condition: map[string]any{"alertBefore": "91d"},+ Channels: []channel{webhookChannel(sink.URL)},+ })++ // Assert+ require.Equalf(t, http.StatusBadRequest, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.Equal(t, "Invalid alert condition: Must be a whole number of days from 1d to 90d, e.g. '30d'", res.JSON400.Message)+ require.Empty(t, alertsOn(t, tn, bot.ID))+ })++ t.Run("should keep an expiry alert's lead time and channel", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ bot := tn.NewMachineIdentity(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)++ // Action+ alertID := newAlert(t, tn.Admin, alertBody{+ Name: "expiry", ResourceType: identityAuthentication, ResourceID: bot.ID.String(),+ EventType: authExpiry, Condition: map[string]any{"alertBefore": "7d"},+ Channels: []channel{webhookChannel(sink.URL)},+ })++ // Assert+ got, err := tn.Admin.API.GetAlertByIdWithResponse(t.Context(), alertID)+ require.NoError(t, err)+ require.NotNilf(t, got.JSON200, "reading the alert returned %d: %s", got.StatusCode(), apierr.Body(got.Body))+ require.Equal(t, "scheduled", got.JSON200.Alert.TriggerType)+ require.Equal(t, map[string]any{"alertBefore": "7d"}, got.JSON200.Alert.Condition)+ require.Len(t, got.JSON200.Alert.Channels, 1)+ require.Equal(t, sink.URL, got.JSON200.Alert.Channels[0].Config["url"])+ })+}diff --git a/tests/suites/alert/helpers_test.go b/tests/suites/alert/helpers_test.gonew file mode 100644index 0000000000..05eb6a2382--- /dev/null+++ b/tests/suites/alert/helpers_test.go@@ -0,0 +1,110 @@+package alert_test++import (+ "bytes"+ "encoding/json"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++const (+ identityAuthentication = "identity.authentication"+ authMethodChanged = "identity.authentication.auth-method-changed"+ authExpiry = "identity.authentication.expiry"+)++// alertBody is a create request. Sent as raw JSON so a test can send what the typed+// body would refuse to express, such as an empty channel list.+type alertBody struct {+ Name string `json:"name"`+ ResourceType string `json:"resourceType"`+ ResourceID string `json:"resourceId,omitempty"`+ EventType string `json:"eventType"`+ Condition any `json:"condition,omitempty"`+ Channels []channel `json:"channels"`+}++type channel struct {+ Name string `json:"name"`+ ChannelType string `json:"channelType"`+ Config map[string]any `json:"config"`+}++func webhookChannel(url string) channel {+ return channel{Name: "hook", ChannelType: "webhook", Config: map[string]any{"url": url}}+}++func createAlert(t *testing.T, actor *harness.Principal, body alertBody) *api.CreateAlertResponse {+ t.Helper()+ raw, err := json.Marshal(body)+ require.NoError(t, err)+ res, err := actor.API.CreateAlertWithBodyWithResponse(t.Context(), "application/json", bytes.NewReader(raw))+ require.NoError(t, err)+ return res+}++func newAlert(t *testing.T, actor *harness.Principal, body alertBody) uuid.UUID {+ t.Helper()+ res := createAlert(t, actor, body)+ require.NotNilf(t, res.JSON200, "creating alert %s returned %d: %s", body.Name, res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.Alert.Id+}++func alertsOn(t *testing.T, tn *harness.Tenant, identityID uuid.UUID) []uuid.UUID {+ t.Helper()+ res, err := tn.Admin.API.ListAlertsWithResponse(t.Context(), &api.ListAlertsParams{+ ResourceType: identityAuthentication,+ ResourceId: &identityID,+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "listing alerts: %s", apierr.Body(res.Body))+ out := []uuid.UUID{}+ for _, a := range res.JSON200.Alerts {+ out = append(out, a.Id)+ }+ return out+}++// alertDelivery is the CloudEvents envelope a webhook channel posts.+type alertDelivery struct {+ Type string `json:"type"`+ Subject string `json:"subject"`+ Data struct {+ Alert struct {+ ID string `json:"id"`+ Name string `json:"name"`+ ResourceType string `json:"resourceType"`+ } `json:"alert"`+ Items []struct {+ Title string `json:"title"`+ Fields []struct {+ Label string `json:"label"`+ Value string `json:"value"`+ } `json:"fields"`+ } `json:"items"`+ } `json:"data"`+}++func fieldsOf(t *testing.T, d alertDelivery) map[string]string {+ t.Helper()+ require.Len(t, d.Data.Items, 1)+ out := map[string]string{}+ for _, f := range d.Data.Items[0].Fields {+ out[f.Label] = f.Value+ }+ return out+}++func addClientSecret(t *testing.T, tn *harness.Tenant, identity *harness.Principal, description string) {+ t.Helper()+ res, err := tn.Admin.API.CreateUniversalAuthClientSecretWithResponse(t.Context(), identity.ID.String(),+ api.CreateUniversalAuthClientSecretJSONRequestBody{Description: &description})+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "adding a client secret: %s", apierr.Body(res.Body))+}diff --git a/tests/suites/alert/main_test.go b/tests/suites/alert/main_test.gonew file mode 100644index 0000000000..690c88af2b--- /dev/null+++ b/tests/suites/alert/main_test.go@@ -0,0 +1,9 @@+package alert_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/harness"+)++func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }diff --git a/tests/suites/alert/notification_test.go b/tests/suites/alert/notification_test.gonew file mode 100644index 0000000000..fb72580c47--- /dev/null+++ b/tests/suites/alert/notification_test.go@@ -0,0 +1,199 @@+package alert_test++import (+ "context"+ "fmt"+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/stretchr/testify/require"+)++type notification struct {+ ID string+ Type string+ Title string+ Body string+ IsRead bool+}++func TestUserNotification(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should list an unread notification naming the project when a user is added to it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))++ // Action+ alice := proj.NewUser(t, fixture.WithPrincipalName("alice"))++ // Assert+ got := waitForInvitation(t, alice)+ require.Equal(t, "Project Invitation", got.Title)+ require.Contains(t, got.Body, proj.Name)+ require.False(t, got.IsRead)+ })++ t.Run("should mark every notification read", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ first := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ second := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ alice := first.NewUser(t, fixture.WithPrincipalName("alice"))+ second.Grant(t, alice)+ waitForNotifications(t, alice, 2)++ // Action+ res, err := alice.API.MarkUserNotificationsAsReadWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ got := notifications(t, alice)+ require.Len(t, got, 2)+ for _, n := range got {+ require.Truef(t, n.IsRead, "%q is still unread", n.Title)+ }+ })++ t.Run("should mark one notification read and leave the others unread", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ first := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ second := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ alice := first.NewUser(t, fixture.WithPrincipalName("alice"))+ second.Grant(t, alice)+ all := waitForNotifications(t, alice, 2)++ // Action+ res, err := alice.API.UpdateUserNotificationWithResponse(t.Context(), all[0].ID,+ api.UpdateUserNotificationJSONRequestBody{IsRead: true})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ read := map[string]bool{}+ for _, n := range notifications(t, alice) {+ read[n.ID] = n.IsRead+ }+ require.Equal(t, map[string]bool{all[0].ID: true, all[1].ID: false}, read)+ })++ t.Run("should answer 404 and change nothing when a user marks another user's notification read", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ alice := proj.NewUser(t, fixture.WithPrincipalName("alice"))+ bob := tn.NewUser(t, harness.WithName("bob"))+ theirs := waitForInvitation(t, alice)++ // Action+ res, err := bob.API.UpdateUserNotificationWithResponse(t.Context(), theirs.ID,+ api.UpdateUserNotificationJSONRequestBody{IsRead: true})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusNotFound, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.Equal(t, "Notification not found", apierr.Message(res.Body))+ require.False(t, waitForInvitation(t, alice).IsRead)+ })++ t.Run("should answer 404 and keep it when a user deletes another user's notification", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ alice := proj.NewUser(t, fixture.WithPrincipalName("alice"))+ bob := tn.NewUser(t, harness.WithName("bob"))+ theirs := waitForInvitation(t, alice)++ // Action+ res, err := bob.API.DeleteUserNotificationWithResponse(t.Context(), theirs.ID)++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusNotFound, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.Equal(t, "Notification not found", apierr.Message(res.Body))+ require.Equal(t, theirs.ID, waitForInvitation(t, alice).ID)+ })+}++func listNotifications(ctx context.Context, user *harness.Principal) ([]notification, error) {+ res, err := user.API.ListUserNotificationsWithResponse(ctx)+ if err != nil {+ return nil, err+ }+ if res.JSON200 == nil {+ return nil, fmt.Errorf("listing notifications returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ }+ out := make([]notification, 0, len(res.JSON200.Notifications))+ for _, n := range res.JSON200.Notifications {+ out = append(out, notification{+ ID: n.Id.String(),+ Type: n.Type,+ Title: n.Title,+ Body: deref(n.Body),+ IsRead: deref(n.IsRead),+ })+ }+ return out, nil+}++func notifications(t *testing.T, user *harness.Principal) []notification {+ t.Helper()+ got, err := listNotifications(t.Context(), user)+ require.NoError(t, err)+ return got+}++// waitForNotifications polls until the user holds n notifications. They are written+// from a queue after the response.+func waitForNotifications(t *testing.T, user *harness.Principal, n int) []notification {+ t.Helper()+ got, err := wait.For(t.Context(), func(ctx context.Context) ([]notification, bool, error) {+ got, err := listNotifications(ctx, user)+ return got, len(got) >= n, err+ })+ require.NoErrorf(t, err, "waiting for %d notifications for %s", n, user.Email)+ return got+}++func waitForInvitation(t *testing.T, user *harness.Principal) notification {+ t.Helper()+ got, err := wait.For(t.Context(), func(ctx context.Context) (notification, bool, error) {+ got, err := listNotifications(ctx, user)+ for _, n := range got {+ if n.Type == "project-invitation" && strings.Contains(n.Body, "project") {+ return n, true, nil+ }+ }+ return notification{}, false, err+ })+ require.NoErrorf(t, err, "waiting for a project invitation notification for %s", user.Email)+ return got+}++func deref[T any](p *T) T {+ var zero T+ if p == nil {+ return zero+ }+ return *p+}diff --git a/tests/suites/auditlog/access_test.go b/tests/suites/auditlog/access_test.gonew file mode 100644index 0000000000..43686b4a84--- /dev/null+++ b/tests/suites/auditlog/access_test.go@@ -0,0 +1,79 @@+package auditlog_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/stretchr/testify/require"+)++func TestAuditLog_Access(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a member without audit-log read", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "no-audit", fixture.Permission{Subject: "settings", Action: []string{"read"}})+ member := tn.NewMachineIdentity(t, harness.OrgRole("no-audit"))+ groupID := createGroup(t, tn.Admin, "g-"+id.Short())+ waitForEvents(t, tn.Admin, filter{EventType: new("create-group")}, 1)++ // Action+ res, _, err := listLogs(t.Context(), member.API, filter{EventType: new("create-group")})++ // Assert+ require.Error(t, err)+ require.Equalf(t, http.StatusForbidden, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.NotContains(t, string(res.Body), groupID)+ })++ t.Run("should never return another org's events, even when given that org's project id", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ other := h.NewTenant(t)+ theirs := fixture.NewProject(t, other, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateSecret(t, theirs, "dev", "THEIRS", "v")+ waitForEvents(t, other.Admin, filter{EventType: new("create-secret"), ProjectId: &theirs.ID}, 1)++ // Action+ byProject, _, byProjectErr := listLogs(t.Context(), tn.Admin.API, filter{EventType: new("create-secret"), ProjectId: &theirs.ID})+ orgWide := events(t, tn.Admin, filter{EventType: new("create-secret")})++ // Assert+ require.Error(t, byProjectErr)+ require.Containsf(t, []int{http.StatusForbidden, http.StatusNotFound}, byProject.StatusCode(), "%s", apierr.Body(byProject.Body))+ require.NotContains(t, string(byProject.Body), "THEIRS")+ require.Empty(t, orgWide)+ })++ t.Run("should refuse a project-scoped read without project audit-log read", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ proj.NewRole(t, "secret-reader", fixture.Permission{Subject: "secrets", Action: []string{"read"}})+ reader := tn.NewMachineIdentity(t, harness.OrgRole("member"))+ proj.Grant(t, reader, "secret-reader")+ secretmanager.CreateSecret(t, proj, "dev", "TOKEN", "v")+ waitForEvents(t, tn.Admin, filter{EventType: new("create-secret"), ProjectId: &proj.ID}, 1)++ // Action+ res, _, err := listLogs(t.Context(), reader.API, filter{EventType: new("create-secret"), ProjectId: &proj.ID})++ // Assert+ require.Error(t, err)+ require.Equalf(t, http.StatusForbidden, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.NotContains(t, string(res.Body), "TOKEN")+ })+}diff --git a/tests/suites/auditlog/actor_test.go b/tests/suites/auditlog/actor_test.gonew file mode 100644index 0000000000..1801a9d35e--- /dev/null+++ b/tests/suites/auditlog/actor_test.go@@ -0,0 +1,245 @@+package auditlog_test++import (+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func TestAuditLog_Actor(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should record a user actor with id, email, IP and user agent", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ip := sourceIP()++ // Action+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{Name: new("renamed-" + id.Short())}, from(ip, "terraform"))++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ got := waitForEvents(t, tn.Admin, filter{EventType: new("update-org")}, 1)[0]+ require.Equal(t, "user", got.ActorType)+ require.Equal(t, tn.Admin.ID.String(), got.Actor["userId"])+ require.Equal(t, tn.Admin.Email, got.Actor["email"])+ require.Equal(t, ip, got.IP)+ require.Equal(t, "terraform", got.UserAgent)+ require.Equal(t, "terraform", got.UserAgentType)+ })++ t.Run("should record a machine identity actor with id and name", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ bot := tn.NewMachineIdentity(t, harness.OrgRole("admin"))++ // Action+ groupID := createGroup(t, bot, "by-bot-"+id.Short())++ // Assert+ got := waitForEvent(t, tn.Admin, "create-group", func(e entry) bool { return e.Metadata["groupId"] == groupID })+ require.Equal(t, "identity", got.ActorType)+ require.Equal(t, bot.ID.String(), got.Actor["identityId"])+ require.Equal(t, bot.Name, got.Actor["name"])+ })++ t.Run("should record ORG_ADMIN_BYPASS_SSO and mail the other admins on break-glass", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ saml := sso.NewSAML(t, tn, sso.Okta)+ otherAdmin := tn.NewUser(t, harness.OrgRole("admin"))+ saml.Enforce(t)++ // Action+ res, err := tn.Admin.API.SelectOrganizationV3WithResponse(t.Context(),+ api.SelectOrganizationV3JSONRequestBody{OrganizationId: tn.OrgID.String()})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ got := waitForEvents(t, tn.Admin, filter{EventType: new("org-admin-bypassed-sso")}, 1)+ require.Len(t, got, 1)+ require.Equal(t, "user", got[0].ActorType)+ require.Equal(t, tn.Admin.ID.String(), got[0].Actor["userId"])+ require.Equal(t, tn.Admin.Email, got[0].Actor["email"])+ mail := tn.Mail(t).Expect(t, otherAdmin.Email, smtp.Subject("SSO Bypass"))+ require.Contains(t, mail.Body, tn.Admin.Email)+ })+}++func TestAuditLog_OrgEvents(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should record an org update with the fields that changed", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ name := "renamed-" + id.Short()++ // Action+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{Name: &name})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ got := waitForEvents(t, tn.Admin, filter{EventType: new("update-org")}, 1)+ require.Len(t, got, 1)+ require.Equal(t, name, got[0].Metadata["name"])+ require.Equal(t, "management", got[0].Class)+ })++ t.Run("should record a membership removal with the membership and user", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t, harness.WithName("alice"))+ membership := fixture.MembershipOf(t, tn, alice.Email)++ // Action+ res, err := tn.Admin.API.DeleteOrgMembershipWithResponse(t.Context(), tn.OrgID.String(), membership.ID.String())++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ got := waitForEvents(t, tn.Admin, filter{EventType: new("delete-user-org-membership")}, 1)+ require.Len(t, got, 1)+ require.Equal(t, membership.ID.String(), got[0].Metadata["membershipId"])+ require.Equal(t, alice.ID.String(), got[0].Metadata["userId"])+ require.Equal(t, tn.Admin.ID.String(), got[0].Actor["userId"])+ })++ t.Run("should record an org selection with the org's id and name", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t, harness.WithName("alice"))+ org, err := tn.Admin.API.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ require.NotNil(t, org.JSON200)+ before := len(waitForEvents(t, tn.Admin, selectionsBy(alice), 1))++ // Action+ res, err := alice.API.SelectOrganizationV3WithResponse(t.Context(),+ api.SelectOrganizationV3JSONRequestBody{OrganizationId: tn.OrgID.String()})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ got := waitForEvents(t, tn.Admin, selectionsBy(alice), before+1)+ require.Equal(t, tn.OrgID.String(), got[0].Metadata["organizationId"])+ require.Equal(t, org.JSON200.Organization.Name, got[0].Metadata["organizationName"])+ require.Equal(t, alice.Email, got[0].Actor["email"])+ })++ t.Run("should record a group's creation and a member joining it with readable names", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t, harness.WithName("alice"))++ // Action+ g := fixture.NewGroup(t, tn, fixture.WithGroupRole("member"))+ g.AddUser(t, alice)++ // Assert+ created := waitForEvents(t, tn.Admin, filter{EventType: new("create-group")}, 1)+ require.Len(t, created, 1)+ require.Equal(t, g.ID.String(), created[0].Metadata["groupId"])+ require.Equal(t, g.Name, created[0].Metadata["name"])+ require.Equal(t, g.Slug, created[0].Metadata["slug"])+ require.Equal(t, "member", created[0].Metadata["role"])+ added := waitForEvents(t, tn.Admin, filter{EventType: new("add-user-to-group")}, 1)+ require.Len(t, added, 1)+ require.Equal(t, g.Name, added[0].Metadata["groupName"])+ require.Equal(t, alice.ID.String(), added[0].Metadata["userId"])+ require.True(t, strings.EqualFold(alice.Email, added[0].Metadata["username"].(string)),+ "username %v is not %s", added[0].Metadata["username"], alice.Email)+ })++ t.Run("should record a group linked to a sub-org in the sub-org's log", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ g := fixture.NewGroup(t, tn)++ // Action+ res, err := sub.Admin.API.CreateOrganizationGroupMembershipWithBodyWithResponse(t.Context(), g.ID,+ "application/json", jsonBody(t, map[string]any{"roles": []map[string]any{{"role": "member"}}}))++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ got := waitForEvents(t, sub.Admin, filter{EventType: new("link-group-to-sub-org")}, 1)+ require.Len(t, got, 1)+ require.Equal(t, g.ID.String(), got[0].Metadata["groupId"])+ require.Equal(t, g.Name, got[0].Metadata["groupName"])+ roles, ok := got[0].Metadata["roles"].([]any)+ require.Truef(t, ok, "metadata has no roles: %+v", got[0].Metadata)+ require.Len(t, roles, 1)+ require.Equal(t, "member", roles[0].(map[string]any)["role"])+ require.Empty(t, events(t, tn.Admin, filter{EventType: new("link-group-to-sub-org")}),+ "the link belongs to the sub-org's log, not the root's")+ })+}++func TestAuditLog_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should record an org invitation naming the invitee", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ invitee := tn.Email("invitee")++ // Action+ res, err := tn.Admin.API.InviteUsersToOrganizationWithResponse(t.Context(), api.InviteUsersToOrganizationJSONRequestBody{+ InviteeEmails: []openapi_types.Email{openapi_types.Email(invitee)},+ OrganizationId: tn.OrgID.String(),+ })++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ tn.Mail(t).Expect(t, invitee, smtp.Subject("invitation"))+ waitForEvent(t, tn.Admin, "", func(e entry) bool {+ return e.Type != "view-audit-logs" && strings.Contains(strings.ToLower(jsonString(t, e.Metadata)), invitee)+ })+ })+}++func selectionsBy(user *harness.Principal) filter {+ return filter{+ EventType: new("select-organization"),+ ActorType: new(api.ListOrganizationAuditLogsParamsActorTypeUser),+ Actor: new(user.ID.String()),+ }+}diff --git a/tests/suites/auditlog/filter_test.go b/tests/suites/auditlog/filter_test.gonew file mode 100644index 0000000000..fe0206f9f0--- /dev/null+++ b/tests/suites/auditlog/filter_test.go@@ -0,0 +1,186 @@+package auditlog_test++import (+ "net/http"+ "slices"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/stretchr/testify/require"+)++func TestAuditLog_OrgFilter(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should return only the events of the requested actor type", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ bot := tn.NewMachineIdentity(t, harness.OrgRole("admin"))+ byUser := createGroup(t, tn.Admin, "by-user-"+id.Short())+ byBot := createGroup(t, bot, "by-bot-"+id.Short())+ waitForEvents(t, tn.Admin, filter{EventType: new("create-group")}, 2)++ // Action+ got := events(t, tn.Admin, filter{+ EventType: new("create-group"),+ ActorType: new(api.ListOrganizationAuditLogsParamsActorTypeIdentity),+ })++ // Assert+ require.Equal(t, []any{byBot}, metadataValues(got, "groupId"))+ require.NotContains(t, metadataValues(got, "groupId"), byUser)+ })++ t.Run("should return only the events of the requested user agent type", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fromTerraform := createGroup(t, tn.Admin, "tf-"+id.Short(), userAgent("terraform"))+ createGroup(t, tn.Admin, "other-"+id.Short())+ waitForEvents(t, tn.Admin, filter{EventType: new("create-group")}, 2)++ // Action+ got := events(t, tn.Admin, filter{+ EventType: new("create-group"),+ UserAgentType: new(api.ListOrganizationAuditLogsParamsUserAgentTypeTerraform),+ })++ // Assert+ require.Equal(t, []any{fromTerraform}, metadataValues(got, "groupId"))+ require.Equal(t, "terraform", got[0].UserAgentType)+ })++ t.Run("should return only the events of the requested event class", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ tn.NewMachineIdentity(t)+ createGroup(t, tn.Admin, "g-"+id.Short())+ waitForEvents(t, tn.Admin, filter{EventType: new("login-identity-universal-auth")}, 1)+ waitForEvents(t, tn.Admin, filter{EventType: new("create-group")}, 1)++ // Action+ got := events(t, tn.Admin, filter{EventClass: new("authentication")})++ // Assert+ require.NotEmpty(t, got)+ types := make([]string, 0, len(got))+ for _, e := range got {+ require.Equalf(t, "authentication", e.Class, "%s is not an authentication event", e.Type)+ types = append(types, e.Type)+ }+ require.Contains(t, types, "login-identity-universal-auth")+ require.NotContains(t, types, "create-group")+ })++ t.Run("should return only the events whose metadata matches", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ wanted := "wanted-" + id.Short()+ wantedID := createGroup(t, tn.Admin, wanted)+ createGroup(t, tn.Admin, "other-"+id.Short())+ waitForEvents(t, tn.Admin, filter{EventType: new("create-group")}, 2)++ // Action+ got := events(t, tn.Admin, filter{EventType: new("create-group"), EventMetadata: new("name=" + wanted)})++ // Assert+ require.Equal(t, []any{wantedID}, metadataValues(got, "groupId"))+ })++ t.Run("should return only the events in the date range", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ first := createGroup(t, tn.Admin, "first-"+id.Short())+ earlier := waitForEvents(t, tn.Admin, filter{EventType: new("create-group")}, 1)[0]+ second := createGroup(t, tn.Admin, "second-"+id.Short())+ waitForEvents(t, tn.Admin, filter{EventType: new("create-group")}, 2)+ // createdAt comes back in milliseconds; the stored value can be up to 1ms later.+ cut := earlier.CreatedAt.UTC().Add(time.Millisecond)++ // Action+ before := events(t, tn.Admin, filter{EventType: new("create-group"), EndDate: &cut})+ after := events(t, tn.Admin, filter{EventType: new("create-group"), StartDate: &cut})++ // Assert+ require.Equal(t, []any{first}, metadataValues(before, "groupId"))+ require.Equal(t, []any{second}, metadataValues(after, "groupId"))+ })++ t.Run("should refuse a range that ends before it starts", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ start := time.Now().UTC().Truncate(time.Second)+ end := start.Add(-time.Hour)++ // Action+ res, err := tn.Admin.API.ListOrganizationAuditLogsWithResponse(t.Context(),+ &api.ListOrganizationAuditLogsParams{StartDate: &start, EndDate: &end})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusUnprocessableEntity, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.Contains(t, string(res.Body), "End date cannot be before start date")+ })++ t.Run("should refuse a range longer than 3 months", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ end := time.Now().UTC().Truncate(time.Second)+ start := end.AddDate(0, -3, -1)++ // Action+ res, err := tn.Admin.API.ListOrganizationAuditLogsWithResponse(t.Context(),+ &api.ListOrganizationAuditLogsParams{StartDate: &start, EndDate: &end})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusUnprocessableEntity, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.Contains(t, string(res.Body), "Dates must be within 3 months")+ })++ t.Run("should page with offset and limit without duplicates or gaps", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ for i := range 5 {+ createGroup(t, tn.Admin, "page-"+id.Short()+"-"+string(rune('a'+i)))+ }+ all := waitForEvents(t, tn.Admin, filter{EventType: new("create-group")}, 5)+ require.Len(t, all, 5)++ // Action+ var paged []entry+ for _, offset := range []float32{0, 2, 4, 6} {+ paged = append(paged, events(t, tn.Admin, filter{+ EventType: new("create-group"),+ Offset: new(offset),+ Limit: new(float32(2)),+ })...)+ }++ // Assert+ pagedIDs := ids(paged)+ require.Equal(t, ids(all), pagedIDs)+ slices.Sort(pagedIDs)+ require.Len(t, slices.Compact(pagedIDs), 5)+ })+}diff --git a/tests/suites/auditlog/helpers_test.go b/tests/suites/auditlog/helpers_test.gonew file mode 100644index 0000000000..3cc32dacc5--- /dev/null+++ b/tests/suites/auditlog/helpers_test.go@@ -0,0 +1,187 @@+package auditlog_test++import (+ "bytes"+ "context"+ "crypto/rand"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/stretchr/testify/require"+)++type entry struct {+ ID string+ Type string+ Class string+ ActorType string+ Actor map[string]any+ Metadata map[string]any+ IP string+ UserAgent string+ UserAgentType string+ ProjectID string+ CreatedAt time.Time+}++type filter = api.ListOrganizationAuditLogsParams++// withDefaults bounds a read to the last hour. The API otherwise starts at the last+// midnight UTC, which a run crossing midnight would fall on the wrong side of.+func withDefaults(f filter) filter {+ if f.StartDate == nil {+ f.StartDate = new(time.Now().UTC().Add(-time.Hour).Truncate(time.Second))+ }+ if f.Limit == nil {+ f.Limit = new(float32(100))+ }+ return f+}++func listLogs(ctx context.Context, actor *api.ClientWithResponses, f filter) (*api.ListOrganizationAuditLogsResponse, []entry, error) {+ f = withDefaults(f)+ res, err := actor.ListOrganizationAuditLogsWithResponse(ctx, &f)+ if err != nil {+ return nil, nil, err+ }+ if res.JSON200 == nil {+ return res, nil, fmt.Errorf("listing audit logs returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ }+ out := make([]entry, 0, len(res.JSON200.AuditLogs))+ for _, l := range res.JSON200.AuditLogs {+ actorMeta, _ := l.Actor.Metadata.(map[string]any)+ metadata, _ := l.Event.Metadata.(map[string]any)+ out = append(out, entry{+ ID: l.Id.String(),+ Type: l.Event.Type,+ Class: string(l.Event.Class),+ ActorType: l.Actor.Type,+ Actor: actorMeta,+ Metadata: metadata,+ IP: deref(l.IpAddress),+ UserAgent: deref(l.UserAgent),+ UserAgentType: deref(l.UserAgentType),+ ProjectID: deref(l.ProjectId),+ CreatedAt: l.CreatedAt,+ })+ }+ return res, out, nil+}++// events reads the log once, as the given principal.+func events(t *testing.T, actor *harness.Principal, f filter) []entry {+ t.Helper()+ _, got, err := listLogs(t.Context(), actor.API, f)+ require.NoError(t, err)+ return got+}++// waitForEvents polls until at least n events match. Audit logs are written from a+// queue drained every few seconds, so a read right after the action is empty.+func waitForEvents(t *testing.T, actor *harness.Principal, f filter, n int) []entry {+ t.Helper()+ got, err := wait.For(t.Context(), func(ctx context.Context) ([]entry, bool, error) {+ _, evs, err := listLogs(ctx, actor.API, f)+ return evs, len(evs) >= n, err+ })+ require.NoErrorf(t, err, "waiting for %d audit events of type %v", n, deref(f.EventType))+ return got+}++// waitForEvent polls until an event of the type, or of any type when it is empty,+// passes match.+func waitForEvent(t *testing.T, actor *harness.Principal, eventType string, match func(entry) bool) entry {+ t.Helper()+ f := filter{}+ if eventType != "" {+ f.EventType = &eventType+ }+ got, err := wait.For(t.Context(), func(ctx context.Context) (entry, bool, error) {+ _, evs, err := listLogs(ctx, actor.API, f)+ for _, e := range evs {+ if match(e) {+ return e, true, nil+ }+ }+ return entry{}, false, err+ })+ require.NoErrorf(t, err, "waiting for a %s audit event", eventType)+ return got+}++func ids(evs []entry) []string {+ out := make([]string, 0, len(evs))+ for _, e := range evs {+ out = append(out, e.ID)+ }+ return out+}++func metadataValues(evs []entry, key string) []any {+ out := make([]any, 0, len(evs))+ for _, e := range evs {+ out = append(out, e.Metadata[key])+ }+ return out+}++func deref[T any](p *T) T {+ var zero T+ if p == nil {+ return zero+ }+ return *p+}++func jsonString(t *testing.T, v any) string {+ t.Helper()+ raw, err := json.Marshal(v)+ require.NoError(t, err)+ return string(raw)+}++func jsonBody(t *testing.T, v any) io.Reader {+ t.Helper()+ raw, err := json.Marshal(v)+ require.NoError(t, err)+ return bytes.NewReader(raw)+}++// from sends one call as if from another address and client, for claims about what+// the log records of the caller.+func from(ip, userAgent string) api.RequestEditorFn {+ return func(_ context.Context, req *http.Request) error {+ req.Header.Set("X-Forwarded-For", ip)+ req.Header.Set("User-Agent", userAgent)+ return nil+ }+}++func userAgent(ua string) api.RequestEditorFn {+ return func(_ context.Context, req *http.Request) error {+ req.Header.Set("User-Agent", ua)+ return nil+ }+}++func sourceIP() string {+ b := make([]byte, 3)+ _, _ = rand.Read(b)+ return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])+}++func createGroup(t *testing.T, actor *harness.Principal, name string, editors ...api.RequestEditorFn) string {+ t.Helper()+ res, err := actor.API.CreateGroupWithResponse(t.Context(), api.CreateGroupJSONRequestBody{Name: name}, editors...)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "creating group %s returned %d: %s", name, res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.Id.String()+}diff --git a/tests/suites/auditlog/main_test.go b/tests/suites/auditlog/main_test.gonew file mode 100644index 0000000000..b2ad982946--- /dev/null+++ b/tests/suites/auditlog/main_test.go@@ -0,0 +1,9 @@+package auditlog_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/harness"+)++func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }diff --git a/tests/suites/auditlog/settings_test.go b/tests/suites/auditlog/settings_test.gonew file mode 100644index 0000000000..93023e677f--- /dev/null+++ b/tests/suites/auditlog/settings_test.go@@ -0,0 +1,94 @@+package auditlog_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++type classSetting struct {+ EventClass string `json:"eventClass"`+ IsEnabled bool `json:"isEnabled"`+}++func TestAuditLog_OrgEventClasses(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ refusals := []struct {+ name string+ classes []classSetting+ message string+ }{+ {+ name: "should refuse the management class and keep the current settings",+ classes: []classSetting{+ {"management", false}, {"authentication", true}, {"authorization", false},+ },+ message: "Event class 'management' is always recorded and cannot be changed",+ },+ {+ name: "should refuse the data-access class and keep the current settings",+ classes: []classSetting{+ {"data-access", false}, {"authentication", true}, {"authorization", false},+ },+ message: "Event class 'data-access' is always recorded and cannot be changed",+ },+ {+ name: "should refuse a class sent twice and keep the current settings",+ classes: []classSetting{+ {"authentication", true}, {"authentication", false}, {"authorization", false},+ },+ message: "Event class 'authentication' appears more than once",+ },+ {+ name: "should refuse settings missing a configurable class and keep the current settings",+ classes: []classSetting{{"authentication", true}},+ message: "Every event class except management and data-access must be included. Missing: authorization",+ },+ }+ for _, tc := range refusals {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ saveOrgClasses(t, tn, classSetting{"authentication", false}, classSetting{"authorization", false})++ // Action+ res, err := tn.Admin.API.UpdateOrganizationAuditLogSettingsWithBodyWithResponse(t.Context(),+ "application/json", jsonBody(t, map[string]any{"eventClasses": tc.classes}))++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusBadRequest, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.Equal(t, tc.message, res.JSON400.Message)+ require.Equal(t, map[string]bool{+ "management": true, "authentication": false, "data-access": true, "authorization": false,+ }, orgClasses(t, tn))+ })+ }+}++func saveOrgClasses(t *testing.T, tn *harness.Tenant, classes ...classSetting) {+ t.Helper()+ res, err := tn.Admin.API.UpdateOrganizationAuditLogSettingsWithBodyWithResponse(t.Context(),+ "application/json", jsonBody(t, map[string]any{"eventClasses": classes}))+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "saving org audit log settings: %s", apierr.Body(res.Body))+}++func orgClasses(t *testing.T, tn *harness.Tenant) map[string]bool {+ t.Helper()+ res, err := tn.Admin.API.GetOrganizationAuditLogSettingsWithResponse(t.Context())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "reading org audit log settings returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ out := map[string]bool{}+ for _, c := range res.JSON200.AuditLogSettings.EventClasses {+ out[string(c.EventClass)] = c.IsEnabled+ }+ return out+}diff --git a/tests/suites/auditlog/stream_helpers_test.go b/tests/suites/auditlog/stream_helpers_test.gonew file mode 100644index 0000000000..3362dc6833--- /dev/null+++ b/tests/suites/auditlog/stream_helpers_test.go@@ -0,0 +1,153 @@+package auditlog_test++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "slices"+ "strings"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/fakes/webhook"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++type header struct {+ Key string `json:"key"`+ Value string `json:"value"`+}++type streamOpts struct {+ headers []header+ products []string+}++type streamOpt func(*streamOpts)++func withHeader(key, value string) streamOpt {+ return func(o *streamOpts) { o.headers = append(o.headers, header{key, value}) }+}++func withProducts(products ...string) streamOpt {+ return func(o *streamOpts) { o.products = products }+}++func customStreamBody(url string, opts ...streamOpt) map[string]any {+ o := streamOpts{headers: []header{}}+ for _, opt := range opts {+ opt(&o)+ }+ body := map[string]any{"credentials": map[string]any{"url": url, "headers": o.headers}}+ if o.products != nil {+ body["filters"] = map[string]any{"products": o.products}+ }+ return body+}++func createCustomStream(t *testing.T, actor *harness.Principal, url string, opts ...streamOpt) (int, []byte) {+ t.Helper()+ res, err := actor.API.CreateCustomAuditLogStreamWithBodyWithResponse(t.Context(), "application/json",+ jsonBody(t, customStreamBody(url, opts...)))+ require.NoError(t, err)+ return res.StatusCode(), res.Body+}++// newCustomStream creates a stream and returns its id. Creation sends a test delivery,+// so the sink has to answer it.+func newCustomStream(t *testing.T, tn *harness.Tenant, sink *fixture.WebhookSink, opts ...streamOpt) uuid.UUID {+ t.Helper()+ res, err := tn.Admin.API.CreateCustomAuditLogStreamWithBodyWithResponse(t.Context(), "application/json",+ jsonBody(t, customStreamBody(sink.URL, opts...)))+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "creating a stream returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.AuditLogStream.Id+}++// streams lists the org's streams as raw objects: the list is a union of every+// provider's shape.+func streams(t *testing.T, tn *harness.Tenant) []map[string]any {+ t.Helper()+ res, err := tn.Admin.API.ListAuditLogStreamsWithResponse(t.Context())+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "listing streams: %s", apierr.Body(res.Body))+ var out struct {+ AuditLogStreams []map[string]any `json:"auditLogStreams"`+ }+ require.NoError(t, json.Unmarshal(res.Body, &out))+ return out.AuditLogStreams+}++// streamedLog is one audit log as a stream delivers it.+type streamedLog struct {+ ID string `json:"id"`+ OrgID string `json:"orgId"`+ EventType string `json:"eventType"`+ EventMetadata map[string]any `json:"eventMetadata"`+}++// batch decodes a delivery as a batch of logs. The test delivery sent on create and+// update is a single object, so it is not a batch.+func batch(body string) ([]streamedLog, bool) {+ var logs []streamedLog+ if json.Unmarshal([]byte(body), &logs) != nil {+ return nil, false+ }+ return logs, true+}++// carries matches a batch holding an event of the type whose metadata field has the+// value.+func carries(eventType, field, value string) func(webhook.DeliveryReceived) bool {+ return func(d webhook.DeliveryReceived) bool {+ logs, ok := batch(d.Body)+ return ok && slices.ContainsFunc(logs, func(l streamedLog) bool {+ return l.EventType == eventType && l.EventMetadata[field] == value+ })+ }+}++func isPing(d webhook.DeliveryReceived) bool {+ return strings.Contains(d.Body, `"ping":"ok"`)+}++// waitForDelivered polls the sink until every group name has arrived in a batch the+// sink answered with 200, and returns those deliveries.+func waitForDelivered(t *testing.T, sink *fixture.WebhookSink, names ...string) []webhook.Delivery {+ t.Helper()+ got, err := wait.For(t.Context(), func(context.Context) ([]webhook.Delivery, bool, error) {+ var hits []webhook.Delivery+ seen := map[string]bool{}+ for _, d := range sink.Deliveries(t) {+ logs, ok := batch(d.Body)+ if !ok || d.Status != http.StatusOK {+ continue+ }+ hit := false+ for _, l := range logs {+ name, _ := l.EventMetadata["name"].(string)+ if l.EventType == "create-group" && slices.Contains(names, name) {+ seen[name] = true+ hit = true+ }+ }+ if hit {+ hits = append(hits, d)+ }+ }+ return hits, len(seen) == len(names), nil+ }, wait.Timeout(45*time.Second))+ require.NoErrorf(t, err, "waiting for groups %v to be streamed", names)+ return got+}++func deliveryOf(t *testing.T, d webhook.Delivery) string {+ t.Helper()+ return fmt.Sprintf("%s %s answered %d: %s", d.Method, d.Path, d.Status, d.Body)+}diff --git a/tests/suites/auditlog/stream_test.go b/tests/suites/auditlog/stream_test.gonew file mode 100644index 0000000000..a80aca0d5d--- /dev/null+++ b/tests/suites/auditlog/stream_test.go@@ -0,0 +1,349 @@+package auditlog_test++import (+ "context"+ "net/http"+ "slices"+ "strings"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fakes/webhook"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra/fakenet"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/stretchr/testify/require"+)++// A stream delivers about 5s after the log is written (the write queue's tick) plus+// a 5s flush debounce.+const streamDelivery = 30 * time.Second++func TestAuditLogStream_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse when the plan does not include streams", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.AuditLogStreams)))+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)++ // Action+ status, body := createCustomStream(t, tn.Admin, sink.URL)++ // Assert+ require.Equalf(t, http.StatusBadRequest, status, "%s", apierr.Body(body))+ require.Equal(t, "Failed to create Audit Log Stream: Plan restriction. Upgrade plan to continue.", apierr.Message(body))+ require.Empty(t, streams(t, tn))+ })++ t.Run("should refuse a stream past the plan's stream limit and keep the existing one", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().With(license.AuditLogStreamLimit, 1)))+ first := fixture.NewWebhookSink(t, tn, webhook.Service)+ second := fixture.NewWebhookSink(t, tn, webhook.Service)+ kept := newCustomStream(t, tn, first)++ // Action+ status, body := createCustomStream(t, tn.Admin, second.URL)++ // Assert+ require.Equalf(t, http.StatusBadRequest, status, "%s", apierr.Body(body))+ require.Equal(t, "Failed to create Audit Log Stream: Plan limit reached. Contact Infisical to increase quota.", apierr.Message(body))+ got := streams(t, tn)+ require.Len(t, got, 1)+ require.Equal(t, kept.String(), got[0]["id"])+ })++ t.Run("should refuse a URL whose test delivery fails and store nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ sink.Seed(t, webhook.Respond(http.StatusInternalServerError))++ // Action+ status, body := createCustomStream(t, tn.Admin, sink.URL)++ // Assert+ require.Equalf(t, http.StatusBadRequest, status, "%s", apierr.Body(body))+ require.True(t, strings.HasPrefix(apierr.Message(body), "Failed to connect with upstream source"), apierr.Message(body))+ require.Empty(t, streams(t, tn))+ })++ t.Run("should refuse a header value with CR or LF and store nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)++ // Action+ status, body := createCustomStream(t, tn.Admin, sink.URL, withHeader("X-Injected", "a\r\nX-Evil: b"))++ // Assert+ require.Equalf(t, http.StatusUnprocessableEntity, status, "%s", apierr.Body(body))+ require.Contains(t, string(body), "Header values cannot contain newlines or carriage returns")+ require.Empty(t, streams(t, tn))+ sink.ExpectNoEvent[webhook.DeliveryReceived](t, nil)+ })++ t.Run("should refuse a member without settings create and store nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)++ // Action+ status, body := createCustomStream(t, member, sink.URL)++ // Assert+ require.Equalf(t, http.StatusForbidden, status, "%s", apierr.Body(body))+ require.Empty(t, streams(t, tn))+ sink.ExpectNoEvent[webhook.DeliveryReceived](t, nil)+ })+}++func TestAuditLogStream_Credentials(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should mask custom header values in every read", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ secret := "hdr-" + id.Short() + id.Short()++ // Action+ created, err := tn.Admin.API.CreateCustomAuditLogStreamWithBodyWithResponse(t.Context(), "application/json",+ jsonBody(t, customStreamBody(sink.URL, withHeader("X-Stream-Token", secret))))+ require.NoError(t, err)+ require.NotNilf(t, created.JSON200, "creating a stream returned %d: %s", created.StatusCode(), apierr.Body(created.Body))+ got, err := tn.Admin.API.GetCustomAuditLogStreamWithResponse(t.Context(), created.JSON200.AuditLogStream.Id)+ require.NoError(t, err)+ require.NotNilf(t, got.JSON200, "reading the stream returned %d: %s", got.StatusCode(), apierr.Body(got.Body))+ listed := streams(t, tn)++ // Assert+ require.Equal(t, "******", created.JSON200.AuditLogStream.Credentials.Headers[0].Value)+ require.Equal(t, "******", got.JSON200.AuditLogStream.Credentials.Headers[0].Value)+ require.Len(t, listed, 1)+ for name, body := range map[string]string{+ "create": string(created.Body), "get": string(got.Body), "list": jsonString(t, listed),+ } {+ require.NotContainsf(t, body, secret, "%s revealed the header value", name)+ require.Containsf(t, body, "X-Stream-Token", "%s dropped the header key", name)+ }+ })++ t.Run("should omit a Datadog token in every read", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ token := strings.Repeat("ab12", 8)++ // Action+ created, err := tn.Admin.API.CreateDatadogAuditLogStreamWithBodyWithResponse(t.Context(), "application/json",+ jsonBody(t, map[string]any{"credentials": map[string]any{"url": sink.URL, "token": token}}))+ require.NoError(t, err)+ require.NotNilf(t, created.JSON200, "creating a stream returned %d: %s", created.StatusCode(), apierr.Body(created.Body))+ got, err := tn.Admin.API.GetDatadogAuditLogStreamWithResponse(t.Context(), created.JSON200.AuditLogStream.Id)+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, got.StatusCode(), "reading the stream: %s", apierr.Body(got.Body))+ listed := streams(t, tn)++ // Assert+ require.Equal(t, token, sink.ExpectEvent[webhook.DeliveryReceived](t, isPing).Header.Get("DD-API-KEY"),+ "the test delivery should carry the token")+ require.Len(t, listed, 1)+ for name, body := range map[string]string{+ "create": string(created.Body), "get": string(got.Body), "list": jsonString(t, listed),+ } {+ require.NotContainsf(t, body, token, "%s revealed the token", name)+ require.Containsf(t, body, sink.URL, "%s dropped the URL", name)+ }+ })++ t.Run("should keep a masked header's stored value when it is sent back on update", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ secret := "hdr-" + id.Short() + id.Short()+ streamID := newCustomStream(t, tn, sink, withHeader("X-Stream-Token", secret))+ mark := sink.Mark(t)++ // Action+ res, err := tn.Admin.API.UpdateCustomAuditLogStreamWithBodyWithResponse(t.Context(), streamID, "application/json",+ jsonBody(t, customStreamBody(sink.URL, withHeader("X-Stream-Token", "******"))))++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ ping := sink.ExpectEvent[webhook.DeliveryReceived](t, isPing, fakenet.Since(mark))+ require.Equal(t, secret, ping.Header.Get("X-Stream-Token"))+ name := "after-update-" + id.Short()+ createGroup(t, tn.Admin, name)+ streamed := sink.ExpectEvent[webhook.DeliveryReceived](t, carries("create-group", "name", name), fakenet.Within(streamDelivery))+ require.Equal(t, secret, streamed.Header.Get("X-Stream-Token"))+ })+}++func TestAuditLogStream_Delivery(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should deliver events in batches with the configured headers", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ newCustomStream(t, tn, sink, withHeader("X-Stream-Token", "configured"))+ first, second := "first-"+id.Short(), "second-"+id.Short()++ // Action+ createGroup(t, tn.Admin, first)+ createGroup(t, tn.Admin, second)++ // Assert+ got := waitForDelivered(t, sink, first, second)+ for _, d := range got {+ require.Equal(t, http.MethodPost, d.Method, deliveryOf(t, d))+ require.Equal(t, "configured", d.Header.Get("X-Stream-Token"), deliveryOf(t, d))+ require.Contains(t, d.Header.Get("Content-Type"), "application/json", deliveryOf(t, d))+ logs, _ := batch(d.Body)+ for _, l := range logs {+ require.Equal(t, tn.OrgID.String(), l.OrgID, deliveryOf(t, d))+ }+ }+ })++ t.Run("should deliver only the products in the filter", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ newCustomStream(t, tn, sink, withProducts("secret-manager"))+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ orgLevel := "org-level-" + id.Short()+ createGroup(t, tn.Admin, orgLevel)+ waitForEvent(t, tn.Admin, "create-group", func(e entry) bool { return e.Metadata["name"] == orgLevel })++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "STREAMED", "v")++ // Assert+ sink.ExpectEvent[webhook.DeliveryReceived](t, carries("create-secret", "secretKey", "STREAMED"), fakenet.Within(streamDelivery))+ sink.ExpectNoEvent[webhook.DeliveryReceived](t, carries("create-group", "name", orgLevel))+ })++ t.Run("should retry a batch the receiver answered with 500 and deliver it once it recovers", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `One delivery attempt is four POSTs: the HTTP client itself retries a 5xx three+ times within about a second. Only once all four fail does the outbox schedule the+ batch again, after a 30s backoff plus up to 15s of jitter, and only a later flush+ picks it up, so the test keeps writing events to wake the stream.`)++ // Setup+ tn := h.NewTenant(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ newCustomStream(t, tn, sink)+ sink.Seed(t, webhook.Respond(http.StatusInternalServerError))+ name := "retried-" + id.Short()+ createGroup(t, tn.Admin, name)+ refused := func(d webhook.DeliveryReceived) bool {+ return d.Status == http.StatusInternalServerError && carries("create-group", "name", name)(d)+ }+ sink.ExpectEvent[webhook.DeliveryReceived](t, refused, fakenet.Within(streamDelivery))+ for range 3 {+ sink.ExpectEvent[webhook.DeliveryReceived](t, refused)+ }++ // Action+ sink.Seed(t, webhook.Respond(http.StatusOK))++ // Assert+ delivered, err := wait.For(t.Context(), func(ctx context.Context) (int, bool, error) {+ _, _, err := listLogs(ctx, tn.Admin.API, filter{EventType: new("view-audit-logs")})+ n := 0+ for _, d := range sink.Deliveries(t) {+ if d.Status == http.StatusOK && carries("create-group", "name", name)(webhook.DeliveryReceived{Delivery: d}) {+ n+++ }+ }+ return n, n > 0, err+ }, wait.Timeout(75*time.Second), wait.Interval(3*time.Second))+ require.NoError(t, err, "the failed batch was never delivered after the receiver recovered")+ require.Equal(t, 1, delivered, "the recovered batch was delivered more than once")+ })++ t.Run("should stop delivering once the stream is deleted", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ streamID := newCustomStream(t, tn, sink)+ before := "before-" + id.Short()+ createGroup(t, tn.Admin, before)+ sink.ExpectEvent[webhook.DeliveryReceived](t, carries("create-group", "name", before), fakenet.Within(streamDelivery))++ // Action+ res, err := tn.Admin.API.DeleteCustomAuditLogStreamWithResponse(t.Context(), streamID)++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.Empty(t, streams(t, tn))+ after := "after-" + id.Short()+ createGroup(t, tn.Admin, after)+ waitForEvent(t, tn.Admin, "create-group", func(e entry) bool { return e.Metadata["name"] == after })+ sink.ExpectNoEvent[webhook.DeliveryReceived](t, carries("create-group", "name", after), fakenet.Within(12*time.Second))+ })++ t.Run("should never deliver another org's events", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ other := h.NewTenant(t)+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)+ newCustomStream(t, tn, sink)+ theirs := "theirs-" + id.Short()+ createGroup(t, other.Admin, theirs)+ waitForEvent(t, other.Admin, "create-group", func(e entry) bool { return e.Metadata["name"] == theirs })++ // Action+ ours := "ours-" + id.Short()+ createGroup(t, tn.Admin, ours)++ // Assert+ sink.ExpectEvent[webhook.DeliveryReceived](t, carries("create-group", "name", ours), fakenet.Within(streamDelivery))+ sink.ExpectNoEvent[webhook.DeliveryReceived](t, func(d webhook.DeliveryReceived) bool {+ logs, _ := batch(d.Body)+ return strings.Contains(d.Body, theirs) || slices.ContainsFunc(logs, func(l streamedLog) bool {+ return l.OrgID == other.OrgID.String()+ })+ })+ })+}diff --git a/tests/suites/gateway/connect_test.go b/tests/suites/gateway/connect_test.gonew file mode 100644index 0000000000..6d21f569b6--- /dev/null+++ b/tests/suites/gateway/connect_test.go@@ -0,0 +1,228 @@+package gateway_test++import (+ "crypto/x509"+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+ "golang.org/x/crypto/ssh"+)++func TestGatewayConnect_Certificates(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a one-day server certificate naming the gateway, from the organization's gateway CA", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := newRelay(t, tn)+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)++ // Action+ res := connectGateway(t, running, api.ConnectGatewayJSONRequestBody{RelayName: &relay.Name})++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ cert := parseCert(t, res.JSON200.Pki.ServerCertificate)+ require.WithinDuration(t, time.Now().Add(24*time.Hour), cert.NotAfter, 10*time.Minute)+ require.Len(t, cert.URIs, 1)+ require.Equal(t, "urn:infisical:gateway:"+gw.ID.String(), cert.URIs[0].String())+ require.Equal(t, "Infisical Gateway Server CA", cert.Issuer.CommonName)+ require.Equal(t, []string{tn.OrgID.String()}, cert.Issuer.Organization)+ connectedRoot(t, tn, res)+ })++ t.Run("should issue an ssh user certificate naming the gateway for its relay", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := newRelay(t, tn)+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)++ // Action+ res := connectGateway(t, running, api.ConnectGatewayJSONRequestBody{RelayName: &relay.Name})++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.NotNil(t, res.JSON200.Ssh)+ require.Equal(t, relay.Host, *res.JSON200.RelayHost)+ key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(res.JSON200.Ssh.ClientCertificate))+ require.NoError(t, err)+ cert, ok := key.(*ssh.Certificate)+ require.True(t, ok, "not an ssh certificate: %s", res.JSON200.Ssh.ClientCertificate)+ require.Equal(t, uint32(ssh.UserCert), cert.CertType)+ require.Contains(t, cert.ValidPrincipals, gw.ID.String())+ })++ t.Run("should issue certificates under a different CA for another organization", func(t *testing.T) {+ t.Parallel()++ // Setup+ first, second := h.NewTenant(t), h.NewTenant(t)+ firstRoot := connectedRoot(t, first, connectNewGateway(t, first))+ secondGateway := newGateway(t, second)+ secondRelay := newRelay(t, second)+ running := enrollGateway(t, second, secondGateway.ID)++ // Action+ res := connectGateway(t, running, api.ConnectGatewayJSONRequestBody{RelayName: &secondRelay.Name})++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.NotEqual(t, firstRoot.Raw, connectedRoot(t, second, res).Raw)+ require.Equal(t, []string{second.OrgID.String()}, parseCert(t, res.JSON200.Pki.ServerCertificate).Issuer.Organization)+ })+}++func TestGatewayConnect_Transport(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a direct address on Infisical Cloud and leave the gateway unrouted", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)+ address := "gateway.example.test:8443"++ // Action+ res := connectGateway(t, running, api.ConnectGatewayJSONRequestBody{DirectAddress: &address})++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Direct gateway connections are not available on Infisical Cloud", apierr.Message(res.Body))+ require.Nil(t, getGateway(t, tn, gw.ID).RelayID)+ })++ t.Run("should answer 404 for a relay that does not exist", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)+ missing := relayName()++ // Action+ res := connectGateway(t, running, api.ConnectGatewayJSONRequestBody{RelayName: &missing})++ // Assert+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Nil(t, getGateway(t, tn, gw.ID).RelayID)+ })++ t.Run("should answer 404 for another organization's relay", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ theirs := newRelay(t, h.NewTenant(t))+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)++ // Action+ res := connectGateway(t, running, api.ConnectGatewayJSONRequestBody{RelayName: &theirs.Name})++ // Assert+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Nil(t, getGateway(t, tn, gw.ID).RelayID)+ })++ t.Run("should answer 404 when a gateway with no relay names no transport", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)++ // Action+ res := connectGateway(t, running, api.ConnectGatewayJSONRequestBody{})++ // Assert+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "No connection transport associated with this gateway", apierr.Message(res.Body))+ })++ t.Run("should list the gateway under its relay once connected", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := newRelay(t, tn)+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)++ // Action+ connected := connectGateway(t, running, api.ConnectGatewayJSONRequestBody{RelayName: &relay.Name})++ // Assert+ requireStatus(t, http.StatusOK, connected.StatusCode(), connected.Body)+ res, err := tn.Admin.API.ListRelayGatewaysWithResponse(t.Context(), relay.ID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Len(t, *res.JSON200, 1)+ require.Equal(t, gw.ID.String(), (*res.JSON200)[0].Id)+ require.Equal(t, relay.ID, *getGateway(t, tn, gw.ID).RelayID)+ })+}++func TestGatewayConnect_Heartbeat(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should report the gateway unreachable and zero its heartbeat ttl when nothing answers the probe", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := newRelay(t, tn)+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)+ connected := connectGateway(t, running, api.ConnectGatewayJSONRequestBody{RelayName: &relay.Name})+ requireStatus(t, http.StatusOK, connected.StatusCode(), connected.Body)++ // Action+ res, err := running.API.GatewayHeartbeatWithBodyWithResponse(t.Context(), "application/json", jsonBody(t, map[string]any{}))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ stored := getGateway(t, tn, gw.ID)+ require.NotNil(t, stored.HeartbeatTTL)+ require.Zero(t, *stored.HeartbeatTTL)+ require.Nil(t, stored.Heartbeat)+ })+}++// connectNewGateway enrolls a new gateway and connects it through a new relay.+func connectNewGateway(t *testing.T, tn *harness.Tenant) *api.ConnectGatewayResponse {+ t.Helper()+ relay := newRelay(t, tn)+ res := connectGateway(t, enrollGateway(t, tn, newGateway(t, tn).ID), api.ConnectGatewayJSONRequestBody{RelayName: &relay.Name})+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return res+}++// connectedRoot is the organization's gateway root CA, the last certificate of the chain+// connect hands the gateway, checked to belong to that organization.+func connectedRoot(t *testing.T, tn *harness.Tenant, res *api.ConnectGatewayResponse) *x509.Certificate {+ t.Helper()+ chain := parseChain(t, res.JSON200.Pki.ClientCertificateChain)+ root := chain[len(chain)-1]+ require.Equal(t, "Infisical Gateway Root CA", root.Subject.CommonName)+ require.Equal(t, []string{tn.OrgID.String()}, root.Subject.Organization)+ return root+}diff --git a/tests/suites/gateway/enrollment_test.go b/tests/suites/gateway/enrollment_test.gonew file mode 100644index 0000000000..4c820f31d1--- /dev/null+++ b/tests/suites/gateway/enrollment_test.go@@ -0,0 +1,304 @@+package gateway_test++import (+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestGatewayEnrollment_Token(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should mint a gwe_ token that expires in an hour", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)++ // Action+ res, err := tn.Admin.API.MintGatewayEnrollmentTokenWithResponse(t.Context(), gw.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.True(t, strings.HasPrefix(res.JSON200.Token, "gwe_"), "token %q", res.JSON200.Token)+ require.WithinDuration(t, time.Now().Add(time.Hour), res.JSON200.ExpiresAt, 2*time.Minute)+ })++ t.Run("should log the gateway in with its enrollment token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ token := enrollmentToken(t, tn, gw.ID)++ // Action+ res := loginGateway(t, tn, token)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, gw.ID.String(), res.JSON200.GatewayId)+ require.EqualValues(t, "Bearer", res.JSON200.TokenType)+ status, body := gatewayTokenStatus(t, agent{API: tn.Client(t, res.JSON200.AccessToken)})+ requireStatus(t, http.StatusOK, status, body)+ })++ t.Run("should refuse an enrollment token that was already used", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ token := enrollmentToken(t, tn, gw.ID)+ first := loginGateway(t, tn, token)+ requireStatus(t, http.StatusOK, first.StatusCode(), first.Body)++ // Action+ res := loginGateway(t, tn, token)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Invalid enrollment token", apierr.Message(res.Body))+ status, body := gatewayTokenStatus(t, agent{API: tn.Client(t, first.JSON200.AccessToken)})+ requireStatus(t, http.StatusOK, status, body)+ })++ t.Run("should refuse a relay enrollment token at gateway login and leave it usable for the relay", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ newGateway(t, tn)+ relay := newRelay(t, tn)+ token := relayToken(t, tn, relay.ID)++ // Action+ res := loginGateway(t, tn, token)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Enrollment token belongs to a relay, not a gateway", apierr.Message(res.Body))+ relayLogin := loginRelay(t, tn, token)+ requireStatus(t, http.StatusOK, relayLogin.StatusCode(), relayLogin.Body)+ })++ t.Run("should refuse a token Infisical never issued", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ newGateway(t, tn)++ // Action+ res := loginGateway(t, tn, "gwe_not-a-real-token")++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Invalid enrollment token", apierr.Message(res.Body))+ })++ t.Run("should refuse minting an enrollment token for a gateway on aws auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ created := createGateway(t, tn.Admin.API, gatewayName(), awsAuth())+ requireStatus(t, http.StatusOK, created.StatusCode(), created.Body)+ gw := decodeGateway(t, created.Body)++ // Action+ res, err := tn.Admin.API.MintGatewayEnrollmentTokenWithResponse(t.Context(), gw.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "not configured for token authentication")+ require.False(t, getGateway(t, tn, gw.ID).CanRevoke)+ })+}++func TestGatewayEnrollment_Revoke(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse the gateway's access token on its next request once the gateway is revoked", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)++ // Action+ res, err := tn.Admin.API.RevokeGatewayAccessWithResponse(t.Context(), gw.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ status, body := gatewayTokenStatus(t, running)+ requireStatus(t, http.StatusUnauthorized, status, body)+ require.Equal(t, "Gateway token has been revoked", apierr.Message(body))+ })++ t.Run("should refuse an unused enrollment token once the gateway is revoked", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ token := enrollmentToken(t, tn, gw.ID)++ // Action+ res, err := tn.Admin.API.RevokeGatewayAccessWithResponse(t.Context(), gw.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ login := loginGateway(t, tn, token)+ requireStatus(t, http.StatusBadRequest, login.StatusCode(), login.Body)+ require.Equal(t, "Invalid enrollment token", apierr.Message(login.Body))+ })+}++func TestGatewayEnrollment_Remint(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should keep the running gateway's access token valid when a new enrollment token is minted", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)++ // Action+ enrollmentToken(t, tn, gw.ID)++ // Assert+ status, body := gatewayTokenStatus(t, running)+ requireStatus(t, http.StatusOK, status, body)+ })++ t.Run("should cut off the running gateway's access token once the new enrollment token is used", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)+ token := enrollmentToken(t, tn, gw.ID)++ // Action+ res := loginGateway(t, tn, token)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ status, body := gatewayTokenStatus(t, running)+ requireStatus(t, http.StatusUnauthorized, status, body)+ status, body = gatewayTokenStatus(t, agent{API: tn.Client(t, res.JSON200.AccessToken)})+ requireStatus(t, http.StatusOK, status, body)+ })++ t.Run("should refuse an earlier unused enrollment token once a new one is minted", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ earlier := enrollmentToken(t, tn, gw.ID)+ later := enrollmentToken(t, tn, gw.ID)++ // Action+ res := loginGateway(t, tn, earlier)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Invalid enrollment token", apierr.Message(res.Body))+ accepted := loginGateway(t, tn, later)+ requireStatus(t, http.StatusOK, accepted.StatusCode(), accepted.Body)+ })+}++func TestGatewayEnrollment_AgentRoutes(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a user's token on gateway connect", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ relay := newRelay(t, tn)++ // Action+ res, err := tn.Admin.API.ConnectGatewayWithResponse(t.Context(), api.ConnectGatewayJSONRequestBody{RelayName: &relay.Name})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Nil(t, getGateway(t, tn, gw.ID).RelayID)+ })++ t.Run("should refuse a machine identity's token on gateway connect", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ relay := newRelay(t, tn)+ identity := tn.NewMachineIdentity(t, harness.OrgRole("admin"))++ // Action+ res, err := identity.API.ConnectGatewayWithResponse(t.Context(), api.ConnectGatewayJSONRequestBody{RelayName: &relay.Name})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Nil(t, getGateway(t, tn, gw.ID).RelayID)+ })++ t.Run("should refuse a user's token on gateway heartbeat", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ newGateway(t, tn)++ // Action+ res, err := tn.Admin.API.GatewayHeartbeatWithBodyWithResponse(t.Context(), "application/json", strings.NewReader("{}"))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ })++ // Identity tokens are accepted on heartbeat for gateways registered under an identity,+ // so a token-enrolled gateway is simply not that identity's.+ t.Run("should answer 404 to a machine identity's heartbeat when no gateway is registered under it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ identity := tn.NewMachineIdentity(t, harness.OrgRole("admin"))++ // Action+ res, err := identity.API.GatewayHeartbeatWithBodyWithResponse(t.Context(), "application/json", strings.NewReader("{}"))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Nil(t, getGateway(t, tn, gw.ID).HeartbeatTTL)+ })+}diff --git a/tests/suites/gateway/forwarding_test.go b/tests/suites/gateway/forwarding_test.gonew file mode 100644index 0000000000..4b58e823f5--- /dev/null+++ b/tests/suites/gateway/forwarding_test.go@@ -0,0 +1,287 @@+package gateway_test++import (+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++// The image under test ships the Infisical CLI, so the agents run the build a customer+// would pair with this server.+const agentImage = "infisical-test:local"++// agentDomain is where the agents reach Infisical: its container on the shared network,+// over plain http, which is what the server listens on.+func agentDomain(h *harness.Stack) string { return h.App().BaseURL(infra.Internal) }++// startRelay runs a relay agent whose recorded host is its own container's address.+func startRelay(t *testing.T, h *harness.Stack, tn *harness.Tenant) relayView {+ t.Helper()+ name := relayName()+ res := createRelay(t, tn.Admin.API, name, name)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ relay := relayView{ID: res.JSON200.Id, Name: name, Host: name}+ h.RunContainer(t, "relay", infra.ContainerSpec{+ Image: agentImage,+ Alias: name,+ Command: []string{"infisical", "relay", "start", "--telemetry=false",+ "--name=" + name, "--enroll-method=token", "--token=" + relayToken(t, tn, relay.ID),+ "--domain=" + agentDomain(h)},+ })+ return relay+}++// startGateway runs a gateway agent for an existing token-auth gateway, through relay.+func startGateway(t *testing.T, h *harness.Stack, tn *harness.Tenant, gw gatewayView, relay relayView) *harness.TestContainer {+ t.Helper()+ return h.RunContainer(t, "gateway", infra.ContainerSpec{+ Image: agentImage,+ Command: []string{"infisical", "gateway", "start", gw.Name, "--telemetry=false",+ "--enroll-method=token", "--token=" + enrollmentToken(t, tn, gw.ID),+ "--domain=" + agentDomain(h), "--target-relay-name=" + relay.Name},+ })+}++func waitHealthy(t *testing.T, tn *harness.Tenant, gatewayID uuid.UUID) gatewayView {+ t.Helper()+ var gw gatewayView+ wait.Until(t, "the gateway to record a heartbeat", func() bool {+ gw = getGateway(t, tn, gatewayID)+ return gw.Heartbeat != nil+ })+ return gw+}++// healthyGateway is a token-auth gateway whose agent is connected through relay.+func healthyGateway(t *testing.T, h *harness.Stack, tn *harness.Tenant, relay relayView) (gatewayView, *harness.TestContainer) {+ t.Helper()+ gw := newGateway(t, tn)+ c := startGateway(t, h, tn, gw, relay)+ waitHealthy(t, tn, gw.ID)+ return gw, c+}++// dynamicSecret is a Postgres dynamic secret on the target that Infisical reaches+// through route, a {"gatewayId": ...} or {"gatewayPoolId": ...} pair.+type dynamicSecret struct {+ name string+ proj *fixture.Project+}++func createDynamicSecret(t *testing.T, tn *harness.Tenant, target *fixture.PostgresTarget, route map[string]any) (*api.CreateDynamicSecretResponse, dynamicSecret) {+ t.Helper()+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ inputs := map[string]any{+ "client": "postgres",+ "host": target.Host,+ "port": target.Port,+ "database": target.Database,+ "username": target.User,+ "password": target.Password,+ "creationStatement": `CREATE ROLE "{{username}}" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';`,+ "revocationStatement": `DROP ROLE "{{username}}";`,+ }+ for k, v := range route {+ inputs[k] = v+ }+ ds := dynamicSecret{name: "ds-" + id.Short(), proj: proj}+ res, err := tn.Admin.API.CreateDynamicSecretWithBodyWithResponse(t.Context(), "application/json", jsonBody(t, map[string]any{+ "projectSlug": proj.Slug,+ "environmentSlug": "dev",+ "path": "/",+ "name": ds.name,+ "provider": map[string]any{"type": "sql-database", "inputs": inputs},+ "defaultTTL": "1h",+ }))+ require.NoError(t, err)+ return res, ds+}++func (d dynamicSecret) lease(t *testing.T) *api.CreateDynamicSecretLeaseResponse {+ t.Helper()+ path := "/"+ res, err := d.proj.Tenant().Admin.API.CreateDynamicSecretLeaseWithResponse(t.Context(), api.CreateDynamicSecretLeaseJSONRequestBody{+ DynamicSecretName: d.name, ProjectSlug: d.proj.Slug, EnvironmentSlug: "dev", Path: &path,+ })+ require.NoError(t, err)+ return res+}++func leasedUsername(t *testing.T, res *api.CreateDynamicSecretLeaseResponse) (string, string) {+ t.Helper()+ data, _ := res.JSON200.Data.(map[string]any)+ username, _ := data["DB_USERNAME"].(string)+ password, _ := data["DB_PASSWORD"].(string)+ require.NotEmpty(t, username, "the lease carries no DB_USERNAME: %v", data)+ return username, password+}++func TestGatewayForwarding_Health(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should show the gateway healthy with a fresh heartbeat once its agent connects through the relay", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := startRelay(t, h, tn)+ gw := newGateway(t, tn)++ // Action+ startGateway(t, h, tn, gw, relay)++ // Assert+ healthy := waitHealthy(t, tn, gw.ID)+ require.WithinDuration(t, time.Now(), *healthy.Heartbeat, time.Minute)+ require.NotNil(t, healthy.HeartbeatTTL)+ require.Positive(t, *healthy.HeartbeatTTL)+ require.Equal(t, relay.ID, *healthy.RelayID)+ })+}++func TestGatewayForwarding_DynamicSecret(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should lease a postgres dynamic secret through the gateway and create the role on the target", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ gw, _ := healthyGateway(t, h, tn, startRelay(t, h, tn))+ created, ds := createDynamicSecret(t, tn, target, map[string]any{"gatewayId": gw.ID})+ requireStatus(t, http.StatusOK, created.StatusCode(), created.Body)++ // Action+ res := ds.lease(t)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ username, password := leasedUsername(t, res)+ target.DropRoleAtCleanup(t, username)+ require.True(t, target.RoleExists(t, username))+ require.NoError(t, target.Login(t, username, password))+ })++ t.Run("should fail the lease once the gateway is revoked", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ gw, _ := healthyGateway(t, h, tn, startRelay(t, h, tn))+ created, ds := createDynamicSecret(t, tn, target, map[string]any{"gatewayId": gw.ID})+ requireStatus(t, http.StatusOK, created.StatusCode(), created.Body)+ revoked, err := tn.Admin.API.RevokeGatewayAccessWithResponse(t.Context(), gw.ID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, revoked.StatusCode(), revoked.Body)++ // Action + Assert+ spec.Why(t, "revoking does not close the agent's open tunnel; the agent drops it once its token is refused")+ wait.Until(t, "a lease to be refused after the revoke", func() bool {+ res := ds.lease(t)+ if res.StatusCode() == http.StatusOK {+ username, _ := leasedUsername(t, res)+ target.DropRoleAtCleanup(t, username)+ return false+ }+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ return true+ })+ })++ t.Run("should fail the lease once the gateway's agent stops", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ gw, agentContainer := healthyGateway(t, h, tn, startRelay(t, h, tn))+ created, ds := createDynamicSecret(t, tn, target, map[string]any{"gatewayId": gw.ID})+ requireStatus(t, http.StatusOK, created.StatusCode(), created.Body)+ agentContainer.Stop(t)++ // Action+ res := ds.lease(t)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ })+}++func TestGatewayForwarding_Pool(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ // pooled is a pool of two healthy gateways sharing one relay.+ pooled := func(t *testing.T, tn *harness.Tenant) (uuid.UUID, []*harness.TestContainer, []uuid.UUID) {+ t.Helper()+ relay := startRelay(t, h, tn)+ poolID := newPool(t, tn)+ var agents []*harness.TestContainer+ var ids []uuid.UUID+ for range 2 {+ gw, c := healthyGateway(t, h, tn, relay)+ added := addToPool(t, tn.Admin.API, poolID, gw.ID)+ requireStatus(t, http.StatusOK, added.StatusCode(), added.Body)+ agents = append(agents, c)+ ids = append(ids, gw.ID)+ }+ return poolID, agents, ids+ }++ t.Run("should fail over to the healthy member when one member's agent is stopped", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ poolID, agents, _ := pooled(t, tn)+ agents[0].Stop(t)++ // Action+ var statuses []int+ for range 4 {+ res := createPostgresConnection(t, tn.Admin.API, target, map[string]any{"gatewayPoolId": poolID})+ statuses = append(statuses, res.StatusCode())+ }++ // Assert+ require.Equal(t, []int{http.StatusOK, http.StatusOK, http.StatusOK, http.StatusOK}, statuses)+ })++ t.Run("should answer that the pool has no healthy gateways when every member is down", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ poolID, agents, ids := pooled(t, tn)+ for i, c := range agents {+ c.Stop(t)+ probed, err := tn.Admin.API.TriggerGatewayHeartbeatWithResponse(t.Context(), ids[i].String())+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, probed.StatusCode(), probed.Body)+ }++ // Action+ res := createPostgresConnection(t, tn.Admin.API, target, map[string]any{"gatewayPoolId": poolID})++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Gateway pool has no healthy gateways.", apierr.Message(res.Body))+ })+}diff --git a/tests/suites/gateway/gateway_test.go b/tests/suites/gateway/gateway_test.gonew file mode 100644index 0000000000..c8d0bfa7be--- /dev/null+++ b/tests/suites/gateway/gateway_test.go@@ -0,0 +1,308 @@+package gateway_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func TestGateway_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ methods := []struct {+ method string+ body map[string]any+ check func(t *testing.T, config map[string]any)+ }{+ {+ method: "token",+ body: tokenAuth(),+ check: func(*testing.T, map[string]any) {},+ },+ {+ method: "aws",+ body: awsAuth(),+ check: func(t *testing.T, config map[string]any) {+ require.Equal(t, "arn:aws:iam::123456789012:role/gateway", config["allowedPrincipalArns"])+ },+ },+ {+ method: "gcp",+ body: gcpAuth(),+ check: func(t *testing.T, config map[string]any) {+ require.Equal(t, "[email protected]", config["allowedServiceAccounts"])+ },+ },+ }+ for _, m := range methods {+ t.Run("should create a gateway that authenticates with "+m.method, func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ name := gatewayName()++ // Action+ res := createGateway(t, tn.Admin.API, name, m.body)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ created := decodeGateway(t, res.Body)+ stored := getGateway(t, tn, created.ID)+ require.Equal(t, name, stored.Name)+ require.Equal(t, m.method, stored.AuthMethod.Method)+ m.check(t, stored.AuthMethod.Config)+ })+ }++ invalid := []struct {+ name string+ authMethod map[string]any+ }{+ {"an unknown auth method", map[string]any{"method": "ldap"}},+ {"aws auth with no allowlist", map[string]any{"method": "aws", "allowedPrincipalArns": "", "allowedAccountIds": ""}},+ {"kubernetes auth with no host when Infisical reviews the token", map[string]any{+ "method": "kubernetes", "allowedNamespaces": "infisical", "allowedNames": "gateway",+ }},+ {"no auth method", nil},+ }+ for _, c := range invalid {+ t.Run("should refuse "+c.name+" and create nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ body := map[string]any{"name": gatewayName()}+ if c.authMethod != nil {+ body["authMethod"] = c.authMethod+ }++ // Action+ res, err := tn.Admin.API.CreateGatewayWithBodyWithResponse(t.Context(), "application/json", jsonBody(t, body))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnprocessableEntity, res.StatusCode(), res.Body)+ require.Empty(t, gatewayIDs(t, tn.Admin.API))+ })+ }++ t.Run("should refuse a second gateway with the same name and keep the first", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ first := newGateway(t, tn)++ // Action+ res := createGateway(t, tn.Admin.API, first.Name, awsAuth())++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "already exists")+ require.Equal(t, []uuid.UUID{first.ID}, gatewayIDs(t, tn.Admin.API))+ require.Equal(t, "token", getGateway(t, tn, first.ID).AuthMethod.Method)+ })++ t.Run("should refuse a 51st gateway in the organization", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ for range 50 {+ newGateway(t, tn)+ }++ // Action+ res := createGateway(t, tn.Admin.API, gatewayName(), tokenAuth())++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "maximum limit of 50 gateways")+ require.Len(t, gatewayIDs(t, tn.Admin.API), 50)+ })+}++func TestGateway_OtherOrganization(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ operations := []struct {+ name string+ call func(t *testing.T, c *api.ClientWithResponses, gatewayID uuid.UUID) (int, []byte)+ }{+ {"get", func(t *testing.T, c *api.ClientWithResponses, gatewayID uuid.UUID) (int, []byte) {+ res, err := c.GetGatewayWithResponse(t.Context(), gatewayID)+ require.NoError(t, err)+ return res.StatusCode(), res.Body+ }},+ {"rename", func(t *testing.T, c *api.ClientWithResponses, gatewayID uuid.UUID) (int, []byte) {+ res, err := c.UpdateGatewayWithBodyWithResponse(t.Context(), gatewayID, "application/json",+ jsonBody(t, map[string]any{"name": "taken-over"}))+ require.NoError(t, err)+ return res.StatusCode(), res.Body+ }},+ {"delete", func(t *testing.T, c *api.ClientWithResponses, gatewayID uuid.UUID) (int, []byte) {+ res, err := c.DeleteGatewayWithResponse(t.Context(), gatewayID.String())+ require.NoError(t, err)+ return res.StatusCode(), res.Body+ }},+ {"mint an enrollment token for", func(t *testing.T, c *api.ClientWithResponses, gatewayID uuid.UUID) (int, []byte) {+ res, err := c.MintGatewayEnrollmentTokenWithResponse(t.Context(), gatewayID)+ require.NoError(t, err)+ return res.StatusCode(), res.Body+ }},+ {"revoke", func(t *testing.T, c *api.ClientWithResponses, gatewayID uuid.UUID) (int, []byte) {+ res, err := c.RevokeGatewayAccessWithResponse(t.Context(), gatewayID)+ require.NoError(t, err)+ return res.StatusCode(), res.Body+ }},+ }+ for _, op := range operations {+ t.Run("should answer 404 and change nothing when another organization's admin tries to "+op.name+" a gateway", func(t *testing.T) {+ t.Parallel()++ // Setup+ owner := h.NewTenant(t)+ outsider := h.NewTenant(t)+ gw := newGateway(t, owner)+ running := enrollGateway(t, owner, gw.ID)++ // Action+ status, body := op.call(t, outsider.Admin.API, gw.ID)++ // Assert+ requireStatus(t, http.StatusNotFound, status, body)+ stored := getGateway(t, owner, gw.ID)+ require.Equal(t, gw.Name, stored.Name)+ status, body = gatewayTokenStatus(t, running)+ requireStatus(t, http.StatusOK, status, body)+ })+ }+}++func TestGateway_MemberPermission(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should let an organization member create a gateway", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))++ // Action+ res := createGateway(t, member.API, gatewayName(), tokenAuth())++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, []uuid.UUID{decodeGateway(t, res.Body).ID}, gatewayIDs(t, tn.Admin.API))+ })++ t.Run("should refuse an organization member minting an enrollment token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))+ created := createGateway(t, member.API, gatewayName(), tokenAuth())+ requireStatus(t, http.StatusOK, created.StatusCode(), created.Body)+ gw := decodeGateway(t, created.Body)++ // Action+ res, err := member.API.MintGatewayEnrollmentTokenWithResponse(t.Context(), gw.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.False(t, getGateway(t, tn, gw.ID).CanRevoke, "a pending enrollment token exists")+ })++ t.Run("should refuse an organization member deleting a gateway", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))+ gw := newGateway(t, tn)++ // Action+ res, err := member.API.DeleteGatewayWithResponse(t.Context(), gw.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Equal(t, []uuid.UUID{gw.ID}, gatewayIDs(t, tn.Admin.API))+ })++ t.Run("should refuse an organization member revoking a gateway and keep it connected", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))+ gw := newGateway(t, tn)+ running := enrollGateway(t, tn, gw.ID)++ // Action+ res, err := member.API.RevokeGatewayAccessWithResponse(t.Context(), gw.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ status, body := gatewayTokenStatus(t, running)+ requireStatus(t, http.StatusOK, status, body)+ })+}++func TestGateway_List(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should list only the organization's own gateways", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ other := h.NewTenant(t)+ mine := newGateway(t, tn)+ newGateway(t, other)++ // Action+ listed := gatewayIDs(t, tn.Admin.API)++ // Assert+ require.Equal(t, []uuid.UUID{mine.ID}, listed)+ })++ t.Run("should show the app connection that routes through a gateway", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ connID := postgresConnection(t, tn)+ attached := updateConnection(t, tn.Admin.API, connID, api.UpdatePostgresAppConnectionJSONRequestBody{GatewayId: &gw.ID})+ requireStatus(t, http.StatusOK, attached.StatusCode(), attached.Body)++ // Action+ res, err := tn.Admin.API.GetGatewayConnectedResourcesWithResponse(t.Context(), gw.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Len(t, res.JSON200.AppConnections, 1)+ require.Equal(t, connID.String(), res.JSON200.AppConnections[0].Id)+ list, err := tn.Admin.API.ListGatewaysWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, list.StatusCode(), list.Body)+ require.Len(t, *list.JSON200, 1)+ require.EqualValues(t, 1, (*list.JSON200)[0].ConnectedResourcesCount)+ })+}diff --git a/tests/suites/gateway/helpers_test.go b/tests/suites/gateway/helpers_test.gonew file mode 100644index 0000000000..2de04fb884--- /dev/null+++ b/tests/suites/gateway/helpers_test.go@@ -0,0 +1,320 @@+package gateway_test++import (+ "bytes"+ "crypto/x509"+ "encoding/json"+ "encoding/pem"+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func requireStatus(t *testing.T, want, got int, body []byte) {+ t.Helper()+ require.Equalf(t, want, got, "body: %s", apierr.Body(body))+}++func jsonBody(t *testing.T, v any) *bytes.Reader {+ t.Helper()+ raw, err := json.Marshal(v)+ require.NoError(t, err)+ return bytes.NewReader(raw)+}++func tokenAuth() map[string]any { return map[string]any{"method": "token"} }++func awsAuth() map[string]any {+ return map[string]any{+ "method": "aws",+ "allowedPrincipalArns": "arn:aws:iam::123456789012:role/gateway",+ "allowedAccountIds": "",+ }+}++func gcpAuth() map[string]any {+ return map[string]any{+ "method": "gcp",+ "type": "iam",+ "allowedServiceAccounts": "[email protected]",+ "allowedProjects": "",+ "allowedZones": "",+ }+}++// gatewayView is a gateway as the v3 routes return it. The auth method is a union in+// the generated client, so the body is read by hand.+type gatewayView struct {+ ID uuid.UUID `json:"id"`+ Name string `json:"name"`+ CanRevoke bool `json:"canRevoke"`+ RelayID *uuid.UUID `json:"relayId"`+ Heartbeat *time.Time `json:"heartbeat"`+ HeartbeatTTL *float64 `json:"heartbeatTTL"`+ AuthMethod struct {+ Method string `json:"method"`+ Config map[string]any `json:"config"`+ } `json:"authMethod"`+}++func decodeGateway(t *testing.T, body []byte) gatewayView {+ t.Helper()+ var v gatewayView+ require.NoError(t, json.Unmarshal(body, &v))+ require.NotEqual(t, uuid.Nil, v.ID, "body: %s", apierr.Body(body))+ return v+}++func gatewayName() string { return "gw-" + id.Short() + id.Short() }++func createGateway(t *testing.T, c *api.ClientWithResponses, name string, authMethod map[string]any) *api.CreateGatewayResponse {+ t.Helper()+ res, err := c.CreateGatewayWithBodyWithResponse(t.Context(), "application/json",+ jsonBody(t, map[string]any{"name": name, "authMethod": authMethod}))+ require.NoError(t, err)+ return res+}++// newGateway creates a token-auth gateway as the tenant's admin.+func newGateway(t *testing.T, tn *harness.Tenant) gatewayView {+ t.Helper()+ res := createGateway(t, tn.Admin.API, gatewayName(), tokenAuth())+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return decodeGateway(t, res.Body)+}++func getGateway(t *testing.T, tn *harness.Tenant, gatewayID uuid.UUID) gatewayView {+ t.Helper()+ res, err := tn.Admin.API.GetGatewayWithResponse(t.Context(), gatewayID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return decodeGateway(t, res.Body)+}++func gatewayIDs(t *testing.T, c *api.ClientWithResponses) []uuid.UUID {+ t.Helper()+ res, err := c.ListGatewaysWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ ids := []uuid.UUID{}+ for _, g := range *res.JSON200 {+ ids = append(ids, g.Id)+ }+ return ids+}++// enrollmentToken mints a gateway enrollment token as the tenant's admin.+func enrollmentToken(t *testing.T, tn *harness.Tenant, gatewayID uuid.UUID) string {+ t.Helper()+ res, err := tn.Admin.API.MintGatewayEnrollmentTokenWithResponse(t.Context(), gatewayID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return res.JSON200.Token+}++func loginGateway(t *testing.T, tn *harness.Tenant, token string) *api.LoginGatewayResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginGatewayWithBodyWithResponse(t.Context(), "application/json",+ jsonBody(t, map[string]any{"method": "token", "token": token}))+ require.NoError(t, err)+ return res+}++// agent is what a running gateway or relay holds after login: its access token and a+// client that sends it.+type agent struct {+ Token string+ API *api.ClientWithResponses+}++func enrollGateway(t *testing.T, tn *harness.Tenant, gatewayID uuid.UUID) agent {+ t.Helper()+ res := loginGateway(t, tn, enrollmentToken(t, tn, gatewayID))+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return agent{Token: res.JSON200.AccessToken, API: tn.Client(t, res.JSON200.AccessToken)}+}++// gatewayTokenStatus is the status a gateway token gets on a route that accepts it and+// changes nothing, so it shows whether the token is still honoured.+func gatewayTokenStatus(t *testing.T, gw agent) (int, []byte) {+ t.Helper()+ res, err := gw.API.GetRelaysWithResponse(t.Context())+ require.NoError(t, err)+ return res.StatusCode(), res.Body+}++func connectGateway(t *testing.T, gw agent, body api.ConnectGatewayJSONRequestBody) *api.ConnectGatewayResponse {+ t.Helper()+ res, err := gw.API.ConnectGatewayWithResponse(t.Context(), body)+ require.NoError(t, err)+ return res+}++func relayName() string { return "rl-" + id.Short() + id.Short() }++// relayHost resolves to fakenet, which accepts nothing on the relay ports.+func relayHost() string { return relayName() + ".relay.test" }++type relayView struct {+ ID uuid.UUID `json:"id"`+ Name string `json:"name"`+ Host string `json:"host"`+ CanRevoke bool `json:"canRevoke"`+ AuthMethod struct {+ Method string `json:"method"`+ } `json:"authMethod"`+}++func createRelay(t *testing.T, c *api.ClientWithResponses, name, host string) *api.CreateRelayResponse {+ t.Helper()+ res, err := c.CreateRelayWithBodyWithResponse(t.Context(), "application/json",+ jsonBody(t, map[string]any{"name": name, "host": host, "authMethod": tokenAuth()}))+ require.NoError(t, err)+ return res+}++func newRelay(t *testing.T, tn *harness.Tenant) relayView {+ t.Helper()+ res := createRelay(t, tn.Admin.API, relayName(), relayHost())+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ var v relayView+ require.NoError(t, json.Unmarshal(res.Body, &v))+ return v+}++func relayToken(t *testing.T, tn *harness.Tenant, relayID uuid.UUID) string {+ t.Helper()+ res, err := tn.Admin.API.MintRelayEnrollmentTokenWithResponse(t.Context(), relayID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return res.JSON200.Token+}++func loginRelay(t *testing.T, tn *harness.Tenant, token string) *api.LoginRelayResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginRelayWithBodyWithResponse(t.Context(), "application/json",+ jsonBody(t, map[string]any{"method": "token", "token": token}))+ require.NoError(t, err)+ return res+}++func enrollRelay(t *testing.T, tn *harness.Tenant, relayID uuid.UUID) agent {+ t.Helper()+ res := loginRelay(t, tn, relayToken(t, tn, relayID))+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return agent{Token: res.JSON200.AccessToken, API: tn.Client(t, res.JSON200.AccessToken)}+}++func relayIDs(t *testing.T, c *api.ClientWithResponses) []uuid.UUID {+ t.Helper()+ res, err := c.GetRelaysWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ ids := []uuid.UUID{}+ for _, r := range *res.JSON200 {+ ids = append(ids, r.Id)+ }+ return ids+}++func relayHosts(t *testing.T, tn *harness.Tenant) []string {+ t.Helper()+ res, err := tn.Admin.API.GetRelaysWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ hosts := []string{}+ for _, r := range *res.JSON200 {+ hosts = append(hosts, r.Host)+ }+ return hosts+}++func parseCert(t *testing.T, pemText string) *x509.Certificate {+ t.Helper()+ return parseChain(t, pemText)[0]+}++func parseChain(t *testing.T, pemText string) []*x509.Certificate {+ t.Helper()+ var certs []*x509.Certificate+ rest := []byte(pemText)+ for {+ var block *pem.Block+ block, rest = pem.Decode(rest)+ if block == nil {+ break+ }+ cert, err := x509.ParseCertificate(block.Bytes)+ require.NoError(t, err)+ certs = append(certs, cert)+ }+ require.NotEmpty(t, certs, "no certificate in %q", pemText)+ return certs+}++// postgresConnection is an App Connection to the target database, which a test then+// points at a gateway or a pool.+func postgresConnection(t *testing.T, tn *harness.Tenant) uuid.UUID {+ t.Helper()+ return fixture.NewAppConnection(t, tn, fixture.PostgresAppConnection(fixture.OpenPostgresTarget(t, tn))).ID+}++func updateConnection(t *testing.T, c *api.ClientWithResponses, connID uuid.UUID, body api.UpdatePostgresAppConnectionJSONRequestBody) *api.UpdatePostgresAppConnectionResponse {+ t.Helper()+ res, err := c.UpdatePostgresAppConnectionWithResponse(t.Context(), connID, body)+ require.NoError(t, err)+ return res+}++type connectionRoute struct {+ GatewayID *uuid.UUID `json:"gatewayId"`+ GatewayPoolID *uuid.UUID `json:"gatewayPoolId"`+}++func connectionRouteOf(t *testing.T, tn *harness.Tenant, connID uuid.UUID) connectionRoute {+ t.Helper()+ res, err := tn.Admin.API.GetPostgresAppConnectionWithResponse(t.Context(), connID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ var out struct {+ AppConnection connectionRoute `json:"appConnection"`+ }+ require.NoError(t, json.Unmarshal(res.Body, &out))+ return out.AppConnection+}++func newPool(t *testing.T, tn *harness.Tenant) uuid.UUID {+ t.Helper()+ res, err := tn.Admin.API.CreateGatewayPoolWithResponse(t.Context(),+ api.CreateGatewayPoolJSONRequestBody{Name: "pool-" + id.Short() + id.Short()})+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return res.JSON200.Id+}++func addToPool(t *testing.T, c *api.ClientWithResponses, poolID, gatewayID uuid.UUID) *api.AddGatewayToPoolResponse {+ t.Helper()+ res, err := c.AddGatewayToPoolWithResponse(t.Context(), poolID, api.AddGatewayToPoolJSONRequestBody{GatewayId: gatewayID})+ require.NoError(t, err)+ return res+}++func poolMembers(t *testing.T, tn *harness.Tenant, poolID uuid.UUID) []uuid.UUID {+ t.Helper()+ res, err := tn.Admin.API.GetGatewayPoolByIdWithResponse(t.Context(), poolID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ ids := []uuid.UUID{}+ for _, g := range res.JSON200.Gateways {+ ids = append(ids, g.Id)+ }+ return ids+}diff --git a/tests/suites/gateway/main_test.go b/tests/suites/gateway/main_test.gonew file mode 100644index 0000000000..d2416748c3--- /dev/null+++ b/tests/suites/gateway/main_test.go@@ -0,0 +1,14 @@+package gateway_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra/postgres"+)++// The target database gives the tests an App Connection to attach a gateway or a pool to.+func TestMain(m *testing.M) {+ harness.Main(m, harness.Shared, harness.WithInfra(postgres.Module(postgres.Named(fixture.PostgresTargetInstance))))+}diff --git a/tests/suites/gateway/pool_test.go b/tests/suites/gateway/pool_test.gonew file mode 100644index 0000000000..ec53421172--- /dev/null+++ b/tests/suites/gateway/pool_test.go@@ -0,0 +1,512 @@+package gateway_test++import (+ "encoding/json"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++const poolUpgradeMessage = "Your current plan does not support gateway pools. Please upgrade to an Enterprise plan."++func withoutPools() license.Plan { return license.Enterprise().Without(license.GatewayPool) }++func TestGatewayPool_License(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse creating a pool when the plan does not include gateway pools", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(withoutPools()))++ // Action+ res, err := tn.Admin.API.CreateGatewayPoolWithResponse(t.Context(), api.CreateGatewayPoolJSONRequestBody{Name: "pool-" + id.Short()})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, poolUpgradeMessage, apierr.Message(res.Body))+ tn.SetPlan(t, license.Enterprise())+ require.Empty(t, poolIDs(t, tn))+ })++ t.Run("should refuse renaming a pool after a downgrade and keep its name", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)+ before := poolName(t, tn, poolID)+ tn.SetPlan(t, withoutPools())++ // Action+ renamed := "renamed-" + id.Short()+ res, err := tn.Admin.API.UpdateGatewayPoolWithResponse(t.Context(), poolID, api.UpdateGatewayPoolJSONRequestBody{Name: &renamed})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, poolUpgradeMessage, apierr.Message(res.Body))+ tn.SetPlan(t, license.Enterprise())+ require.Equal(t, before, poolName(t, tn, poolID))+ })++ t.Run("should refuse adding a gateway to a pool after a downgrade", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)+ gw := newGateway(t, tn)+ tn.SetPlan(t, withoutPools())++ // Action+ res := addToPool(t, tn.Admin.API, poolID, gw.ID)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, poolUpgradeMessage, apierr.Message(res.Body))+ tn.SetPlan(t, license.Enterprise())+ require.Empty(t, poolMembers(t, tn, poolID))+ })+}++func TestGatewayPool_Membership(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should add a gateway to a pool and list it as a member", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)+ gw := newGateway(t, tn)++ // Action+ res := addToPool(t, tn.Admin.API, poolID, gw.ID)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, []uuid.UUID{gw.ID}, poolMembers(t, tn, poolID))+ })++ t.Run("should remove a gateway from a pool", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)+ kept, removed := newGateway(t, tn), newGateway(t, tn)+ for _, gw := range []gatewayView{kept, removed} {+ added := addToPool(t, tn.Admin.API, poolID, gw.ID)+ requireStatus(t, http.StatusOK, added.StatusCode(), added.Body)+ }++ // Action+ res, err := tn.Admin.API.RemoveGatewayFromPoolWithResponse(t.Context(), poolID, removed.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, []uuid.UUID{kept.ID}, poolMembers(t, tn, poolID))+ require.Contains(t, gatewayIDs(t, tn.Admin.API), removed.ID)+ })++ t.Run("should answer 404 when adding another organization's gateway", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)+ theirs := newGateway(t, h.NewTenant(t))++ // Action+ res := addToPool(t, tn.Admin.API, poolID, theirs.ID)++ // Assert+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Empty(t, poolMembers(t, tn, poolID))+ })+}++func TestGatewayPool_Delete(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should delete a pool nothing uses", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)++ // Action+ res, err := tn.Admin.API.DeleteGatewayPoolWithResponse(t.Context(), poolID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Empty(t, poolIDs(t, tn))+ })++ t.Run("should refuse deleting a pool an app connection routes through, naming why", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)+ connID := postgresConnection(t, tn)+ attached := updateConnection(t, tn.Admin.API, connID, api.UpdatePostgresAppConnectionJSONRequestBody{GatewayPoolId: &poolID})+ requireStatus(t, http.StatusOK, attached.StatusCode(), attached.Body)++ // Action+ res, err := tn.Admin.API.DeleteGatewayPoolWithResponse(t.Context(), poolID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "referenced by one or more consumer configurations")+ require.Equal(t, []uuid.UUID{poolID}, poolIDs(t, tn))+ require.Equal(t, poolID, *connectionRouteOf(t, tn, connID).GatewayPoolID)+ })+}++func TestGatewayPool_Health(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should report no healthy members for a pool of gateways that never connected", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)+ for range 2 {+ added := addToPool(t, tn.Admin.API, poolID, newGateway(t, tn).ID)+ requireStatus(t, http.StatusOK, added.StatusCode(), added.Body)+ }++ // Action+ res, err := tn.Admin.API.ListGatewayPoolsWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Len(t, *res.JSON200, 1)+ require.EqualValues(t, 2, (*res.JSON200)[0].MemberCount)+ require.EqualValues(t, 0, (*res.JSON200)[0].HealthyMemberCount)+ })+}++func TestGatewayPool_RequirePools(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse attaching an individual gateway when the organization requires gateway pools", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ connID := postgresConnection(t, tn)+ requirePools(t, tn)++ // Action+ res := updateConnection(t, tn.Admin.API, connID, api.UpdatePostgresAppConnectionJSONRequestBody{GatewayId: &gw.ID})++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "requires resources to connect through a gateway pool")+ require.Nil(t, connectionRouteOf(t, tn, connID).GatewayID)+ })++ t.Run("should let a pool be attached when the organization requires gateway pools", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)+ connID := postgresConnection(t, tn)+ requirePools(t, tn)++ // Action+ res := updateConnection(t, tn.Admin.API, connID, api.UpdatePostgresAppConnectionJSONRequestBody{GatewayPoolId: &poolID})++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, poolID, *connectionRouteOf(t, tn, connID).GatewayPoolID)+ })++ t.Run("should refuse requiring gateway pools when the plan does not include them", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(withoutPools()))++ // Action+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{RequireGatewayPools: new(true)})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "Upgrade to Infisical Enterprise to use gateway pools")+ require.False(t, requiresPools(t, tn))+ })+}++func TestGatewayAttach_License(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse creating an app connection through a gateway when the plan does not include gateways", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ target := fixture.OpenPostgresTarget(t, tn)+ tn.SetPlan(t, license.Enterprise().Without(license.Gateway))++ // Action+ res := createPostgresConnection(t, tn.Admin.API, target, map[string]any{"gatewayId": gw.ID})++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "does not support gateway usage with app connections")+ listed, err := tn.Admin.API.ListPostgresAppConnectionsWithResponse(t.Context(), nil)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, listed.StatusCode(), listed.Body)+ require.JSONEq(t, `[]`, string(appConnectionsOf(t, listed.Body)))+ })+}++func poolIDs(t *testing.T, tn *harness.Tenant) []uuid.UUID {+ t.Helper()+ res, err := tn.Admin.API.ListGatewayPoolsWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ ids := []uuid.UUID{}+ for _, p := range *res.JSON200 {+ ids = append(ids, p.Id)+ }+ return ids+}++func poolName(t *testing.T, tn *harness.Tenant, poolID uuid.UUID) string {+ t.Helper()+ res, err := tn.Admin.API.GetGatewayPoolByIdWithResponse(t.Context(), poolID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return res.JSON200.Name+}++func requirePools(t *testing.T, tn *harness.Tenant) {+ t.Helper()+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{RequireGatewayPools: new(true)})+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+}++func requiresPools(t *testing.T, tn *harness.Tenant) bool {+ t.Helper()+ res, err := tn.Admin.API.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return res.JSON200.Organization.RequireGatewayPools != nil && *res.JSON200.Organization.RequireGatewayPools+}++// createPostgresConnection creates a connection to the target through route, a+// {"gatewayId": ...} or {"gatewayPoolId": ...} pair, or directly when route is nil.+func createPostgresConnection(t *testing.T, c *api.ClientWithResponses, target *fixture.PostgresTarget, route map[string]any) *api.CreatePostgresAppConnectionResponse {+ t.Helper()+ body := map[string]any{+ "name": "pg-" + id.Short() + id.Short(),+ "method": "username-and-password",+ "credentials": map[string]any{+ "host": target.Host,+ "port": target.Port,+ "database": target.Database,+ "username": target.User,+ "password": target.Password,+ "sslEnabled": false,+ "sslRejectUnauthorized": false,+ },+ }+ for k, v := range route {+ body[k] = v+ }+ res, err := c.CreatePostgresAppConnectionWithBodyWithResponse(t.Context(), "application/json", jsonBody(t, body))+ require.NoError(t, err)+ return res+}++func appConnectionsOf(t *testing.T, body []byte) json.RawMessage {+ t.Helper()+ var out struct {+ AppConnections json.RawMessage `json:"appConnections"`+ }+ require.NoError(t, json.Unmarshal(body, &out))+ return out.AppConnections+}++// Losing an entitlement makes a feature read-only (backend/CODE_QUALITY.md, License+// Checks), but every pool route checks the plan, so a downgraded organization can no+// longer see, audit or clean up the pools its resources still route through.+func TestGatewayPool_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ // downgraded is an organization that built a pool with one member while entitled.+ downgraded := func(t *testing.T) (*harness.Tenant, uuid.UUID, uuid.UUID) {+ t.Helper()+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)+ gw := newGateway(t, tn)+ added := addToPool(t, tn.Admin.API, poolID, gw.ID)+ requireStatus(t, http.StatusOK, added.StatusCode(), added.Body)+ tn.SetPlan(t, withoutPools())+ return tn, poolID, gw.ID+ }++ t.Run("should keep listing pools after a downgrade", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, poolID, _ := downgraded(t)++ // Action+ res, err := tn.Admin.API.ListGatewayPoolsWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Len(t, *res.JSON200, 1)+ require.Equal(t, poolID, (*res.JSON200)[0].Id)+ })++ t.Run("should keep reading a pool and its members after a downgrade", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, poolID, gatewayID := downgraded(t)++ // Action+ res, err := tn.Admin.API.GetGatewayPoolByIdWithResponse(t.Context(), poolID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Len(t, res.JSON200.Gateways, 1)+ require.Equal(t, gatewayID, res.JSON200.Gateways[0].Id)+ })++ t.Run("should keep showing what uses a pool after a downgrade", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, poolID, _ := downgraded(t)++ // Action+ res, err := tn.Admin.API.GetGatewayPoolConnectedResourcesWithResponse(t.Context(), poolID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ })++ t.Run("should let a downgraded organization remove a gateway from a pool", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, poolID, gatewayID := downgraded(t)++ // Action+ res, err := tn.Admin.API.RemoveGatewayFromPoolWithResponse(t.Context(), poolID, gatewayID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ tn.SetPlan(t, license.Enterprise())+ require.Empty(t, poolMembers(t, tn, poolID))+ })++ t.Run("should let a downgraded organization delete a pool", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, poolID, _ := downgraded(t)++ // Action+ res, err := tn.Admin.API.DeleteGatewayPoolWithResponse(t.Context(), poolID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ tn.SetPlan(t, license.Enterprise())+ require.Empty(t, poolIDs(t, tn))+ })+}++// Creating an App Connection through a gateway checks plan.gateway, but pointing an+// existing one at a gateway does not, so the gate is one PATCH away.+func TestGatewayAttach_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse pointing an existing app connection at a gateway when the plan does not include gateways", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ gw := newGateway(t, tn)+ connID := postgresConnection(t, tn)+ tn.SetPlan(t, license.Enterprise().Without(license.Gateway))++ // Action+ res := updateConnection(t, tn.Admin.API, connID, api.UpdatePostgresAppConnectionJSONRequestBody{GatewayId: &gw.ID})++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "does not support gateway usage")+ require.Nil(t, connectionRouteOf(t, tn, connID).GatewayID)+ })+}++// addGatewayToPool maps a unique violation to "already a member", but reads the code+// from the wrong field of the wrapped database error, so the duplicate surfaces as a 500.+func TestGatewayPoolMembership_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse adding a gateway that is already a member", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ poolID := newPool(t, tn)+ gw := newGateway(t, tn)+ first := addToPool(t, tn.Admin.API, poolID, gw.ID)+ requireStatus(t, http.StatusOK, first.StatusCode(), first.Body)++ // Action+ res := addToPool(t, tn.Admin.API, poolID, gw.ID)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "This gateway is already a member of the pool.", apierr.Message(res.Body))+ require.Equal(t, []uuid.UUID{gw.ID}, poolMembers(t, tn, poolID))+ })+}diff --git a/tests/suites/gateway/relay_test.go b/tests/suites/gateway/relay_test.gonew file mode 100644index 0000000000..0d9e251bbd--- /dev/null+++ b/tests/suites/gateway/relay_test.go@@ -0,0 +1,285 @@+package gateway_test++import (+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra"+ "github.com/Infisical/infisical/tests/infra/postgres"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+ "golang.org/x/crypto/ssh"+)++func TestRelay_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should create an organization relay that enrolls with a token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ name, host := relayName(), relayHost()++ // Action+ res := createRelay(t, tn.Admin.API, name, host)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ got, err := tn.Admin.API.GetRelayWithResponse(t.Context(), res.JSON200.Id)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, got.StatusCode(), got.Body)+ require.Equal(t, name, got.JSON200.Name)+ require.Equal(t, host, got.JSON200.Host)+ require.Contains(t, string(got.Body), `"method":"token"`)+ })++ t.Run("should refuse a second relay with the same name and keep the first", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ first := newRelay(t, tn)++ // Action+ res := createRelay(t, tn.Admin.API, first.Name, relayHost())++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "already exists")+ require.Equal(t, []string{first.Host}, relayHosts(t, tn))+ })++ t.Run("should refuse a host that points at Infisical's own database", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ database := tn.Module(t, postgres.Key, "harness.Shared").Endpoint(infra.Internal).Host++ // Action+ res := createRelay(t, tn.Admin.API, relayName(), database)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "in-use by Infisical")+ require.Empty(t, relayHosts(t, tn))+ })+}++func TestRelay_Connect(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a one-day tls certificate for the relay's host marked OU=Relay", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := newRelay(t, tn)+ running := enrollRelay(t, tn, relay.ID)++ // Action+ res, err := running.API.ConnectRelayWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ cert := parseCert(t, res.JSON200.Pki.ServerCertificate)+ require.Equal(t, relay.Host, cert.Subject.CommonName)+ require.Equal(t, []string{"Relay"}, cert.Subject.OrganizationalUnit)+ require.Equal(t, []string{relay.Host}, cert.DNSNames)+ require.WithinDuration(t, time.Now().Add(24*time.Hour), cert.NotAfter, 10*time.Minute)+ })++ t.Run("should issue an ssh host certificate for the relay's host on port 2222", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := newRelay(t, tn)+ running := enrollRelay(t, tn, relay.ID)++ // Action+ res, err := running.API.ConnectRelayWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(res.JSON200.Ssh.ServerCertificate))+ require.NoError(t, err)+ cert, ok := key.(*ssh.Certificate)+ require.True(t, ok, "not an ssh certificate: %s", res.JSON200.Ssh.ServerCertificate)+ require.Equal(t, uint32(ssh.HostCert), cert.CertType)+ require.Equal(t, []string{relay.Host + ":2222"}, cert.ValidPrincipals)+ })+}++func TestRelay_Revoke(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse the relay's access token once the relay is revoked", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := newRelay(t, tn)+ running := enrollRelay(t, tn, relay.ID)++ // Action+ res, err := tn.Admin.API.RevokeRelayAccessWithResponse(t.Context(), relay.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ connect, err := running.API.ConnectRelayWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusUnauthorized, connect.StatusCode(), connect.Body)+ require.Equal(t, "Relay token has been revoked", apierr.Message(connect.Body))+ })++ t.Run("should report the relay unreachable on heartbeat when nothing listens on its host", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := newRelay(t, tn)+ running := enrollRelay(t, tn, relay.ID)++ // Action+ res, err := running.API.RelayHeartbeatWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "Relay "+relay.Name+" is not reachable")+ got, err := tn.Admin.API.GetRelayWithResponse(t.Context(), relay.ID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, got.StatusCode(), got.Body)+ require.Nil(t, got.JSON200.Heartbeat)+ })+}++func TestRelay_List(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should list the organization's relays and not another organization's", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ mine := newRelay(t, tn)+ theirs := newRelay(t, h.NewTenant(t))++ // Action+ listed := relayIDs(t, tn.Admin.API)++ // Assert+ require.Contains(t, listed, mine.ID)+ require.NotContains(t, listed, theirs.ID)+ })++ t.Run("should answer 404 and keep the relay when another organization deletes it", func(t *testing.T) {+ t.Parallel()++ // Setup+ owner := h.NewTenant(t)+ relay := newRelay(t, owner)+ outsider := h.NewTenant(t)++ // Action+ res, err := outsider.Admin.API.DeleteRelayWithResponse(t.Context(), relay.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Contains(t, relayIDs(t, owner.Admin.API), relay.ID)+ })+}++func TestRelay_InstanceRegistration(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ secrets := []struct {+ name string+ client func(t *testing.T, tn *harness.Tenant) *api.ClientWithResponses+ }{+ {"no auth secret", func(t *testing.T, tn *harness.Tenant) *api.ClientWithResponses { return tn.Anonymous(t) }},+ {"a wrong auth secret", func(t *testing.T, tn *harness.Tenant) *api.ClientWithResponses {+ return tn.Client(t, "not-the-relay-auth-secret")+ }},+ }+ for _, s := range secrets {+ t.Run("should refuse registering an instance relay with "+s.name, func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ name := relayName()++ // Action+ res, err := s.client(t, tn).RegisterInstanceRelayWithResponse(t.Context(),+ api.RegisterInstanceRelayJSONRequestBody{Name: name, Host: relayHost()})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Invalid relay auth secret", apierr.Message(res.Body))+ listed, err := tn.Admin.API.GetRelaysWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, listed.StatusCode(), listed.Body)+ for _, r := range *listed.JSON200 {+ require.NotEqual(t, name, r.Name)+ }+ })+ }+}++func TestRelay_MemberPermission(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse an organization member deleting a relay", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := newRelay(t, tn)+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))++ // Action+ res, err := member.API.DeleteRelayWithResponse(t.Context(), relay.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, relayIDs(t, tn.Admin.API), relay.ID)+ })++ t.Run("should refuse an organization member revoking a relay and keep it connected", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ relay := newRelay(t, tn)+ running := enrollRelay(t, tn, relay.ID)+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))++ // Action+ res, err := member.API.RevokeRelayAccessWithResponse(t.Context(), relay.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ connect, err := running.API.ConnectRelayWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, connect.StatusCode(), connect.Body)+ })+}diff --git a/tests/suites/group/delete_test.go b/tests/suites/group/delete_test.gonew file mode 100644index 0000000000..a3efd9e6c8--- /dev/null+++ b/tests/suites/group/delete_test.go@@ -0,0 +1,62 @@+package group_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestGroup_Delete(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should remove every member's project access when the group is deleted", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ first, second := tn.NewUser(t), tn.NewUser(t)+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, first, second)+ proj.GrantGroup(t, group, "viewer")+ for _, p := range []*harness.Principal{first, second} {+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return listSecrets(t, p.API, proj.ID) })+ }++ // Action+ res, err := tn.Admin.API.DeleteGroupWithResponse(t.Context(), group.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ for _, p := range []*harness.Principal{first, second} {+ body := waitForStatus(t, http.StatusForbidden, func() (int, []byte) { return listSecrets(t, p.API, proj.ID) })+ require.Contains(t, string(body), "You are not a member of this project")+ }+ })++ t.Run("should refuse deleting a root group linked into a sub-org, naming the sub-org", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ group := fixture.NewGroup(t, tn)+ sub.LinkGroup(t, group)++ // Action+ res, err := tn.Admin.API.DeleteGroupWithResponse(t.Context(), group.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Cannot delete this group because it is linked by sub-organizations")+ require.Contains(t, apierr.Message(res.Body), `"`+sub.Name+`"`)+ require.Contains(t, groupNames(t, tn.Admin.API), group.Name)+ })+}diff --git a/tests/suites/group/escalation_test.go b/tests/suites/group/escalation_test.gonew file mode 100644index 0000000000..b01f45fd8e--- /dev/null+++ b/tests/suites/group/escalation_test.go@@ -0,0 +1,179 @@+package group_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/stretchr/testify/require"+)++func groupsRule(actions ...string) fixture.Permission {+ return fixture.Permission{Subject: "groups", Action: actions}+}++func TestGroup_Escalation(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse adding a user to a group without add-members, and add nobody", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "group-editor", groupsRule("read", "edit"))+ actor := tn.NewUser(t, harness.OrgRole("group-editor"))+ target := tn.NewUser(t)+ group := fixture.NewGroup(t, tn)++ // Action+ res, err := actor.API.AddUserToGroupWithResponse(t.Context(), group.ID.String(), target.Email)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to add user to more privileged group")+ require.Contains(t, string(res.Body), "add-members on groups")+ require.Empty(t, fixture.GroupUserIDs(t, tn.Admin.API, group.ID))+ })++ t.Run("should refuse creating an admin group without grant-privileges on groups, and create none", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `Under the new privilege system, giving a group any role but no-access needs+ grant-privileges on groups; the role is not compared with the actor's own.`)++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "group-creator", groupsRule("read", "create"))+ actor := tn.NewUser(t, harness.OrgRole("group-creator"))++ // Action+ res, err := actor.API.CreateGroupWithResponse(t.Context(), api.CreateGroupJSONRequestBody{+ Name: "escalated", Role: new("admin"),+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to create group. Permission denied: grant-privileges on groups")+ require.NotContains(t, groupNames(t, tn.Admin.API), "escalated")+ })++ t.Run("should refuse changing a more privileged group's role, and keep its role", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "group-editor", groupsRule("read", "edit"))+ actor := tn.NewUser(t, harness.OrgRole("group-editor"))+ group := fixture.NewGroup(t, tn, fixture.WithGroupRole("admin"))++ // Action+ res, err := actor.API.UpdateGroupWithResponse(t.Context(), group.ID.String(), api.UpdateGroupJSONRequestBody{+ Role: new("member"),+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to change the roles of a more privileged group")+ require.Equal(t, "admin", groupRole(t, tn, group.ID))+ })++ t.Run("should refuse deleting a group without delete on groups, and keep it", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `The new privilege system bounds deletion by the delete action alone, so an+ actor who may delete groups may delete an admin one.`)++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "group-editor", groupsRule("read", "edit"))+ actor := tn.NewUser(t, harness.OrgRole("group-editor"))+ group := fixture.NewGroup(t, tn, fixture.WithGroupRole("admin"))++ // Action+ res, err := actor.API.DeleteGroupWithResponse(t.Context(), group.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "You are not allowed to delete on groups")+ require.Contains(t, groupNames(t, tn.Admin.API), group.Name)+ })++ t.Run("should refuse adding a group to a project with a role above the actor's own", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ proj.NewRole(t, "group-assigner",+ fixture.Permission{Subject: "groups", Action: []string{"read", "create"}},+ fixture.Permission{Subject: "groups", Action: []string{"assign-role"},+ Conditions: map[string]any{"assignableRole": map[string]any{"$eq": "viewer"}}})+ actor := proj.NewUser(t, fixture.WithRoles("group-assigner"))+ group := fixture.NewGroup(t, tn)++ // Action+ res, err := actor.API.CreateProjectGroupMembershipWithBodyWithResponse(t.Context(), proj.ID, group.ID,+ "application/json", rolesBody(t, permanent("admin")))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to create group project membership")+ require.NotContains(t, projectGroupIDs(t, tn.Admin.API, proj.ID), group.ID)+ })++ t.Run("should refuse removing a more privileged group from a project", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ proj.NewRole(t, "group-remover",+ fixture.Permission{Subject: "groups", Action: []string{"read"}},+ fixture.Permission{Subject: "groups", Action: []string{"delete"},+ Conditions: map[string]any{"assignableRole": map[string]any{"$ne": "admin"}}})+ actor := proj.NewUser(t, fixture.WithRoles("group-remover"))+ group := fixture.NewGroup(t, tn)+ proj.GrantGroup(t, group, "admin")++ // Action+ res, err := actor.API.RemoveProjectGroupMembershipWithResponse(t.Context(), proj.ID, group.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to remove a more privileged group from the project")+ require.Contains(t, projectGroupIDs(t, tn.Admin.API, proj.ID), group.ID)+ })+}++func TestGroup_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a custom role with edit and add-members adding itself to an admin group", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `Suspected bug: under the new privilege system the add-members boundary only+ checks the action, so add-members alone lets an actor join a group holding admin.`)++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "group-joiner", groupsRule("read", "edit", "add-members"))+ actor := tn.NewUser(t, harness.OrgRole("group-joiner"))+ group := fixture.NewGroup(t, tn, fixture.WithGroupRole("admin"))++ // Action+ res, err := actor.API.AddUserToGroupWithResponse(t.Context(), group.ID.String(), actor.Email)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.NotContains(t, fixture.GroupUserIDs(t, tn.Admin.API, group.ID), actor.ID)+ })+}diff --git a/tests/suites/group/externalmapping_test.go b/tests/suites/group/externalmapping_test.gonew file mode 100644index 0000000000..2235f2b057--- /dev/null+++ b/tests/suites/group/externalmapping_test.go@@ -0,0 +1,146 @@+package group_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/stretchr/testify/require"+)++type mapping = struct {+ GroupName string `json:"groupName"`+ RoleSlug string `json:"roleSlug"`+}++func mappingsBody(pairs ...string) api.UpdateExternalGroupOrgRoleMappingsJSONRequestBody {+ body := api.UpdateExternalGroupOrgRoleMappingsJSONRequestBody{Mappings: []mapping{}}+ for i := 0; i+1 < len(pairs); i += 2 {+ body.Mappings = append(body.Mappings, mapping{GroupName: pairs[i], RoleSlug: pairs[i+1]})+ }+ return body+}++func setMappings(t *testing.T, client *api.ClientWithResponses, pairs ...string) *api.UpdateExternalGroupOrgRoleMappingsResponse {+ t.Helper()+ res, err := client.UpdateExternalGroupOrgRoleMappingsWithResponse(t.Context(), mappingsBody(pairs...))+ require.NoError(t, err)+ return res+}++// currentMappings is the tenant's mapping set as group name to role.+func currentMappings(t *testing.T, tn *harness.Tenant) map[string]string {+ t.Helper()+ res, err := tn.Admin.API.ListExternalGroupOrgRoleMappingsWithResponse(t.Context())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing mappings returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ out := map[string]string{}+ for _, m := range *res.JSON200 {+ out[m.GroupName] = m.Role+ }+ return out+}++func TestGroup_ExternalMapping(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a group name mapped twice and keep the old mapping set", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ requireStatus(t, http.StatusOK, setMappings(t, tn.Admin.API, "engineering", "member").StatusCode(), nil)++ // Action+ res := setMappings(t, tn.Admin.API, "platform", "admin", "platform", "member")++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Group 'platform' is mapped more than once")+ require.Equal(t, map[string]string{"engineering": "member"}, currentMappings(t, tn))+ })++ t.Run("should refuse mapping to a custom role when the plan lacks rbac", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "auditor", fixture.Permission{Subject: "audit-logs", Action: []string{"read"}})+ tn.SetPlan(t, license.Enterprise().Without(license.RBAC))++ // Action+ res := setMappings(t, tn.Admin.API, "auditors", "auditor")++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to set group organization role mapping due to plan RBAC restriction")+ require.Empty(t, currentMappings(t, tn))+ })++ t.Run("should refuse a member without scim edit and keep the mapping set", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))++ // Action+ res := setMappings(t, member.API, "engineering", "member")++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "You are not allowed to edit on scim")+ require.Empty(t, currentMappings(t, tn))+ })++ t.Run("should refuse the mapping from a sub-org token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)++ // Action+ res := setMappings(t, sub.Admin.API, "engineering", "member")++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Child organization cannot do this operation")+ require.Empty(t, currentMappings(t, tn))+ })++ t.Run("should put an OIDC user in the group their groups claim names and give them its org role", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `External group to org role mappings are applied by SCIM only. On OIDC login a+ groups claim drives Infisical group membership (manageGroupMemberships), and the+ org role comes from the group.`)++ // Setup+ tn := h.NewTenant(t)+ oidc := oidcManagedGroups(t, tn)+ group := fixture.NewGroup(t, tn, fixture.WithGroupRole("admin"))+ person := oidc.Person()+ person.Groups = []string{group.Name}++ // Action+ login := oidc.Login(t, person)++ // Assert+ require.Equal(t, []string{person.Email}, groupUsernames(t, tn, group.ID))+ signup := oidc.CompleteSignup(t, login, sso.VerificationCode(t, tn, person.Email))+ require.NotNilf(t, signup.JSON200, "completing the OIDC signup returned %d: %s", signup.StatusCode(), apierr.Body(signup.Body))+ selected, err := tn.Client(t, signup.JSON200.Token).SelectOrganizationV3WithResponse(t.Context(),+ api.SelectOrganizationV3JSONRequestBody{OrganizationId: tn.OrgID.String()})+ require.NoError(t, err)+ require.NotNilf(t, selected.JSON200, "selecting the organization returned %d: %s", selected.StatusCode(), apierr.Body(selected.Body))+ status, body := readConnections(t, tn.Client(t, selected.JSON200.Token))+ requireStatus(t, http.StatusOK, status, body)+ })+}diff --git a/tests/suites/group/helpers_test.go b/tests/suites/group/helpers_test.gonew file mode 100644index 0000000000..da76f41f73--- /dev/null+++ b/tests/suites/group/helpers_test.go@@ -0,0 +1,220 @@+package group_test++import (+ "bytes"+ "context"+ "crypto/rand"+ "encoding/json"+ "fmt"+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/harness/infisical"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/mail"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/google/uuid"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func requireStatus(t *testing.T, want, got int, body []byte) {+ t.Helper()+ require.Equalf(t, want, got, "answered %d: %s", got, apierr.Body(body))+}++// waitForStatus polls a call until it answers with the wanted status. Membership and+// role changes reach the project permission cache up to 10 seconds late.+func waitForStatus(t *testing.T, want int, call func() (int, []byte)) []byte {+ t.Helper()+ var last []byte+ _, err := wait.For(t.Context(), func(context.Context) (struct{}, bool, error) {+ status, body := call()+ last = body+ return struct{}{}, status == want, nil+ })+ require.NoErrorf(t, err, "waiting for %d, last body: %s", want, apierr.Body(last))+ return last+}++func jsonBody(t *testing.T, v any) *bytes.Reader {+ t.Helper()+ raw, err := json.Marshal(v)+ require.NoError(t, err)+ return bytes.NewReader(raw)+}++// sourceIP is a fresh rate-limit bucket, for calls that go through smtpRateLimit.+func sourceIP() string {+ b := make([]byte, 3)+ _, _ = rand.Read(b)+ return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])+}++func permanent(slug string) map[string]any { return map[string]any{"role": slug, "isTemporary": false} }++// expired is a temporary role whose window closed an hour ago.+func expired(slug string) map[string]any {+ return map[string]any{+ "role": slug,+ "isTemporary": true,+ "temporaryMode": "relative",+ "temporaryRange": "1h",+ "temporaryAccessStartTime": time.Now().Add(-2 * time.Hour).UTC().Format(time.RFC3339),+ }+}++func rolesBody(t *testing.T, roles ...map[string]any) *bytes.Reader {+ t.Helper()+ return jsonBody(t, map[string]any{"roles": roles})+}++// readConnections lists AWS app connections, which needs read on app-connections at+// the org level: admin has it, member does not.+func readConnections(t *testing.T, client *api.ClientWithResponses) (int, []byte) {+ t.Helper()+ res, err := client.ListAwsAppConnectionsWithResponse(t.Context(), nil)+ require.NoError(t, err)+ return res.StatusCode(), res.Body+}++func listSecrets(t *testing.T, client *api.ClientWithResponses, projectID string) (int, []byte) {+ t.Helper()+ env, path := "dev", "/"+ res, err := client.ListSecretsV4WithResponse(t.Context(), &api.ListSecretsV4Params{+ ProjectId: &projectID,+ Environment: &env,+ SecretPath: &path,+ })+ require.NoError(t, err)+ return res.StatusCode(), res.Body+}++func createSecret(t *testing.T, client *api.ClientWithResponses, projectID, name string) (int, []byte) {+ t.Helper()+ path := "/"+ res, err := client.CreateSecretV4WithResponse(t.Context(), name, api.CreateSecretV4JSONRequestBody{+ ProjectId: projectID,+ Environment: "dev",+ SecretPath: &path,+ SecretValue: "value",+ })+ require.NoError(t, err)+ return res.StatusCode(), res.Body+}++func groupRole(t *testing.T, tn *harness.Tenant, groupID uuid.UUID) string {+ t.Helper()+ res, err := tn.Admin.API.GetGroupByIdWithResponse(t.Context(), groupID.String())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "reading group %s returned %d: %s", groupID, res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.Role+}++func groupNames(t *testing.T, client *api.ClientWithResponses) []string {+ t.Helper()+ res, err := client.ListGroupsWithResponse(t.Context())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing groups returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ names := []string{}+ for _, g := range *res.JSON200 {+ names = append(names, g.Name)+ }+ return names+}++func groupIdentityIDs(t *testing.T, tn *harness.Tenant, groupID uuid.UUID) []uuid.UUID {+ t.Helper()+ filter := api.AssignedMachineIdentities+ res, err := tn.Admin.API.ListGroupMachineIdentitiesWithResponse(t.Context(), groupID.String(),+ &api.ListGroupMachineIdentitiesParams{Filter: &filter})+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing the identities of group %s returned %d: %s", groupID, res.StatusCode(), apierr.Body(res.Body))+ out := []uuid.UUID{}+ for _, i := range res.JSON200.MachineIdentities {+ out = append(out, i.Id)+ }+ return out+}++func projectGroupIDs(t *testing.T, client *api.ClientWithResponses, projectID string) []uuid.UUID {+ t.Helper()+ res, err := client.ListProjectGroupMembershipsWithResponse(t.Context(), projectID)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing the groups of %s returned %d: %s", projectID, res.StatusCode(), apierr.Body(res.Body))+ out := []uuid.UUID{}+ for _, m := range res.JSON200.GroupMemberships {+ out = append(out, m.GroupId)+ }+ return out+}++// invite asks the tenant's admin to invite an address, and leaves the invitation+// unaccepted.+func invite(t *testing.T, tn *harness.Tenant, local string) string {+ t.Helper()+ addr := tn.Email(local)+ admin := tn.Client(t, tn.Admin.Token, infisical.ForwardedFor(sourceIP()))+ res, err := admin.InviteUsersToOrganizationWithResponse(t.Context(), api.InviteUsersToOrganizationJSONRequestBody{+ InviteeEmails: []openapi_types.Email{openapi_types.Email(addr)},+ OrganizationId: tn.OrgID.String(),+ })+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return addr+}++// accept takes an invitation the way the invitee does: the mailed link, account+// completion and organization selection. It returns their org-scoped client.+func accept(t *testing.T, tn *harness.Tenant, addr string) *api.ClientWithResponses {+ t.Helper()+ ctx := t.Context()+ msg := tn.Mail(t).Expect(t, addr, smtp.Subject("invitation"))+ code, err := mail.Param(msg, "token")+ require.NoError(t, err)++ verified, err := tn.Anonymous(t).VerifyUserToOrganizationWithResponse(ctx, api.VerifyUserToOrganizationJSONRequestBody{+ Email: openapi_types.Email(addr),+ OrganizationId: tn.OrgID.String(),+ Code: code,+ })+ require.NoError(t, err)+ require.Truef(t, verified.JSON200 != nil && verified.JSON200.Token != nil,+ "verifying the invitation returned %d: %s", verified.StatusCode(), apierr.Body(verified.Body))++ var union api.CompleteAccountSignupV3JSONBody+ require.NoError(t, union.FromCompleteAccountSignupV3JSONBody0(api.CompleteAccountSignupV3JSONBody0{+ Type: api.CompleteAccountSignupV3JSONBody0TypeEmail,+ Email: addr,+ FirstName: "invitee",+ Password: harness.UserPassword,+ }))+ completed, err := tn.Client(t, *verified.JSON200.Token).CompleteAccountSignupV3WithBodyWithResponse(ctx,+ "application/json", jsonBody(t, union))+ require.NoError(t, err)+ require.NotNilf(t, completed.JSON200, "completing the account returned %d: %s", completed.StatusCode(), apierr.Body(completed.Body))++ selected, err := tn.Client(t, completed.JSON200.Token).SelectOrganizationV3WithResponse(ctx,+ api.SelectOrganizationV3JSONRequestBody{OrganizationId: tn.OrgID.String()})+ require.NoError(t, err)+ require.NotNilf(t, selected.JSON200, "selecting the organization returned %d: %s", selected.StatusCode(), apierr.Body(selected.Body))+ return tn.Client(t, selected.JSON200.Token)+}++func groupUsernames(t *testing.T, tn *harness.Tenant, groupID uuid.UUID) []string {+ t.Helper()+ filter := api.ListGroupUsersParamsFilterExistingMembers+ res, err := tn.Admin.API.ListGroupUsersWithResponse(t.Context(), groupID.String(), &api.ListGroupUsersParams{Filter: &filter})+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing the users of group %s returned %d: %s", groupID, res.StatusCode(), apierr.Body(res.Body))+ out := []string{}+ for _, u := range res.JSON200.Users {+ out = append(out, u.Username)+ }+ return out+}+diff --git a/tests/suites/group/main_test.go b/tests/suites/group/main_test.gonew file mode 100644index 0000000000..dff84a2da6--- /dev/null+++ b/tests/suites/group/main_test.go@@ -0,0 +1,9 @@+package group_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/harness"+)++func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }diff --git a/tests/suites/group/membership_test.go b/tests/suites/group/membership_test.gonew file mode 100644index 0000000000..4168a1f1fb--- /dev/null+++ b/tests/suites/group/membership_test.go@@ -0,0 +1,323 @@+package group_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++// oidcManagedGroups configures OIDC for the tenant and hands group membership to it.+func oidcManagedGroups(t *testing.T, tn *harness.Tenant) *sso.OIDC {+ t.Helper()+ oidc := sso.NewOIDC(t, tn)+ res, err := tn.Admin.API.UpdateOidcConfigWithResponse(t.Context(), api.UpdateOidcConfigJSONRequestBody{+ OrganizationId: tn.OrgID.String(),+ ManageGroupMemberships: new(true),+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "enabling OIDC group management: %s", apierr.Body(res.Body))+ return oidc+}++func TestGroup_Lifecycle(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a duplicate group name and keep one group", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ group := fixture.NewGroup(t, tn)++ // Action+ res, err := tn.Admin.API.CreateGroupWithResponse(t.Context(), api.CreateGroupJSONRequestBody{Name: group.Name})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "This name or slug is already in use by another group in your organization")+ require.Equal(t, []string{group.Name}, groupNames(t, tn.Admin.API))+ })++ t.Run("should refuse creating a group when the plan lacks groups", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.Groups)))++ // Action+ res, err := tn.Admin.API.CreateGroupWithResponse(t.Context(), api.CreateGroupJSONRequestBody{Name: "unlicensed"})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to create group due to plan restriction. Upgrade plan to create group.")+ require.Empty(t, groupNames(t, tn.Admin.API))+ })++ t.Run("should refuse renaming a group when the plan lacks groups, and keep its name", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ group := fixture.NewGroup(t, tn)+ tn.SetPlan(t, license.Enterprise().Without(license.Groups))++ // Action+ res, err := tn.Admin.API.UpdateGroupWithResponse(t.Context(), group.ID.String(), api.UpdateGroupJSONRequestBody{+ Name: new("renamed"),+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to update group due to plan restriction")+ require.Equal(t, []string{group.Name}, groupNames(t, tn.Admin.API))+ })++ t.Run("should refuse deleting a group when the plan lacks groups, and keep listing it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ group := fixture.NewGroup(t, tn)+ tn.SetPlan(t, license.Enterprise().Without(license.Groups))++ // Action+ res, err := tn.Admin.API.DeleteGroupWithResponse(t.Context(), group.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to delete group due to plan restriction. Upgrade plan to delete group.")+ require.Equal(t, []string{group.Name}, groupNames(t, tn.Admin.API))+ })+}++func TestGroup_Membership(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse adding another organization's user and add nobody", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, other := h.NewTenant(t), h.NewTenant(t)+ group := fixture.NewGroup(t, tn)++ // Action+ res, err := tn.Admin.API.AddUserToGroupWithResponse(t.Context(), group.ID.String(), other.Admin.Email)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "is not part of the organization")+ require.Empty(t, fixture.GroupUserIDs(t, tn.Admin.API, group.ID))+ })++ t.Run("should answer 404 for another organization's identity and add nobody", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, other := h.NewTenant(t), h.NewTenant(t)+ outsider := other.NewMachineIdentity(t)+ group := fixture.NewGroup(t, tn)++ // Action+ res, err := tn.Admin.API.AddMachineIdentityToGroupWithResponse(t.Context(), group.ID.String(), outsider.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Identity with id "+outsider.ID.String()+" is not part of the organization")+ require.Empty(t, groupIdentityIDs(t, tn, group.ID))+ })++ t.Run("should add an invited user who has not accepted yet", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ addr := invite(t, tn, "invitee")+ group := fixture.NewGroup(t, tn)++ // Action+ res, err := tn.Admin.API.AddUserToGroupWithResponse(t.Context(), group.ID.String(), addr)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, []string{addr}, groupUsernames(t, tn, group.ID))+ })++ t.Run("should give an invited group member the group's project access once they accept", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateSecret(t, proj, "dev", "FROM_GROUP", "value")+ addr := invite(t, tn, "invitee")+ group := fixture.NewGroup(t, tn)+ added, err := tn.Admin.API.AddUserToGroupWithResponse(t.Context(), group.ID.String(), addr)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, added.StatusCode(), added.Body)+ proj.GrantGroup(t, group, "viewer")++ // Action+ invitee := accept(t, tn, addr)++ // Assert+ body := waitForStatus(t, http.StatusOK, func() (int, []byte) { return listSecrets(t, invitee, proj.ID) })+ require.Contains(t, string(body), "FROM_GROUP")+ })++ t.Run("should refuse adding a user twice and keep one membership", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t)+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, member)++ // Action+ res, err := tn.Admin.API.AddUserToGroupWithResponse(t.Context(), group.ID.String(), member.Email)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "User(s) are already part of the group "+group.Slug)+ require.Equal(t, []string{member.Email}, groupUsernames(t, tn, group.ID))+ })++ t.Run("should refuse removing a user who is not in the group", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member, outsider := tn.NewUser(t), tn.NewUser(t)+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, member)++ // Action+ res, err := tn.Admin.API.RemoveUserFromGroupWithResponse(t.Context(), group.ID.String(), outsider.Email)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "User(s) are not part of the group "+group.Slug)+ require.Equal(t, []string{member.Email}, groupUsernames(t, tn, group.ID))+ })++ t.Run("should refuse adding a user by hand when OIDC manages group memberships", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t)+ group := fixture.NewGroup(t, tn)+ oidcManagedGroups(t, tn)++ // Action+ res, err := tn.Admin.API.AddUserToGroupWithResponse(t.Context(), group.ID.String(), member.Email)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Cannot add user to group: OIDC group membership mapping is enabled")+ require.Empty(t, fixture.GroupUserIDs(t, tn.Admin.API, group.ID))+ })++ t.Run("should refuse removing a user by hand when OIDC manages group memberships", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t)+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, member)+ oidcManagedGroups(t, tn)++ // Action+ res, err := tn.Admin.API.RemoveUserFromGroupWithResponse(t.Context(), group.ID.String(), member.Email)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Cannot remove user from group: OIDC group membership mapping is enabled")+ require.Equal(t, []string{member.Email}, groupUsernames(t, tn, group.ID))+ })++ t.Run("should still add a machine identity when OIDC manages group memberships", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identity := tn.NewMachineIdentity(t)+ group := fixture.NewGroup(t, tn)+ oidcManagedGroups(t, tn)++ // Action+ res, err := tn.Admin.API.AddMachineIdentityToGroupWithResponse(t.Context(), group.ID.String(), identity.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, []uuid.UUID{identity.ID}, groupIdentityIDs(t, tn, group.ID))+ })++ t.Run("should remove group-derived project access when a user leaves the group", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ member := tn.NewUser(t)+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, member)+ proj.GrantGroup(t, group, "viewer")+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return listSecrets(t, member.API, proj.ID) })++ // Action+ group.RemoveUser(t, member)++ // Assert+ body := waitForStatus(t, http.StatusForbidden, func() (int, []byte) { return listSecrets(t, member.API, proj.ID) })+ require.Contains(t, string(body), "You are not a member of this project")+ })++ t.Run("should keep a user's direct project access when they leave the group", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateSecret(t, proj, "dev", "EXISTING", "value")+ member := proj.NewUser(t, fixture.WithRoles("viewer"))+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, member)+ proj.GrantGroup(t, group, "member")+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return createSecret(t, member.API, proj.ID, "BEFORE") })++ // Action+ group.RemoveUser(t, member)++ // Assert+ waitForStatus(t, http.StatusForbidden, func() (int, []byte) { return createSecret(t, member.API, proj.ID, "AFTER_"+id.Short()) })+ status, body := listSecrets(t, member.API, proj.ID)+ requireStatus(t, http.StatusOK, status, body)+ require.Contains(t, string(body), "EXISTING")+ })+}diff --git a/tests/suites/group/permission_test.go b/tests/suites/group/permission_test.gonew file mode 100644index 0000000000..439115361e--- /dev/null+++ b/tests/suites/group/permission_test.go@@ -0,0 +1,186 @@+package group_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/stretchr/testify/require"+)++var (+ readConnectionsRule = fixture.Permission{Subject: "app-connections", Action: []string{"read"}}+ denyConnectionsRule = fixture.Permission{Subject: "app-connections", Action: []string{"read"}, Inverted: true}+)++func TestGroup_Permission(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should give a member the group's org role on top of their own", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))+ group := fixture.NewGroup(t, tn, fixture.WithGroupRole("admin"))+ status, body := readConnections(t, member.API)+ requireStatus(t, http.StatusForbidden, status, body)++ // Action+ group.AddUser(t, member)++ // Assert+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return readConnections(t, member.API) })+ require.Equal(t, "member", fixture.MembershipOf(t, tn, member.Email).Role)+ })++ t.Run("should drop the group's org role when the member leaves the group", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))+ group := fixture.NewGroup(t, tn, fixture.WithGroupRole("admin"))+ group.AddUser(t, member)+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return readConnections(t, member.API) })++ // Action+ group.RemoveUser(t, member)++ // Assert+ body := waitForStatus(t, http.StatusForbidden, func() (int, []byte) { return readConnections(t, member.API) })+ require.Contains(t, string(body), "You are not allowed to read on app-connections")+ })++ t.Run("should give a machine identity the group's org role and project role", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateSecret(t, proj, "dev", "FROM_GROUP", "value")+ identity := tn.NewMachineIdentity(t, harness.OrgRole("member"))+ group := fixture.NewGroup(t, tn, fixture.WithGroupRole("admin"))+ proj.GrantGroup(t, group, "viewer")++ // Action+ group.AddIdentity(t, identity)++ // Assert+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return readConnections(t, identity.API) })+ body := waitForStatus(t, http.StatusOK, func() (int, []byte) { return listSecrets(t, identity.API, proj.ID) })+ require.Contains(t, string(body), "FROM_GROUP")+ })++ t.Run("should let a deny in the group's org role override an allow in the member's own role", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "conn-reader", readConnectionsRule)+ fixture.NewOrgRole(t, tn, "conn-denier", denyConnectionsRule)+ member := tn.NewUser(t, harness.OrgRole("conn-reader"))+ group := fixture.NewGroup(t, tn, fixture.WithGroupRole("conn-denier"))+ status, body := readConnections(t, member.API)+ requireStatus(t, http.StatusOK, status, body)++ // Action+ group.AddUser(t, member)++ // Assert+ body = waitForStatus(t, http.StatusForbidden, func() (int, []byte) { return readConnections(t, member.API) })+ require.Contains(t, string(body), "You are not allowed to read on app-connections")+ })++ t.Run("should let a deny in the member's own role override an allow from the group", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "conn-denier", denyConnectionsRule)+ member := tn.NewUser(t, harness.OrgRole("conn-denier"))+ peer := tn.NewMachineIdentity(t, harness.OrgRole("member"))+ group := fixture.NewGroup(t, tn, fixture.WithGroupRole("admin"))+ group.AddIdentity(t, peer)+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return readConnections(t, peer.API) })++ // Action+ group.AddUser(t, member)++ // Assert+ status, body := readConnections(t, member.API)+ requireStatus(t, http.StatusForbidden, status, body)+ require.Contains(t, string(body), "You are not allowed to read on app-connections")+ })++ t.Run("should give no group-derived project access to a deactivated member", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ member := tn.NewUser(t)+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, member)+ proj.GrantGroup(t, group, "viewer")+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return listSecrets(t, member.API, proj.ID) })+ membership := fixture.MembershipOf(t, tn, member.Email)++ // Action+ res, err := tn.Admin.API.UpdateOrgMembershipWithResponse(t.Context(), tn.OrgID.String(), membership.ID.String(),+ api.UpdateOrgMembershipJSONRequestBody{IsActive: new(false)})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ body := waitForStatus(t, http.StatusForbidden, func() (int, []byte) { return listSecrets(t, member.API, proj.ID) })+ require.Contains(t, string(body), "User organization membership is inactive")+ })++ t.Run("should stop a temporary group project role at its end time while the permanent role still applies", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateSecret(t, proj, "dev", "EXISTING", "value")+ member := tn.NewUser(t)+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, member)++ // Action+ res, err := tn.Admin.API.CreateProjectGroupMembershipWithBodyWithResponse(t.Context(), proj.ID, group.ID,+ "application/json", rolesBody(t, permanent("viewer"), expired("member")))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ body := waitForStatus(t, http.StatusOK, func() (int, []byte) { return listSecrets(t, member.API, proj.ID) })+ require.Contains(t, string(body), "EXISTING")+ status, body := createSecret(t, member.API, proj.ID, "WRITTEN")+ requireStatus(t, http.StatusForbidden, status, body)+ })++ t.Run("should give no access through a group with the default no-access role", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("no-access"))+ group := fixture.NewGroup(t, tn)++ // Action+ group.AddUser(t, member)++ // Assert+ res, err := member.API.ListGroupsWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "You are not allowed to read on groups")+ require.Equal(t, "no-access", groupRole(t, tn, group.ID))+ })+}diff --git a/tests/suites/group/project_test.go b/tests/suites/group/project_test.gonew file mode 100644index 0000000000..0b30aaa931--- /dev/null+++ b/tests/suites/group/project_test.go@@ -0,0 +1,133 @@+package group_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/stretchr/testify/require"+)++func TestGroup_Project(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should remove access from every member when the group is removed from the project", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ user := tn.NewUser(t)+ identity := tn.NewMachineIdentity(t)+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, user)+ group.AddIdentity(t, identity)+ proj.GrantGroup(t, group, "viewer")+ for _, p := range []*harness.Principal{user, identity} {+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return listSecrets(t, p.API, proj.ID) })+ }++ // Action+ res, err := tn.Admin.API.RemoveProjectGroupMembershipWithResponse(t.Context(), proj.ID, group.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ for _, p := range []*harness.Principal{user, identity} {+ body := waitForStatus(t, http.StatusForbidden, func() (int, []byte) { return listSecrets(t, p.API, proj.ID) })+ require.Contains(t, string(body), "You are not a member of this project")+ }+ })++ t.Run("should refuse a group membership with only temporary roles and add nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ group := fixture.NewGroup(t, tn)++ // Action+ res, err := tn.Admin.API.CreateProjectGroupMembershipWithBodyWithResponse(t.Context(), proj.ID, group.ID,+ "application/json", rolesBody(t, expired("viewer")))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Group must have at least one permanent role")+ require.NotContains(t, projectGroupIDs(t, tn.Admin.API, proj.ID), group.ID)+ })++ t.Run("should refuse a temporary role without a start time and range and add nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ group := fixture.NewGroup(t, tn)++ // Action+ res, err := tn.Admin.API.CreateProjectGroupMembershipWithBodyWithResponse(t.Context(), proj.ID, group.ID,+ "application/json", rolesBody(t, permanent("viewer"), map[string]any{"role": "admin", "isTemporary": true}))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnprocessableEntity, res.StatusCode(), res.Body)+ require.NotContains(t, projectGroupIDs(t, tn.Admin.API, proj.ID), group.ID)+ })++ t.Run("should refuse removing a group that is an approver on a policy, naming the policy", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ group := fixture.NewGroup(t, tn)+ proj.GrantGroup(t, group, "member")+ policy, err := tn.Admin.API.CreateAccessApprovalPolicyWithBodyWithResponse(t.Context(), "application/json",+ jsonBody(t, map[string]any{+ "name": "guarded-by-group",+ "projectSlug": proj.Slug,+ "environment": "dev",+ "secretPath": "/",+ "approvals": 1,+ "approvers": []map[string]any{{"type": "group", "id": group.ID.String()}},+ }))+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, policy.StatusCode(), policy.Body)++ // Action+ res, err := tn.Admin.API.RemoveProjectGroupMembershipWithResponse(t.Context(), proj.ID, group.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Cannot remove group from project: group is an approver in access approval policy: guarded-by-group")+ require.Contains(t, projectGroupIDs(t, tn.Admin.API, proj.ID), group.ID)+ })++ t.Run("should refuse a group name that matches both a root and a linked group, naming the fix", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ rootGroup := fixture.NewGroup(t, tn)+ sub.NewGroup(t, rootGroup.Name)+ sub.LinkGroup(t, rootGroup)+ projectID := sub.NewProject(t)++ // Action+ res, err := sub.Admin.API.AddGroupToProjectWithBodyWithResponse(t.Context(), projectID, rootGroup.Name,+ "application/json", jsonBody(t, map[string]any{"role": "viewer"}))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body),+ "Multiple groups with name '"+rootGroup.Name+"' are visible in this organization. Use the group ID instead.")+ require.Empty(t, projectGroupIDs(t, sub.Admin.API, projectID))+ })+}diff --git a/tests/suites/machineidentity/accesstoken_test.go b/tests/suites/machineidentity/accesstoken_test.gonew file mode 100644index 0000000000..07aa51b56f--- /dev/null+++ b/tests/suites/machineidentity/accesstoken_test.go@@ -0,0 +1,562 @@+package machineidentity_test++import (+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/mail"+ "github.com/Infisical/infisical/tests/internal/wait"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func TestAccessToken_Revoke(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a token on its next request once it is revoked", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{}).login(t, tn)+ c := tn.Client(t, token)+ requireWorks(t, c)++ // Action+ res := revoke(t, tn, token)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ status, body := whoami(t, c)+ requireStatus(t, http.StatusUnauthorized, status, body)+ require.Contains(t, string(body), "Failed to authorize: token has been revoked")+ })++ t.Run("should refuse renewing a revoked token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{}).login(t, tn)+ revoked := revoke(t, tn, token)+ requireStatus(t, http.StatusOK, revoked.StatusCode(), revoked.Body)++ // Action+ res := renew(t, tn, token)++ // Assert+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Cannot renew: token has been revoked")+ })++ t.Run("should refuse revoking a user session token as not an identity token, and keep it working", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res := revoke(t, tn, tn.Admin.Token)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Token is not an identity access token")+ still, err := tn.Admin.API.ListOrgMembershipsWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, still.StatusCode(), still.Body)+ })+}++func TestAccessToken_NumUses(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should accept exactly N requests and refuse the next with token usage limit reached", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenNumUsesLimit: new(3)}).login(t, tn)+ c := tn.Client(t, token)+ statuses := []int{}++ // Action+ for range 4 {+ status, _ := whoami(t, c)+ statuses = append(statuses, status)+ }++ // Assert+ require.Equal(t, []int{http.StatusOK, http.StatusOK, http.StatusOK, http.StatusUnauthorized}, statuses)+ _, body := whoami(t, c)+ require.Contains(t, string(body), "token usage limit reached")+ })++ t.Run("should count uses across a renewal rather than resetting them", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenNumUsesLimit: new(3)}).login(t, tn)+ requireWorks(t, tn.Client(t, token))+ requireWorks(t, tn.Client(t, token))++ // Action+ res := renew(t, tn, token)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ renewed := tn.Client(t, res.JSON200.AccessToken)+ requireWorks(t, renewed)+ status, body := whoami(t, renewed)+ requireStatus(t, http.StatusUnauthorized, status, body)+ require.Contains(t, string(body), "token usage limit reached")+ })++ t.Run("should refuse renewing an exhausted token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenNumUsesLimit: new(1)}).login(t, tn)+ requireWorks(t, tn.Client(t, token))++ // Action+ res := renew(t, tn, token)++ // Assert+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Cannot renew exhausted access token")+ })+}++func TestAccessToken_TTL(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a token after its TTL with the expired-token message", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTTL: new(2), AccessTokenMaxTTL: new(10)}).login(t, tn)+ c := tn.Client(t, token)++ // Action+ requireWorks(t, c)++ // Assert+ body := waitForStatus(t, http.StatusForbidden, func() (int, []byte) { return whoami(t, c) })+ require.Contains(t, string(body), `"error":"TokenError"`)+ require.Contains(t, string(body), "Your token has expired. Please re-authenticate.")+ })++ t.Run("should keep the same token id and creation time when it is renewed", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{}).login(t, tn)++ // Action+ res := renew(t, tn, token)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ before, after := claims(t, token), claims(t, res.JSON200.AccessToken)+ require.Equal(t, before["identityAccessTokenId"], after["identityAccessTokenId"])+ require.Equal(t, before["jti"], after["jti"])+ require.Equal(t, before["creationEpoch"], after["creationEpoch"])+ requireWorks(t, tn.Client(t, res.JSON200.AccessToken))+ })++ t.Run("should refuse renewal once the max TTL has passed since the first login", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ const maxTTL = 4+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTTL: new(2), AccessTokenMaxTTL: new(maxTTL)}).login(t, tn)+ deadline := int64(claims(t, token)["creationEpoch"].(float64)) + maxTTL+ var exps []int64++ // Action+ refused, err := wait.For(t.Context(), func(context.Context) (*api.RenewIdentityAccessTokenResponse, bool, error) {+ res := renew(t, tn, token)+ if res.JSON200 == nil {+ return res, true, nil+ }+ token = res.JSON200.AccessToken+ exps = append(exps, int64(claims(t, token)["exp"].(float64)))+ return nil, false, nil+ })++ // Assert+ require.NoError(t, err)+ require.NotEmpty(t, exps, "the token was never renewed")+ for _, exp := range exps {+ require.LessOrEqual(t, exp, deadline+1, "a renewed token outlived the max TTL")+ }+ require.GreaterOrEqual(t, time.Now().Unix(), deadline-1, "renewal was refused before the max TTL ran out: %s", refused.Body)+ require.Truef(t, refusedForMaxTTL(refused.StatusCode(), refused.Body), "answered %d: %s", refused.StatusCode(), apierr.Body(refused.Body))+ })++ t.Run("should cap expiresIn at the remaining max TTL budget", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ const ttl, maxTTL = 4, 6+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTTL: new(ttl), AccessTokenMaxTTL: new(maxTTL)}).login(t, tn)+ deadline := claims(t, token)["creationEpoch"].(float64) + maxTTL++ // Action+ capped, err := wait.For(t.Context(), func(context.Context) (*api.RenewIdentityAccessTokenResponse, bool, error) {+ res := renew(t, tn, token)+ if res.JSON200 == nil {+ return nil, false, fmt.Errorf("renewing answered %d: %s", res.StatusCode(), apierr.Body(res.Body))+ }+ return res, res.JSON200.ExpiresIn < ttl, nil+ })++ // Assert+ require.NoError(t, err)+ require.EqualValues(t, maxTTL, capped.JSON200.AccessTokenMaxTTL)+ require.InDelta(t, deadline, claims(t, capped.JSON200.AccessToken)["exp"].(float64), 1)+ })++ t.Run("should renew a periodic token indefinitely", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ const period, maxTTL = 2, 3+ token := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{+ AccessTokenTTL: new(period), AccessTokenMaxTTL: new(maxTTL), AccessTokenPeriod: new(period),+ }).login(t, tn)+ start := time.Now()+ var expiresIn []float32++ // Action+ _, err := wait.For(t.Context(), func(context.Context) (struct{}, bool, error) {+ res := renew(t, tn, token)+ if res.JSON200 == nil {+ return struct{}{}, false, fmt.Errorf("renewing after %s answered %d: %s", time.Since(start), res.StatusCode(), apierr.Body(res.Body))+ }+ token = res.JSON200.AccessToken+ expiresIn = append(expiresIn, res.JSON200.ExpiresIn)+ return struct{}{}, time.Since(start) > 2*maxTTL*time.Second, nil+ }, wait.Interval(500*time.Millisecond), wait.Timeout(15*time.Second))++ // Assert+ require.NoError(t, err)+ for _, e := range expiresIn {+ require.EqualValues(t, period, e)+ }+ requireWorks(t, tn.Client(t, token))+ })+}++func TestAccessToken_CrossOrg(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ // crossOrg is org A's admin identity and org B's resources.+ type crossOrg struct {+ a, b *harness.Tenant+ identity *harness.Principal+ }+ setup := func(t *testing.T) crossOrg {+ t.Helper()+ a, b := h.NewTenant(t), h.NewTenant(t)+ return crossOrg{a: a, b: b, identity: a.NewMachineIdentity(t, harness.OrgRole("admin"))}+ }++ t.Run("should refuse org B's org route for org A's token, naming the token's org", func(t *testing.T) {+ t.Parallel()++ // Setup+ x := setup(t)++ // Action+ res, err := x.identity.API.ListOrgMembershipsWithResponse(t.Context(), x.b.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Your token is scoped to organization with ID "+x.a.OrgID.String())+ require.NotContains(t, string(res.Body), x.b.Admin.Email)+ })++ t.Run("should refuse org B's member route for org A's token, naming the token's org", func(t *testing.T) {+ t.Parallel()++ // Setup+ x := setup(t)+ membership := fixture.MembershipOf(t, x.b, x.b.Admin.Email)++ // Action+ res, err := x.identity.API.GetOrgMembershipWithResponse(t.Context(), x.b.OrgID.String(), membership.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Your token is scoped to organization with ID "+x.a.OrgID.String())+ })++ t.Run("should refuse org B's project route for org A's token", func(t *testing.T) {+ t.Parallel()++ // Setup+ x := setup(t)+ proj := fixture.NewProject(t, x.b, fixture.WithProjectType("secret-manager"))++ // Action+ res, err := x.identity.API.ListProjectIdentityMembershipsWithResponse(t.Context(), proj.ID, nil)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "This project does not belong to your selected organization.")+ })++ t.Run("should answer 404 for org B's identity to org A's token", func(t *testing.T) {+ t.Parallel()++ // Setup+ x := setup(t)+ identityID := createIdentity(t, x.b, api.CreateMachineIdentityJSONRequestBody{})++ // Action+ res, err := x.identity.API.GetMachineIdentityByIdWithResponse(t.Context(), identityID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ })++ t.Run("should answer 404 for org B's group to org A's token", func(t *testing.T) {+ t.Parallel()++ // Setup+ x := setup(t)+ group := fixture.NewGroup(t, x.b)++ // Action+ res, err := x.identity.API.GetGroupByIdWithResponse(t.Context(), group.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.NotContains(t, string(res.Body), group.Name)+ })+}++func TestAccessToken_Header(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a request with no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res, err := tn.Anonymous(t).ListOrgMembershipsWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Token missing")+ })++ t.Run("should refuse an unsigned token as a token error", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ real := claims(t, tn.NewMachineIdentity(t).Token)+ unsigned := encodeSegment(t, map[string]any{"alg": "none", "typ": "JWT"}) + "." + encodeSegment(t, real) + "."++ // Action+ res, err := tn.Client(t, unsigned).ListOrgMembershipsWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), `"error":"TokenError"`)+ })++ t.Run("should refuse an identity token signed with another secret as a token error", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ forged := signHS256(t, "not-the-server-secret", claims(t, tn.NewMachineIdentity(t).Token))++ // Action+ res, err := tn.Client(t, forged).ListOrgMembershipsWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), `"error":"TokenError"`)+ })++ t.Run("should refuse a refresh token used as a bearer token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ refresh := refreshToken(t, tn)++ // Action+ res, err := tn.Client(t, refresh).ListOrgMembershipsWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Token missing")+ })++ t.Run("should refuse a signup token used as a bearer token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ signup := signupToken(t, tn)++ // Action+ res, err := tn.Client(t, signup).ListOrgMembershipsWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Token missing")+ })++ t.Run("should refuse an x-api-key header with the not supported anymore message", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ withAPIKey := func(_ context.Context, req *http.Request) error {+ req.Header.Set("x-api-key", "legacy-api-key")+ return nil+ }++ // Action+ res, err := tn.Anonymous(t).ListOrgMembershipsWithResponse(t.Context(), tn.OrgID.String(), withAPIKey)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "API key authentication is not supported anymore")+ })++ t.Run("should refuse an identity token on a route that does not accept identity tokens", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identity := tn.NewMachineIdentity(t, harness.OrgRole("admin"))++ // Action+ res, err := identity.API.GetCurrentUserV1WithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Forbidden access to /api/v1/user")+ })+}++func renew(t *testing.T, tn *harness.Tenant, token string) *api.RenewIdentityAccessTokenResponse {+ t.Helper()+ res, err := tn.Anonymous(t).RenewIdentityAccessTokenWithResponse(t.Context(),+ api.RenewIdentityAccessTokenJSONRequestBody{AccessToken: token})+ require.NoError(t, err)+ return res+}++func revoke(t *testing.T, tn *harness.Tenant, token string) *api.RevokeIdentityAccessTokenResponse {+ t.Helper()+ res, err := tn.Anonymous(t).RevokeIdentityAccessTokenWithResponse(t.Context(),+ api.RevokeIdentityAccessTokenJSONRequestBody{AccessToken: token})+ require.NoError(t, err)+ return res+}++// refusedForMaxTTL accepts both ways a renewal past the max TTL is refused: the budget+// check, or the presented token having expired, since no renewed token outlives the+// budget.+func refusedForMaxTTL(status int, body []byte) bool {+ msg := string(body)+ return (status == http.StatusUnauthorized && strings.Contains(msg, "reached its max TTL")) ||+ (status == http.StatusForbidden && strings.Contains(msg, "Your token has expired"))+}++func encodeSegment(t *testing.T, v any) string {+ t.Helper()+ raw, err := json.Marshal(v)+ require.NoError(t, err)+ return base64.RawURLEncoding.EncodeToString(raw)+}++func signHS256(t *testing.T, secret string, payload map[string]any) string {+ t.Helper()+ signing := encodeSegment(t, map[string]any{"alg": "HS256", "typ": "JWT"}) + "." + encodeSegment(t, payload)+ mac := hmac.New(sha256.New, []byte(secret))+ mac.Write([]byte(signing))+ return signing + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))+}++// refreshToken logs the tenant admin in with a password and returns the refresh token+// the login sets as a cookie.+func refreshToken(t *testing.T, tn *harness.Tenant) string {+ t.Helper()+ res, err := tn.Anonymous(t).LoginV3WithResponse(t.Context(), api.LoginV3JSONRequestBody{+ Email: tn.Admin.Email, Password: harness.UserPassword,+ })+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ for _, c := range res.HTTPResponse.Cookies() {+ if c.Name == "jid" {+ return c.Value+ }+ }+ t.Fatal("login set no refresh token cookie")+ return ""+}++// signupToken starts an email signup and returns the token the verified code is+// exchanged for, which only completes an account.+func signupToken(t *testing.T, tn *harness.Tenant) string {+ t.Helper()+ addr := tn.Email("signup-" + strings.ToLower(time.Now().Format("150405.000000")))+ anon := tn.Anonymous(t)+ begun, err := anon.BeginEmailSignupV3WithResponse(t.Context(), api.BeginEmailSignupV3JSONRequestBody{Email: openapi_types.Email(addr)})+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, begun.StatusCode(), begun.Body)+ code, err := mail.Code(tn.Mail(t).Expect(t, addr, smtp.Subject("confirmation code")), 6)+ require.NoError(t, err)+ verified, err := anon.VerifyEmailSignupV3WithResponse(t.Context(), api.VerifyEmailSignupV3JSONRequestBody{Email: openapi_types.Email(addr), Code: code})+ require.NoError(t, err)+ require.NotNilf(t, verified.JSON200, "verifying the signup returned %d: %s", verified.StatusCode(), apierr.Body(verified.Body))+ return verified.JSON200.Token+}diff --git a/tests/suites/machineidentity/helpers_test.go b/tests/suites/machineidentity/helpers_test.gonew file mode 100644index 0000000000..7768cf4eb3--- /dev/null+++ b/tests/suites/machineidentity/helpers_test.go@@ -0,0 +1,238 @@+package machineidentity_test++import (+ "bytes"+ "context"+ "crypto/rand"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++// uaIdentity is an org identity with universal auth whose credentials the test holds,+// so it can log in as often, and from wherever, the claim needs.+type uaIdentity struct {+ ID uuid.UUID+ Name string+ ClientID string+ ClientSecret string+ SecretID string+}++// createIdentity creates an org identity as the tenant admin and returns its id. Name and+// organization are filled in when the body leaves them empty.+func createIdentity(t *testing.T, tn *harness.Tenant, body api.CreateMachineIdentityJSONRequestBody) uuid.UUID {+ t.Helper()+ if body.Name == "" {+ body.Name = "i-" + id.Short()+ }+ body.OrganizationId = tn.OrgID.String()+ if body.Role == nil {+ body.Role = new("member")+ }+ res, err := tn.Admin.API.CreateMachineIdentityWithResponse(t.Context(), body)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "creating identity %s returned %d: %s", body.Name, res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.Identity.Id+}++// attachUA attaches universal auth as the tenant admin and returns the client id.+func attachUA(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, body api.AttachUniversalAuthJSONRequestBody) string {+ t.Helper()+ res, err := tn.Admin.API.AttachUniversalAuthWithResponse(t.Context(), identityID.String(), body)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "attaching universal auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.IdentityUniversalAuth.ClientId+}++// addClientSecret creates a client secret as the tenant admin and returns it with its id.+func addClientSecret(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, body api.CreateUniversalAuthClientSecretJSONRequestBody) (string, string) {+ t.Helper()+ res, err := tn.Admin.API.CreateUniversalAuthClientSecretWithResponse(t.Context(), identityID.String(), body)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "creating a client secret returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.ClientSecret, res.JSON200.ClientSecretData.Id+}++// newUA creates a member identity with universal auth configured by attach and one+// client secret.+func newUA(t *testing.T, tn *harness.Tenant, attach api.AttachUniversalAuthJSONRequestBody) *uaIdentity {+ t.Helper()+ name := "ua-" + id.Short()+ identityID := createIdentity(t, tn, api.CreateMachineIdentityJSONRequestBody{Name: name})+ clientID := attachUA(t, tn, identityID, attach)+ secret, secretID := addClientSecret(t, tn, identityID, api.CreateUniversalAuthClientSecretJSONRequestBody{})+ return &uaIdentity{ID: identityID, Name: name, ClientID: clientID, ClientSecret: secret, SecretID: secretID}+}++// uaLogin logs in through c, which decides the source address.+func uaLogin(t *testing.T, c *api.ClientWithResponses, clientID, secret, orgSlug string) *api.LoginWithUniversalAuthResponse {+ t.Helper()+ res, err := c.LoginWithUniversalAuthWithResponse(t.Context(), api.LoginWithUniversalAuthJSONRequestBody{+ ClientId: clientID,+ ClientSecret: secret,+ OrganizationSlug: &orgSlug,+ })+ require.NoError(t, err)+ return res+}++// login logs the identity into the tenant's organization and returns the access token.+func (u *uaIdentity) login(t *testing.T, tn *harness.Tenant) string {+ t.Helper()+ res := uaLogin(t, tn.Anonymous(t), u.ClientID, u.ClientSecret, tn.OrgSlug)+ require.NotNilf(t, res.JSON200, "logging in as %s returned %d: %s", u.Name, res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.AccessToken+}++// whoami is the cheapest call an identity token can make, so it is what proves a token+// still authenticates. Every call counts against a token's use limit.+func whoami(t *testing.T, c *api.ClientWithResponses) (int, []byte) {+ t.Helper()+ res, err := c.GetMachineIdentityDetailsWithResponse(t.Context())+ require.NoError(t, err)+ return res.StatusCode(), res.Body+}++func requireWorks(t *testing.T, c *api.ClientWithResponses) {+ t.Helper()+ status, body := whoami(t, c)+ requireStatus(t, http.StatusOK, status, body)+}++func requireStatus(t *testing.T, want, got int, body []byte) {+ t.Helper()+ require.Equalf(t, want, got, "answered %d: %s", got, apierr.Body(body))+}++// waitForStatus polls a call until it answers with the wanted status. Permission and+// revocation changes can reach a token a few seconds late.+func waitForStatus(t *testing.T, want int, call func() (int, []byte)) []byte {+ t.Helper()+ var last []byte+ var lastStatus int+ _, err := wait.For(t.Context(), func(context.Context) (struct{}, bool, error) {+ lastStatus, last = call()+ return struct{}{}, lastStatus == want, nil+ })+ require.NoErrorf(t, err, "waiting for %d, last %d: %s", want, lastStatus, apierr.Body(last))+ return last+}++// sourceIP is a fresh address for a caller whose source address is what the test is+// about.+func sourceIP() string {+ b := make([]byte, 3)+ _, _ = rand.Read(b)+ return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])+}++type trustedIP = struct {+ IpAddress string `json:"ipAddress"`+}++func ips(addrs ...string) *[]trustedIP {+ out := make([]trustedIP, 0, len(addrs))+ for _, a := range addrs {+ out = append(out, trustedIP{IpAddress: a})+ }+ return &out+}++// storedIPs reads a trusted IP list as the API returns it: each entry is stored as an+// address plus prefix.+func storedIPs(v any) []string {+ entries, _ := v.([]any)+ out := []string{}+ for _, e := range entries {+ m, _ := e.(map[string]any)+ addr, _ := m["ipAddress"].(string)+ if prefix, ok := m["prefix"].(float64); ok {+ addr = fmt.Sprintf("%s/%d", addr, int(prefix))+ }+ out = append(out, addr)+ }+ return out+}++func getUA(t *testing.T, tn *harness.Tenant, identityID uuid.UUID) *api.GetUniversalAuthResponse {+ t.Helper()+ res, err := tn.Admin.API.GetUniversalAuthWithResponse(t.Context(), identityID.String())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "reading universal auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return res+}++// claims decodes an access token's payload. The test holds the token, so reading what it+// carries is observing the response, not reaching into the server.+func claims(t *testing.T, token string) map[string]any {+ t.Helper()+ parts := strings.Split(token, ".")+ require.Len(t, parts, 3, "an access token is a JWT")+ raw, err := base64.RawURLEncoding.DecodeString(parts[1])+ require.NoError(t, err)+ out := map[string]any{}+ require.NoError(t, json.Unmarshal(raw, &out))+ return out+}++func jsonBody(t *testing.T, v any) io.Reader {+ t.Helper()+ raw, err := json.Marshal(v)+ require.NoError(t, err)+ return bytes.NewReader(raw)+}++// permanentRoles is a membership body's roles, sent as raw JSON because the generated+// item type is a union.+func permanentRoles(slugs ...string) map[string]any {+ roles := make([]map[string]any, 0, len(slugs))+ for _, s := range slugs {+ roles = append(roles, map[string]any{"role": s, "isTemporary": false})+ }+ return map[string]any{"roles": roles}+}++// identityNames lists the identities that hold a membership in an organization, as c+// sees them.+func identityNames(t *testing.T, c *api.ClientWithResponses, orgID string) []string {+ t.Helper()+ res, err := c.ListOrgIdentityMembershipsWithResponse(t.Context(), orgID, nil)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing identities returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ names := []string{}+ for _, m := range res.JSON200.IdentityMemberships {+ names = append(names, m.Identity.Name)+ }+ return names+}++func getIdentity(t *testing.T, tn *harness.Tenant, identityID uuid.UUID) *api.GetMachineIdentityByIdResponse {+ t.Helper()+ res, err := tn.Admin.API.GetMachineIdentityByIdWithResponse(t.Context(), identityID.String())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "reading identity returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return res+}++// linkIdentity gives a root identity a membership in a sub-organization, as the+// sub-organization's admin.+func linkIdentity(t *testing.T, subAdmin *harness.Principal, identityID uuid.UUID, role string) {+ t.Helper()+ res, err := subAdmin.API.CreateOrganizationIdentityMembershipWithBodyWithResponse(t.Context(),+ identityID.String(), "application/json", jsonBody(t, permanentRoles(role)))+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+}diff --git a/tests/suites/machineidentity/jwtauth_test.go b/tests/suites/machineidentity/jwtauth_test.gonew file mode 100644index 0000000000..3f76017633--- /dev/null+++ b/tests/suites/machineidentity/jwtauth_test.go@@ -0,0 +1,227 @@+package machineidentity_test++import (+ "crypto"+ "crypto/rand"+ "crypto/rsa"+ "crypto/sha256"+ "crypto/x509"+ "encoding/base64"+ "encoding/pem"+ "maps"+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++const (+ jwtIssuer = "https://issuer.test"+ jwtAudience = "infisical"+ jwtSubject = "workload"+)++func TestJwtAuth_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for a JWT signed by a configured key", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ key := rsaKey(t)+ identityID := jwtIdentity(t, tn, key)++ // Action+ res := jwtLogin(t, tn, identityID, signRS256(t, key, workloadClaims(nil)))++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ requireWorks(t, tn.Client(t, res.JSON200.AccessToken))+ })++ refusals := []struct {+ name string+ status int+ message string+ sign func(t *testing.T, configured *rsa.PrivateKey) string+ }{+ {+ name: "should refuse a JWT signed by a key that is not configured", status: http.StatusUnauthorized,+ message: "JWT verification failed with all keys",+ sign: func(t *testing.T, _ *rsa.PrivateKey) string {+ return signRS256(t, rsaKey(t), workloadClaims(nil))+ },+ },+ {+ name: "should refuse a JWT from another issuer", status: http.StatusForbidden,+ message: "Access denied: issuer mismatch",+ sign: func(t *testing.T, key *rsa.PrivateKey) string {+ return signRS256(t, key, workloadClaims(map[string]any{"iss": "https://other-issuer.test"}))+ },+ },+ {+ name: "should refuse a JWT for another audience", status: http.StatusUnauthorized,+ message: "Access denied: token audience not allowed",+ sign: func(t *testing.T, key *rsa.PrivateKey) string {+ return signRS256(t, key, workloadClaims(map[string]any{"aud": "someone-else"}))+ },+ },+ {+ name: "should refuse a JWT for another subject", status: http.StatusForbidden,+ message: "Access denied: subject not allowed",+ sign: func(t *testing.T, key *rsa.PrivateKey) string {+ return signRS256(t, key, workloadClaims(map[string]any{"sub": "intruder"}))+ },+ },+ {+ name: "should refuse a JWT whose bound claim does not match", status: http.StatusUnauthorized,+ message: "Access denied: claim mismatch for field env",+ sign: func(t *testing.T, key *rsa.PrivateKey) string {+ return signRS256(t, key, workloadClaims(map[string]any{"env": "staging"}))+ },+ },+ }+ for _, tc := range refusals {+ t.Run(tc.name+" and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ key := rsaKey(t)+ identityID := jwtIdentity(t, tn, key)++ // Action+ res := jwtLogin(t, tn, identityID, tc.sign(t, key))++ // Assert+ requireStatus(t, tc.status, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), tc.message)+ require.Nil(t, res.JSON200)+ })+ }++ t.Run("should accept a JWT after its key is added and refuse it after the key is removed", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ original, added := rsaKey(t), rsaKey(t)+ identityID := jwtIdentity(t, tn, original)+ before := jwtLogin(t, tn, identityID, signRS256(t, added, workloadClaims(nil)))+ requireStatus(t, http.StatusUnauthorized, before.StatusCode(), before.Body)++ // Action+ updateJwtKeys(t, tn, identityID, original, added)+ withKey := jwtLogin(t, tn, identityID, signRS256(t, added, workloadClaims(nil)))+ updateJwtKeys(t, tn, identityID, original)+ withoutKey := jwtLogin(t, tn, identityID, signRS256(t, added, workloadClaims(nil)))++ // Assert+ requireStatus(t, http.StatusOK, withKey.StatusCode(), withKey.Body)+ requireStatus(t, http.StatusUnauthorized, withoutKey.StatusCode(), withoutKey.Body)+ require.Contains(t, string(withoutKey.Body), "JWT verification failed with all keys")+ })++ t.Run("should answer 404 to a login for an identity without the method configured", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identity := tn.NewMachineIdentity(t)++ // Action+ res := jwtLogin(t, tn, identity.ID, signRS256(t, rsaKey(t), workloadClaims(nil)))++ // Assert+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "JWT auth method not found for identity")+ })+}++func rsaKey(t *testing.T) *rsa.PrivateKey {+ t.Helper()+ key, err := rsa.GenerateKey(rand.Reader, 2048)+ require.NoError(t, err)+ return key+}++func publicKeyPEM(t *testing.T, key *rsa.PrivateKey) string {+ t.Helper()+ der, err := x509.MarshalPKIXPublicKey(&key.PublicKey)+ require.NoError(t, err)+ return string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}))+}++// workloadClaims satisfies every binding jwtIdentity configures, with overrides applied.+func workloadClaims(overrides map[string]any) map[string]any {+ now := time.Now()+ c := map[string]any{+ "iss": jwtIssuer,+ "aud": jwtAudience,+ "sub": jwtSubject,+ "env": "prod",+ "iat": now.Unix(),+ "exp": now.Add(time.Minute).Unix(),+ }+ maps.Copy(c, overrides)+ return c+}++func signRS256(t *testing.T, key *rsa.PrivateKey, payload map[string]any) string {+ t.Helper()+ signing := encodeSegment(t, map[string]any{"alg": "RS256", "typ": "JWT"}) + "." + encodeSegment(t, payload)+ digest := sha256.Sum256([]byte(signing))+ sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:])+ require.NoError(t, err)+ return signing + "." + base64.RawURLEncoding.EncodeToString(sig)+}++func jwtConfig(t *testing.T, keys ...*rsa.PrivateKey) map[string]any {+ t.Helper()+ pems := make([]string, 0, len(keys))+ for _, k := range keys {+ pems = append(pems, publicKeyPEM(t, k))+ }+ return map[string]any{+ "configurationType": "static",+ "publicKeys": pems,+ "boundIssuer": jwtIssuer,+ "boundAudiences": jwtAudience,+ "boundSubject": jwtSubject,+ "boundClaims": map[string]string{"env": "prod"},+ }+}++// jwtIdentity creates an identity with JWT auth trusting key's static public key.+func jwtIdentity(t *testing.T, tn *harness.Tenant, key *rsa.PrivateKey) uuid.UUID {+ t.Helper()+ identityID := createIdentity(t, tn, api.CreateMachineIdentityJSONRequestBody{})+ res, err := tn.Admin.API.AttachJwtAuthWithBodyWithResponse(t.Context(), identityID.String(), "application/json",+ jsonBody(t, jwtConfig(t, key)))+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return identityID+}++func updateJwtKeys(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, keys ...*rsa.PrivateKey) {+ t.Helper()+ res, err := tn.Admin.API.UpdateJwtAuthWithBodyWithResponse(t.Context(), identityID.String(), "application/json",+ jsonBody(t, jwtConfig(t, keys...)))+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+}++func jwtLogin(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, token string) *api.LoginWithJwtAuthResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginWithJwtAuthWithResponse(t.Context(), api.LoginWithJwtAuthJSONRequestBody{+ IdentityId: identityID.String(), Jwt: token,+ })+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/machineidentity/lifecycle_test.go b/tests/suites/machineidentity/lifecycle_test.gonew file mode 100644index 0000000000..62c558c35f--- /dev/null+++ b/tests/suites/machineidentity/lifecycle_test.go@@ -0,0 +1,293 @@+package machineidentity_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/stretchr/testify/require"+)++func TestMachineIdentity_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should create the identity with the requested org role", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ name := "i-" + id.Short()++ // Action+ res, err := tn.Admin.API.CreateMachineIdentityWithResponse(t.Context(), api.CreateMachineIdentityJSONRequestBody{+ Name: name, OrganizationId: tn.OrgID.String(), Role: new("member"),+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ got := getIdentity(t, tn, res.JSON200.Identity.Id).JSON200.Identity+ require.Equal(t, name, got.Identity.Name)+ require.Equal(t, "member", got.Role)+ })++ t.Run("should refuse a role the actor cannot grant and create no identity", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))+ name := "i-" + id.Short()++ // Action+ res, err := member.API.CreateMachineIdentityWithResponse(t.Context(), api.CreateMachineIdentityJSONRequestBody{+ Name: name, OrganizationId: tn.OrgID.String(), Role: new("admin"),+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to create identity. Permission denied: grant-privileges on identity")+ require.NotContains(t, identityNames(t, tn.Admin.API, tn.OrgID.String()), name)+ })++ t.Run("should refuse a custom org role when the plan does not include rbac", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "auditor", fixture.Permission{Subject: "identity", Action: []string{"read"}})+ tn.SetPlan(t, license.Enterprise().Without(license.RBAC))+ name := "i-" + id.Short()++ // Action+ res, err := tn.Admin.API.CreateMachineIdentityWithResponse(t.Context(), api.CreateMachineIdentityJSONRequestBody{+ Name: name, OrganizationId: tn.OrgID.String(), Role: new("auditor"),+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Upgrade to Infisical Enterprise to assign custom roles")+ require.NotContains(t, identityNames(t, tn.Admin.API, tn.OrgID.String()), name)+ })++ t.Run("should refuse creation past the plan's identity limit and create none", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ createIdentity(t, tn, api.CreateMachineIdentityJSONRequestBody{})+ limited := license.Enterprise().With(license.MaxIdentityLimit, 1)+ limited.Slug = "pro"+ tn.SetPlan(t, limited)+ name := "i-" + id.Short()++ // Action+ res, err := tn.Admin.API.CreateMachineIdentityWithResponse(t.Context(), api.CreateMachineIdentityJSONRequestBody{+ Name: name, OrganizationId: tn.OrgID.String(), Role: new("member"),+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "identity limit reached")+ require.NotContains(t, identityNames(t, tn.Admin.API, tn.OrgID.String()), name)+ })++ t.Run("should refuse a member without identity create permission", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "identity-reader", fixture.Permission{Subject: "identity", Action: []string{"read"}})+ reader := tn.NewMachineIdentity(t, harness.OrgRole("identity-reader"))+ name := "i-" + id.Short()++ // Action+ res, err := reader.API.CreateMachineIdentityWithResponse(t.Context(), api.CreateMachineIdentityJSONRequestBody{+ Name: name, OrganizationId: tn.OrgID.String(), Role: new("no-access"),+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.NotContains(t, identityNames(t, tn.Admin.API, tn.OrgID.String()), name)+ })+}++func TestMachineIdentity_RoleChange(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should apply a downgraded org role to an existing token on its next request", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identity := tn.NewMachineIdentity(t, harness.OrgRole("admin"))+ status, body := createGroupAs(t, identity.API)+ requireStatus(t, http.StatusOK, status, body)++ // Action+ res, err := tn.Admin.API.UpdateMachineIdentityWithResponse(t.Context(), identity.ID.String(),+ api.UpdateMachineIdentityJSONRequestBody{Role: new("member")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ waitForStatus(t, http.StatusForbidden, func() (int, []byte) { return createGroupAs(t, identity.API) })+ })++ t.Run("should apply an upgraded org role without a new login", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identity := tn.NewMachineIdentity(t, harness.OrgRole("member"))+ status, body := createGroupAs(t, identity.API)+ requireStatus(t, http.StatusForbidden, status, body)++ // Action+ res, err := tn.Admin.API.UpdateMachineIdentityWithResponse(t.Context(), identity.ID.String(),+ api.UpdateMachineIdentityJSONRequestBody{Role: new("admin")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return createGroupAs(t, identity.API) })+ })+}++func TestMachineIdentity_Delete(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse deleting an identity with delete protection and keep it working", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identityID := createIdentity(t, tn, api.CreateMachineIdentityJSONRequestBody{HasDeleteProtection: new(true)})+ identity := tn.LoginWithUniversalAuth(t, identityID, "protected")++ // Action+ res, err := tn.Admin.API.DeleteMachineIdentityWithResponse(t.Context(), identityID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Identity has delete protection")+ requireWorks(t, identity.API)+ })++ t.Run("should only remove the membership when a sub-org deletes a linked root identity", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ identity := tn.NewMachineIdentity(t)+ linkIdentity(t, sub.Admin, identity.ID, "member")++ // Action+ res, err := sub.Admin.API.DeleteMachineIdentityWithResponse(t.Context(), identity.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.NotContains(t, identityNames(t, sub.Admin.API, sub.ID.String()), identity.Name)+ require.Contains(t, identityNames(t, tn.Admin.API, tn.OrgID.String()), identity.Name)+ requireWorks(t, identity.API)+ })+}++func TestMachineIdentity_OrgMembership(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a token once the identity is removed from the org", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})+ linkIdentity(t, sub.Admin, ua.ID, "member")+ login := uaLogin(t, tn.Anonymous(t), ua.ClientID, ua.ClientSecret, sub.Slug)+ requireStatus(t, http.StatusOK, login.StatusCode(), login.Body)+ inSub := tn.Client(t, login.JSON200.AccessToken)+ requireWorks(t, inSub)++ // Action+ res, err := sub.Admin.API.DeleteOrganizationIdentityMembershipWithResponse(t.Context(), ua.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ body := waitForStatus(t, http.StatusUnauthorized, func() (int, []byte) { return whoami(t, inSub) })+ require.Contains(t, string(body), "Identity is not a member of the organization")+ })++ t.Run("should answer 404 for another org's identity id, so ids cannot be probed", func(t *testing.T) {+ t.Parallel()++ // Setup+ owner := h.NewTenant(t)+ other := h.NewTenant(t)+ identityID := createIdentity(t, owner, api.CreateMachineIdentityJSONRequestBody{Name: "original"})++ // Action+ read, err := other.Admin.API.GetMachineIdentityByIdWithResponse(t.Context(), identityID.String())+ require.NoError(t, err)+ update, err := other.Admin.API.UpdateMachineIdentityWithResponse(t.Context(), identityID.String(),+ api.UpdateMachineIdentityJSONRequestBody{Name: new("renamed")})+ require.NoError(t, err)++ // Assert+ requireStatus(t, http.StatusNotFound, read.StatusCode(), read.Body)+ requireStatus(t, http.StatusNotFound, update.StatusCode(), update.Body)+ require.Equal(t, "original", getIdentity(t, owner, identityID).JSON200.Identity.Identity.Name)+ })++ t.Run("should refuse a project-managed identity being edited at org level", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ identity := proj.NewMachineIdentity(t, fixture.WithPrincipalName("project-owned"))++ // Action+ res, err := tn.Admin.API.UpdateMachineIdentityWithResponse(t.Context(), identity.ID.String(),+ api.UpdateMachineIdentityJSONRequestBody{Name: new("renamed")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Identity is managed by project")+ require.Equal(t, "project-owned", projectIdentityName(t, proj, identity.ID.String()))+ })+}++// createGroupAs is an org action the admin role grants and the member role does not, so+// it shows which org role a token currently carries.+func createGroupAs(t *testing.T, c *api.ClientWithResponses) (int, []byte) {+ t.Helper()+ res, err := c.CreateGroupWithResponse(t.Context(), api.CreateGroupJSONRequestBody{Name: "g-" + id.Short()})+ require.NoError(t, err)+ return res.StatusCode(), res.Body+}++func projectIdentityName(t *testing.T, proj *fixture.Project, identityID string) string {+ t.Helper()+ res, err := proj.Tenant().Admin.API.GetProjectMachineIdentityByIdWithResponse(t.Context(), proj.ID, identityID)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "reading project identity returned %d: %s", res.StatusCode(), res.Body)+ return res.JSON200.Identity.Name+}diff --git a/tests/suites/machineidentity/main_test.go b/tests/suites/machineidentity/main_test.gonew file mode 100644index 0000000000..21b001e94c--- /dev/null+++ b/tests/suites/machineidentity/main_test.go@@ -0,0 +1,9 @@+package machineidentity_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/harness"+)++func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }diff --git a/tests/suites/machineidentity/tlscertauth_test.go b/tests/suites/machineidentity/tlscertauth_test.gonew file mode 100644index 0000000000..f8237b4620--- /dev/null+++ b/tests/suites/machineidentity/tlscertauth_test.go@@ -0,0 +1,214 @@+package machineidentity_test++import (+ "context"+ "crypto/ecdsa"+ "crypto/elliptic"+ "crypto/rand"+ "crypto/x509"+ "crypto/x509/pkix"+ "encoding/pem"+ "math/big"+ "net/http"+ "net/url"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++const clientCertHeader = "x-identity-tls-cert-auth-client-cert"++func TestTlsCertAuth_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for a client cert issued by the configured CA with an allowed CN", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ca := newCA(t)+ identityID := tlsIdentity(t, tn, ca, false)++ // Action+ res := tlsLogin(t, tn, identityID, withClientCert(ca.issue(t, "allowed-workload").pem))++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ requireWorks(t, tn.Client(t, res.JSON200.AccessToken))+ })++ refusals := []struct {+ name string+ status int+ message string+ cert func(t *testing.T, configured *testCA) []api.RequestEditorFn+ }{+ {+ name: "should refuse a cert issued by another CA", status: http.StatusUnauthorized,+ message: "Access denied: Certificate not issued by the provided CA.",+ cert: func(t *testing.T, _ *testCA) []api.RequestEditorFn {+ return []api.RequestEditorFn{withClientCert(newCA(t).issue(t, "allowed-workload").pem)}+ },+ },+ {+ name: "should refuse a cert whose CN is not allowed", status: http.StatusUnauthorized,+ message: "Access denied: TLS Certificate Auth common name not allowed.",+ cert: func(t *testing.T, ca *testCA) []api.RequestEditorFn {+ return []api.RequestEditorFn{withClientCert(ca.issue(t, "other-workload").pem)}+ },+ },+ {+ name: "should refuse a login with no client cert header as a bad request", status: http.StatusBadRequest,+ message: "Missing TLS certificate in header",+ cert: func(*testing.T, *testCA) []api.RequestEditorFn { return nil },+ },+ {+ name: "should refuse the CA cert used as the client cert", status: http.StatusUnauthorized,+ message: "Access denied: a CA certificate cannot be used as a client certificate.",+ cert: func(_ *testing.T, ca *testCA) []api.RequestEditorFn {+ return []api.RequestEditorFn{withClientCert(ca.pem)}+ },+ },+ }+ for _, tc := range refusals {+ t.Run(tc.name+" and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ca := newCA(t)+ identityID := tlsIdentity(t, tn, ca, false)++ // Action+ res := tlsLogin(t, tn, identityID, tc.cert(t, ca)...)++ // Assert+ requireStatus(t, tc.status, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), tc.message)+ require.Nil(t, res.JSON200)+ })+ }++ t.Run("should refuse a cert-bound token presented without the cert it was issued for", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ca := newCA(t)+ identityID := tlsIdentity(t, tn, ca, true)+ cert := ca.issue(t, "allowed-workload")+ login := tlsLogin(t, tn, identityID, withClientCert(cert.pem))+ requireStatus(t, http.StatusOK, login.StatusCode(), login.Body)+ token := login.JSON200.AccessToken++ // Action+ bare, err := tn.Client(t, token).GetMachineIdentityDetailsWithResponse(t.Context())+ require.NoError(t, err)+ other, err := tn.Client(t, token).GetMachineIdentityDetailsWithResponse(t.Context(),+ withClientCert(ca.issue(t, "allowed-workload").pem))+ require.NoError(t, err)++ // Assert+ requireStatus(t, http.StatusUnauthorized, bare.StatusCode(), bare.Body)+ require.Contains(t, string(bare.Body), "no client certificate was presented")+ requireStatus(t, http.StatusUnauthorized, other.StatusCode(), other.Body)+ require.Contains(t, string(other.Body), "does not match the certificate the access token is bound to")+ same, err := tn.Client(t, token).GetMachineIdentityDetailsWithResponse(t.Context(), withClientCert(cert.pem))+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, same.StatusCode(), same.Body)+ })+}++type testCA struct {+ cert *x509.Certificate+ key *ecdsa.PrivateKey+ pem string+}++type testCert struct {+ pem string+}++func newCA(t *testing.T) *testCA {+ t.Helper()+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ require.NoError(t, err)+ tmpl := &x509.Certificate{+ SerialNumber: serial(t),+ Subject: pkix.Name{CommonName: "test-ca-" + uuid.NewString()[:8]},+ NotBefore: time.Now().Add(-time.Hour),+ NotAfter: time.Now().Add(time.Hour),+ IsCA: true,+ BasicConstraintsValid: true,+ KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},+ }+ der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)+ require.NoError(t, err)+ cert, err := x509.ParseCertificate(der)+ require.NoError(t, err)+ return &testCA{cert: cert, key: key, pem: string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))}+}++// issue signs a client-auth leaf certificate with the given common name.+func (ca *testCA) issue(t *testing.T, cn string) testCert {+ t.Helper()+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ require.NoError(t, err)+ tmpl := &x509.Certificate{+ SerialNumber: serial(t),+ Subject: pkix.Name{CommonName: cn},+ NotBefore: time.Now().Add(-time.Hour),+ NotAfter: time.Now().Add(time.Hour),+ KeyUsage: x509.KeyUsageDigitalSignature,+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},+ }+ der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.cert, &key.PublicKey, ca.key)+ require.NoError(t, err)+ return testCert{pem: string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))}+}++func serial(t *testing.T) *big.Int {+ t.Helper()+ n, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 62))+ require.NoError(t, err)+ return n+}++// withClientCert sends a certificate the way a TLS-terminating proxy forwards it:+// URL-encoded PEM in a header. Path escaping, because the server decodes with+// decodeURIComponent, which leaves a '+' as a plus rather than a space.+func withClientCert(certPEM string) api.RequestEditorFn {+ return func(_ context.Context, req *http.Request) error {+ req.Header.Set(clientCertHeader, url.PathEscape(certPEM))+ return nil+ }+}++// tlsIdentity creates an identity whose TLS cert auth trusts ca and allows the common+// name allowed-workload.+func tlsIdentity(t *testing.T, tn *harness.Tenant, ca *testCA, bind bool) uuid.UUID {+ t.Helper()+ identityID := createIdentity(t, tn, api.CreateMachineIdentityJSONRequestBody{})+ res, err := tn.Admin.API.AttachTlsCertAuthWithResponse(t.Context(), identityID.String(), api.AttachTlsCertAuthJSONRequestBody{+ CaCertificate: ca.pem,+ AllowedCommonNames: new("allowed-workload"),+ BindAccessTokenToCertificate: &bind,+ })+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return identityID+}++func tlsLogin(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, editors ...api.RequestEditorFn) *api.LoginWithTlsCertAuthResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginWithTlsCertAuthWithResponse(t.Context(),+ api.LoginWithTlsCertAuthJSONRequestBody{IdentityId: identityID.String()}, editors...)+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/machineidentity/tokenauth_test.go b/tests/suites/machineidentity/tokenauth_test.gonew file mode 100644index 0000000000..dd770fbdfa--- /dev/null+++ b/tests/suites/machineidentity/tokenauth_test.go@@ -0,0 +1,130 @@+package machineidentity_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func TestTokenAuth_Tokens(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should authenticate with a created token and stop on revoke", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identityID := tokenAuthIdentity(t, tn)+ created := newTokenAuthToken(t, tn.Admin.API, identityID)+ c := tn.Client(t, created.JSON200.AccessToken)+ requireWorks(t, c)++ // Action+ res, err := tn.Admin.API.RevokeTokenAuthTokenWithResponse(t.Context(), created.JSON200.TokenData.Id)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ waitForStatus(t, http.StatusUnauthorized, func() (int, []byte) { return whoami(t, c) })+ })++ t.Run("should answer 404 when a token is revoked twice", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ created := newTokenAuthToken(t, tn.Admin.API, tokenAuthIdentity(t, tn))+ tokenID := created.JSON200.TokenData.Id+ first, err := tn.Admin.API.RevokeTokenAuthTokenWithResponse(t.Context(), tokenID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, first.StatusCode(), first.Body)++ // Action+ res, err := tn.Admin.API.RevokeTokenAuthTokenWithResponse(t.Context(), tokenID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "not found or already revoked")+ })++ t.Run("should list tokens by name and never their values", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identityID := tokenAuthIdentity(t, tn)+ ci := createTokenAuthToken(t, tn.Admin.API, identityID, "ci")+ deploy := createTokenAuthToken(t, tn.Admin.API, identityID, "deploy")++ // Action+ res, err := tn.Admin.API.GetTokenAuthTokensWithResponse(t.Context(), identityID.String(), nil)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ names := []string{}+ for _, tok := range res.JSON200.Tokens {+ if tok.Name != nil {+ names = append(names, *tok.Name)+ }+ }+ require.ElementsMatch(t, []string{"ci", "deploy"}, names)+ require.NotContains(t, string(res.Body), ci.JSON200.AccessToken)+ require.NotContains(t, string(res.Body), deploy.JSON200.AccessToken)+ })++ t.Run("should refuse creating a token without create-token permission", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identityID := tokenAuthIdentity(t, tn)+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))++ // Action+ res := createTokenAuthToken(t, member.API, identityID, "sneaky")++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ listed, err := tn.Admin.API.GetTokenAuthTokensWithResponse(t.Context(), identityID.String(), nil)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, listed.StatusCode(), listed.Body)+ require.Empty(t, listed.JSON200.Tokens)+ })+}++// tokenAuthIdentity creates a member identity with only token auth attached.+func tokenAuthIdentity(t *testing.T, tn *harness.Tenant) uuid.UUID {+ t.Helper()+ identityID := createIdentity(t, tn, api.CreateMachineIdentityJSONRequestBody{})+ attachTokenAuth(t, tn, identityID, api.AttachTokenAuthJSONRequestBody{})+ return identityID+}++func attachTokenAuth(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, body api.AttachTokenAuthJSONRequestBody) {+ t.Helper()+ res, err := tn.Admin.API.AttachTokenAuthWithResponse(t.Context(), identityID.String(), body)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+}++func createTokenAuthToken(t *testing.T, c *api.ClientWithResponses, identityID uuid.UUID, name string) *api.CreateTokenAuthTokenResponse {+ t.Helper()+ res, err := c.CreateTokenAuthTokenWithResponse(t.Context(), identityID.String(), api.CreateTokenAuthTokenJSONRequestBody{Name: &name})+ require.NoError(t, err)+ return res+}++func newTokenAuthToken(t *testing.T, c *api.ClientWithResponses, identityID uuid.UUID) *api.CreateTokenAuthTokenResponse {+ t.Helper()+ res := createTokenAuthToken(t, c, identityID, "token")+ require.NotNilf(t, res.JSON200, "creating a token returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return res+}diff --git a/tests/suites/machineidentity/trustedip_test.go b/tests/suites/machineidentity/trustedip_test.gonew file mode 100644index 0000000000..36430ea7c3--- /dev/null+++ b/tests/suites/machineidentity/trustedip_test.go@@ -0,0 +1,114 @@+package machineidentity_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/harness/infisical"+ "github.com/stretchr/testify/require"+)++func TestMachineIdentity_TrustedIPs(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse an identity token used from outside its trusted IPs and accept it from inside", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ trusted := sourceIP()+ identity := identityTrustedFrom(t, tn, trusted)+ outside := tn.Client(t, identity.Token, infisical.ForwardedFor(sourceIP()))++ // Action+ status, body := whoami(t, outside)++ // Assert+ requireStatus(t, http.StatusForbidden, status, body)+ require.Contains(t, string(body), "You are not allowed to access this resource from the current IP address")+ requireWorks(t, identity.API)+ })++ t.Run("should apply a narrowed allowlist to tokens issued before the update", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})+ token := ua.login(t, tn)+ before := tn.Client(t, token, infisical.ForwardedFor(sourceIP()))+ requireWorks(t, before)+ trusted := sourceIP()++ // Action+ res, err := tn.Admin.API.UpdateUniversalAuthWithResponse(t.Context(), ua.ID.String(),+ api.UpdateUniversalAuthJSONRequestBody{AccessTokenTrustedIps: ips(trusted + "/32")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ body := waitForStatus(t, http.StatusForbidden, func() (int, []byte) { return whoami(t, before) })+ require.Contains(t, string(body), "from the current IP address")+ requireWorks(t, tn.Client(t, token, infisical.ForwardedFor(trusted)))+ })++ t.Run("should refuse a non-wildcard allowlist when the plan lacks IP allowlisting, and keep the old one", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.IPAllowlisting)))+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})+ old := storedIPs(getUA(t, tn, ua.ID).JSON200.IdentityUniversalAuth.AccessTokenTrustedIps)++ // Action+ res, err := tn.Admin.API.UpdateUniversalAuthWithResponse(t.Context(), ua.ID.String(),+ api.UpdateUniversalAuthJSONRequestBody{AccessTokenTrustedIps: ips(sourceIP() + "/32")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Upgrade plan to add IP access range")+ require.Equal(t, old, storedIPs(getUA(t, tn, ua.ID).JSON200.IdentityUniversalAuth.AccessTokenTrustedIps))+ })++ t.Run("should refuse an invalid CIDR and keep the old allowlist", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ trusted := sourceIP() + "/32"+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTrustedIps: ips(trusted)})++ // Action+ res, err := tn.Admin.API.UpdateUniversalAuthWithResponse(t.Context(), ua.ID.String(),+ api.UpdateUniversalAuthJSONRequestBody{AccessTokenTrustedIps: ips("10.0.0.0/99")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "The IP is not a valid IPv4, IPv6, or CIDR block")+ require.Equal(t, []string{trusted}, storedIPs(getUA(t, tn, ua.ID).JSON200.IdentityUniversalAuth.AccessTokenTrustedIps))+ })+}++// identityTrustedFrom creates an org identity whose access tokens are valid only from+// one address, logged in from that address. Its API sends that address.+func identityTrustedFrom(t *testing.T, tn *harness.Tenant, ip string) *harness.Principal {+ t.Helper()+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTrustedIps: ips(ip + "/32")})+ login := uaLogin(t, tn.Anonymous(t, infisical.ForwardedFor(ip)), ua.ClientID, ua.ClientSecret, tn.OrgSlug)+ require.NotNilf(t, login.JSON200, "logging in returned %d: %s", login.StatusCode(), login.Body)++ token := login.JSON200.AccessToken+ return &harness.Principal{+ Kind: harness.MachineIdentity,+ ID: ua.ID,+ Name: ua.Name,+ Token: token,+ API: tn.Client(t, token, infisical.ForwardedFor(ip)),+ }+}diff --git a/tests/suites/machineidentity/universalauth_test.go b/tests/suites/machineidentity/universalauth_test.gonew file mode 100644index 0000000000..f03acbb022--- /dev/null+++ b/tests/suites/machineidentity/universalauth_test.go@@ -0,0 +1,453 @@+package machineidentity_test++import (+ "context"+ "fmt"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/harness/infisical"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func TestUniversalAuth_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse an unknown client id and a wrong secret with the same invalid credentials answer", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})+ anon := tn.Anonymous(t)++ // Action+ unknown := uaLogin(t, anon, uuid.NewString(), ua.ClientSecret, tn.OrgSlug)+ wrong := uaLogin(t, anon, ua.ClientID, "not-the-secret", tn.OrgSlug)++ // Assert+ requireStatus(t, http.StatusUnauthorized, unknown.StatusCode(), unknown.Body)+ requireStatus(t, http.StatusUnauthorized, wrong.StatusCode(), wrong.Body)+ require.Equal(t, "Invalid credentials", apierr.Message(unknown.Body))+ require.Equal(t, "Invalid credentials", apierr.Message(wrong.Body))+ })++ t.Run("should refuse a login from outside the client secret trusted IPs and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ trusted := sourceIP()+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{ClientSecretTrustedIps: ips(trusted + "/32")})++ // Action+ res := uaLogin(t, tn.Anonymous(t, infisical.ForwardedFor(sourceIP())), ua.ClientID, ua.ClientSecret, tn.OrgSlug)++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Nil(t, res.JSON200)+ require.Zero(t, secretUses(t, tn, ua.ID, ua.SecretID))+ inside := uaLogin(t, tn.Anonymous(t, infisical.ForwardedFor(trusted)), ua.ClientID, ua.ClientSecret, tn.OrgSlug)+ requireStatus(t, http.StatusOK, inside.StatusCode(), inside.Body)+ })++ t.Run("should log into a sub-org the identity is a direct member of", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})+ linkIdentity(t, sub.Admin, ua.ID, "member")++ // Action+ res := uaLogin(t, tn.Anonymous(t), ua.ClientID, ua.ClientSecret, sub.Slug)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, sub.ID.String(), claims(t, res.JSON200.AccessToken)["orgId"])+ requireReadsMembers(t, tn.Client(t, res.JSON200.AccessToken), sub.ID.String())+ })++ t.Run("should log into a sub-org the identity reaches through a root group", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ identity := tn.NewMachineIdentity(t)+ ua := uaFor(t, tn, identity.ID)+ group := fixture.NewGroup(t, tn)+ group.AddIdentity(t, identity)+ linked, err := sub.Admin.API.CreateOrganizationGroupMembershipWithBodyWithResponse(t.Context(), group.ID,+ "application/json", jsonBody(t, permanentRoles("member")))+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, linked.StatusCode(), linked.Body)++ // Action+ res := uaLogin(t, tn.Anonymous(t), ua.ClientID, ua.ClientSecret, sub.Slug)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, sub.ID.String(), claims(t, res.JSON200.AccessToken)["orgId"])+ requireReadsMembers(t, tn.Client(t, res.JSON200.AccessToken), sub.ID.String())+ })++ t.Run("should refuse a login into a sub-org the identity does not reach", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})++ // Action+ res := uaLogin(t, tn.Anonymous(t), ua.ClientID, ua.ClientSecret, sub.Slug)++ // Assert+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Identity not authorized to access sub organization "+sub.Slug)+ require.Nil(t, res.JSON200)+ })+}++func TestUniversalAuth_ClientSecret(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should return the secret once and list only its prefix", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})++ // Action+ res, err := tn.Admin.API.ListUniversalAuthClientSecretsWithResponse(t.Context(), ua.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Len(t, res.JSON200.ClientSecretData, 1)+ require.Equal(t, ua.ClientSecret[:4], res.JSON200.ClientSecretData[0].ClientSecretPrefix)+ require.NotContains(t, string(res.Body), ua.ClientSecret)+ })++ t.Run("should refuse new logins with a revoked secret and cut off the tokens it issued", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})+ issued := tn.Client(t, ua.login(t, tn))+ requireWorks(t, issued)++ // Action+ res, err := tn.Admin.API.RevokeUniversalAuthClientSecretWithResponse(t.Context(), ua.ID.String(), ua.SecretID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ login := uaLogin(t, tn.Anonymous(t), ua.ClientID, ua.ClientSecret, tn.OrgSlug)+ requireStatus(t, http.StatusUnauthorized, login.StatusCode(), login.Body)+ body := waitForStatus(t, http.StatusUnauthorized, func() (int, []byte) { return whoami(t, issued) })+ require.Contains(t, string(body), "client secret has been revoked")+ })++ t.Run("should keep other secrets and their tokens working when one is revoked", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})+ kept, _ := addClientSecret(t, tn, ua.ID, api.CreateUniversalAuthClientSecretJSONRequestBody{})+ keptLogin := uaLogin(t, tn.Anonymous(t), ua.ClientID, kept, tn.OrgSlug)+ requireStatus(t, http.StatusOK, keptLogin.StatusCode(), keptLogin.Body)+ revokedToken := tn.Client(t, ua.login(t, tn))++ // Action+ res, err := tn.Admin.API.RevokeUniversalAuthClientSecretWithResponse(t.Context(), ua.ID.String(), ua.SecretID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ waitForStatus(t, http.StatusUnauthorized, func() (int, []byte) { return whoami(t, revokedToken) })+ requireWorks(t, tn.Client(t, keptLogin.JSON200.AccessToken))+ again := uaLogin(t, tn.Anonymous(t), ua.ClientID, kept, tn.OrgSlug)+ requireStatus(t, http.StatusOK, again.StatusCode(), again.Body)+ })++ t.Run("should accept N logins with numUsesLimit N, refuse the next, and revoke the secret", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})+ secret, secretID := addClientSecret(t, tn, ua.ID, api.CreateUniversalAuthClientSecretJSONRequestBody{NumUsesLimit: new(float32(2))})+ for range 2 {+ res := uaLogin(t, tn.Anonymous(t), ua.ClientID, secret, tn.OrgSlug)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ }++ // Action+ res := uaLogin(t, tn.Anonymous(t), ua.ClientID, secret, tn.OrgSlug)++ // Assert+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Access denied due to client secret usage limit reached")+ require.True(t, secretRevoked(t, tn, ua.ID, secretID))+ })++ t.Run("should refuse and revoke an expired secret", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})+ secret, secretID := addClientSecret(t, tn, ua.ID, api.CreateUniversalAuthClientSecretJSONRequestBody{Ttl: new(float32(1))})++ // Action+ refused, err := wait.For(t.Context(), func(context.Context) (*api.LoginWithUniversalAuthResponse, bool, error) {+ res := uaLogin(t, tn.Anonymous(t), ua.ClientID, secret, tn.OrgSlug)+ return res, res.StatusCode() != http.StatusOK, nil+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnauthorized, refused.StatusCode(), refused.Body)+ require.Contains(t, string(refused.Body), "Access denied due to expired client secret")+ require.True(t, secretRevoked(t, tn, ua.ID, secretID))+ })++ t.Run("should refuse creating a secret without create-token permission and create none", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))++ // Action+ res, err := member.API.CreateUniversalAuthClientSecretWithResponse(t.Context(), ua.ID.String(),+ api.CreateUniversalAuthClientSecretJSONRequestBody{})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ listed, err := tn.Admin.API.ListUniversalAuthClientSecretsWithResponse(t.Context(), ua.ID.String())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, listed.StatusCode(), listed.Body)+ require.Len(t, listed.JSON200.ClientSecretData, 1)+ })+}++func TestUniversalAuth_Lockout(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ lockable := api.AttachUniversalAuthJSONRequestBody{+ LockoutEnabled: new(true),+ LockoutThreshold: new(float32(2)),+ LockoutDurationSeconds: new(float32(300)),+ }++ t.Run("should lock after the threshold of wrong secrets and refuse even the right secret", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, lockable)++ // Action+ failWrong(t, tn, ua, 2)++ // Assert+ res := uaLogin(t, tn.Anonymous(t), ua.ClientID, ua.ClientSecret, tn.OrgSlug)+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "This identity auth method is temporarily locked")+ })++ t.Run("should accept the identity again after clear-lockouts", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, lockable)+ failWrong(t, tn, ua, 2)++ // Action+ res, err := tn.Admin.API.ClearUniversalAuthLockoutsWithResponse(t.Context(), ua.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ login := uaLogin(t, tn.Anonymous(t), ua.ClientID, ua.ClientSecret, tn.OrgSlug)+ requireStatus(t, http.StatusOK, login.StatusCode(), login.Body)+ })++ t.Run("should not lock when lockout is disabled", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{LockoutEnabled: new(false), LockoutThreshold: new(float32(2))})++ // Action+ failWrong(t, tn, ua, 4)++ // Assert+ res := uaLogin(t, tn.Anonymous(t), ua.ClientID, ua.ClientSecret, tn.OrgSlug)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Empty(t, getIdentity(t, tn, ua.ID).JSON200.Identity.Identity.ActiveLockoutAuthMethods)+ })++ t.Run("should show the method in activeLockoutAuthMethods while locked", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, lockable)+ require.Empty(t, getIdentity(t, tn, ua.ID).JSON200.Identity.Identity.ActiveLockoutAuthMethods)++ // Action+ failWrong(t, tn, ua, 2)++ // Assert+ require.Equal(t, []string{"universal-auth"}, getIdentity(t, tn, ua.ID).JSON200.Identity.Identity.ActiveLockoutAuthMethods)+ })+}++func TestUniversalAuth_Configure(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a TTL greater than the max TTL and keep the old config", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{AccessTokenTTL: new(60), AccessTokenMaxTTL: new(120)})++ // Action+ res, err := tn.Admin.API.UpdateUniversalAuthWithResponse(t.Context(), ua.ID.String(),+ api.UpdateUniversalAuthJSONRequestBody{AccessTokenTTL: new(121)})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Access token TTL cannot be greater than max TTL")+ require.EqualValues(t, 60, *getUA(t, tn, ua.ID).JSON200.IdentityUniversalAuth.AccessTokenTTL)+ })++ t.Run("should refuse attaching twice", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ ua := newUA(t, tn, api.AttachUniversalAuthJSONRequestBody{})++ // Action+ res, err := tn.Admin.API.AttachUniversalAuthWithResponse(t.Context(), ua.ID.String(), api.AttachUniversalAuthJSONRequestBody{})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to add universal auth to already configured identity")+ require.Equal(t, ua.ClientID, getUA(t, tn, ua.ID).JSON200.IdentityUniversalAuth.ClientId)+ })++ t.Run("should refuse configuring an identity when the actor lacks edit-auth, and keep the config", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := tn.NewMachineIdentity(t, harness.OrgRole("admin"))+ member := tn.NewMachineIdentity(t, harness.OrgRole("member"))+ before := getUA(t, tn, target.ID).JSON200.IdentityUniversalAuth.AccessTokenTTL++ // Action+ res, err := member.API.UpdateUniversalAuthWithResponse(t.Context(), target.ID.String(),+ api.UpdateUniversalAuthJSONRequestBody{AccessTokenTTL: new(1)})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Equal(t, before, getUA(t, tn, target.ID).JSON200.IdentityUniversalAuth.AccessTokenTTL)+ })++ t.Run("should refuse tokens from a removed method and keep tokens from other methods working", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identity := tn.NewMachineIdentity(t)+ attachTokenAuth(t, tn, identity.ID, api.AttachTokenAuthJSONRequestBody{})+ other := tn.Client(t, newTokenAuthToken(t, tn.Admin.API, identity.ID).JSON200.AccessToken)++ // Action+ res, err := tn.Admin.API.DeleteUniversalAuthWithResponse(t.Context(), identity.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ body := waitForStatus(t, http.StatusUnauthorized, func() (int, []byte) { return whoami(t, identity.API) })+ require.Contains(t, string(body), "auth method has been revoked")+ requireWorks(t, other)+ })+}++// uaFor attaches universal auth and a client secret to an existing identity.+func uaFor(t *testing.T, tn *harness.Tenant, identityID uuid.UUID) *uaIdentity {+ t.Helper()+ res := getUA(t, tn, identityID)+ secret, secretID := addClientSecret(t, tn, identityID, api.CreateUniversalAuthClientSecretJSONRequestBody{})+ return &uaIdentity{ID: identityID, ClientID: res.JSON200.IdentityUniversalAuth.ClientId, ClientSecret: secret, SecretID: secretID}+}++// failWrong sends n logins with a wrong secret, each refused as invalid credentials.+func failWrong(t *testing.T, tn *harness.Tenant, ua *uaIdentity, n int) {+ t.Helper()+ for i := range n {+ res := uaLogin(t, tn.Anonymous(t), ua.ClientID, fmt.Sprintf("wrong-secret-%d", i), tn.OrgSlug)+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ }+}++func readSecret(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, secretID string) *api.GetUniversalAuthClientSecretResponse {+ t.Helper()+ res, err := tn.Admin.API.GetUniversalAuthClientSecretWithResponse(t.Context(), identityID.String(), secretID)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "reading client secret returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return res+}++func secretRevoked(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, secretID string) bool {+ t.Helper()+ revoked := readSecret(t, tn, identityID, secretID).JSON200.ClientSecretData.IsClientSecretRevoked+ return revoked != nil && *revoked+}++func secretUses(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, secretID string) float32 {+ t.Helper()+ uses := readSecret(t, tn, identityID, secretID).JSON200.ClientSecretData.ClientSecretNumUses+ if uses == nil {+ return 0+ }+ return *uses+}++// requireReadsMembers proves a token acts inside an organization: org members can list+// its memberships, and nobody else can.+func requireReadsMembers(t *testing.T, c *api.ClientWithResponses, orgID string) {+ t.Helper()+ res, err := c.ListOrgMembershipsWithResponse(t.Context(), orgID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+}diff --git a/tests/suites/machineidentityfed/alicloudauth_test.go b/tests/suites/machineidentityfed/alicloudauth_test.gonew file mode 100644index 0000000000..aaf72e3e91--- /dev/null+++ b/tests/suites/machineidentityfed/alicloudauth_test.go@@ -0,0 +1,115 @@+package machineidentityfed_test++import (+ "net/http"+ "net/url"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/alicloud"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++const fedAliCloudAccount = "1234567890123456"++func TestAliCloudAuth_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for an access key whose caller ARN is allowed", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ akid, arn := fedNewAliCloudKey(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachAliCloud(t, tn, identityID, arn)++ // Action+ res := fedLoginAliCloud(t, tn, identityID, akid)++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })++ t.Run("should refuse a caller ARN outside the allowlist and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ akid, _ := fedNewAliCloudKey(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachAliCloud(t, tn, identityID, "acs:ram::"+fedAliCloudAccount+":user/someone-else")++ // Action+ res := fedLoginAliCloud(t, tn, identityID, akid)++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Access denied: Alibaba Cloud account ARN not allowed.", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should answer 404 when the identity has no Alibaba Cloud auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ akid, _ := fedNewAliCloudKey(t, tn)+ identityID := fedNewIdentity(t, tn)++ // Action+ res := fedLoginAliCloud(t, tn, identityID, akid)++ // Assert+ fedRequireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "Alibaba Cloud auth method not found for identity, did you configure Alibaba Cloud auth?", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++// fedNewAliCloudKey registers an access key with STS and returns it with its caller ARN.+func fedNewAliCloudKey(t *testing.T, tn *harness.Tenant) (akid, arn string) {+ t.Helper()+ akid = id.Nonce()+ arn = "acs:ram::" + fedAliCloudAccount + ":user/" + akid+ alicloud.Open(t, fixture.FakenetAdmin(t, tn), akid, fedAliCloudAccount, arn)+ return akid, arn+}++func fedAttachAliCloud(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, arns string) {+ t.Helper()+ res, err := tn.Admin.API.AttachAlicloudAuthWithResponse(t.Context(), identityID.String(),+ api.AttachAlicloudAuthJSONRequestBody{AllowedArns: arns})+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "attaching Alibaba Cloud auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++// fedLoginAliCloud sends the signed GetCallerIdentity parameters a workload would.+func fedLoginAliCloud(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, akid string) *api.LoginWithAlicloudAuthResponse {+ t.Helper()+ params := url.Values{+ "Action": {"GetCallerIdentity"},+ "Format": {"JSON"},+ "Version": {"2015-04-01"},+ "AccessKeyId": {akid},+ "SignatureMethod": {"HMAC-SHA1"},+ "Timestamp": {time.Now().UTC().Format("2006-01-02T15:04:05Z")},+ "SignatureVersion": {"1.0"},+ "SignatureNonce": {id.Nonce()},+ }+ body := map[string]any{"identityId": identityID.String(), "Signature": alicloud.Sign(http.MethodGet, params, alicloud.SecretFor(akid))}+ for k := range params {+ body[k] = params.Get(k)+ }+ res, err := tn.Anonymous(t).LoginWithAlicloudAuthWithBodyWithResponse(t.Context(), "application/json", fedJSON(t, body))+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/machineidentityfed/awsauth_test.go b/tests/suites/machineidentityfed/awsauth_test.gonew file mode 100644index 0000000000..f644801978--- /dev/null+++ b/tests/suites/machineidentityfed/awsauth_test.go@@ -0,0 +1,196 @@+package machineidentityfed_test++import (+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "encoding/hex"+ "encoding/json"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/aws"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func TestAwsAuth_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for an allowed account and a principal ARN matching a glob", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ akid := fedAccessKeyID()+ account := aws.AccountID(akid)+ identityID := fedNewIdentity(t, tn)+ fedAttachAws(t, tn, identityID, account, "arn:aws:iam::"+account+":user/*")++ // Action+ res := fedLoginAws(t, tn, identityID, fedSignedCallerIdentity(t, akid, "sts.amazonaws.com"))++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })++ t.Run("should refuse an account outside the allowlist and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ akid := fedAccessKeyID()+ identityID := fedNewIdentity(t, tn)+ fedAttachAws(t, tn, identityID, fedOtherAccount(aws.AccountID(akid)), "")++ // Action+ res := fedLoginAws(t, tn, identityID, fedSignedCallerIdentity(t, akid, "sts.amazonaws.com"))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Access denied: AWS account ID not allowed.", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a principal ARN outside the allowlist and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ akid := fedAccessKeyID()+ account := aws.AccountID(akid)+ identityID := fedNewIdentity(t, tn)+ fedAttachAws(t, tn, identityID, account, "arn:aws:iam::"+account+":role/*")++ // Action+ res := fedLoginAws(t, tn, identityID, fedSignedCallerIdentity(t, akid, "sts.amazonaws.com"))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Access denied: AWS principal ARN not allowed. [principal-arn=arn:aws:iam::"+account+":user/infisical]",+ apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a request signed for a host that is not STS and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ akid := fedAccessKeyID()+ identityID := fedNewIdentity(t, tn)+ fedAttachAws(t, tn, identityID, aws.AccountID(akid), "")++ // Action+ res := fedLoginAws(t, tn, identityID, fedSignedCallerIdentity(t, akid, "sts.attacker.test"))++ // Assert+ fedRequireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Signed STS request has an invalid host header", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should answer 404 when the identity has no AWS auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identityID := fedNewIdentity(t, tn)++ // Action+ res := fedLoginAws(t, tn, identityID, fedSignedCallerIdentity(t, fedAccessKeyID(), "sts.amazonaws.com"))++ // Assert+ fedRequireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "AWS auth method not found for identity, did you configure AWS auth?", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++// fedAccessKeyID invents a credential the AWS fake derives a secret and an account for.+func fedAccessKeyID() string { return "AKIA" + strings.ToUpper(id.Nonce()) }++// fedOtherAccount is a 12-digit account that is not account.+func fedOtherAccount(account string) string {+ if account == "111111111111" {+ return "222222222222"+ }+ return "111111111111"+}++func fedAttachAws(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, accounts, arns string) {+ t.Helper()+ body := api.AttachAwsAuthJSONRequestBody{}+ if accounts != "" {+ body.AllowedAccountIds = new(accounts)+ }+ if arns != "" {+ body.AllowedPrincipalArns = new(arns)+ }+ res, err := tn.Admin.API.AttachAwsAuthWithResponse(t.Context(), identityID.String(), body)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "attaching AWS auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++// fedSignedCallerIdentity is what a workload's SDK sends: an sts:GetCallerIdentity+// request SigV4-signed for us-east-1, as base64 JSON headers and a base64 body.+func fedSignedCallerIdentity(t *testing.T, akid, host string) api.LoginWithAwsAuthJSONRequestBody {+ t.Helper()+ const body = "Action=GetCallerIdentity&Version=2011-06-15"+ const contentType = "application/x-www-form-urlencoded"+ now := time.Now().UTC()+ amzDate, day := now.Format("20060102T150405Z"), now.Format("20060102")++ payload := sha256.Sum256([]byte(body))+ canonical := strings.Join([]string{+ http.MethodPost, "/", "",+ "content-type:" + contentType + "\nhost:" + host + "\nx-amz-date:" + amzDate + "\n",+ "content-type;host;x-amz-date",+ hex.EncodeToString(payload[:]),+ }, "\n")+ scope := day + "/us-east-1/sts/aws4_request"+ canonicalHash := sha256.Sum256([]byte(canonical))+ toSign := strings.Join([]string{"AWS4-HMAC-SHA256", amzDate, scope, hex.EncodeToString(canonicalHash[:])}, "\n")+ key := fedHMAC([]byte("AWS4"+aws.SecretAccessKey(akid)), day)+ key = fedHMAC(key, "us-east-1")+ key = fedHMAC(key, "sts")+ key = fedHMAC(key, "aws4_request")+ signature := hex.EncodeToString(fedHMAC(key, toSign))++ headers, err := json.Marshal(map[string]string{+ "Host": host,+ "Content-Type": contentType,+ "X-Amz-Date": amzDate,+ "Accept": "application/json",+ "Authorization": "AWS4-HMAC-SHA256 Credential=" + akid + "/" + scope ++ ", SignedHeaders=content-type;host;x-amz-date, Signature=" + signature,+ })+ require.NoError(t, err)+ return api.LoginWithAwsAuthJSONRequestBody{+ IamHttpRequestMethod: new(http.MethodPost),+ IamRequestBody: base64.StdEncoding.EncodeToString([]byte(body)),+ IamRequestHeaders: base64.StdEncoding.EncodeToString(headers),+ }+}++func fedLoginAws(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, signed api.LoginWithAwsAuthJSONRequestBody) *api.LoginWithAwsAuthResponse {+ t.Helper()+ signed.IdentityId = identityID.String()+ res, err := tn.Anonymous(t).LoginWithAwsAuthWithResponse(t.Context(), signed)+ require.NoError(t, err)+ return res+}++func fedHMAC(key []byte, data string) []byte {+ m := hmac.New(sha256.New, key)+ m.Write([]byte(data))+ return m.Sum(nil)+}diff --git a/tests/suites/machineidentityfed/azureauth_test.go b/tests/suites/machineidentityfed/azureauth_test.gonew file mode 100644index 0000000000..c3914fa494--- /dev/null+++ b/tests/suites/machineidentityfed/azureauth_test.go@@ -0,0 +1,176 @@+package machineidentityfed_test++import (+ "crypto/rsa"+ "encoding/base64"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/azure"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++const fedAzureResource = "https://management.azure.com/"++func TestAzureAuth_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for an allowed service principal's managed identity token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ entra := fedNewEntraTenant(t, tn)+ principal := uuid.NewString()+ identityID := fedNewIdentity(t, tn)+ fedAttachAzure(t, tn, identityID, entra.tenantID, principal)++ // Action+ res := fedLoginAzure(t, tn, identityID, entra.sign(t, entra.kid, entra.tenantID, principal, fedAzureResource))++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })++ t.Run("should refuse a service principal outside the allowlist and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ entra := fedNewEntraTenant(t, tn)+ principal := uuid.NewString()+ identityID := fedNewIdentity(t, tn)+ fedAttachAzure(t, tn, identityID, entra.tenantID, uuid.NewString())++ // Action+ res := fedLoginAzure(t, tn, identityID, entra.sign(t, entra.kid, entra.tenantID, principal, fedAzureResource))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Service principal '"+principal+"' not allowed", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a token whose tid names another tenant and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ entra := fedNewEntraTenant(t, tn)+ principal := uuid.NewString()+ identityID := fedNewIdentity(t, tn)+ fedAttachAzure(t, tn, identityID, entra.tenantID, principal)++ // Action+ res := fedLoginAzure(t, tn, identityID, entra.sign(t, entra.kid, uuid.NewString(), principal, fedAzureResource))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Tenant ID mismatch", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a token issued for another resource and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ entra := fedNewEntraTenant(t, tn)+ principal := uuid.NewString()+ identityID := fedNewIdentity(t, tn)+ fedAttachAzure(t, tn, identityID, entra.tenantID, principal)++ // Action+ res := fedLoginAzure(t, tn, identityID, entra.sign(t, entra.kid, entra.tenantID, principal, "https://vault.azure.net"))++ // Assert+ fedRequireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "jwt audience invalid")+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a token signed by a key the tenant does not publish and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ entra := fedNewEntraTenant(t, tn)+ principal := uuid.NewString()+ identityID := fedNewIdentity(t, tn)+ fedAttachAzure(t, tn, identityID, entra.tenantID, principal)++ // Action+ res := fedLoginAzure(t, tn, identityID, entra.sign(t, "unpublished-"+id.Short(), entra.tenantID, principal, fedAzureResource))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Invalid signing key", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should answer 404 when the identity has no Azure auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ entra := fedNewEntraTenant(t, tn)+ identityID := fedNewIdentity(t, tn)++ // Action+ res := fedLoginAzure(t, tn, identityID, entra.sign(t, entra.kid, entra.tenantID, uuid.NewString(), fedAzureResource))++ // Assert+ fedRequireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "Azure auth method not found for identity, did you configure Azure Auth?", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++// fedEntraTenant is an Entra tenant whose signing certificate the Azure fake publishes.+type fedEntraTenant struct {+ tenantID string+ kid string+ key *rsa.PrivateKey+}++func fedNewEntraTenant(t *testing.T, tn *harness.Tenant) *fedEntraTenant {+ t.Helper()+ e := &fedEntraTenant{tenantID: id.Nonce(), kid: "k-" + id.Short(), key: fedRSAKey(t)}+ azure.Open(t, fixture.FakenetAdmin(t, tn), e.tenantID).Publish(t, e.kid,+ base64.StdEncoding.EncodeToString(fedSelfSignedCert(t, e.key, "login.microsoftonline.com")))+ return e+}++// sign mints a managed identity token issued by this tenant's STS, naming tid as the+// tenant and oid as the service principal.+func (e *fedEntraTenant) sign(t *testing.T, kid, tid, oid, resource string) string {+ t.Helper()+ return fedSignJWT(t, e.key, kid, fedClaims("https://sts.windows.net/"+e.tenantID+"/", oid, resource,+ map[string]any{"tid": tid, "oid": oid}))+}++func fedAttachAzure(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, tenantID, principals string) {+ t.Helper()+ res, err := tn.Admin.API.AttachAzureAuthWithResponse(t.Context(), identityID.String(), api.AttachAzureAuthJSONRequestBody{+ TenantId: tenantID, Resource: fedAzureResource, AllowedServicePrincipalIds: new(principals),+ })+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "attaching Azure auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++func fedLoginAzure(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, jwt string) *api.LoginWithAzureAuthResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginWithAzureAuthWithResponse(t.Context(), api.LoginWithAzureAuthJSONRequestBody{+ IdentityId: identityID.String(), Jwt: jwt,+ })+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/machineidentityfed/fedhelpers_test.go b/tests/suites/machineidentityfed/fedhelpers_test.gonew file mode 100644index 0000000000..24d70a0390--- /dev/null+++ b/tests/suites/machineidentityfed/fedhelpers_test.go@@ -0,0 +1,176 @@+package machineidentityfed_test++import (+ "bytes"+ "crypto"+ "crypto/rand"+ "crypto/rsa"+ "crypto/sha256"+ "crypto/x509"+ "crypto/x509/pkix"+ "encoding/base64"+ "encoding/json"+ "math/big"+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++// fedNewIdentity creates an org identity with no auth method, so the method under test+// is the only way in.+func fedNewIdentity(t *testing.T, tn *harness.Tenant) uuid.UUID {+ t.Helper()+ res, err := tn.Admin.API.CreateMachineIdentityWithResponse(t.Context(), api.CreateMachineIdentityJSONRequestBody{+ Name: "fed-" + id.Short(), OrganizationId: tn.OrgID.String(), Role: new("member"),+ })+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "creating an identity returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.Identity.Id+}++// fedPrincipal wraps a token a federated login issued, so project fixtures can grant it.+func fedPrincipal(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, token string) *harness.Principal {+ t.Helper()+ return &harness.Principal{+ Kind: harness.MachineIdentity,+ ID: identityID,+ Name: "fed",+ Token: token,+ API: tn.Client(t, token),+ }+}++func fedRequireStatus(t *testing.T, want, got int, body []byte) {+ t.Helper()+ require.Equalf(t, want, got, "body: %s", apierr.Body(body))+}++// fedRequireTokenWorks proves a token authenticates as an identity of this tenant.+func fedRequireTokenWorks(t *testing.T, tn *harness.Tenant, token string) {+ t.Helper()+ res, err := tn.Client(t, token).GetMachineIdentityDetailsWithResponse(t.Context())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "using the issued token returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ require.Equal(t, tn.OrgID.String(), res.JSON200.IdentityDetails.Organization.Id)+}++// fedWaitTokenRefused polls until a token is refused, since revocation verdicts are+// cached per token.+func fedWaitTokenRefused(t *testing.T, tn *harness.Tenant, token string) (int, []byte) {+ t.Helper()+ client := tn.Client(t, token)+ var status int+ var body []byte+ wait.Until(t, "the token to be refused", func() bool {+ res, err := client.GetMachineIdentityDetailsWithResponse(t.Context())+ if err != nil {+ return false+ }+ status, body = res.StatusCode(), res.Body+ return status != http.StatusOK+ })+ return status, body+}++func fedIdentity(t *testing.T, tn *harness.Tenant, identityID uuid.UUID) *api.GetMachineIdentityByIdResponse {+ t.Helper()+ res, err := tn.Admin.API.GetMachineIdentityByIdWithResponse(t.Context(), identityID.String())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "reading identity %s returned %d: %s", identityID, res.StatusCode(), apierr.Body(res.Body))+ return res+}++// fedRequireNeverLoggedIn checks no login succeeded: a successful login records its+// method on the identity's org membership before the token is issued.+func fedRequireNeverLoggedIn(t *testing.T, tn *harness.Tenant, identityID uuid.UUID) {+ t.Helper()+ got := fedIdentity(t, tn, identityID).JSON200.Identity.LastLoginAuthMethod+ require.Nilf(t, got, "the identity logged in with %v", got)+}++func fedAuthMethods(t *testing.T, tn *harness.Tenant, identityID uuid.UUID) []string {+ t.Helper()+ return fedIdentity(t, tn, identityID).JSON200.Identity.Identity.AuthMethods+}++func fedRSAKey(t *testing.T) *rsa.PrivateKey {+ t.Helper()+ key, err := rsa.GenerateKey(rand.Reader, 2048)+ require.NoError(t, err)+ return key+}++// fedSignJWT signs claims with RS256 under kid; an empty kid leaves the header without one.+func fedSignJWT(t *testing.T, key *rsa.PrivateKey, kid string, claims map[string]any) string {+ t.Helper()+ header := map[string]string{"alg": "RS256", "typ": "JWT"}+ if kid != "" {+ header["kid"] = kid+ }+ h, err := json.Marshal(header)+ require.NoError(t, err)+ p, err := json.Marshal(claims)+ require.NoError(t, err)+ unsigned := fedB64(h) + "." + fedB64(p)+ digest := sha256.Sum256([]byte(unsigned))+ sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:])+ require.NoError(t, err)+ return unsigned + "." + fedB64(sig)+}++// fedClaims are the registered claims every test token carries, valid for five minutes.+func fedClaims(iss, sub, aud string, extra map[string]any) map[string]any {+ now := time.Now()+ claims := map[string]any{"iss": iss, "sub": sub, "aud": aud, "iat": now.Unix(), "nbf": now.Add(-time.Minute).Unix(), "exp": now.Add(5 * time.Minute).Unix()}+ for k, v := range extra {+ claims[k] = v+ }+ return claims+}++// fedSelfSignedCert returns a self-signed certificate over key, DER encoded.+func fedSelfSignedCert(t *testing.T, key *rsa.PrivateKey, cn string) []byte {+ t.Helper()+ tmpl := &x509.Certificate{+ SerialNumber: big.NewInt(time.Now().UnixNano()),+ Subject: pkix.Name{CommonName: cn},+ NotBefore: time.Now().Add(-time.Hour),+ NotAfter: time.Now().Add(24 * time.Hour),+ KeyUsage: x509.KeyUsageDigitalSignature,+ }+ der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)+ require.NoError(t, err)+ return der+}++func fedB64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }++func fedTrustedIPs(cidrs ...string) *[]struct {+ IpAddress string `json:"ipAddress"`+} {+ out := make([]struct {+ IpAddress string `json:"ipAddress"`+ }, 0, len(cidrs))+ for _, c := range cidrs {+ out = append(out, struct {+ IpAddress string `json:"ipAddress"`+ }{IpAddress: c})+ }+ return &out+}++// fedJSON encodes a request body by hand, for union bodies the generated types cannot carry.+func fedJSON(t *testing.T, v any) *bytes.Reader {+ t.Helper()+ raw, err := json.Marshal(v)+ require.NoError(t, err)+ return bytes.NewReader(raw)+}diff --git a/tests/suites/machineidentityfed/gcpauth_test.go b/tests/suites/machineidentityfed/gcpauth_test.gonew file mode 100644index 0000000000..6c4d0b5985--- /dev/null+++ b/tests/suites/machineidentityfed/gcpauth_test.go@@ -0,0 +1,151 @@+package machineidentityfed_test++import (+ "crypto/rsa"+ "encoding/pem"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/oauth"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++// GCE identity tokens are verified against Google's global oauth2/v1/certs, which carry+// no credential fakenet could scope per test, so only the iam type is covered here.+func TestGcpAuth_IamLogin(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for an allowed service account's signed JWT", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sa := fedNewServiceAccount(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachGcpIam(t, tn, identityID, sa.email)++ // Action+ res := fedLoginGcp(t, tn, identityID, sa.sign(t, sa.kid, identityID.String()))++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })++ t.Run("should refuse a service account outside the allowlist and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sa := fedNewServiceAccount(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachGcpIam(t, tn, identityID, "[email protected]")++ // Action+ res := fedLoginGcp(t, tn, identityID, sa.sign(t, sa.kid, identityID.String()))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Access denied: GCP service account not allowed.", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a JWT minted for another audience and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sa := fedNewServiceAccount(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachGcpIam(t, tn, identityID, sa.email)++ // Action+ res := fedLoginGcp(t, tn, identityID, sa.sign(t, sa.kid, uuid.NewString()))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Invalid audience in GCP IAM Token", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a JWT signed by a key the service account does not publish and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sa := fedNewServiceAccount(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachGcpIam(t, tn, identityID, sa.email)++ // Action+ res := fedLoginGcp(t, tn, identityID, sa.sign(t, "unpublished-"+id.Short(), identityID.String()))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "No matching signing key found for the GCP IAM token", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should answer 404 when the identity has no GCP auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sa := fedNewServiceAccount(t, tn)+ identityID := fedNewIdentity(t, tn)++ // Action+ res := fedLoginGcp(t, tn, identityID, sa.sign(t, sa.kid, identityID.String()))++ // Assert+ fedRequireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "GCP auth method not found for identity, did you configure GCP auth?", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++// fedServiceAccount is a GCP service account whose signing certificate the Google fake+// publishes, the way a workload's iam.signJwt key is published.+type fedServiceAccount struct {+ email string+ kid string+ key *rsa.PrivateKey+}++func fedNewServiceAccount(t *testing.T, tn *harness.Tenant) *fedServiceAccount {+ t.Helper()+ sa := &fedServiceAccount{email: id.Nonce() + "@fed-proj.iam.gserviceaccount.com", kid: id.Short() + id.Short(), key: fedRSAKey(t)}+ cert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: fedSelfSignedCert(t, sa.key, sa.email)})+ oauth.Open(t, fixture.FakenetAdmin(t, tn), oauth.Google, sa.email).Seed(t, oauth.Grant{Certs: map[string]string{sa.kid: string(cert)}})+ return sa+}++func (sa *fedServiceAccount) sign(t *testing.T, kid, audience string) string {+ t.Helper()+ return fedSignJWT(t, sa.key, kid, fedClaims(sa.email, sa.email, audience, nil))+}++func fedAttachGcpIam(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, serviceAccounts string) {+ t.Helper()+ res, err := tn.Admin.API.AttachGcpAuthWithResponse(t.Context(), identityID.String(), api.AttachGcpAuthJSONRequestBody{+ Type: api.AttachGcpAuthJSONBodyType("iam"), AllowedServiceAccounts: new(serviceAccounts),+ })+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "attaching GCP auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++func fedLoginGcp(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, jwt string) *api.LoginWithGcpAuthResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginWithGcpAuthWithResponse(t.Context(), api.LoginWithGcpAuthJSONRequestBody{+ IdentityId: identityID.String(), Jwt: jwt,+ })+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/machineidentityfed/jwtauthjwks_test.go b/tests/suites/machineidentityfed/jwtauthjwks_test.gonew file mode 100644index 0000000000..4664632c23--- /dev/null+++ b/tests/suites/machineidentityfed/jwtauthjwks_test.go@@ -0,0 +1,136 @@+package machineidentityfed_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/oidcidp"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func TestJwtAuth_Jwks(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for a JWT signed by a key the JWKS URL publishes", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachJwks(t, tn, identityID, idp)++ // Action+ res := fedLoginJwt(t, tn, identityID, idp.sign(t, fedClaims(idp.issuer, "workload", "infisical", nil)))++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })++ t.Run("should accept a key published after the method was attached without reconfiguring it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachJwks(t, tn, identityID, idp)+ rotated, kid := fedRSAKey(t), "rotated-"+id.Short()+ idp.cp.TrustKey(t, oidcidp.PublicJWK(kid, &rotated.PublicKey))++ // Action+ res := fedLoginJwt(t, tn, identityID, fedSignJWT(t, rotated, kid, fedClaims(idp.issuer, "workload", "infisical", nil)))++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })++ t.Run("should refuse a JWT whose signature does not match the published key and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachJwks(t, tn, identityID, idp)++ // Action+ res := fedLoginJwt(t, tn, identityID, fedSignJWT(t, fedRSAKey(t), idp.kid, fedClaims(idp.issuer, "workload", "infisical", nil)))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Access denied: invalid signature", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should answer 404 when the identity has no JWT auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)++ // Action+ res := fedLoginJwt(t, tn, identityID, idp.sign(t, fedClaims(idp.issuer, "workload", "infisical", nil)))++ // Assert+ fedRequireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "JWT auth method not found for identity, did you configure JWT auth?", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++func TestJwtAuth_Jwks_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a JWT whose kid the JWKS does not publish as unauthorized rather than a server error", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachJwks(t, tn, identityID, idp)++ // Action+ res := fedLoginJwt(t, tn, identityID, fedSignJWT(t, fedRSAKey(t), "unpublished-"+id.Short(),+ fedClaims(idp.issuer, "workload", "infisical", nil)))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++func fedAttachJwks(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, idp *fedOidcProvider) {+ t.Helper()+ res, err := tn.Admin.API.AttachJwtAuthWithBodyWithResponse(t.Context(), identityID.String(), "application/json", fedJSON(t, map[string]any{+ "configurationType": "jwks",+ "jwksUrl": idp.cp.JWKSURL(),+ "boundIssuer": idp.issuer,+ "boundAudiences": "infisical",+ "boundSubject": "workload",+ "boundClaims": map[string]string{},+ }))+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "attaching JWT auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++func fedLoginJwt(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, jwt string) *api.LoginWithJwtAuthResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginWithJwtAuthWithResponse(t.Context(), api.LoginWithJwtAuthJSONRequestBody{+ IdentityId: identityID.String(), Jwt: jwt,+ })+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/machineidentityfed/kubernetesauth_test.go b/tests/suites/machineidentityfed/kubernetesauth_test.gonew file mode 100644index 0000000000..585b8dde58--- /dev/null+++ b/tests/suites/machineidentityfed/kubernetesauth_test.go@@ -0,0 +1,193 @@+package machineidentityfed_test++import (+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/kubernetes"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func TestKubernetesAuth_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for an allowed namespace, service account and audience", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ cluster := kubernetes.Open(t, fixture.FakenetAdmin(t, tn))+ identityID := fedNewIdentity(t, tn)+ fedAttachKubernetes(t, tn, identityID, cluster)+ saToken := cluster.ServiceAccountToken(t, "payments", "api", "infisical")++ // Action+ res := fedLoginKubernetes(t, tn, identityID, saToken)++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ cluster.ExpectEvent(t, func(e kubernetes.TokenReviewed) bool {+ return e.Token == saToken && len(e.Audiences) == 1 && e.Audiences[0] == "infisical"+ })+ })++ refusals := []struct {+ name string+ message string+ token func(t *testing.T, cluster *kubernetes.ControlPlane) string+ }{+ {+ name: "should refuse a service account in a namespace outside the allowlist and issue no token", message: "Access denied: K8s namespace not allowed.",+ token: func(t *testing.T, cluster *kubernetes.ControlPlane) string {+ return cluster.ServiceAccountToken(t, "billing", "api", "infisical")+ },+ },+ {+ name: "should refuse a service account name outside the allowlist and issue no token", message: "Access denied: K8s name not allowed.",+ token: func(t *testing.T, cluster *kubernetes.ControlPlane) string {+ return cluster.ServiceAccountToken(t, "payments", "worker", "infisical")+ },+ },+ {+ name: "should refuse a token for another audience and issue no token", message: "Access denied: K8s audience not allowed.",+ token: func(t *testing.T, cluster *kubernetes.ControlPlane) string {+ return cluster.ServiceAccountToken(t, "payments", "api", "vault")+ },+ },+ {+ name: "should refuse a token TokenReview reports as unauthenticated and issue no token", message: "Kubernetes token not authenticated",+ token: func(*testing.T, *kubernetes.ControlPlane) string { return "sa-the-cluster-never-issued" },+ },+ }+ for _, tc := range refusals {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ cluster := kubernetes.Open(t, fixture.FakenetAdmin(t, tn))+ identityID := fedNewIdentity(t, tn)+ fedAttachKubernetes(t, tn, identityID, cluster)++ // Action+ res := fedLoginKubernetes(t, tn, identityID, tc.token(t, cluster))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, tc.message, apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+ }++ t.Run("should answer 404 when the identity has no Kubernetes auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ cluster := kubernetes.Open(t, fixture.FakenetAdmin(t, tn))+ identityID := fedNewIdentity(t, tn)++ // Action+ res := fedLoginKubernetes(t, tn, identityID, cluster.ServiceAccountToken(t, "payments", "api", "infisical"))++ // Assert+ fedRequireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "Kubernetes auth method not found for identity, did you configure Kubernetes auth?", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++func TestKubernetesAuth_Attach(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse attaching when the cluster rejects the token reviewer JWT, and store nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ cluster := kubernetes.Open(t, fixture.FakenetAdmin(t, tn))+ cluster.RejectReviewer(t)+ identityID := fedNewIdentity(t, tn)++ // Action+ res, err := tn.Admin.API.AttachKubernetesAuthWithResponse(t.Context(), identityID.String(), fedKubernetesBindings(cluster))++ // Assert+ require.NoError(t, err)+ fedSkipWhenKubernetesFakeRefusesVersion(t, res.Body)+ fedRequireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), "Ensure the service account has the 'system:auth-delegator' ClusterRole binding.")+ require.NotContains(t, fedAuthMethods(t, tn, identityID), "kubernetes-auth")+ })++ t.Run("should refuse gateway token review when the plan does not include gateways, and store nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.Gateway)))+ identityID := fedNewIdentity(t, tn)+ gatewayMode := api.AttachKubernetesAuthJSONBodyTokenReviewMode("gateway")++ // Action+ res, err := tn.Admin.API.AttachKubernetesAuthWithResponse(t.Context(), identityID.String(), api.AttachKubernetesAuthJSONRequestBody{+ TokenReviewMode: &gatewayMode,+ GatewayId: new(uuid.New()),+ AllowedNamespaces: "payments",+ AllowedNames: "api",+ })++ // Assert+ require.NoError(t, err)+ fedRequireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Your current plan does not support gateway usage with identity k8s auth. Please upgrade your plan or contact Infisical Sales for assistance.",+ apierr.Message(res.Body))+ require.NotContains(t, fedAuthMethods(t, tn, identityID), "kubernetes-auth")+ })+}++func fedKubernetesBindings(cluster *kubernetes.ControlPlane) api.AttachKubernetesAuthJSONRequestBody {+ return api.AttachKubernetesAuthJSONRequestBody{+ KubernetesHost: new(kubernetes.Service.URL()),+ TokenReviewerJwt: new(cluster.ReviewerJWT),+ AllowedNamespaces: "payments",+ AllowedNames: "api",+ AllowedAudience: new("infisical"),+ }+}++func fedAttachKubernetes(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, cluster *kubernetes.ControlPlane) {+ t.Helper()+ res, err := tn.Admin.API.AttachKubernetesAuthWithResponse(t.Context(), identityID.String(), fedKubernetesBindings(cluster))+ require.NoError(t, err)+ fedSkipWhenKubernetesFakeRefusesVersion(t, res.Body)+ require.NotNilf(t, res.JSON200, "attaching Kubernetes auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++// fedSkipWhenKubernetesFakeRefusesVersion skips while fakes/kubernetes cannot answer the+// unauthenticated GET /version Infisical sends on attach: the fake scopes by bearer token,+// so fakenet refuses that request with 501 and every API-mode attach fails.+func fedSkipWhenKubernetesFakeRefusesVersion(t *testing.T, body []byte) {+ t.Helper()+ if strings.Contains(apierr.Message(body), "Kubernetes API returned server error: 501") {+ t.Skip("fakes/kubernetes answers the unauthenticated GET /version with fakenet's 501, so API-mode attach cannot succeed")+ }+}++func fedLoginKubernetes(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, jwt string) *api.LoginWithKubernetesAuthResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginWithKubernetesAuthWithResponse(t.Context(), api.LoginWithKubernetesAuthJSONRequestBody{+ IdentityId: identityID.String(), Jwt: jwt,+ })+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/machineidentityfed/ldapauth_test.go b/tests/suites/machineidentityfed/ldapauth_test.gonew file mode 100644index 0000000000..5eb9b4249e--- /dev/null+++ b/tests/suites/machineidentityfed/ldapauth_test.go@@ -0,0 +1,191 @@+package machineidentityfed_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/ldap"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++const fedLdapPassword = "workload-password-1"++func TestLdapAuth_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for a directory user with the right password and required fields", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ dir := fedNewDirectory(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachLdap(t, tn, identityID, fedLdapConfig(dir, dir.BindPassword))++ // Action+ res := fedLoginLdap(t, tn, identityID, "svc-app", fedLdapPassword)++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })++ t.Run("should refuse a wrong password and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ dir := fedNewDirectory(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachLdap(t, tn, identityID, fedLdapConfig(dir, dir.BindPassword))++ // Action+ res := fedLoginLdap(t, tn, identityID, "svc-app", "not-the-password")++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Invalid credentials", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a user whose entry lacks a required field value and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ dir := fedNewDirectory(t, tn)+ dir.AddUser(t, "svc-other", fedLdapPassword, map[string][]string{"departmentNumber": {"billing"}})+ identityID := fedNewIdentity(t, tn)+ fedAttachLdap(t, tn, identityID, fedLdapConfig(dir, dir.BindPassword))++ // Action+ res := fedLoginLdap(t, tn, identityID, "svc-other", fedLdapPassword)++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Invalid credentials", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse login once the plan no longer includes LDAP and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ dir := fedNewDirectory(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachLdap(t, tn, identityID, fedLdapConfig(dir, dir.BindPassword))+ tn.SetPlan(t, license.Enterprise().Without(license.LDAP))++ // Action+ res := fedLoginLdap(t, tn, identityID, "svc-app", fedLdapPassword)++ // Assert+ fedRequireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Failed to login to identity due to plan restriction. Upgrade plan to login to use LDAP authentication.",+ apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should answer 404 when the identity has no LDAP auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identityID := fedNewIdentity(t, tn)++ // Action+ res := fedLoginLdap(t, tn, identityID, "svc-app", fedLdapPassword)++ // Assert+ fedRequireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "LDAP auth with ID '"+identityID.String()+"' not found", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++func TestLdapAuth_Attach(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse bind credentials the directory does not accept and store nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ dir := fedNewDirectory(t, tn)+ identityID := fedNewIdentity(t, tn)++ // Action+ res, err := tn.Admin.API.AttachLdapAuthWithBodyWithResponse(t.Context(), identityID.String(), "application/json",+ fedJSON(t, fedLdapConfig(dir, "wrong-bind-password")))++ // Assert+ require.NoError(t, err)+ fedRequireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Failed to connect to LDAP server. Please ensure that the LDAP server is running and your credentials are correct.",+ apierr.Message(res.Body))+ require.NotContains(t, fedAuthMethods(t, tn, identityID), "ldap-auth")+ })++ t.Run("should refuse attaching when the plan does not include LDAP and store nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.LDAP)))+ dir := fedNewDirectory(t, tn)+ identityID := fedNewIdentity(t, tn)++ // Action+ res, err := tn.Admin.API.AttachLdapAuthWithBodyWithResponse(t.Context(), identityID.String(), "application/json",+ fedJSON(t, fedLdapConfig(dir, dir.BindPassword)))++ // Assert+ require.NoError(t, err)+ fedRequireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Failed to add LDAP Auth to identity due to plan restriction. Upgrade plan to add LDAP Auth.", apierr.Message(res.Body))+ require.NotContains(t, fedAuthMethods(t, tn, identityID), "ldap-auth")+ })+}++// fedNewDirectory opens a test-owned directory holding svc-app in the payments department.+func fedNewDirectory(t *testing.T, tn *harness.Tenant) *ldap.ControlPlane {+ t.Helper()+ dir := ldap.Open(t, fixture.FakenetAdmin(t, tn))+ dir.AddUser(t, "svc-app", fedLdapPassword, map[string][]string{"departmentNumber": {"payments"}})+ return dir+}++func fedLdapConfig(dir *ldap.ControlPlane, bindPassword string) map[string]any {+ return map[string]any{+ "url": ldap.Service.URL(),+ "bindDN": dir.BindDN,+ "bindPass": bindPassword,+ "searchBase": "ou=people," + dir.BaseDN,+ "searchFilter": "(uid={{username}})",+ "allowedFields": []map[string]string{{"key": "departmentNumber", "value": "payments"}},+ }+}++func fedAttachLdap(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, config map[string]any) {+ t.Helper()+ res, err := tn.Admin.API.AttachLdapAuthWithBodyWithResponse(t.Context(), identityID.String(), "application/json", fedJSON(t, config))+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "attaching LDAP auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++func fedLoginLdap(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, username, password string) *api.LoginWithLdapAuthResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginWithLdapAuthWithResponse(t.Context(), api.LoginWithLdapAuthJSONRequestBody{+ IdentityId: identityID, Username: username, Password: password,+ })+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/machineidentityfed/main_test.go b/tests/suites/machineidentityfed/main_test.gonew file mode 100644index 0000000000..71bae04685--- /dev/null+++ b/tests/suites/machineidentityfed/main_test.go@@ -0,0 +1,9 @@+package machineidentityfed_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/harness"+)++func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }diff --git a/tests/suites/machineidentityfed/ociauth_test.go b/tests/suites/machineidentityfed/ociauth_test.gonew file mode 100644index 0000000000..597088e894--- /dev/null+++ b/tests/suites/machineidentityfed/ociauth_test.go@@ -0,0 +1,188 @@+package machineidentityfed_test++import (+ "crypto/rsa"+ "crypto/x509"+ "encoding/pem"+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/oci"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func TestOciAuth_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for an allowed user of the configured tenancy", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ user := fedNewOciUser(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachOci(t, tn, identityID, user.tenancy, user.name)++ // Action+ res := fedLoginOci(t, tn, identityID, user.signed(t, user.ocid, oci.Service.Host()))++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })++ t.Run("should refuse a user of another tenancy and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ user := fedNewOciUser(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachOci(t, tn, identityID, "ocid1.tenancy.oc1..other"+id.Short(), user.name)++ // Action+ res := fedLoginOci(t, tn, identityID, user.signed(t, user.ocid, oci.Service.Host()))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Access denied: OCI account isn't part of tenancy.", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a username outside the allowlist and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ user := fedNewOciUser(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachOci(t, tn, identityID, user.tenancy, "someone-else")++ // Action+ res := fedLoginOci(t, tn, identityID, user.signed(t, user.ocid, oci.Service.Host()))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Access denied: OCI account username not allowed.", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a request signed by another user than the one named and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ user := fedNewOciUser(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachOci(t, tn, identityID, user.tenancy, user.name)+ signed := user.signed(t, user.ocid, oci.Service.Host())+ signed.UserOcid = "ocid1.user.oc1..victim" + id.Short()++ // Action+ res := fedLoginOci(t, tn, identityID, signed)++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, "Access denied: the OCI user that signed the request does not match the provided user OCID.", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should refuse a request signed for a host that is not OCI identity and issue no token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ user := fedNewOciUser(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachOci(t, tn, identityID, user.tenancy, user.name)++ // Action+ res := fedLoginOci(t, tn, identityID, user.signed(t, user.ocid, "attacker.test"))++ // Assert+ fedRequireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Invalid OCI host format. Expected format: identity.<region>.oraclecloud.com", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })++ t.Run("should answer 404 when the identity has no OCI auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ user := fedNewOciUser(t, tn)+ identityID := fedNewIdentity(t, tn)++ // Action+ res := fedLoginOci(t, tn, identityID, user.signed(t, user.ocid, oci.Service.Host()))++ // Assert+ fedRequireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "OCI auth method not found for identity, did you configure OCI auth?", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++// fedOciUser is an OCI user whose API key's public half the OCI fake holds.+type fedOciUser struct {+ tenancy string+ ocid string+ name string+ keyID string+ key *rsa.PrivateKey+}++func fedNewOciUser(t *testing.T, tn *harness.Tenant) *fedOciUser {+ t.Helper()+ nonce := id.Nonce()+ u := &fedOciUser{+ tenancy: "ocid1.tenancy.oc1.." + nonce,+ ocid: "ocid1.user.oc1.." + nonce,+ name: "workload-" + id.Short(),+ key: fedRSAKey(t),+ }+ u.keyID = u.tenancy + "/" + u.ocid + "/aa:bb:cc"+ der, err := x509.MarshalPKIXPublicKey(&u.key.PublicKey)+ require.NoError(t, err)+ oci.Open(t, fixture.FakenetAdmin(t, tn), u.keyID, u.ocid, u.name, u.tenancy,+ string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der})))+ return u+}++// signed is what a workload sends: the headers of a GetUser request it signed for host.+func (u *fedOciUser) signed(t *testing.T, userOcid, host string) api.LoginWithOciAuthJSONRequestBody {+ t.Helper()+ date := time.Now().UTC().Format(http.TimeFormat)+ auth, err := oci.Authorization(u.key, u.keyID, "/20160918/users/"+userOcid, host, date)+ require.NoError(t, err)+ body := api.LoginWithOciAuthJSONRequestBody{UserOcid: userOcid}+ body.Headers.Authorization = auth+ body.Headers.Host = host+ body.Headers.Date = &date+ return body+}++func fedAttachOci(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, tenancy, usernames string) {+ t.Helper()+ res, err := tn.Admin.API.AttachOciAuthWithResponse(t.Context(), identityID.String(), api.AttachOciAuthJSONRequestBody{+ TenancyOcid: tenancy, AllowedUsernames: new(usernames),+ })+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "attaching OCI auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++func fedLoginOci(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, signed api.LoginWithOciAuthJSONRequestBody) *api.LoginWithOciAuthResponse {+ t.Helper()+ signed.IdentityId = identityID.String()+ res, err := tn.Anonymous(t).LoginWithOciAuthWithResponse(t.Context(), signed)+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/machineidentityfed/oidcauth_test.go b/tests/suites/machineidentityfed/oidcauth_test.gonew file mode 100644index 0000000000..609b55a1fd--- /dev/null+++ b/tests/suites/machineidentityfed/oidcauth_test.go@@ -0,0 +1,293 @@+package machineidentityfed_test++import (+ "crypto/rsa"+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fakes/oidcidp"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func TestOidcAuth_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token when issuer, audience, subject and bound claims match", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachOidc(t, tn, identityID, fedOidcBindings(idp))++ // Action+ res := fedLoginOidc(t, tn, identityID, idp.sign(t, fedClaims(idp.issuer, "repo:acme/app", "infisical", map[string]any{"team": "payments"})))++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ require.Equal(t, "oidc-auth", *fedIdentity(t, tn, identityID).JSON200.Identity.LastLoginAuthMethod)+ })++ refusals := []struct {+ name string+ status int+ message string+ token func(t *testing.T, idp *fedOidcProvider) string+ }{+ {+ name: "should refuse a JWT for another audience and issue no token", status: http.StatusUnauthorized,+ message: "Access denied: OIDC audience not allowed.",+ token: func(t *testing.T, idp *fedOidcProvider) string {+ return idp.sign(t, fedClaims(idp.issuer, "repo:acme/app", "someone-else", map[string]any{"team": "payments"}))+ },+ },+ {+ name: "should refuse a JWT for another subject and issue no token", status: http.StatusForbidden,+ message: "Access denied: OIDC subject not allowed.",+ token: func(t *testing.T, idp *fedOidcProvider) string {+ return idp.sign(t, fedClaims(idp.issuer, "repo:acme/other", "infisical", map[string]any{"team": "payments"}))+ },+ },+ {+ name: "should refuse a JWT whose bound claim differs and issue no token", status: http.StatusUnauthorized,+ message: "Access denied: OIDC claim not allowed.",+ token: func(t *testing.T, idp *fedOidcProvider) string {+ return idp.sign(t, fedClaims(idp.issuer, "repo:acme/app", "infisical", map[string]any{"team": "billing"}))+ },+ },+ {+ name: "should refuse a JWT from another issuer and issue no token", status: http.StatusUnauthorized,+ message: "Access denied: jwt issuer invalid. expected: ",+ token: func(t *testing.T, idp *fedOidcProvider) string {+ return idp.sign(t, fedClaims(oidcidp.IssuerURL("elsewhere"), "repo:acme/app", "infisical", map[string]any{"team": "payments"}))+ },+ },+ {+ name: "should refuse a JWT signed by a key outside the JWKS and issue no token", status: http.StatusUnauthorized,+ message: "was not found in the OIDC provider's JWKS endpoint",+ token: func(t *testing.T, idp *fedOidcProvider) string {+ return fedSignJWT(t, fedRSAKey(t), "untrusted-"+id.Short(),+ fedClaims(idp.issuer, "repo:acme/app", "infisical", map[string]any{"team": "payments"}))+ },+ },+ {+ name: "should refuse an expired JWT and issue no token", status: http.StatusUnauthorized,+ message: "Access denied: jwt expired",+ token: func(t *testing.T, idp *fedOidcProvider) string {+ claims := fedClaims(idp.issuer, "repo:acme/app", "infisical", map[string]any{"team": "payments"})+ claims["iat"] = time.Now().Add(-2 * time.Hour).Unix()+ claims["nbf"] = time.Now().Add(-2 * time.Hour).Unix()+ claims["exp"] = time.Now().Add(-time.Hour).Unix()+ return idp.sign(t, claims)+ },+ },+ }+ for _, tc := range refusals {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachOidc(t, tn, identityID, fedOidcBindings(idp))++ // Action+ res := fedLoginOidc(t, tn, identityID, tc.token(t, idp))++ // Assert+ fedRequireStatus(t, tc.status, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Message(res.Body), tc.message)+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+ }++ t.Run("should answer 404 when the identity has no OIDC auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)++ // Action+ res := fedLoginOidc(t, tn, identityID, idp.sign(t, fedClaims(idp.issuer, "repo:acme/app", "infisical", nil)))++ // Assert+ fedRequireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "OIDC auth method not found for identity, did you configure OIDC auth?", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++func TestOidcAuth_ClaimMetadata(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should expose a mapped claim to role templates as identity.auth.oidc.claims", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ for _, team := range []string{"backend", "frontend"} {+ secretmanager.CreateFolder(t, proj, "dev", "/"+team)+ secretmanager.CreateSecret(t, proj, "dev", "KEY", team, secretmanager.WithPath("/"+team))+ }+ proj.NewRole(t, "own-team", fixture.Permission{+ Subject: "secrets",+ Action: []string{"read"},+ Conditions: map[string]any{"secretPath": "/{{identity.auth.oidc.claims.team}}"},+ })+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ body := fedOidcBindings(idp)+ body.ClaimMetadataMapping = &map[string]string{"team": "department"}+ fedAttachOidc(t, tn, identityID, body)+ login := fedLoginOidc(t, tn, identityID, idp.sign(t,+ fedClaims(idp.issuer, "repo:acme/app", "infisical", map[string]any{"team": "payments", "department": "backend"})))+ require.NotNilf(t, login.JSON200, "login returned %d: %s", login.StatusCode(), apierr.Body(login.Body))+ identity := fedPrincipal(t, tn, identityID, login.JSON200.AccessToken)+ proj.Grant(t, identity, "own-team")++ // Action+ own := fedListSecretKeys(t, identity, proj, "/backend")+ other := fedListSecretKeys(t, identity, proj, "/frontend")++ // Assert+ require.Equal(t, []string{"KEY"}, own)+ require.Empty(t, other)+ })+}++func TestOidcAuth_Remove(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse the tokens it issued once OIDC auth is removed", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachOidc(t, tn, identityID, fedOidcBindings(idp))+ jwt := idp.sign(t, fedClaims(idp.issuer, "repo:acme/app", "infisical", map[string]any{"team": "payments"}))+ login := fedLoginOidc(t, tn, identityID, jwt)+ require.NotNilf(t, login.JSON200, "login returned %d: %s", login.StatusCode(), apierr.Body(login.Body))+ fedRequireTokenWorks(t, tn, login.JSON200.AccessToken)++ // Action+ res, err := tn.Admin.API.DeleteOidcAuthWithResponse(t.Context(), identityID.String())++ // Assert+ require.NoError(t, err)+ fedRequireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ status, body := fedWaitTokenRefused(t, tn, login.JSON200.AccessToken)+ fedRequireStatus(t, http.StatusUnauthorized, status, body)+ again := fedLoginOidc(t, tn, identityID, jwt)+ fedRequireStatus(t, http.StatusNotFound, again.StatusCode(), again.Body)+ })+}++func TestOidcAuth_TrustedIPs(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a non-wildcard trusted IP range when the plan lacks IP allowlisting and attach nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.IPAllowlisting)))+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ body := fedOidcBindings(idp)+ body.AccessTokenTrustedIps = fedTrustedIPs("10.0.0.0/8")++ // Action+ res, err := tn.Admin.API.AttachOidcAuthWithResponse(t.Context(), identityID.String(), body)++ // Assert+ require.NoError(t, err)+ fedRequireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "Failed to add IP access range to access token due to plan restriction. Upgrade plan to add IP access range.",+ apierr.Message(res.Body))+ require.NotContains(t, fedAuthMethods(t, tn, identityID), "oidc-auth")+ })+}++// fedOidcProvider is a tenant's OIDC provider in fakenet, publishing a key the test signs with.+type fedOidcProvider struct {+ issuer string+ key *rsa.PrivateKey+ kid string+ cp *oidcidp.ControlPlane+}++func fedNewOidcProvider(t *testing.T, tn *harness.Tenant) *fedOidcProvider {+ t.Helper()+ cp := oidcidp.Open(t, fixture.FakenetAdmin(t, tn), id.Nonce())+ key := fedRSAKey(t)+ kid := "k-" + id.Short()+ cp.TrustKey(t, oidcidp.PublicJWK(kid, &key.PublicKey))+ return &fedOidcProvider{issuer: cp.DiscoveryURL(), key: key, kid: kid, cp: cp}+}++func (p *fedOidcProvider) sign(t *testing.T, claims map[string]any) string {+ t.Helper()+ return fedSignJWT(t, p.key, p.kid, claims)+}++// fedOidcBindings binds audience, subject and one claim, so each can be refused alone.+func fedOidcBindings(p *fedOidcProvider) api.AttachOidcAuthJSONRequestBody {+ return api.AttachOidcAuthJSONRequestBody{+ OidcDiscoveryUrl: new(p.issuer),+ BoundIssuer: new(p.issuer),+ BoundAudiences: new("infisical"),+ BoundSubject: new("repo:acme/app"),+ BoundClaims: map[string]string{"team": "payments"},+ }+}++func fedAttachOidc(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, body api.AttachOidcAuthJSONRequestBody) {+ t.Helper()+ res, err := tn.Admin.API.AttachOidcAuthWithResponse(t.Context(), identityID.String(), body)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "attaching OIDC auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++func fedLoginOidc(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, jwt string) *api.LoginWithOidcAuthResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginWithOidcAuthWithResponse(t.Context(), api.LoginWithOidcAuthJSONRequestBody{+ IdentityId: identityID.String(), Jwt: jwt,+ })+ require.NoError(t, err)+ return res+}++// fedListSecretKeys lists a dev folder as pr and returns the keys it can see.+func fedListSecretKeys(t *testing.T, pr *harness.Principal, proj *fixture.Project, path string) []string {+ t.Helper()+ res, err := pr.API.ListSecretsV4WithResponse(t.Context(), &api.ListSecretsV4Params{+ ProjectId: &proj.ID, Environment: new("dev"), SecretPath: &path,+ })+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing %s returned %d: %s", path, res.StatusCode(), apierr.Body(res.Body))+ keys := []string{}+ for _, s := range res.JSON200.Secrets {+ keys = append(keys, s.SecretKey)+ }+ return keys+}diff --git a/tests/suites/machineidentityfed/spiffeauth_test.go b/tests/suites/machineidentityfed/spiffeauth_test.gonew file mode 100644index 0000000000..99b7144d01--- /dev/null+++ b/tests/suites/machineidentityfed/spiffeauth_test.go@@ -0,0 +1,188 @@+package machineidentityfed_test++import (+ "encoding/json"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/oidcidp"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++const (+ fedTrustDomain = "fed.example.test"+ fedSpiffeID = "spiffe://" + fedTrustDomain + "/ns/payments/sa/api"+)++func TestSpiffeAuth_StaticBundle(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for a JWT-SVID signed by a key in the static bundle", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachSpiffe(t, tn, identityID, fedStaticBundle(t, idp))++ // Action+ res := fedLoginSpiffe(t, tn, identityID, idp.sign(t, fedClaims("", fedSpiffeID, "infisical", nil)))++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })++ refusals := []struct {+ name string+ message string+ svid func(t *testing.T, idp *fedOidcProvider) string+ }{+ {+ name: "should refuse a JWT-SVID for another audience and issue no token", message: "JWT-SVID audience validation failed",+ svid: func(t *testing.T, idp *fedOidcProvider) string {+ return idp.sign(t, fedClaims("", fedSpiffeID, "vault", nil))+ },+ },+ {+ name: "should refuse a SPIFFE ID from another trust domain and issue no token", message: "Access denied",+ svid: func(t *testing.T, idp *fedOidcProvider) string {+ return idp.sign(t, fedClaims("", "spiffe://other.example.test/ns/payments/sa/api", "infisical", nil))+ },+ },+ {+ name: "should refuse a SPIFFE ID outside the allowed patterns and issue no token", message: "Access denied",+ svid: func(t *testing.T, idp *fedOidcProvider) string {+ return idp.sign(t, fedClaims("", "spiffe://"+fedTrustDomain+"/ns/billing/sa/api", "infisical", nil))+ },+ },+ {+ name: "should refuse a JWT-SVID signed by a key outside the bundle and issue no token",+ message: "No key in the SPIFFE trust bundle matches the JWT-SVID signing key",+ svid: func(t *testing.T, _ *fedOidcProvider) string {+ return fedSignJWT(t, fedRSAKey(t), "untrusted-"+id.Short(), fedClaims("", fedSpiffeID, "infisical", nil))+ },+ },+ }+ for _, tc := range refusals {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachSpiffe(t, tn, identityID, fedStaticBundle(t, idp))++ // Action+ res := fedLoginSpiffe(t, tn, identityID, tc.svid(t, idp))++ // Assert+ fedRequireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Equal(t, tc.message, apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+ }++ t.Run("should answer 404 when the identity has no SPIFFE auth", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)++ // Action+ res := fedLoginSpiffe(t, tn, identityID, idp.sign(t, fedClaims("", fedSpiffeID, "infisical", nil)))++ // Assert+ fedRequireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "SPIFFE auth method not found for identity, did you configure SPIFFE auth?", apierr.Message(res.Body))+ fedRequireNeverLoggedIn(t, tn, identityID)+ })+}++func TestSpiffeAuth_WebBundle(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a token for a JWT-SVID signed by a key the bundle endpoint serves", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachSpiffe(t, tn, identityID, fedWebBundle(idp))++ // Action+ res := fedLoginSpiffe(t, tn, identityID, idp.sign(t, fedClaims("", fedSpiffeID, "infisical", nil)))++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })++ t.Run("should refetch the cached bundle and accept a key the endpoint started serving after the last fetch", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ idp := fedNewOidcProvider(t, tn)+ identityID := fedNewIdentity(t, tn)+ fedAttachSpiffe(t, tn, identityID, fedWebBundle(idp))+ first := fedLoginSpiffe(t, tn, identityID, idp.sign(t, fedClaims("", fedSpiffeID, "infisical", nil)))+ require.NotNilf(t, first.JSON200, "first login returned %d: %s", first.StatusCode(), apierr.Body(first.Body))+ rotated, kid := fedRSAKey(t), "rotated-"+id.Short()+ idp.cp.TrustKey(t, oidcidp.PublicJWK(kid, &rotated.PublicKey))++ // Action+ res := fedLoginSpiffe(t, tn, identityID, fedSignJWT(t, rotated, kid, fedClaims("", fedSpiffeID, "infisical", nil)))++ // Assert+ require.NotNilf(t, res.JSON200, "login returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ fedRequireTokenWorks(t, tn, res.JSON200.AccessToken)+ })+}++// fedStaticBundle is the provider's test key as a SPIFFE bundle an admin uploads.+func fedStaticBundle(t *testing.T, idp *fedOidcProvider) map[string]any {+ t.Helper()+ jwk := oidcidp.PublicJWK(idp.kid, &idp.key.PublicKey)+ jwk.Use = "jwt-svid"+ bundle, err := json.Marshal(map[string]any{"keys": []oidcidp.JWK{jwk}})+ require.NoError(t, err)+ return map[string]any{"profile": "static", "bundle": string(bundle)}+}++func fedWebBundle(idp *fedOidcProvider) map[string]any {+ return map[string]any{"profile": "https_web_bundle", "endpointUrl": idp.cp.SpiffeBundleURL()}+}++func fedAttachSpiffe(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, distribution map[string]any) {+ t.Helper()+ res, err := tn.Admin.API.AttachSpiffeAuthWithBodyWithResponse(t.Context(), identityID.String(), "application/json", fedJSON(t, map[string]any{+ "trustDomain": fedTrustDomain,+ "allowedSpiffeIds": "spiffe://" + fedTrustDomain + "/ns/payments/**",+ "allowedAudiences": "infisical",+ "trustBundleDistribution": distribution,+ }))+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "attaching SPIFFE auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++func fedLoginSpiffe(t *testing.T, tn *harness.Tenant, identityID uuid.UUID, jwt string) *api.LoginWithSpiffeAuthResponse {+ t.Helper()+ res, err := tn.Anonymous(t).LoginWithSpiffeAuthWithResponse(t.Context(), api.LoginWithSpiffeAuthJSONRequestBody{+ IdentityId: identityID.String(), Jwt: jwt,+ })+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/organization/adminconsole_test.go b/tests/suites/organization/adminconsole_test.gonew file mode 100644index 0000000000..e6333d2066--- /dev/null+++ b/tests/suites/organization/adminconsole_test.go@@ -0,0 +1,91 @@+package organization_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/stretchr/testify/require"+)++func TestAdminConsole_ProjectAccess(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should make an org admin a project admin and mail the project's other admins", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ orgAdmin := tn.NewUser(t, harness.OrgRole("admin"))++ // Action+ res, err := orgAdmin.API.GrantOrganizationAdminProjectAccessWithResponse(t.Context(), proj.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Contains(t, projectMemberEmails(t, tn, proj), orgAdmin.Email)+ msg := tn.Mail(t).Expect(t, tn.Admin.Email, smtp.Subject("Organization Admin Project Direct Access Issued"))+ require.Contains(t, msg.Body, orgAdmin.Email)+ require.Contains(t, msg.Body, proj.Name)+ })++ t.Run("should refuse listing all projects to a member without access-all-projects", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ member := tn.NewUser(t, harness.OrgRole("member"))++ // Action+ res, err := member.API.ListOrganizationProjectsWithResponse(t.Context(), nil)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ })++ t.Run("should refuse self-granted project access to a member without access-all-projects and add no membership", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ member := tn.NewUser(t, harness.OrgRole("member"))++ // Action+ res, err := member.API.GrantOrganizationAdminProjectAccessWithResponse(t.Context(), proj.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.NotContains(t, projectMemberEmails(t, tn, proj), member.Email)+ })++ t.Run("should let a custom role with access-all-projects list every project", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ console := customRoleUser(t, tn, "console",+ fixture.Permission{Subject: "organization-admin-console", Action: []string{"access-all-projects"}})++ // Action+ res, err := console.API.ListOrganizationProjectsWithResponse(t.Context(), nil)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ var ids []string+ for _, p := range res.JSON200.Projects {+ ids = append(ids, p.Id)+ }+ require.Contains(t, ids, proj.ID)+ })+}diff --git a/tests/suites/organization/emaildomain_test.go b/tests/suites/organization/emaildomain_test.gonew file mode 100644index 0000000000..244e99f5fa--- /dev/null+++ b/tests/suites/organization/emaildomain_test.go@@ -0,0 +1,171 @@+package organization_test++import (+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra/fakenet"+ "github.com/Infisical/infisical/tests/internal/id"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func TestEmailDomain_Verify(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should verify a domain with the published TXT record", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ d := pendingDomain(t, tn)+ fakenet.SetTXT(t, fixture.FakenetAdmin(t, tn), d.VerificationRecordName, "infisical-domain-verification="+d.VerificationCode)++ // Action+ res, err := tn.Admin.API.VerifyEmailDomainWithResponse(t.Context(), d.Id)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, "verified", domainStatus(t, tn, d.Domain))+ })++ t.Run("should refuse verification when no TXT record exists and leave it pending", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ d := pendingDomain(t, tn)++ // Action+ res, err := tn.Admin.API.VerifyEmailDomainWithResponse(t.Context(), d.Id)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Equal(t, "pending", domainStatus(t, tn, d.Domain))+ })++ t.Run("should refuse verification when the TXT record holds another value and leave it pending", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ d := pendingDomain(t, tn)+ fakenet.SetTXT(t, fixture.FakenetAdmin(t, tn), d.VerificationRecordName, "infisical-domain-verification=wrong")++ // Action+ res, err := tn.Admin.API.VerifyEmailDomainWithResponse(t.Context(), d.Id)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "DNS TXT record not found or value does not match")+ require.Equal(t, "pending", domainStatus(t, tn, d.Domain))+ })+}++func TestEmailDomain_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a domain already verified by another org", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, other := h.NewTenant(t), h.NewTenant(t)+ fixture.VerifiedEmailDomain(t, other)+ domain := strings.SplitN(other.Email("x"), "@", 2)[1]++ // Action+ res, err := tn.Admin.API.CreateEmailDomainWithResponse(t.Context(), api.CreateEmailDomainJSONRequestBody{Domain: domain})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "This domain is already verified by an organization")+ require.Empty(t, domainNames(t, tn))+ })++ t.Run("should refuse when the plan has no SSO feature", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.SAMLSSO, license.OIDCSSO, license.LDAP)))++ // Action+ res, err := tn.Admin.API.CreateEmailDomainWithResponse(t.Context(), api.CreateEmailDomainJSONRequestBody{Domain: id.Nonce() + ".test"})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to add email domain due to plan restriction")+ require.Empty(t, domainNames(t, tn))+ })++ t.Run("should refuse a member without email domain permission", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))++ // Action+ res, err := member.API.CreateEmailDomainWithResponse(t.Context(), api.CreateEmailDomainJSONRequestBody{Domain: id.Nonce() + ".test"})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Empty(t, domainNames(t, tn))+ })+}++type emailDomain struct {+ Id openapi_types.UUID+ Domain string+ VerificationCode string+ VerificationRecordName string+}++func pendingDomain(t *testing.T, tn *harness.Tenant) emailDomain {+ t.Helper()+ res, err := tn.Admin.API.CreateEmailDomainWithResponse(t.Context(), api.CreateEmailDomainJSONRequestBody{Domain: id.Nonce() + ".test"})+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ d := res.JSON200.EmailDomain+ return emailDomain{Id: d.Id, Domain: d.Domain, VerificationCode: d.VerificationCode, VerificationRecordName: d.VerificationRecordName}+}++func listDomains(t *testing.T, tn *harness.Tenant) *api.ListEmailDomainsResponse {+ t.Helper()+ res, err := fresh(t, tn, tn.Admin).ListEmailDomainsWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return res+}++func domainNames(t *testing.T, tn *harness.Tenant) []string {+ t.Helper()+ var out []string+ for _, d := range listDomains(t, tn).JSON200.EmailDomains {+ out = append(out, d.Domain)+ }+ return out+}++func domainStatus(t *testing.T, tn *harness.Tenant, domain string) string {+ t.Helper()+ for _, d := range listDomains(t, tn).JSON200.EmailDomains {+ if d.Domain == domain {+ return deref(d.Status)+ }+ }+ t.Fatalf("domain %s is not listed", domain)+ return ""+}diff --git a/tests/suites/organization/helpers_test.go b/tests/suites/organization/helpers_test.gonew file mode 100644index 0000000000..bfa74bb3df--- /dev/null+++ b/tests/suites/organization/helpers_test.go@@ -0,0 +1,149 @@+package organization_test++import (+ "bytes"+ "crypto/rand"+ "encoding/json"+ "fmt"+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/harness/infisical"+ "github.com/Infisical/infisical/tests/internal/apierr"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++// sourceIP is a fresh rate-limit bucket. Invites go through smtpRateLimit (two per+// forty seconds per address), so every invite a test sends needs its own.+func sourceIP() string {+ b := make([]byte, 3)+ _, _ = rand.Read(b)+ return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])+}++// fresh is p's client on a bucket nobody else is drawing down.+func fresh(t *testing.T, tn *harness.Tenant, p *harness.Principal) *api.ClientWithResponses {+ t.Helper()+ return tn.Client(t, p.Token, infisical.ForwardedFor(sourceIP()))+}++func requireStatus(t *testing.T, want, got int, body []byte) {+ t.Helper()+ require.Equalf(t, want, got, "answered %d: %s", got, apierr.Body(body))+}++type organization struct {+ Name string+ Slug string+ AuthEnforced bool+ GoogleSsoAuthEnforced bool+ DefaultMembershipRole string+}++func orgOf(t *testing.T, tn *harness.Tenant) organization {+ t.Helper()+ res, err := fresh(t, tn, tn.Admin).GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ o := res.JSON200.Organization+ return organization{+ Name: o.Name,+ Slug: o.Slug,+ AuthEnforced: o.AuthEnforced != nil && *o.AuthEnforced,+ GoogleSsoAuthEnforced: o.GoogleSsoAuthEnforced != nil && *o.GoogleSsoAuthEnforced,+ DefaultMembershipRole: deref(o.DefaultMembershipRole),+ }+}++func membershipOf(t *testing.T, tn *harness.Tenant, p *harness.Principal) *fixture.Membership {+ t.Helper()+ m := fixture.MembershipOf(t, tn, p.Email)+ require.NotNilf(t, m, "%s has no org membership", p.Email)+ return m+}++func invite(t *testing.T, tn *harness.Tenant, actor *harness.Principal, role string, emails ...string) *api.InviteUsersToOrganizationResponse {+ t.Helper()+ addrs := make([]openapi_types.Email, len(emails))+ for i, e := range emails {+ addrs[i] = openapi_types.Email(e)+ }+ res, err := fresh(t, tn, actor).InviteUsersToOrganizationWithResponse(t.Context(), api.InviteUsersToOrganizationJSONRequestBody{+ InviteeEmails: addrs,+ OrganizationId: tn.OrgID.String(),+ OrganizationRoleSlug: &role,+ })+ require.NoError(t, err)+ return res+}++// customRoleUser is a user whose only org role is a new custom role with exactly the+// given rules.+func customRoleUser(t *testing.T, tn *harness.Tenant, slug string, perms ...fixture.Permission) *harness.Principal {+ t.Helper()+ fixture.NewOrgRole(t, tn, slug, perms...)+ return tn.NewUser(t, harness.OrgRole(slug))+}++func createOrgRole(t *testing.T, actor *api.ClientWithResponses, slug string, perms ...fixture.Permission) *api.CreateOrganizationRoleResponse {+ t.Helper()+ if perms == nil {+ perms = []fixture.Permission{}+ }+ body, err := json.Marshal(map[string]any{"slug": slug, "name": slug, "permissions": perms})+ require.NoError(t, err)+ res, err := actor.CreateOrganizationRoleWithBodyWithResponse(t.Context(), "application/json", bytes.NewReader(body))+ require.NoError(t, err)+ return res+}++func orgRoleSlugs(t *testing.T, tn *harness.Tenant) []string {+ t.Helper()+ res, err := fresh(t, tn, tn.Admin).ListOrganizationRolesWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ var slugs []string+ for _, r := range res.JSON200.Roles {+ slugs = append(slugs, r.Slug)+ }+ return slugs+}++// packedRules turns the CASL packed rules GET /organization/permissions returns into+// subject -> actions, for allow rules only.+func packedRules(t *testing.T, raw []any) map[string][]string {+ t.Helper()+ out := map[string][]string{}+ for _, r := range raw {+ rule, ok := r.([]any)+ require.Truef(t, ok, "rule %v is not packed", r)+ require.GreaterOrEqual(t, len(rule), 2)+ if len(rule) > 3 {+ if inverted, _ := rule[3].(float64); inverted == 1 {+ continue+ }+ if inverted, _ := rule[3].(bool); inverted {+ continue+ }+ }+ actions, _ := rule[0].(string)+ subjects, _ := rule[1].(string)+ for _, s := range strings.Split(subjects, ",") {+ out[s] = append(out[s], strings.Split(actions, ",")...)+ }+ }+ return out+}++func deref[T any](p *T) T {+ var zero T+ if p == nil {+ return zero+ }+ return *p+}diff --git a/tests/suites/organization/invite_test.go b/tests/suites/organization/invite_test.gonew file mode 100644index 0000000000..45b68546fd--- /dev/null+++ b/tests/suites/organization/invite_test.go@@ -0,0 +1,155 @@+package organization_test++import (+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra/fakenet"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/Infisical/infisical/tests/internal/spec"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func TestInvite_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should mail an invite and give the requested org role and project access", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ addr := tn.Email("invitee")++ // Action+ res, err := fresh(t, tn, tn.Admin).InviteUsersToOrganizationWithResponse(t.Context(), api.InviteUsersToOrganizationJSONRequestBody{+ InviteeEmails: []openapi_types.Email{openapi_types.Email(addr)},+ OrganizationId: tn.OrgID.String(),+ OrganizationRoleSlug: new("admin"),+ ProjectIds: &[]string{proj.ID},+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Nil(t, res.JSON200.GrantFailures)+ tn.Mail(t).Expect(t, addr, smtp.Subject("invitation"))+ m := fixture.MembershipOf(t, tn, addr)+ require.NotNil(t, m)+ require.Equal(t, "admin", m.Role)+ require.Equal(t, "invited", m.Status)+ require.Contains(t, projectMemberEmails(t, tn, proj), addr)+ })++ t.Run("should refuse a role the actor cannot grant and mail nobody", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ inviter := customRoleUser(t, tn, "inviter",+ fixture.Permission{Subject: "member", Action: []string{"read", "create"}})+ addr := tn.Email("escalated")++ // Action+ res := invite(t, tn, inviter, "admin", addr)++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Permission denied: grant-privileges on member")+ require.Nil(t, fixture.MembershipOf(t, tn, addr))+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool { return e.Recipient == addr })+ })++ t.Run("should refuse invitees off the verified domains when SSO is enforced", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sso.NewSAML(t, tn, sso.Okta).Enforce(t)+ outsider := "outsider@" + id.Nonce() + ".test"++ // Action+ res := invite(t, tn, tn.Admin, "member", outsider)++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Only users with a verified organization email domain can be invited")+ require.Nil(t, fixture.MembershipOf(t, tn, outsider))+ })++ t.Run("should refuse a member without member create and mail nobody", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))+ addr := tn.Email("uninvited")++ // Action+ res := invite(t, tn, member, "member", addr)++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Nil(t, fixture.MembershipOf(t, tn, addr))+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool { return e.Recipient == addr })+ })++ t.Run("should refuse invites past the plan's member limit and mail nobody", func(t *testing.T) {+ t.Parallel()++ spec.Why(t, `The admin sits only in the bootstrapped product projects, which are not+ billed, so the one seat in use is the machine identity.`)++ // Setup+ limited := license.Enterprise().With(license.MaxIdentityLimit, 1)+ limited.Slug = "pro"+ tn := h.NewTenant(t, harness.WithPlan(limited))+ tn.NewMachineIdentity(t)+ addr := tn.Email("overflow")++ // Action+ res := invite(t, tn, tn.Admin, "member", addr)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "member limit reached")+ require.Nil(t, fixture.MembershipOf(t, tn, addr))+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool { return e.Recipient == addr })+ })+}++func TestInvite_Resend(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a resend for an accepted invite and mail nobody", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))+ mark := tn.Mail(t).Mark(t)++ // Action+ res, err := fresh(t, tn, tn.Admin).ResendOrganizationMemberInvitationWithResponse(t.Context(),+ api.ResendOrganizationMemberInvitationJSONRequestBody{MembershipId: membershipOf(t, tn, member).ID.String()})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Organization invitation already accepted")+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t,+ func(e smtp.MessageReceived) bool {+ return e.Recipient == member.Email && strings.Contains(e.Message.Subject, "invitation")+ }, fakenet.Since(mark))+ })+}diff --git a/tests/suites/organization/membership_test.go b/tests/suites/organization/membership_test.gonew file mode 100644index 0000000000..3a8b14835a--- /dev/null+++ b/tests/suites/organization/membership_test.go@@ -0,0 +1,220 @@+package organization_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func TestMembership_Update(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse editing one's own membership", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ own := membershipOf(t, tn, tn.Admin)++ // Action+ res, err := tn.Admin.API.UpdateOrgMembershipWithResponse(t.Context(), tn.OrgID.String(), own.ID.String(),+ api.UpdateOrgMembershipJSONRequestBody{Role: new("member")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnauthorized, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Cannot update own organization membership")+ require.Equal(t, "admin", membershipOf(t, tn, tn.Admin).Role)+ })++ t.Run("should refuse assigning admin when the actor cannot grant member privileges, and keep the role", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ editor := customRoleUser(t, tn, "member-editor",+ fixture.Permission{Subject: "member", Action: []string{"read", "edit"}})+ target := tn.NewUser(t, harness.OrgRole("member"))++ // Action+ res, err := editor.API.UpdateOrgMembershipWithResponse(t.Context(), tn.OrgID.String(),+ membershipOf(t, tn, target).ID.String(), api.UpdateOrgMembershipJSONRequestBody{Role: new("admin")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Permission denied: grant-privileges on member")+ require.Equal(t, "member", membershipOf(t, tn, target).Role)+ })++ t.Run("should answer 404 for another org's membership id and leave it unchanged", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, other := h.NewTenant(t), h.NewTenant(t)+ theirs := other.NewUser(t, harness.OrgRole("member"))+ id := membershipOf(t, other, theirs).ID.String()++ // Action+ res, err := tn.Admin.API.UpdateOrgMembershipWithResponse(t.Context(), tn.OrgID.String(), id,+ api.UpdateOrgMembershipJSONRequestBody{Role: new("admin")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Equal(t, "member", membershipOf(t, other, theirs).Role)+ })+}++func TestMembership_Delete(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse removing the last admin through the API", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ identity := tn.NewMachineIdentity(t, harness.OrgRole("admin"))++ // Action+ res, err := identity.API.DeleteOrgMembershipWithResponse(t.Context(), tn.OrgID.String(),+ membershipOf(t, tn, tn.Admin).ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "This action would leave the organization with no admin")+ require.Equal(t, "admin", membershipOf(t, tn, tn.Admin).Role)+ })++ t.Run("should refuse removing oneself", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ second := tn.NewUser(t, harness.OrgRole("admin"))++ // Action+ res, err := second.API.DeleteOrgMembershipWithResponse(t.Context(), tn.OrgID.String(),+ membershipOf(t, tn, second).ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "You cannot remove yourself from an organization")+ require.Equal(t, "admin", membershipOf(t, tn, second).Role)+ })++ t.Run("should remove the member from projects and groups when removed from the org", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ member := tn.NewUser(t, harness.OrgRole("member"))+ proj.Grant(t, member, "viewer")+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, member)++ // Action+ res, err := tn.Admin.API.DeleteOrgMembershipWithResponse(t.Context(), tn.OrgID.String(),+ membershipOf(t, tn, member).ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Nil(t, fixture.MembershipOf(t, tn, member.Email))+ require.NotContains(t, projectMemberEmails(t, tn, proj), member.Email)+ require.NotContains(t, groupMemberIDs(t, tn, group), member.ID)+ })++ t.Run("should answer 404 for another org's membership id and keep it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, other := h.NewTenant(t), h.NewTenant(t)+ theirs := other.NewUser(t, harness.OrgRole("member"))++ // Action+ res, err := tn.Admin.API.DeleteOrgMembershipWithResponse(t.Context(), tn.OrgID.String(),+ membershipOf(t, other, theirs).ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.NotNil(t, fixture.MembershipOf(t, other, theirs.Email))+ })++ t.Run("should refuse the whole bulk delete when one id is unknown, and remove nobody", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))+ unknown := uuid.NewString()++ // Action+ res, err := tn.Admin.API.BulkDeleteOrgMembershipsWithResponse(t.Context(), tn.OrgID.String(),+ api.BulkDeleteOrgMembershipsJSONRequestBody{MembershipIds: []string{membershipOf(t, tn, member).ID.String(), unknown}})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), unknown)+ require.NotNil(t, fixture.MembershipOf(t, tn, member.Email))+ })+}++func projectMemberEmails(t *testing.T, tn *harness.Tenant, proj *fixture.Project) []string {+ t.Helper()+ res, err := fresh(t, tn, tn.Admin).ListProjectMembershipsWithResponse(t.Context(), proj.ID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ var emails []string+ for _, m := range res.JSON200.Memberships {+ emails = append(emails, m.User.Username)+ }+ return emails+}++func groupMemberIDs(t *testing.T, tn *harness.Tenant, g *fixture.Group) []uuid.UUID {+ t.Helper()+ res, err := fresh(t, tn, tn.Admin).ListGroupUsersWithResponse(t.Context(), g.ID.String(), nil)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ var ids []uuid.UUID+ for _, u := range res.JSON200.Users {+ if u.IsPartOfGroup {+ ids = append(ids, u.Id)+ }+ }+ return ids+}++func TestMembership_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should answer 404 when reading another org's membership id", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, other := h.NewTenant(t), h.NewTenant(t)+ theirs := other.NewUser(t, harness.OrgRole("member"))++ // Action+ res, err := tn.Admin.API.GetOrgMembershipWithResponse(t.Context(), tn.OrgID.String(),+ membershipOf(t, other, theirs).ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ })+}diff --git a/tests/suites/organization/oidcissuer_test.go b/tests/suites/organization/oidcissuer_test.gonew file mode 100644index 0000000000..d48fec095f--- /dev/null+++ b/tests/suites/organization/oidcissuer_test.go@@ -0,0 +1,93 @@+package organization_test++import (+ "context"+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/harness"+ "github.com/stretchr/testify/require"+)++func TestOIDCIssuer_Discovery(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should serve discovery whose issuer and jwks_uri belong to the org", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ issuer := h.App().SiteURL() + "/api/v1/oidc-issuer/organizations/" + tn.OrgID.String()++ // Action+ res, err := tn.Anonymous(t).GetOidcIssuerDiscoveryDocumentWithResponse(t.Context(), tn.OrgID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, issuer, res.JSON200.Issuer)+ require.Equal(t, issuer+"/.well-known/jwks.json", res.JSON200.JwksUri)+ require.Equal(t, []string{"RS256"}, res.JSON200.IdTokenSigningAlgValuesSupported)+ })++ t.Run("should answer 422 for a non-uuid org id", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res, err := tn.Anonymous(t).GetOidcIssuerDiscoveryDocumentWithResponse(t.Context(), tn.OrgID, orgIDInPath(tn.OrgID.String(), "not-a-uuid"))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnprocessableEntity, res.StatusCode(), res.Body)+ })+}++func TestOIDCIssuer_JWKS(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should serve an empty JWKS with no-store before any token is signed", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res, err := tn.Anonymous(t).GetOidcIssuerJwksWithResponse(t.Context(), tn.OrgID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Empty(t, res.JSON200.Keys)+ require.Equal(t, "no-store", res.HTTPResponse.Header.Get("Cache-Control"))+ })++ t.Run("should answer 422 for a non-uuid org id", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res, err := tn.Anonymous(t).GetOidcIssuerJwksWithResponse(t.Context(), tn.OrgID, orgIDInPath(tn.OrgID.String(), "not-a-uuid"))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnprocessableEntity, res.StatusCode(), res.Body)+ })+}++// orgIDInPath swaps the org id in the request path. The generated client types the+// parameter as a UUID, so a malformed one can only be sent by editing the request.+func orgIDInPath(from, to string) func(context.Context, *http.Request) error {+ return func(_ context.Context, req *http.Request) error {+ req.URL.Path = strings.Replace(req.URL.Path, from, to, 1)+ req.URL.RawPath = ""+ return nil+ }+}diff --git a/tests/suites/organization/organization_test.go b/tests/suites/organization/organization_test.goindex 77a66250ab..e618e6f5fe 100644--- a/tests/suites/organization/organization_test.go+++ b/tests/suites/organization/organization_test.go@@ -1,12 +1,18 @@package organization_testimport (+ "context""net/http""testing"+ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/sso""github.com/Infisical/infisical/tests/harness""github.com/Infisical/infisical/tests/internal/spec""github.com/google/uuid"+ openapi_types "github.com/oapi-codegen/runtime/types""github.com/stretchr/testify/require")@@ -44,4 +50,238 @@ func TestOrganization_Create(t *testing.T) {require.NoError(t, err)require.NotEqual(t, http.StatusOK, res.StatusCode(), "an organization that does not exist returned a plan")})++ t.Run("should make the creator admin", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ creator := tn.NewUser(t, harness.OrgRole("member"))++ // Action+ res, err := creator.API.CreateOrganizationWithResponse(t.Context(), api.CreateOrganizationJSONRequestBody{Name: "second"})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ orgID := res.JSON200.Organization.Id+ scoped := selectOrg(t, tn, creator, orgID)+ t.Cleanup(func() { _, _ = scoped.DeleteOrganizationWithResponse(context.WithoutCancel(t.Context()), orgID.String()) })+ perms, err := scoped.GetOrganizationPermissionsWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, perms.StatusCode(), perms.Body)+ require.Len(t, perms.JSON200.Memberships, 1)+ require.Equal(t, "admin", perms.JSON200.Memberships[0].Roles[0].Role)+ })++ t.Run("should refuse a second root org for the same user on cloud", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res, err := tn.Admin.API.CreateOrganizationWithResponse(t.Context(), api.CreateOrganizationJSONRequestBody{Name: "second"})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusConflict, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "You have already created an organization")+ orgs, err := tn.Admin.API.ListUserOrganizationsWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, orgs.StatusCode(), orgs.Body)+ require.Len(t, orgs.JSON200.Organizations, 1)+ })+}++func TestOrganization_Update(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a settings edit without settings edit, and keep the name", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))+ before := orgOf(t, tn)++ // Action+ res, err := member.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{Name: new("renamed")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Equal(t, before.Name, orgOf(t, tn).Name)+ })++ t.Run("should refuse a slug another org holds", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn, other := h.NewTenant(t), h.NewTenant(t)++ // Action+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{Slug: &other.OrgSlug})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Organization with slug "+other.OrgSlug+" already exists")+ require.Equal(t, tn.OrgSlug, orgOf(t, tn).Slug)+ })++ t.Run("should refuse an invalid userTokenExpiration", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{UserTokenExpiration: new("0d")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusUnprocessableEntity, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Duration value must be at least 1")+ })++ t.Run("should refuse a custom default membership role when the plan lacks rbac", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ fixture.NewOrgRole(t, tn, "reader", fixture.Permission{Subject: "member", Action: []string{"read"}})+ tn.SetPlan(t, license.Enterprise().Without(license.RBAC))++ // Action+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{DefaultMembershipRoleSlug: new("reader")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to set custom default role due to plan RBAC restriction")+ require.Equal(t, "member", orgOf(t, tn).DefaultMembershipRole)+ })++ t.Run("should give new invitees the default membership role", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{DefaultMembershipRoleSlug: new("no-access")})+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ addr := tn.Email("newcomer")++ // Action+ invited, err := tn.Admin.API.InviteProjectMembersWithResponse(t.Context(), proj.ID,+ api.InviteProjectMembersJSONRequestBody{Emails: &[]openapi_types.Email{openapi_types.Email(addr)}})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, invited.StatusCode(), invited.Body)+ m := fixture.MembershipOf(t, tn, addr)+ require.NotNil(t, m)+ require.Equal(t, "no-access", m.Role)+ })++ t.Run("should refuse SSO enforcement before a successful OIDC login", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sso.NewOIDC(t, tn)++ // Action+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{AuthEnforced: new(true)})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "please log in via OIDC at least once")+ require.False(t, orgOf(t, tn).AuthEnforced)+ })++ t.Run("should refuse SAML and Google enforcement together", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{AuthEnforced: new(true), GoogleSsoAuthEnforced: new(true)})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body),+ "SAML/OIDC auth enforcement and Google SSO auth enforcement cannot be enabled at the same time")+ after := orgOf(t, tn)+ require.False(t, after.AuthEnforced)+ require.False(t, after.GoogleSsoAuthEnforced)+ })+}++func TestOrganization_Delete(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a non-admin and keep the org", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))++ // Action+ res, err := member.API.DeleteOrganizationWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Equal(t, tn.OrgSlug, orgOf(t, tn).Slug)+ })++ t.Run("should delete the org and refuse its members' tokens on its routes", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))+ before, err := member.API.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, before.StatusCode(), before.Body)++ // Action+ res, err := tn.Admin.API.DeleteOrganizationWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ after, err := member.API.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ requireStatus(t, http.StatusUnauthorized, after.StatusCode(), after.Body)+ require.Contains(t, string(after.Body), "no longer exists")+ members, err := member.API.ListOrgMembershipsWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ requireStatus(t, http.StatusUnauthorized, members.StatusCode(), members.Body)+ })+}++// selectOrg scopes p's session to another organization p belongs to.+func selectOrg(t *testing.T, tn *harness.Tenant, p *harness.Principal, orgID uuid.UUID) *api.ClientWithResponses {+ t.Helper()+ res, err := p.API.SelectOrganizationV3WithResponse(t.Context(), api.SelectOrganizationV3JSONRequestBody{OrganizationId: orgID.String()})+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ return tn.Client(t, res.JSON200.Token)}diff --git a/tests/suites/organization/ratelimit_test.go b/tests/suites/organization/ratelimit_test.gonew file mode 100644index 0000000000..441ebd76e3--- /dev/null+++ b/tests/suites/organization/ratelimit_test.go@@ -0,0 +1,126 @@+package organization_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/harness/infisical"+ "github.com/Infisical/infisical/tests/internal/spec"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func TestRateLimit_Read(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should answer 429 with the retry message past the plan's read limit", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().With(license.ReadRateLimit, 3)))+ caller := tn.Client(t, tn.Admin.Token, infisical.ForwardedFor(sourceIP()))+ require.Equal(t, []int{200, 200, 200}, readOrg(t, tn, caller, 3))++ // Action+ res, err := caller.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusTooManyRequests, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Rate limit exceeded. Please try again in")+ })++ t.Run("should apply a raised plan limit", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `Counted from a fresh address after the raise, so the result cannot come+ from the old bucket expiring.`)++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().With(license.ReadRateLimit, 2)))+ before := tn.Client(t, tn.Admin.Token, infisical.ForwardedFor(sourceIP()))+ require.Equal(t, []int{200, 200, 429}, readOrg(t, tn, before, 3))++ // Action+ tn.SetPlan(t, license.Enterprise().With(license.ReadRateLimit, 5))++ // Assert+ after := tn.Client(t, tn.Admin.Token, infisical.ForwardedFor(sourceIP()))+ require.Equal(t, []int{200, 200, 200, 200, 200, 429}, readOrg(t, tn, after, 6))+ })++ t.Run("should leave other source IPs unaffected", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().With(license.ReadRateLimit, 2)))+ exhausted := tn.Client(t, tn.Admin.Token, infisical.ForwardedFor(sourceIP()))+ require.Equal(t, []int{200, 200, 429}, readOrg(t, tn, exhausted, 3))+ other := tn.Client(t, tn.Admin.Token, infisical.ForwardedFor(sourceIP()))++ // Action+ res, err := other.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ })+}++func TestRateLimit_InviteMail(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should limit invite mail sends and send no extra mail", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ caller := tn.Client(t, tn.Admin.Token, infisical.ForwardedFor(sourceIP()))+ first, second, third := tn.Email("first"), tn.Email("second"), tn.Email("third")+ for _, addr := range []string{first, second} {+ res := inviteWith(t, tn, caller, addr)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ }++ // Action+ res := inviteWith(t, tn, caller, third)++ // Assert+ requireStatus(t, http.StatusTooManyRequests, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Rate limit exceeded")+ inbox := tn.Mail(t)+ inbox.Expect(t, first, smtp.Subject("invitation"))+ inbox.Expect(t, second, smtp.Subject("invitation"))+ inbox.ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool { return e.Recipient == third })+ require.Nil(t, fixture.MembershipOf(t, tn, third))+ })+}++// readOrg reads the org n times and returns each status.+func readOrg(t *testing.T, tn *harness.Tenant, c *api.ClientWithResponses, n int) []int {+ t.Helper()+ out := make([]int, 0, n)+ for range n {+ res, err := c.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ out = append(out, res.StatusCode())+ }+ return out+}++func inviteWith(t *testing.T, tn *harness.Tenant, c *api.ClientWithResponses, addr string) *api.InviteUsersToOrganizationResponse {+ t.Helper()+ res, err := c.InviteUsersToOrganizationWithResponse(t.Context(), api.InviteUsersToOrganizationJSONRequestBody{+ InviteeEmails: []openapi_types.Email{openapi_types.Email(addr)},+ OrganizationId: tn.OrgID.String(),+ OrganizationRoleSlug: new("member"),+ })+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/organization/role_test.go b/tests/suites/organization/role_test.gonew file mode 100644index 0000000000..01e2d46dab--- /dev/null+++ b/tests/suites/organization/role_test.go@@ -0,0 +1,290 @@+package organization_test++import (+ "bytes"+ "encoding/json"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/stretchr/testify/require"+)++var emailDomainsRead = fixture.Permission{Subject: "email-domains", Action: []string{"read"}}++func TestOrgRole_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should create, read by slug and list a custom role alongside admin, member and no-access", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res := createOrgRole(t, tn.Admin.API, "domain-reader", emailDomainsRead)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ got, err := tn.Admin.API.GetOrganizationRoleBySlugWithResponse(t.Context(), "domain-reader")+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, got.StatusCode(), got.Body)+ require.Equal(t, res.JSON200.Role.Id, got.JSON200.Role.Id)+ require.Equal(t, []fixture.Permission{emailDomainsRead}, rolePermissions(t, got.Body))+ require.Subset(t, orgRoleSlugs(t, tn), []string{"admin", "member", "no-access", "domain-reader"})+ })++ t.Run("should refuse a reserved slug", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ before := orgRoleSlugs(t, tn)++ // Action+ res := createOrgRole(t, tn.Admin.API, "admin", emailDomainsRead)++ // Assert+ requireStatus(t, http.StatusUnprocessableEntity, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "the slug you have entered is reserved")+ require.Equal(t, before, orgRoleSlugs(t, tn))+ })++ t.Run("should refuse a duplicate slug and keep the original", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ original := fixture.NewOrgRole(t, tn, "domain-reader", emailDomainsRead)++ // Action+ res := createOrgRole(t, tn.Admin.API, "domain-reader", fixture.Permission{Subject: "member", Action: []string{"read"}})++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Role with domain-reader already exists")+ got, err := tn.Admin.API.GetOrganizationRoleBySlugWithResponse(t.Context(), "domain-reader")+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, got.StatusCode(), got.Body)+ require.Equal(t, original, got.JSON200.Role.Id.String())+ require.Equal(t, []fixture.Permission{emailDomainsRead}, rolePermissions(t, got.Body))+ })++ t.Run("should refuse create when the plan lacks rbac", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.RBAC)))++ // Action+ res := createOrgRole(t, tn.Admin.API, "domain-reader", emailDomainsRead)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to create custom role due to plan RBAC restriction")+ require.NotContains(t, orgRoleSlugs(t, tn), "domain-reader")+ })+}++func TestOrgRole_Update(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse update when the plan lacks rbac and keep the rules", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ roleID := fixture.NewOrgRole(t, tn, "domain-reader", emailDomainsRead)+ tn.SetPlan(t, license.Enterprise().Without(license.RBAC))+ body, err := json.Marshal(map[string]any{"permissions": []fixture.Permission{{Subject: "member", Action: []string{"read"}}}})+ require.NoError(t, err)++ // Action+ res, err := tn.Admin.API.UpdateOrganizationRoleWithBodyWithResponse(t.Context(), roleID, "application/json", bytes.NewReader(body))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Failed to update custom role due to plan RBAC restriction")+ got, err := tn.Admin.API.GetOrganizationRoleBySlugWithResponse(t.Context(), "domain-reader")+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, got.StatusCode(), got.Body)+ require.Equal(t, []fixture.Permission{emailDomainsRead}, rolePermissions(t, got.Body))+ })++ t.Run("should keep an assigned custom role working after the plan loses rbac", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ reader := customRoleUser(t, tn, "domain-reader", emailDomainsRead)++ // Action+ tn.SetPlan(t, license.Enterprise().Without(license.RBAC))++ // Assert+ res, err := reader.API.ListEmailDomainsWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ })+}++func TestOrgRole_Delete(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse deleting a role assigned to a member and keep it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ roleID := fixture.NewOrgRole(t, tn, "domain-reader", emailDomainsRead)+ tn.NewUser(t, harness.OrgRole("domain-reader"))++ // Action+ res, err := tn.Admin.API.DeleteOrganizationRoleWithResponse(t.Context(), roleID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Role is assigned to 1")+ require.Contains(t, orgRoleSlugs(t, tn), "domain-reader")+ })++ t.Run("should refuse deleting a role used by an external group mapping and keep it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ roleID := fixture.NewOrgRole(t, tn, "domain-reader", emailDomainsRead)+ var mapping api.UpdateExternalGroupOrgRoleMappingsJSONRequestBody+ mapping.Mappings = append(mapping.Mappings, struct {+ GroupName string `json:"groupName"`+ RoleSlug string `json:"roleSlug"`+ }{GroupName: "engineering", RoleSlug: "domain-reader"})+ mapped, err := tn.Admin.API.UpdateExternalGroupOrgRoleMappingsWithResponse(t.Context(), mapping)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, mapped.StatusCode(), mapped.Body)++ // Action+ res, err := tn.Admin.API.DeleteOrganizationRoleWithResponse(t.Context(), roleID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Cannot delete role assigned to external group organization role mapping")+ require.Contains(t, orgRoleSlugs(t, tn), "domain-reader")+ })+}++func TestOrgRole_Permissions(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should let a custom role read what it grants", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ reader := customRoleUser(t, tn, "domain-reader", emailDomainsRead)++ // Action+ res, err := reader.API.ListEmailDomainsWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ })++ t.Run("should refuse a custom role an action on a subject it grants only read on, and create nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ reader := customRoleUser(t, tn, "domain-reader", emailDomainsRead)++ // Action+ res, err := reader.API.CreateEmailDomainWithResponse(t.Context(), api.CreateEmailDomainJSONRequestBody{Domain: "acme-" + tn.OrgSlug + ".test"})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ domains, err := tn.Admin.API.ListEmailDomainsWithResponse(t.Context())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, domains.StatusCode(), domains.Body)+ require.Empty(t, domains.JSON200.EmailDomains)+ })++ t.Run("should refuse a custom role a subject it does not grant", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ reader := customRoleUser(t, tn, "domain-reader", emailDomainsRead)++ // Action+ res, err := reader.API.ListOrgMembershipsWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ })++ t.Run("should let a deny rule from a group's role override an allow from the member's own role", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ user := customRoleUser(t, tn, "conn-reader",+ fixture.Permission{Subject: "app-connections", Action: []string{"read"}})+ fixture.NewOrgRole(t, tn, "conn-denied",+ fixture.Permission{Subject: "app-connections", Action: []string{"read"}, Inverted: true})+ group := fixture.NewGroup(t, tn, fixture.WithGroupRole("conn-denied"))+ allowed, err := user.API.ListGitHubAppConnectionsWithResponse(t.Context(), nil)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, allowed.StatusCode(), allowed.Body)++ // Action+ group.AddUser(t, user)++ // Assert+ res, err := user.API.ListGitHubAppConnectionsWithResponse(t.Context(), nil)+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ })++ t.Run("should report the caller's org role and rules from GET /organization/permissions", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ reader := customRoleUser(t, tn, "domain-reader", emailDomainsRead)++ // Action+ res, err := reader.API.GetOrganizationPermissionsWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Len(t, res.JSON200.Memberships, 1)+ require.Equal(t, "custom", res.JSON200.Memberships[0].Roles[0].Role)+ require.Equal(t, map[string][]string{"email-domains": {"read"}}, packedRules(t, res.JSON200.Permissions))+ })+}++// rolePermissions reads a role's rules back in the shape they were sent.+func rolePermissions(t *testing.T, body []byte) []fixture.Permission {+ t.Helper()+ var out struct {+ Role struct {+ Permissions []fixture.Permission `json:"permissions"`+ } `json:"role"`+ }+ require.NoError(t, json.Unmarshal(body, &out))+ return out.Role.Permissions+}diff --git a/tests/suites/organization/settings_test.go b/tests/suites/organization/settings_test.gonew file mode 100644index 0000000000..ec89768b4c--- /dev/null+++ b/tests/suites/organization/settings_test.go@@ -0,0 +1,125 @@+package organization_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/harness"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func TestOrganization_PrivilegeUpgrade(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a non-admin", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))++ // Action+ res, err := member.API.UpgradePrivilegeSystemWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "only the organization admin can upgrade the privilege system")+ })++ t.Run("should refuse an upgrade when the org is already on the new privilege system", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res, err := tn.Admin.API.UpgradePrivilegeSystemWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Privilege system already upgraded")+ })+}++func TestOrganization_IncidentContacts(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should list an added contact and drop it once removed", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ addr := tn.Email("oncall")+ added := addIncidentContact(t, tn, tn.Admin, addr)+ requireStatus(t, http.StatusOK, added.StatusCode(), added.Body)+ require.Equal(t, []string{addr}, incidentContacts(t, tn))++ // Action+ res, err := tn.Admin.API.DeleteOrganizationIncidentContactWithResponse(t.Context(), tn.OrgID.String(),+ added.JSON200.IncidentContactsOrg.Id.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Empty(t, incidentContacts(t, tn))+ })++ t.Run("should refuse a duplicate contact and keep one", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ addr := tn.Email("oncall")+ first := addIncidentContact(t, tn, tn.Admin, addr)+ requireStatus(t, http.StatusOK, first.StatusCode(), first.Body)++ // Action+ res := addIncidentContact(t, tn, tn.Admin, addr)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Incident contact already exists")+ require.Equal(t, []string{addr}, incidentContacts(t, tn))+ })++ t.Run("should refuse a member adding a contact", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t, harness.OrgRole("member"))++ // Action+ res := addIncidentContact(t, tn, member, tn.Email("oncall"))++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Empty(t, incidentContacts(t, tn))+ })+}++func addIncidentContact(t *testing.T, tn *harness.Tenant, actor *harness.Principal, addr string) *api.CreateOrganizationIncidentContactResponse {+ t.Helper()+ res, err := actor.API.CreateOrganizationIncidentContactWithResponse(t.Context(), tn.OrgID.String(),+ api.CreateOrganizationIncidentContactJSONRequestBody{Email: openapi_types.Email(addr)})+ require.NoError(t, err)+ return res+}++func incidentContacts(t *testing.T, tn *harness.Tenant) []string {+ t.Helper()+ res, err := fresh(t, tn, tn.Admin).ListOrganizationIncidentContactsWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ var out []string+ for _, c := range res.JSON200.IncidentContactsOrg {+ out = append(out, c.Email)+ }+ return out+}diff --git a/tests/suites/secretmanager/access/helpers_test.go b/tests/suites/secretmanager/access/helpers_test.goindex 77992fda44..e5778919e1 100644--- a/tests/suites/secretmanager/access/helpers_test.go+++ b/tests/suites/secretmanager/access/helpers_test.go@@ -3,7 +3,6 @@ package access_testimport ("bytes""context"- "crypto/rand""encoding/json""fmt""testing"@@ -213,14 +212,6 @@ func auditEvent(t *testing.T, tn *harness.Tenant, eventType string, match func(mreturn found}-// sourceIP is a fresh address for a caller whose source address is what the test is-// about.-func sourceIP() string {- b := make([]byte, 3)- _, _ = rand.Read(b)- return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])-}-func requireStatus(t *testing.T, want, got int, body []byte) {t.Helper()require.Equalf(t, want, got, "answered %d: %s", got, apierr.Body(body))diff --git a/tests/suites/secretmanager/access/principal_test.go b/tests/suites/secretmanager/access/principal_test.goindex 314747d269..7c33c1539c 100644--- a/tests/suites/secretmanager/access/principal_test.go+++ b/tests/suites/secretmanager/access/principal_test.go@@ -4,11 +4,9 @@ import ("net/http""testing"- "github.com/Infisical/infisical/tests/clients/api""github.com/Infisical/infisical/tests/fixture""github.com/Infisical/infisical/tests/fixture/secretmanager""github.com/Infisical/infisical/tests/harness"- "github.com/Infisical/infisical/tests/harness/infisical""github.com/stretchr/testify/require")@@ -119,78 +117,3 @@ func TestPrincipal_ProjectAccess(t *testing.T) {})})}--func TestPrincipal_TrustedIPs(t *testing.T) {- t.Parallel()- h := harness.From(t)-- t.Run("should refuse an identity token used from outside its trusted IPs and accept it from inside", func(t *testing.T) {- t.Parallel()-- // Setup- tn := h.NewTenant(t)- proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))- secretmanager.CreateSecret(t, proj, "dev", "EXISTING", "value")- trusted := sourceIP()- identity := identityTrustedFrom(t, tn, trusted)- proj.Grant(t, identity, "viewer")- outside := tn.Client(t, identity.Token, infisical.ForwardedFor(sourceIP()))-- // Action- res := listSecrets(t, outside, proj, "dev", "/")-- // Assert- require.Equal(t, http.StatusForbidden, res.StatusCode())- require.Contains(t, string(res.Body), "You are not allowed to access this resource from the current IP address")- inside := listSecrets(t, identity.API, proj, "dev", "/")- requireStatus(t, http.StatusOK, inside.StatusCode(), inside.Body)- require.Equal(t, []string{"EXISTING"}, keysOf(inside))- })-}--// identityTrustedFrom creates an org identity whose access tokens are valid only from-// one address, logged in from that address. Its API sends that address.-func identityTrustedFrom(t *testing.T, tn *harness.Tenant, ip string) *harness.Principal {- t.Helper()- ctx, admin := t.Context(), tn.Admin.API- name := "trusted-" + ip-- created, err := admin.CreateMachineIdentityWithResponse(ctx, api.CreateMachineIdentityJSONRequestBody{- Name: name, OrganizationId: tn.OrgID.String(), Role: new("member"),- })- require.NoError(t, err)- require.NotNilf(t, created.JSON200, "creating identity returned %d: %s", created.StatusCode(), created.Body)- identityID := created.JSON200.Identity.Id-- trustedIPs := []struct {- IpAddress string `json:"ipAddress"`- }{{IpAddress: ip + "/32"}}- attached, err := admin.AttachUniversalAuthWithResponse(ctx, identityID.String(), api.AttachUniversalAuthJSONRequestBody{- AccessTokenTrustedIps: &trustedIPs,- })- require.NoError(t, err)- require.NotNilf(t, attached.JSON200, "attaching universal auth returned %d: %s", attached.StatusCode(), attached.Body)-- secret, err := admin.CreateUniversalAuthClientSecretWithResponse(ctx, identityID.String(),- api.CreateUniversalAuthClientSecretJSONRequestBody{})- require.NoError(t, err)- require.NotNilf(t, secret.JSON200, "creating a client secret returned %d: %s", secret.StatusCode(), secret.Body)-- login, err := tn.Anonymous(t, infisical.ForwardedFor(ip)).LoginWithUniversalAuthWithResponse(ctx,- api.LoginWithUniversalAuthJSONRequestBody{- ClientId: attached.JSON200.IdentityUniversalAuth.ClientId,- ClientSecret: secret.JSON200.ClientSecret,- OrganizationSlug: &tn.OrgSlug,- })- require.NoError(t, err)- require.NotNilf(t, login.JSON200, "logging in returned %d: %s", login.StatusCode(), login.Body)-- token := login.JSON200.AccessToken- return &harness.Principal{- Kind: harness.MachineIdentity,- ID: identityID,- Name: name,- Token: token,- API: tn.Client(t, token, infisical.ForwardedFor(ip)),- }-}diff --git a/tests/suites/suborganization/helpers_test.go b/tests/suites/suborganization/helpers_test.gonew file mode 100644index 0000000000..3f403f8ebd--- /dev/null+++ b/tests/suites/suborganization/helpers_test.go@@ -0,0 +1,269 @@+package suborganization_test++import (+ "bytes"+ "context"+ "crypto/rand"+ "encoding/json"+ "fmt"+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/harness/infisical"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/google/uuid"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func requireStatus(t *testing.T, want, got int, body []byte) {+ t.Helper()+ require.Equalf(t, want, got, "answered %d: %s", got, apierr.Body(body))+}++// waitForStatus polls a call until it answers with the wanted status. Membership and+// role changes reach the project permission cache up to 10 seconds late.+func waitForStatus(t *testing.T, want int, call func() (int, []byte)) []byte {+ t.Helper()+ var last []byte+ _, err := wait.For(t.Context(), func(context.Context) (struct{}, bool, error) {+ status, body := call()+ last = body+ return struct{}{}, status == want, nil+ })+ require.NoErrorf(t, err, "waiting for %d, last body: %s", want, apierr.Body(last))+ return last+}++func jsonBody(t *testing.T, v any) *bytes.Reader {+ t.Helper()+ raw, err := json.Marshal(v)+ require.NoError(t, err)+ return bytes.NewReader(raw)+}++// sourceIP is a fresh rate-limit bucket, for calls that go through smtpRateLimit.+func sourceIP() string {+ b := make([]byte, 3)+ _, _ = rand.Read(b)+ return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])+}++func permanent(slug string) map[string]any { return map[string]any{"role": slug, "isTemporary": false} }++// expired is a temporary role whose window closed an hour ago.+func expired(slug string) map[string]any {+ return map[string]any{+ "role": slug,+ "isTemporary": true,+ "temporaryMode": "relative",+ "temporaryRange": "1h",+ "temporaryAccessStartTime": time.Now().Add(-2 * time.Hour).UTC().Format(time.RFC3339),+ }+}++// link asks the client's organization to link a group with these roles.+func link(t *testing.T, client *api.ClientWithResponses, groupID uuid.UUID, roles ...map[string]any) *api.CreateOrganizationGroupMembershipResponse {+ t.Helper()+ res, err := client.CreateOrganizationGroupMembershipWithBodyWithResponse(t.Context(), groupID,+ "application/json", jsonBody(t, map[string]any{"roles": roles}))+ require.NoError(t, err)+ return res+}++// addToSubOrg invites a root member into the sub-org with an org role, as its admin.+func addToSubOrg(t *testing.T, sub *fixture.SubOrg, user *harness.Principal, role string) {+ t.Helper()+ admin := sub.Tenant().Client(t, sub.Admin.Token, infisical.ForwardedFor(sourceIP()))+ res, err := admin.InviteUsersToOrganizationWithResponse(t.Context(), api.InviteUsersToOrganizationJSONRequestBody{+ InviteeEmails: []openapi_types.Email{openapi_types.Email(user.Email)},+ OrganizationId: sub.ID.String(),+ OrganizationRoleSlug: &role,+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "adding %s to %s: %s", user.Email, sub.Slug, apierr.Body(res.Body))+}++// memberUserIDs lists the users holding a direct membership in an organization.+func memberUserIDs(t *testing.T, client *api.ClientWithResponses, orgID uuid.UUID) []uuid.UUID {+ t.Helper()+ res, err := client.ListOrgMembershipsWithResponse(t.Context(), orgID.String())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing the members of %s returned %d: %s", orgID, res.StatusCode(), apierr.Body(res.Body))+ out := []uuid.UUID{}+ for _, m := range res.JSON200.Users {+ out = append(out, m.User.Id)+ }+ return out+}++func memberRole(t *testing.T, client *api.ClientWithResponses, orgID, userID uuid.UUID) string {+ t.Helper()+ res, err := client.ListOrgMembershipsWithResponse(t.Context(), orgID.String())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing the members of %s returned %d: %s", orgID, res.StatusCode(), apierr.Body(res.Body))+ for _, m := range res.JSON200.Users {+ if m.User.Id == userID {+ return m.Role+ }+ }+ t.Fatalf("user %s has no membership in %s", userID, orgID)+ return ""+}++func subOrgNames(t *testing.T, tn *harness.Tenant) []string {+ t.Helper()+ res, err := tn.Admin.API.ListSubOrganizationsWithResponse(t.Context(), nil)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing sub-organizations returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ out := []string{}+ for _, o := range res.JSON200.Organizations {+ out = append(out, o.Name)+ }+ return out+}++// groupIDs lists the groups that hold a membership in the client's organization.+func groupIDs(t *testing.T, client *api.ClientWithResponses) []uuid.UUID {+ t.Helper()+ res, err := client.ListGroupsWithResponse(t.Context())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing groups returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ out := []uuid.UUID{}+ for _, g := range *res.JSON200 {+ out = append(out, g.Id)+ }+ return out+}++func groupRoleIn(t *testing.T, client *api.ClientWithResponses, groupID uuid.UUID) string {+ t.Helper()+ res, err := client.GetGroupByIdWithResponse(t.Context(), groupID.String())+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "reading group %s returned %d: %s", groupID, res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.Role+}++func projectGroupIDs(t *testing.T, client *api.ClientWithResponses, projectID string) []uuid.UUID {+ t.Helper()+ res, err := client.ListProjectGroupMembershipsWithResponse(t.Context(), projectID)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "listing the groups of %s returned %d: %s", projectID, res.StatusCode(), apierr.Body(res.Body))+ out := []uuid.UUID{}+ for _, m := range res.JSON200.GroupMemberships {+ out = append(out, m.GroupId)+ }+ return out+}++func listSecrets(t *testing.T, client *api.ClientWithResponses, projectID string) (int, []byte) {+ t.Helper()+ env, path := "dev", "/"+ res, err := client.ListSecretsV4WithResponse(t.Context(), &api.ListSecretsV4Params{+ ProjectId: &projectID,+ Environment: &env,+ SecretPath: &path,+ })+ require.NoError(t, err)+ return res.StatusCode(), res.Body+}++// readConnections lists AWS app connections, which needs read on app-connections at+// the org level: admin has it, member does not.+func readConnections(t *testing.T, client *api.ClientWithResponses) (int, []byte) {+ t.Helper()+ res, err := client.ListAwsAppConnectionsWithResponse(t.Context(), nil)+ require.NoError(t, err)+ return res.StatusCode(), res.Body+}++// passwordLogin logs a harness user in again and returns the session's token, which+// is not yet bound to any organization.+func passwordLogin(t *testing.T, tn *harness.Tenant, email string) string {+ t.Helper()+ res, err := tn.Anonymous(t, infisical.ForwardedFor(sourceIP())).LoginV3WithResponse(t.Context(), api.LoginV3JSONRequestBody{+ Email: email,+ Password: harness.UserPassword,+ })+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "logging in as %s returned %d: %s", email, res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.AccessToken+}++func selectOrg(t *testing.T, tn *harness.Tenant, token string, orgID uuid.UUID) *api.SelectOrganizationV3Response {+ t.Helper()+ res, err := tn.Client(t, token).SelectOrganizationV3WithResponse(t.Context(),+ api.SelectOrganizationV3JSONRequestBody{OrganizationId: orgID.String()})+ require.NoError(t, err)+ return res+}++// universalAuth is a root org machine identity's universal auth credentials.+type universalAuth struct {+ IdentityID uuid.UUID+ ClientID string+ ClientSecret string+}++func newUniversalAuth(t *testing.T, tn *harness.Tenant) universalAuth {+ t.Helper()+ ctx, admin := t.Context(), tn.Admin.API+ created, err := admin.CreateMachineIdentityWithResponse(ctx, api.CreateMachineIdentityJSONRequestBody{+ Name: "i-" + id.Short(), OrganizationId: tn.OrgID.String(), Role: new("no-access"),+ })+ require.NoError(t, err)+ require.NotNilf(t, created.JSON200, "creating an identity returned %d: %s", created.StatusCode(), apierr.Body(created.Body))+ identityID := created.JSON200.Identity.Id++ attached, err := admin.AttachUniversalAuthWithResponse(ctx, identityID.String(), api.AttachUniversalAuthJSONRequestBody{})+ require.NoError(t, err)+ require.NotNilf(t, attached.JSON200, "attaching universal auth returned %d: %s", attached.StatusCode(), apierr.Body(attached.Body))+ secret, err := admin.CreateUniversalAuthClientSecretWithResponse(ctx, identityID.String(),+ api.CreateUniversalAuthClientSecretJSONRequestBody{})+ require.NoError(t, err)+ require.NotNilf(t, secret.JSON200, "creating a client secret returned %d: %s", secret.StatusCode(), apierr.Body(secret.Body))++ return universalAuth{IdentityID: identityID, ClientID: attached.JSON200.IdentityUniversalAuth.ClientId, ClientSecret: secret.JSON200.ClientSecret}+}++func (u universalAuth) login(t *testing.T, tn *harness.Tenant, orgSlug string) *api.LoginWithUniversalAuthResponse {+ t.Helper()+ res, err := tn.Anonymous(t, infisical.ForwardedFor(sourceIP())).LoginWithUniversalAuthWithResponse(t.Context(),+ api.LoginWithUniversalAuthJSONRequestBody{ClientId: u.ClientID, ClientSecret: u.ClientSecret, OrganizationSlug: &orgSlug})+ require.NoError(t, err)+ return res+}++// auditEvent waits for an organization's audit log to hold an event of the type whose+// metadata passes match. Audit logs are written from a queue after the response.+func auditEvent(t *testing.T, client *api.ClientWithResponses, eventType string, match func(map[string]any) bool) map[string]any {+ t.Helper()+ since := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)+ found, err := wait.For(t.Context(), func(ctx context.Context) (map[string]any, bool, error) {+ res, err := client.ListOrganizationAuditLogsWithResponse(ctx, &api.ListOrganizationAuditLogsParams{+ EventType: &eventType,+ StartDate: &since,+ })+ if err != nil {+ return nil, false, err+ }+ if res.JSON200 == nil {+ return nil, false, fmt.Errorf("listing audit logs returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ }+ for _, l := range res.JSON200.AuditLogs {+ metadata, _ := l.Event.Metadata.(map[string]any)+ if match(metadata) {+ return metadata, true, nil+ }+ }+ return nil, false, nil+ })+ require.NoErrorf(t, err, "waiting for a %s audit event", eventType)+ return found+}diff --git a/tests/suites/suborganization/main_test.go b/tests/suites/suborganization/main_test.gonew file mode 100644index 0000000000..58504872be--- /dev/null+++ b/tests/suites/suborganization/main_test.go@@ -0,0 +1,9 @@+package suborganization_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/harness"+)++func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }diff --git a/tests/suites/suborganization/suborg_test.go b/tests/suites/suborganization/suborg_test.gonew file mode 100644index 0000000000..1f8221419b--- /dev/null+++ b/tests/suites/suborganization/suborg_test.go@@ -0,0 +1,299 @@+package suborganization_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/stretchr/testify/require"+)++func TestSubOrganization_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should create a sub-org with its creator as admin", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ name := "sub-" + id.Short()++ // Action+ res, err := tn.Admin.API.CreateSubOrganizationWithResponse(t.Context(), api.CreateSubOrganizationJSONRequestBody{Name: name})++ // Assert+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "answered %d: %s", res.StatusCode(), res.Body)+ subID := res.JSON200.Organization.Id+ selected := selectOrg(t, tn, tn.Admin.Token, subID)+ require.NotNilf(t, selected.JSON200, "selecting the sub-org answered %d: %s", selected.StatusCode(), selected.Body)+ scoped := tn.Client(t, selected.JSON200.Token)+ require.Equal(t, "admin", memberRole(t, scoped, subID, tn.Admin.ID))+ require.Equal(t, []string{name}, subOrgNames(t, tn))+ })++ t.Run("should refuse creating a sub-org from a sub-org token and create none", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)++ // Action+ res, err := sub.Admin.API.CreateSubOrganizationWithResponse(t.Context(), api.CreateSubOrganizationJSONRequestBody{Name: "nested"})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Child organization cannot do this operation")+ require.Equal(t, []string{sub.Name}, subOrgNames(t, tn))+ })++ t.Run("should refuse creating a sub-org when the root plan lacks sub-organizations", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.SubOrganization)))++ // Action+ res, err := tn.Admin.API.CreateSubOrganizationWithResponse(t.Context(), api.CreateSubOrganizationJSONRequestBody{Name: "unlicensed"})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Sub-organization creation failed. Please upgrade your instance to Infisical's Enterprise plan.")+ require.Empty(t, subOrgNames(t, tn))+ })++ t.Run("should refuse a duplicate slug under the same parent", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)++ // Action+ res, err := tn.Admin.API.CreateSubOrganizationWithResponse(t.Context(), api.CreateSubOrganizationJSONRequestBody{+ Name: "another", Slug: &sub.Slug,+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), `Sub-organization with slug \"`+sub.Slug+`\" already exists`)+ require.Equal(t, []string{sub.Name}, subOrgNames(t, tn))+ })++ t.Run("should answer 400 not found for another root's sub-org and change nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ mine, theirs := h.NewTenant(t), h.NewTenant(t)+ sub := fixture.NewSubOrg(t, theirs)++ // Action+ res, err := mine.Admin.API.UpdateSubOrganizationWithResponse(t.Context(), sub.ID.String(),+ api.UpdateSubOrganizationJSONRequestBody{Name: new("taken-over")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Sub-organization not found")+ require.Equal(t, []string{sub.Name}, subOrgNames(t, theirs))+ })+}++func TestSubOrganization_Join(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should let a root admin join a sub-org through direct access", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ admin := tn.NewUser(t, harness.OrgRole("admin"))++ // Action+ res, err := admin.API.CreateSubOrganizationMembershipWithResponse(t.Context(), sub.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, "member", memberRole(t, sub.Admin.API, sub.ID, admin.ID))+ })++ t.Run("should refuse joining a sub-org without direct access and add no membership", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ member := tn.NewUser(t, harness.OrgRole("member"))++ // Action+ res, err := member.API.CreateSubOrganizationMembershipWithResponse(t.Context(), sub.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "You are not allowed to direct-access on sub-organization")+ require.NotContains(t, memberUserIDs(t, sub.Admin.API, sub.ID), member.ID)+ })++ t.Run("should refuse a second join and keep the existing role", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)++ // Action+ res, err := tn.Admin.API.CreateSubOrganizationMembershipWithResponse(t.Context(), sub.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "You are already a member of this sub-organization")+ require.Equal(t, "admin", memberRole(t, sub.Admin.API, sub.ID, tn.Admin.ID))+ })+}++func TestSubOrganization_Policy(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a password session into a sub-org when the root enforces SSO", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ member := tn.NewUser(t)+ addToSubOrg(t, sub, member, "member")+ sso.NewSAML(t, tn, sso.Okta).Enforce(t)+ session := passwordLogin(t, tn, member.Email)++ // Action+ res := selectOrg(t, tn, session, sub.ID)++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Organization authentication is enforced")+ })++ t.Run("should require MFA to enter a sub-org when the root enforces it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)+ member := tn.NewUser(t)+ addToSubOrg(t, sub, member, "member")+ enforced, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{EnforceMfa: new(true)})+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, enforced.StatusCode(), enforced.Body)+ session := passwordLogin(t, tn, member.Email)++ // Action+ res := selectOrg(t, tn, session, sub.ID)++ // Assert+ require.NotNilf(t, res.JSON200, "answered %d: %s", res.StatusCode(), res.Body)+ require.True(t, res.JSON200.IsMfaEnabled)+ require.Equal(t, "email", *res.JSON200.MfaMethod)+ })+}++func TestSubOrganization_Scope(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a sub-org token on a sibling sub-org's members", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ mine, sibling := fixture.NewSubOrg(t, tn), fixture.NewSubOrg(t, tn)++ // Action+ res, err := mine.Admin.API.ListOrgMembershipsWithResponse(t.Context(), sibling.ID.String())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Your token is scoped to organization with ID "+mine.ID.String())+ })++ t.Run("should refuse a sub-org role using sso, scim, billing or sub-organization subjects", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)++ // Action+ res, err := sub.Admin.API.CreateOrganizationRoleWithBodyWithResponse(t.Context(), "application/json", jsonBody(t, map[string]any{+ "slug": "too-wide", "name": "too-wide",+ "permissions": []fixture.Permission{+ {Subject: "sso", Action: []string{"read"}},+ {Subject: "scim", Action: []string{"read"}},+ {Subject: "billing", Action: []string{"read"}},+ {Subject: "sub-organization", Action: []string{"create"}},+ },+ }))++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Suborganization contains invalid permission subjects: sso,scim,billing,sub-organization")+ roles, err := sub.Admin.API.ListOrganizationRolesWithResponse(t.Context())+ require.NoError(t, err)+ require.NotNil(t, roles.JSON200)+ for _, r := range roles.JSON200.Roles {+ require.NotEqual(t, "too-wide", r.Slug)+ }+ })++ t.Run("should refuse updating the organization from a sub-org token and keep its name", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)++ // Action+ res, err := sub.Admin.API.UpdateOrganizationWithResponse(t.Context(), sub.ID.String(),+ api.UpdateOrganizationJSONRequestBody{Name: new("renamed")})++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Child organization cannot do this operation")+ require.Equal(t, []string{sub.Name}, subOrgNames(t, tn))+ })++ t.Run("should refuse reading the external group mapping from a sub-org token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sub := fixture.NewSubOrg(t, tn)++ // Action+ res, err := sub.Admin.API.ListExternalGroupOrgRoleMappingsWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "Child organization cannot do this operation")+ })+}diff --git a/tests/suites/user/delete_test.go b/tests/suites/user/delete_test.gonew file mode 100644index 0000000000..ffff360b31--- /dev/null+++ b/tests/suites/user/delete_test.go@@ -0,0 +1,39 @@+package user_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestUser_Delete(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should delete the account, mail a confirmation, and refuse its sessions", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ phone := signIn(t, tn, alice.Email)++ // Action+ res, err := alice.API.DeleteUserWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "deleting: %s", apierr.Body(res.Body))+ tn.Mail(t).Expect(t, alice.Email, smtp.Subject("Your Infisical account has been deleted"))+ requireSessionGone(t, alice.API)+ requireSessionGone(t, phone.API)+ again, _ := login(t, tn, alice.Email, harness.UserPassword)+ require.Equal(t, http.StatusBadRequest, again.StatusCode())+ require.Nil(t, fixture.MembershipOf(t, tn, alice.Email))+ })+}diff --git a/tests/suites/user/emailchange_test.go b/tests/suites/user/emailchange_test.gonew file mode 100644index 0000000000..7ace4d60e6--- /dev/null+++ b/tests/suites/user/emailchange_test.go@@ -0,0 +1,85 @@+package user_test++import (+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func TestEmailChange(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should change the email after both codes, revoke sessions, and log in with the new address", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ next := tn.Email("renamed-" + id.Short())+ confirmed := confirmCurrentEmail(t, tn, alice, next)+ require.Equalf(t, http.StatusOK, confirmed.StatusCode(), "confirming: %s", apierr.Body(confirmed.Body))+ newCode := code(t, tn.Mail(t).Expect(t, next, smtp.Subject("Infisical email change verification")))++ // Action+ res, err := alice.API.UpdateUserEmailWithResponse(t.Context(), api.UpdateUserEmailJSONRequestBody{+ NewEmail: openapi_types.Email(next),+ OtpCode: newCode,+ })++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "changing the email: %s", apierr.Body(res.Body))+ require.Equal(t, strings.ToLower(next), *res.JSON200.User.Email)+ requireSessionGone(t, alice.API)+ renamed, _ := login(t, tn, next, harness.UserPassword)+ require.Equal(t, http.StatusOK, renamed.StatusCode())+ old, _ := login(t, tn, alice.Email, harness.UserPassword)+ require.Equal(t, http.StatusBadRequest, old.StatusCode())+ })++ t.Run("should refuse a taken address and mail its owner rather than revealing it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ bob := tn.NewUser(t)++ // Action+ res := confirmCurrentEmail(t, tn, alice, bob.Email)++ // Assert+ require.Equalf(t, http.StatusOK, res.StatusCode(), "confirming: %s", apierr.Body(res.Body))+ require.True(t, res.JSON200.Success)+ require.Equal(t, strings.ToLower(bob.Email), res.JSON200.NewEmail)+ tn.Mail(t).Expect(t, bob.Email, smtp.Subject("Email Change Request for Your Infisical Account"))+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool {+ return e.Recipient == strings.ToLower(bob.Email) && strings.Contains(e.Message.Subject, "email change verification")+ })+ me, err := alice.API.GetCurrentUserWithResponse(t.Context())+ require.NoError(t, err)+ require.Equal(t, strings.ToLower(alice.Email), *me.JSON200.User.Email)+ })+}++// confirmCurrentEmail asks to move p to next and proves control of the current address+// with the code mailed there.+func confirmCurrentEmail(t *testing.T, tn *harness.Tenant, p *harness.Principal, next string) *api.VerifyCurrentEmailOtpResponse {+ t.Helper()+ requested, err := p.API.RequestEmailChangeOtpWithResponse(t.Context(), api.RequestEmailChangeOtpJSONRequestBody{NewEmail: openapi_types.Email(next)})+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, requested.StatusCode(), "requesting the change: %s", apierr.Body(requested.Body))+ current := code(t, tn.Mail(t).Expect(t, p.Email, smtp.Subject("Confirm your Infisical email change")))+ res, err := p.API.VerifyCurrentEmailOtpWithResponse(t.Context(), api.VerifyCurrentEmailOtpJSONRequestBody{OtpCode: current})+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/user/helpers_test.go b/tests/suites/user/helpers_test.gonew file mode 100644index 0000000000..d83fb0b527--- /dev/null+++ b/tests/suites/user/helpers_test.go@@ -0,0 +1,182 @@+package user_test++import (+ "bytes"+ "context"+ "crypto/rand"+ "encoding/json"+ "fmt"+ "net/http"+ "regexp"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/harness/infisical"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/mail"+ "github.com/stretchr/testify/require"+)++// newIP is a source address no other caller uses: its own rate-limit bucket, and to+// Infisical a device it has not seen.+func newIP() string {+ b := make([]byte, 3)+ _, _ = rand.Read(b)+ return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])+}++// device is a browser on its own address with no credentials.+func device(t *testing.T, tn *harness.Tenant, ip string, opts ...api.ClientOption) *api.ClientWithResponses {+ t.Helper()+ return tn.Anonymous(t, append([]api.ClientOption{infisical.ForwardedFor(ip)}, opts...)...)+}++// as is a client carrying a token from a given address.+func as(t *testing.T, tn *harness.Tenant, token, ip string) *api.ClientWithResponses {+ t.Helper()+ return tn.Client(t, token, infisical.ForwardedFor(ip))+}++func withCookies(cookies ...*http.Cookie) api.RequestEditorFn {+ return func(_ context.Context, req *http.Request) error {+ for _, c := range cookies {+ if c != nil {+ req.AddCookie(c)+ }+ }+ return nil+ }+}++func cookieNamed(res *http.Response, name string) *http.Cookie {+ for _, c := range res.Cookies() {+ if c.Name == name {+ return c+ }+ }+ return nil+}++// session is one browser's login: the access token and the refresh cookie, from one+// address, so the server sees one session row for it.+type session struct {+ IP string+ Token string+ JID *http.Cookie+ API *api.ClientWithResponses+}++// login is the password step of a login, from a fresh address.+func login(t *testing.T, tn *harness.Tenant, email, password string) (*api.LoginV3Response, string) {+ t.Helper()+ ip := newIP()+ res, err := device(t, tn, ip).LoginV3WithResponse(t.Context(), api.LoginV3JSONRequestBody{+ Email: email,+ Password: password,+ })+ require.NoError(t, err)+ return res, ip+}++// loggedIn logs in with the harness password and returns the org-less session.+func loggedIn(t *testing.T, tn *harness.Tenant, email string) session {+ t.Helper()+ res, ip := login(t, tn, email, harness.UserPassword)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "logging in as %s: %s", email, apierr.Body(res.Body))+ return session{+ IP: ip,+ Token: res.JSON200.AccessToken,+ JID: cookieNamed(res.HTTPResponse, "jid"),+ API: as(t, tn, res.JSON200.AccessToken, ip),+ }+}++// selectOrg binds a session to an organization.+func selectOrg(t *testing.T, tn *harness.Tenant, s session, orgID string) *api.SelectOrganizationV3Response {+ t.Helper()+ res, err := s.API.SelectOrganizationV3WithResponse(t.Context(), api.SelectOrganizationV3JSONRequestBody{OrganizationId: orgID})+ require.NoError(t, err)+ return res+}++// signIn is a full password login into the tenant's organization from a fresh address.+func signIn(t *testing.T, tn *harness.Tenant, email string) session {+ t.Helper()+ s := loggedIn(t, tn, email)+ res := selectOrg(t, tn, s, tn.OrgID.String())+ require.Equalf(t, http.StatusOK, res.StatusCode(), "selecting the organization: %s", apierr.Body(res.Body))+ require.False(t, res.JSON200.IsMfaEnabled, "the login asked for MFA")+ return session{+ IP: s.IP,+ Token: res.JSON200.Token,+ JID: cookieNamed(res.HTTPResponse, "jid"),+ API: as(t, tn, res.JSON200.Token, s.IP),+ }+}++// orgReachable reports the status of a read every member may make.+func orgStatus(t *testing.T, c *api.ClientWithResponses, orgID string) int {+ t.Helper()+ res, err := c.GetOrganizationByIdWithResponse(t.Context(), orgID)+ require.NoError(t, err)+ return res.StatusCode()+}++func meStatus(t *testing.T, c *api.ClientWithResponses) int {+ t.Helper()+ res, err := c.GetCurrentUserWithResponse(t.Context())+ require.NoError(t, err)+ return res.StatusCode()+}++// refresh exchanges a refresh cookie for an access token.+func refresh(t *testing.T, tn *harness.Tenant, ip string, jid *http.Cookie) *api.RefreshAuthTokenResponse {+ t.Helper()+ res, err := device(t, tn, ip).RefreshAuthTokenWithResponse(t.Context(), withCookies(jid))+ require.NoError(t, err)+ return res+}++// addresses are dropped before looking for a code: a tenant's mail domain is a hex nonce,+// which can hold a run of six digits that mail.Code would take for the code.+var addresses = regexp.MustCompile(`[^\s<>"'()]*@[^\s<>"'()]*`)++func code(t *testing.T, msg smtp.Message) string {+ t.Helper()+ msg.Body = addresses.ReplaceAllString(msg.Body, " ")+ c, err := mail.Code(msg, 6)+ require.NoError(t, err)+ return c+}++func otherCode(c string) string {+ if c == "000000" {+ return "111111"+ }+ return "000000"+}++// postJSON marshals a union body, which the typed request body cannot carry.+func postJSON(t *testing.T, v any) *bytes.Reader {+ t.Helper()+ raw, err := json.Marshal(v)+ require.NoError(t, err)+ return bytes.NewReader(raw)+}++func errorName(body []byte) string {+ var e struct {+ Error string `json:"error"`+ }+ _ = json.Unmarshal(body, &e)+ return e.Error+}++func updateOrg(t *testing.T, tn *harness.Tenant, body api.UpdateOrganizationJSONRequestBody) *api.UpdateOrganizationResponse {+ t.Helper()+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(), body)+ require.NoError(t, err)+ return res+}diff --git a/tests/suites/user/login_test.go b/tests/suites/user/login_test.gonew file mode 100644index 0000000000..482694fe47--- /dev/null+++ b/tests/suites/user/login_test.go@@ -0,0 +1,217 @@+package user_test++import (+ "context"+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++func TestLogin_Password(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse unknown email and wrong password with the same invalid credentials answer", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)++ // Action+ unknown, _ := login(t, tn, tn.Email("nobody-"+id.Short()), harness.UserPassword)+ wrong, _ := login(t, tn, alice.Email, "WrongPassword7!xyz")++ // Assert+ require.Equal(t, http.StatusBadRequest, unknown.StatusCode())+ require.Equal(t, unknown.StatusCode(), wrong.StatusCode())+ require.Equal(t, "Invalid credentials", apierr.Message(unknown.Body))+ require.Equal(t, apierr.Message(unknown.Body), apierr.Message(wrong.Body))+ require.Nil(t, cookieNamed(wrong.HTTPResponse, "jid"))+ again, _ := login(t, tn, alice.Email, harness.UserPassword)+ require.Equal(t, http.StatusOK, again.StatusCode())+ })++ t.Run("should return an org-less token that every org route refuses until an org is selected", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)++ // Action+ s := loggedIn(t, tn, alice.Email)++ // Assert+ require.Equal(t, http.StatusUnauthorized, orgStatus(t, s.API, tn.OrgID.String()))+ require.Equal(t, http.StatusUnauthorized, meStatus(t, s.API))+ selected := selectOrg(t, tn, s, tn.OrgID.String())+ require.Equalf(t, http.StatusOK, selected.StatusCode(), "selecting: %s", apierr.Body(selected.Body))+ require.Equal(t, http.StatusOK, orgStatus(t, as(t, tn, selected.JSON200.Token, s.IP), tn.OrgID.String()))+ })++ t.Run("should mail a new-device notice for a new IP and user agent, and not for a repeat", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ first := signIn(t, tn, alice.Email)++ // Action+ signInFrom(t, tn, alice.Email, first.IP)++ // Assert+ tn.Mail(t).Expect(t, alice.Email, smtp.Subject("new device"), bodyContains(first.IP))+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool {+ return e.Recipient == strings.ToLower(alice.Email) &&+ strings.Contains(e.Message.Subject, "new device") && strings.Contains(e.Message.Body, first.IP)+ })+ })+}++func TestSelectOrganization(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse an org the user is not a member of", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ other := h.NewTenant(t)+ alice := tn.NewUser(t)+ s := loggedIn(t, tn, alice.Email)++ // Action+ res := selectOrg(t, tn, s, other.OrgID.String())++ // Assert+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Equal(t, "User does not have access to the organization with ID "+other.OrgID.String(), apierr.Message(res.Body))+ require.Nil(t, fixture.MembershipOf(t, other, alice.Email))+ })++ t.Run("should refuse an org whose membership is deactivated", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ deactivate(t, tn, alice.Email)+ s := loggedIn(t, tn, alice.Email)++ // Action+ res := selectOrg(t, tn, s, tn.OrgID.String())++ // Assert+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Equal(t, "User organization membership is inactive", apierr.Message(res.Body))+ require.Nil(t, cookieNamed(res.HTTPResponse, "jid"))+ })++ t.Run("should accept an invited membership and mark it accepted", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ other := h.NewTenant(t)+ alice := tn.NewUser(t)+ invite(t, other, alice.Email)+ require.Equal(t, "invited", fixture.MembershipOf(t, other, alice.Email).Status)+ s := loggedIn(t, tn, alice.Email)++ // Action+ res := selectOrg(t, tn, s, other.OrgID.String())++ // Assert+ require.Equalf(t, http.StatusOK, res.StatusCode(), "selecting: %s", apierr.Body(res.Body))+ require.Equal(t, "accepted", fixture.MembershipOf(t, other, alice.Email).Status)+ require.Equal(t, http.StatusOK, orgStatus(t, as(t, tn, res.JSON200.Token, s.IP), other.OrgID.String()))+ })+}++func TestLogin_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a login without a user agent with a 4xx", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)++ // Action+ res, err := device(t, tn, newIP()).LoginV3WithResponse(t.Context(), api.LoginV3JSONRequestBody{+ Email: alice.Email,+ Password: harness.UserPassword,+ }, func(_ context.Context, req *http.Request) error {+ req.Header.Set("User-Agent", "")+ return nil+ })++ // Assert+ require.NoError(t, err)+ require.GreaterOrEqualf(t, res.StatusCode(), 400, "body: %s", apierr.Body(res.Body))+ require.Lessf(t, res.StatusCode(), 500, "body: %s", apierr.Body(res.Body))+ require.Nil(t, cookieNamed(res.HTTPResponse, "jid"))+ })+}++func bodyContains(s string) smtp.Filter {+ return func(m smtp.Message) bool { return strings.Contains(m.Body, s) }+}++// signInFrom is a full password login into the tenant's organization from a given+// address.+func signInFrom(t *testing.T, tn *harness.Tenant, email, ip string) session {+ t.Helper()+ res, err := device(t, tn, ip).LoginV3WithResponse(t.Context(), api.LoginV3JSONRequestBody{+ Email: email,+ Password: harness.UserPassword,+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "logging in: %s", apierr.Body(res.Body))+ s := session{IP: ip, Token: res.JSON200.AccessToken, API: as(t, tn, res.JSON200.AccessToken, ip)}+ selected := selectOrg(t, tn, s, tn.OrgID.String())+ require.Equalf(t, http.StatusOK, selected.StatusCode(), "selecting the organization: %s", apierr.Body(selected.Body))+ return session{+ IP: ip,+ Token: selected.JSON200.Token,+ JID: cookieNamed(selected.HTTPResponse, "jid"),+ API: as(t, tn, selected.JSON200.Token, ip),+ }+}++// invite adds an existing account to another tenant's organization as a member, leaving+// the membership invited until the user selects that organization.+func invite(t *testing.T, tn *harness.Tenant, email string) {+ t.Helper()+ res, err := tn.Admin.API.InviteUsersToOrganizationWithResponse(t.Context(), api.InviteUsersToOrganizationJSONRequestBody{+ InviteeEmails: []openapi_types.Email{openapi_types.Email(email)},+ OrganizationId: tn.OrgID.String(),+ OrganizationRoleSlug: new("member"),+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "inviting %s: %s", email, apierr.Body(res.Body))+}++func deactivate(t *testing.T, tn *harness.Tenant, email string) {+ t.Helper()+ m := fixture.MembershipOf(t, tn, email)+ require.NotNil(t, m)+ res, err := tn.Admin.API.UpdateOrgMembershipWithResponse(t.Context(), tn.OrgID.String(), m.ID.String(),+ api.UpdateOrgMembershipJSONRequestBody{IsActive: new(false)})+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "deactivating %s: %s", email, apierr.Body(res.Body))+}diff --git a/tests/suites/user/main_test.go b/tests/suites/user/main_test.gonew file mode 100644index 0000000000..d1de2d2368--- /dev/null+++ b/tests/suites/user/main_test.go@@ -0,0 +1,9 @@+package user_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/harness"+)++func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }diff --git a/tests/suites/user/mfa_test.go b/tests/suites/user/mfa_test.gonew file mode 100644index 0000000000..4ace4ca4bc--- /dev/null+++ b/tests/suites/user/mfa_test.go@@ -0,0 +1,466 @@+package user_test++import (+ "crypto/hmac"+ "crypto/sha1"+ "encoding/base32"+ "encoding/binary"+ "encoding/json"+ "fmt"+ "net/http"+ "net/url"+ "strings"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/harness/infisical"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/mail"+ "github.com/stretchr/testify/require"+)++const mfaSubject = "Infisical MFA code"++func TestMFA_Login(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should return an MFA token instead of a session when the org enforces MFA, and mail a code", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ enforceMFA(t, tn, api.UpdateOrganizationJSONBodySelectedMfaMethodEmail)+ s := loggedIn(t, tn, alice.Email)++ // Action+ res := selectOrg(t, tn, s, tn.OrgID.String())++ // Assert+ require.Equalf(t, http.StatusOK, res.StatusCode(), "selecting: %s", apierr.Body(res.Body))+ require.True(t, res.JSON200.IsMfaEnabled)+ require.Equal(t, "email", *res.JSON200.MfaMethod)+ require.Equal(t, "mfaToken", claims(t, res.JSON200.Token)["authTokenType"])+ require.Nil(t, cookieNamed(res.HTTPResponse, "jid"))+ require.Len(t, code(t, tn.Mail(t).Expect(t, alice.Email, smtp.Subject(mfaSubject))), 6)+ })++ t.Run("should start a session with the mailed code", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ enforceMFA(t, tn, api.UpdateOrganizationJSONBodySelectedMfaMethodEmail)+ c := challenge(t, tn, alice.Email)+ mailed := code(t, tn.Mail(t).Expect(t, alice.Email, smtp.Subject(mfaSubject)))++ // Action+ res, err := c.API.VerifyMfaWithResponse(t.Context(), api.VerifyMfaJSONRequestBody{MfaToken: mailed})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "verifying: %s", apierr.Body(res.Body))+ require.NotNil(t, cookieNamed(res.HTTPResponse, "jid"))+ require.Equal(t, true, claims(t, res.JSON200.Token)["isMfaVerified"])+ require.Equal(t, http.StatusOK, orgStatus(t, as(t, tn, res.JSON200.Token, c.IP), tn.OrgID.String()))+ })++ t.Run("should refuse the MFA token as a bearer on ordinary routes", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ enforceMFA(t, tn, api.UpdateOrganizationJSONBodySelectedMfaMethodEmail)+ c := challenge(t, tn, alice.Email)++ // Action+ res, err := c.API.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusUnauthorized, res.StatusCode())+ require.Equal(t, http.StatusUnauthorized, meStatus(t, c.API))+ })++ t.Run("should lock the account after repeated wrong codes and mail an unlock link", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ enforceMFA(t, tn, api.UpdateOrganizationJSONBodySelectedMfaMethodEmail)+ c := challenge(t, tn, alice.Email)+ wrong := otherCode(code(t, tn.Mail(t).Expect(t, alice.Email, smtp.Subject(mfaSubject))))++ // Action+ for range 20 {+ _, err := c.API.VerifyMfaWithResponse(t.Context(), api.VerifyMfaJSONRequestBody{MfaToken: wrong})+ require.NoError(t, err)+ }++ // Assert+ unlock := tn.Mail(t).Expect(t, alice.Email, smtp.Subject("Unlock your Infisical account"))+ link, err := mail.Link(unlock, "token")+ require.NoError(t, err)+ require.Equal(t, "/api/v1/user/"+alice.ID.String()+"/unlock", link.Path)+ locked := selectOrg(t, tn, loggedIn(t, tn, alice.Email), tn.OrgID.String())+ require.Equal(t, http.StatusUnauthorized, locked.StatusCode())+ require.Equal(t, "Account is locked", apierr.Message(locked.Body))+ unlocked, err := device(t, tn, newIP(), infisical.NoRedirects()).UnlockUserWithResponse(t.Context(), alice.ID.String(),+ &api.UnlockUserParams{Token: link.Query().Get("token")})+ require.NoError(t, err)+ require.Equal(t, http.StatusFound, unlocked.StatusCode())+ again := selectOrg(t, tn, loggedIn(t, tn, alice.Email), tn.OrgID.String())+ require.Equalf(t, http.StatusOK, again.StatusCode(), "selecting after unlocking: %s", apierr.Body(again.Body))+ require.True(t, again.JSON200.IsMfaEnabled)+ })++ t.Run("should refuse enforcing MFA when the plan does not include it, and keep it off", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.EnforceMFA)))+ alice := tn.NewUser(t)++ // Action+ res := updateOrg(t, tn, api.UpdateOrganizationJSONRequestBody{EnforceMfa: new(true)})++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, apierr.Message(res.Body), "Upgrade plan to enforce/un-enforce MFA")+ org, err := tn.Admin.API.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ require.False(t, *org.JSON200.Organization.EnforceMfa)+ signIn(t, tn, alice.Email)+ })+}++func TestMFA_StepUp(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should require an MFA session to change MFA settings and accept after the mailed code", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ enableEmailMFA(t, tn, alice)++ // Action+ refused := deactivateMFA(t, alice.API, "")+ sessionID := stepUpSession(t, refused.StatusCode(), refused.Body)+ verified := verifyStepUp(t, tn, alice, sessionID)+ accepted := deactivateMFA(t, alice.API, sessionID)++ // Assert+ require.Equalf(t, http.StatusOK, verified.StatusCode(), "verifying: %s", apierr.Body(verified.Body))+ require.Equalf(t, http.StatusOK, accepted.StatusCode(), "deactivating: %s", apierr.Body(accepted.Body))+ require.False(t, mfaEnabled(t, alice.API))+ })++ t.Run("should refuse another user's MFA session", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ bob := tn.NewUser(t)+ enableEmailMFA(t, tn, alice)+ refused := deactivateMFA(t, alice.API, "")+ sessionID := stepUpSession(t, refused.StatusCode(), refused.Body)+ mailed := code(t, tn.Mail(t).Expect(t, alice.Email, smtp.Subject(mfaSubject)))++ // Action+ res, err := bob.API.VerifyMfaSessionWithResponse(t.Context(), sessionID, api.VerifyMfaSessionJSONRequestBody{+ MfaToken: mailed,+ MfaMethod: api.VerifyMfaSessionJSONBodyMfaMethodEmail,+ })++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Equal(t, "MFA session does not belong to current user", apierr.Message(res.Body))+ status, err := alice.API.GetMfaSessionStatusWithResponse(t.Context(), sessionID)+ require.NoError(t, err)+ require.Equal(t, "PENDING", string(status.JSON200.Status))+ require.True(t, mfaEnabled(t, alice.API))+ })++ t.Run("should refuse deactivating MFA while an org enforces it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ enableEmailMFA(t, tn, alice)+ enforceMFA(t, tn, api.UpdateOrganizationJSONBodySelectedMfaMethodEmail)++ // Action+ res := deactivateMFA(t, alice.API, "")++ // Assert+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Equal(t, "Two-factor authentication is required by your organization and cannot be disabled", apierr.Message(res.Body))+ require.True(t, mfaEnabled(t, alice.API))+ })++ t.Run("should accept a recovery code once, mail a notice, and refuse it a second time", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ recovery := enableEmailMFA(t, tn, alice)[0]+ first := challenge(t, tn, alice.Email)++ // Action+ used, err := first.API.VerifyMfaRecoveryCodeWithResponse(t.Context(), api.VerifyMfaRecoveryCodeJSONRequestBody{RecoveryCode: recovery})+ require.NoError(t, err)+ replayed, err := challenge(t, tn, alice.Email).API.VerifyMfaRecoveryCodeWithResponse(t.Context(),+ api.VerifyMfaRecoveryCodeJSONRequestBody{RecoveryCode: recovery})+ require.NoError(t, err)++ // Assert+ require.Equalf(t, http.StatusOK, used.StatusCode(), "using the recovery code: %s", apierr.Body(used.Body))+ require.Equal(t, http.StatusOK, orgStatus(t, as(t, tn, used.JSON200.Token, first.IP), tn.OrgID.String()))+ tn.Mail(t).Expect(t, alice.Email, smtp.Subject("A recovery code was used"))+ require.Equal(t, http.StatusForbidden, replayed.StatusCode())+ require.Equal(t, "Invalid recovery code", apierr.Message(replayed.Body))+ require.Nil(t, cookieNamed(replayed.HTTPResponse, "jid"))+ })+}++func TestMFA_TOTP(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should accept a valid TOTP code after registration and refuse a wrong one", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ registered, err := alice.API.RegisterUserTotpWithResponse(t.Context())+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, registered.StatusCode(), "registering: %s", apierr.Body(registered.Body))+ secret := totpSecret(t, registered.JSON200.OtpUrl)++ // Action+ wrong, err := alice.API.VerifyUserTotpConfigWithResponse(t.Context(),+ api.VerifyUserTotpConfigJSONRequestBody{Totp: otherCode(totp(secret, time.Now()))})+ require.NoError(t, err)+ valid, err := alice.API.VerifyUserTotpConfigWithResponse(t.Context(),+ api.VerifyUserTotpConfigJSONRequestBody{Totp: totp(secret, time.Now())})+ require.NoError(t, err)++ // Assert+ require.Equal(t, http.StatusBadRequest, wrong.StatusCode())+ require.Equal(t, "Invalid TOTP token", apierr.Message(wrong.Body))+ require.Equalf(t, http.StatusOK, valid.StatusCode(), "verifying: %s", apierr.Body(valid.Body))+ cfg, err := alice.API.GetUserTotpConfigWithResponse(t.Context())+ require.NoError(t, err)+ require.True(t, cfg.JSON200.IsVerified)+ })++ t.Run("should start a session with a TOTP code when the org enforces TOTP, and refuse a wrong one", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ secret := registerTOTP(t, alice)+ enforceMFA(t, tn, api.UpdateOrganizationJSONBodySelectedMfaMethodTotp)+ c := challenge(t, tn, alice.Email)+ totpMethod := new(api.VerifyMfaJSONBodyMfaMethodTotp)++ // Action+ wrong, err := c.API.VerifyMfaWithResponse(t.Context(), api.VerifyMfaJSONRequestBody{+ MfaToken: otherCode(totp(secret, time.Now())), MfaMethod: totpMethod,+ })+ require.NoError(t, err)+ valid, err := c.API.VerifyMfaWithResponse(t.Context(), api.VerifyMfaJSONRequestBody{+ MfaToken: totp(secret, time.Now()), MfaMethod: totpMethod,+ })+ require.NoError(t, err)++ // Assert+ require.Equal(t, http.StatusForbidden, wrong.StatusCode())+ require.Equal(t, "Invalid TOTP", apierr.Message(wrong.Body))+ require.Equalf(t, http.StatusOK, valid.StatusCode(), "verifying: %s", apierr.Body(valid.Body))+ require.Equal(t, http.StatusOK, orgStatus(t, as(t, tn, valid.JSON200.Token, c.IP), tn.OrgID.String()))+ })+}++func TestMFA_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a wrong mailed MFA code with a 4xx and start no session", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ enforceMFA(t, tn, api.UpdateOrganizationJSONBodySelectedMfaMethodEmail)+ c := challenge(t, tn, alice.Email)+ wrong := otherCode(code(t, tn.Mail(t).Expect(t, alice.Email, smtp.Subject(mfaSubject))))++ // Action+ res, err := c.API.VerifyMfaWithResponse(t.Context(), api.VerifyMfaJSONRequestBody{MfaToken: wrong})++ // Assert+ require.NoError(t, err)+ require.Nil(t, cookieNamed(res.HTTPResponse, "jid"))+ require4xx(t, res.StatusCode(), res.Body)+ })++ t.Run("should refuse an MFA route called with an ordinary session token with a 4xx", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)++ // Action+ res, err := alice.API.VerifyMfaWithResponse(t.Context(), api.VerifyMfaJSONRequestBody{MfaToken: "123456"})++ // Assert+ require.NoError(t, err)+ require.Nil(t, cookieNamed(res.HTTPResponse, "jid"))+ require4xx(t, res.StatusCode(), res.Body)+ })+}++func require4xx(t *testing.T, status int, body []byte) {+ t.Helper()+ require.GreaterOrEqualf(t, status, 400, "body: %s", apierr.Body(body))+ require.Lessf(t, status, 500, "body: %s", apierr.Body(body))+}++func enforceMFA(t *testing.T, tn *harness.Tenant, method api.UpdateOrganizationJSONBodySelectedMfaMethod) {+ t.Helper()+ res := updateOrg(t, tn, api.UpdateOrganizationJSONRequestBody{EnforceMfa: new(true), SelectedMfaMethod: &method})+ require.Equalf(t, http.StatusOK, res.StatusCode(), "enforcing MFA: %s", apierr.Body(res.Body))+}++// challenge logs in from a fresh address and selects the tenant's organization, which+// answers with an MFA token. The session's API carries that token.+func challenge(t *testing.T, tn *harness.Tenant, email string) session {+ t.Helper()+ s := loggedIn(t, tn, email)+ res := selectOrg(t, tn, s, tn.OrgID.String())+ require.Equalf(t, http.StatusOK, res.StatusCode(), "selecting: %s", apierr.Body(res.Body))+ require.True(t, res.JSON200.IsMfaEnabled, "the login was not challenged")+ return session{IP: s.IP, Token: res.JSON200.Token, API: as(t, tn, res.JSON200.Token, s.IP)}+}++// stepUpSession reads the MFA session a step-up refusal opened.+func stepUpSession(t *testing.T, status int, body []byte) string {+ t.Helper()+ require.Equalf(t, http.StatusBadRequest, status, "expected a step-up challenge: %s", apierr.Body(body))+ var e struct {+ Error string `json:"error"`+ Details struct {+ MfaSessionID string `json:"mfaSessionId"`+ } `json:"details"`+ }+ require.NoError(t, json.Unmarshal(body, &e))+ require.Equal(t, "SESSION_MFA_REQUIRED", e.Error)+ require.NotEmpty(t, e.Details.MfaSessionID)+ return e.Details.MfaSessionID+}++func verifyStepUp(t *testing.T, tn *harness.Tenant, p *harness.Principal, sessionID string) *api.VerifyMfaSessionResponse {+ t.Helper()+ mailed := code(t, tn.Mail(t).Expect(t, p.Email, smtp.Subject(mfaSubject)))+ res, err := p.API.VerifyMfaSessionWithResponse(t.Context(), sessionID, api.VerifyMfaSessionJSONRequestBody{+ MfaToken: mailed,+ MfaMethod: api.VerifyMfaSessionJSONBodyMfaMethodEmail,+ })+ require.NoError(t, err)+ return res+}++// enableEmailMFA turns on email MFA from personal settings, which needs a step-up with+// the mailed code, and returns the recovery codes it issued.+func enableEmailMFA(t *testing.T, tn *harness.Tenant, p *harness.Principal) []string {+ t.Helper()+ method := api.ActivateUserMfaJSONBodySelectedMfaMethodEmail+ refused, err := p.API.ActivateUserMfaWithResponse(t.Context(), api.ActivateUserMfaJSONRequestBody{SelectedMfaMethod: &method})+ require.NoError(t, err)+ sessionID := stepUpSession(t, refused.StatusCode(), refused.Body)+ verified := verifyStepUp(t, tn, p, sessionID)+ require.Equalf(t, http.StatusOK, verified.StatusCode(), "verifying the step-up: %s", apierr.Body(verified.Body))+ res, err := p.API.ActivateUserMfaWithResponse(t.Context(), api.ActivateUserMfaJSONRequestBody{+ SelectedMfaMethod: &method,+ MfaSessionId: &sessionID,+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "activating MFA: %s", apierr.Body(res.Body))+ require.NotEmpty(t, res.JSON200.RecoveryCodes)+ return res.JSON200.RecoveryCodes+}++func deactivateMFA(t *testing.T, c *api.ClientWithResponses, sessionID string) *api.DeactivateUserMfaResponse {+ t.Helper()+ body := map[string]string{}+ if sessionID != "" {+ body["mfaSessionId"] = sessionID+ }+ res, err := c.DeactivateUserMfaWithBodyWithResponse(t.Context(), "application/json", postJSON(t, body))+ require.NoError(t, err)+ return res+}++func mfaEnabled(t *testing.T, c *api.ClientWithResponses) bool {+ t.Helper()+ res, err := c.GetCurrentUserWithResponse(t.Context())+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "reading the user: %s", apierr.Body(res.Body))+ return res.JSON200.User.IsMfaEnabled != nil && *res.JSON200.User.IsMfaEnabled+}++// registerTOTP registers and verifies an authenticator for the user and returns its+// secret.+func registerTOTP(t *testing.T, p *harness.Principal) []byte {+ t.Helper()+ registered, err := p.API.RegisterUserTotpWithResponse(t.Context())+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, registered.StatusCode(), "registering: %s", apierr.Body(registered.Body))+ secret := totpSecret(t, registered.JSON200.OtpUrl)+ res, err := p.API.VerifyUserTotpConfigWithResponse(t.Context(), api.VerifyUserTotpConfigJSONRequestBody{Totp: totp(secret, time.Now())})+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "verifying the authenticator: %s", apierr.Body(res.Body))+ return secret+}++func totpSecret(t *testing.T, otpURL string) []byte {+ t.Helper()+ u, err := url.Parse(otpURL)+ require.NoError(t, err)+ raw := strings.ToUpper(u.Query().Get("secret"))+ secret, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(raw)+ require.NoError(t, err)+ return secret+}++// totp is RFC 6238 with the authenticator defaults: HMAC-SHA1, 30 second steps, six+// digits.+func totp(secret []byte, at time.Time) string {+ var counter [8]byte+ binary.BigEndian.PutUint64(counter[:], uint64(at.Unix()/30))+ mac := hmac.New(sha1.New, secret)+ mac.Write(counter[:])+ sum := mac.Sum(nil)+ offset := sum[len(sum)-1] & 0x0f+ n := binary.BigEndian.Uint32(sum[offset:offset+4]) & 0x7fffffff+ return fmt.Sprintf("%06d", n%1_000_000)+}diff --git a/tests/suites/user/oauth_test.go b/tests/suites/user/oauth_test.gonew file mode 100644index 0000000000..e4a57ecbdb--- /dev/null+++ b/tests/suites/user/oauth_test.go@@ -0,0 +1,413 @@+package user_test++import (+ "context"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ githubfake "github.com/Infisical/infisical/tests/fakes/github"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/stretchr/testify/require"+)++func TestOAuth_Signup(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should send a first-time user with a provider-verified email to select-organization with a session, and create the account", func(t *testing.T) {+ t.Parallel()+ for _, kind := range providers {+ t.Run(string(kind), func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ p := newPerson(tn, true)++ // Action+ res := oauthLogin(t, tn, kind, p)++ // Assert+ loc := res.redirect(t)+ require.Equal(t, "/login/select-organization", loc.Path)+ require.Equal(t, "true", loc.Query().Get("signup_completed"))+ me := accountOf(t, tn, res).JSON200.User+ require.Equal(t, strings.ToLower(p.Email), *me.Email)+ require.Contains(t, *me.AuthMethods, string(kind))+ })+ }+ })++ t.Run("should send a first-time user with an unverified email to SSO signup and mail a code", func(t *testing.T) {+ t.Parallel()+ for _, kind := range providers {+ t.Run(string(kind), func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ p := newPerson(tn, false)++ // Action+ res := oauthLogin(t, tn, kind, p)++ // Assert+ loc := res.redirect(t)+ require.Equal(t, "/signup/sso", loc.Path)+ signup := claims(t, loc.Query().Get("token"))+ require.Equal(t, "signupToken", signup["authTokenType"])+ require.Equal(t, strings.ToLower(p.Email), signup["email"])+ require.Equal(t, string(kind), signup["authMethod"])+ require.Nil(t, cookieNamed(res.HTTP, "jid"))+ require.Len(t, sso.VerificationCode(t, tn, p.Email), 6)+ })+ }+ })++ t.Run("should send a first-time Google user with an unverified email to SSO signup", func(t *testing.T) {+ t.Parallel()+ skipUntilGoogleFakeAttributesQueryToken(t)++ // Setup+ tn := h.NewTenant(t)+ p := newPerson(tn, false)++ // Action+ res := oauthLogin(t, tn, viaGoogle, p)++ // Assert+ require.Equal(t, "/signup/sso", res.redirect(t).Path)+ require.Nil(t, cookieNamed(res.HTTP, "jid"))+ })++ t.Run("should complete signup with the mailed code and refuse a wrong code", func(t *testing.T) {+ t.Parallel()+ for _, kind := range providers {+ t.Run(string(kind), func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ p := newPerson(tn, false)+ first := oauthLogin(t, tn, kind, p)+ require.Equal(t, "/signup/sso", first.redirect(t).Path)+ mailed := sso.VerificationCode(t, tn, p.Email)++ // Action+ wrong := sso.CompleteSignup(t, tn, first.HTTP, otherCode(mailed))+ right := sso.CompleteSignup(t, tn, first.HTTP, mailed)++ // Assert+ require.Equal(t, http.StatusBadRequest, wrong.StatusCode())+ require.Equal(t, "Invalid token", apierr.Message(wrong.Body))+ require.Equalf(t, http.StatusOK, right.StatusCode(), "completing: %s", apierr.Body(right.Body))+ again := oauthLogin(t, tn, kind, p)+ require.Equal(t, "/login/select-organization", again.redirect(t).Path)+ require.Equal(t, strings.ToLower(p.Email), *accountOf(t, tn, again).JSON200.User.Email)+ })+ }+ })++ t.Run("should prefer GitHub's primary verified email, then any verified email", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ secondary, primary := tn.Email("x-"+id.Short()), tn.Email("x-"+id.Short())+ unverifiedPrimary, verified := tn.Email("x-"+id.Short()), tn.Email("x-"+id.Short())++ // Action+ withPrimary := startOAuth(t, tn, viaGitHub).finish(t, viaGitHub, consentGitHub(t, tn, newAccountID(),+ githubfake.Email{Email: secondary, Verified: true},+ githubfake.Email{Email: primary, Primary: true, Verified: true},+ ))+ withoutPrimary := startOAuth(t, tn, viaGitHub).finish(t, viaGitHub, consentGitHub(t, tn, newAccountID(),+ githubfake.Email{Email: unverifiedPrimary, Primary: true},+ githubfake.Email{Email: verified, Verified: true},+ ))++ // Assert+ require.Equal(t, strings.ToLower(primary), *accountOf(t, tn, withPrimary).JSON200.User.Email)+ require.Equal(t, strings.ToLower(verified), *accountOf(t, tn, withoutPrimary).JSON200.User.Email)+ })+}++func TestOAuth_ExistingAccount(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should link a returning provider login to the existing password account when the provider verified the email", func(t *testing.T) {+ t.Parallel()+ for _, kind := range providers {+ t.Run(string(kind), func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ p := newPerson(tn, true)+ p.Email = alice.Email++ // Action+ res := oauthLogin(t, tn, kind, p)++ // Assert+ require.Equal(t, "/login/select-organization", res.redirect(t).Path)+ me := accountOf(t, tn, res).JSON200.User+ require.Equal(t, alice.ID, me.Id)+ require.Contains(t, *me.AuthMethods, "email")+ require.Contains(t, *me.AuthMethods, string(kind))+ })+ }+ })++ t.Run("should refuse to link or modify an existing account from an unverified provider email", func(t *testing.T) {+ t.Parallel()+ for _, kind := range providers {+ t.Run(string(kind), func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ p := newPerson(tn, false)+ p.Email = alice.Email++ // Action+ res := oauthLogin(t, tn, kind, p)++ // Assert+ require.Equal(t, "/signup/sso", res.redirect(t).Path)+ require.Nil(t, cookieNamed(res.HTTP, "jid"))+ me, err := alice.API.GetCurrentUserWithResponse(t.Context())+ require.NoError(t, err)+ require.Equal(t, []string{"email"}, *me.JSON200.User.AuthMethods)+ require.Equal(t, alice.Name, *me.JSON200.User.FirstName)+ })+ }+ })++ t.Run("should rename the account when the provider's email changes", func(t *testing.T) {+ t.Parallel()+ for _, kind := range providers {+ t.Run(string(kind), func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ p := newPerson(tn, true)+ before := accountOf(t, tn, oauthLogin(t, tn, kind, p)).JSON200.User+ p.Email = tn.Email("renamed-" + id.Short())++ // Action+ res := oauthLogin(t, tn, kind, p)++ // Assert+ require.Equal(t, "/login/select-organization", res.redirect(t).Path)+ after := accountOf(t, tn, res).JSON200.User+ require.Equal(t, before.Id, after.Id)+ require.Equal(t, strings.ToLower(p.Email), *after.Email)+ require.Equal(t, strings.ToLower(p.Email), after.Username)+ })+ }+ })++ t.Run("should refuse to rename the account to an email that belongs to another account", func(t *testing.T) {+ t.Parallel()+ for _, kind := range providers {+ t.Run(string(kind), func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ bob := tn.NewUser(t)+ p := newPerson(tn, true)+ original := p.Email+ before := accountOf(t, tn, oauthLogin(t, tn, kind, p)).JSON200.User+ p.Email = bob.Email++ // Action+ res := oauthLogin(t, tn, kind, p)++ // Assert+ require.Equalf(t, http.StatusBadRequest, res.Status, "body: %s", apierr.Body(res.Body))+ require.Contains(t, apierr.Message(res.Body), "already in use by another Infisical user")+ require.Nil(t, cookieNamed(res.HTTP, "jid"))+ p.Email = original+ after := accountOf(t, tn, oauthLogin(t, tn, kind, p)).JSON200.User+ require.Equal(t, before.Id, after.Id)+ require.Equal(t, strings.ToLower(original), *after.Email)+ me, err := bob.API.GetCurrentUserWithResponse(t.Context())+ require.NoError(t, err)+ require.Equal(t, []string{"email"}, *me.JSON200.User.AuthMethods)+ })+ }+ })+}++func TestOAuth_Callback(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a callback with a forged state, and create no account", func(t *testing.T) {+ t.Parallel()+ for _, kind := range providers {+ t.Run(string(kind), func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ p := newPerson(tn, true)+ b := startOAuth(t, tn, kind)+ cp := consent(t, tn, kind, p)++ // Action+ res, err := b.callback(t.Context(), kind, cp.Code, "forged-"+id.Short(), b.cookies...)++ // Assert+ require.NoError(t, err)+ requireNoSession(t, res)+ require.False(t, cp.State(t).Redeemed, "Infisical redeemed a code that came back with a forged state")+ require.Equal(t, "true", oauthLogin(t, tn, kind, p).redirect(t).Query().Get("signup_completed"))+ })+ }+ })++ t.Run("should refuse a callback without the redirect's session cookie, and create no account", func(t *testing.T) {+ t.Parallel()+ for _, kind := range providers {+ t.Run(string(kind), func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ p := newPerson(tn, true)+ b := startOAuth(t, tn, kind)+ cp := consent(t, tn, kind, p)++ // Action+ res, err := b.callback(t.Context(), kind, cp.Code, b.state)++ // Assert+ require.NoError(t, err)+ requireNoSession(t, res)+ require.False(t, cp.State(t).Redeemed, "Infisical redeemed a code without the browser's session")+ require.Equal(t, "true", oauthLogin(t, tn, kind, p).redirect(t).Query().Get("signup_completed"))+ })+ }+ })++ t.Run("should keep the CLI callback port through the round trip", func(t *testing.T) {+ t.Parallel()+ for _, kind := range providers {+ t.Run(string(kind), func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ p := newPerson(tn, true)++ // Action+ res := oauthLogin(t, tn, kind, p, withCallbackPort("5555"))++ // Assert+ loc := res.redirect(t)+ require.Equal(t, "/login/select-organization", loc.Path)+ require.Equal(t, "5555", loc.Query().Get("callback_port"))+ })+ }+ })+}++func TestOAuth_Google(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should accept an invited membership when Google login names the org slug", func(t *testing.T) {+ t.Parallel()+ skipUntilGoogleFakeAttributesQueryToken(t)++ // Setup+ tn := h.NewTenant(t)+ other := h.NewTenant(t)+ alice := tn.NewUser(t)+ invite(t, other, alice.Email)+ p := newPerson(tn, true)+ p.Email = alice.Email++ // Action+ res := oauthLogin(t, tn, viaGoogle, p, withOrgSlug(other.OrgSlug))++ // Assert+ require.Equal(t, "/login/select-organization", res.redirect(t).Path)+ require.Equal(t, "accepted", fixture.MembershipOf(t, other, alice.Email).Status)+ })++ t.Run("should refuse selecting an org with Google SSO enforced for a non-Google session, and allow a Google one", func(t *testing.T) {+ t.Parallel()+ skipUntilGoogleFakeAttributesQueryToken(t)++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ p := newPerson(tn, true)+ p.Email = alice.Email+ google := sessionFrom(t, tn, oauthLogin(t, tn, viaGoogle, p))+ first := selectOrg(t, tn, google, tn.OrgID.String())+ require.Equalf(t, http.StatusOK, first.StatusCode(), "selecting with Google: %s", apierr.Body(first.Body))+ enforced := updateOrg(t, tn, api.UpdateOrganizationJSONRequestBody{GoogleSsoAuthEnforced: new(true)})+ require.Equalf(t, http.StatusOK, enforced.StatusCode(), "enforcing Google SSO: %s", apierr.Body(enforced.Body))++ // Action+ password := selectOrg(t, tn, loggedIn(t, tn, alice.Email), tn.OrgID.String())+ viaGoogleAgain := selectOrg(t, tn, sessionFrom(t, tn, oauthLogin(t, tn, viaGoogle, p)), tn.OrgID.String())++ // Assert+ require.Equal(t, http.StatusForbidden, password.StatusCode())+ require.Equal(t, "Google SSO is enforced for this organization. Please use Google SSO to login.", apierr.Message(password.Body))+ require.Equalf(t, http.StatusOK, viaGoogleAgain.StatusCode(), "selecting with Google: %s", apierr.Body(viaGoogleAgain.Body))+ })+}++func TestOAuth_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should answer a 4xx when the provider returns no email", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ b := startOAuth(t, tn, viaGitHub)+ cp := consentGitHub(t, tn, newAccountID())+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)+ defer cancel()++ // Action+ res, err := b.callback(ctx, viaGitHub, cp.Code, b.state, b.cookies...)++ // Assert+ require.NoError(t, err, "the callback never answered")+ require4xx(t, res.Status, res.Body)+ require.Nil(t, cookieNamed(res.HTTP, "jid"))+ })+}++// requireNoSession checks a callback started no session: it either refused outright or+// sent the browser to the provider error page.+func requireNoSession(t *testing.T, res callbackResult) {+ t.Helper()+ require.Nil(t, cookieNamed(res.HTTP, "jid"))+ if res.Status == http.StatusFound {+ require.Equal(t, "/login/provider/error", res.redirect(t).Path)+ return+ }+ require4xx(t, res.Status, res.Body)+}diff --git a/tests/suites/user/oauthflow_test.go b/tests/suites/user/oauthflow_test.gonew file mode 100644index 0000000000..44500c3257--- /dev/null+++ b/tests/suites/user/oauthflow_test.go@@ -0,0 +1,237 @@+package user_test++import (+ "context"+ "crypto/rand"+ "fmt"+ "net/http"+ "net/url"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ githubfake "github.com/Infisical/infisical/tests/fakes/github"+ "github.com/Infisical/infisical/tests/fakes/oauth"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/harness/infisical"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/stretchr/testify/require"+)++type providerKind string++const (+ viaGoogle providerKind = "google"+ viaGitHub providerKind = "github"+ viaGitLab providerKind = "gitlab"+)++// providers are the logins every provider-agnostic claim runs against.+//+// Google is left out: passport-google-oauth20 sends the access token to+// www.googleapis.com/oauth2/v3/userinfo as an access_token query parameter, and+// fakes/oauth attributes profile calls only by the Authorization header, so every+// Google callback answers 500 until the fake reads the query parameter too.+var providers = []providerKind{viaGitHub, viaGitLab}++func skipUntilGoogleFakeAttributesQueryToken(t *testing.T) {+ t.Helper()+ t.Skip("fakes/oauth does not attribute www.googleapis.com/oauth2/v3/userinfo?access_token=..., " ++ "which is how passport-google-oauth20 sends the token, so the Google callback answers 500")+}++// browser is the half of an OAuth login the test drives: Infisical's redirect to the+// provider, and the provider's redirect back.+type browser struct {+ ip string+ api *api.ClientWithResponses+ cookies []*http.Cookie+ state string+}++type startOption func(*startParams)++type startParams struct {+ callbackPort *string+ orgSlug *string+}++func withCallbackPort(p string) startOption { return func(s *startParams) { s.callbackPort = &p } }+func withOrgSlug(slug string) startOption { return func(s *startParams) { s.orgSlug = &slug } }++// startOAuth calls Infisical's redirect route and keeps what a browser would: the+// session cookie that carries state and the PKCE verifier, and the state itself.+func startOAuth(t *testing.T, tn *harness.Tenant, kind providerKind, opts ...startOption) *browser {+ t.Helper()+ var p startParams+ for _, o := range opts {+ o(&p)+ }+ ip := newIP()+ b := &browser{ip: ip, api: device(t, tn, ip, infisical.NoRedirects())}+ ctx := t.Context()++ var res *http.Response+ var body []byte+ switch kind {+ case viaGoogle:+ r, err := b.api.RedirectGoogleSSOWithResponse(ctx, &api.RedirectGoogleSSOParams{CallbackPort: p.callbackPort, OrgSlug: p.orgSlug})+ require.NoError(t, err)+ res, body = r.HTTPResponse, r.Body+ case viaGitHub:+ r, err := b.api.RedirectGitHubSSOWithResponse(ctx, &api.RedirectGitHubSSOParams{CallbackPort: p.callbackPort})+ require.NoError(t, err)+ res, body = r.HTTPResponse, r.Body+ case viaGitLab:+ r, err := b.api.RedirectGitLabSSOWithResponse(ctx, &api.RedirectGitLabSSOParams{CallbackPort: p.callbackPort})+ require.NoError(t, err)+ res, body = r.HTTPResponse, r.Body+ }+ require.Equalf(t, http.StatusFound, res.StatusCode, "starting %s login: %s", kind, apierr.Body(body))+ loc, err := url.Parse(res.Header.Get("Location"))+ require.NoError(t, err)+ b.state, b.cookies = loc.Query().Get("state"), res.Cookies()+ require.NotEmptyf(t, b.state, "the authorization redirect carries no state: %s", loc)+ return b+}++// callbackResult is Infisical's answer to the provider's redirect.+type callbackResult struct {+ Status int+ HTTP *http.Response+ Body []byte+}++// callback is the provider sending the browser back with a code and a state.+func (b *browser) callback(ctx context.Context, kind providerKind, code, state string, cookies ...*http.Cookie) (callbackResult, error) {+ editor := withCookies(cookies...)+ switch kind {+ case viaGoogle:+ r, err := b.api.GoogleLoginCallbackWithResponse(ctx, &api.GoogleLoginCallbackParams{Code: new(code), State: new(state)}, editor)+ if err != nil {+ return callbackResult{}, err+ }+ return callbackResult{r.StatusCode(), r.HTTPResponse, r.Body}, nil+ case viaGitHub:+ r, err := b.api.GithubLoginCallbackWithResponse(ctx, &api.GithubLoginCallbackParams{Code: new(code), State: new(state)}, editor)+ if err != nil {+ return callbackResult{}, err+ }+ return callbackResult{r.StatusCode(), r.HTTPResponse, r.Body}, nil+ default:+ r, err := b.api.GitlabLoginCallbackWithResponse(ctx, &api.GitlabLoginCallbackParams{Code: new(code), State: new(state)}, editor)+ if err != nil {+ return callbackResult{}, err+ }+ return callbackResult{r.StatusCode(), r.HTTPResponse, r.Body}, nil+ }+}++// finish completes the round trip with the browser's own cookies and state.+func (b *browser) finish(t *testing.T, kind providerKind, cp *oauth.ControlPlane) callbackResult {+ t.Helper()+ res, err := b.callback(t.Context(), kind, cp.Code, b.state, b.cookies...)+ require.NoError(t, err)+ return res+}++// redirect is where the callback sent the browser.+func (r callbackResult) redirect(t *testing.T) *url.URL {+ t.Helper()+ require.Equalf(t, http.StatusFound, r.Status, "the callback did not redirect: %s", apierr.Body(r.Body))+ loc, err := url.Parse(r.HTTP.Header.Get("Location"))+ require.NoError(t, err)+ return loc+}++// person is who logs in at the provider: a stable provider account id, the address the+// provider asserts, and whether the provider vouches for it.+type person struct {+ ID int64+ Email string+ Verified bool+}++// newAccountID is a provider account id no other run has used: Infisical finds a+// returning provider login by this id across the whole instance.+func newAccountID() int64 {+ b := make([]byte, 6)+ _, _ = rand.Read(b)+ var n int64+ for _, x := range b {+ n = n<<8 | int64(x)+ }+ return n+}++func newPerson(tn *harness.Tenant, verified bool) person {+ return person{ID: newAccountID(), Email: tn.Email("x-" + id.Short()), Verified: verified}+}++// consent seeds the provider fake with a person who just consented, and returns the+// code the provider would put on the redirect.+func consent(t *testing.T, tn *harness.Tenant, kind providerKind, p person) *oauth.ControlPlane {+ t.Helper()+ switch kind {+ case viaGoogle:+ return oauth.LogIn(t, fixture.FakenetAdmin(t, tn), oauth.Google, oauth.Profile{+ Subject: fmt.Sprintf("g-%d", p.ID),+ Email: p.Email,+ EmailVerified: p.Verified,+ GivenName: "Ada",+ FamilyName: "Lovelace",+ })+ case viaGitLab:+ profile := oauth.Profile{ID: p.ID, Username: "ada", Name: "Ada", Email: p.Email}+ if p.Verified {+ profile.ConfirmedAt = "2024-01-01T00:00:00Z"+ }+ return oauth.LogIn(t, fixture.FakenetAdmin(t, tn), oauth.GitLab, profile)+ default:+ return consentGitHub(t, tn, p.ID, githubfake.Email{Email: p.Email, Primary: true, Verified: p.Verified})+ }+}++func consentGitHub(t *testing.T, tn *harness.Tenant, accountID int64, emails ...githubfake.Email) *oauth.ControlPlane {+ t.Helper()+ return oauth.LogInGitHub(t, fixture.FakenetAdmin(t, tn), oauth.GitHubUser{+ Login: "ada",+ ID: accountID,+ Name: "Ada",+ Emails: emails,+ })+}++// oauthLogin is a whole login: start, consent, callback.+func oauthLogin(t *testing.T, tn *harness.Tenant, kind providerKind, p person, opts ...startOption) callbackResult {+ t.Helper()+ b := startOAuth(t, tn, kind, opts...)+ return b.finish(t, kind, consent(t, tn, kind, p))+}++// accountOf follows a login that issued a session and reads the account it belongs to.+func accountOf(t *testing.T, tn *harness.Tenant, res callbackResult) *api.GetCurrentUserV1Response {+ t.Helper()+ jid := cookieNamed(res.HTTP, "jid")+ require.NotNil(t, jid, "the login set no refresh cookie")+ ip := newIP()+ refreshed := refresh(t, tn, ip, jid)+ require.Equalf(t, http.StatusOK, refreshed.StatusCode(), "refreshing the session: %s", apierr.Body(refreshed.Body))+ me, err := as(t, tn, refreshed.JSON200.Token, ip).GetCurrentUserV1WithResponse(t.Context())+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, me.StatusCode(), "reading the account: %s", apierr.Body(me.Body))+ return me+}++// sessionFrom turns a login's refresh cookie into an org-less session, the way the+// select-organization page starts.+func sessionFrom(t *testing.T, tn *harness.Tenant, res callbackResult) session {+ t.Helper()+ jid := cookieNamed(res.HTTP, "jid")+ require.NotNil(t, jid, "the login set no refresh cookie")+ ip := newIP()+ refreshed := refresh(t, tn, ip, jid)+ require.Equalf(t, http.StatusOK, refreshed.StatusCode(), "refreshing the session: %s", apierr.Body(refreshed.Body))+ return session{IP: ip, Token: refreshed.JSON200.Token, API: as(t, tn, refreshed.JSON200.Token, ip)}+}diff --git a/tests/suites/user/password_test.go b/tests/suites/user/password_test.gonew file mode 100644index 0000000000..99ad0ac576--- /dev/null+++ b/tests/suites/user/password_test.go@@ -0,0 +1,194 @@+package user_test++import (+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/Infisical/infisical/tests/internal/mail"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++const (+ newPassword = "ChangedHarnessPassword9#"+ recoverySubject = "Infisical account recovery"+)++func TestPassword_Change(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should change the password, revoke all sessions, and refuse the old password", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ phone := signIn(t, tn, alice.Email)++ // Action+ res, err := alice.API.ResetUserPasswordWithResponse(t.Context(), api.ResetUserPasswordJSONRequestBody{+ OldPassword: harness.UserPassword,+ NewPassword: newPassword,+ })++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "changing the password: %s", apierr.Body(res.Body))+ requireSessionGone(t, alice.API)+ requireSessionGone(t, phone.API)+ old, _ := login(t, tn, alice.Email, harness.UserPassword)+ require.Equal(t, http.StatusBadRequest, old.StatusCode())+ changed, _ := login(t, tn, alice.Email, newPassword)+ require.Equal(t, http.StatusOK, changed.StatusCode())+ })++ t.Run("should refuse a wrong old password and keep the current one", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)++ // Action+ res, err := alice.API.ResetUserPasswordWithResponse(t.Context(), api.ResetUserPasswordJSONRequestBody{+ OldPassword: "NotTheOldPassword7!x",+ NewPassword: newPassword,+ })++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t, "Incorrect current password.", apierr.Message(res.Body))+ require.Equal(t, http.StatusOK, meStatus(t, alice.API))+ current, _ := login(t, tn, alice.Email, harness.UserPassword)+ require.Equal(t, http.StatusOK, current.StatusCode())+ })+}++func TestAccountRecovery(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should answer the same for unknown and known emails, mailing only the known one", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ nobody := tn.Email("nobody-" + id.Short())++ // Action+ unknown := sendRecovery(t, tn, nobody)+ known := sendRecovery(t, tn, alice.Email)++ // Assert+ require.Equal(t, http.StatusOK, unknown.StatusCode())+ require.Equal(t, http.StatusOK, known.StatusCode())+ require.Equal(t, unknown.JSON200.Message, known.JSON200.Message)+ tn.Mail(t).Expect(t, alice.Email, smtp.Subject(recoverySubject))+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool {+ return e.Recipient == strings.ToLower(nobody)+ })+ })++ t.Run("should reset the password through the mailed code and revoke all sessions", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ token := recoveryToken(t, tn, alice.Email)++ // Action+ res, err := tn.Client(t, token).ResetPasswordWithResponse(t.Context(), api.ResetPasswordJSONRequestBody{NewPassword: newPassword})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "resetting: %s", apierr.Body(res.Body))+ requireSessionGone(t, alice.API)+ old, _ := login(t, tn, alice.Email, harness.UserPassword)+ require.Equal(t, http.StatusBadRequest, old.StatusCode())+ reset, _ := login(t, tn, alice.Email, newPassword)+ require.Equal(t, http.StatusOK, reset.StatusCode())+ })++ t.Run("should refuse a replayed recovery token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ token := recoveryToken(t, tn, alice.Email)+ first, err := tn.Client(t, token).ResetPasswordWithResponse(t.Context(), api.ResetPasswordJSONRequestBody{NewPassword: newPassword})+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, first.StatusCode(), "resetting: %s", apierr.Body(first.Body))++ // Action+ res, err := tn.Client(t, token).ResetPasswordWithResponse(t.Context(), api.ResetPasswordJSONRequestBody{NewPassword: "ReplayedHarnessPassword9#"})++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusUnauthorized, res.StatusCode())+ require.Equal(t, "Invalid recovery token", apierr.Message(res.Body))+ kept, _ := login(t, tn, alice.Email, newPassword)+ require.Equal(t, http.StatusOK, kept.StatusCode())+ })+}++func TestAccountRecovery_KnownIssues(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a wrong recovery code with a 4xx", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ sendRecovery(t, tn, alice.Email)+ tn.Mail(t).Expect(t, alice.Email, smtp.Subject(recoverySubject))++ // Action+ res, err := tn.Anonymous(t).VerifyAccountRecoveryEmailWithResponse(t.Context(), api.VerifyAccountRecoveryEmailJSONRequestBody{+ Email: openapi_types.Email(alice.Email),+ Code: "not-the-code",+ })++ // Assert+ require.NoError(t, err)+ require4xx(t, res.StatusCode(), res.Body)+ })+}++func sendRecovery(t *testing.T, tn *harness.Tenant, email string) *api.SendAccountRecoveryEmailResponse {+ t.Helper()+ res, err := tn.Anonymous(t).SendAccountRecoveryEmailWithResponse(t.Context(), api.SendAccountRecoveryEmailJSONRequestBody{+ Email: openapi_types.Email(email),+ })+ require.NoError(t, err)+ return res+}++// recoveryToken runs the recovery mail round trip and returns the token that may reset+// the password.+func recoveryToken(t *testing.T, tn *harness.Tenant, email string) string {+ t.Helper()+ sent := sendRecovery(t, tn, email)+ require.Equalf(t, http.StatusOK, sent.StatusCode(), "sending the recovery mail: %s", apierr.Body(sent.Body))+ code, err := mail.Param(tn.Mail(t).Expect(t, email, smtp.Subject(recoverySubject)), "token")+ require.NoError(t, err)+ res, err := tn.Anonymous(t).VerifyAccountRecoveryEmailWithResponse(t.Context(), api.VerifyAccountRecoveryEmailJSONRequestBody{+ Email: openapi_types.Email(email),+ Code: code,+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "verifying the recovery code: %s", apierr.Body(res.Body))+ return res.JSON200.Token+}diff --git a/tests/suites/user/session_test.go b/tests/suites/user/session_test.gonew file mode 100644index 0000000000..843bf1926f--- /dev/null+++ b/tests/suites/user/session_test.go@@ -0,0 +1,294 @@+package user_test++import (+ "encoding/base64"+ "encoding/json"+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/stretchr/testify/require"+)++const sessionGone = "Your session is no longer valid, please re-authenticate"++func TestSession_Scope(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse org B's routes for a session selected into org A, naming the token's org", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ other := h.NewTenant(t)+ alice := tn.NewUser(t)+ invite(t, other, alice.Email)+ selectOrg(t, tn, loggedIn(t, tn, alice.Email), other.OrgID.String())++ // Action+ res, err := alice.API.ListOrgMembershipsWithResponse(t.Context(), other.OrgID.String())++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Contains(t, apierr.Message(res.Body), "Your token is scoped to organization with ID "+tn.OrgID.String())+ require.Equal(t, "accepted", fixture.MembershipOf(t, other, alice.Email).Status)+ })+}++func TestSession_Revoke(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a session's token on its next request once that session is revoked", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ laptop := signIn(t, tn, alice.Email)+ phone := signIn(t, tn, alice.Email)++ // Action+ res, err := laptop.API.RevokeUserSessionWithResponse(t.Context(), sessionAt(t, laptop.API, phone.IP))++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "revoking: %s", apierr.Body(res.Body))+ requireSessionGone(t, phone.API)+ require.Equal(t, http.StatusOK, meStatus(t, laptop.API))+ })++ t.Run("should refuse every session once all are revoked, and accept a new login", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ laptop := signIn(t, tn, alice.Email)++ // Action+ res, err := laptop.API.RevokeAllUserSessionsWithResponse(t.Context())++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "revoking: %s", apierr.Body(res.Body))+ requireSessionGone(t, laptop.API)+ requireSessionGone(t, alice.API)+ require.Equal(t, http.StatusOK, meStatus(t, signIn(t, tn, alice.Email).API))+ })++ t.Run("should leave another user's session working when its id is revoked", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ bob := signIn(t, tn, tn.NewUser(t).Email)++ // Action+ res, err := alice.API.RevokeUserSessionWithResponse(t.Context(), sessionAt(t, bob.API, bob.IP))++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "body: %s", apierr.Body(res.Body))+ require.Equal(t, http.StatusOK, meStatus(t, bob.API))+ })++ t.Run("should refuse the access token immediately after logout", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ s := signIn(t, tn, alice.Email)++ // Action+ res, err := s.API.LogoutWithResponse(t.Context(), withCookies(s.JID))++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "logging out: %s", apierr.Body(res.Body))+ requireSessionGone(t, s.API)+ require.Equal(t, http.StatusUnauthorized, refresh(t, tn, s.IP, s.JID).StatusCode())+ })++ t.Run("should cut off open sessions when the org membership is deleted", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ m := fixture.MembershipOf(t, tn, alice.Email)++ // Action+ res, err := tn.Admin.API.DeleteOrgMembershipWithResponse(t.Context(), tn.OrgID.String(), m.ID.String())++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "deleting the membership: %s", apierr.Body(res.Body))+ requireRefused(t, alice.API, tn.OrgID.String(), http.StatusForbidden, "User not member of organization")+ })++ t.Run("should cut off an open session when an admin deactivates the member through the API", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ m := fixture.MembershipOf(t, tn, alice.Email)++ // Action+ res, err := tn.Admin.API.UpdateOrgMembershipWithResponse(t.Context(), tn.OrgID.String(), m.ID.String(),+ api.UpdateOrgMembershipJSONRequestBody{IsActive: new(false)})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "deactivating: %s", apierr.Body(res.Body))+ requireRefused(t, alice.API, tn.OrgID.String(), http.StatusForbidden, "User organization membership is inactive")+ })+}++func TestSession_Refresh(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should rotate the refresh token and issue a working access token", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ s := signIn(t, tn, tn.NewUser(t).Email)++ // Action+ res := refresh(t, tn, s.IP, s.JID)++ // Assert+ require.Equalf(t, http.StatusOK, res.StatusCode(), "refreshing: %s", apierr.Body(res.Body))+ rotated := cookieNamed(res.HTTPResponse, "jid")+ require.NotNil(t, rotated)+ require.NotEqual(t, s.JID.Value, rotated.Value)+ require.Equal(t, rotated.Value, *res.JSON200.RefreshToken)+ require.Equal(t, tn.OrgID.String(), *res.JSON200.OrganizationId)+ require.Equal(t, http.StatusOK, orgStatus(t, as(t, tn, res.JSON200.Token, s.IP), tn.OrgID.String()))+ })++ t.Run("should refuse a reused refresh token outside its grace window and delete the session", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ s := signIn(t, tn, tn.NewUser(t).Email)+ second := cookieNamed(refresh(t, tn, s.IP, s.JID).HTTPResponse, "jid")+ third := cookieNamed(refresh(t, tn, s.IP, second).HTTPResponse, "jid")++ // Action+ res := refresh(t, tn, s.IP, s.JID)++ // Assert+ require.Equal(t, http.StatusUnauthorized, res.StatusCode())+ require.Equal(t, "Refresh token reuse detected. Session has been revoked for security.", apierr.Message(res.Body))+ requireSessionGone(t, s.API)+ require.Equal(t, http.StatusUnauthorized, refresh(t, tn, s.IP, third).StatusCode())+ })++ t.Run("should accept the previous refresh token within its grace window without rotating again", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ s := signIn(t, tn, tn.NewUser(t).Email)+ second := cookieNamed(refresh(t, tn, s.IP, s.JID).HTTPResponse, "jid")++ // Action+ res := refresh(t, tn, s.IP, s.JID)++ // Assert+ require.Equalf(t, http.StatusOK, res.StatusCode(), "refreshing: %s", apierr.Body(res.Body))+ require.Nil(t, res.JSON200.RefreshToken)+ require.Equal(t, http.StatusOK, refresh(t, tn, s.IP, second).StatusCode())+ })++ t.Run("should cap access and refresh lifetime at the org's userTokenExpiration", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ set := updateOrg(t, tn, api.UpdateOrganizationJSONRequestBody{UserTokenExpiration: new("1h")})+ require.Equalf(t, http.StatusOK, set.StatusCode(), "setting the expiration: %s", apierr.Body(set.Body))++ // Action+ s := signIn(t, tn, alice.Email)++ // Assert+ require.Equal(t, int64(3600), lifetime(t, s.Token))+ require.Equal(t, int64(3600), lifetime(t, s.JID.Value))+ refreshed := refresh(t, tn, s.IP, s.JID)+ require.Equalf(t, http.StatusOK, refreshed.StatusCode(), "refreshing: %s", apierr.Body(refreshed.Body))+ require.Equal(t, int64(3600), lifetime(t, refreshed.JSON200.Token))+ require.Equal(t, int64(3600), lifetime(t, *refreshed.JSON200.RefreshToken))+ })+}++// sessionAt is the id of the caller's session that was opened from ip.+func sessionAt(t *testing.T, c *api.ClientWithResponses, ip string) string {+ t.Helper()+ res, err := c.ListUserSessionsWithResponse(t.Context())+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "listing sessions: %s", apierr.Body(res.Body))+ for _, s := range *res.JSON200 {+ if s.Ip == ip {+ return s.Id.String()+ }+ }+ require.Failf(t, "no session", "no session from %s", ip)+ return ""+}++func requireSessionGone(t *testing.T, c *api.ClientWithResponses) {+ t.Helper()+ res, err := c.GetCurrentUserWithResponse(t.Context())+ require.NoError(t, err)+ require.Equal(t, http.StatusUnauthorized, res.StatusCode())+ require.Equal(t, sessionGone, apierr.Message(res.Body))+}++// requireRefused waits for the org route to refuse the session. Membership changes reach+// the auth check without a cache today, so this normally holds on the first read.+func requireRefused(t *testing.T, c *api.ClientWithResponses, orgID string, status int, message string) {+ t.Helper()+ var last *api.GetOrganizationByIdResponse+ wait.Until(t, "the session to be refused", func() bool {+ res, err := c.GetOrganizationByIdWithResponse(t.Context(), orgID)+ require.NoError(t, err)+ last = res+ return res.StatusCode() != http.StatusOK+ })+ require.Equal(t, status, last.StatusCode())+ require.Equal(t, message, apierr.Message(last.Body))+}++// lifetime is a JWT's exp minus its iat, in seconds.+func lifetime(t *testing.T, token string) int64 {+ t.Helper()+ c := claims(t, token)+ return int64(c["exp"].(float64)) - int64(c["iat"].(float64))+}++func claims(t *testing.T, token string) map[string]any {+ t.Helper()+ parts := strings.Split(token, ".")+ require.Len(t, parts, 3, "not a JWT")+ raw, err := base64.RawURLEncoding.DecodeString(parts[1])+ require.NoError(t, err)+ var out map[string]any+ require.NoError(t, json.Unmarshal(raw, &out))+ return out+}diff --git a/tests/suites/user/signup_test.go b/tests/suites/user/signup_test.gonew file mode 100644index 0000000000..bdbc479410--- /dev/null+++ b/tests/suites/user/signup_test.go@@ -0,0 +1,164 @@+package user_test++import (+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/smtp"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ openapi_types "github.com/oapi-codegen/runtime/types"+ "github.com/stretchr/testify/require"+)++const signupCodeSubject = "confirmation code"++func TestSignup_Email(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should create an account through the mailed code and refuse a wrong code", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ email := tn.Email("s-" + id.Short())+ b := device(t, tn, newIP())+ require.Equal(t, http.StatusOK, beginSignup(t, b, email).StatusCode())+ mailed := code(t, tn.Mail(t).Expect(t, email, smtp.Subject(signupCodeSubject)))++ // Action+ wrong := verifySignup(t, b, email, otherCode(mailed))+ right := verifySignup(t, b, email, mailed)++ // Assert+ require.Equal(t, http.StatusUnauthorized, wrong.StatusCode())+ require.Equal(t, "Invalid token", apierr.Message(wrong.Body))+ require.Equalf(t, http.StatusOK, right.StatusCode(), "verifying: %s", apierr.Body(right.Body))+ completed := completeEmailSignup(t, tn, right.JSON200.Token, email, harness.UserPassword)+ require.Equalf(t, http.StatusOK, completed.StatusCode(), "completing: %s", apierr.Body(completed.Body))+ res, _ := login(t, tn, email, harness.UserPassword)+ require.Equal(t, http.StatusOK, res.StatusCode())+ })++ t.Run("should answer the same for an existing account and mail it a notice instead of a code", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ alice := tn.NewUser(t)+ fresh := tn.Email("s-" + id.Short())+ b := device(t, tn, newIP())++ // Action+ existing := beginSignup(t, b, alice.Email)+ unknown := beginSignup(t, b, fresh)++ // Assert+ require.Equal(t, http.StatusOK, existing.StatusCode())+ require.Equal(t, http.StatusOK, unknown.StatusCode())+ require.Equal(t, "Sent an email verification code to "+alice.Email, existing.JSON200.Message)+ require.Equal(t, unknown.JSON200.CooldownSeconds, existing.JSON200.CooldownSeconds)+ tn.Mail(t).Expect(t, alice.Email, smtp.Subject("Sign-up Request for Your Infisical Account"))+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool {+ return e.Recipient == strings.ToLower(alice.Email) && strings.Contains(e.Message.Subject, signupCodeSubject)+ })+ })++ t.Run("should refuse a second request within the cooldown", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ email := tn.Email("s-" + id.Short())+ b := device(t, tn, newIP())+ require.Equal(t, http.StatusOK, beginSignup(t, b, email).StatusCode())+ tn.Mail(t).Expect(t, email, smtp.Subject(signupCodeSubject))++ // Action+ res := beginSignup(t, b, email)++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t, "Please wait before requesting another email", apierr.Message(res.Body))+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool {+ return e.Recipient == strings.ToLower(email)+ })+ })++ t.Run("should refuse a password that breaks the policy and create no account", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ email := tn.Email("s-" + id.Short())+ b := device(t, tn, newIP())+ require.Equal(t, http.StatusOK, beginSignup(t, b, email).StatusCode())+ verified := verifySignup(t, b, email, code(t, tn.Mail(t).Expect(t, email, smtp.Subject(signupCodeSubject))))+ require.Equalf(t, http.StatusOK, verified.StatusCode(), "verifying: %s", apierr.Body(verified.Body))++ // Action+ res := completeEmailSignup(t, tn, verified.JSON200.Token, email, "short")++ // Assert+ require.Equal(t, http.StatusUnprocessableEntity, res.StatusCode())+ weak, _ := login(t, tn, email, "short")+ require.Equal(t, http.StatusBadRequest, weak.StatusCode())+ strong, _ := login(t, tn, email, harness.UserPassword)+ require.Equal(t, http.StatusBadRequest, strong.StatusCode())+ })++ t.Run("should refuse signup for a domain owned by an SSO-enforced org", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ sso.NewSAML(t, tn, sso.Okta).Enforce(t)+ email := tn.Email("s-" + id.Short())++ // Action+ res := beginSignup(t, device(t, tn, newIP()), email)++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, apierr.Message(res.Body), "Your organization requires single sign-on")+ tn.Mail(t).ExpectNoEvent[smtp.MessageReceived](t, func(e smtp.MessageReceived) bool {+ return e.Recipient == strings.ToLower(email)+ })+ })+}++func beginSignup(t *testing.T, c *api.ClientWithResponses, email string) *api.BeginEmailSignupV3Response {+ t.Helper()+ res, err := c.BeginEmailSignupV3WithResponse(t.Context(), api.BeginEmailSignupV3JSONRequestBody{Email: openapi_types.Email(email)})+ require.NoError(t, err)+ return res+}++func verifySignup(t *testing.T, c *api.ClientWithResponses, email, code string) *api.VerifyEmailSignupV3Response {+ t.Helper()+ res, err := c.VerifyEmailSignupV3WithResponse(t.Context(), api.VerifyEmailSignupV3JSONRequestBody{+ Email: openapi_types.Email(email),+ Code: code,+ })+ require.NoError(t, err)+ return res+}++func completeEmailSignup(t *testing.T, tn *harness.Tenant, signupToken, email, password string) *api.CompleteAccountSignupV3Response {+ t.Helper()+ var union api.CompleteAccountSignupV3JSONBody+ require.NoError(t, union.FromCompleteAccountSignupV3JSONBody0(api.CompleteAccountSignupV3JSONBody0{+ Type: api.CompleteAccountSignupV3JSONBody0TypeEmail,+ Email: email,+ FirstName: "ada",+ Password: password,+ }))+ res, err := tn.Client(t, signupToken).CompleteAccountSignupV3WithBodyWithResponse(t.Context(), "application/json", postJSON(t, union))+ require.NoError(t, err)+ return res+}