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
test(e2e): cover dynamic secrets and secret rotations on a postgres target
varonix733ffc811f69
diff --git a/tests/fixture/appconnection_postgres.go b/tests/fixture/appconnection_postgres.gonew file mode 100644index 0000000000..3586d02908--- /dev/null+++ b/tests/fixture/appconnection_postgres.go@@ -0,0 +1,55 @@+package fixture++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/google/uuid"+)++// PostgresAppConnection is a PostgreSQL App Connection over username and password, as+// the target's superuser.+//+// A function rather than a variable because the host is the target container, not a+// hostname a client hardcodes: there is no fake in between, and Infisical dials the+// database itself.+func PostgresAppConnection(target *PostgresTarget) AppConnectionKind {+ return AppConnectionKind{+ App: "postgres",+ Host: target.Host,+ create: func(ctx context.Context, c *api.ClientWithResponses, name, _ string) (uuid.UUID, error) {+ raw, err := json.Marshal(map[string]any{+ "name": name,+ "method": "username-and-password",+ "credentials": map[string]any{+ "host": target.Host,+ "port": target.Port,+ "database": target.Database,+ "username": target.User,+ "password": target.Password,+ "sslEnabled": false,+ "sslRejectUnauthorized": false,+ },+ })+ if err != nil {+ return uuid.Nil, err+ }+ res, err := c.CreatePostgresAppConnectionWithBodyWithResponse(ctx, "application/json", bytes.NewReader(raw))+ if err != nil {+ return uuid.Nil, err+ }+ var out struct {+ AppConnection struct {+ ID uuid.UUID `json:"id"`+ } `json:"appConnection"`+ }+ if res.StatusCode() != 200 || json.Unmarshal(res.Body, &out) != nil || out.AppConnection.ID == uuid.Nil {+ return uuid.Nil, fmt.Errorf("creating the connection returned %d: %s", res.StatusCode(), res.Body)+ }+ return out.AppConnection.ID, nil+ },+ }+}diff --git a/tests/fixture/postgres_target.go b/tests/fixture/postgres_target.gonew file mode 100644index 0000000000..d35bb0c7df--- /dev/null+++ b/tests/fixture/postgres_target.go@@ -0,0 +1,144 @@+package fixture++import (+ "context"+ "fmt"+ "net/url"+ "testing"++ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra"+ "github.com/Infisical/infisical/tests/infra/postgres"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/jackc/pgx/v5"+ "github.com/stretchr/testify/require"+)++// PostgresTargetInstance names the target database in TestMain:+//+// harness.Main(m, harness.Shared, harness.WithInfra(postgres.Module(postgres.Named(fixture.PostgresTargetInstance))))+//+// It has to be a second instance. Infisical refuses its own database host as a target.+const PostgresTargetInstance = "target"++// PostgresTarget is a database Infisical manages credentials on: the one a rotation+// rotates or a dynamic secret leases roles in. Every package that declares it shares+// the one container, so tests stay apart by role name, never by database.+type PostgresTarget struct {+ // Host, Port and Database are what Infisical dials, on the container network.+ Host string+ Port int+ Database string++ // User and Password are the superuser, for an App Connection or a provider+ // configuration that has to create and alter roles.+ User string+ Password string++ external string+}++// OpenPostgresTarget returns the package's target database.+func OpenPostgresTarget(tt *testing.T, tn *harness.Tenant) *PostgresTarget {+ tt.Helper()+ h := tn.Module(tt, postgres.Key+":"+PostgresTargetInstance,+ fmt.Sprintf("harness.WithInfra(postgres.Module(postgres.Named(%q)))", PostgresTargetInstance)).(*postgres.Handle)++ u, err := url.Parse(h.DSN(infra.Internal))+ require.NoError(tt, err)+ pw, _ := u.User.Password()+ in := h.Endpoint(infra.Internal)+ return &PostgresTarget{+ Host: in.Host,+ Port: in.Port,+ Database: h.Database(),+ User: u.User.Username(),+ Password: pw,+ external: h.DSN(infra.External),+ }+}++// NewRole creates a role that can log in, named uniquely so parallel tests never share+// one, and drops it when the test ends.+func (p *PostgresTarget) NewRole(tt *testing.T) (name, password string) {+ tt.Helper()+ name = "r_" + id.Short() + id.Short()+ password = "pw_" + id.Nonce()+ p.exec(tt, fmt.Sprintf(`CREATE ROLE %s WITH LOGIN PASSWORD '%s'`, pgx.Identifier{name}.Sanitize(), password))+ p.DropRoleAtCleanup(tt, name)+ return name, password+}++// DropRoleAtCleanup drops a role Infisical created, such as a lease the test leaves+// behind on purpose.+func (p *PostgresTarget) DropRoleAtCleanup(tt *testing.T, name string) {+ tt.Helper()+ tt.Cleanup(func() {+ ctx := context.WithoutCancel(tt.Context())+ conn, err := pgx.Connect(ctx, p.external)+ if err != nil {+ return+ }+ defer func() { _ = conn.Close(ctx) }()+ _, _ = conn.Exec(ctx, "DROP ROLE IF EXISTS "+pgx.Identifier{name}.Sanitize())+ })+}++// DropRole removes a role behind Infisical's back.+func (p *PostgresTarget) DropRole(tt *testing.T, name string) {+ tt.Helper()+ p.exec(tt, "DROP ROLE "+pgx.Identifier{name}.Sanitize())+}++// SetPassword changes a role's password behind Infisical's back, which is how a+// credential gets revoked out of band.+func (p *PostgresTarget) SetPassword(tt *testing.T, name, password string) {+ tt.Helper()+ p.exec(tt, fmt.Sprintf(`ALTER ROLE %s WITH PASSWORD '%s'`, pgx.Identifier{name}.Sanitize(), password))+}++// RoleExists reports whether the role is present on the target.+func (p *PostgresTarget) RoleExists(tt *testing.T, name string) bool {+ tt.Helper()+ conn := p.connect(tt)+ defer p.close(tt, conn)+ var exists bool+ require.NoError(tt, conn.QueryRow(tt.Context(),+ "SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = $1)", name).Scan(&exists))+ return exists+}++// Login connects as a role and returns why it could not, or nil when it could. The+// proof a published credential works is that it logs in.+func (p *PostgresTarget) Login(tt *testing.T, name, password string) error {+ tt.Helper()+ u, err := url.Parse(p.external)+ require.NoError(tt, err)+ u.User = url.UserPassword(name, password)+ conn, err := pgx.Connect(tt.Context(), u.String())+ if err != nil {+ return err+ }+ return conn.Close(context.WithoutCancel(tt.Context()))+}++func (p *PostgresTarget) exec(tt *testing.T, sql string) {+ tt.Helper()+ conn := p.connect(tt)+ defer p.close(tt, conn)+ _, err := conn.Exec(tt.Context(), sql)+ require.NoErrorf(tt, err, "running %q on the target database", sql)+}++func (p *PostgresTarget) connect(tt *testing.T) *pgx.Conn {+ tt.Helper()+ conn, err := pgx.Connect(tt.Context(), p.external)+ require.NoError(tt, err, "connecting to the target database")+ return conn+}++// close is per call rather than at cleanup: every package shares the one target, and+// parallel tests holding their connections would run it out of slots.+func (p *PostgresTarget) close(tt *testing.T, conn *pgx.Conn) {+ _ = conn.Close(context.WithoutCancel(tt.Context()))+}diff --git a/tests/go.mod b/tests/go.modindex 7be8d88b36..1437ec4ff6 100644--- a/tests/go.mod+++ b/tests/go.mod@@ -5,6 +5,7 @@ go 1.27.0require (github.com/beevik/etree v1.8.1github.com/google/uuid v1.6.0+ github.com/jackc/pgx/v5 v5.9.2github.com/moby/moby/api v1.55.0github.com/mocktools/go-smtp-mock/v2 v2.5.4github.com/oapi-codegen/runtime v1.7.0@@ -40,6 +41,8 @@ require (github.com/go-ole/go-ole v1.3.0 // indirectgithub.com/go-openapi/jsonpointer v0.23.1 // indirectgithub.com/go-openapi/swag/jsonname v0.26.0 // indirect+ github.com/jackc/pgpassfile v1.0.0 // indirect+ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirectgithub.com/jonboulle/clockwork v0.5.0 // indirectgithub.com/klauspost/compress v1.18.6 // indirectgithub.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirectdiff --git a/tests/go.sum b/tests/go.sumindex ff572edd45..2d3c8abfc2 100644--- a/tests/go.sum+++ b/tests/go.sum@@ -92,6 +92,12 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=+github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=+github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=+github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=+github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I=github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE=@@ -185,6 +191,7 @@ github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+Qgithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI=diff --git a/tests/suites/secretmanager/dynamicsecrets/config_test.go b/tests/suites/secretmanager/dynamicsecrets/config_test.gonew file mode 100644index 0000000000..fee0b4d6ec--- /dev/null+++ b/tests/suites/secretmanager/dynamicsecrets/config_test.go@@ -0,0 +1,163 @@+package dynamicsecrets_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++func TestDynamicSecret_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should issue a code from the configured secret when a totp dynamic secret is leased", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider())++ // Action+ l := ds.lease(t, nil, "")++ // Assert+ require.Contains(t, totpCodes(t, totpSecret), l.Data["TOTP"])+ require.Equal(t, []string{l.ID}, ds.leaseIDs(t))+ })++ t.Run("should refuse and keep the original when the same name is created twice in a folder", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider(), defaultTTL("1h"))++ // Action+ res, _ := createDynamicSecret(t, tn.Admin.API, proj, totpProvider(), named(ds.Name), defaultTTL("2h"))++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "already exists under the folder")+ got := ds.get(t, tn.Admin.API)+ require.NotNil(t, got.JSON200)+ require.Equal(t, "1h", got.JSON200.DynamicSecret.DefaultTTL)+ })++ t.Run("should refuse naming the path when the folder does not exist", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))++ // Action+ res, _ := createDynamicSecret(t, tn.Admin.API, proj, totpProvider(), atPath("/missing"))++ // Assert+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "/missing")+ require.Empty(t, names(t, proj, "/"))+ })++ t.Run("should refuse and create nothing when both a gateway and a gateway pool are set", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ inputs := postgresInputs(target)+ inputs["gatewayId"] = uuid.NewString()+ inputs["gatewayPoolId"] = uuid.NewString()++ // Action+ res, _ := createDynamicSecret(t, tn.Admin.API, proj, provider{"type": "sql-database", "inputs": inputs})++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "Cannot specify both a gateway and a gateway pool")+ require.Empty(t, names(t, proj, "/"))+ })++ t.Run("should refuse naming the gateway and create nothing when the gateway does not exist", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ gatewayID := uuid.NewString()+ inputs := postgresInputs(target)+ inputs["gatewayId"] = gatewayID++ // Action+ res, _ := createDynamicSecret(t, tn.Admin.API, proj, provider{"type": "sql-database", "inputs": inputs})++ // Assert+ requireStatus(t, http.StatusNotFound, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), gatewayID)+ require.Empty(t, names(t, proj, "/"))+ })++ t.Run("should refuse and create nothing when the username template uses an unknown variable", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))++ // Action+ res, _ := createDynamicSecret(t, tn.Admin.API, proj, totpProvider(), usernameTemplate("{{identity.email}}"))++ // Assert+ requireStatus(t, http.StatusUnprocessableEntity, res.StatusCode(), res.Body)+ require.Empty(t, names(t, proj, "/"))+ })+}++func TestDynamicSecret_Inputs(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should leave the private key out of a read", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, sshProvider())++ // Action+ in := ds.inputs(t)++ // Assert+ require.NotContains(t, in, "caPrivateKey")+ require.NotEmpty(t, in["caPublicKey"], "the read does not carry the public half either: %v", in)+ })++ t.Run("should keep the stored private key when an update leaves it out", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, sshProvider())+ before := ds.inputs(t)["caPublicKey"]++ // Action+ res := ds.update(t, map[string]any{"inputs": map[string]any{"principals": []string{"deploy", "ops"}}})++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ after := ds.inputs(t)+ require.Equal(t, before, after["caPublicKey"], "the CA was replaced, so the stored private key was lost")+ require.Equal(t, []any{"deploy", "ops"}, after["principals"])+ })+}diff --git a/tests/suites/secretmanager/dynamicsecrets/delete_test.go b/tests/suites/secretmanager/dynamicsecrets/delete_test.gonew file mode 100644index 0000000000..a4be52b135--- /dev/null+++ b/tests/suites/secretmanager/dynamicsecrets/delete_test.go@@ -0,0 +1,78 @@+package dynamicsecrets_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/stretchr/testify/require"+)++func TestDynamicSecret_Delete(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should remove the dynamic secret at once when it has no leases", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider())++ // Action+ res := ds.delete(t, false)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, http.StatusNotFound, ds.get(t, tn.Admin.API).StatusCode())+ })++ t.Run("should revoke every lease at the provider and then remove the dynamic secret when it has leases", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, postgresProvider(target))+ first, _ := credentials(t, ds.lease(t, nil, ""))+ second, _ := credentials(t, ds.lease(t, nil, ""))+ target.DropRoleAtCleanup(t, first)+ target.DropRoleAtCleanup(t, second)++ // Action+ res := ds.delete(t, false)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, "Revocation in process", *res.JSON200.DynamicSecret.Status)+ wait.Until(t, "the dynamic secret to be removed", func() bool {+ return ds.get(t, tn.Admin.API).StatusCode() == http.StatusNotFound+ })+ require.False(t, target.RoleExists(t, first), "the first lease's role is still on the database")+ require.False(t, target.RoleExists(t, second), "the second lease's role is still on the database")+ })++ t.Run("should remove the dynamic secret at once and leave the leased roles when the delete is forced", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, postgresProvider(target))+ username, password := credentials(t, ds.lease(t, nil, ""))+ target.DropRoleAtCleanup(t, username)++ // Action+ res := ds.delete(t, true)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, http.StatusNotFound, ds.get(t, tn.Admin.API).StatusCode())+ require.NoError(t, target.Login(t, username, password), "a forced delete revoked the lease at the provider")+ })+}diff --git a/tests/suites/secretmanager/dynamicsecrets/helpers_test.go b/tests/suites/secretmanager/dynamicsecrets/helpers_test.gonew file mode 100644index 0000000000..448fe4ad21--- /dev/null+++ b/tests/suites/secretmanager/dynamicsecrets/helpers_test.go@@ -0,0 +1,300 @@+package dynamicsecrets_test++import (+ "bytes"+ "crypto/hmac"+ "crypto/sha1"+ "encoding/base32"+ "encoding/binary"+ "encoding/json"+ "fmt"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/stretchr/testify/require"+)++// Suite-local until a second package creates a dynamic secret; then it moves to+// fixture/secretmanager.++const totpSecret = "JBSWY3DPEHPK3PXP"++type provider map[string]any++func totpProvider() provider {+ return provider{"type": "totp", "inputs": map[string]any{"configType": "manual", "secret": totpSecret}}+}++// The statements quote the name so a generated name with a hyphen is one identifier. The+// revocation has no IF EXISTS on purpose: a role dropped behind Infisical's back then+// fails the revoke, which is how a test makes one fail.+func postgresInputs(target *fixture.PostgresTarget) map[string]any {+ return map[string]any{+ "client": "postgres",+ "host": target.Host,+ "port": target.Port,+ "database": target.Database,+ "username": target.User,+ "password": target.Password,+ "creationStatement": `CREATE ROLE "{{username}}" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';`,+ "revocationStatement": `DROP ROLE "{{username}}";`,+ }+}++func postgresProvider(target *fixture.PostgresTarget) provider {+ return provider{"type": "sql-database", "inputs": postgresInputs(target)}+}++func sshProvider() provider {+ return provider{"type": "ssh", "inputs": map[string]any{"principals": []string{"deploy"}}}+}++type dsConfig struct {+ name string+ env string+ path string+ defaultTTL string+ maxTTL string+ usernameTemplate string+ metadata map[string]string+}++type dsOption func(*dsConfig)++func atPath(p string) dsOption { return func(c *dsConfig) { c.path = p } }+func defaultTTL(ttl string) dsOption { return func(c *dsConfig) { c.defaultTTL = ttl } }+func maxTTL(ttl string) dsOption { return func(c *dsConfig) { c.maxTTL = ttl } }+func usernameTemplate(t string) dsOption { return func(c *dsConfig) { c.usernameTemplate = t } }+func named(n string) dsOption { return func(c *dsConfig) { c.name = n } }++func withMetadata(key, value string) dsOption {+ return func(c *dsConfig) {+ if c.metadata == nil {+ c.metadata = map[string]string{}+ }+ c.metadata[key] = value+ }+}++type dynamicSecret struct {+ ID string+ Name string+ env string+ path string+ proj *fixture.Project+}++func newConfig(opts []dsOption) dsConfig {+ cfg := dsConfig{name: "ds-" + id.Short(), env: "dev", path: "/", defaultTTL: "1h"}+ for _, o := range opts {+ o(&cfg)+ }+ return cfg+}++// createDynamicSecret sends the create as raw JSON: the provider is a union, which+// the generated body type cannot marshal (docs/client.md).+func createDynamicSecret(tt *testing.T, c *api.ClientWithResponses, p *fixture.Project, prov provider,+ opts ...dsOption) (*api.CreateDynamicSecretResponse, dsConfig) {+ tt.Helper()+ cfg := newConfig(opts)+ body := map[string]any{+ "projectSlug": p.Slug,+ "environmentSlug": cfg.env,+ "path": cfg.path,+ "name": cfg.name,+ "provider": prov,+ "defaultTTL": cfg.defaultTTL,+ }+ if cfg.maxTTL != "" {+ body["maxTTL"] = cfg.maxTTL+ }+ if cfg.usernameTemplate != "" {+ body["usernameTemplate"] = cfg.usernameTemplate+ }+ if len(cfg.metadata) > 0 {+ var md []map[string]string+ for k, v := range cfg.metadata {+ md = append(md, map[string]string{"key": k, "value": v})+ }+ body["metadata"] = md+ }+ raw, err := json.Marshal(body)+ require.NoError(tt, err)+ res, err := c.CreateDynamicSecretWithBodyWithResponse(tt.Context(), "application/json", bytes.NewReader(raw))+ require.NoError(tt, err, "creating a dynamic secret")+ return res, cfg+}++func newDynamicSecret(tt *testing.T, p *fixture.Project, prov provider, opts ...dsOption) *dynamicSecret {+ tt.Helper()+ res, cfg := createDynamicSecret(tt, p.Tenant().Admin.API, p, prov, opts...)+ require.NotNilf(tt, res.JSON200, "creating a dynamic secret returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return &dynamicSecret{ID: res.JSON200.DynamicSecret.Id.String(), Name: cfg.name, env: cfg.env, path: cfg.path, proj: p}+}++func (d *dynamicSecret) get(tt *testing.T, c *api.ClientWithResponses) *api.GetDynamicSecretResponse {+ tt.Helper()+ res, err := c.GetDynamicSecretWithResponse(tt.Context(), d.Name, &api.GetDynamicSecretParams{+ ProjectSlug: d.proj.Slug, EnvironmentSlug: d.env, Path: &d.path,+ })+ require.NoError(tt, err, "getting a dynamic secret")+ return res+}++func (d *dynamicSecret) inputs(tt *testing.T) map[string]any {+ tt.Helper()+ res := d.get(tt, d.proj.Tenant().Admin.API)+ require.NotNilf(tt, res.JSON200, "getting a dynamic secret returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ in, ok := res.JSON200.DynamicSecret.Inputs.(map[string]any)+ require.True(tt, ok, "the inputs are not an object: %v", res.JSON200.DynamicSecret.Inputs)+ return in+}++func (d *dynamicSecret) update(tt *testing.T, data map[string]any) *api.UpdateDynamicSecretResponse {+ tt.Helper()+ raw, err := json.Marshal(map[string]any{+ "projectSlug": d.proj.Slug, "environmentSlug": d.env, "path": d.path, "data": data,+ })+ require.NoError(tt, err)+ res, err := d.proj.Tenant().Admin.API.UpdateDynamicSecretWithBodyWithResponse(tt.Context(), d.Name,+ "application/json", bytes.NewReader(raw))+ require.NoError(tt, err, "updating a dynamic secret")+ return res+}++func (d *dynamicSecret) delete(tt *testing.T, forced bool) *api.DeleteDynamicSecretResponse {+ tt.Helper()+ res, err := d.proj.Tenant().Admin.API.DeleteDynamicSecretWithResponse(tt.Context(), d.Name,+ api.DeleteDynamicSecretJSONRequestBody{+ ProjectSlug: d.proj.Slug, EnvironmentSlug: d.env, Path: &d.path, IsForced: &forced,+ })+ require.NoError(tt, err, "deleting a dynamic secret")+ return res+}++type lease struct {+ ID string+ ExpireAt time.Time+ CreatedAt time.Time+ Data map[string]any+}++func (d *dynamicSecret) requestLease(tt *testing.T, c *api.ClientWithResponses, ttl string) *api.CreateDynamicSecretLeaseResponse {+ tt.Helper()+ body := api.CreateDynamicSecretLeaseJSONRequestBody{+ DynamicSecretName: d.Name, ProjectSlug: d.proj.Slug, EnvironmentSlug: d.env, Path: &d.path,+ }+ if ttl != "" {+ body.Ttl = &ttl+ }+ res, err := c.CreateDynamicSecretLeaseWithResponse(tt.Context(), body)+ require.NoError(tt, err, "requesting a lease")+ return res+}++func (d *dynamicSecret) lease(tt *testing.T, as *harness.Principal, ttl string) lease {+ tt.Helper()+ c := d.proj.Tenant().Admin.API+ if as != nil {+ c = as.API+ }+ res := d.requestLease(tt, c, ttl)+ require.NotNilf(tt, res.JSON200, "requesting a lease returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ data, _ := res.JSON200.Data.(map[string]any)+ l := res.JSON200.Lease+ return lease{ID: l.Id.String(), ExpireAt: l.ExpireAt, CreatedAt: l.CreatedAt, Data: data}+}++func (d *dynamicSecret) getLease(tt *testing.T, leaseID, path string) *api.GetDynamicSecretLeaseResponse {+ tt.Helper()+ res, err := d.proj.Tenant().Admin.API.GetDynamicSecretLeaseWithResponse(tt.Context(), leaseID,+ &api.GetDynamicSecretLeaseParams{ProjectSlug: d.proj.Slug, EnvironmentSlug: d.env, Path: &path})+ require.NoError(tt, err, "getting a lease")+ return res+}++func (d *dynamicSecret) revoke(tt *testing.T, c *api.ClientWithResponses, leaseID string, forced bool) *api.RevokeDynamicSecretLeaseResponse {+ tt.Helper()+ res, err := c.RevokeDynamicSecretLeaseWithResponse(tt.Context(), leaseID, api.RevokeDynamicSecretLeaseJSONRequestBody{+ ProjectSlug: d.proj.Slug, EnvironmentSlug: d.env, Path: &d.path, IsForced: &forced,+ })+ require.NoError(tt, err, "revoking a lease")+ return res+}++func (d *dynamicSecret) renew(tt *testing.T, leaseID, ttl string) *api.RenewDynamicSecretLeaseResponse {+ tt.Helper()+ res, err := d.proj.Tenant().Admin.API.RenewDynamicSecretLeaseWithResponse(tt.Context(), leaseID,+ api.RenewDynamicSecretLeaseJSONRequestBody{ProjectSlug: d.proj.Slug, EnvironmentSlug: d.env, Path: &d.path, Ttl: &ttl})+ require.NoError(tt, err, "renewing a lease")+ return res+}++func (d *dynamicSecret) leaseIDs(tt *testing.T) []string {+ tt.Helper()+ res, err := d.proj.Tenant().Admin.API.ListDynamicSecretLeasesWithResponse(tt.Context(), d.Name,+ &api.ListDynamicSecretLeasesParams{ProjectSlug: d.proj.Slug, EnvironmentSlug: d.env, Path: &d.path})+ require.NoError(tt, err, "listing leases")+ require.NotNilf(tt, res.JSON200, "listing leases returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ ids := []string{}+ for _, l := range res.JSON200.Leases {+ ids = append(ids, l.Id.String())+ }+ return ids+}++// names lists the dynamic secrets at a path, as the administrator sees them.+func names(tt *testing.T, p *fixture.Project, path string) []string {+ tt.Helper()+ res, err := p.Tenant().Admin.API.ListDynamicSecretsWithResponse(tt.Context(), &api.ListDynamicSecretsParams{+ ProjectSlug: p.Slug, EnvironmentSlug: "dev", Path: &path,+ })+ require.NoError(tt, err, "listing dynamic secrets")+ require.NotNilf(tt, res.JSON200, "listing dynamic secrets returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ out := []string{}+ for _, ds := range res.JSON200.DynamicSecrets {+ out = append(out, ds.Name)+ }+ return out+}++func credentials(tt *testing.T, l lease) (username, password string) {+ tt.Helper()+ username, _ = l.Data["DB_USERNAME"].(string)+ password, _ = l.Data["DB_PASSWORD"].(string)+ require.NotEmpty(tt, username, "the lease carries no DB_USERNAME: %v", l.Data)+ require.NotEmpty(tt, password, "the lease carries no DB_PASSWORD")+ return username, password+}++// totpCodes are the codes RFC 6238 gives for the steps either side of now, so a lease+// issued at a step boundary still matches.+func totpCodes(tt *testing.T, secret string) []string {+ tt.Helper()+ key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)+ require.NoError(tt, err)+ step := time.Now().Unix() / 30+ var codes []string+ for _, s := range []int64{step - 1, step, step + 1} {+ msg := make([]byte, 8)+ binary.BigEndian.PutUint64(msg, uint64(s))+ mac := hmac.New(sha1.New, key)+ mac.Write(msg)+ sum := mac.Sum(nil)+ off := sum[len(sum)-1] & 0x0f+ code := binary.BigEndian.Uint32(sum[off:off+4]) & 0x7fffffff+ codes = append(codes, fmt.Sprintf("%06d", code%1_000_000))+ }+ return codes+}++func requireStatus(tt *testing.T, want int, got int, body []byte) {+ tt.Helper()+ require.Equalf(tt, want, got, "%s", apierr.Body(body))+}diff --git a/tests/suites/secretmanager/dynamicsecrets/lease_test.go b/tests/suites/secretmanager/dynamicsecrets/lease_test.gonew file mode 100644index 0000000000..a0b800c693--- /dev/null+++ b/tests/suites/secretmanager/dynamicsecrets/lease_test.go@@ -0,0 +1,124 @@+package dynamicsecrets_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/stretchr/testify/require"+)++func TestDynamicSecretLease_Revoke(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should remove the lease when it is revoked", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider())+ l := ds.lease(t, nil, "")++ // Action+ res := ds.revoke(t, tn.Admin.API, l.ID, false)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, http.StatusNotFound, ds.getLease(t, l.ID, "/").StatusCode())+ require.Empty(t, ds.leaseIDs(t))+ })++ t.Run("should report failed deletion and keep the lease when the provider refuses an unforced revoke", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, postgresProvider(target))+ l := ds.lease(t, nil, "")+ username, _ := credentials(t, l)+ target.DropRole(t, username)++ // Action+ res := ds.revoke(t, tn.Admin.API, l.ID, false)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, "Failed to delete", *res.JSON200.Lease.Status)+ require.Contains(t, *res.JSON200.Lease.StatusDetails, "does not exist")+ require.Equal(t, []string{l.ID}, ds.leaseIDs(t))+ })++ t.Run("should remove a lease the provider refuses to revoke when the revoke is forced", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, postgresProvider(target))+ l := ds.lease(t, nil, "")+ username, _ := credentials(t, l)+ target.DropRole(t, username)+ failed := ds.revoke(t, tn.Admin.API, l.ID, false)+ require.NotNil(t, failed.JSON200)+ require.Equal(t, "Failed to delete", *failed.JSON200.Lease.Status)++ // Action+ res := ds.revoke(t, tn.Admin.API, l.ID, true)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, http.StatusNotFound, ds.getLease(t, l.ID, "/").StatusCode())+ require.Empty(t, ds.leaseIDs(t))+ })+}++func TestDynamicSecretLease_Get(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should return not found and keep the lease when it is reached through another dynamic secret's folder", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateFolder(t, proj, "dev", "/other")+ ds := newDynamicSecret(t, proj, totpProvider())+ other := newDynamicSecret(t, proj, totpProvider(), atPath("/other"))+ l := ds.lease(t, nil, "")++ // Action+ get := other.getLease(t, l.ID, "/other")+ revoke := other.revoke(t, tn.Admin.API, l.ID, false)++ // Assert+ requireStatus(t, http.StatusNotFound, get.StatusCode(), get.Body)+ requireStatus(t, http.StatusNotFound, revoke.StatusCode(), revoke.Body)+ require.Equal(t, []string{l.ID}, ds.leaseIDs(t))+ })++ t.Run("should list only the leases of the named dynamic secret", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider())+ other := newDynamicSecret(t, proj, totpProvider())+ mine := ds.lease(t, nil, "")+ other.lease(t, nil, "")++ // Action+ got := ds.leaseIDs(t)++ // Assert+ require.Equal(t, []string{mine.ID}, got)+ })+}diff --git a/tests/suites/secretmanager/dynamicsecrets/main_test.go b/tests/suites/secretmanager/dynamicsecrets/main_test.gonew file mode 100644index 0000000000..21c3e27618--- /dev/null+++ b/tests/suites/secretmanager/dynamicsecrets/main_test.go@@ -0,0 +1,13 @@+package dynamicsecrets_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra/postgres"+)++func TestMain(m *testing.M) {+ harness.Main(m, harness.Shared, harness.WithInfra(postgres.Module(postgres.Named(fixture.PostgresTargetInstance))))+}diff --git a/tests/suites/secretmanager/dynamicsecrets/permission_test.go b/tests/suites/secretmanager/dynamicsecrets/permission_test.gonew file mode 100644index 0000000000..755093874b--- /dev/null+++ b/tests/suites/secretmanager/dynamicsecrets/permission_test.go@@ -0,0 +1,110 @@+package dynamicsecrets_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestDynamicSecretLease_Permission(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a lease to a viewer and create none", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ viewer := proj.NewMachineIdentity(t, fixture.WithRoles("viewer"))+ ds := newDynamicSecret(t, proj, totpProvider())++ // Action+ res := ds.requestLease(t, viewer.API, "")++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Empty(t, ds.leaseIDs(t))+ })++ t.Run("should lease only the dynamic secrets whose metadata the role's condition matches", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ proj.NewRole(t, "payments-lease", fixture.Permission{+ Subject: "dynamic-secrets",+ Action: []string{"lease"},+ Conditions: map[string]any{"metadata": map[string]any{"$elemMatch": map[string]any{+ "key": map[string]any{"$eq": "team"}, "value": map[string]any{"$eq": "payments"},+ }}},+ })+ member := proj.NewMachineIdentity(t, fixture.WithRoles("payments-lease"))+ payments := newDynamicSecret(t, proj, totpProvider(), withMetadata("team", "payments"))+ growth := newDynamicSecret(t, proj, totpProvider(), withMetadata("team", "growth"))++ // Action+ allowed := payments.requestLease(t, member.API, "")+ refused := growth.requestLease(t, member.API, "")++ // Assert+ requireStatus(t, http.StatusOK, allowed.StatusCode(), allowed.Body)+ requireStatus(t, http.StatusForbidden, refused.StatusCode(), refused.Body)+ require.Empty(t, growth.leaseIDs(t))+ })+}++func TestDynamicSecret_License(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse create and lease when the plan does not include dynamic secrets", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider())+ tn.SetPlan(t, license.Enterprise().Without(license.DynamicSecret))++ // Action+ created, _ := createDynamicSecret(t, tn.Admin.API, proj, totpProvider())+ leased := ds.requestLease(t, tn.Admin.API, "")++ // Assert+ requireStatus(t, http.StatusBadRequest, created.StatusCode(), created.Body)+ require.Contains(t, apierr.Body(created.Body), "plan restriction")+ requireStatus(t, http.StatusBadRequest, leased.StatusCode(), leased.Body)+ require.Contains(t, apierr.Body(leased.Body), "plan restriction")+ require.Equal(t, []string{ds.Name}, names(t, proj, "/"))+ require.Empty(t, ds.leaseIDs(t))+ })++ t.Run("should still list, revoke and delete when the plan does not include dynamic secrets", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider())+ l := ds.lease(t, nil, "")+ tn.SetPlan(t, license.Enterprise().Without(license.DynamicSecret))++ // Action+ listed := names(t, proj, "/")+ revoked := ds.revoke(t, tn.Admin.API, l.ID, false)+ deleted := ds.delete(t, false)++ // Assert+ require.Equal(t, []string{ds.Name}, listed)+ requireStatus(t, http.StatusOK, revoked.StatusCode(), revoked.Body)+ requireStatus(t, http.StatusOK, deleted.StatusCode(), deleted.Body)+ require.Equal(t, http.StatusNotFound, ds.get(t, tn.Admin.API).StatusCode())+ })+}diff --git a/tests/suites/secretmanager/dynamicsecrets/postgres_test.go b/tests/suites/secretmanager/dynamicsecrets/postgres_test.gonew file mode 100644index 0000000000..c5cffb565c--- /dev/null+++ b/tests/suites/secretmanager/dynamicsecrets/postgres_test.go@@ -0,0 +1,59 @@+package dynamicsecrets_test++import (+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/stretchr/testify/require"+)++func TestPostgresDynamicSecret_Lease(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should create a role that can log in, and drop it on revoke", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, postgresProvider(target))+ l := ds.lease(t, nil, "")+ username, password := credentials(t, l)+ target.DropRoleAtCleanup(t, username)+ require.NoError(t, target.Login(t, username, password), "the leased credential does not log in")++ // Action+ res := ds.revoke(t, tn.Admin.API, l.ID, false)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.False(t, target.RoleExists(t, username), "the revoked lease's role is still on the database")+ require.Error(t, target.Login(t, username, password))+ })++ t.Run("should render the identity name into the role name when the template uses it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ target := fixture.OpenPostgresTarget(t, tn)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ci := proj.NewMachineIdentity(t, fixture.WithPrincipalName("ci-"+id.Short()), fixture.WithRoles("admin"))+ ds := newDynamicSecret(t, proj, postgresProvider(target), usernameTemplate("{{identity.name}}-{{randomUsername}}"))++ // Action+ l := ds.lease(t, ci, "")++ // Assert+ username, password := credentials(t, l)+ target.DropRoleAtCleanup(t, username)+ require.True(t, strings.HasPrefix(username, ci.Name+"-"), "%q does not start with the identity name %q", username, ci.Name)+ require.NoError(t, target.Login(t, username, password))+ })+}diff --git a/tests/suites/secretmanager/dynamicsecrets/ttl_test.go b/tests/suites/secretmanager/dynamicsecrets/ttl_test.gonew file mode 100644index 0000000000..4793b385b4--- /dev/null+++ b/tests/suites/secretmanager/dynamicsecrets/ttl_test.go@@ -0,0 +1,163 @@+package dynamicsecrets_test++import (+ "net/http"+ "testing"+ "time"++ "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 TestDynamicSecret_TTL(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ for _, tc := range []struct{ ttl, message string }{+ {"30s", "greater than 1min"},+ {"11y", "less than 10 years"},+ } {+ t.Run("should refuse a default ttl of "+tc.ttl, func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))++ // Action+ res, _ := createDynamicSecret(t, tn.Admin.API, proj, totpProvider(), defaultTTL(tc.ttl))++ // Assert+ require.Equalf(t, http.StatusUnprocessableEntity, res.StatusCode(), "%s", apierr.Body(res.Body))+ require.Contains(t, apierr.Body(res.Body), tc.message)+ require.Empty(t, names(t, proj, "/"))+ })+ }++ t.Run("should accept a default ttl over the max ttl and then refuse a lease at that default", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))++ // Action+ res, cfg := createDynamicSecret(t, tn.Admin.API, proj, totpProvider(), defaultTTL("2h"), maxTTL("1h"))++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ ds := &dynamicSecret{Name: cfg.name, env: cfg.env, path: cfg.path, proj: proj}+ lres := ds.requestLease(t, tn.Admin.API, "")+ requireStatus(t, http.StatusBadRequest, lres.StatusCode(), lres.Body)+ require.Contains(t, apierr.Body(lres.Body), "TTL cannot be larger than max TTL")+ })+}++func TestDynamicSecretLease_TTL(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should expire at the default ttl when the lease names none", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider(), defaultTTL("2h"))++ // Action+ l := ds.lease(t, nil, "")++ // Assert+ require.WithinDuration(t, l.CreatedAt.Add(2*time.Hour), l.ExpireAt, time.Minute)+ })++ t.Run("should refuse a lease under a minute and create none", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider())++ // Action+ res := ds.requestLease(t, tn.Admin.API, "30s")++ // Assert+ requireStatus(t, http.StatusUnprocessableEntity, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "greater than 1min")+ require.Empty(t, ds.leaseIDs(t))+ })++ t.Run("should refuse a lease over the max ttl and create none", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider(), maxTTL("1h"))++ // Action+ res := ds.requestLease(t, tn.Admin.API, "2h")++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "TTL cannot be larger than max TTL")+ require.Empty(t, ds.leaseIDs(t))+ })++ t.Run("should answer 500 and create no lease when the ttl is not a duration", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider())++ // Action+ res := ds.requestLease(t, tn.Admin.API, "abc")++ // Assert+ requireStatus(t, http.StatusInternalServerError, res.StatusCode(), res.Body)+ require.Empty(t, ds.leaseIDs(t))+ })++ t.Run("should push the expiry out by the ttl when a lease is renewed within the max ttl", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider(), maxTTL("2h"))+ l := ds.lease(t, nil, "1h")++ // Action+ res := ds.renew(t, l.ID, "30m")++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.WithinDuration(t, l.ExpireAt.Add(30*time.Minute), res.JSON200.Lease.ExpireAt, time.Second)+ })++ t.Run("should refuse and keep the expiry when a renewal would pass the max ttl from creation", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ ds := newDynamicSecret(t, proj, totpProvider(), maxTTL("2h"))+ l := ds.lease(t, nil, "1h")++ // Action+ res := ds.renew(t, l.ID, "90m")++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "exceed the maximum allowed lease duration")+ got := ds.getLease(t, l.ID, "/")+ require.NotNil(t, got.JSON200)+ require.True(t, l.ExpireAt.Equal(got.JSON200.Lease.ExpireAt), "the expiry moved: %v -> %v", l.ExpireAt, got.JSON200.Lease.ExpireAt)+ })+}diff --git a/tests/suites/secretmanager/rotations/check_test.go b/tests/suites/secretmanager/rotations/check_test.gonew file mode 100644index 0000000000..2cce876643--- /dev/null+++ b/tests/suites/secretmanager/rotations/check_test.go@@ -0,0 +1,45 @@+package rotations_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestSecretRotation_CheckCredentials(t *testing.T) {+ t.Parallel()++ t.Run("should pass when the active credential logs in", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)++ // Action+ res := r.check(t, e.tn.Admin.API)++ // Assert+ requireStatus(t, http.StatusNoContent, res.StatusCode(), res.Body)+ })++ t.Run("should fail and leave the secrets when the active credential was changed at the database", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ published := e.published(t, "/")+ e.target.SetPassword(t, published.name, "changed-out-of-band")++ // Action+ res := r.check(t, e.tn.Admin.API)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "password authentication failed")+ require.Equal(t, published, e.published(t, "/"))+ })+}diff --git a/tests/suites/secretmanager/rotations/create_test.go b/tests/suites/secretmanager/rotations/create_test.gonew file mode 100644index 0000000000..878a54b08f--- /dev/null+++ b/tests/suites/secretmanager/rotations/create_test.go@@ -0,0 +1,137 @@+package rotations_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestSecretRotation_Create(t *testing.T) {+ t.Parallel()++ t.Run("should issue the first credential and write it to the mapped secrets, so that it logs in", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)++ // Action+ res := e.create(t)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ got := decode(t, res.Body)+ require.Equal(t, 0, got.ActiveIndex)+ require.Equal(t, "success", got.RotationStatus)+ published := e.published(t, "/")+ require.Equal(t, e.users[0].name, published.name)+ e.requireLogsIn(t, published, "the published credential")+ e.requireRefused(t, e.users[0], "the first user's password from before the rotation")+ e.requireRefused(t, e.users[1], "the second user's password from before the rotation")+ })++ t.Run("should refuse a name already used at the path and leave the users alone", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ first := e.newRotation(t)+ a, aPw := e.target.NewRole(t)+ b, bPw := e.target.NewRole(t)++ // Action+ res := e.create(t, rotationName(first.Name), usernames(a, b), mapping("OTHER_USERNAME", "OTHER_PASSWORD"))++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), first.Name)+ require.Equal(t, []string{first.Name}, e.rotationNames(t))+ e.requireLogsIn(t, role{a, aPw}, "a user of the refused rotation")+ e.requireLogsIn(t, role{b, bPw}, "a user of the refused rotation")+ })++ t.Run("should refuse a mapped key that already exists and keep its value and the users", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ secretmanager.CreateSecret(t, e.proj, "dev", usernameKey, "hand-written")++ // Action+ res := e.create(t)++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), usernameKey)+ require.Equal(t, map[string]string{usernameKey: "hand-written"}, e.secretsAt(t, "/"))+ e.requireLogsIn(t, e.users[0], "a user of the refused rotation")+ })++ t.Run("should refuse duplicate mapping keys and leave the users alone", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)++ // Action+ res := e.create(t, mapping("SAME_KEY", "SAME_KEY"))++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "must be unique")+ require.Empty(t, e.rotationNames(t))+ e.requireLogsIn(t, e.users[0], "a user of the refused rotation")+ })++ t.Run("should refuse naming the path and environment when the folder does not exist", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)++ // Action+ res := e.create(t, atPath("/does/not/exist"))++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "/does/not/exist")+ require.Contains(t, apierr.Body(res.Body), "dev")+ e.requireLogsIn(t, e.users[0], "a user of the refused rotation")+ })++ t.Run("should leave no rotation, no secrets and the first user's password when the database refuses", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)++ // Action+ res := e.create(t, usernames(e.users[0].name, "missing_"+e.users[1].name))++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "does not exist")+ require.Empty(t, e.rotationNames(t))+ require.Empty(t, e.secretsAt(t, "/"))+ e.requireLogsIn(t, e.users[0], "the first user after the refused rotation")+ })++ t.Run("should refuse a rotation user that is the connection's own user", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)++ // Action+ res := e.create(t, usernames(e.target.User, e.users[1].name))++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "cannot be the same as the connection username")+ require.Empty(t, e.rotationNames(t))+ e.requireLogsIn(t, role{e.target.User, e.target.Password}, "the connection user")+ })+}diff --git a/tests/suites/secretmanager/rotations/delete_test.go b/tests/suites/secretmanager/rotations/delete_test.gonew file mode 100644index 0000000000..4dca2da90c--- /dev/null+++ b/tests/suites/secretmanager/rotations/delete_test.go@@ -0,0 +1,54 @@+package rotations_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/stretchr/testify/require"+)++func TestSecretRotation_Delete(t *testing.T) {+ t.Parallel()++ t.Run("should revoke both credentials and remove the secrets when deleted with both flags", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ first := e.published(t, "/")+ r.mustRotate(t)+ second := e.published(t, "/")++ // Action+ res := r.delete(t, true, true)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ e.requireRefused(t, first, "the inactive credential after the delete")+ e.requireRefused(t, second, "the published credential after the delete")+ require.Empty(t, e.secretsAt(t, "/"))+ require.Empty(t, e.rotationNames(t))+ })++ t.Run("should leave the credential live and the secrets editable when deleted with neither flag", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ published := e.published(t, "/")++ // Action+ res := r.delete(t, false, false)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ e.requireLogsIn(t, published, "the credential of a rotation deleted without revoking")+ require.Equal(t, published, e.published(t, "/"))+ require.Empty(t, e.rotationNames(t))+ secretmanager.UpdateSecret(t, e.proj, "dev", usernameKey, "hand-written")+ require.Equal(t, "hand-written", e.secretsAt(t, "/")[usernameKey])+ })+}diff --git a/tests/suites/secretmanager/rotations/helpers_test.go b/tests/suites/secretmanager/rotations/helpers_test.gonew file mode 100644index 0000000000..fea6e72603--- /dev/null+++ b/tests/suites/secretmanager/rotations/helpers_test.go@@ -0,0 +1,296 @@+package rotations_test++import (+ "encoding/json"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+)++// Suite-local until a second package creates a rotation; then it moves to+// fixture/secretmanager.++const (+ usernameKey = "PG_USERNAME"+ passwordKey = "PG_PASSWORD"+)++// role is a database user the rotation alternates between, with the password it was+// created with.+type role struct{ name, password string }++type env struct {+ tn *harness.Tenant+ proj *fixture.Project+ target *fixture.PostgresTarget+ conn *fixture.AppConnection+ users [2]role+}++// setup returns a project, a connection to the target as its superuser, and two+// database users for a rotation to take over.+func setup(t *testing.T, opts ...harness.TenantOption) env {+ t.Helper()+ tn := harness.From(t).NewTenant(t, opts...)+ target := fixture.OpenPostgresTarget(t, tn)+ e := env{+ tn: tn,+ proj: fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager")),+ target: target,+ conn: fixture.NewAppConnection(t, tn, fixture.PostgresAppConnection(target)),+ }+ for i := range e.users {+ name, password := target.NewRole(t)+ e.users[i] = role{name, password}+ }+ return e+}++type rotationConfig struct {+ name string+ path string+ usernames [2]string+ mapping [2]string+ auto bool+ interval float32+ rotateAt *[2]int+}++type rotationOption func(*rotationConfig)++func rotationName(n string) rotationOption { return func(c *rotationConfig) { c.name = n } }+func atPath(p string) rotationOption { return func(c *rotationConfig) { c.path = p } }+func usernames(a, b string) rotationOption {+ return func(c *rotationConfig) { c.usernames = [2]string{a, b} }+}+func mapping(u, p string) rotationOption {+ return func(c *rotationConfig) { c.mapping = [2]string{u, p} }+}++// autoRotate is off by default, so the midnight cron never touches a test's rotation.+func autoRotate(intervalDays float32, hours, minutes int) rotationOption {+ return func(c *rotationConfig) {+ c.auto = true+ c.interval = intervalDays+ c.rotateAt = &[2]int{hours, minutes}+ }+}++func (e env) body(opts []rotationOption) api.CreatePostgreSQLCredentialsRotationJSONRequestBody {+ cfg := rotationConfig{+ name: "rot-" + id.Short(),+ path: "/",+ usernames: [2]string{e.users[0].name, e.users[1].name},+ mapping: [2]string{usernameKey, passwordKey},+ interval: 1,+ }+ for _, o := range opts {+ o(&cfg)+ }+ body := api.CreatePostgreSQLCredentialsRotationJSONRequestBody{+ Name: cfg.name,+ ProjectId: e.proj.ID,+ ConnectionId: e.conn.ID,+ Environment: "dev",+ SecretPath: cfg.path,+ IsAutoRotationEnabled: &cfg.auto,+ RotationInterval: cfg.interval,+ }+ body.Parameters.Username1 = cfg.usernames[0]+ body.Parameters.Username2 = cfg.usernames[1]+ body.SecretsMapping.Username = cfg.mapping[0]+ body.SecretsMapping.Password = cfg.mapping[1]+ if cfg.rotateAt != nil {+ body.RotateAtUtc = &struct {+ Hours float32 `json:"hours"`+ Minutes float32 `json:"minutes"`+ }{Hours: float32(cfg.rotateAt[0]), Minutes: float32(cfg.rotateAt[1])}+ }+ return body+}++func (e env) create(t *testing.T, opts ...rotationOption) *api.CreatePostgreSQLCredentialsRotationResponse {+ t.Helper()+ res, err := e.tn.Admin.API.CreatePostgreSQLCredentialsRotationWithResponse(t.Context(), e.body(opts))+ require.NoError(t, err, "creating a rotation")+ return res+}++type rotation struct {+ ID uuid.UUID+ Name string+ e env+}++func (e env) newRotation(t *testing.T, opts ...rotationOption) *rotation {+ t.Helper()+ res := e.create(t, opts...)+ require.NotNilf(t, res.JSON200, "creating a rotation returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return &rotation{ID: res.JSON200.SecretRotation.Id, Name: res.JSON200.SecretRotation.Name, e: e}+}++// view is the part of a rotation the tests read. Decoded from the body because each+// route's generated response is its own anonymous struct.+type view struct {+ ID uuid.UUID `json:"id"`+ Name string `json:"name"`+ Description *string `json:"description"`+ ActiveIndex int `json:"activeIndex"`+ RotationStatus string `json:"rotationStatus"`+ LastRotationMessage *string `json:"lastRotationMessage"`+ LastRotatedAt time.Time `json:"lastRotatedAt"`+ NextRotationAt *time.Time `json:"nextRotationAt"`+ RotationInterval int `json:"rotationInterval"`+ SecretsMapping struct {+ Username string `json:"username"`+ Password string `json:"password"`+ } `json:"secretsMapping"`+ Folder struct {+ Path string `json:"path"`+ } `json:"folder"`+}++func decode(t *testing.T, body []byte) view {+ t.Helper()+ var out struct {+ SecretRotation view `json:"secretRotation"`+ }+ require.NoError(t, json.Unmarshal(body, &out), "decoding a rotation: %s", body)+ return out.SecretRotation+}++func (r *rotation) get(t *testing.T) *api.GetPostgreSQLCredentialsRotationResponse {+ t.Helper()+ res, err := r.e.tn.Admin.API.GetPostgreSQLCredentialsRotationWithResponse(t.Context(), r.ID)+ require.NoError(t, err, "getting a rotation")+ return res+}++func (r *rotation) view(t *testing.T) view {+ t.Helper()+ res := r.get(t)+ require.NotNilf(t, res.JSON200, "getting a rotation returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return decode(t, res.Body)+}++func (r *rotation) rotate(t *testing.T) *api.RotatePostgreSQLCredentialsRotationResponse {+ t.Helper()+ res, err := r.e.tn.Admin.API.RotatePostgreSQLCredentialsRotationWithResponse(t.Context(), r.ID)+ require.NoError(t, err, "rotating")+ return res+}++func (r *rotation) mustRotate(t *testing.T) view {+ t.Helper()+ res := r.rotate(t)+ require.NotNilf(t, res.JSON200, "rotating returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return decode(t, res.Body)+}++func (r *rotation) generated(t *testing.T, c *api.ClientWithResponses) *api.GetPostgreSQLCredentialsRotationGeneratedCredentialsResponse {+ t.Helper()+ res, err := c.GetPostgreSQLCredentialsRotationGeneratedCredentialsWithResponse(t.Context(), r.ID)+ require.NoError(t, err, "reading generated credentials")+ return res+}++func (r *rotation) check(t *testing.T, c *api.ClientWithResponses) *api.CheckPostgreSQLCredentialsRotationCredentialsResponse {+ t.Helper()+ res, err := c.CheckPostgreSQLCredentialsRotationCredentialsWithResponse(t.Context(), r.ID)+ require.NoError(t, err, "checking credentials")+ return res+}++func (r *rotation) update(t *testing.T, body api.UpdatePostgreSQLCredentialsRotationJSONRequestBody) *api.UpdatePostgreSQLCredentialsRotationResponse {+ t.Helper()+ res, err := r.e.tn.Admin.API.UpdatePostgreSQLCredentialsRotationWithResponse(t.Context(), r.ID, body)+ require.NoError(t, err, "updating a rotation")+ return res+}++func (r *rotation) move(t *testing.T, c *api.ClientWithResponses, path string) *api.MovePostgreSQLCredentialsRotationResponse {+ t.Helper()+ res, err := c.MovePostgreSQLCredentialsRotationWithResponse(t.Context(), r.ID,+ api.MovePostgreSQLCredentialsRotationJSONRequestBody{DestinationEnvironment: "dev", DestinationSecretPath: path})+ require.NoError(t, err, "moving a rotation")+ return res+}++func (r *rotation) delete(t *testing.T, deleteSecrets, revoke bool) *api.DeletePostgreSQLCredentialsRotationResponse {+ t.Helper()+ ds := api.DeletePostgreSQLCredentialsRotationParamsDeleteSecrets(boolString(deleteSecrets))+ rv := api.DeletePostgreSQLCredentialsRotationParamsRevokeGeneratedCredentials(boolString(revoke))+ res, err := r.e.tn.Admin.API.DeletePostgreSQLCredentialsRotationWithResponse(t.Context(), r.ID,+ &api.DeletePostgreSQLCredentialsRotationParams{DeleteSecrets: &ds, RevokeGeneratedCredentials: &rv})+ require.NoError(t, err, "deleting a rotation")+ return res+}++func boolString(b bool) string {+ if b {+ return "true"+ }+ return "false"+}++// list is the rotations the administrator can see in the project.+func (e env) list(t *testing.T) *api.ListPostgreSQLCredentialsRotationsResponse {+ t.Helper()+ res, err := e.tn.Admin.API.ListPostgreSQLCredentialsRotationsWithResponse(t.Context(),+ &api.ListPostgreSQLCredentialsRotationsParams{ProjectId: e.proj.ID})+ require.NoError(t, err, "listing rotations")+ return res+}++func (e env) rotationNames(t *testing.T) []string {+ t.Helper()+ res := e.list(t)+ require.NotNilf(t, res.JSON200, "listing rotations returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ out := []string{}+ for _, r := range res.JSON200.SecretRotations {+ out = append(out, r.Name)+ }+ return out+}++// secretsAt is what an application reading the folder gets.+func (e env) secretsAt(t *testing.T, path string) map[string]string {+ t.Helper()+ out := map[string]string{}+ for _, s := range secretmanager.ListSecrets(t, e.proj, "dev", secretmanager.WithPath(path)) {+ out[s.Key] = s.Value+ }+ return out+}++// published is the credential the mapped secrets hold.+func (e env) published(t *testing.T, path string) role {+ t.Helper()+ got := e.secretsAt(t, path)+ require.Contains(t, got, usernameKey, "the mapped username secret is missing: %v", got)+ require.Contains(t, got, passwordKey, "the mapped password secret is missing")+ return role{got[usernameKey], got[passwordKey]}+}++func (e env) requireLogsIn(t *testing.T, r role, msg string) {+ t.Helper()+ require.NoErrorf(t, e.target.Login(t, r.name, r.password), "%s: %s does not log in", msg, r.name)+}++func (e env) requireRefused(t *testing.T, r role, msg string) {+ t.Helper()+ require.Errorf(t, e.target.Login(t, r.name, r.password), "%s: %s still logs in", msg, r.name)+}++func requireStatus(t *testing.T, want, got int, body []byte) {+ t.Helper()+ require.Equalf(t, want, got, "%s", apierr.Body(body))+}diff --git a/tests/suites/secretmanager/rotations/main_test.go b/tests/suites/secretmanager/rotations/main_test.gonew file mode 100644index 0000000000..49011c585c--- /dev/null+++ b/tests/suites/secretmanager/rotations/main_test.go@@ -0,0 +1,13 @@+package rotations_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra/postgres"+)++func TestMain(m *testing.M) {+ harness.Main(m, harness.Shared, harness.WithInfra(postgres.Module(postgres.Named(fixture.PostgresTargetInstance))))+}diff --git a/tests/suites/secretmanager/rotations/mapping_test.go b/tests/suites/secretmanager/rotations/mapping_test.gonew file mode 100644index 0000000000..dd875a6dc6--- /dev/null+++ b/tests/suites/secretmanager/rotations/mapping_test.go@@ -0,0 +1,80 @@+package rotations_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func remap(u, p string) api.UpdatePostgreSQLCredentialsRotationJSONRequestBody {+ var body api.UpdatePostgreSQLCredentialsRotationJSONRequestBody+ body.SecretsMapping = &struct {+ Password string `json:"password"`+ Username string `json:"username"`+ }{Password: p, Username: u}+ return body+}++func TestSecretRotation_MappedSecrets(t *testing.T) {+ t.Parallel()++ t.Run("should refuse setting a mapped secret by hand and keep the published value", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ e.newRotation(t)+ before := e.published(t, "/")+ path, value := "/", "hand-written"++ // Action+ res, err := e.tn.Admin.API.UpdateSecretV4WithResponse(t.Context(), usernameKey, api.UpdateSecretV4JSONRequestBody{+ ProjectId: e.proj.ID, Environment: "dev", SecretPath: &path, SecretValue: &value,+ })++ // Assert+ require.NoError(t, err)+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "Cannot update rotated secret")+ require.Equal(t, before, e.published(t, "/"))+ })++ t.Run("should rename the mapped secrets and keep their values when the mapping changes", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ before := e.published(t, "/")++ // Action+ res := r.update(t, remap("DB_USER", "DB_PASS"))++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, map[string]string{"DB_USER": before.name, "DB_PASS": before.password}, e.secretsAt(t, "/"))+ })++ t.Run("should refuse a mapping onto an existing secret and keep both", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ secretmanager.CreateSecret(t, e.proj, "dev", "TAKEN", "someone else's")+ before := e.published(t, "/")++ // Action+ res := r.update(t, remap("TAKEN", passwordKey))++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "TAKEN")+ require.Equal(t, map[string]string{usernameKey: before.name, passwordKey: before.password, "TAKEN": "someone else's"},+ e.secretsAt(t, "/"))+ })+}diff --git a/tests/suites/secretmanager/rotations/move_test.go b/tests/suites/secretmanager/rotations/move_test.gonew file mode 100644index 0000000000..c677cbfc64--- /dev/null+++ b/tests/suites/secretmanager/rotations/move_test.go@@ -0,0 +1,94 @@+package rotations_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestSecretRotation_Move(t *testing.T) {+ t.Parallel()++ t.Run("should carry the mapped secrets to the destination folder", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ secretmanager.CreateFolder(t, e.proj, "dev", "/services")+ r := e.newRotation(t)+ published := e.published(t, "/")++ // Action+ res := r.move(t, e.tn.Admin.API, "/services")++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Equal(t, "/services", r.view(t).Folder.Path)+ require.Equal(t, published, e.published(t, "/services"))+ require.Empty(t, e.secretsAt(t, "/"))+ })++ t.Run("should refuse a move to the folder the rotation is already in", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)++ // Action+ res := r.move(t, e.tn.Admin.API, "/")++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "Source and destination locations are the same")+ require.Equal(t, "/", r.view(t).Folder.Path)+ })++ t.Run("should refuse a move onto existing keys and leave both folders as they were", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ secretmanager.CreateFolder(t, e.proj, "dev", "/services")+ secretmanager.CreateSecret(t, e.proj, "dev", usernameKey, "already here", secretmanager.WithPath("/services"))+ r := e.newRotation(t)+ published := e.published(t, "/")++ // Action+ res := r.move(t, e.tn.Admin.API, "/services")++ // Assert+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "overwriteDestination")+ require.Equal(t, "/", r.view(t).Folder.Path)+ require.Equal(t, published, e.published(t, "/"))+ require.Equal(t, map[string]string{usernameKey: "already here"}, e.secretsAt(t, "/services"))+ })++ t.Run("should refuse a move to a folder the actor cannot create rotations in", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ secretmanager.CreateFolder(t, e.proj, "dev", "/services")+ e.proj.NewRole(t, "root-rotations", fixture.Permission{+ Subject: "secret-rotation",+ Action: []string{"read", "create", "delete"},+ Conditions: map[string]any{"secretPath": map[string]any{"$eq": "/"}},+ })+ operator := e.proj.NewMachineIdentity(t, fixture.WithRoles("root-rotations"))+ r := e.newRotation(t)++ // Action+ res := r.move(t, operator.API, "/services")++ // Assert+ requireStatus(t, http.StatusForbidden, res.StatusCode(), res.Body)+ require.Equal(t, "/", r.view(t).Folder.Path)+ require.Empty(t, e.secretsAt(t, "/services"))+ })+}diff --git a/tests/suites/secretmanager/rotations/permission_test.go b/tests/suites/secretmanager/rotations/permission_test.gonew file mode 100644index 0000000000..3371ffedaf--- /dev/null+++ b/tests/suites/secretmanager/rotations/permission_test.go@@ -0,0 +1,112 @@+package rotations_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestSecretRotation_Permission(t *testing.T) {+ t.Parallel()++ for _, projectRole := range []string{"member", "viewer"} {+ t.Run("should refuse generated credentials and a credential check to a "+projectRole, func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ actor := e.proj.NewMachineIdentity(t, fixture.WithRoles(projectRole))+ r := e.newRotation(t)++ // Action+ generated := r.generated(t, actor.API)+ checked := r.check(t, actor.API)++ // Assert+ requireStatus(t, http.StatusForbidden, generated.StatusCode(), generated.Body)+ require.NotContains(t, string(generated.Body), e.published(t, "/").password)+ requireStatus(t, http.StatusForbidden, checked.StatusCode(), checked.Body)+ })+ }+}++func TestSecretRotation_License(t *testing.T) {+ t.Parallel()++ t.Run("should refuse create, update and rotate when the plan does not include secret rotation", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ published := e.published(t, "/")+ a, aPw := e.target.NewRole(t)+ b, _ := e.target.NewRole(t)+ e.tn.SetPlan(t, license.Enterprise().Without(license.SecretRotation))+ description := "changed"++ // Action+ created := e.create(t, usernames(a, b), mapping("OTHER_USERNAME", "OTHER_PASSWORD"))+ updated := r.update(t, api.UpdatePostgreSQLCredentialsRotationJSONRequestBody{Description: &description})+ rotated := r.rotate(t)++ // Assert+ for _, res := range []struct {+ status int+ body []byte+ }{{created.StatusCode(), created.Body}, {updated.StatusCode(), updated.Body}, {rotated.StatusCode(), rotated.Body}} {+ requireStatus(t, http.StatusBadRequest, res.status, res.body)+ require.Contains(t, apierr.Body(res.body), "plan restriction")+ }+ require.Equal(t, published, e.published(t, "/"))+ e.requireLogsIn(t, role{a, aPw}, "a user of the refused rotation")+ e.tn.SetPlan(t, license.Enterprise())+ got := r.view(t)+ require.Nil(t, got.Description)+ require.Equal(t, 0, got.ActiveIndex)+ })++ t.Run("should refuse listing and getting rotations and keep the mapped secrets readable when the plan does not include secret rotation", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ published := e.published(t, "/")+ e.tn.SetPlan(t, license.Enterprise().Without(license.SecretRotation))++ // Action+ listed := e.list(t)+ got := r.get(t)++ // Assert+ requireStatus(t, http.StatusBadRequest, listed.StatusCode(), listed.Body)+ require.Contains(t, apierr.Body(listed.Body), "plan restriction")+ requireStatus(t, http.StatusBadRequest, got.StatusCode(), got.Body)+ require.Contains(t, apierr.Body(got.Body), "plan restriction")+ require.Equal(t, published, e.published(t, "/"))+ })++ t.Run("should still delete a rotation when the plan does not include secret rotation", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ e.tn.SetPlan(t, license.Enterprise().Without(license.SecretRotation))++ // Action+ res := r.delete(t, true, false)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Empty(t, e.secretsAt(t, "/"))+ e.tn.SetPlan(t, license.Enterprise())+ require.Equal(t, http.StatusNotFound, r.get(t).StatusCode())+ })+}diff --git a/tests/suites/secretmanager/rotations/rotate_test.go b/tests/suites/secretmanager/rotations/rotate_test.gonew file mode 100644index 0000000000..8e18b08e46--- /dev/null+++ b/tests/suites/secretmanager/rotations/rotate_test.go@@ -0,0 +1,84 @@+package rotations_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/stretchr/testify/require"+)++func TestSecretRotation_Rotate(t *testing.T) {+ t.Parallel()++ t.Run("should flip the active index and publish the other user, so that it logs in", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ before := e.published(t, "/")++ // Action+ got := r.mustRotate(t)++ // Assert+ require.Equal(t, 1, got.ActiveIndex)+ after := e.published(t, "/")+ require.Equal(t, e.users[1].name, after.name)+ e.requireLogsIn(t, after, "the newly published credential")+ e.requireLogsIn(t, before, "the previous credential, which stays live until the next rotation")+ })++ t.Run("should return both credentials with the newest in the active slot", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ r.mustRotate(t)+ r.mustRotate(t)++ // Action+ res := r.generated(t, e.tn.Admin.API)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.EqualValues(t, 0, res.JSON200.ActiveIndex)+ creds := res.JSON200.GeneratedCredentials+ require.Len(t, creds, 2)+ require.Equal(t, e.users[0].name, creds[0].Username)+ require.Equal(t, e.users[1].name, creds[1].Username)+ require.Equal(t, role{creds[0].Username, creds[0].Password}, e.published(t, "/"))+ e.requireLogsIn(t, role{creds[0].Username, creds[0].Password}, "the active credential")+ e.requireLogsIn(t, role{creds[1].Username, creds[1].Password}, "the inactive credential")+ })++ t.Run("should answer 500 with the rotation error, keep the working credential published, and record failed when a manual rotation fails", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `Today's behaviour, pinned so the planned fix finds it: rotateSecretRotation+ wraps the provider error in an InternalServerError, so a refusal by the database+ reads as a server fault.`)++ // Setup+ e := setup(t)+ r := e.newRotation(t)+ before := e.published(t, "/")+ e.target.DropRole(t, e.users[1].name)++ // Action+ res := r.rotate(t)++ // Assert+ requireStatus(t, http.StatusInternalServerError, res.StatusCode(), res.Body)+ require.Contains(t, apierr.Body(res.Body), "does not exist")+ require.Equal(t, before, e.published(t, "/"))+ e.requireLogsIn(t, before, "the credential published before the failed rotation")+ got := r.view(t)+ require.Equal(t, "failed", got.RotationStatus)+ require.Equal(t, 0, got.ActiveIndex)+ require.NotNil(t, got.LastRotationMessage)+ require.Contains(t, *got.LastRotationMessage, "does not exist")+ })+}diff --git a/tests/suites/secretmanager/rotations/schedule_test.go b/tests/suites/secretmanager/rotations/schedule_test.gonew file mode 100644index 0000000000..153fb4dcd1--- /dev/null+++ b/tests/suites/secretmanager/rotations/schedule_test.go@@ -0,0 +1,78 @@+package rotations_test++import (+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/stretchr/testify/require"+)++// nextRotation is the schedule the product documents: the configured time of day,+// the interval in days after the last rotation, plus a day when the rotation happened+// at or after that time, so a full interval always elapses.+func nextRotation(last time.Time, intervalDays, hours, minutes int) time.Time {+ last = last.UTC()+ next := time.Date(last.Year(), last.Month(), last.Day(), hours, minutes, 0, 0, time.UTC)+ days := intervalDays+ if last.Hour() > hours || (last.Hour() == hours && last.Minute() >= minutes) {+ days+++ }+ return next.AddDate(0, 0, days)+}++func TestSecretRotation_Schedule(t *testing.T) {+ t.Parallel()++ t.Run("should schedule the next rotation from the interval and the time of day", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ now := time.Now().UTC()++ // Action+ res := e.create(t, autoRotate(3, now.Hour(), 30))++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ got := decode(t, res.Body)+ require.NotNil(t, got.NextRotationAt)+ require.True(t, nextRotation(got.LastRotatedAt, 3, now.Hour(), 30).Equal(*got.NextRotationAt),+ "last rotated %v, next %v", got.LastRotatedAt, *got.NextRotationAt)+ })++ t.Run("should schedule nothing when auto-rotation is off", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)++ // Action+ res := e.create(t)++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ require.Nil(t, decode(t, res.Body).NextRotationAt)+ })++ t.Run("should move the next rotation when the interval is updated", func(t *testing.T) {+ t.Parallel()++ // Setup+ e := setup(t)+ r := e.newRotation(t, autoRotate(3, 12, 0))+ interval := float32(5)++ // Action+ res := r.update(t, api.UpdatePostgreSQLCredentialsRotationJSONRequestBody{RotationInterval: &interval})++ // Assert+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)+ got := decode(t, res.Body)+ require.NotNil(t, got.NextRotationAt)+ require.True(t, nextRotation(got.LastRotatedAt, 5, 12, 0).Equal(*got.NextRotationAt),+ "last rotated %v, next %v", got.LastRotatedAt, *got.NextRotationAt)+ })+}