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: stable fakenet image ids, OIDC SSO suite, project leave and assumed privilege scope
Claude0c76feec9513
diff --git a/tests/harness/infisical/image.go b/tests/harness/infisical/image.goindex 7b3b3732b0..8fc765cf88 100644--- a/tests/harness/infisical/image.go+++ b/tests/harness/infisical/image.go@@ -86,7 +86,8 @@ func build(ctx context.Context, repoRoot string) (string, error) {_ = iid.Close()defer func() { _ = os.Remove(iidPath) }()- args := []string{"build", "-f", filepath.Join(backend, "Dockerfile"), "-t", localTag, "--iidfile", iidPath}+ // See fakenet.ResolveImage: without this the id changes on every build.+ args := []string{"build", "--provenance=false", "-f", filepath.Join(backend, "Dockerfile"), "-t", localTag, "--iidfile", iidPath}if pin := cliVersion(repoRoot); pin != "" {// Keep the pinned CLI version honest. The Dockerfile carries a matching ARG// default, and check-dockerfile-pins.yml fails a PR when they drift.diff --git a/tests/infra/fakenet/module.go b/tests/infra/fakenet/module.goindex 803170a966..8b0f25b05c 100644--- a/tests/infra/fakenet/module.go+++ b/tests/infra/fakenet/module.go@@ -88,7 +88,11 @@ func ResolveImage(ctx context.Context, repoRoot string, log infra.Logger) (Image}iid := filepath.Join(dir, "iid")- dockerBuild := exec.CommandContext(ctx, "docker", "build",+ // --provenance=false: with the containerd image store the image id covers the+ // provenance attestation, which carries build timestamps, so an identical binary+ // would get a new id on every build and each test binary would replace the+ // running fakenet under the others.+ dockerBuild := exec.CommandContext(ctx, "docker", "build", "--provenance=false","-f", filepath.Join(tests, "cmd", "fakenet", "Dockerfile"),"-t", localTag, "--iidfile", iid, dir)dockerBuild.Stdout = os.Stderrdiff --git a/tests/suites/secretmanager/access/assume_privilege_scope_test.go b/tests/suites/secretmanager/access/assume_privilege_scope_test.gonew file mode 100644index 0000000000..6dd6307e1e--- /dev/null+++ b/tests/suites/secretmanager/access/assume_privilege_scope_test.go@@ -0,0 +1,38 @@+package access_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/stretchr/testify/require"+)++func TestAssumePrivilege_Scope(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should not carry the assumed identity's access into another project the requester is not in", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ assumed := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ other := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ requester := assumed.NewUser(t, fixture.WithRoles("admin"))+ target := tn.NewMachineIdentity(t)+ assumed.Grant(t, target, "viewer")+ other.Grant(t, target, "admin")+ session := startSession(t, requester, assumed, target)++ // Action+ created := createSecret(t, requester.API, other, "dev", "/", "THROUGH_COOKIE", "value", withCookie(session))++ // Assert+ requireStatus(t, http.StatusForbidden, created.StatusCode(), created.Body)+ require.Empty(t, keysOf(listSecrets(t, tn.Admin.API, other, "dev", "/")))+ asViewer := createSecret(t, requester.API, assumed, "dev", "/", "AS_VIEWER", "value", withCookie(session))+ require.Equal(t, http.StatusForbidden, asViewer.StatusCode(), "the session should still hold the viewer's access in its own project")+ })+}diff --git a/tests/suites/secretmanager/access/project_leave_test.go b/tests/suites/secretmanager/access/project_leave_test.gonew file mode 100644index 0000000000..0c8d6a7178--- /dev/null+++ b/tests/suites/secretmanager/access/project_leave_test.go@@ -0,0 +1,100 @@+package access_test++import (+ "net/http"+ "testing"++ "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 TestProjectLeave(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should remove the user's membership and access when they leave", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ viewer := proj.NewUser(t, fixture.WithRoles("viewer"))++ // Action+ res, err := viewer.API.LeaveProjectWithResponse(t.Context(), proj.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Nil(t, userRoles(t, proj, viewer))+ waitForStatus(t, http.StatusForbidden, func() (int, []byte) {+ listed := listSecrets(t, viewer.API, proj, "dev", "/")+ return listed.StatusCode(), listed.Body+ })+ })++ t.Run("should refuse and keep the group's access when the user is a member only through a group", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ user := tn.NewUser(t)+ group := fixture.NewGroup(t, tn)+ group.AddUser(t, user)+ proj.GrantGroup(t, group, "viewer")++ // Action+ res, err := user.API.LeaveProjectWithResponse(t.Context(), proj.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "You have access to this project through a group rather than a direct membership.")+ listed := listSecrets(t, user.API, proj, "dev", "/")+ requireStatus(t, http.StatusOK, listed.StatusCode(), listed.Body)+ })++ t.Run("should refuse a user who is not a member of the project", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ outsider := tn.NewUser(t)++ // Action+ res, err := outsider.API.LeaveProjectWithResponse(t.Context(), proj.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, string(res.Body), "You are not a member of this project")+ require.Contains(t, slugs(userRoles(t, proj, tn.Admin)), "admin")+ })++ t.Run("should let the last admin leave a secret manager project", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, "Pins current behaviour: only the org-scoped products (PAM, Agent Vault) keep a last admin; "++ "a secret manager project can be left adminless, and an org admin regains it through grant-admin-access.")++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ viewer := proj.NewUser(t, fixture.WithRoles("viewer"))++ // Action+ res, err := tn.Admin.API.LeaveProjectWithResponse(t.Context(), proj.ID)++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ members, err := viewer.API.ListProjectMembershipsWithResponse(t.Context(), proj.ID)+ require.NoError(t, err)+ requireStatus(t, http.StatusOK, members.StatusCode(), members.Body)+ require.Len(t, members.JSON200.Memberships, 1)+ require.Equal(t, viewer.ID, members.JSON200.Memberships[0].UserId)+ })+}diff --git a/tests/suites/sso/oidc/config_test.go b/tests/suites/sso/oidc/config_test.gonew file mode 100644index 0000000000..694a99c76c--- /dev/null+++ b/tests/suites/sso/oidc/config_test.go@@ -0,0 +1,319 @@+package oidc_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/oidcidp"+ "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/Infisical/infisical/tests/internal/spec"+ "github.com/stretchr/testify/require"+)++func TestOIDCConfig_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should store the provider settings without echoing the secret when an admin creates a config", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ body := configBody(t, tn)++ // Action+ res, err := tn.Admin.API.CreateOidcConfigWithResponse(t.Context(), body)++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.NotContains(t, string(res.Body), body.ClientSecret)+ stored := readConfig(t, tn, tn.Admin)+ require.Equal(t, *body.DiscoveryURL, *stored.DiscoveryURL)+ require.Equal(t, "discoveryURL", stored.ConfigurationType)+ require.Equal(t, body.ClientId, stored.ClientId)+ require.Equal(t, body.ClientSecret, stored.ClientSecret)+ require.True(t, stored.IsActive)+ })++ t.Run("should reject creation when the plan lacks OIDC SSO", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.OIDCSSO)))++ // Action+ res, err := tn.Admin.API.CreateOidcConfigWithResponse(t.Context(), configBody(t, tn))++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, string(res.Body), "Failed to create OIDC SSO configuration due to plan restriction")+ requireNoConfig(t, tn)+ })++ t.Run("should reject creation when the actor is a member without SSO permission", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ member := tn.NewUser(t)++ // Action+ res, err := member.API.CreateOidcConfigWithResponse(t.Context(), configBody(t, tn))++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ requireNoConfig(t, tn)+ })++ t.Run("should reject creation when the admin belongs to another organization", func(t *testing.T) {+ t.Parallel()++ // Setup+ mine, theirs := h.NewTenant(t), h.NewTenant(t)++ // Action+ res, err := theirs.Admin.API.CreateOidcConfigWithResponse(t.Context(), configBody(t, mine))++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ requireNoConfig(t, mine)+ })++ t.Run("should reject a discovery config that has no discovery URL", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ body := configBody(t, tn)+ body.DiscoveryURL = nil++ // Action+ res, err := tn.Admin.API.CreateOidcConfigWithResponse(t.Context(), body)++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusUnprocessableEntity, res.StatusCode())+ require.Contains(t, string(res.Body), "Discovery URL is required")+ requireNoConfig(t, tn)+ })+}++func TestOIDCConfig_Read(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should return not found when the organization has no config", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)++ // Action+ res, err := tn.Admin.API.GetOidcConfigWithResponse(t.Context(), &api.GetOidcConfigParams{OrganizationId: tn.OrgID.String()})++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusNotFound, res.StatusCode())+ require.Contains(t, string(res.Body), "Failed to find OIDC SSO data")+ })++ t.Run("should refuse the config, which carries the client secret, when the actor is a member", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ member := o.Tenant.NewUser(t)++ // Action+ res, err := member.API.GetOidcConfigWithResponse(t.Context(), &api.GetOidcConfigParams{OrganizationId: o.Tenant.OrgID.String()})++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Nil(t, res.JSON200)+ })++ t.Run("should return the config when a machine identity has SSO read", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ identity := o.Tenant.NewMachineIdentity(t, harness.OrgRole("admin"))++ // Action+ stored := readConfig(t, o.Tenant, identity)++ // Assert+ require.Equal(t, o.OP.DiscoveryURL()+"/.well-known/openid-configuration", *stored.DiscoveryURL)+ })+}++func TestOIDCConfig_Update(t *testing.T) {+ t.Parallel()++ t.Run("should apply new provider settings when an admin updates the config", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ replacement := configBody(t, o.Tenant)++ // Action+ res, err := o.Tenant.Admin.API.UpdateOidcConfigWithResponse(t.Context(), api.UpdateOidcConfigJSONRequestBody{+ OrganizationId: o.Tenant.OrgID.String(),+ DiscoveryURL: replacement.DiscoveryURL,+ ClientId: new(replacement.ClientId),+ ClientSecret: new(replacement.ClientSecret),+ AllowedEmailDomains: new("a.test,b.test"),+ })++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ stored := readConfig(t, o.Tenant, o.Tenant.Admin)+ require.Equal(t, *replacement.DiscoveryURL, *stored.DiscoveryURL)+ require.Equal(t, replacement.ClientId, stored.ClientId)+ require.Equal(t, replacement.ClientSecret, stored.ClientSecret)+ require.Equal(t, "a.test, b.test", *stored.AllowedEmailDomains)+ })++ t.Run("should reject an update and keep the config when the plan no longer includes OIDC SSO", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ o.Tenant.SetPlan(t, license.Enterprise().Without(license.OIDCSSO))++ // Action+ res, err := o.Tenant.Admin.API.UpdateOidcConfigWithResponse(t.Context(), api.UpdateOidcConfigJSONRequestBody{+ OrganizationId: o.Tenant.OrgID.String(),+ AllowedEmailDomains: new("other.test"),+ })++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, string(res.Body), "Failed to update OIDC SSO configuration due to plan restriction")+ require.Empty(t, *readConfig(t, o.Tenant, o.Tenant.Admin).AllowedEmailDomains)+ })++ t.Run("should reject an update and keep the config when the actor is a member", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ member := o.Tenant.NewUser(t)++ // Action+ res, err := member.API.UpdateOidcConfigWithResponse(t.Context(), api.UpdateOidcConfigJSONRequestBody{+ OrganizationId: o.Tenant.OrgID.String(),+ IsActive: new(false),+ })++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.True(t, readConfig(t, o.Tenant, o.Tenant.Admin).IsActive)+ })++ t.Run("should refuse to start a login when the config is deactivated", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ res, err := o.Tenant.Admin.API.UpdateOidcConfigWithResponse(t.Context(), api.UpdateOidcConfigJSONRequestBody{+ OrganizationId: o.Tenant.OrgID.String(),+ IsActive: new(false),+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))++ // Action+ start, err := o.Browser.RedirectOidcLoginWithResponse(t.Context(), &api.RedirectOidcLoginParams{OrgSlug: new(o.Tenant.OrgSlug)})++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusForbidden, start.StatusCode())+ require.Contains(t, string(start.Body), "Failed to authenticate with OIDC SSO")+ })++ t.Run("should turn off SSO enforcement when the config is updated", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, "Pins current behaviour: every config update clears authEnforced and lastUsed, "++ "so an admin who rotates a client secret silently drops SSO enforcement.")++ // Setup+ o := setup(t)+ enforce(t, o)++ // Action+ res, err := o.Tenant.Admin.API.UpdateOidcConfigWithResponse(t.Context(), api.UpdateOidcConfigJSONRequestBody{+ OrganizationId: o.Tenant.OrgID.String(),+ ClientSecret: new(id.Short()),+ })++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.False(t, authEnforced(t, o.Tenant))+ })+}++// configBody points a config at a new provider in fakenet that knows the client.+func configBody(t *testing.T, tn *harness.Tenant) api.CreateOidcConfigJSONRequestBody {+ t.Helper()+ scope := "t-" + id.Short()+ clientID, secret := "infisical-"+id.Short(), id.Short()+id.Short()+ op := oidcidp.Open(t, fixture.FakenetAdmin(t, tn), scope)+ op.Seed(t, oidcidp.Client(clientID, secret))+ return api.CreateOidcConfigJSONRequestBody{+ OrganizationId: tn.OrgID.String(),+ ConfigurationType: api.CreateOidcConfigJSONBodyConfigurationTypeDiscoveryURL,+ DiscoveryURL: new(op.DiscoveryURL() + "/.well-known/openid-configuration"),+ ClientId: clientID,+ ClientSecret: secret,+ IsActive: true,+ }+}++type storedConfig struct {+ DiscoveryURL, AllowedEmailDomains *string+ ConfigurationType string+ ClientId, ClientSecret string+ IsActive bool+}++func readConfig(t *testing.T, tn *harness.Tenant, actor *harness.Principal) storedConfig {+ t.Helper()+ res, err := actor.API.GetOidcConfigWithResponse(t.Context(), &api.GetOidcConfigParams{OrganizationId: tn.OrgID.String()})+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "reading OIDC config: %s", apierr.Body(res.Body))+ empty := ""+ if res.JSON200.AllowedEmailDomains == nil {+ res.JSON200.AllowedEmailDomains = &empty+ }+ return storedConfig{+ DiscoveryURL: res.JSON200.DiscoveryURL,+ AllowedEmailDomains: res.JSON200.AllowedEmailDomains,+ ConfigurationType: res.JSON200.ConfigurationType,+ ClientId: res.JSON200.ClientId,+ ClientSecret: res.JSON200.ClientSecret,+ IsActive: res.JSON200.IsActive,+ }+}++func requireNoConfig(t *testing.T, tn *harness.Tenant) {+ t.Helper()+ res, err := tn.Admin.API.GetOidcConfigWithResponse(t.Context(), &api.GetOidcConfigParams{OrganizationId: tn.OrgID.String()})+ require.NoError(t, err)+ require.Equalf(t, http.StatusNotFound, res.StatusCode(), "an OIDC config exists: %s", apierr.Body(res.Body))+}diff --git a/tests/suites/sso/oidc/enforcement_test.go b/tests/suites/sso/oidc/enforcement_test.gonew file mode 100644index 0000000000..1128ce7fee--- /dev/null+++ b/tests/suites/sso/oidc/enforcement_test.go@@ -0,0 +1,108 @@+package oidc_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestOIDCEnforcement(t *testing.T) {+ t.Parallel()++ t.Run("should refuse enforcement when nobody has logged in with OIDC yet", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)++ // Action+ res, err := o.Tenant.Admin.API.UpdateOrganizationWithResponse(t.Context(), o.Tenant.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{AuthEnforced: new(true)})++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, string(res.Body), "please log in via OIDC at least once")+ require.False(t, authEnforced(t, o.Tenant))+ })++ t.Run("should enable enforcement when an OIDC login has succeeded", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ signedUp(t, o)++ // Action+ res, err := o.Tenant.Admin.API.UpdateOrganizationWithResponse(t.Context(), o.Tenant.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{AuthEnforced: new(true), BypassOrgAuthEnabled: new(true)})++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.True(t, authEnforced(t, o.Tenant))+ })++ t.Run("should block org resources when a password session is used under enforcement", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ member := o.Tenant.NewUser(t)+ enforce(t, o)++ // Action+ res, err := member.API.GetOrganizationByIdWithResponse(t.Context(), o.Tenant.OrgID.String())++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Contains(t, string(res.Body), "Organization authentication is enforced")+ })++ t.Run("should refuse org selection when a password user logs in under enforcement", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ member := o.Tenant.NewUser(t)+ enforce(t, o)+ login, err := o.Tenant.Anonymous(t).LoginV3WithResponse(t.Context(), api.LoginV3JSONRequestBody{+ Email: member.Email,+ Password: harness.UserPassword,+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, login.StatusCode(), "password login: %s", apierr.Body(login.Body))++ // Action+ res, err := o.Tenant.Client(t, login.JSON200.AccessToken).SelectOrganizationV3WithResponse(t.Context(),+ api.SelectOrganizationV3JSONRequestBody{OrganizationId: o.Tenant.OrgID.String()})++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Contains(t, string(res.Body), "Organization authentication is enforced")+ })++ t.Run("should allow org resources when the session came from OIDC", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ alice := signedUp(t, o)+ sso.Enforce(t, o.Tenant)+ session := o.Session(t, o.Login(t, alice))++ // Action+ res, err := session.GetOrganizationByIdWithResponse(t.Context(), o.Tenant.OrgID.String())++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ })+}diff --git a/tests/suites/sso/oidc/helpers_test.go b/tests/suites/sso/oidc/helpers_test.gonew file mode 100644index 0000000000..18000170a3--- /dev/null+++ b/tests/suites/sso/oidc/helpers_test.go@@ -0,0 +1,81 @@+package oidc_test++import (+ "context"+ "net/http"+ "net/url"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/oidcidp"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func setup(t *testing.T) *sso.OIDC {+ t.Helper()+ return sso.NewOIDC(t, harness.From(t).NewTenant(t))+}++// signedUp logs a new person in through OIDC and completes their signup, leaving an+// accepted member with a verified OIDC account.+func signedUp(t *testing.T, o *sso.OIDC) oidcidp.Person {+ t.Helper()+ person := o.Person()+ login := o.Login(t, person)+ res := o.CompleteSignup(t, login, sso.VerificationCode(t, o.Tenant, person.Email))+ require.Equalf(t, http.StatusOK, res.StatusCode(), "completing SSO signup: %s", apierr.Body(res.Body))+ return person+}++// enforce makes OIDC the org's required login, which needs one OIDC login first.+func enforce(t *testing.T, o *sso.OIDC) {+ t.Helper()+ signedUp(t, o)+ sso.Enforce(t, o.Tenant)+}++// startLogin begins a login the way the login page does and returns the state Infisical+// put on the authorization redirect, with the session cookie it set.+func startLogin(t *testing.T, o *sso.OIDC) (string, []*http.Cookie) {+ t.Helper()+ res, err := o.Browser.RedirectOidcLoginWithResponse(t.Context(), &api.RedirectOidcLoginParams{OrgSlug: new(o.Tenant.OrgSlug)})+ require.NoError(t, err)+ require.Equalf(t, http.StatusFound, res.StatusCode(), "starting OIDC login: %s", apierr.Body(res.Body))+ authorize, err := url.Parse(res.HTTPResponse.Header.Get("Location"))+ require.NoError(t, err)+ state := authorize.Query().Get("state")+ require.NotEmpty(t, state)+ return state, res.HTTPResponse.Cookies()+}++func callback(t *testing.T, o *sso.OIDC, code, state string, cookies []*http.Cookie) *api.OidcCallbackResponse {+ t.Helper()+ res, err := o.Browser.OidcCallbackWithResponse(t.Context(),+ &api.OidcCallbackParams{Code: new(code), State: new(state)},+ func(_ context.Context, req *http.Request) error {+ for _, c := range cookies {+ req.AddCookie(c)+ }+ return nil+ })+ require.NoError(t, err)+ return res+}++func readOrg(t *testing.T, session *api.ClientWithResponses, tn *harness.Tenant) int {+ t.Helper()+ res, err := session.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ return res.StatusCode()+}++func authEnforced(t *testing.T, tn *harness.Tenant) bool {+ t.Helper()+ res, err := tn.Admin.API.GetOrganizationByIdWithResponse(t.Context(), tn.OrgID.String())+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "reading the org: %s", apierr.Body(res.Body))+ return res.JSON200.Organization.AuthEnforced != nil && *res.JSON200.Organization.AuthEnforced+}diff --git a/tests/suites/sso/oidc/login_test.go b/tests/suites/sso/oidc/login_test.gonew file mode 100644index 0000000000..1fa141c22c--- /dev/null+++ b/tests/suites/sso/oidc/login_test.go@@ -0,0 +1,189 @@+package oidc_test++import (+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestOIDCLogin_NewUser(t *testing.T) {+ t.Parallel()++ t.Run("should send the user to SSO signup and mail a code when they log in for the first time", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ alice := o.Person()++ // Action+ res := o.Login(t, alice)++ // Assert+ claims := o.SignupClaims(t, res)+ require.Equal(t, "signupToken", claims["authTokenType"])+ require.Equal(t, "oidc", claims["authMethod"])+ require.Equal(t, alice.Email, claims["email"])+ require.Equal(t, alice.GivenName, claims["firstName"])+ require.Equal(t, alice.FamilyName, claims["lastName"])+ require.Equal(t, o.Tenant.OrgID.String(), claims["organizationId"])+ require.Nil(t, sso.RefreshCookie(res.HTTPResponse))+ require.Len(t, sso.VerificationCode(t, o.Tenant, alice.Email), 6)+ })++ t.Run("should accept the user into the org when signup completes with the mailed code", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ alice := o.Person()+ login := o.Login(t, alice)++ // Action+ res := o.CompleteSignup(t, login, sso.VerificationCode(t, o.Tenant, alice.Email))++ // Assert+ require.Equalf(t, http.StatusOK, res.StatusCode(), "completing SSO signup: %s", apierr.Body(res.Body))+ require.Equal(t, "accepted", fixture.MembershipOf(t, o.Tenant, alice.Email).Status)+ require.Equal(t, http.StatusOK, readOrg(t, o.Session(t, o.Login(t, alice)), o.Tenant))+ })++ t.Run("should keep the user out when signup completes with a wrong code", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ alice := o.Person()+ login := o.Login(t, alice)+ code := sso.VerificationCode(t, o.Tenant, alice.Email)+ wrong := "000000"+ if code == wrong {+ wrong = "111111"+ }++ // Action+ res := o.CompleteSignup(t, login, wrong)++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, string(res.Body), "Invalid token")+ require.Equal(t, "invited", fixture.MembershipOf(t, o.Tenant, alice.Email).Status)+ require.Equal(t, "/signup/sso", o.Redirect(t, o.Login(t, alice)).Path)+ })++ t.Run("should start a session without verification when the org enforces OIDC", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ enforce(t, o)+ alice := o.Person()++ // Action+ res := o.Login(t, alice)++ // Assert+ require.Equal(t, "/login/select-organization", o.Redirect(t, res).Path)+ require.Equal(t, http.StatusOK, readOrg(t, o.Session(t, res), o.Tenant))+ require.Equal(t, "accepted", fixture.MembershipOf(t, o.Tenant, alice.Email).Status)+ })+}++func TestOIDCLogin_ReturningUser(t *testing.T) {+ t.Parallel()++ t.Run("should start a session when a verified user logs in again", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ alice := signedUp(t, o)++ // Action+ res := o.Login(t, alice)++ // Assert+ require.Equal(t, "/login/select-organization", o.Redirect(t, res).Path)+ jid := sso.RefreshCookie(res.HTTPResponse)+ require.NotNil(t, jid)+ require.True(t, jid.HttpOnly)+ require.Equal(t, "/api", jid.Path)+ require.Equal(t, http.StatusOK, readOrg(t, o.Session(t, res), o.Tenant))+ })++ t.Run("should refuse login without a session when the membership is deactivated", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ alice := signedUp(t, o)+ m := fixture.MembershipOf(t, o.Tenant, alice.Email)+ deactivated, err := o.Tenant.Admin.API.UpdateOrgMembershipWithResponse(t.Context(), o.Tenant.OrgID.String(), m.ID.String(),+ api.UpdateOrgMembershipJSONRequestBody{IsActive: new(false)})+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, deactivated.StatusCode(), "deactivating: %s", apierr.Body(deactivated.Body))++ // Action+ res := o.Login(t, alice)++ // Assert+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Contains(t, string(res.Body), "User organization membership is inactive")+ require.Nil(t, sso.RefreshCookie(res.HTTPResponse))+ require.False(t, fixture.MembershipOf(t, o.Tenant, alice.Email).IsActive)+ })+}++func TestOIDCLogin_AllowedEmailDomains(t *testing.T) {+ t.Parallel()++ t.Run("should refuse login without creating the user when the email is outside the allowed domains", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ res, err := o.Tenant.Admin.API.UpdateOidcConfigWithResponse(t.Context(), api.UpdateOidcConfigJSONRequestBody{+ OrganizationId: o.Tenant.OrgID.String(),+ AllowedEmailDomains: new("allowed.test"),+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))+ alice := o.Person()++ // Action+ login := o.Login(t, alice)++ // Assert+ require.Equal(t, http.StatusForbidden, login.StatusCode())+ require.Contains(t, string(login.Body), "Email not allowed.")+ require.Nil(t, sso.RefreshCookie(login.HTTPResponse))+ require.Nil(t, fixture.MembershipOf(t, o.Tenant, alice.Email))+ })++ t.Run("should let the user in when their domain is on the allowed list", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ alice := o.Person()+ _, domain, _ := strings.Cut(alice.Email, "@")+ res, err := o.Tenant.Admin.API.UpdateOidcConfigWithResponse(t.Context(), api.UpdateOidcConfigJSONRequestBody{+ OrganizationId: o.Tenant.OrgID.String(),+ AllowedEmailDomains: new("allowed.test, " + domain),+ })+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))++ // Action+ login := o.Login(t, alice)++ // Assert+ require.Equal(t, alice.Email, o.SignupClaims(t, login)["email"])+ })+}diff --git a/tests/suites/sso/oidc/main_test.go b/tests/suites/sso/oidc/main_test.gonew file mode 100644index 0000000000..0252392791--- /dev/null+++ b/tests/suites/sso/oidc/main_test.go@@ -0,0 +1,9 @@+package oidc_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/harness"+)++func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }diff --git a/tests/suites/sso/oidc/state_test.go b/tests/suites/sso/oidc/state_test.gonew file mode 100644index 0000000000..0bdc6be08d--- /dev/null+++ b/tests/suites/sso/oidc/state_test.go@@ -0,0 +1,104 @@+package oidc_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/sso"+ "github.com/stretchr/testify/require"+)++func TestOIDCState(t *testing.T) {+ t.Parallel()++ t.Run("should refuse the callback without a session when the state was not issued by Infisical", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ _, cookies := startLogin(t, o)+ alice := o.Person()++ // Action+ res := callback(t, o, o.OP.LogIn(t, alice), "forged-state", cookies)++ // Assert+ require.Equal(t, http.StatusFound, res.StatusCode())+ require.Equal(t, "/api/v1/sso/oidc/login/error", res.HTTPResponse.Header.Get("Location"))+ require.Nil(t, sso.RefreshCookie(res.HTTPResponse))+ require.Nil(t, fixture.MembershipOf(t, o.Tenant, alice.Email))+ })++ t.Run("should refuse the callback without a session when a used state is replayed", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ state, cookies := startLogin(t, o)+ first := callback(t, o, o.OP.LogIn(t, o.Person()), state, cookies)+ require.Equalf(t, http.StatusFound, first.StatusCode(), "first callback: %s", first.Body)+ mallory := o.Person()++ // Action+ res := callback(t, o, o.OP.LogIn(t, mallory), state, cookies)++ // Assert+ require.NotEqual(t, http.StatusFound, res.StatusCode())+ require.Nil(t, sso.RefreshCookie(res.HTTPResponse))+ require.Nil(t, fixture.MembershipOf(t, o.Tenant, mallory.Email))+ })++ t.Run("should refuse the callback without a session when the login session cookie is missing", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ state, _ := startLogin(t, o)+ alice := o.Person()++ // Action+ res := callback(t, o, o.OP.LogIn(t, alice), state, nil)++ // Assert+ require.NotEqual(t, http.StatusFound, res.StatusCode())+ require.Nil(t, sso.RefreshCookie(res.HTTPResponse))+ require.Nil(t, fixture.MembershipOf(t, o.Tenant, alice.Email))+ })+}++func TestOIDCState_KnownIssues(t *testing.T) {+ t.Parallel()++ t.Run("should answer a client error rather than 500 when a used state is replayed", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ state, cookies := startLogin(t, o)+ first := callback(t, o, o.OP.LogIn(t, o.Person()), state, cookies)+ require.Equalf(t, http.StatusFound, first.StatusCode(), "first callback: %s", first.Body)++ // Action+ res := callback(t, o, o.OP.LogIn(t, o.Person()), state, cookies)++ // Assert+ require.GreaterOrEqual(t, res.StatusCode(), 400)+ require.Lessf(t, res.StatusCode(), 500, "%s", res.Body)+ })++ t.Run("should answer a client error rather than 500 when the login session cookie is missing", func(t *testing.T) {+ t.Parallel()++ // Setup+ o := setup(t)+ state, _ := startLogin(t, o)++ // Action+ res := callback(t, o, o.OP.LogIn(t, o.Person()), state, nil)++ // Assert+ require.GreaterOrEqual(t, res.StatusCode(), 400)+ require.Lessf(t, res.StatusCode(), 500, "%s", res.Body)+ })+}