Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

tests: federated machine identity auth tests; kubernetes fake answers the attach probe

Claudec8a594da2cad
diff --git a/tests/fakes/kubernetes/controlplane.go b/tests/fakes/kubernetes/controlplane.go
index c3efe2f901..568ad269bc 100644
--- a/tests/fakes/kubernetes/controlplane.go
+++ b/tests/fakes/kubernetes/controlplane.go
@@ -16,7 +16,7 @@ type ControlPlane struct {
// Open mints a reviewer JWT and returns the cluster it reaches.
func Open(tt *testing.T, adminURL string) *ControlPlane {
tt.Helper()
- reviewer := "reviewer-" + id.Nonce()
+ reviewer := id.Nonce() + "-reviewer"
fakenet.Track(tt, adminURL, Service.Host(), reviewer)
return &ControlPlane{Scope: fakenet.Open[Cluster](tt, adminURL, Service.Host(), reviewer), ReviewerJWT: reviewer}
}
diff --git a/tests/fakes/kubernetes/kubernetes.go b/tests/fakes/kubernetes/kubernetes.go
index 6be4d9ce20..37ff1ad02f 100644
--- a/tests/fakes/kubernetes/kubernetes.go
+++ b/tests/fakes/kubernetes/kubernetes.go
@@ -26,8 +26,14 @@ func (s service) Host() string { return s.host }
// URL is what an identity's kubernetesHost is set to.
func (s service) URL() string { return "https://" + s.host }
+// Scope is the reviewer JWT. Attaching Kubernetes auth probes /version with no
+// credential first, which a real API server answers anonymously; it holds no state, so
+// those probes share one scope.
func (service) Scope(r *http.Request) (string, bool) {
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
+ if (!ok || token == "") && r.URL.Path == "/version" {
+ return "anonymous-version", true
+ }
return token, ok && token != ""
}
diff --git a/tests/fixture/user_oauth.go b/tests/fixture/user_oauth.go
new file mode 100644
index 0000000000..f30ce920d5
--- /dev/null
+++ b/tests/fixture/user_oauth.go
@@ -0,0 +1,221 @@
+package fixture
+
+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/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"
+)
+
+// OAuthProvider is one of the OAuth providers Infisical offers as user login.
+type OAuthProvider string
+
+const (
+ OAuthGoogle OAuthProvider = "google"
+ OAuthGitHub OAuthProvider = "github"
+ OAuthGitLab OAuthProvider = "gitlab"
+)
+
+// OAuthPerson 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 OAuthPerson struct {
+ ID int64
+ Email string
+ Verified bool
+}
+
+// NewOAuthPerson is a provider account no other test or run has used, on the tenant's
+// mail domain.
+func NewOAuthPerson(tn *harness.Tenant, verified bool) OAuthPerson {
+ return OAuthPerson{ID: NewOAuthAccountID(), Email: tn.Email("x-" + id.Short()), Verified: verified}
+}
+
+// NewOAuthAccountID is a provider account id no other run has used: Infisical finds a
+// returning provider login by this id across the whole instance. 48 bits, so it stays
+// exact as a JavaScript number.
+func NewOAuthAccountID() int64 {
+ b := make([]byte, 6)
+ _, _ = rand.Read(b)
+ var n int64
+ for _, x := range b {
+ n = n<<8 | int64(x)
+ }
+ return n
+}
+
+// OAuthBrowser is the half of an OAuth login a test drives: Infisical's redirect to the
+// provider, and the provider's redirect back. It keeps what a browser would: the session
+// cookie that carries state and the PKCE verifier, and the state itself.
+type OAuthBrowser struct {
+ IP string
+ Cookies []*http.Cookie
+ State string
+ api *api.ClientWithResponses
+}
+
+type OAuthStartOption func(*oauthStart)
+
+type oauthStart struct {
+ callbackPort *string
+ orgSlug *string
+}
+
+func WithOAuthCallbackPort(p string) OAuthStartOption {
+ return func(s *oauthStart) { s.callbackPort = &p }
+}
+
+// WithOAuthOrgSlug names the organization on the redirect. Only Google takes it.
+func WithOAuthOrgSlug(slug string) OAuthStartOption {
+ return func(s *oauthStart) { s.orgSlug = &slug }
+}
+
+// StartOAuth calls Infisical's redirect route from a fresh address.
+func StartOAuth(tt *testing.T, tn *harness.Tenant, kind OAuthProvider, opts ...OAuthStartOption) *OAuthBrowser {
+ tt.Helper()
+ var p oauthStart
+ for _, o := range opts {
+ o(&p)
+ }
+ b := &OAuthBrowser{IP: oauthIP()}
+ b.api = tn.Anonymous(tt, infisical.ForwardedFor(b.IP), infisical.NoRedirects())
+ ctx := tt.Context()
+
+ var res *http.Response
+ var body []byte
+ switch kind {
+ case OAuthGoogle:
+ r, err := b.api.RedirectGoogleSSOWithResponse(ctx, &api.RedirectGoogleSSOParams{CallbackPort: p.callbackPort, OrgSlug: p.orgSlug})
+ require.NoError(tt, err)
+ res, body = r.HTTPResponse, r.Body
+ case OAuthGitHub:
+ r, err := b.api.RedirectGitHubSSOWithResponse(ctx, &api.RedirectGitHubSSOParams{CallbackPort: p.callbackPort})
+ require.NoError(tt, err)
+ res, body = r.HTTPResponse, r.Body
+ case OAuthGitLab:
+ r, err := b.api.RedirectGitLabSSOWithResponse(ctx, &api.RedirectGitLabSSOParams{CallbackPort: p.callbackPort})
+ require.NoError(tt, err)
+ res, body = r.HTTPResponse, r.Body
+ }
+ require.Equalf(tt, http.StatusFound, res.StatusCode, "starting %s login: %s", kind, apierr.Body(body))
+ loc, err := url.Parse(res.Header.Get("Location"))
+ require.NoError(tt, err)
+ b.State, b.Cookies = loc.Query().Get("state"), res.Cookies()
+ require.NotEmptyf(tt, b.State, "the authorization redirect carries no state: %s", loc)
+ return b
+}
+
+// OAuthResult is Infisical's answer to the provider's redirect.
+type OAuthResult struct {
+ Status int
+ HTTP *http.Response
+ Body []byte
+}
+
+// Redirect is where the callback sent the browser.
+func (r OAuthResult) Redirect(tt *testing.T) *url.URL {
+ tt.Helper()
+ require.Equalf(tt, 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(tt, err)
+ return loc
+}
+
+// Callback is the provider sending the browser back with a code and a state, carrying
+// whichever cookies the test chooses. It returns the transport error rather than failing,
+// so a test can bound a callback that never answers.
+func (b *OAuthBrowser) Callback(ctx context.Context, kind OAuthProvider, code, state string, cookies ...*http.Cookie) (OAuthResult, error) {
+ editor := func(_ context.Context, req *http.Request) error {
+ for _, c := range cookies {
+ req.AddCookie(c)
+ }
+ return nil
+ }
+ switch kind {
+ case OAuthGoogle:
+ r, err := b.api.GoogleLoginCallbackWithResponse(ctx, &api.GoogleLoginCallbackParams{Code: new(code), State: new(state)}, editor)
+ if err != nil {
+ return OAuthResult{}, err
+ }
+ return OAuthResult{r.StatusCode(), r.HTTPResponse, r.Body}, nil
+ case OAuthGitHub:
+ r, err := b.api.GithubLoginCallbackWithResponse(ctx, &api.GithubLoginCallbackParams{Code: new(code), State: new(state)}, editor)
+ if err != nil {
+ return OAuthResult{}, err
+ }
+ return OAuthResult{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 OAuthResult{}, err
+ }
+ return OAuthResult{r.StatusCode(), r.HTTPResponse, r.Body}, nil
+ }
+}
+
+// Finish completes the round trip with the browser's own cookies and state.
+func (b *OAuthBrowser) Finish(tt *testing.T, kind OAuthProvider, cp *oauth.ControlPlane) OAuthResult {
+ tt.Helper()
+ res, err := b.Callback(tt.Context(), kind, cp.Code, b.State, b.Cookies...)
+ require.NoError(tt, err)
+ return res
+}
+
+// OAuthConsent seeds the provider fake with a person who just consented, and returns
+// the code the provider would put on the redirect.
+func OAuthConsent(tt *testing.T, tn *harness.Tenant, kind OAuthProvider, p OAuthPerson) *oauth.ControlPlane {
+ tt.Helper()
+ switch kind {
+ case OAuthGoogle:
+ return oauth.LogIn(tt, FakenetAdmin(tt, tn), oauth.Google, oauth.Profile{
+ Subject: fmt.Sprintf("g-%d", p.ID),
+ Email: p.Email,
+ EmailVerified: p.Verified,
+ GivenName: "Ada",
+ FamilyName: "Lovelace",
+ })
+ case OAuthGitLab:
+ 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(tt, FakenetAdmin(tt, tn), oauth.GitLab, profile)
+ default:
+ return OAuthConsentGitHub(tt, tn, p.ID, githubfake.Email{Email: p.Email, Primary: true, Verified: p.Verified})
+ }
+}
+
+// OAuthConsentGitHub is a GitHub consent with the account's email list spelled out.
+func OAuthConsentGitHub(tt *testing.T, tn *harness.Tenant, accountID int64, emails ...githubfake.Email) *oauth.ControlPlane {
+ tt.Helper()
+ return oauth.LogInGitHub(tt, FakenetAdmin(tt, tn), oauth.GitHubUser{
+ Login: "ada",
+ ID: accountID,
+ Name: "Ada",
+ Emails: emails,
+ })
+}
+
+// OAuthLogin is a whole login: start, consent, callback.
+func OAuthLogin(tt *testing.T, tn *harness.Tenant, kind OAuthProvider, p OAuthPerson, opts ...OAuthStartOption) OAuthResult {
+ tt.Helper()
+ b := StartOAuth(tt, tn, kind, opts...)
+ return b.Finish(tt, kind, OAuthConsent(tt, tn, kind, p))
+}
+
+// oauthIP gives each login its own rate-limit bucket and, to Infisical, its own device.
+func oauthIP() string {
+ b := make([]byte, 3)
+ _, _ = rand.Read(b)
+ return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])
+}
diff --git a/tests/suites/alert/notification_test.go b/tests/suites/alert/notification_test.go
index fb72580c47..148cb8614b 100644
--- a/tests/suites/alert/notification_test.go
+++ b/tests/suites/alert/notification_test.go
@@ -2,13 +2,13 @@ package alert_test
import (
"context"
+ "crypto/rand"
"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"
@@ -27,20 +27,22 @@ 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.Run("should list an unread notification naming the device when a user signs in from a new one", func(t *testing.T) {
t.Parallel()
// Setup
tn := h.NewTenant(t)
- proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ alice := tn.NewUser(t, harness.WithName("alice"))
+ ip := sourceIP()
// Action
- alice := proj.NewUser(t, fixture.WithPrincipalName("alice"))
+ signInFrom(t, tn, alice, ip, "new-laptop")
// Assert
- got := waitForInvitation(t, alice)
- require.Equal(t, "Project Invitation", got.Title)
- require.Contains(t, got.Body, proj.Name)
+ got := waitForDeviceNotice(t, alice, ip)
+ require.Equal(t, "login-from-new-device", got.Type)
+ require.Equal(t, "Login From New Device", got.Title)
+ require.Contains(t, got.Body, "new-laptop")
require.False(t, got.IsRead)
})
@@ -49,11 +51,12 @@ func TestUserNotification(t *testing.T) {
// 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)
+ alice := tn.NewUser(t, harness.WithName("alice"))
+ first, second := sourceIP(), sourceIP()
+ signInFrom(t, tn, alice, first, "laptop")
+ signInFrom(t, tn, alice, second, "phone")
+ waitForDeviceNotice(t, alice, first)
+ waitForDeviceNotice(t, alice, second)
// Action
res, err := alice.API.MarkUserNotificationsAsReadWithResponse(t.Context())
@@ -62,9 +65,9 @@ func TestUserNotification(t *testing.T) {
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)
+ require.GreaterOrEqual(t, len(got), 2)
for _, n := range got {
- require.Truef(t, n.IsRead, "%q is still unread", n.Title)
+ require.Truef(t, n.IsRead, "%q is still unread", n.Body)
}
})
@@ -73,24 +76,23 @@ func TestUserNotification(t *testing.T) {
// 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)
+ alice := tn.NewUser(t, harness.WithName("alice"))
+ first, second := sourceIP(), sourceIP()
+ signInFrom(t, tn, alice, first, "laptop")
+ signInFrom(t, tn, alice, second, "phone")
+ read := waitForDeviceNotice(t, alice, first)
+ unread := waitForDeviceNotice(t, alice, second)
// Action
- res, err := alice.API.UpdateUserNotificationWithResponse(t.Context(), all[0].ID,
+ res, err := alice.API.UpdateUserNotificationWithResponse(t.Context(), read.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)
+ require.True(t, waitForDeviceNotice(t, alice, first).IsRead)
+ require.False(t, waitForDeviceNotice(t, alice, second).IsRead)
+ require.Equal(t, unread.ID, waitForDeviceNotice(t, alice, second).ID)
})
t.Run("should answer 404 and change nothing when a user marks another user's notification read", func(t *testing.T) {
@@ -98,10 +100,11 @@ func TestUserNotification(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
- alice := proj.NewUser(t, fixture.WithPrincipalName("alice"))
+ alice := tn.NewUser(t, harness.WithName("alice"))
bob := tn.NewUser(t, harness.WithName("bob"))
- theirs := waitForInvitation(t, alice)
+ ip := sourceIP()
+ signInFrom(t, tn, alice, ip, "laptop")
+ theirs := waitForDeviceNotice(t, alice, ip)
// Action
res, err := bob.API.UpdateUserNotificationWithResponse(t.Context(), theirs.ID,
@@ -111,7 +114,7 @@ func TestUserNotification(t *testing.T) {
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)
+ require.False(t, waitForDeviceNotice(t, alice, ip).IsRead)
})
t.Run("should answer 404 and keep it when a user deletes another user's notification", func(t *testing.T) {
@@ -119,10 +122,11 @@ func TestUserNotification(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
- alice := proj.NewUser(t, fixture.WithPrincipalName("alice"))
+ alice := tn.NewUser(t, harness.WithName("alice"))
bob := tn.NewUser(t, harness.WithName("bob"))
- theirs := waitForInvitation(t, alice)
+ ip := sourceIP()
+ signInFrom(t, tn, alice, ip, "laptop")
+ theirs := waitForDeviceNotice(t, alice, ip)
// Action
res, err := bob.API.DeleteUserNotificationWithResponse(t.Context(), theirs.ID)
@@ -131,10 +135,31 @@ func TestUserNotification(t *testing.T) {
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)
+ require.Equal(t, theirs.ID, waitForDeviceNotice(t, alice, ip).ID)
})
}
+// signInFrom selects the org from an address and client the user has not used, which
+// is what raises a new-device notification.
+func signInFrom(t *testing.T, tn *harness.Tenant, user *harness.Principal, ip, userAgent string) {
+ t.Helper()
+ res, err := user.API.SelectOrganizationV3WithResponse(t.Context(),
+ api.SelectOrganizationV3JSONRequestBody{OrganizationId: tn.OrgID.String()},
+ func(_ context.Context, req *http.Request) error {
+ req.Header.Set("X-Forwarded-For", ip)
+ req.Header.Set("User-Agent", userAgent)
+ return nil
+ })
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "selecting the org: %s", apierr.Body(res.Body))
+}
+
+func sourceIP() string {
+ b := make([]byte, 3)
+ _, _ = rand.Read(b)
+ return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])
+}
+
func listNotifications(ctx context.Context, user *harness.Principal) ([]notification, error) {
res, err := user.API.ListUserNotificationsWithResponse(ctx)
if err != nil {
@@ -163,30 +188,20 @@ func notifications(t *testing.T, user *harness.Principal) []notification {
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 {
+// waitForDeviceNotice polls for the new-device notification naming an address.
+// Notifications are written from a queue after the response.
+func waitForDeviceNotice(t *testing.T, user *harness.Principal, ip string) 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") {
+ if strings.Contains(n.Body, "**"+ip+"**") {
return n, true, nil
}
}
return notification{}, false, err
})
- require.NoErrorf(t, err, "waiting for a project invitation notification for %s", user.Email)
+ require.NoErrorf(t, err, "waiting for a new-device notification for %s from %s", user.Email, ip)
return got
}
diff --git a/tests/suites/auditlog/access_test.go b/tests/suites/auditlog/access_test.go
index 43686b4a84..1d7718a742 100644
--- a/tests/suites/auditlog/access_test.go
+++ b/tests/suites/auditlog/access_test.go
@@ -50,6 +50,7 @@ func TestAuditLog_Access(t *testing.T) {
orgWide := events(t, tn.Admin, filter{EventType: new("create-secret")})
// Assert
+ t.Logf("PROBE %d %s", byProject.StatusCode(), byProject.Body)
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")
diff --git a/tests/suites/gateway/forwarding_test.go b/tests/suites/gateway/forwarding_test.go
index 4b58e823f5..13616870d8 100644
--- a/tests/suites/gateway/forwarding_test.go
+++ b/tests/suites/gateway/forwarding_test.go
@@ -11,7 +11,6 @@ import (
"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"
@@ -176,33 +175,6 @@ func TestGatewayForwarding_DynamicSecret(t *testing.T) {
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()
@@ -285,3 +257,36 @@ func TestGatewayForwarding_Pool(t *testing.T) {
require.Equal(t, "Gateway pool has no healthy gateways.", apierr.Message(res.Body))
})
}
+
+// Revoking is documented to disconnect the running gateway, but Infisical keeps handing
+// out connection details for it, and the agent keeps proxying on its open tunnel until
+// it notices its own token was refused (about 30 seconds here). Leases issued in that
+// window reach the target through a revoked gateway.
+func TestGatewayForwarding_KnownIssues(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse a lease through a gateway as soon as it 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
+ res := ds.lease(t)
+
+ // Assert
+ if res.StatusCode() == http.StatusOK {
+ username, _ := leasedUsername(t, res)
+ target.DropRoleAtCleanup(t, username)
+ }
+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)
+ })
+}
diff --git a/tests/suites/machineidentity/template_test.go b/tests/suites/machineidentity/template_test.go
new file mode 100644
index 0000000000..2632fc30b7
--- /dev/null
+++ b/tests/suites/machineidentity/template_test.go
@@ -0,0 +1,134 @@
+package machineidentity_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/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"
+ openapi_types "github.com/oapi-codegen/runtime/types"
+ "github.com/stretchr/testify/require"
+)
+
+func TestMachineIdentity_AuthTemplate(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse a template when the plan lacks auth templates", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.MachineIdentityAuthTemplates)))
+
+ // Action
+ res := createOidcTemplate(t, tn, "https://issuer.test")
+
+ // Assert
+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Upgrade plan to access machine identity auth templates")
+ tn.SetPlan(t, license.Enterprise())
+ require.Empty(t, oidcTemplateIDs(t, tn))
+ })
+
+ t.Run("should apply template changes to every identity using it, and report usage", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ created := createOidcTemplate(t, tn, "https://issuer.test")
+ requireStatus(t, http.StatusOK, created.StatusCode(), created.Body)
+ templateID := templateIDOf(t, created.Body)
+ first, second := oidcFromTemplate(t, tn, templateID), oidcFromTemplate(t, tn, templateID)
+
+ // Action
+ res, err := tn.Admin.API.UpdateIdentityAuthTemplateWithBodyWithResponse(t.Context(), templateID.String(), "application/json",
+ jsonBody(t, map[string]any{"templateFields": map[string]any{"boundIssuer": "https://rotated-issuer.test"}}))
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ require.Equal(t, "https://rotated-issuer.test", oidcIssuer(t, tn, first))
+ require.Equal(t, "https://rotated-issuer.test", oidcIssuer(t, tn, second))
+ usage, err := tn.Admin.API.GetIdentityAuthTemplateUsageWithResponse(t.Context(), templateID.String())
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, usage.StatusCode(), usage.Body)
+ used := []string{}
+ for _, u := range *usage.JSON200 {
+ used = append(used, u.IdentityId)
+ }
+ require.ElementsMatch(t, []string{first.String(), second.String()}, used)
+ })
+}
+
+// createOidcTemplate creates an OIDC auth template. The discovery host only has to
+// resolve: nothing logs in through it here.
+func createOidcTemplate(t *testing.T, tn *harness.Tenant, issuer string) *api.CreateIdentityAuthTemplateResponse {
+ t.Helper()
+ res, err := tn.Admin.API.CreateIdentityAuthTemplateWithBodyWithResponse(t.Context(), "application/json", jsonBody(t, map[string]any{
+ "name": "tpl-" + id.Short(),
+ "authMethod": "oidc",
+ "templateFields": map[string]any{
+ "oidcDiscoveryUrl": oidcidp.IssuerURL(id.Nonce()),
+ "boundIssuer": issuer,
+ },
+ }))
+ require.NoError(t, err)
+ return res
+}
+
+func templateIDOf(t *testing.T, body []byte) uuid.UUID {
+ t.Helper()
+ var tpl struct {
+ ID uuid.UUID `json:"id"`
+ }
+ require.NoError(t, json.Unmarshal(body, &tpl))
+ require.NotEqual(t, uuid.Nil, tpl.ID, "template response carried no id: %s", apierr.Body(body))
+ return tpl.ID
+}
+
+func oidcTemplateIDs(t *testing.T, tn *harness.Tenant) []string {
+ t.Helper()
+ res, err := tn.Admin.API.ListIdentityAuthTemplatesWithResponse(t.Context(),
+ &api.ListIdentityAuthTemplatesParams{AuthMethod: api.ListIdentityAuthTemplatesParamsAuthMethod("oidc")})
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ var templates []struct {
+ ID string `json:"id"`
+ }
+ require.NoError(t, json.Unmarshal(res.Body, &templates))
+ ids := []string{}
+ for _, tpl := range templates {
+ ids = append(ids, tpl.ID)
+ }
+ return ids
+}
+
+// oidcFromTemplate creates an identity with OIDC auth linked to the template. A linked
+// identity has to bind a subject of its own.
+func oidcFromTemplate(t *testing.T, tn *harness.Tenant, templateID uuid.UUID) uuid.UUID {
+ t.Helper()
+ identityID := createIdentity(t, tn, api.CreateMachineIdentityJSONRequestBody{})
+ tid := openapi_types.UUID(templateID)
+ res, err := tn.Admin.API.AttachOidcAuthWithResponse(t.Context(), identityID.String(), api.AttachOidcAuthJSONRequestBody{
+ TemplateId: &tid,
+ BoundSubject: new("workload-" + id.Short()),
+ BoundClaims: map[string]string{},
+ })
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ return identityID
+}
+
+func oidcIssuer(t *testing.T, tn *harness.Tenant, identityID uuid.UUID) string {
+ t.Helper()
+ res, err := tn.Admin.API.GetOidcAuthWithResponse(t.Context(), identityID.String())
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "reading OIDC auth returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+ return res.JSON200.IdentityOidcAuth.BoundIssuer
+}
diff --git a/tests/suites/machineidentityfed/kubernetesauth_test.go b/tests/suites/machineidentityfed/kubernetesauth_test.go
index 585b8dde58..5dad2c8688 100644
--- a/tests/suites/machineidentityfed/kubernetesauth_test.go
+++ b/tests/suites/machineidentityfed/kubernetesauth_test.go
@@ -2,7 +2,6 @@ package machineidentityfed_test
import (
"net/http"
- "strings"
"testing"
"github.com/Infisical/infisical/tests/clients/api"
@@ -124,7 +123,6 @@ func TestKubernetesAuth_Attach(t *testing.T) {
// 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")
@@ -169,20 +167,9 @@ func fedAttachKubernetes(t *testing.T, tn *harness.Tenant, identityID uuid.UUID,
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{
diff --git a/tests/suites/suborganization/group_test.go b/tests/suites/suborganization/group_test.go
new file mode 100644
index 0000000000..923ed0406b
--- /dev/null
+++ b/tests/suites/suborganization/group_test.go
@@ -0,0 +1,566 @@
+package suborganization_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/apierr"
+ "github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+func identityPrincipal(ua universalAuth) *harness.Principal {
+ return &harness.Principal{Kind: harness.MachineIdentity, ID: ua.IdentityID, Name: ua.IdentityID.String()}
+}
+
+// scopedMember is a root user who also holds a direct sub-org membership with a role,
+// with a session selected into the sub-org.
+func scopedMember(t *testing.T, sub *fixture.SubOrg, rootRole, subRole string) *harness.Principal {
+ t.Helper()
+ user := sub.Tenant().NewUser(t, harness.OrgRole(rootRole))
+ addToSubOrg(t, sub, user, subRole)
+ return sub.Scope(t, user)
+}
+
+func availableGroupIDs(t *testing.T, client *api.ClientWithResponses) []uuid.UUID {
+ t.Helper()
+ res, err := client.ListAvailableOrganizationGroupsWithResponse(t.Context())
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "listing available groups returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+ out := []uuid.UUID{}
+ for _, g := range res.JSON200.Groups {
+ out = append(out, g.Id)
+ }
+ return out
+}
+
+func membershipIDIn(t *testing.T, client *api.ClientWithResponses, orgID, userID 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))
+ for _, m := range res.JSON200.Users {
+ if m.User.Id == userID {
+ return m.Id
+ }
+ }
+ t.Fatalf("user %s has no membership in %s", userID, orgID)
+ return uuid.Nil
+}
+
+func TestSubOrgGroup_Native(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should let a sub-org create its own group with a name a root group already uses", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ rootGroup := fixture.NewGroup(t, tn)
+
+ // Action
+ res, err := sub.Admin.API.CreateGroupWithResponse(t.Context(), api.CreateGroupJSONRequestBody{Name: rootGroup.Name})
+
+ // Assert
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "answered %d: %s", res.StatusCode(), res.Body)
+ require.Equal(t, sub.ID, res.JSON200.OrgId)
+ require.Equal(t, []uuid.UUID{res.JSON200.Id}, groupIDs(t, sub.Admin.API))
+ require.Equal(t, []uuid.UUID{rootGroup.ID}, groupIDs(t, tn.Admin.API))
+ })
+
+ t.Run("should refuse adding a user to a native sub-org group when they are not a sub-org member", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ rootOnly := tn.NewUser(t)
+ groupID := sub.NewGroup(t, "native")
+
+ // Action
+ res, err := sub.Admin.API.AddUserToGroupWithResponse(t.Context(), groupID.String(), rootOnly.Email)
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "User with id "+rootOnly.ID.String()+" is not part of the organization")
+ require.Empty(t, fixture.GroupUserIDs(t, sub.Admin.API, groupID))
+ })
+}
+
+func TestSubOrgGroup_Link(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should let a linked root group's members select the sub-org with no direct membership", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ member := tn.NewUser(t)
+ group := fixture.NewGroup(t, tn)
+ group.AddUser(t, member)
+
+ // Action
+ res := link(t, sub.Admin.API, group.ID, permanent("member"))
+
+ // Assert
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ scoped := sub.Scope(t, member)
+ require.Contains(t, groupIDs(t, scoped.API), group.ID)
+ require.NotContains(t, memberUserIDs(t, sub.Admin.API, sub.ID), member.ID)
+ })
+
+ t.Run("should let a linked root group's identity log into the sub-org", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ ua := newUniversalAuth(t, tn)
+ group := fixture.NewGroup(t, tn)
+ group.AddIdentity(t, identityPrincipal(ua))
+ sub.LinkGroup(t, group, "member")
+
+ // Action
+ res := ua.login(t, tn, sub.Slug)
+
+ // Assert
+ require.NotNilf(t, res.JSON200, "answered %d: %s", res.StatusCode(), res.Body)
+ require.Contains(t, groupIDs(t, tn.Client(t, res.JSON200.AccessToken)), group.ID)
+ })
+
+ t.Run("should refuse linking from the root org", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ group := fixture.NewGroup(t, tn)
+
+ // Action
+ res := link(t, tn.Admin.API, group.ID, permanent("member"))
+
+ // Assert
+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Organization membership cannot be created for groups in root organization")
+ })
+
+ t.Run("should refuse linking without link-group on the root and link nothing", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ actor := scopedMember(t, sub, "member", "admin")
+ group := fixture.NewGroup(t, tn)
+
+ // Action
+ res := link(t, actor.API, group.ID, permanent("member"))
+
+ // Assert
+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "You are not allowed to link-group on sub-organization")
+ require.NotContains(t, groupIDs(t, sub.Admin.API), group.ID)
+ })
+
+ t.Run("should refuse linking without groups create in the sub-org and link nothing", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ actor := scopedMember(t, sub, "admin", "member")
+ group := fixture.NewGroup(t, tn)
+
+ // Action
+ res := link(t, actor.API, group.ID, permanent("member"))
+
+ // Assert
+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "You are not allowed to create on groups")
+ require.NotContains(t, groupIDs(t, sub.Admin.API), group.ID)
+ })
+
+ t.Run("should answer 404 when linking a sibling sub-org's group", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ mine, sibling := fixture.NewSubOrg(t, tn), fixture.NewSubOrg(t, tn)
+ siblingGroup := sibling.NewGroup(t, "sibling")
+
+ // Action
+ res := link(t, mine.Admin.API, siblingGroup, permanent("member"))
+
+ // Assert
+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Group with ID '"+siblingGroup.String()+"' not found")
+ require.Empty(t, groupIDs(t, mine.Admin.API))
+ })
+
+ t.Run("should answer 404 when linking another root's group", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn, other := h.NewTenant(t), h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ foreign := fixture.NewGroup(t, other)
+
+ // Action
+ res := link(t, sub.Admin.API, foreign.ID, permanent("member"))
+
+ // Assert
+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Group with ID '"+foreign.ID.String()+"' not found")
+ require.Empty(t, groupIDs(t, sub.Admin.API))
+ })
+
+ t.Run("should refuse linking the sub-org's own group", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ own := sub.NewGroup(t, "own")
+
+ // Action
+ res := link(t, sub.Admin.API, own, permanent("member"))
+
+ // Assert
+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Group 'own' belongs to this organization. Only groups from the parent organization can be linked to it.")
+ require.Equal(t, []uuid.UUID{own}, groupIDs(t, sub.Admin.API))
+ })
+
+ t.Run("should refuse linking the same group twice and keep its first role", 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, "member")
+
+ // Action
+ res := link(t, sub.Admin.API, group.ID, permanent("admin"))
+
+ // Assert
+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Group is already a member")
+ require.Equal(t, "member", groupRoleIn(t, sub.Admin.API, group.ID))
+ })
+
+ t.Run("should refuse a link with only temporary roles and link nothing", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ group := fixture.NewGroup(t, tn)
+
+ // Action
+ res := link(t, sub.Admin.API, group.ID, expired("admin"))
+
+ // Assert
+ 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, groupIDs(t, sub.Admin.API), group.ID)
+ })
+
+ t.Run("should keep access from the permanent link role after a temporary one expires", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ member := tn.NewUser(t)
+ group := fixture.NewGroup(t, tn)
+ group.AddUser(t, member)
+
+ // Action
+ res := link(t, sub.Admin.API, group.ID, permanent("member"), expired("admin"))
+
+ // Assert
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ scoped := sub.Scope(t, member)
+ require.Contains(t, groupIDs(t, scoped.API), group.ID)
+ status, body := readConnections(t, scoped.API)
+ requireStatus(t, http.StatusForbidden, status, body)
+ })
+
+ t.Run("should refuse a link role without grant-privileges on groups in the sub-org", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `Under the new privilege system a link role is bounded by grant-privileges on
+ groups, not by comparing it with the actor's own role.`)
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ role, err := sub.Admin.API.CreateOrganizationRoleWithBodyWithResponse(t.Context(), "application/json", jsonBody(t, map[string]any{
+ "slug": "group-linker", "name": "group-linker",
+ "permissions": []fixture.Permission{{Subject: "groups", Action: []string{"read", "create"}}},
+ }))
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, role.StatusCode(), role.Body)
+ actor := scopedMember(t, sub, "admin", "group-linker")
+ group := fixture.NewGroup(t, tn)
+
+ // Action
+ res := link(t, actor.API, group.ID, permanent("admin"))
+
+ // Assert
+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Failed to link group to sub-organization. Permission denied: grant-privileges on groups")
+ require.NotContains(t, groupIDs(t, sub.Admin.API), group.ID)
+ })
+}
+
+func TestSubOrgGroup_Linked(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse managing a linked root group's members from the sub-org, naming the parent", 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, "member")
+
+ // Action
+ res, err := sub.Admin.API.AddUserToGroupWithResponse(t.Context(), group.ID.String(), tn.Admin.Email)
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Group '"+group.Slug+"' is owned by a parent organization. Its members must be managed from that organization.")
+ require.Empty(t, fixture.GroupUserIDs(t, tn.Admin.API, group.ID))
+ })
+
+ t.Run("should refuse renaming a linked group from 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, "member")
+
+ // Action
+ res, err := sub.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), "Cannot update name or slug of a linked group")
+ got, err := tn.Admin.API.GetGroupByIdWithResponse(t.Context(), group.ID.String())
+ require.NoError(t, err)
+ require.NotNil(t, got.JSON200)
+ require.Equal(t, group.Name, got.JSON200.Name)
+ })
+
+ t.Run("should change a linked group's role in the sub-org only", 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, "member")
+
+ // Action
+ res, err := sub.Admin.API.UpdateGroupWithResponse(t.Context(), group.ID.String(), api.UpdateGroupJSONRequestBody{Role: new("admin")})
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ require.Equal(t, "admin", groupRoleIn(t, sub.Admin.API, group.ID))
+ require.Equal(t, "no-access", groupRoleIn(t, tn.Admin.API, group.ID))
+ })
+
+ t.Run("should refuse adding a root group to a sub-org project before it is linked", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ projectID := sub.NewProject(t)
+ group := fixture.NewGroup(t, tn)
+
+ // Action
+ res, err := sub.Admin.API.CreateProjectGroupMembershipWithBodyWithResponse(t.Context(), projectID, group.ID,
+ "application/json", jsonBody(t, map[string]any{"roles": []map[string]any{permanent("viewer")}}))
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Group "+group.ID.String()+" is missing organization membership")
+ require.Empty(t, projectGroupIDs(t, sub.Admin.API, projectID))
+ })
+
+ t.Run("should add a root group to a sub-org project once it is linked", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ projectID := sub.NewProject(t)
+ member := tn.NewUser(t)
+ group := fixture.NewGroup(t, tn)
+ group.AddUser(t, member)
+ sub.LinkGroup(t, group, "member")
+
+ // Action
+ res, err := sub.Admin.API.CreateProjectGroupMembershipWithBodyWithResponse(t.Context(), projectID, group.ID,
+ "application/json", jsonBody(t, map[string]any{"roles": []map[string]any{permanent("viewer")}}))
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ scoped := sub.Scope(t, member)
+ waitForStatus(t, http.StatusOK, func() (int, []byte) { return listSecrets(t, scoped.API, projectID) })
+ })
+
+ t.Run("should list linked root groups in the sub-org and offer only unlinked ones as available", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ linked, unlinked := fixture.NewGroup(t, tn), fixture.NewGroup(t, tn)
+ sub.LinkGroup(t, linked, "member")
+
+ // Action
+ available := availableGroupIDs(t, sub.Admin.API)
+
+ // Assert
+ require.Equal(t, []uuid.UUID{unlinked.ID}, available)
+ require.Equal(t, []uuid.UUID{linked.ID}, groupIDs(t, sub.Admin.API))
+ })
+
+ t.Run("should remove the group's sub-org project access when it is unlinked, and keep the root group", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ projectID := sub.NewProject(t)
+ member := tn.NewUser(t)
+ group := fixture.NewGroup(t, tn)
+ group.AddUser(t, member)
+ sub.LinkGroup(t, group, "member")
+ added, err := sub.Admin.API.CreateProjectGroupMembershipWithBodyWithResponse(t.Context(), projectID, group.ID,
+ "application/json", jsonBody(t, map[string]any{"roles": []map[string]any{permanent("viewer")}}))
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, added.StatusCode(), added.Body)
+
+ // Action
+ res, err := sub.Admin.API.DeleteOrganizationGroupMembershipWithResponse(t.Context(), group.ID)
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ require.NotContains(t, projectGroupIDs(t, sub.Admin.API, projectID), group.ID)
+ require.NotContains(t, groupIDs(t, sub.Admin.API), group.ID)
+ require.Equal(t, []uuid.UUID{member.ID}, fixture.GroupUserIDs(t, tn.Admin.API, group.ID))
+ })
+
+ t.Run("should refuse unlinking from the root and keep the link", 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, "member")
+
+ // Action
+ res, err := tn.Admin.API.DeleteOrganizationGroupMembershipWithResponse(t.Context(), group.ID)
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Parent organization cannot do this operation")
+ require.Contains(t, groupIDs(t, sub.Admin.API), group.ID)
+ })
+
+ t.Run("should refuse unlinking the sub-org's own group and keep it", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ own := sub.NewGroup(t, "own")
+
+ // Action
+ res, err := sub.Admin.API.DeleteOrganizationGroupMembershipWithResponse(t.Context(), own)
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "Group 'own' belongs to this organization and can't be unlinked from it. Delete the group instead.")
+ require.Equal(t, []uuid.UUID{own}, groupIDs(t, sub.Admin.API))
+ })
+
+ t.Run("should unlink rather than delete when a sub-org deletes a linked group, and audit it as an unlink", 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, "member")
+
+ // Action
+ res, err := sub.Admin.API.DeleteGroupWithResponse(t.Context(), group.ID.String())
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ require.NotContains(t, groupIDs(t, sub.Admin.API), group.ID)
+ require.Equal(t, []uuid.UUID{group.ID}, groupIDs(t, tn.Admin.API))
+ event := auditEvent(t, sub.Admin.API, "unlink-group-from-sub-org", func(m map[string]any) bool {
+ return m["groupId"] == group.ID.String()
+ })
+ require.Equal(t, group.Name, event["groupName"])
+ })
+}
+
+func TestSubOrgGroup_KnownIssues(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should keep the user in the root group when they are removed from a sub-org", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `Suspected bug: deleteOrgMembershipsFn (services/org/org-fns.ts) removes the user
+ from every group holding a membership in the org it removes them from, and a linked
+ root group holds one in the sub-org, so the user leaves the root group everywhere.`)
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ member := tn.NewUser(t)
+ group := fixture.NewGroup(t, tn)
+ group.AddUser(t, member)
+ sub.LinkGroup(t, group, "member")
+ addToSubOrg(t, sub, member, "member")
+ membershipID := membershipIDIn(t, sub.Admin.API, sub.ID, member.ID)
+
+ // Action
+ res, err := sub.Admin.API.DeleteOrgMembershipWithResponse(t.Context(), sub.ID.String(), membershipID.String())
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ require.Equal(t, []uuid.UUID{member.ID}, fixture.GroupUserIDs(t, tn.Admin.API, group.ID))
+ })
+}
diff --git a/tests/suites/suborganization/membership_test.go b/tests/suites/suborganization/membership_test.go
new file mode 100644
index 0000000000..60214a4d95
--- /dev/null
+++ b/tests/suites/suborganization/membership_test.go
@@ -0,0 +1,89 @@
+package suborganization_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/harness/infisical"
+ "github.com/google/uuid"
+ openapi_types "github.com/oapi-codegen/runtime/types"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSubOrganization_Membership(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should remove a user from every sub-org and sub-org group when removed from the root", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ first, second := fixture.NewSubOrg(t, tn), fixture.NewSubOrg(t, tn)
+ member := tn.NewUser(t)
+ addToSubOrg(t, first, member, "member")
+ addToSubOrg(t, second, member, "member")
+ groupID := first.NewGroup(t, "native")
+ added, err := first.Admin.API.AddUserToGroupWithResponse(t.Context(), groupID.String(), member.Email)
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, added.StatusCode(), added.Body)
+ membership := fixture.MembershipOf(t, tn, member.Email)
+
+ // Action
+ res, err := tn.Admin.API.DeleteOrgMembershipWithResponse(t.Context(), tn.OrgID.String(), membership.ID.String())
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ require.NotContains(t, memberUserIDs(t, first.Admin.API, first.ID), member.ID)
+ require.NotContains(t, memberUserIDs(t, second.Admin.API, second.ID), member.ID)
+ require.Empty(t, fixture.GroupUserIDs(t, first.Admin.API, groupID))
+ })
+
+ t.Run("should refuse inviting a user who is not in the root org", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ sub := fixture.NewSubOrg(t, tn)
+ admin := tn.Client(t, sub.Admin.Token, infisical.ForwardedFor(sourceIP()))
+
+ // Action
+ res, err := admin.InviteUsersToOrganizationWithResponse(t.Context(), api.InviteUsersToOrganizationJSONRequestBody{
+ InviteeEmails: []openapi_types.Email{openapi_types.Email(tn.Email("stranger"))},
+ OrganizationId: sub.ID.String(),
+ })
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)
+ require.Contains(t, string(res.Body), "doesn't have membership in root organization")
+ require.Equal(t, []uuid.UUID{tn.Admin.ID}, memberUserIDs(t, sub.Admin.API, sub.ID))
+ })
+
+ t.Run("should refuse selecting the sub-org when the root membership is deactivated", 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")
+ membership := fixture.MembershipOf(t, tn, member.Email)
+ deactivated, err := tn.Admin.API.UpdateOrgMembershipWithResponse(t.Context(), tn.OrgID.String(), membership.ID.String(),
+ api.UpdateOrgMembershipJSONRequestBody{IsActive: new(false)})
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, deactivated.StatusCode(), deactivated.Body)
+ 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), "User organization membership is inactive")
+ })
+}
diff --git a/tests/suites/user/isolated/main_test.go b/tests/suites/user/isolated/main_test.go
new file mode 100644
index 0000000000..76f6d4b289
--- /dev/null
+++ b/tests/suites/user/isolated/main_test.go
@@ -0,0 +1,10 @@
+package isolated_test
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/harness"
+)
+
+// Isolated: these tests change instance-wide signup and login method configuration.
+func TestMain(m *testing.M) { harness.Main(m, harness.Isolated) }
diff --git a/tests/suites/user/isolated/oauth_test.go b/tests/suites/user/isolated/oauth_test.go
new file mode 100644
index 0000000000..dcd9617935
--- /dev/null
+++ b/tests/suites/user/isolated/oauth_test.go
@@ -0,0 +1,126 @@
+package isolated_test
+
+import (
+ "bytes"
+ "context"
+ "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/stretchr/testify/require"
+)
+
+func TestOAuth_InstanceSignup(t *testing.T) {
+ h := harness.From(t)
+
+ t.Run("should refuse signup by OAuth when signups are disabled, and create no account", func(t *testing.T) {
+ // Setup
+ tn := h.NewTenant(t)
+ configure(t, h, `{"allowSignUp": false}`, `{"allowSignUp": true}`)
+ p := fixture.NewOAuthPerson(tn, true)
+
+ // Action
+ res := fixture.OAuthLogin(t, tn, fixture.OAuthGitHub, p)
+
+ // Assert
+ require.Equalf(t, http.StatusBadRequest, res.Status, "body: %s", apierr.Body(res.Body))
+ require.Equal(t, "Sign up disabled", apierr.Message(res.Body))
+ require.Nil(t, refreshCookie(res))
+ configure(t, h, `{"allowSignUp": true}`, `{"allowSignUp": true}`)
+ require.Equal(t, "true", fixture.OAuthLogin(t, tn, fixture.OAuthGitHub, p).Redirect(t).Query().Get("signup_completed"))
+ })
+
+ t.Run("should refuse signup by OAuth when the email domain is not allowed", func(t *testing.T) {
+ // Setup
+ tn := h.NewTenant(t)
+ configure(t, h, `{"allowedSignUpDomain": "allowed.test"}`, `{"allowedSignUpDomain": null}`)
+ p := fixture.NewOAuthPerson(tn, true)
+ domain := strings.SplitN(p.Email, "@", 2)[1]
+
+ // Action
+ res := fixture.OAuthLogin(t, tn, fixture.OAuthGitLab, p)
+
+ // Assert
+ require.Equalf(t, http.StatusBadRequest, res.Status, "body: %s", apierr.Body(res.Body))
+ require.Equal(t, "Email with a domain (@"+domain+") is not supported", apierr.Message(res.Body))
+ require.Nil(t, refreshCookie(res))
+ })
+}
+
+func TestOAuth_DisabledProvider(t *testing.T) {
+ h := harness.From(t)
+
+ t.Run("should refuse a provider the admin disabled", func(t *testing.T) {
+ // Setup
+ tn := h.NewTenant(t)
+ member := tn.NewUser(t)
+ disableGitHub(t, h)
+ p := fixture.NewOAuthPerson(tn, true)
+ p.Email = member.Email
+
+ // Action
+ res := fixture.OAuthLogin(t, tn, fixture.OAuthGitHub, p)
+
+ // Assert
+ require.Equalf(t, http.StatusBadRequest, res.Status, "body: %s", apierr.Body(res.Body))
+ require.Equal(t, "Login with Github is disabled by administrator.", apierr.Message(res.Body))
+ require.Nil(t, refreshCookie(res))
+ me, err := member.API.GetCurrentUserWithResponse(t.Context())
+ require.NoError(t, err)
+ require.Equal(t, []string{"email"}, *me.JSON200.User.AuthMethods)
+ })
+
+ t.Run("should let an org admin log in with a provider the admin disabled", func(t *testing.T) {
+ // Setup
+ tn := h.NewTenant(t)
+ disableGitHub(t, h)
+ p := fixture.NewOAuthPerson(tn, true)
+ p.Email = tn.Admin.Email
+
+ // Action
+ res := fixture.OAuthLogin(t, tn, fixture.OAuthGitHub, p)
+
+ // Assert
+ require.Equal(t, "/login/select-organization", res.Redirect(t).Path)
+ require.NotNil(t, refreshCookie(res))
+ })
+}
+
+// configure writes instance configuration as raw JSON, since the typed body cannot send
+// null, and restores it when the test ends.
+func configure(t *testing.T, h *harness.Stack, set, restore string) {
+ t.Helper()
+ admin := h.InstanceAdmin(t)
+ write := func(ctx context.Context, body string) *api.UpdateAdminConfigResponse {
+ res, err := admin.API.UpdateAdminConfigWithBodyWithResponse(ctx, "application/json", bytes.NewReader([]byte(body)))
+ require.NoError(t, err)
+ return res
+ }
+ res := write(t.Context(), set)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "configuring the instance: %s", apierr.Body(res.Body))
+ t.Cleanup(func() {
+ // t.Context is already cancelled when cleanups run.
+ res := write(context.Background(), restore)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "restoring the instance: %s", apierr.Body(res.Body))
+ })
+}
+
+func disableGitHub(t *testing.T, h *harness.Stack) {
+ t.Helper()
+ configure(t, h,
+ `{"enabledLoginMethods": ["email", "google", "gitlab", "saml", "oidc", "ldap"]}`,
+ `{"enabledLoginMethods": ["email", "google", "github", "gitlab", "saml", "oidc", "ldap"]}`)
+}
+
+func refreshCookie(res fixture.OAuthResult) *http.Cookie {
+ for _, c := range res.HTTP.Cookies() {
+ if c.Name == "jid" {
+ return c
+ }
+ }
+ return nil
+}
diff --git a/tests/suites/user/oauth_test.go b/tests/suites/user/oauth_test.go
index e4a57ecbdb..2a767c7c61 100644
--- a/tests/suites/user/oauth_test.go
+++ b/tests/suites/user/oauth_test.go
@@ -29,13 +29,13 @@ func TestOAuth_Signup(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- p := newPerson(tn, true)
+ p := fixture.NewOAuthPerson(tn, true)
// Action
- res := oauthLogin(t, tn, kind, p)
+ res := fixture.OAuthLogin(t, tn, kind, p)
// Assert
- loc := res.redirect(t)
+ 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
@@ -53,13 +53,13 @@ func TestOAuth_Signup(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- p := newPerson(tn, false)
+ p := fixture.NewOAuthPerson(tn, false)
// Action
- res := oauthLogin(t, tn, kind, p)
+ res := fixture.OAuthLogin(t, tn, kind, p)
// Assert
- loc := res.redirect(t)
+ loc := res.Redirect(t)
require.Equal(t, "/signup/sso", loc.Path)
signup := claims(t, loc.Query().Get("token"))
require.Equal(t, "signupToken", signup["authTokenType"])
@@ -77,13 +77,13 @@ func TestOAuth_Signup(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- p := newPerson(tn, false)
+ p := fixture.NewOAuthPerson(tn, false)
// Action
- res := oauthLogin(t, tn, viaGoogle, p)
+ res := fixture.OAuthLogin(t, tn, fixture.OAuthGoogle, p)
// Assert
- require.Equal(t, "/signup/sso", res.redirect(t).Path)
+ require.Equal(t, "/signup/sso", res.Redirect(t).Path)
require.Nil(t, cookieNamed(res.HTTP, "jid"))
})
@@ -95,9 +95,9 @@ func TestOAuth_Signup(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- p := newPerson(tn, false)
- first := oauthLogin(t, tn, kind, p)
- require.Equal(t, "/signup/sso", first.redirect(t).Path)
+ p := fixture.NewOAuthPerson(tn, false)
+ first := fixture.OAuthLogin(t, tn, kind, p)
+ require.Equal(t, "/signup/sso", first.Redirect(t).Path)
mailed := sso.VerificationCode(t, tn, p.Email)
// Action
@@ -108,8 +108,8 @@ func TestOAuth_Signup(t *testing.T) {
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)
+ again := fixture.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)
})
}
@@ -124,11 +124,11 @@ func TestOAuth_Signup(t *testing.T) {
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(),
+ withPrimary := fixture.StartOAuth(t, tn, fixture.OAuthGitHub).Finish(t, fixture.OAuthGitHub, fixture.OAuthConsentGitHub(t, tn, fixture.NewOAuthAccountID(),
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(),
+ withoutPrimary := fixture.StartOAuth(t, tn, fixture.OAuthGitHub).Finish(t, fixture.OAuthGitHub, fixture.OAuthConsentGitHub(t, tn, fixture.NewOAuthAccountID(),
githubfake.Email{Email: unverifiedPrimary, Primary: true},
githubfake.Email{Email: verified, Verified: true},
))
@@ -152,14 +152,14 @@ func TestOAuth_ExistingAccount(t *testing.T) {
// Setup
tn := h.NewTenant(t)
alice := tn.NewUser(t)
- p := newPerson(tn, true)
+ p := fixture.NewOAuthPerson(tn, true)
p.Email = alice.Email
// Action
- res := oauthLogin(t, tn, kind, p)
+ res := fixture.OAuthLogin(t, tn, kind, p)
// Assert
- require.Equal(t, "/login/select-organization", res.redirect(t).Path)
+ 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")
@@ -177,14 +177,14 @@ func TestOAuth_ExistingAccount(t *testing.T) {
// Setup
tn := h.NewTenant(t)
alice := tn.NewUser(t)
- p := newPerson(tn, false)
+ p := fixture.NewOAuthPerson(tn, false)
p.Email = alice.Email
// Action
- res := oauthLogin(t, tn, kind, p)
+ res := fixture.OAuthLogin(t, tn, kind, p)
// Assert
- require.Equal(t, "/signup/sso", res.redirect(t).Path)
+ 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)
@@ -202,15 +202,15 @@ func TestOAuth_ExistingAccount(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- p := newPerson(tn, true)
- before := accountOf(t, tn, oauthLogin(t, tn, kind, p)).JSON200.User
+ p := fixture.NewOAuthPerson(tn, true)
+ before := accountOf(t, tn, fixture.OAuthLogin(t, tn, kind, p)).JSON200.User
p.Email = tn.Email("renamed-" + id.Short())
// Action
- res := oauthLogin(t, tn, kind, p)
+ res := fixture.OAuthLogin(t, tn, kind, p)
// Assert
- require.Equal(t, "/login/select-organization", res.redirect(t).Path)
+ 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)
@@ -228,20 +228,20 @@ func TestOAuth_ExistingAccount(t *testing.T) {
// Setup
tn := h.NewTenant(t)
bob := tn.NewUser(t)
- p := newPerson(tn, true)
+ p := fixture.NewOAuthPerson(tn, true)
original := p.Email
- before := accountOf(t, tn, oauthLogin(t, tn, kind, p)).JSON200.User
+ before := accountOf(t, tn, fixture.OAuthLogin(t, tn, kind, p)).JSON200.User
p.Email = bob.Email
// Action
- res := oauthLogin(t, tn, kind, p)
+ res := fixture.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
+ after := accountOf(t, tn, fixture.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())
@@ -264,18 +264,18 @@ func TestOAuth_Callback(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- p := newPerson(tn, true)
- b := startOAuth(t, tn, kind)
- cp := consent(t, tn, kind, p)
+ p := fixture.NewOAuthPerson(tn, true)
+ b := fixture.StartOAuth(t, tn, kind)
+ cp := fixture.OAuthConsent(t, tn, kind, p)
// Action
- res, err := b.callback(t.Context(), kind, cp.Code, "forged-"+id.Short(), b.cookies...)
+ 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"))
+ require.Equal(t, "true", fixture.OAuthLogin(t, tn, kind, p).Redirect(t).Query().Get("signup_completed"))
})
}
})
@@ -288,18 +288,18 @@ func TestOAuth_Callback(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- p := newPerson(tn, true)
- b := startOAuth(t, tn, kind)
- cp := consent(t, tn, kind, p)
+ p := fixture.NewOAuthPerson(tn, true)
+ b := fixture.StartOAuth(t, tn, kind)
+ cp := fixture.OAuthConsent(t, tn, kind, p)
// Action
- res, err := b.callback(t.Context(), kind, cp.Code, b.state)
+ 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"))
+ require.Equal(t, "true", fixture.OAuthLogin(t, tn, kind, p).Redirect(t).Query().Get("signup_completed"))
})
}
})
@@ -312,13 +312,13 @@ func TestOAuth_Callback(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- p := newPerson(tn, true)
+ p := fixture.NewOAuthPerson(tn, true)
// Action
- res := oauthLogin(t, tn, kind, p, withCallbackPort("5555"))
+ res := fixture.OAuthLogin(t, tn, kind, p, fixture.WithOAuthCallbackPort("5555"))
// Assert
- loc := res.redirect(t)
+ loc := res.Redirect(t)
require.Equal(t, "/login/select-organization", loc.Path)
require.Equal(t, "5555", loc.Query().Get("callback_port"))
})
@@ -339,14 +339,14 @@ func TestOAuth_Google(t *testing.T) {
other := h.NewTenant(t)
alice := tn.NewUser(t)
invite(t, other, alice.Email)
- p := newPerson(tn, true)
+ p := fixture.NewOAuthPerson(tn, true)
p.Email = alice.Email
// Action
- res := oauthLogin(t, tn, viaGoogle, p, withOrgSlug(other.OrgSlug))
+ res := fixture.OAuthLogin(t, tn, fixture.OAuthGoogle, p, fixture.WithOAuthOrgSlug(other.OrgSlug))
// Assert
- require.Equal(t, "/login/select-organization", res.redirect(t).Path)
+ require.Equal(t, "/login/select-organization", res.Redirect(t).Path)
require.Equal(t, "accepted", fixture.MembershipOf(t, other, alice.Email).Status)
})
@@ -357,9 +357,9 @@ func TestOAuth_Google(t *testing.T) {
// Setup
tn := h.NewTenant(t)
alice := tn.NewUser(t)
- p := newPerson(tn, true)
+ p := fixture.NewOAuthPerson(tn, true)
p.Email = alice.Email
- google := sessionFrom(t, tn, oauthLogin(t, tn, viaGoogle, p))
+ google := sessionFrom(t, tn, fixture.OAuthLogin(t, tn, fixture.OAuthGoogle, 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)})
@@ -367,12 +367,12 @@ func TestOAuth_Google(t *testing.T) {
// 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())
+ googleAgain := selectOrg(t, tn, sessionFrom(t, tn, fixture.OAuthLogin(t, tn, fixture.OAuthGoogle, 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))
+ require.Equalf(t, http.StatusOK, googleAgain.StatusCode(), "selecting with Google: %s", apierr.Body(googleAgain.Body))
})
}
@@ -385,13 +385,13 @@ func TestOAuth_KnownIssues(t *testing.T) {
// Setup
tn := h.NewTenant(t)
- b := startOAuth(t, tn, viaGitHub)
- cp := consentGitHub(t, tn, newAccountID())
+ b := fixture.StartOAuth(t, tn, fixture.OAuthGitHub)
+ cp := fixture.OAuthConsentGitHub(t, tn, fixture.NewOAuthAccountID())
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
// Action
- res, err := b.callback(ctx, viaGitHub, cp.Code, b.state, b.cookies...)
+ res, err := b.Callback(ctx, fixture.OAuthGitHub, cp.Code, b.State, b.Cookies...)
// Assert
require.NoError(t, err, "the callback never answered")
@@ -399,15 +399,3 @@ func TestOAuth_KnownIssues(t *testing.T) {
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.go
index 44500c3257..1c368c9f43 100644
--- a/tests/suites/user/oauthflow_test.go
+++ b/tests/suites/user/oauthflow_test.go
@@ -1,39 +1,23 @@
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}
+var providers = []fixture.OAuthProvider{fixture.OAuthGitHub, fixture.OAuthGitLab}
func skipUntilGoogleFakeAttributesQueryToken(t *testing.T) {
t.Helper()
@@ -41,184 +25,11 @@ func skipUntilGoogleFakeAttributesQueryToken(t *testing.T) {
"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 {
+func accountOf(t *testing.T, tn *harness.Tenant, res fixture.OAuthResult) *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())
+ s := sessionFrom(t, tn, res)
+ me, err := s.API.GetCurrentUserV1WithResponse(t.Context())
require.NoError(t, err)
require.Equalf(t, http.StatusOK, me.StatusCode(), "reading the account: %s", apierr.Body(me.Body))
return me
@@ -226,7 +37,7 @@ func accountOf(t *testing.T, tn *harness.Tenant, res callbackResult) *api.GetCur
// 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 {
+func sessionFrom(t *testing.T, tn *harness.Tenant, res fixture.OAuthResult) session {
t.Helper()
jid := cookieNamed(res.HTTP, "jid")
require.NotNil(t, jid, "the login set no refresh cookie")
@@ -235,3 +46,15 @@ func sessionFrom(t *testing.T, tn *harness.Tenant, res callbackResult) session {
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)}
}
+
+// 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 fixture.OAuthResult) {
+ 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)
+}