Skip to content

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

feat: merged dal with service

=1a5e9a0eca5d
diff --git a/backend-go/Makefile b/backend-go/Makefile
index 3e908db270..39731b6405 100644
--- a/backend-go/Makefile
+++ b/backend-go/Makefile
@@ -1,3 +1,5 @@
+.PHONY: lint lint-fix test test-integration test-all gen-goa gen-db dev build
+
# Run unit tests (no infra required)
lint:
golangci-lint run --build-tags integration
diff --git a/backend-go/internal/database/pg/qb/insert.go b/backend-go/internal/database/pg/qb/insert.go
index f020a07216..c4d7721f83 100644
--- a/backend-go/internal/database/pg/qb/insert.go
+++ b/backend-go/internal/database/pg/qb/insert.go
@@ -44,7 +44,7 @@ func (b *InsertBuilder) Build() (sql string, args []any) {
for _, row := range b.values {
placeholders := make([]string, colCount)
- for i := 0; i < colCount; i++ {
+ for i := range colCount {
placeholders[i] = fmt.Sprintf("$%d", argNum)
args = append(args, row[i])
argNum++
diff --git a/backend-go/internal/server/api/platform/projects/projects_integration_test.go b/backend-go/internal/server/api/platform/projects/projects_integration_test.go
index 15874c7404..899eec84aa 100644
--- a/backend-go/internal/server/api/platform/projects/projects_integration_test.go
+++ b/backend-go/internal/server/api/platform/projects/projects_integration_test.go
@@ -36,8 +36,7 @@ func TestMain(m *testing.M) {
func setupMux(t *testing.T) *testutil.TestMux {
t.Helper()
- permDAL := permission.NewDAL(stack.DB())
- permLib := permission.NewService(testutil.NopLogger(), permission.Deps{DAL: permDAL})
+ permLib := permission.NewService(testutil.NopLogger(), permission.Deps{DB: stack.DB()})
authenticator := auth.NewAuthenticator(stack.DB(), infra.AuthSecret)
diff --git a/backend-go/internal/server/api/secretmanager/secrets/get_secret_by_name.go b/backend-go/internal/server/api/secretmanager/secrets/get_secret_by_name.go
index ca7ce0eea7..831de85aed 100644
--- a/backend-go/internal/server/api/secretmanager/secrets/get_secret_by_name.go
+++ b/backend-go/internal/server/api/secretmanager/secrets/get_secret_by_name.go
@@ -110,7 +110,7 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
}
// Find the secret by name
- foundSecret, err := h.secretManagerSvc.SecretDAL.FindByKey(ctx, folderNode.ID, opts.SecretName, secretType, userID)
+ foundSecret, err := h.secretManagerSvc.Secret.FindByKey(ctx, folderNode.ID, opts.SecretName, secretType, userID)
if err != nil {
return nil, errutil.DatabaseErr("Failed to find secret").WithErrf("GetSecretByName(secretName=%s): %w", opts.SecretName, err)
}
@@ -132,7 +132,7 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
// Search imports in reverse order (last import wins)
for i := len(chainResult.Imports) - 1; i >= 0; i-- {
imp := &chainResult.Imports[i]
- importedSecret, err := h.secretManagerSvc.SecretDAL.FindByKey(ctx, imp.FolderID, opts.SecretName, secretType, userID)
+ importedSecret, err := h.secretManagerSvc.Secret.FindByKey(ctx, imp.FolderID, opts.SecretName, secretType, userID)
if err != nil {
continue
}
@@ -205,7 +205,7 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
// Add imported secrets for reference resolution
if len(chainResult.Imports) > 0 {
allFolderIDs := chainResult.AllFolderIDs()
- importedSecrets, _ := h.secretManagerSvc.SecretDAL.FindByFolderIds(ctx, allFolderIDs, userID, nil)
+ importedSecrets, _ := h.secretManagerSvc.Secret.FindByFolderIds(ctx, allFolderIDs, userID, nil)
for i := range importedSecrets {
sec := &importedSecrets[i]
if sec.ID == foundSecret.ID {
@@ -234,7 +234,7 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
envBySlug,
folderLookup,
h.secretManagerSvc.SecretFolder,
- h.secretManagerSvc.SecretDAL,
+ h.secretManagerSvc.Secret,
cipherPair,
userID,
)
diff --git a/backend-go/internal/server/api/secretmanager/secrets/list_secrets.go b/backend-go/internal/server/api/secretmanager/secrets/list_secrets.go
index b9bdd99ee7..33ae645f00 100644
--- a/backend-go/internal/server/api/secretmanager/secrets/list_secrets.go
+++ b/backend-go/internal/server/api/secretmanager/secrets/list_secrets.go
@@ -193,7 +193,7 @@ func (h *Handler) listSecretsCore(ctx context.Context, opts *ListSecretsOpts) (*
}
}
- secrets, err := h.secretManagerSvc.SecretDAL.FindByFolderIds(ctx, allFolderIDs, userID, dalFilters)
+ secrets, err := h.secretManagerSvc.Secret.FindByFolderIds(ctx, allFolderIDs, userID, dalFilters)
if err != nil {
return nil, errutil.DatabaseErr("Failed to fetch secrets").WithErrf("ListSecrets(projectId=%s): %w", opts.ProjectID, err)
}
@@ -246,7 +246,7 @@ func (h *Handler) listSecretsCore(ctx context.Context, opts *ListSecretsOpts) (*
envBySlug,
chainResult.FolderLookup,
h.secretManagerSvc.SecretFolder,
- h.secretManagerSvc.SecretDAL,
+ h.secretManagerSvc.Secret,
cipherPair,
expansionUserID,
)
diff --git a/backend-go/internal/server/api/secretmanager/secrets/secrets_integration_test.go b/backend-go/internal/server/api/secretmanager/secrets/secrets_integration_test.go
index a94066d045..2d94651b0b 100644
--- a/backend-go/internal/server/api/secretmanager/secrets/secrets_integration_test.go
+++ b/backend-go/internal/server/api/secretmanager/secrets/secrets_integration_test.go
@@ -11,7 +11,6 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/infisical/api/internal/keystore"
"github.com/infisical/api/internal/queue"
"github.com/infisical/api/internal/server/api/secretmanager/secrets"
gensecrets "github.com/infisical/api/internal/server/gen/secrets"
@@ -49,18 +48,15 @@ func TestMain(m *testing.M) {
func newSecretsHandler(t *testing.T) gensecrets.Service {
t.Helper()
- permDAL := permission.NewDAL(stack.DB())
- permSvc := permission.NewService(testutil.NopLogger(), permission.Deps{DAL: permDAL})
+ permSvc := permission.NewService(testutil.NopLogger(), permission.Deps{DB: stack.DB()})
authenticator := auth.NewAuthenticator(stack.DB(), infra.AuthSecret)
redisClient := stack.Redis().Client()
t.Cleanup(func() { redisClient.Close() })
- ks := keystore.NewKeyStore(redisClient, stack.DB().Primary())
- kmsDAL := kms.NewDAL(stack.DB(), ks)
kmsSvc, err := kms.NewService(kms.Deps{
- DAL: kmsDAL,
+ DB: stack.DB(),
HSM: nil,
Config: stack.Config(),
})
diff --git a/backend-go/internal/services/auditlog/dal.go b/backend-go/internal/services/auditlog/dal.go
deleted file mode 100644
index fee468fe31..0000000000
--- a/backend-go/internal/services/auditlog/dal.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package auditlog
-
-import (
- "context"
- "database/sql"
- "time"
-
- "github.com/google/uuid"
-
- "github.com/infisical/api/internal/database/pg"
- "github.com/infisical/api/internal/database/pg/gen/model"
- "github.com/infisical/api/internal/database/pg/gen/table"
-)
-
-// AuditLogRecord represents a single audit log entry for database operations.
-type AuditLogRecord struct {
- ID uuid.UUID
- Actor string
- ActorMetadata string
- IPAddress sql.Null[string]
- EventType string
- EventMetadata sql.Null[string]
- UserAgent sql.Null[string]
- UserAgentType sql.Null[string]
- ExpiresAt sql.NullTime
- CreatedAt time.Time
- UpdatedAt time.Time
- OrgID sql.Null[uuid.UUID]
- ProjectID sql.Null[string]
- ProjectName sql.Null[string]
-}
-
-// DAL provides data access for audit logs.
-type DAL struct {
- db pg.DB
-}
-
-// NewDAL creates a new audit log DAL.
-func NewDAL(db pg.DB) *DAL {
- return &DAL{db: db}
-}
-
-// Create inserts a new audit log record.
-func (d *DAL) Create(ctx context.Context, record *AuditLogRecord) error {
- auditLogs := table.AuditLogs
-
- stmt := auditLogs.INSERT(
- auditLogs.ID,
- auditLogs.Actor,
- auditLogs.ActorMetadata,
- auditLogs.IpAddress,
- auditLogs.EventType,
- auditLogs.EventMetadata,
- auditLogs.UserAgent,
- auditLogs.UserAgentType,
- auditLogs.ExpiresAt,
- auditLogs.CreatedAt,
- auditLogs.UpdatedAt,
- auditLogs.OrgId,
- auditLogs.ProjectId,
- auditLogs.ProjectName,
- ).MODEL(model.AuditLogs{
- ID: record.ID,
- Actor: record.Actor,
- ActorMetadata: record.ActorMetadata,
- IpAddress: record.IPAddress,
- EventType: record.EventType,
- EventMetadata: record.EventMetadata,
- UserAgent: record.UserAgent,
- UserAgentType: record.UserAgentType,
- ExpiresAt: record.ExpiresAt,
- CreatedAt: record.CreatedAt,
- UpdatedAt: record.UpdatedAt,
- OrgId: record.OrgID,
- ProjectId: record.ProjectID,
- ProjectName: record.ProjectName,
- })
-
- _, err := stmt.ExecContext(ctx, d.db.Primary())
- return err
-}
diff --git a/backend-go/internal/services/auditlog/queue_handler.go b/backend-go/internal/services/auditlog/queue_handler.go
index cb014e97c9..f2ff4ce11f 100644
--- a/backend-go/internal/services/auditlog/queue_handler.go
+++ b/backend-go/internal/services/auditlog/queue_handler.go
@@ -9,8 +9,10 @@ import (
"time"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
"github.com/infisical/api/internal/config"
+ "github.com/infisical/api/internal/database/pg"
"github.com/infisical/api/internal/keystore"
"github.com/infisical/api/internal/queue"
"github.com/infisical/api/internal/services/license"
@@ -19,6 +21,24 @@ import (
const auditLogClickHouseStreamKey = "audit-log-stream"
+// AuditLogRecord represents a single audit log entry for database operations.
+type AuditLogRecord struct {
+ ID uuid.UUID
+ Actor string
+ ActorMetadata string
+ IPAddress sql.Null[string]
+ EventType string
+ EventMetadata sql.Null[string]
+ UserAgent sql.Null[string]
+ UserAgentType sql.Null[string]
+ ExpiresAt sql.NullTime
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ OrgID sql.Null[uuid.UUID]
+ ProjectID sql.Null[string]
+ ProjectName sql.Null[string]
+}
+
// normalizeJSONPayload ensures the payload is an object for ClickHouse.
// Arrays are wrapped in {data: [...]}, objects pass through, others become {}.
func normalizeJSONPayload(payload any) any {
@@ -47,17 +67,17 @@ type licenseService interface {
// QueueHandlerDeps holds dependencies for the audit log queue handler.
type QueueHandlerDeps struct {
- DAL *DAL
- Project projectService
- License licenseService
- Config *config.Config
- KeyStore keystore.KeyStore
+ DB pg.DB
+ Project projectService
+ License licenseService
+ Config *config.Config
+ KeyStore keystore.KeyStore
}
// QueueHandler processes audit log tasks from the queue.
type QueueHandler struct {
logger *slog.Logger
- dal *DAL
+ db pg.DB
project projectService
license licenseService
config *config.Config
@@ -68,7 +88,7 @@ type QueueHandler struct {
func NewQueueHandler(logger *slog.Logger, deps QueueHandlerDeps) *QueueHandler {
return &QueueHandler{
logger: logger.With(slog.String("queue_handler", "auditlog")),
- dal: deps.DAL,
+ db: deps.DB,
project: deps.Project,
license: deps.License,
config: deps.Config,
@@ -216,7 +236,7 @@ func (h *QueueHandler) HandleAuditLog(ctx context.Context, dto *CreateAuditLogDT
}
if !h.config.DisableAuditLogStorage {
- if err := h.dal.Create(ctx, record); err != nil {
+ if err := h.createRecord(ctx, record); err != nil {
h.logger.ErrorContext(ctx, "failed to insert audit log",
slog.String("eventType", string(dto.Event.Type())),
slog.Any("error", err),
@@ -228,6 +248,39 @@ func (h *QueueHandler) HandleAuditLog(ctx context.Context, dto *CreateAuditLogDT
return nil
}
+func (h *QueueHandler) createRecord(ctx context.Context, record *AuditLogRecord) error {
+ query := `
+ INSERT INTO audit_logs (
+ id, actor, "actorMetadata", "ipAddress", "eventType", "eventMetadata",
+ "userAgent", "userAgentType", "expiresAt", "createdAt", "updatedAt",
+ "orgId", "projectId", "projectName"
+ ) VALUES (
+ @id, @actor, @actorMetadata, @ipAddress, @eventType, @eventMetadata,
+ @userAgent, @userAgentType, @expiresAt, @createdAt, @updatedAt,
+ @orgID, @projectID, @projectName
+ )
+ `
+ args := pgx.NamedArgs{
+ "id": record.ID,
+ "actor": record.Actor,
+ "actorMetadata": record.ActorMetadata,
+ "ipAddress": record.IPAddress,
+ "eventType": record.EventType,
+ "eventMetadata": record.EventMetadata,
+ "userAgent": record.UserAgent,
+ "userAgentType": record.UserAgentType,
+ "expiresAt": record.ExpiresAt,
+ "createdAt": record.CreatedAt,
+ "updatedAt": record.UpdatedAt,
+ "orgID": record.OrgID,
+ "projectID": record.ProjectID,
+ "projectName": record.ProjectName,
+ }
+
+ _, err := h.db.Primary().Exec(ctx, query, args)
+ return err
+}
+
func toNullStr(s string) sql.Null[string] {
if s == "" {
return sql.Null[string]{}
diff --git a/backend-go/internal/services/auth/handler.go b/backend-go/internal/services/auth/handler.go
index 1354b437fe..20f1ff7d07 100644
--- a/backend-go/internal/services/auth/handler.go
+++ b/backend-go/internal/services/auth/handler.go
@@ -554,9 +554,9 @@ type membershipRow struct {
// findSessionByIDAndUserID returns the session matching id + userId, or nil if not found.
func (a Authenticator) findSessionByIDAndUserID(ctx context.Context, sessionID, userID uuid.UUID) (*sessionRow, error) {
query := `
- SELECT access_version, user_id
+ SELECT "accessVersion", "userId"
FROM auth_token_sessions
- WHERE id = @sessionID AND user_id = @userID
+ WHERE id = @sessionID AND "userId" = @userID
`
args := pgx.NamedArgs{"sessionID": sessionID, "userID": userID}
@@ -575,7 +575,7 @@ func (a Authenticator) findSessionByIDAndUserID(ctx context.Context, sessionID,
// findUserByID returns the user matching id, or nil if not found.
func (a Authenticator) findUserByID(ctx context.Context, id uuid.UUID) (*userRow, error) {
query := `
- SELECT id, email, username, is_accepted, super_admin, is_locked, temporary_lock_date_end
+ SELECT id, email, username, "isAccepted", "superAdmin", "isLocked", "temporaryLockDateEnd"
FROM users
WHERE id = @id
`
@@ -596,7 +596,7 @@ func (a Authenticator) findUserByID(ctx context.Context, id uuid.UUID) (*userRow
// findOrgByID returns the organization matching id, or nil if not found.
func (a Authenticator) findOrgByID(ctx context.Context, id uuid.UUID) (*orgRow, error) {
query := `
- SELECT id, name, root_org_id, parent_org_id
+ SELECT id, name, "rootOrgId", "parentOrgId"
FROM organizations
WHERE id = @id
`
@@ -617,7 +617,7 @@ func (a Authenticator) findOrgByID(ctx context.Context, id uuid.UUID) (*orgRow,
// findProjectByID returns the project matching id, or nil if not found.
func (a Authenticator) findProjectByID(ctx context.Context, id string) (*projectRow, error) {
query := `
- SELECT org_id
+ SELECT "orgId"
FROM projects
WHERE id = @id
`
@@ -639,23 +639,23 @@ func (a Authenticator) findProjectByID(ctx context.Context, id string) (*project
func (a Authenticator) findIdentityAccessTokenByID(ctx context.Context, id string) (*identityAccessTokenRow, error) {
query := `
SELECT
- iat.id,
- iat.access_token_ttl,
- iat.access_token_max_ttl,
- iat.access_token_num_uses,
- iat.access_token_num_uses_limit,
- iat.access_token_last_renewed_at,
- iat.is_access_token_revoked,
- iat.identity_id,
- iat.created_at,
- iat.auth_method,
- iat.access_token_period,
- iat.sub_organization_id,
- i.org_id AS identity_org_id,
- i.name AS identity_name
- FROM identity_access_tokens iat
- INNER JOIN identities i ON iat.identity_id = i.id
- WHERE iat.id = @id AND iat.is_access_token_revoked = false
+ token.id,
+ token."accessTokenTTL",
+ token."accessTokenMaxTTL",
+ token."accessTokenNumUses",
+ token."accessTokenNumUsesLimit",
+ token."accessTokenLastRenewedAt",
+ token."isAccessTokenRevoked",
+ token."identityId",
+ token."createdAt",
+ token."authMethod",
+ token."accessTokenPeriod",
+ token."subOrganizationId",
+ identity."orgId" AS identity_org_id,
+ identity.name AS identity_name
+ FROM identity_access_tokens token
+ INNER JOIN identities identity ON token."identityId" = identity.id
+ WHERE token.id = @id AND token."isAccessTokenRevoked" = false
`
args := pgx.NamedArgs{"id": id}
@@ -697,7 +697,7 @@ func (a Authenticator) deleteIdentityAccessTokenByID(ctx context.Context, id uui
// findServiceTokenByID returns the service token matching id, or nil.
func (a Authenticator) findServiceTokenByID(ctx context.Context, id string) (*serviceTokenRow, error) {
query := `
- SELECT id, name, project_id, expires_at, secret_hash
+ SELECT id, name, "projectId", "expiresAt", "secretHash"
FROM service_tokens
WHERE id = @id
`
@@ -730,20 +730,20 @@ func (a Authenticator) findEffectiveOrgMembership(ctx context.Context, actorType
var actorCondition string
if actorType == actor.TypeUser {
actorCondition = `(
- m.actor_user_id = @actorID
- OR m.actor_group_id IN (
- SELECT g.id FROM groups g
- INNER JOIN user_group_membership ugm ON ugm.group_id = g.id
- WHERE ugm.user_id = @actorID
+ membership."actorUserId" = @actorID
+ OR membership."actorGroupId" IN (
+ SELECT grp.id FROM groups grp
+ INNER JOIN user_group_membership ugm ON ugm."groupId" = grp.id
+ WHERE ugm."userId" = @actorID
)
)`
} else {
actorCondition = `(
- m.actor_identity_id = @actorID
- OR m.actor_group_id IN (
- SELECT g.id FROM groups g
- INNER JOIN identity_group_membership igm ON igm.group_id = g.id
- WHERE igm.identity_id = @actorID
+ membership."actorIdentityId" = @actorID
+ OR membership."actorGroupId" IN (
+ SELECT grp.id FROM groups grp
+ INNER JOIN identity_group_membership igm ON igm."groupId" = grp.id
+ WHERE igm."identityId" = @actorID
)
)`
}
@@ -754,12 +754,12 @@ func (a Authenticator) findEffectiveOrgMembership(ctx context.Context, actorType
}
query := fmt.Sprintf(`
- SELECT m.is_active
- FROM memberships m
- WHERE m.scope = 'organization'
- AND m.scope_org_id = @orgID
+ SELECT membership."isActive"
+ FROM memberships membership
+ WHERE membership.scope = 'organization'
+ AND membership."scopeOrgId" = @orgID
AND %s
- AND (m.status = @status OR m.status IS NULL)
+ AND (membership.status = @status OR membership.status IS NULL)
LIMIT 1
`, actorCondition)
@@ -817,9 +817,9 @@ func (a Authenticator) findTrustedIPsByAuthMethod(ctx context.Context, identityI
}
query := fmt.Sprintf(`
- SELECT access_token_trusted_ips
+ SELECT "accessTokenTrustedIps"
FROM %s
- WHERE identity_id = @identityID
+ WHERE "identityId" = @identityID
LIMIT 1
`, tableName)
@@ -840,12 +840,6 @@ func (a Authenticator) findTrustedIPsByAuthMethod(ctx context.Context, identityI
// --- Helpers ---
-// parseUUID parses a string to uuid.UUID. Returns uuid.Nil on failure.
-func parseUUID(s string) uuid.UUID {
- id, _ := uuid.Parse(s)
- return id
-}
-
// nullUUIDValid returns true when the nullable UUID is present and non-nil.
func nullUUIDValid(n sql.Null[uuid.UUID]) bool {
return n.Valid && n.V != uuid.Nil
diff --git a/backend-go/internal/services/kms/kms.go b/backend-go/internal/services/kms/kms.go
index e717841c2a..e7ce5768e0 100644
--- a/backend-go/internal/services/kms/kms.go
+++ b/backend-go/internal/services/kms/kms.go
@@ -408,8 +408,8 @@ type kmsKeyWithAssociatedKms struct {
Name string `db:"name"`
// Internal KMS fields (nullable from LEFT JOIN)
- InternalKmsID sql.Null[uuid.UUID] `db:"internal_kms_id"`
- InternalEncryptedKey sql.Null[[]byte] `db:"internal_encrypted_key"`
+ InternalKmsID sql.Null[uuid.UUID] `db:"internal_kms_id"`
+ InternalEncryptedKey sql.Null[[]byte] `db:"internal_encrypted_key"`
InternalEncryptionAlgorithm sql.Null[string] `db:"internal_encryption_algorithm"`
// External KMS fields (nullable from LEFT JOIN)
@@ -435,19 +435,19 @@ type projectKmsInfo struct {
// findSuperAdminConfig returns the super_admin config row if it exists.
func (s *Service) findSuperAdminConfig(ctx context.Context) (*superAdminConfigRow, error) {
- query := `SELECT fips_enabled FROM super_admin WHERE id = @id`
+ query := `SELECT "fipsEnabled" FROM super_admin WHERE id = @id`
args := pgx.NamedArgs{"id": superAdminConfigUUID}
row := s.db.Replica().QueryRow(ctx, query, args)
- var config superAdminConfigRow
- err := row.Scan(&config.FipsEnabled)
+ var cfg superAdminConfigRow
+ err := row.Scan(&cfg.FipsEnabled)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("finding super_admin config: %w", err)
}
- return &config, nil
+ return &cfg, nil
}
// findOrCreateRootConfig atomically ensures the KMS root config row exists.
@@ -456,7 +456,7 @@ func (s *Service) findOrCreateRootConfig(ctx context.Context, createFn func() (e
if err != nil {
return nil, fmt.Errorf("beginning transaction: %w", err)
}
- defer tx.Rollback(ctx) //nolint:errcheck
+ defer tx.Rollback(ctx) //nolint:errcheck // rollback on defer is best-effort cleanup
// Acquire advisory lock
if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock($1)", PgLockKmsRootKeyInit); err != nil {
@@ -464,7 +464,7 @@ func (s *Service) findOrCreateRootConfig(ctx context.Context, createFn func() (e
}
// Check if root config already exists.
- checkQuery := `SELECT id, encrypted_root_key, encryption_strategy FROM kms_root_config WHERE id = @id`
+ checkQuery := `SELECT id, "encryptedRootKey", "encryptionStrategy" FROM kms_root_config WHERE id = @id`
checkArgs := pgx.NamedArgs{"id": KmsRootConfigUUID}
row := tx.QueryRow(ctx, checkQuery, checkArgs)
@@ -488,9 +488,9 @@ func (s *Service) findOrCreateRootConfig(ctx context.Context, createFn func() (e
// Create the initial root config row.
insertQuery := `
- INSERT INTO kms_root_config (id, encrypted_root_key, encryption_strategy)
+ INSERT INTO kms_root_config (id, "encryptedRootKey", "encryptionStrategy")
VALUES (@id, @encryptedRootKey, @encryptionStrategy)
- RETURNING id, encrypted_root_key, encryption_strategy
+ RETURNING id, "encryptedRootKey", "encryptionStrategy"
`
insertArgs := pgx.NamedArgs{
"id": KmsRootConfigUUID,
@@ -515,16 +515,16 @@ func (s *Service) findOrCreateRootConfig(ctx context.Context, createFn func() (e
func (s *Service) findKmsKeyByID(ctx context.Context, kmsKeyID uuid.UUID) (*kmsKeyWithAssociatedKms, error) {
query := `
SELECT
- k.id,
- k.name,
- ik.id AS internal_kms_id,
- ik.encrypted_key AS internal_encrypted_key,
- ik.encryption_algorithm AS internal_encryption_algorithm,
- ek.id AS external_kms_id
- FROM kms_keys k
- LEFT JOIN internal_kms ik ON ik.kms_key_id = k.id
- LEFT JOIN external_kms ek ON ek.kms_key_id = k.id
- WHERE k.id = @kmsKeyID
+ kmsKey.id,
+ kmsKey.name,
+ internalKms.id AS internal_kms_id,
+ internalKms."encryptedKey" AS internal_encrypted_key,
+ internalKms."encryptionAlgorithm" AS internal_encryption_algorithm,
+ externalKms.id AS external_kms_id
+ FROM kms_keys kmsKey
+ LEFT JOIN internal_kms internalKms ON internalKms."kmsKeyId" = kmsKey.id
+ LEFT JOIN external_kms externalKms ON externalKms."kmsKeyId" = kmsKey.id
+ WHERE kmsKey.id = @kmsKeyID
`
args := pgx.NamedArgs{"kmsKeyID": kmsKeyID}
@@ -547,7 +547,7 @@ func (s *Service) findKmsKeyByID(ctx context.Context, kmsKeyID uuid.UUID) (*kmsK
// findOrgKmsInfo returns the narrow org fields needed for KMS data key operations.
func (s *Service) findOrgKmsInfo(ctx context.Context, orgID uuid.UUID) (*orgKmsInfo, error) {
query := `
- SELECT id, kms_default_key_id, kms_encrypted_data_key
+ SELECT id, "kmsDefaultKeyId", "kmsEncryptedDataKey"
FROM organizations
WHERE id = @orgID
`
@@ -565,7 +565,7 @@ func (s *Service) findOrgKmsInfo(ctx context.Context, orgID uuid.UUID) (*orgKmsI
// findOrgKmsInfoTx returns org KMS info within a transaction.
func (s *Service) findOrgKmsInfoTx(ctx context.Context, tx pgx.Tx, orgID uuid.UUID) (*orgKmsInfo, error) {
query := `
- SELECT id, kms_default_key_id, kms_encrypted_data_key
+ SELECT id, "kmsDefaultKeyId", "kmsEncryptedDataKey"
FROM organizations
WHERE id = @orgID
`
@@ -583,7 +583,7 @@ func (s *Service) findOrgKmsInfoTx(ctx context.Context, tx pgx.Tx, orgID uuid.UU
// findProjectKmsInfo returns the narrow project fields needed for KMS data key operations.
func (s *Service) findProjectKmsInfo(ctx context.Context, projectID string) (*projectKmsInfo, error) {
query := `
- SELECT id, org_id, kms_secret_manager_key_id, kms_secret_manager_encrypted_data_key
+ SELECT id, "orgId", "kmsSecretManagerKeyId", "kmsSecretManagerEncryptedDataKey"
FROM projects
WHERE id = @projectID
`
@@ -601,7 +601,7 @@ func (s *Service) findProjectKmsInfo(ctx context.Context, projectID string) (*pr
// findProjectKmsInfoTx returns project KMS info within a transaction.
func (s *Service) findProjectKmsInfoTx(ctx context.Context, tx pgx.Tx, projectID string) (*projectKmsInfo, error) {
query := `
- SELECT id, org_id, kms_secret_manager_key_id, kms_secret_manager_encrypted_data_key
+ SELECT id, "orgId", "kmsSecretManagerKeyId", "kmsSecretManagerEncryptedDataKey"
FROM projects
WHERE id = @projectID
`
@@ -622,7 +622,7 @@ func (s *Service) createKmsKeyWithInternal(ctx context.Context, tx pgx.Tx, orgID
// Insert kms_keys
insertKeyQuery := `
- INSERT INTO kms_keys (name, org_id, is_reserved, key_usage)
+ INSERT INTO kms_keys (name, "orgId", "isReserved", "keyUsage")
VALUES (@name, @orgID, true, 'encrypt-decrypt')
RETURNING id
`
@@ -639,7 +639,7 @@ func (s *Service) createKmsKeyWithInternal(ctx context.Context, tx pgx.Tx, orgID
// Insert internal_kms
insertInternalQuery := `
- INSERT INTO internal_kms (encrypted_key, encryption_algorithm, version, kms_key_id)
+ INSERT INTO internal_kms ("encryptedKey", "encryptionAlgorithm", version, "kmsKeyId")
VALUES (@encryptedKey, 'aes-256-gcm', 1, @kmsKeyID)
`
internalArgs := pgx.NamedArgs{
@@ -665,14 +665,14 @@ func (s *Service) findOrCreateOrgKmsKey(ctx context.Context, orgID uuid.UUID, cr
lock, err := pglock.AcquireBlockingLock(ctx, tx, lockID)
if err != nil {
- tx.Rollback(ctx) //nolint:errcheck
+ tx.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return uuid.Nil, fmt.Errorf("acquiring org key lock: %w", err)
}
// Re-check after lock — another request may have created it.
org, err := s.findOrgKmsInfoTx(ctx, tx, orgID)
if err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return uuid.Nil, fmt.Errorf("finding org: %w", err)
}
if org.KmsDefaultKeyID.Valid {
@@ -684,21 +684,21 @@ func (s *Service) findOrCreateOrgKmsKey(ctx context.Context, orgID uuid.UUID, cr
encryptedKey, err := createFn()
if err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return uuid.Nil, fmt.Errorf("generating KMS key: %w", err)
}
createdID, err := s.createKmsKeyWithInternal(ctx, tx, org.ID, encryptedKey)
if err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return uuid.Nil, err
}
// Update org with new key ID
- updateQuery := `UPDATE organizations SET kms_default_key_id = @keyID WHERE id = @orgID`
+ updateQuery := `UPDATE organizations SET "kmsDefaultKeyId" = @keyID WHERE id = @orgID`
updateArgs := pgx.NamedArgs{"keyID": createdID, "orgID": orgID}
if _, err := tx.Exec(ctx, updateQuery, updateArgs); err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return uuid.Nil, fmt.Errorf("updating org default key: %w", err)
}
@@ -719,14 +719,14 @@ func (s *Service) findOrCreateOrgDataKey(ctx context.Context, orgID uuid.UUID, c
lock, err := pglock.AcquireBlockingLock(ctx, tx, lockID)
if err != nil {
- tx.Rollback(ctx) //nolint:errcheck
+ tx.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return nil, fmt.Errorf("acquiring org data key lock: %w", err)
}
// Re-check after lock — another request may have created it.
org, err := s.findOrgKmsInfoTx(ctx, tx, orgID)
if err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return nil, fmt.Errorf("finding org: %w", err)
}
if len(org.KmsEncryptedDataKey) > 0 {
@@ -738,14 +738,14 @@ func (s *Service) findOrCreateOrgDataKey(ctx context.Context, orgID uuid.UUID, c
encryptedDataKey, err := createFn()
if err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return nil, fmt.Errorf("generating data key: %w", err)
}
- updateQuery := `UPDATE organizations SET kms_encrypted_data_key = @dataKey WHERE id = @orgID`
+ updateQuery := `UPDATE organizations SET "kmsEncryptedDataKey" = @dataKey WHERE id = @orgID`
updateArgs := pgx.NamedArgs{"dataKey": encryptedDataKey, "orgID": orgID}
if _, err := tx.Exec(ctx, updateQuery, updateArgs); err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return nil, fmt.Errorf("setting org encrypted data key: %w", err)
}
@@ -766,14 +766,14 @@ func (s *Service) findOrCreateProjectKmsKey(ctx context.Context, projectID strin
lock, err := pglock.AcquireBlockingLock(ctx, tx, lockID)
if err != nil {
- tx.Rollback(ctx) //nolint:errcheck
+ tx.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return uuid.Nil, fmt.Errorf("acquiring project key lock: %w", err)
}
// Re-check after lock — another request may have created it.
project, err := s.findProjectKmsInfoTx(ctx, tx, projectID)
if err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return uuid.Nil, fmt.Errorf("finding project: %w", err)
}
if project.KmsSecretManagerKeyID.Valid {
@@ -785,20 +785,20 @@ func (s *Service) findOrCreateProjectKmsKey(ctx context.Context, projectID strin
encryptedKey, err := createFn()
if err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return uuid.Nil, fmt.Errorf("generating KMS key: %w", err)
}
createdID, err := s.createKmsKeyWithInternal(ctx, tx, project.OrgID, encryptedKey)
if err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return uuid.Nil, err
}
- updateQuery := `UPDATE projects SET kms_secret_manager_key_id = @keyID WHERE id = @projectID`
+ updateQuery := `UPDATE projects SET "kmsSecretManagerKeyId" = @keyID WHERE id = @projectID`
updateArgs := pgx.NamedArgs{"keyID": createdID, "projectID": projectID}
if _, err := tx.Exec(ctx, updateQuery, updateArgs); err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return uuid.Nil, fmt.Errorf("updating project KMS key: %w", err)
}
@@ -819,14 +819,14 @@ func (s *Service) findOrCreateProjectDataKey(ctx context.Context, projectID stri
lock, err := pglock.AcquireBlockingLock(ctx, tx, lockID)
if err != nil {
- tx.Rollback(ctx) //nolint:errcheck
+ tx.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return nil, fmt.Errorf("acquiring project data key lock: %w", err)
}
// Re-check after lock — another request may have created it.
project, err := s.findProjectKmsInfoTx(ctx, tx, projectID)
if err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return nil, fmt.Errorf("finding project: %w", err)
}
if len(project.KmsSecretManagerEncryptedDataKey) > 0 {
@@ -838,14 +838,14 @@ func (s *Service) findOrCreateProjectDataKey(ctx context.Context, projectID stri
encryptedDataKey, err := createFn()
if err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return nil, fmt.Errorf("generating data key: %w", err)
}
- updateQuery := `UPDATE projects SET kms_secret_manager_encrypted_data_key = @dataKey WHERE id = @projectID`
+ updateQuery := `UPDATE projects SET "kmsSecretManagerEncryptedDataKey" = @dataKey WHERE id = @projectID`
updateArgs := pgx.NamedArgs{"dataKey": encryptedDataKey, "projectID": projectID}
if _, err := tx.Exec(ctx, updateQuery, updateArgs); err != nil {
- lock.Rollback(ctx) //nolint:errcheck
+ lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
return nil, fmt.Errorf("setting project encrypted data key: %w", err)
}
diff --git a/backend-go/internal/services/kms/kms_integration_test.go b/backend-go/internal/services/kms/kms_integration_test.go
index 83cc12edb7..abcfbb8d5f 100644
--- a/backend-go/internal/services/kms/kms_integration_test.go
+++ b/backend-go/internal/services/kms/kms_integration_test.go
@@ -12,7 +12,6 @@ import (
"github.com/google/uuid"
"github.com/stretchr/testify/require"
- "github.com/infisical/api/internal/keystore"
"github.com/infisical/api/internal/services/kms"
"github.com/infisical/api/internal/testutil/infra"
)
@@ -44,14 +43,8 @@ func TestMain(m *testing.M) {
func setupService(t *testing.T) *kms.Service {
t.Helper()
- redisClient := stack.Redis().Client()
- t.Cleanup(func() { redisClient.Close() })
-
- ks := keystore.NewKeyStore(redisClient, stack.DB().Primary())
- dal := kms.NewDAL(stack.DB(), ks)
-
svc, err := kms.NewService(kms.Deps{
- DAL: dal,
+ DB: stack.DB(),
HSM: nil,
Config: stack.Config(),
})
diff --git a/backend-go/internal/services/libs.go b/backend-go/internal/services/libs.go
index e1a8f736c2..fe698b325f 100644
--- a/backend-go/internal/services/libs.go
+++ b/backend-go/internal/services/libs.go
@@ -64,14 +64,13 @@ func NewServices(ctx context.Context, deps *ServicesDeps) (*Services, error) {
projectSvc := project.NewService(deps.Logger, project.Deps{DB: deps.DB})
- auditLogDAL := auditlog.NewDAL(deps.DB)
auditLogSvc := auditlog.NewService(deps.Logger, auditlog.Deps{
Queue: deps.Queue,
Config: deps.Config,
})
auditLogQueueHandler := auditlog.NewQueueHandler(deps.Logger, auditlog.QueueHandlerDeps{
- DAL: auditLogDAL,
+ DB: deps.DB,
Project: projectSvc,
License: licenseSvc,
Config: deps.Config,
diff --git a/backend-go/internal/services/permission/dal.go b/backend-go/internal/services/permission/dal.go
deleted file mode 100644
index f8bd7f9390..0000000000
--- a/backend-go/internal/services/permission/dal.go
+++ /dev/null
@@ -1,396 +0,0 @@
-package permission
-
-import (
- "context"
- "database/sql"
- "errors"
- "time"
-
- "github.com/google/uuid"
- "github.com/jackc/pgx/v5"
-
- "github.com/infisical/api/internal/database/pg"
- "github.com/infisical/api/internal/database/pg/qb"
- "github.com/infisical/api/internal/database/pg/sqln"
- "github.com/infisical/api/internal/libs/fn"
-)
-
-// --- Types ---
-
-// AccessScope determines whether the permission query is for an organization or project.
-type AccessScope string
-
-const (
- AccessScopeOrganization AccessScope = "organization"
- AccessScopeProject AccessScope = "project"
-)
-
-// getPermissionParams holds the input for the main permission query.
-type getPermissionParams struct {
- Scope AccessScope
- OrgID uuid.UUID
- ProjectID string
- ActorID uuid.UUID
- ActorType ActorType
-}
-
-// RoleInfo represents a single role assignment from the permission query.
-type RoleInfo struct {
- ID uuid.UUID
- Role string
- IsTemporary sql.Null[bool]
- TemporaryAccessEndTime sql.Null[time.Time]
- CustomRoleSlug sql.Null[string]
- Permissions sql.Null[string]
-}
-
-// AdditionalPrivilegeInfo represents an additional privilege from the permission query.
-type AdditionalPrivilegeInfo struct {
- ID uuid.UUID
- Permissions sql.Null[string]
- IsTemporary sql.Null[bool]
- TemporaryAccessEndTime sql.Null[time.Time]
-}
-
-// MetadataInfo represents identity metadata key-value pair.
-type MetadataInfo struct {
- ID uuid.UUID
- Key string
- Value string
-}
-
-// permissionData is the nested result of the permission query.
-type permissionData struct {
- ID uuid.UUID
- ScopeOrgID uuid.UUID
- OrgAuthEnforced sql.Null[bool]
- OrgGoogleSsoAuthEnforced bool
- BypassOrgAuthEnabled bool
- ShouldUseNewPrivilegeSystem bool
- RootOrgID sql.Null[uuid.UUID]
- Roles []RoleInfo
- AdditionalPrivileges []AdditionalPrivilegeInfo
- Metadata []MetadataInfo
-}
-
-// projectDetail holds project info needed by the permission service.
-type projectDetail struct {
- ID string
- Name string
- Slug string
- OrgID uuid.UUID
- Type string
- EnforceEncryptedSecretManagerSecretMetadata bool
-}
-
-// serviceTokenDetail holds service token info needed by the permission service.
-type serviceTokenDetail struct {
- ID string
- ProjectID string
- ExpiresAt *time.Time
- Scopes string
- Permissions []string
-}
-
-// permissionGrouper groups flat permission rows by membership ID.
-var permissionGrouper = sqln.Grouper[permissionData, uuid.UUID]{
- Key: func(p *permissionData) uuid.UUID { return p.ID },
- Merge: func(existing, row *permissionData) {
- if len(row.Roles) > 0 {
- existing.Roles = fn.AppendUnique(existing.Roles, row.Roles[0], func(r RoleInfo) uuid.UUID { return r.ID })
- }
- if len(row.AdditionalPrivileges) > 0 {
- existing.AdditionalPrivileges = fn.AppendUnique(existing.AdditionalPrivileges, row.AdditionalPrivileges[0], func(a AdditionalPrivilegeInfo) uuid.UUID { return a.ID })
- }
- if len(row.Metadata) > 0 {
- existing.Metadata = fn.AppendUnique(existing.Metadata, row.Metadata[0], func(m MetadataInfo) uuid.UUID { return m.ID })
- }
- },
-}
-
-// --- Query methods on Service ---
-
-// getPermission executes the main permission join query.
-func (s *Service) getPermission(ctx context.Context, params *getPermissionParams) ([]permissionData, error) {
- // Build actor subquery for group membership
- var groupSubquery string
- if params.ActorType == ActorTypeUser {
- groupSubquery = `
- SELECT g.id FROM groups g
- INNER JOIN user_group_membership ugm ON ugm.group_id = g.id
- WHERE ugm.user_id = @actorID
- `
- } else {
- groupSubquery = `
- SELECT g.id FROM groups g
- INNER JOIN identity_group_membership igm ON igm.group_id = g.id
- WHERE igm.identity_id = @actorID
- `
- }
-
- // Build WHERE conditions using qb.Where
- where := qb.NewWhere().Add("m.scope_org_id = @orgID")
-
- // Actor condition
- if params.ActorType == ActorTypeUser {
- where.Add("(m.actor_user_id = @actorID OR m.actor_group_id IN (" + groupSubquery + "))")
- } else {
- where.Add("(m.actor_identity_id = @actorID OR m.actor_group_id IN (" + groupSubquery + "))")
- }
-
- // Scope condition
- if params.Scope == AccessScopeOrganization {
- where.Add("m.scope = 'organization'")
- } else {
- where.Add("m.scope = 'project'").Add("m.scope_project_id = @projectID")
- }
-
- // Build additional privilege join condition
- apJoinCond := qb.NewWhere()
- if params.ActorType == ActorTypeIdentity {
- apJoinCond.Add("m.actor_identity_id = ap.actor_identity_id")
- } else {
- apJoinCond.Add("m.actor_user_id = ap.actor_user_id")
- }
- if params.Scope == AccessScopeOrganization {
- apJoinCond.Add("m.scope_org_id = ap.org_id")
- } else {
- apJoinCond.Add("m.scope_project_id = ap.project_id")
- }
-
- // Build metadata join condition
- metaJoinCond := qb.NewWhere()
- if params.ActorType == ActorTypeUser {
- metaJoinCond.Add("im.user_id = @actorID").Add("m.scope_org_id = im.org_id")
- } else {
- metaJoinCond.Add("im.identity_id = @actorID")
- }
-
- query := `
- SELECT
- m.id AS membership_id,
- m.scope_org_id,
- o.auth_enforced,
- o.google_sso_auth_enforced,
- o.bypass_org_auth_enabled,
- o.should_use_new_privilege_system,
- o.root_org_id,
- mr.id AS role_id,
- mr.role,
- mr.is_temporary AS role_is_temporary,
- mr.temporary_access_end_time AS role_temporary_access_end_time,
- r.slug AS custom_role_slug,
- r.permissions AS custom_role_permissions,
- ap.id AS ap_id,
- ap.permissions AS ap_permissions,
- ap.is_temporary AS ap_is_temporary,
- ap.temporary_access_end_time AS ap_temporary_access_end_time,
- im.id AS meta_id,
- im.key AS meta_key,
- im.value AS meta_value
- FROM memberships m
- INNER JOIN membership_roles mr ON m.id = mr.membership_id
- INNER JOIN organizations o ON m.scope_org_id = o.id
- LEFT JOIN roles r ON mr.custom_role_id = r.id
- LEFT JOIN additional_privileges ap ON ` + apJoinCond.String() + `
- LEFT JOIN identity_metadata im ON ` + metaJoinCond.String() + `
- WHERE ` + where.String()
-
- args := pgx.NamedArgs{
- "orgID": params.OrgID,
- "actorID": params.ActorID,
- "projectID": params.ProjectID,
- }
-
- rows, err := s.db.Replica().Query(ctx, query, args)
- if err != nil {
- return nil, err
- }
-
- flatRows, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (permissionData, error) {
- var (
- membershipID uuid.UUID
- scopeOrgID uuid.UUID
- orgAuthEnforced sql.Null[bool]
- orgGoogleSsoAuthEnforced bool
- orgBypassOrgAuthEnabled bool
- orgShouldUseNewPrivSys bool
- orgRootOrgID sql.Null[uuid.UUID]
- roleID sql.Null[uuid.UUID]
- role sql.Null[string]
- roleIsTemporary sql.Null[bool]
- roleTemporaryEndTime sql.Null[time.Time]
- customRoleSlug sql.Null[string]
- customRolePermissions sql.Null[string]
- apID sql.Null[uuid.UUID]
- apPermissions sql.Null[string]
- apIsTemporary sql.Null[bool]
- apTemporaryEndTime sql.Null[time.Time]
- metaID sql.Null[uuid.UUID]
- metaKey sql.Null[string]
- metaValue sql.Null[string]
- )
-
- if err := row.Scan(
- &membershipID, &scopeOrgID,
- &orgAuthEnforced, &orgGoogleSsoAuthEnforced, &orgBypassOrgAuthEnabled,
- &orgShouldUseNewPrivSys, &orgRootOrgID,
- &roleID, &role, &roleIsTemporary, &roleTemporaryEndTime,
- &customRoleSlug, &customRolePermissions,
- &apID, &apPermissions, &apIsTemporary, &apTemporaryEndTime,
- &metaID, &metaKey, &metaValue,
- ); err != nil {
- return permissionData{}, err
- }
-
- data := permissionData{
- ID: membershipID,
- ScopeOrgID: scopeOrgID,
- OrgAuthEnforced: orgAuthEnforced,
- OrgGoogleSsoAuthEnforced: orgGoogleSsoAuthEnforced,
- BypassOrgAuthEnabled: orgBypassOrgAuthEnabled,
- ShouldUseNewPrivilegeSystem: orgShouldUseNewPrivSys,
- RootOrgID: orgRootOrgID,
- }
-
- if roleID.Valid {
- data.Roles = []RoleInfo{{
- ID: roleID.V,
- Role: role.V,
- IsTemporary: roleIsTemporary,
- TemporaryAccessEndTime: roleTemporaryEndTime,
- CustomRoleSlug: customRoleSlug,
- Permissions: customRolePermissions,
- }}
- }
-
- if apID.Valid {
- data.AdditionalPrivileges = []AdditionalPrivilegeInfo{{
- ID: apID.V,
- Permissions: apPermissions,
- IsTemporary: apIsTemporary,
- TemporaryAccessEndTime: apTemporaryEndTime,
- }}
- }
-
- if metaID.Valid {
- data.Metadata = []MetadataInfo{{
- ID: metaID.V,
- Key: metaKey.V,
- Value: metaValue.V,
- }}
- }
-
- return data, nil
- })
- if err != nil {
- return nil, err
- }
-
- if len(flatRows) == 0 {
- return nil, nil
- }
-
- return sqln.GroupRows(flatRows, permissionGrouper), nil
-}
-
-// findProjectByID returns basic project details needed for permission checks.
-func (s *Service) findProjectByID(ctx context.Context, projectID string) (*projectDetail, error) {
- query := `
- SELECT id, name, slug, org_id, type, enforce_encrypted_secret_manager_secret_metadata
- FROM projects
- WHERE id = @projectID
- `
- args := pgx.NamedArgs{"projectID": projectID}
-
- row := s.db.Replica().QueryRow(ctx, query, args)
-
- var id, name, slug string
- var orgID uuid.UUID
- var projectType sql.Null[string]
- var enforceEncrypted sql.Null[bool]
-
- err := row.Scan(&id, &name, &slug, &orgID, &projectType, &enforceEncrypted)
- if errors.Is(err, pgx.ErrNoRows) {
- return nil, nil
- }
- if err != nil {
- return nil, err
- }
-
- return &projectDetail{
- ID: id,
- Name: name,
- Slug: slug,
- OrgID: orgID,
- Type: projectType.V,
- EnforceEncryptedSecretManagerSecretMetadata: enforceEncrypted.Valid && enforceEncrypted.V,
- }, nil
-}
-
-// findUserUsername returns the username for a user by ID.
-func (s *Service) findUserUsername(ctx context.Context, userID uuid.UUID) (string, error) {
- query := `SELECT username FROM users WHERE id = @userID`
- args := pgx.NamedArgs{"userID": userID}
-
- var username string
- err := s.db.Replica().QueryRow(ctx, query, args).Scan(&username)
- if err != nil {
- return "", err
- }
- return username, nil
-}
-
-// findIdentityName returns the name for an identity by ID.
-func (s *Service) findIdentityName(ctx context.Context, identityID uuid.UUID) (string, error) {
- query := `SELECT name FROM identities WHERE id = @identityID`
- args := pgx.NamedArgs{"identityID": identityID}
-
- var name string
- err := s.db.Replica().QueryRow(ctx, query, args).Scan(&name)
- if err != nil {
- return "", err
- }
- return name, nil
-}
-
-// findServiceTokenByID returns service token details needed for permission checks.
-func (s *Service) findServiceTokenByID(ctx context.Context, tokenID string) (*serviceTokenDetail, error) {
- query := `
- SELECT id, project_id, expires_at, scopes, permissions
- FROM service_tokens
- WHERE id = @tokenID
- `
- args := pgx.NamedArgs{"tokenID": tokenID}
-
- row := s.db.Replica().QueryRow(ctx, query, args)
-
- var id, projectID, scopes string
- var expiresAt sql.Null[time.Time]
- var permissions []string
-
- err := row.Scan(&id, &projectID, &expiresAt, &scopes, &permissions)
- if errors.Is(err, pgx.ErrNoRows) {
- return nil, nil
- }
- if err != nil {
- return nil, err
- }
-
- detail := &serviceTokenDetail{
- ID: id,
- ProjectID: projectID,
- Scopes: scopes,
- Permissions: permissions,
- }
- if expiresAt.Valid {
- detail.ExpiresAt = &expiresAt.V
- }
- return detail, nil
-}
-
-// NewDAL is kept for backward compatibility during migration.
-// Deprecated: Use service methods directly.
-func NewDAL(db pg.DB) *Service {
- return &Service{db: db}
-}
diff --git a/backend-go/internal/services/permission/permission.go b/backend-go/internal/services/permission/permission.go
index 3eeffe60f3..6d66dfdd7e 100644
--- a/backend-go/internal/services/permission/permission.go
+++ b/backend-go/internal/services/permission/permission.go
@@ -2,16 +2,22 @@ package permission
import (
"context"
+ "database/sql"
"encoding/json"
+ "errors"
"fmt"
"log/slog"
"time"
"github.com/google/uuid"
"github.com/infisical/gocasl"
+ "github.com/jackc/pgx/v5"
"github.com/infisical/api/internal/database/pg"
+ "github.com/infisical/api/internal/database/pg/qb"
+ "github.com/infisical/api/internal/database/pg/sqln"
"github.com/infisical/api/internal/libs/errutil"
+ "github.com/infisical/api/internal/libs/fn"
"github.com/infisical/api/internal/services/actor"
"github.com/infisical/api/internal/services/permission/project"
)
@@ -445,3 +451,377 @@ func buildIdentityAuthMap(ctx context.Context, actorID uuid.UUID) map[string]any
return result
}
+
+// --- Query Types ---
+
+// AccessScope determines whether the permission query is for an organization or project.
+type AccessScope string
+
+const (
+ AccessScopeOrganization AccessScope = "organization"
+ AccessScopeProject AccessScope = "project"
+)
+
+// getPermissionParams holds the input for the main permission query.
+type getPermissionParams struct {
+ Scope AccessScope
+ OrgID uuid.UUID
+ ProjectID string
+ ActorID uuid.UUID
+ ActorType ActorType
+}
+
+// RoleInfo represents a single role assignment from the permission query.
+type RoleInfo struct {
+ ID uuid.UUID
+ Role string
+ IsTemporary sql.Null[bool]
+ TemporaryAccessEndTime sql.Null[time.Time]
+ CustomRoleSlug sql.Null[string]
+ Permissions sql.Null[string]
+}
+
+// AdditionalPrivilegeInfo represents an additional privilege from the permission query.
+type AdditionalPrivilegeInfo struct {
+ ID uuid.UUID
+ Permissions sql.Null[string]
+ IsTemporary sql.Null[bool]
+ TemporaryAccessEndTime sql.Null[time.Time]
+}
+
+// MetadataInfo represents identity metadata key-value pair.
+type MetadataInfo struct {
+ ID uuid.UUID
+ Key string
+ Value string
+}
+
+// permissionData is the nested result of the permission query.
+type permissionData struct {
+ ID uuid.UUID
+ ScopeOrgID uuid.UUID
+ OrgAuthEnforced sql.Null[bool]
+ OrgGoogleSsoAuthEnforced bool
+ BypassOrgAuthEnabled bool
+ ShouldUseNewPrivilegeSystem bool
+ RootOrgID sql.Null[uuid.UUID]
+ Roles []RoleInfo
+ AdditionalPrivileges []AdditionalPrivilegeInfo
+ Metadata []MetadataInfo
+}
+
+// projectDetail holds project info needed by the permission service.
+type projectDetail struct {
+ ID string
+ Name string
+ Slug string
+ OrgID uuid.UUID
+ Type string
+ EnforceEncryptedSecretManagerSecretMetadata bool
+}
+
+// serviceTokenDetail holds service token info needed by the permission service.
+type serviceTokenDetail struct {
+ ID string
+ ProjectID string
+ ExpiresAt *time.Time
+ Scopes string
+ Permissions []string
+}
+
+// permissionGrouper groups flat permission rows by membership ID.
+var permissionGrouper = sqln.Grouper[permissionData, uuid.UUID]{
+ Key: func(p *permissionData) uuid.UUID { return p.ID },
+ Merge: func(existing, row *permissionData) {
+ if len(row.Roles) > 0 {
+ existing.Roles = fn.AppendUnique(existing.Roles, row.Roles[0], func(r RoleInfo) uuid.UUID { return r.ID })
+ }
+ if len(row.AdditionalPrivileges) > 0 {
+ existing.AdditionalPrivileges = fn.AppendUnique(existing.AdditionalPrivileges, row.AdditionalPrivileges[0], func(a AdditionalPrivilegeInfo) uuid.UUID { return a.ID })
+ }
+ if len(row.Metadata) > 0 {
+ existing.Metadata = fn.AppendUnique(existing.Metadata, row.Metadata[0], func(m MetadataInfo) uuid.UUID { return m.ID })
+ }
+ },
+}
+
+// --- Query methods ---
+
+// getPermission executes the main permission join query.
+func (s *Service) getPermission(ctx context.Context, params *getPermissionParams) ([]permissionData, error) {
+ // Build actor subquery for group membership
+ var groupSubquery string
+ if params.ActorType == ActorTypeUser {
+ groupSubquery = `
+ SELECT grp.id FROM groups grp
+ INNER JOIN user_group_membership ugm ON ugm."groupId" = grp.id
+ WHERE ugm."userId" = @actorID
+ `
+ } else {
+ groupSubquery = `
+ SELECT grp.id FROM groups grp
+ INNER JOIN identity_group_membership igm ON igm."groupId" = grp.id
+ WHERE igm."identityId" = @actorID
+ `
+ }
+
+ // Build WHERE conditions using qb.Where
+ where := qb.NewWhere().Add(`membership."scopeOrgId" = @orgID`)
+
+ // Actor condition
+ if params.ActorType == ActorTypeUser {
+ where.Add(`(membership."actorUserId" = @actorID OR membership."actorGroupId" IN (` + groupSubquery + `))`)
+ } else {
+ where.Add(`(membership."actorIdentityId" = @actorID OR membership."actorGroupId" IN (` + groupSubquery + `))`)
+ }
+
+ // Scope condition
+ if params.Scope == AccessScopeOrganization {
+ where.Add("membership.scope = 'organization'")
+ } else {
+ where.Add("membership.scope = 'project'").Add(`membership."scopeProjectId" = @projectID`)
+ }
+
+ // Build additional privilege join condition
+ apJoinCond := qb.NewWhere()
+ if params.ActorType == ActorTypeIdentity {
+ apJoinCond.Add(`membership."actorIdentityId" = addlPriv."actorIdentityId"`)
+ } else {
+ apJoinCond.Add(`membership."actorUserId" = addlPriv."actorUserId"`)
+ }
+ if params.Scope == AccessScopeOrganization {
+ apJoinCond.Add(`membership."scopeOrgId" = addlPriv."orgId"`)
+ } else {
+ apJoinCond.Add(`membership."scopeProjectId" = addlPriv."projectId"`)
+ }
+
+ // Build metadata join condition
+ metaJoinCond := qb.NewWhere()
+ if params.ActorType == ActorTypeUser {
+ metaJoinCond.Add(`identityMeta."userId" = @actorID`).Add(`membership."scopeOrgId" = identityMeta."orgId"`)
+ } else {
+ metaJoinCond.Add(`identityMeta."identityId" = @actorID`)
+ }
+
+ query := `
+ SELECT
+ membership.id AS membership_id,
+ membership."scopeOrgId",
+ org."authEnforced",
+ org."googleSsoAuthEnforced",
+ org."bypassOrgAuthEnabled",
+ org."shouldUseNewPrivilegeSystem",
+ org."rootOrgId",
+ memberRole.id AS role_id,
+ memberRole.role,
+ memberRole."isTemporary" AS role_is_temporary,
+ memberRole."temporaryAccessEndTime" AS role_temporary_access_end_time,
+ customRole.slug AS custom_role_slug,
+ customRole.permissions AS custom_role_permissions,
+ addlPriv.id AS ap_id,
+ addlPriv.permissions AS ap_permissions,
+ addlPriv."isTemporary" AS ap_is_temporary,
+ addlPriv."temporaryAccessEndTime" AS ap_temporary_access_end_time,
+ identityMeta.id AS meta_id,
+ identityMeta.key AS meta_key,
+ identityMeta.value AS meta_value
+ FROM memberships membership
+ INNER JOIN membership_roles memberRole ON membership.id = memberRole."membershipId"
+ INNER JOIN organizations org ON membership."scopeOrgId" = org.id
+ LEFT JOIN roles customRole ON memberRole."customRoleId" = customRole.id
+ LEFT JOIN additional_privileges addlPriv ON ` + apJoinCond.String() + `
+ LEFT JOIN identity_metadata identityMeta ON ` + metaJoinCond.String() + `
+ WHERE ` + where.String()
+
+ args := pgx.NamedArgs{
+ "orgID": params.OrgID,
+ "actorID": params.ActorID,
+ "projectID": params.ProjectID,
+ }
+
+ rows, err := s.db.Replica().Query(ctx, query, args)
+ if err != nil {
+ return nil, err
+ }
+
+ flatRows, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (permissionData, error) {
+ var (
+ membershipID uuid.UUID
+ scopeOrgID uuid.UUID
+ orgAuthEnforced sql.Null[bool]
+ orgGoogleSsoAuthEnforced bool
+ orgBypassOrgAuthEnabled bool
+ orgShouldUseNewPrivSys bool
+ orgRootOrgID sql.Null[uuid.UUID]
+ roleID sql.Null[uuid.UUID]
+ role sql.Null[string]
+ roleIsTemporary sql.Null[bool]
+ roleTemporaryEndTime sql.Null[time.Time]
+ customRoleSlug sql.Null[string]
+ customRolePermissions sql.Null[string]
+ apID sql.Null[uuid.UUID]
+ apPermissions sql.Null[string]
+ apIsTemporary sql.Null[bool]
+ apTemporaryEndTime sql.Null[time.Time]
+ metaID sql.Null[uuid.UUID]
+ metaKey sql.Null[string]
+ metaValue sql.Null[string]
+ )
+
+ if err := row.Scan(
+ &membershipID, &scopeOrgID,
+ &orgAuthEnforced, &orgGoogleSsoAuthEnforced, &orgBypassOrgAuthEnabled,
+ &orgShouldUseNewPrivSys, &orgRootOrgID,
+ &roleID, &role, &roleIsTemporary, &roleTemporaryEndTime,
+ &customRoleSlug, &customRolePermissions,
+ &apID, &apPermissions, &apIsTemporary, &apTemporaryEndTime,
+ &metaID, &metaKey, &metaValue,
+ ); err != nil {
+ return permissionData{}, err
+ }
+
+ data := permissionData{
+ ID: membershipID,
+ ScopeOrgID: scopeOrgID,
+ OrgAuthEnforced: orgAuthEnforced,
+ OrgGoogleSsoAuthEnforced: orgGoogleSsoAuthEnforced,
+ BypassOrgAuthEnabled: orgBypassOrgAuthEnabled,
+ ShouldUseNewPrivilegeSystem: orgShouldUseNewPrivSys,
+ RootOrgID: orgRootOrgID,
+ }
+
+ if roleID.Valid {
+ data.Roles = []RoleInfo{{
+ ID: roleID.V,
+ Role: role.V,
+ IsTemporary: roleIsTemporary,
+ TemporaryAccessEndTime: roleTemporaryEndTime,
+ CustomRoleSlug: customRoleSlug,
+ Permissions: customRolePermissions,
+ }}
+ }
+
+ if apID.Valid {
+ data.AdditionalPrivileges = []AdditionalPrivilegeInfo{{
+ ID: apID.V,
+ Permissions: apPermissions,
+ IsTemporary: apIsTemporary,
+ TemporaryAccessEndTime: apTemporaryEndTime,
+ }}
+ }
+
+ if metaID.Valid {
+ data.Metadata = []MetadataInfo{{
+ ID: metaID.V,
+ Key: metaKey.V,
+ Value: metaValue.V,
+ }}
+ }
+
+ return data, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ if len(flatRows) == 0 {
+ return nil, nil
+ }
+
+ return sqln.GroupRows(flatRows, permissionGrouper), nil
+}
+
+// findProjectByID returns basic project details needed for permission checks.
+func (s *Service) findProjectByID(ctx context.Context, projectID string) (*projectDetail, error) {
+ query := `
+ SELECT id, name, slug, "orgId", type, "enforceEncryptedSecretManagerSecretMetadata"
+ FROM projects
+ WHERE id = @projectID
+ `
+ args := pgx.NamedArgs{"projectID": projectID}
+
+ row := s.db.Replica().QueryRow(ctx, query, args)
+
+ var id, name, slug string
+ var orgID uuid.UUID
+ var projectType sql.Null[string]
+ var enforceEncrypted sql.Null[bool]
+
+ err := row.Scan(&id, &name, &slug, &orgID, &projectType, &enforceEncrypted)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ return &projectDetail{
+ ID: id,
+ Name: name,
+ Slug: slug,
+ OrgID: orgID,
+ Type: projectType.V,
+ EnforceEncryptedSecretManagerSecretMetadata: enforceEncrypted.Valid && enforceEncrypted.V,
+ }, nil
+}
+
+// findUserUsername returns the username for a user by ID.
+func (s *Service) findUserUsername(ctx context.Context, userID uuid.UUID) (string, error) {
+ query := `SELECT username FROM users WHERE id = @userID`
+ args := pgx.NamedArgs{"userID": userID}
+
+ var username string
+ err := s.db.Replica().QueryRow(ctx, query, args).Scan(&username)
+ if err != nil {
+ return "", err
+ }
+ return username, nil
+}
+
+// findIdentityName returns the name for an identity by ID.
+func (s *Service) findIdentityName(ctx context.Context, identityID uuid.UUID) (string, error) {
+ query := `SELECT name FROM identities WHERE id = @identityID`
+ args := pgx.NamedArgs{"identityID": identityID}
+
+ var name string
+ err := s.db.Replica().QueryRow(ctx, query, args).Scan(&name)
+ if err != nil {
+ return "", err
+ }
+ return name, nil
+}
+
+// findServiceTokenByID returns service token details needed for permission checks.
+func (s *Service) findServiceTokenByID(ctx context.Context, tokenID string) (*serviceTokenDetail, error) {
+ query := `
+ SELECT id, "projectId", "expiresAt", scopes, permissions
+ FROM service_tokens
+ WHERE id = @tokenID
+ `
+ args := pgx.NamedArgs{"tokenID": tokenID}
+
+ row := s.db.Replica().QueryRow(ctx, query, args)
+
+ var id, projectID, scopes string
+ var expiresAt sql.Null[time.Time]
+ var permissions []string
+
+ err := row.Scan(&id, &projectID, &expiresAt, &scopes, &permissions)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ detail := &serviceTokenDetail{
+ ID: id,
+ ProjectID: projectID,
+ Scopes: scopes,
+ Permissions: permissions,
+ }
+ if expiresAt.Valid {
+ detail.ExpiresAt = &expiresAt.V
+ }
+ return detail, nil
+}
diff --git a/backend-go/internal/services/permission/permission_integration_test.go b/backend-go/internal/services/permission/permission_integration_test.go
index 7084bbbd41..70659b0a62 100644
--- a/backend-go/internal/services/permission/permission_integration_test.go
+++ b/backend-go/internal/services/permission/permission_integration_test.go
@@ -39,8 +39,7 @@ func TestMain(m *testing.M) {
}
func newPermissionService() *permission.Service {
- dal := permission.NewDAL(stack.DB())
- return permission.NewService(testutil.NopLogger(), permission.Deps{DAL: dal})
+ return permission.NewService(testutil.NopLogger(), permission.Deps{DB: stack.DB()})
}
func getProjectPermission(t *testing.T, actorType permission.ActorType, actorID string) *permission.GetProjectPermissionResult {
diff --git a/backend-go/internal/services/permission/permission_test.go b/backend-go/internal/services/permission/permission_test.go
index c93b6c9e78..0621b90635 100644
--- a/backend-go/internal/services/permission/permission_test.go
+++ b/backend-go/internal/services/permission/permission_test.go
@@ -561,12 +561,12 @@ func TestFlattenActiveRolesFromMemberships_ActiveRolesIncluded(t *testing.T) {
t.Parallel()
perms := `[[["read"],["secrets"]]]`
- data := []PermissionData{
+ data := []permissionData{
{
ID: uuid.New(),
Roles: []RoleInfo{
{Role: project.RoleAdmin, IsTemporary: sql.Null[bool]{V: false, Valid: true}},
- {Role: project.RoleCustom, IsTemporary: sql.Null[bool]{V: false, Valid: true}, Permissions: sql.NullString{String: perms, Valid: true}},
+ {Role: project.RoleCustom, IsTemporary: sql.Null[bool]{V: false, Valid: true}, Permissions: sql.Null[string]{V: perms, Valid: true}},
},
},
}
@@ -581,11 +581,11 @@ func TestFlattenActiveRolesFromMemberships_ExpiredTemporaryRoleExcluded(t *testi
t.Parallel()
pastTime := time.Now().Add(-1 * time.Hour)
- data := []PermissionData{
+ data := []permissionData{
{
ID: uuid.New(),
Roles: []RoleInfo{
- {Role: project.RoleAdmin, IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.NullTime{Time: pastTime, Valid: true}},
+ {Role: project.RoleAdmin, IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.Null[time.Time]{V: pastTime, Valid: true}},
},
},
}
@@ -598,11 +598,11 @@ func TestFlattenActiveRolesFromMemberships_ActiveTemporaryRoleIncluded(t *testin
t.Parallel()
futureTime := time.Now().Add(1 * time.Hour)
- data := []PermissionData{
+ data := []permissionData{
{
ID: uuid.New(),
Roles: []RoleInfo{
- {Role: project.RoleMember, IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.NullTime{Time: futureTime, Valid: true}},
+ {Role: project.RoleMember, IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.Null[time.Time]{V: futureTime, Valid: true}},
},
},
}
@@ -615,11 +615,11 @@ func TestFlattenActiveRolesFromMemberships_ActiveTemporaryRoleIncluded(t *testin
func TestFlattenActiveRolesFromMemberships_TemporaryWithNilEndTimeExcluded(t *testing.T) {
t.Parallel()
- data := []PermissionData{
+ data := []permissionData{
{
ID: uuid.New(),
Roles: []RoleInfo{
- {Role: project.RoleAdmin, IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.NullTime{Valid: false}},
+ {Role: project.RoleAdmin, IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.Null[time.Time]{Valid: false}},
},
},
}
@@ -633,11 +633,11 @@ func TestFlattenActiveRolesFromMemberships_ExpiredAdditionalPrivilegeExcluded(t
pastTime := time.Now().Add(-1 * time.Hour)
perms := `[[["read"],["secrets"]]]`
- data := []PermissionData{
+ data := []permissionData{
{
ID: uuid.New(),
AdditionalPrivileges: []AdditionalPrivilegeInfo{
- {IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.NullTime{Time: pastTime, Valid: true}, Permissions: sql.NullString{String: perms, Valid: true}},
+ {IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.Null[time.Time]{V: pastTime, Valid: true}, Permissions: sql.Null[string]{V: perms, Valid: true}},
},
},
}
@@ -651,11 +651,11 @@ func TestFlattenActiveRolesFromMemberships_ActiveAdditionalPrivilegeIncluded(t *
futureTime := time.Now().Add(1 * time.Hour)
perms := `[[["read"],["secrets"]]]`
- data := []PermissionData{
+ data := []permissionData{
{
ID: uuid.New(),
AdditionalPrivileges: []AdditionalPrivilegeInfo{
- {IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.NullTime{Time: futureTime, Valid: true}, Permissions: sql.NullString{String: perms, Valid: true}},
+ {IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.Null[time.Time]{V: futureTime, Valid: true}, Permissions: sql.Null[string]{V: perms, Valid: true}},
},
},
}
@@ -669,11 +669,11 @@ func TestFlattenActiveRolesFromMemberships_NonTemporaryAdditionalPrivilegeInclud
t.Parallel()
perms := `[[["read"],["secrets"]]]`
- data := []PermissionData{
+ data := []permissionData{
{
ID: uuid.New(),
AdditionalPrivileges: []AdditionalPrivilegeInfo{
- {IsTemporary: sql.Null[bool]{V: false, Valid: true}, Permissions: sql.NullString{String: perms, Valid: true}},
+ {IsTemporary: sql.Null[bool]{V: false, Valid: true}, Permissions: sql.Null[string]{V: perms, Valid: true}},
},
},
}
@@ -740,7 +740,7 @@ func TestHasRole_EmptyMemberships(t *testing.T) {
func TestCheckProjectEnforcement(t *testing.T) {
t.Parallel()
- fn := checkProjectEnforcement(&ProjectDetail{
+ fn := checkProjectEnforcement(&projectDetail{
EnforceEncryptedSecretManagerSecretMetadata: true,
})
@@ -748,7 +748,7 @@ func TestCheckProjectEnforcement(t *testing.T) {
assert.False(t, fn("unknownEnforcement"))
assert.False(t, fn(""))
- fnDisabled := checkProjectEnforcement(&ProjectDetail{
+ fnDisabled := checkProjectEnforcement(&projectDetail{
EnforceEncryptedSecretManagerSecretMetadata: false,
})
assert.False(t, fnDisabled("enforceEncryptedSecretManagerSecretMetadata"))
diff --git a/backend-go/internal/services/project/service.go b/backend-go/internal/services/project/service.go
index 90193d33ac..4468d52cd6 100644
--- a/backend-go/internal/services/project/service.go
+++ b/backend-go/internal/services/project/service.go
@@ -55,11 +55,11 @@ func (s *Service) GetByID(ctx context.Context, projectID string) (*Project, erro
// --- Row types ---
type projectRow struct {
- ID string `db:"id"`
- Name string `db:"name"`
- Slug string `db:"slug"`
- OrgID uuid.UUID `db:"org_id"`
- Type sql.Null[string] `db:"type"`
+ ID string `db:"id"`
+ Name string `db:"name"`
+ Slug string `db:"slug"`
+ OrgID uuid.UUID `db:"org_id"`
+ Type sql.Null[string] `db:"type"`
}
// --- Query methods ---
@@ -67,9 +67,9 @@ type projectRow struct {
// findBySlug returns a project by its slug within an organization.
func (s *Service) findBySlug(ctx context.Context, orgID uuid.UUID, slug string) (*Project, error) {
query := `
- SELECT id, name, slug, org_id, type
+ SELECT id, name, slug, "orgId", type
FROM projects
- WHERE slug = @slug AND org_id = @orgID
+ WHERE slug = @slug AND "orgId" = @orgID
`
args := pgx.NamedArgs{"slug": slug, "orgID": orgID}
@@ -100,7 +100,7 @@ func (s *Service) findBySlug(ctx context.Context, orgID uuid.UUID, slug string)
// findByID returns a project by its ID.
func (s *Service) findByID(ctx context.Context, projectID string) (*Project, error) {
query := `
- SELECT id, name, slug, org_id, type
+ SELECT id, name, slug, "orgId", type
FROM projects
WHERE id = @projectID
`
diff --git a/backend-go/internal/services/secretmanager/environment/service.go b/backend-go/internal/services/secretmanager/environment/service.go
index 6208b5b32a..1669e93b64 100644
--- a/backend-go/internal/services/secretmanager/environment/service.go
+++ b/backend-go/internal/services/secretmanager/environment/service.go
@@ -33,9 +33,9 @@ func NewService(deps Deps) *Service {
func (s *Service) GetBySlug(ctx context.Context, projectID, slug string) (*Environment, error) {
query := `
- SELECT id, slug, name, project_id, position
+ SELECT id, slug, name, "projectId", position
FROM project_environments
- WHERE project_id = @projectID AND slug = @slug
+ WHERE "projectId" = @projectID AND slug = @slug
LIMIT 1
`
args := pgx.NamedArgs{"projectID": projectID, "slug": slug}
@@ -56,7 +56,7 @@ func (s *Service) GetBySlug(ctx context.Context, projectID, slug string) (*Envir
func (s *Service) GetByID(ctx context.Context, envID uuid.UUID) (*Environment, error) {
query := `
- SELECT id, slug, name, project_id, position
+ SELECT id, slug, name, "projectId", position
FROM project_environments
WHERE id = @envID
LIMIT 1
@@ -79,9 +79,9 @@ func (s *Service) GetByID(ctx context.Context, envID uuid.UUID) (*Environment, e
func (s *Service) GetAllByProjectID(ctx context.Context, projectID string) ([]Environment, error) {
query := `
- SELECT id, slug, name, project_id, position
+ SELECT id, slug, name, "projectId", position
FROM project_environments
- WHERE project_id = @projectID
+ WHERE "projectId" = @projectID
ORDER BY position ASC
`
args := pgx.NamedArgs{"projectID": projectID}
diff --git a/backend-go/internal/services/secretmanager/libs.go b/backend-go/internal/services/secretmanager/libs.go
index a56c2465a5..e615d5d253 100644
--- a/backend-go/internal/services/secretmanager/libs.go
+++ b/backend-go/internal/services/secretmanager/libs.go
@@ -15,19 +15,15 @@ type ServicesDeps struct {
type Services struct {
SecretFolder *secretfolder.Service
SecretImport *secretimport.Service
- SecretDAL *secret.DAL
+ Secret *secret.Service
Environment *environment.Service
}
func NewServices(deps ServicesDeps) *Services {
- secretFolderDAL := secretfolder.NewDAL(deps.DB)
- secretImportDAL := secretimport.NewDAL(deps.DB)
- secretDAL := secret.NewDAL(deps.DB)
-
return &Services{
- SecretFolder: secretfolder.NewService(secretfolder.Deps{DAL: secretFolderDAL}),
- SecretImport: secretimport.NewService(secretimport.Deps{DAL: secretImportDAL}),
- SecretDAL: secretDAL,
+ SecretFolder: secretfolder.NewService(secretfolder.Deps{DB: deps.DB}),
+ SecretImport: secretimport.NewService(secretimport.Deps{DB: deps.DB}),
+ Secret: secret.NewService(secret.Deps{DB: deps.DB}),
Environment: environment.NewService(environment.Deps{DB: deps.DB}),
}
}
diff --git a/backend-go/internal/services/secretmanager/secret/dal.go b/backend-go/internal/services/secretmanager/secret/dal.go
deleted file mode 100644
index 68454964b5..0000000000
--- a/backend-go/internal/services/secretmanager/secret/dal.go
+++ /dev/null
@@ -1,380 +0,0 @@
-package secret
-
-import (
- "context"
- "database/sql"
- "errors"
- "fmt"
- "time"
-
- "github.com/go-jet/jet/v2/postgres"
- "github.com/go-jet/jet/v2/qrm"
- "github.com/google/uuid"
-
- "github.com/infisical/api/internal/database/pg"
- "github.com/infisical/api/internal/database/pg/gen/table"
-)
-
-type OrderByDirection string
-
-const (
- OrderByDirectionASC OrderByDirection = "asc"
- OrderByDirectionDESC OrderByDirection = "desc"
-)
-
-type SecretsOrderBy string
-
-const (
- SecretsOrderByName SecretsOrderBy = "name"
-)
-
-type SecretTag struct {
- ID uuid.UUID `sql:"primary_key" alias:"secret_tags.id"`
- Slug string `alias:"secret_tags.slug"`
- Color string `alias:"secret_tags.color"`
-}
-
-type SecretMetadata struct {
- ID uuid.UUID `sql:"primary_key" alias:"resource_metadata.id"`
- Key string `alias:"resource_metadata.key"`
- Value string `alias:"resource_metadata.value"`
- EncryptedValue []byte `alias:"resource_metadata.encrypted_value"`
-}
-
-type ReminderRecipientUser struct {
- ID uuid.UUID `sql:"primary_key" alias:"users.id"`
- Username string `alias:"users.username"`
- Email string `alias:"users.email"`
-}
-
-type SecretReminderRecipient struct {
- ID uuid.UUID `sql:"primary_key" alias:"reminders_recipients.id"`
- User ReminderRecipientUser `alias:"users"`
-}
-
-type SecretRotationMapping struct {
- RotationID uuid.UUID `sql:"primary_key" alias:"secret_rotation_v2_secret_mappings.rotation_id"`
-}
-
-type Secret struct {
- ID uuid.UUID `sql:"primary_key" alias:"secrets_v2.id"`
- Version int32 `alias:"secrets_v2.version"`
- Type string `alias:"secrets_v2.type"`
- Key string `alias:"secrets_v2.key"`
- EncryptedValue sql.Null[[]byte] `alias:"secrets_v2.encrypted_value"`
- EncryptedComment sql.Null[[]byte] `alias:"secrets_v2.encrypted_comment"`
- SkipMultilineEncoding sql.Null[bool] `alias:"secrets_v2.skip_multiline_encoding"`
- Metadata sql.Null[string] `alias:"secrets_v2.metadata"`
- UserID sql.Null[uuid.UUID] `alias:"secrets_v2.user_id"`
- FolderID uuid.UUID `alias:"secrets_v2.folder_id"`
- CreatedAt time.Time `alias:"secrets_v2.created_at"`
- UpdatedAt time.Time `alias:"secrets_v2.updated_at"`
-
- Tags []SecretTag `alias:"secret_tags"`
- SecretMetadata []SecretMetadata `alias:"resource_metadata"`
- SecretReminderRecipients []SecretReminderRecipient `alias:"reminders_recipients"`
- RotationMapping []SecretRotationMapping `alias:"secret_rotation_v2_secret_mappings"`
-}
-
-func (s *Secret) IsRotatedSecret() bool {
- return len(s.RotationMapping) > 0
-}
-
-func (s *Secret) GetRotationID() uuid.UUID {
- if len(s.RotationMapping) > 0 {
- return s.RotationMapping[0].RotationID
- }
- return uuid.Nil
-}
-
-type MetadataFilter struct {
- Key string
- Value string
-}
-
-type FindByFolderIdsFilter struct {
- Limit *int
- Offset *int
- OrderBy *SecretsOrderBy
- OrderDirection *OrderByDirection
- Search string
- TagSlugs []string
- MetadataFilter []MetadataFilter
- IncludeTagsInSearch bool
- IncludeMetadataInSearch bool
- Keys []string
- ExcludeRotatedSecrets bool
-}
-
-type DAL struct {
- db pg.DB
-}
-
-func NewDAL(db pg.DB) *DAL {
- return &DAL{db: db}
-}
-
-func (d *DAL) FindByFolderIds(
- ctx context.Context,
- folderIDs []uuid.UUID,
- userID *uuid.UUID,
- filters *FindByFolderIdsFilter,
-) ([]Secret, error) {
- if len(folderIDs) == 0 {
- return []Secret{}, nil
- }
-
- secretsV2 := table.SecretsV2
- secretV2TagJunction := table.SecretV2TagJunction
- secretTags := table.SecretTags
- resourceMetadata := table.ResourceMetadata
- secretRotationV2SecretMappings := table.SecretRotationV2SecretMappings
- reminders := table.Reminders
- remindersRecipients := table.RemindersRecipients
- users := table.Users
-
- folderExpressions := make([]postgres.Expression, len(folderIDs))
- for i, id := range folderIDs {
- folderExpressions[i] = postgres.UUID(id)
- }
-
- orderDirection := OrderByDirectionASC
- if filters != nil && filters.OrderDirection != nil {
- orderDirection = *filters.OrderDirection
- }
-
- var orderByColumn postgres.OrderByClause
- if filters != nil && filters.OrderBy != nil && *filters.OrderBy == SecretsOrderByName {
- if orderDirection == OrderByDirectionDESC {
- orderByColumn = secretsV2.Key.DESC()
- } else {
- orderByColumn = secretsV2.Key.ASC()
- }
- } else {
- if orderDirection == OrderByDirectionDESC {
- orderByColumn = secretsV2.ID.DESC()
- } else {
- orderByColumn = secretsV2.ID.ASC()
- }
- }
-
- selectColumns := []postgres.Projection{
- secretsV2.ID,
- secretsV2.Version,
- secretsV2.Type,
- secretsV2.Key,
- secretsV2.EncryptedValue,
- secretsV2.EncryptedComment,
- secretsV2.SkipMultilineEncoding,
- secretsV2.Metadata,
- secretsV2.UserId,
- secretsV2.FolderId,
- secretsV2.CreatedAt,
- secretsV2.UpdatedAt,
- secretTags.ID,
- secretTags.Slug,
- secretTags.Color,
- resourceMetadata.ID,
- resourceMetadata.Key,
- resourceMetadata.Value,
- resourceMetadata.EncryptedValue,
- secretRotationV2SecretMappings.RotationId,
- remindersRecipients.ID,
- users.ID,
- users.Username,
- users.Email,
- }
-
- fromClause := secretsV2.
- LEFT_JOIN(secretV2TagJunction, secretsV2.ID.EQ(secretV2TagJunction.SecretsV2id)).
- LEFT_JOIN(secretTags, secretV2TagJunction.SecretTagsid.EQ(secretTags.ID)).
- LEFT_JOIN(resourceMetadata, secretsV2.ID.EQ(resourceMetadata.SecretId)).
- LEFT_JOIN(secretRotationV2SecretMappings, secretsV2.ID.EQ(secretRotationV2SecretMappings.SecretId)).
- LEFT_JOIN(reminders, secretsV2.ID.EQ(reminders.SecretId)).
- LEFT_JOIN(remindersRecipients, reminders.ID.EQ(remindersRecipients.ReminderId)).
- LEFT_JOIN(users, remindersRecipients.UserId.EQ(users.ID))
-
- var conditions []postgres.BoolExpression
-
- conditions = append(conditions, secretsV2.FolderId.IN(folderExpressions...))
-
- if filters != nil && filters.Search != "" {
- searchPattern := "%" + filters.Search + "%"
- searchConditions := []postgres.BoolExpression{
- secretsV2.Key.LIKE(postgres.String(searchPattern)),
- }
- if filters.IncludeTagsInSearch {
- searchConditions = append(searchConditions, secretTags.Slug.LIKE(postgres.String(searchPattern)))
- }
- if filters.IncludeMetadataInSearch {
- searchConditions = append(searchConditions,
- resourceMetadata.Key.LIKE(postgres.String(searchPattern)),
- resourceMetadata.Value.LIKE(postgres.String(searchPattern)),
- )
- }
- conditions = append(conditions, postgres.OR(searchConditions...))
- }
-
- if filters != nil && len(filters.Keys) > 0 {
- keyExpressions := make([]postgres.Expression, len(filters.Keys))
- for i, key := range filters.Keys {
- keyExpressions[i] = postgres.String(key)
- }
- conditions = append(conditions, secretsV2.Key.IN(keyExpressions...))
- }
-
- if userID == nil {
- conditions = append(conditions, secretsV2.UserId.IS_NULL())
- } else {
- conditions = append(conditions, postgres.OR(
- secretsV2.UserId.IS_NULL(),
- secretsV2.UserId.EQ(postgres.UUID(*userID)),
- ))
- }
-
- if filters != nil && len(filters.MetadataFilter) > 0 {
- for _, meta := range filters.MetadataFilter {
- subQuery := postgres.SELECT(resourceMetadata.SecretId).
- FROM(resourceMetadata).
- WHERE(postgres.AND(
- resourceMetadata.SecretId.EQ(secretsV2.ID),
- resourceMetadata.Key.EQ(postgres.String(meta.Key)),
- resourceMetadata.Value.EQ(postgres.String(meta.Value)),
- resourceMetadata.Value.IS_NOT_NULL(),
- ))
- conditions = append(conditions, postgres.EXISTS(subQuery))
- }
- }
-
- if filters != nil && len(filters.TagSlugs) > 0 {
- var validSlugs []string
- for _, slug := range filters.TagSlugs {
- if slug != "" {
- validSlugs = append(validSlugs, slug)
- }
- }
- if len(validSlugs) > 0 {
- slugExpressions := make([]postgres.Expression, len(validSlugs))
- for i, slug := range validSlugs {
- slugExpressions[i] = postgres.String(slug)
- }
- conditions = append(conditions, secretTags.Slug.IN(slugExpressions...))
- }
- }
-
- if filters != nil && filters.ExcludeRotatedSecrets {
- conditions = append(conditions, secretRotationV2SecretMappings.SecretId.IS_NULL())
- }
-
- stmt := postgres.SELECT(selectColumns[0], selectColumns[1:]...).
- FROM(fromClause).
- WHERE(postgres.AND(conditions...)).
- ORDER_BY(orderByColumn)
-
- var secrets []Secret
-
- if filters != nil && filters.Limit != nil {
- offset := 0
- if filters.Offset != nil {
- offset = *filters.Offset
- }
- stmt = stmt.LIMIT(int64(*filters.Limit)).OFFSET(int64(offset))
- }
-
- err := stmt.QueryContext(ctx, d.db.Replica(), &secrets)
- if err != nil {
- if errors.Is(err, qrm.ErrNoRows) {
- return []Secret{}, nil
- }
- return nil, fmt.Errorf("FindByFolderIds query: %w", err)
- }
-
- return secrets, nil
-}
-
-// FindByKey finds a single secret by folder ID, key, and type.
-// For personal secrets, userID must be provided.
-// Returns nil if not found.
-func (d *DAL) FindByKey(
- ctx context.Context,
- folderID uuid.UUID,
- key string,
- secretType string,
- userID *uuid.UUID,
-) (*Secret, error) {
- secretsV2 := table.SecretsV2
- secretV2TagJunction := table.SecretV2TagJunction
- secretTags := table.SecretTags
- resourceMetadata := table.ResourceMetadata
- secretRotationV2SecretMappings := table.SecretRotationV2SecretMappings
- reminders := table.Reminders
- remindersRecipients := table.RemindersRecipients
- users := table.Users
-
- selectColumns := []postgres.Projection{
- secretsV2.ID,
- secretsV2.Version,
- secretsV2.Type,
- secretsV2.Key,
- secretsV2.EncryptedValue,
- secretsV2.EncryptedComment,
- secretsV2.SkipMultilineEncoding,
- secretsV2.Metadata,
- secretsV2.UserId,
- secretsV2.FolderId,
- secretsV2.CreatedAt,
- secretsV2.UpdatedAt,
- secretTags.ID,
- secretTags.Slug,
- secretTags.Color,
- resourceMetadata.ID,
- resourceMetadata.Key,
- resourceMetadata.Value,
- resourceMetadata.EncryptedValue,
- secretRotationV2SecretMappings.RotationId,
- remindersRecipients.ID,
- users.ID,
- users.Username,
- users.Email,
- }
-
- fromClause := secretsV2.
- LEFT_JOIN(secretV2TagJunction, secretsV2.ID.EQ(secretV2TagJunction.SecretsV2id)).
- LEFT_JOIN(secretTags, secretV2TagJunction.SecretTagsid.EQ(secretTags.ID)).
- LEFT_JOIN(resourceMetadata, secretsV2.ID.EQ(resourceMetadata.SecretId)).
- LEFT_JOIN(secretRotationV2SecretMappings, secretsV2.ID.EQ(secretRotationV2SecretMappings.SecretId)).
- LEFT_JOIN(reminders, secretsV2.ID.EQ(reminders.SecretId)).
- LEFT_JOIN(remindersRecipients, reminders.ID.EQ(remindersRecipients.ReminderId)).
- LEFT_JOIN(users, remindersRecipients.UserId.EQ(users.ID))
-
- conditions := []postgres.BoolExpression{
- secretsV2.FolderId.EQ(postgres.UUID(folderID)),
- secretsV2.Key.EQ(postgres.String(key)),
- secretsV2.Type.EQ(postgres.String(secretType)),
- }
-
- if secretType == "personal" && userID != nil {
- conditions = append(conditions, secretsV2.UserId.EQ(postgres.UUID(*userID)))
- } else {
- conditions = append(conditions, secretsV2.UserId.IS_NULL())
- }
-
- stmt := postgres.SELECT(selectColumns[0], selectColumns[1:]...).
- FROM(fromClause).
- WHERE(postgres.AND(conditions...))
-
- var secrets []Secret
- err := stmt.QueryContext(ctx, d.db.Replica(), &secrets)
- if err != nil {
- if errors.Is(err, qrm.ErrNoRows) {
- return nil, nil
- }
- return nil, fmt.Errorf("FindByKey query: %w", err)
- }
-
- if len(secrets) == 0 {
- return nil, nil
- }
-
- return &secrets[0], nil
-}
diff --git a/backend-go/internal/services/secretmanager/secret/service.go b/backend-go/internal/services/secretmanager/secret/service.go
new file mode 100644
index 0000000000..c58e0e1015
--- /dev/null
+++ b/backend-go/internal/services/secretmanager/secret/service.go
@@ -0,0 +1,416 @@
+package secret
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+
+ "github.com/infisical/api/internal/database/pg"
+ "github.com/infisical/api/internal/database/pg/qb"
+ "github.com/infisical/api/internal/database/pg/sqln"
+ "github.com/infisical/api/internal/libs/fn"
+)
+
+type OrderByDirection string
+
+const (
+ OrderByDirectionASC OrderByDirection = "asc"
+ OrderByDirectionDESC OrderByDirection = "desc"
+)
+
+type SecretsOrderBy string
+
+const (
+ SecretsOrderByName SecretsOrderBy = "name"
+)
+
+type SecretTag struct {
+ ID uuid.UUID
+ Slug string
+ Color string
+}
+
+type SecretMetadata struct {
+ ID uuid.UUID
+ Key string
+ Value string
+ EncryptedValue []byte
+}
+
+type ReminderRecipientUser struct {
+ ID uuid.UUID
+ Username string
+ Email string
+}
+
+type SecretReminderRecipient struct {
+ ID uuid.UUID
+ User ReminderRecipientUser
+}
+
+type SecretRotationMapping struct {
+ RotationID uuid.UUID
+}
+
+type Secret struct {
+ ID uuid.UUID
+ Version int32
+ Type string
+ Key string
+ EncryptedValue sql.Null[[]byte]
+ EncryptedComment sql.Null[[]byte]
+ SkipMultilineEncoding sql.Null[bool]
+ Metadata sql.Null[string]
+ UserID sql.Null[uuid.UUID]
+ FolderID uuid.UUID
+ CreatedAt time.Time
+ UpdatedAt time.Time
+
+ Tags []SecretTag
+ SecretMetadata []SecretMetadata
+ SecretReminderRecipients []SecretReminderRecipient
+ RotationMapping []SecretRotationMapping
+}
+
+func (s *Secret) IsRotatedSecret() bool {
+ return len(s.RotationMapping) > 0
+}
+
+func (s *Secret) GetRotationID() uuid.UUID {
+ if len(s.RotationMapping) > 0 {
+ return s.RotationMapping[0].RotationID
+ }
+ return uuid.Nil
+}
+
+type MetadataFilter struct {
+ Key string
+ Value string
+}
+
+type FindByFolderIdsFilter struct {
+ Limit *int
+ Offset *int
+ OrderBy *SecretsOrderBy
+ OrderDirection *OrderByDirection
+ Search string
+ TagSlugs []string
+ MetadataFilter []MetadataFilter
+ IncludeTagsInSearch bool
+ IncludeMetadataInSearch bool
+ Keys []string
+ ExcludeRotatedSecrets bool
+}
+
+type Deps struct {
+ DB pg.DB
+}
+
+type Service struct {
+ db pg.DB
+}
+
+func NewService(deps Deps) *Service {
+ return &Service{db: deps.DB}
+}
+
+var secretGrouper = sqln.Grouper[Secret, uuid.UUID]{
+ Key: func(s *Secret) uuid.UUID { return s.ID },
+ Merge: func(existing, row *Secret) {
+ if len(row.Tags) > 0 {
+ existing.Tags = fn.AppendUnique(existing.Tags, row.Tags[0], func(t SecretTag) uuid.UUID { return t.ID })
+ }
+ if len(row.SecretMetadata) > 0 {
+ existing.SecretMetadata = fn.AppendUnique(existing.SecretMetadata, row.SecretMetadata[0], func(m SecretMetadata) uuid.UUID { return m.ID })
+ }
+ if len(row.SecretReminderRecipients) > 0 {
+ existing.SecretReminderRecipients = fn.AppendUnique(existing.SecretReminderRecipients, row.SecretReminderRecipients[0], func(r SecretReminderRecipient) uuid.UUID { return r.ID })
+ }
+ if len(row.RotationMapping) > 0 {
+ existing.RotationMapping = fn.AppendUnique(existing.RotationMapping, row.RotationMapping[0], func(r SecretRotationMapping) uuid.UUID { return r.RotationID })
+ }
+ },
+}
+
+func (s *Service) FindByFolderIds(
+ ctx context.Context,
+ folderIDs []uuid.UUID,
+ userID *uuid.UUID,
+ filters *FindByFolderIdsFilter,
+) ([]Secret, error) {
+ if len(folderIDs) == 0 {
+ return []Secret{}, nil
+ }
+
+ where := qb.NewWhere().Add(`secret."folderId" = ANY(@folderIDs)`)
+
+ if userID == nil {
+ where.Add(`secret."userId" IS NULL`)
+ } else {
+ where.Add(`(secret."userId" IS NULL OR secret."userId" = @userID)`)
+ }
+
+ if filters != nil {
+ if filters.Search != "" {
+ searchCond := "secret.key ILIKE @searchPattern"
+ if filters.IncludeTagsInSearch {
+ searchCond = "(" + searchCond + " OR tag.slug ILIKE @searchPattern)"
+ }
+ if filters.IncludeMetadataInSearch {
+ searchCond = "(" + searchCond + " OR meta.key ILIKE @searchPattern OR meta.value ILIKE @searchPattern)"
+ }
+ where.Add(searchCond)
+ }
+
+ if len(filters.Keys) > 0 {
+ where.Add("secret.key = ANY(@keys)")
+ }
+
+ if len(filters.TagSlugs) > 0 {
+ where.Add("tag.slug = ANY(@tagSlugs)")
+ }
+
+ if filters.ExcludeRotatedSecrets {
+ where.Add(`rotationMapping."secretId" IS NULL`)
+ }
+
+ for i := range filters.MetadataFilter {
+ where.Add(`EXISTS (SELECT 1 FROM resource_metadata metaSub WHERE metaSub."secretId" = secret.id AND metaSub.key = @metaKey` + string(rune('0'+i)) + " AND metaSub.value = @metaValue" + string(rune('0'+i)) + " AND metaSub.value IS NOT NULL)")
+ }
+ }
+
+ orderBy := "secret.id ASC"
+ if filters != nil && filters.OrderBy != nil && *filters.OrderBy == SecretsOrderByName {
+ if filters.OrderDirection != nil && *filters.OrderDirection == OrderByDirectionDESC {
+ orderBy = "secret.key DESC"
+ } else {
+ orderBy = "secret.key ASC"
+ }
+ } else if filters != nil && filters.OrderDirection != nil && *filters.OrderDirection == OrderByDirectionDESC {
+ orderBy = "secret.id DESC"
+ }
+
+ limitClause := ""
+ if filters != nil && filters.Limit != nil {
+ limitClause = " LIMIT @limit OFFSET @offset"
+ }
+
+ query := `
+ SELECT
+ secret.id, secret.version, secret.type, secret.key, secret."encryptedValue", secret."encryptedComment",
+ secret."skipMultilineEncoding", secret.metadata, secret."userId", secret."folderId", secret."createdAt", secret."updatedAt",
+ tag.id AS tag_id, tag.slug AS tag_slug, tag.color AS tag_color,
+ meta.id AS meta_id, meta.key AS meta_key, meta.value AS meta_value, meta."encryptedValue" AS meta_encrypted_value,
+ rotationMapping."rotationId",
+ recipient.id AS recipient_id, recipientUser.id AS recipient_user_id, recipientUser.username AS recipient_username, recipientUser.email AS recipient_email
+ FROM secrets_v2 secret
+ LEFT JOIN secret_v2_tag_junction tagJunction ON secret.id = tagJunction."secrets_v2Id"
+ LEFT JOIN secret_tags tag ON tagJunction."secret_tagsId" = tag.id
+ LEFT JOIN resource_metadata meta ON secret.id = meta."secretId"
+ LEFT JOIN secret_rotation_v2_secret_mappings rotationMapping ON secret.id = rotationMapping."secretId"
+ LEFT JOIN reminders reminder ON secret.id = reminder."secretId"
+ LEFT JOIN reminders_recipients recipient ON reminder.id = recipient."reminderId"
+ LEFT JOIN users recipientUser ON recipient."userId" = recipientUser.id
+ WHERE ` + where.String() + `
+ ORDER BY ` + orderBy + limitClause
+
+ args := pgx.NamedArgs{
+ "folderIDs": folderIDs,
+ "userID": userID,
+ }
+
+ if filters != nil {
+ if filters.Search != "" {
+ args["searchPattern"] = "%" + filters.Search + "%"
+ }
+ if len(filters.Keys) > 0 {
+ args["keys"] = filters.Keys
+ }
+ if len(filters.TagSlugs) > 0 {
+ args["tagSlugs"] = filters.TagSlugs
+ }
+ if filters.Limit != nil {
+ args["limit"] = *filters.Limit
+ offset := 0
+ if filters.Offset != nil {
+ offset = *filters.Offset
+ }
+ args["offset"] = offset
+ }
+ for i, meta := range filters.MetadataFilter {
+ args["metaKey"+string(rune('0'+i))] = meta.Key
+ args["metaValue"+string(rune('0'+i))] = meta.Value
+ }
+ }
+
+ rows, err := s.db.Replica().Query(ctx, query, args)
+ if err != nil {
+ return nil, err
+ }
+
+ flatSecrets, err := pgx.CollectRows(rows, scanSecretRow)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(flatSecrets) == 0 {
+ return []Secret{}, nil
+ }
+
+ return sqln.GroupRows(flatSecrets, secretGrouper), nil
+}
+
+func (s *Service) FindByKey(
+ ctx context.Context,
+ folderID uuid.UUID,
+ key string,
+ secretType string,
+ userID *uuid.UUID,
+) (*Secret, error) {
+ where := qb.NewWhere().
+ Add(`secret."folderId" = @folderID`).
+ Add("secret.key = @key").
+ Add("secret.type = @secretType")
+
+ if secretType == "personal" && userID != nil {
+ where.Add(`secret."userId" = @userID`)
+ } else {
+ where.Add(`secret."userId" IS NULL`)
+ }
+
+ query := `
+ SELECT
+ secret.id, secret.version, secret.type, secret.key, secret."encryptedValue", secret."encryptedComment",
+ secret."skipMultilineEncoding", secret.metadata, secret."userId", secret."folderId", secret."createdAt", secret."updatedAt",
+ tag.id AS tag_id, tag.slug AS tag_slug, tag.color AS tag_color,
+ meta.id AS meta_id, meta.key AS meta_key, meta.value AS meta_value, meta."encryptedValue" AS meta_encrypted_value,
+ rotationMapping."rotationId",
+ recipient.id AS recipient_id, recipientUser.id AS recipient_user_id, recipientUser.username AS recipient_username, recipientUser.email AS recipient_email
+ FROM secrets_v2 secret
+ LEFT JOIN secret_v2_tag_junction tagJunction ON secret.id = tagJunction."secrets_v2Id"
+ LEFT JOIN secret_tags tag ON tagJunction."secret_tagsId" = tag.id
+ LEFT JOIN resource_metadata meta ON secret.id = meta."secretId"
+ LEFT JOIN secret_rotation_v2_secret_mappings rotationMapping ON secret.id = rotationMapping."secretId"
+ LEFT JOIN reminders reminder ON secret.id = reminder."secretId"
+ LEFT JOIN reminders_recipients recipient ON reminder.id = recipient."reminderId"
+ LEFT JOIN users recipientUser ON recipient."userId" = recipientUser.id
+ WHERE ` + where.String()
+
+ args := pgx.NamedArgs{
+ "folderID": folderID,
+ "key": key,
+ "secretType": secretType,
+ "userID": userID,
+ }
+
+ rows, err := s.db.Replica().Query(ctx, query, args)
+ if err != nil {
+ return nil, err
+ }
+
+ flatSecrets, err := pgx.CollectRows(rows, scanSecretRow)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(flatSecrets) == 0 {
+ return nil, nil
+ }
+
+ grouped := sqln.GroupRows(flatSecrets, secretGrouper)
+ return &grouped[0], nil
+}
+
+func scanSecretRow(row pgx.CollectableRow) (Secret, error) {
+ var (
+ id uuid.UUID
+ version int32
+ secretType string
+ key string
+ encryptedValue sql.Null[[]byte]
+ encryptedComment sql.Null[[]byte]
+ skipMultilineEncoding sql.Null[bool]
+ metadata sql.Null[string]
+ userID sql.Null[uuid.UUID]
+ folderID uuid.UUID
+ createdAt time.Time
+ updatedAt time.Time
+ tagID sql.Null[uuid.UUID]
+ tagSlug sql.Null[string]
+ tagColor sql.Null[string]
+ metaID sql.Null[uuid.UUID]
+ metaKey sql.Null[string]
+ metaValue sql.Null[string]
+ metaEncryptedValue []byte
+ rotationID sql.Null[uuid.UUID]
+ recipientID sql.Null[uuid.UUID]
+ recipientUserID sql.Null[uuid.UUID]
+ recipientUsername sql.Null[string]
+ recipientEmail sql.Null[string]
+ )
+
+ if err := row.Scan(
+ &id, &version, &secretType, &key, &encryptedValue, &encryptedComment,
+ &skipMultilineEncoding, &metadata, &userID, &folderID, &createdAt, &updatedAt,
+ &tagID, &tagSlug, &tagColor,
+ &metaID, &metaKey, &metaValue, &metaEncryptedValue,
+ &rotationID,
+ &recipientID, &recipientUserID, &recipientUsername, &recipientEmail,
+ ); err != nil {
+ return Secret{}, err
+ }
+
+ secret := Secret{
+ ID: id,
+ Version: version,
+ Type: secretType,
+ Key: key,
+ EncryptedValue: encryptedValue,
+ EncryptedComment: encryptedComment,
+ SkipMultilineEncoding: skipMultilineEncoding,
+ Metadata: metadata,
+ UserID: userID,
+ FolderID: folderID,
+ CreatedAt: createdAt,
+ UpdatedAt: updatedAt,
+ }
+
+ if tagID.Valid {
+ secret.Tags = []SecretTag{{
+ ID: tagID.V,
+ Slug: tagSlug.V,
+ Color: tagColor.V,
+ }}
+ }
+
+ if metaID.Valid {
+ secret.SecretMetadata = []SecretMetadata{{
+ ID: metaID.V,
+ Key: metaKey.V,
+ Value: metaValue.V,
+ EncryptedValue: metaEncryptedValue,
+ }}
+ }
+
+ if rotationID.Valid {
+ secret.RotationMapping = []SecretRotationMapping{{
+ RotationID: rotationID.V,
+ }}
+ }
+
+ if recipientID.Valid {
+ secret.SecretReminderRecipients = []SecretReminderRecipient{{
+ ID: recipientID.V,
+ User: ReminderRecipientUser{
+ ID: recipientUserID.V,
+ Username: recipientUsername.V,
+ Email: recipientEmail.V,
+ },
+ }}
+ }
+
+ return secret, nil
+}
diff --git a/backend-go/internal/services/secretmanager/secretfolder/dal.go b/backend-go/internal/services/secretmanager/secretfolder/dal.go
deleted file mode 100644
index d668c037a8..0000000000
--- a/backend-go/internal/services/secretmanager/secretfolder/dal.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package secretfolder
-
-import (
- "context"
- "database/sql"
- "errors"
-
- "github.com/go-jet/jet/v2/postgres"
- "github.com/go-jet/jet/v2/qrm"
- "github.com/google/uuid"
-
- "github.com/infisical/api/internal/database/pg"
- "github.com/infisical/api/internal/database/pg/gen/table"
-)
-
-type folderRow struct {
- ID uuid.UUID `alias:"secret_folders.id"`
- Name string `alias:"secret_folders.name"`
- ParentID sql.Null[uuid.UUID] `alias:"secret_folders.parent_id"`
- EnvID uuid.UUID `alias:"secret_folders.env_id"`
-}
-
-type DAL struct {
- db pg.DB
-}
-
-func NewDAL(db pg.DB) *DAL {
- return &DAL{db: db}
-}
-
-func (d *DAL) GetFoldersByProjectAndEnvIDs(ctx context.Context, projectID string, envIDs []uuid.UUID) ([]folderRow, error) {
- sf := table.SecretFolders
- pe := table.ProjectEnvironments
-
- envExpressions := make([]postgres.Expression, len(envIDs))
- for i, id := range envIDs {
- envExpressions[i] = postgres.UUID(id)
- }
-
- stmt := postgres.SELECT(
- sf.ID,
- sf.Name,
- sf.ParentId,
- sf.EnvId,
- ).FROM(
- sf.INNER_JOIN(pe, sf.EnvId.EQ(pe.ID)),
- ).WHERE(
- postgres.AND(
- pe.ProjectId.EQ(postgres.String(projectID)),
- sf.EnvId.IN(envExpressions...),
- ),
- )
-
- var rows []folderRow
- err := stmt.QueryContext(ctx, d.db.Primary(), &rows)
- if err != nil {
- if errors.Is(err, qrm.ErrNoRows) {
- return nil, nil
- }
- return nil, err
- }
-
- return rows, nil
-}
diff --git a/backend-go/internal/services/secretmanager/secretfolder/secret_folder.go b/backend-go/internal/services/secretmanager/secretfolder/secret_folder.go
deleted file mode 100644
index 7260fe3023..0000000000
--- a/backend-go/internal/services/secretmanager/secretfolder/secret_folder.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package secretfolder
-
-import (
- "context"
-
- "github.com/google/uuid"
-
- "github.com/infisical/api/internal/libs/errutil"
-)
-
-type dal interface {
- GetFoldersByProjectAndEnvIDs(ctx context.Context, projectID string, envIDs []uuid.UUID) ([]folderRow, error)
-}
-
-type Service struct {
- dal dal
-}
-
-// Deps holds the dependencies for the secret folder shared service.
-type Deps struct {
- DAL dal
-}
-
-func NewService(deps Deps) *Service {
- return &Service{dal: deps.DAL}
-}
-
-// LoadProjectFolders fetches folders for the given environments in a project and builds an in-memory lookup tree.
-func (s *Service) LoadProjectFolders(ctx context.Context, projectID string, envIDs []uuid.UUID) (*FolderLookup, error) {
- rows, err := s.dal.GetFoldersByProjectAndEnvIDs(ctx, projectID, envIDs)
- if err != nil {
- return nil, errutil.DatabaseErr("Failed to get folders for project").WithErrf("LoadProjectFolders(projectId=%s): %w", projectID, err)
- }
- return newFolderLookup(rows), nil
-}
diff --git a/backend-go/internal/services/secretmanager/secretfolder/service.go b/backend-go/internal/services/secretmanager/secretfolder/service.go
new file mode 100644
index 0000000000..70e95e07ab
--- /dev/null
+++ b/backend-go/internal/services/secretmanager/secretfolder/service.go
@@ -0,0 +1,69 @@
+package secretfolder
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+
+ "github.com/infisical/api/internal/database/pg"
+ "github.com/infisical/api/internal/libs/errutil"
+)
+
+type folderRow struct {
+ ID uuid.UUID
+ Name string
+ ParentID sql.Null[uuid.UUID]
+ EnvID uuid.UUID
+}
+
+type Deps struct {
+ DB pg.DB
+}
+
+type Service struct {
+ db pg.DB
+}
+
+func NewService(deps Deps) *Service {
+ return &Service{db: deps.DB}
+}
+
+// LoadProjectFolders fetches folders for the given environments in a project and builds an in-memory lookup tree.
+func (s *Service) LoadProjectFolders(ctx context.Context, projectID string, envIDs []uuid.UUID) (*FolderLookup, error) {
+ rows, err := s.getFoldersByProjectAndEnvIDs(ctx, projectID, envIDs)
+ if err != nil {
+ return nil, errutil.DatabaseErr("Failed to get folders for project").WithErrf("LoadProjectFolders(projectId=%s): %w", projectID, err)
+ }
+ return newFolderLookup(rows), nil
+}
+
+func (s *Service) getFoldersByProjectAndEnvIDs(ctx context.Context, projectID string, envIDs []uuid.UUID) ([]folderRow, error) {
+ query := `
+ SELECT folder.id, folder.name, folder."parentId", folder."envId"
+ FROM secret_folders folder
+ INNER JOIN project_environments env ON folder."envId" = env.id
+ WHERE env."projectId" = @projectID AND folder."envId" = ANY(@envIDs)
+ `
+ args := pgx.NamedArgs{
+ "projectID": projectID,
+ "envIDs": envIDs,
+ }
+
+ rows, err := s.db.Replica().Query(ctx, query, args)
+ if err != nil {
+ return nil, err
+ }
+
+ folders, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (folderRow, error) {
+ var f folderRow
+ err := row.Scan(&f.ID, &f.Name, &f.ParentID, &f.EnvID)
+ return f, err
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return folders, nil
+}
diff --git a/backend-go/internal/services/secretmanager/secretimport/dal.go b/backend-go/internal/services/secretmanager/secretimport/dal.go
deleted file mode 100644
index ddaf5b620b..0000000000
--- a/backend-go/internal/services/secretmanager/secretimport/dal.go
+++ /dev/null
@@ -1,66 +0,0 @@
-package secretimport
-
-import (
- "context"
- "database/sql"
- "errors"
-
- "github.com/go-jet/jet/v2/postgres"
- "github.com/go-jet/jet/v2/qrm"
- "github.com/google/uuid"
-
- "github.com/infisical/api/internal/database/pg"
- "github.com/infisical/api/internal/database/pg/gen/table"
-)
-
-type importRow struct {
- ID uuid.UUID `alias:"secret_imports.id"`
- ImportPath string `alias:"secret_imports.importPath"`
- ImportEnvID uuid.UUID `alias:"secret_imports.importEnv"`
- Position int32 `alias:"secret_imports.position"`
- FolderID uuid.UUID `alias:"secret_imports.folderId"`
- IsReplication sql.Null[bool] `alias:"secret_imports.isReplication"`
- IsReserved sql.Null[bool] `alias:"secret_imports.isReserved"`
-}
-
-type DAL struct {
- db pg.DB
-}
-
-func NewDAL(db pg.DB) *DAL {
- return &DAL{db: db}
-}
-
-func (d *DAL) GetImportsByProjectID(ctx context.Context, projectID string) ([]importRow, error) {
- si := table.SecretImports
- sf := table.SecretFolders
- pe := table.ProjectEnvironments
-
- stmt := postgres.SELECT(
- si.ID,
- si.ImportPath,
- si.ImportEnv,
- si.Position,
- si.FolderId,
- si.IsReplication,
- si.IsReserved,
- ).FROM(
- si.INNER_JOIN(sf, si.FolderId.EQ(sf.ID)).
- INNER_JOIN(pe, sf.EnvId.EQ(pe.ID)),
- ).WHERE(
- pe.ProjectId.EQ(postgres.String(projectID)),
- ).ORDER_BY(
- si.FolderId.ASC(), si.Position.ASC(),
- )
-
- var rows []importRow
- err := stmt.QueryContext(ctx, d.db.Primary(), &rows)
- if err != nil {
- if errors.Is(err, qrm.ErrNoRows) {
- return nil, nil
- }
- return nil, err
- }
-
- return rows, nil
-}
diff --git a/backend-go/internal/services/secretmanager/secretimport/secret_import.go b/backend-go/internal/services/secretmanager/secretimport/secret_import.go
deleted file mode 100644
index 6fbad7de4a..0000000000
--- a/backend-go/internal/services/secretmanager/secretimport/secret_import.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package secretimport
-
-import (
- "context"
-
- "github.com/infisical/api/internal/libs/errutil"
-)
-
-type dal interface {
- GetImportsByProjectID(ctx context.Context, projectID string) ([]importRow, error)
-}
-
-type Service struct {
- dal dal
-}
-
-// Deps holds the dependencies for the secret import shared service.
-type Deps struct {
- DAL dal
-}
-
-func NewService(deps Deps) *Service {
- return &Service{dal: deps.DAL}
-}
-
-// LoadProjectImports fetches all secret imports for a project and builds an in-memory lookup.
-func (s *Service) LoadProjectImports(ctx context.Context, projectID string) (*ImportLookup, error) {
- rows, err := s.dal.GetImportsByProjectID(ctx, projectID)
- if err != nil {
- return nil, errutil.DatabaseErr("Failed to get imports for project").WithErrf("LoadProjectImports(projectId=%s): %w", projectID, err)
- }
- return newImportLookup(rows), nil
-}
diff --git a/backend-go/internal/services/secretmanager/secretimport/service.go b/backend-go/internal/services/secretmanager/secretimport/service.go
new file mode 100644
index 0000000000..7b9abcac66
--- /dev/null
+++ b/backend-go/internal/services/secretmanager/secretimport/service.go
@@ -0,0 +1,71 @@
+package secretimport
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+
+ "github.com/infisical/api/internal/database/pg"
+ "github.com/infisical/api/internal/libs/errutil"
+)
+
+type importRow struct {
+ ID uuid.UUID
+ ImportPath string
+ ImportEnvID uuid.UUID
+ Position int32
+ FolderID uuid.UUID
+ IsReplication sql.Null[bool]
+ IsReserved sql.Null[bool]
+}
+
+type Deps struct {
+ DB pg.DB
+}
+
+type Service struct {
+ db pg.DB
+}
+
+func NewService(deps Deps) *Service {
+ return &Service{db: deps.DB}
+}
+
+// LoadProjectImports fetches all secret imports for a project and builds an in-memory lookup.
+func (s *Service) LoadProjectImports(ctx context.Context, projectID string) (*ImportLookup, error) {
+ rows, err := s.getImportsByProjectID(ctx, projectID)
+ if err != nil {
+ return nil, errutil.DatabaseErr("Failed to get imports for project").WithErrf("LoadProjectImports(projectId=%s): %w", projectID, err)
+ }
+ return newImportLookup(rows), nil
+}
+
+func (s *Service) getImportsByProjectID(ctx context.Context, projectID string) ([]importRow, error) {
+ query := `
+ SELECT imp.id, imp."importPath", imp."importEnv", imp.position, imp."folderId", imp."isReplication", imp."isReserved"
+ FROM secret_imports imp
+ INNER JOIN secret_folders folder ON imp."folderId" = folder.id
+ INNER JOIN project_environments env ON folder."envId" = env.id
+ WHERE env."projectId" = @projectID
+ ORDER BY imp."folderId" ASC, imp.position ASC
+ `
+ args := pgx.NamedArgs{"projectID": projectID}
+
+ rows, err := s.db.Replica().Query(ctx, query, args)
+ if err != nil {
+ return nil, err
+ }
+
+ imports, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (importRow, error) {
+ var imp importRow
+ err := row.Scan(&imp.ID, &imp.ImportPath, &imp.ImportEnvID, &imp.Position, &imp.FolderID, &imp.IsReplication, &imp.IsReserved)
+ return imp, err
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return imports, nil
+}
diff --git a/backend-go/internal/services/serverconfig/dal.go b/backend-go/internal/services/serverconfig/dal.go
deleted file mode 100644
index ae7e624cab..0000000000
--- a/backend-go/internal/services/serverconfig/dal.go
+++ /dev/null
@@ -1,82 +0,0 @@
-package serverconfig
-
-import (
- "context"
- "database/sql"
- "errors"
- "fmt"
-
- "github.com/go-jet/jet/v2/postgres"
- "github.com/go-jet/jet/v2/qrm"
-
- "github.com/infisical/api/internal/database/ormify"
- "github.com/infisical/api/internal/database/pg/gen/model"
- "github.com/infisical/api/internal/database/pg/gen/table"
-)
-
-// DAL handles all database operations for the super_admin config table.
-type DAL struct {
- *ormify.DAL[model.SuperAdmin]
- db *sql.DB
-}
-
-// NewDAL creates a new server config DAL.
-func NewDAL(primary, replica qrm.DB, db *sql.DB) *DAL {
- return &DAL{
- DAL: ormify.New[model.SuperAdmin](primary, replica, &ormify.TableDef{
- Table: table.SuperAdmin,
- AllColumns: table.SuperAdmin.AllColumns,
- MutableColumns: table.SuperAdmin.MutableColumns,
- IDColumn: table.SuperAdmin.ID,
- }),
- db: db,
- }
-}
-
-// FindOrCreateConfig atomically ensures the config row exists.
-// It acquires a PG advisory lock, checks for an existing row, and creates one if missing.
-// The entire operation runs in a single transaction — no tx is exposed to callers.
-func (d *DAL) FindOrCreateConfig(ctx context.Context) (*model.SuperAdmin, error) {
- tx, err := d.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, fmt.Errorf("beginning transaction: %w", err)
- }
-
- // Acquire advisory lock to prevent concurrent init.
- if _, err := tx.ExecContext(ctx, "SELECT pg_advisory_xact_lock($1)", PgLockSuperAdminInit); err != nil {
- _ = tx.Rollback()
- return nil, fmt.Errorf("acquiring advisory lock: %w", err)
- }
-
- // Check if config already exists.
- txDAL := d.WithTx(tx)
- cfg, err := txDAL.FindByID(ctx, adminConfigDBUUID)
- if err == nil {
- if cerr := tx.Commit(); cerr != nil {
- return nil, fmt.Errorf("committing config read: %w", cerr)
- }
- return cfg, nil
- }
- if !errors.Is(err, qrm.ErrNoRows) {
- _ = tx.Rollback()
- return nil, fmt.Errorf("checking existing config: %w", err)
- }
-
- // Create the initial config row (ID is not in MutableColumns, so we use a custom insert).
- var result model.SuperAdmin
- err = table.SuperAdmin.
- INSERT(table.SuperAdmin.ID, table.SuperAdmin.Initialized, table.SuperAdmin.AllowSignUp, table.SuperAdmin.FipsEnabled).
- VALUES(postgres.UUID(adminConfigDBUUID), postgres.Bool(false), postgres.Bool(true), postgres.Bool(false)).
- RETURNING(table.SuperAdmin.AllColumns).
- QueryContext(ctx, tx, &result)
- if err != nil {
- _ = tx.Rollback()
- return nil, fmt.Errorf("creating initial config: %w", err)
- }
-
- if err := tx.Commit(); err != nil {
- return nil, fmt.Errorf("committing init transaction: %w", err)
- }
-
- return &result, nil
-}
diff --git a/backend-go/internal/services/serverconfig/serverconfig.go b/backend-go/internal/services/serverconfig/serverconfig.go
index bac6efa7c9..71883f13e6 100644
--- a/backend-go/internal/services/serverconfig/serverconfig.go
+++ b/backend-go/internal/services/serverconfig/serverconfig.go
@@ -2,23 +2,23 @@ package serverconfig
import (
"context"
+ "database/sql"
"encoding/json"
+ "errors"
"fmt"
"log/slog"
"time"
"github.com/google/uuid"
- "github.com/lib/pq"
+ "github.com/jackc/pgx/v5"
- "github.com/infisical/api/internal/database/pg/gen/model"
+ "github.com/infisical/api/internal/database/pg"
"github.com/infisical/api/internal/libs/errutil"
)
var adminConfigDBUUID = uuid.MustParse("00000000-0000-0000-0000-000000000000")
const (
- // AdminConfigDBUUID is the fixed UUID for the single super_admin config row.
-
// PgLockSuperAdminInit is the advisory lock ID used during config initialization.
PgLockSuperAdminInit int64 = 2024
@@ -46,47 +46,67 @@ type ServerConfig struct {
FipsEnabled bool
}
-func configFromModel(m *model.SuperAdmin) ServerConfig {
+// superAdminRow is the raw database row for super_admin.
+type superAdminRow struct {
+ ID uuid.UUID
+ Initialized sql.Null[bool]
+ AllowSignUp sql.Null[bool]
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ AllowedSignUpDomain sql.Null[string]
+ InstanceID uuid.UUID
+ TrustSamlEmails sql.Null[bool]
+ TrustLdapEmails sql.Null[bool]
+ TrustOidcEmails sql.Null[bool]
+ DefaultAuthOrgID sql.Null[uuid.UUID]
+ EnabledLoginMethods []string
+ AuthConsentContent sql.Null[string]
+ PageFrameContent sql.Null[string]
+ AdminIdentityIDs []string
+ FipsEnabled bool
+}
+
+func configFromRow(r *superAdminRow) ServerConfig {
cfg := ServerConfig{
- ID: m.ID,
- CreatedAt: m.CreatedAt,
- UpdatedAt: m.UpdatedAt,
- InstanceID: m.InstanceId,
- FipsEnabled: m.FipsEnabled,
+ ID: r.ID,
+ CreatedAt: r.CreatedAt,
+ UpdatedAt: r.UpdatedAt,
+ InstanceID: r.InstanceID,
+ FipsEnabled: r.FipsEnabled,
}
- if m.Initialized.Valid {
- cfg.Initialized = m.Initialized.V
+ if r.Initialized.Valid {
+ cfg.Initialized = r.Initialized.V
}
- if m.AllowSignUp.Valid {
- cfg.AllowSignUp = m.AllowSignUp.V
+ if r.AllowSignUp.Valid {
+ cfg.AllowSignUp = r.AllowSignUp.V
}
- if m.AllowedSignUpDomain.Valid {
- cfg.AllowedSignUpDomain = m.AllowedSignUpDomain.V
+ if r.AllowedSignUpDomain.Valid {
+ cfg.AllowedSignUpDomain = r.AllowedSignUpDomain.V
}
- if m.TrustSamlEmails.Valid {
- cfg.TrustSamlEmails = m.TrustSamlEmails.V
+ if r.TrustSamlEmails.Valid {
+ cfg.TrustSamlEmails = r.TrustSamlEmails.V
}
- if m.TrustLdapEmails.Valid {
- cfg.TrustLdapEmails = m.TrustLdapEmails.V
+ if r.TrustLdapEmails.Valid {
+ cfg.TrustLdapEmails = r.TrustLdapEmails.V
}
- if m.TrustOidcEmails.Valid {
- cfg.TrustOidcEmails = m.TrustOidcEmails.V
+ if r.TrustOidcEmails.Valid {
+ cfg.TrustOidcEmails = r.TrustOidcEmails.V
}
- if m.DefaultAuthOrgId.Valid {
- cfg.DefaultAuthOrgID = &m.DefaultAuthOrgId.V
+ if r.DefaultAuthOrgID.Valid {
+ cfg.DefaultAuthOrgID = &r.DefaultAuthOrgID.V
}
- if m.EnabledLoginMethods != nil {
- cfg.EnabledLoginMethods = []string(*m.EnabledLoginMethods)
+ if r.EnabledLoginMethods != nil {
+ cfg.EnabledLoginMethods = r.EnabledLoginMethods
}
- if m.AuthConsentContent.Valid {
- cfg.AuthConsentContent = m.AuthConsentContent.V
+ if r.AuthConsentContent.Valid {
+ cfg.AuthConsentContent = r.AuthConsentContent.V
}
- if m.PageFrameContent.Valid {
- cfg.PageFrameContent = m.PageFrameContent.V
+ if r.PageFrameContent.Valid {
+ cfg.PageFrameContent = r.PageFrameContent.V
}
- if m.AdminIdentityIds != nil {
- cfg.AdminIdentityIDs = []string(*m.AdminIdentityIds)
+ if r.AdminIdentityIDs != nil {
+ cfg.AdminIdentityIDs = r.AdminIdentityIDs
}
return cfg
@@ -99,48 +119,41 @@ type keyStore interface {
DeleteItem(ctx context.Context, key string) (int64, error)
}
-// dal defines the subset of DAL operations this service needs.
-type dal interface {
- FindByID(ctx context.Context, id uuid.UUID) (*model.SuperAdmin, error)
- FindOrCreateConfig(ctx context.Context) (*model.SuperAdmin, error)
- UpdateByID(ctx context.Context, id string, columns pq.StringArray, data *model.SuperAdmin) (*model.SuperAdmin, error)
-}
-
// Service manages the server admin configuration (the single super_admin row).
// It provides cached reads (via Redis) and idempotent initialization (via PG advisory lock).
type Service struct {
- dal dal
+ db pg.DB
keyStore keyStore
logger *slog.Logger
}
// Deps holds the dependencies for the server config shared service.
type Deps struct {
- DAL dal
+ DB pg.DB
KeyStore keyStore
}
// NewService creates a new server config service.
func NewService(logger *slog.Logger, deps Deps) *Service {
return &Service{
- dal: deps.DAL,
+ db: deps.DB,
keyStore: deps.KeyStore,
logger: logger,
}
}
// Init ensures the super_admin config row exists.
-// Delegates to the DAL which handles the advisory lock and transaction internally.
+// Uses a PG advisory lock to prevent concurrent initialization.
func (s *Service) Init(ctx context.Context) (ServerConfig, error) {
if _, err := s.keyStore.DeleteItem(ctx, adminConfigCacheKey); err != nil {
return ServerConfig{}, fmt.Errorf("deleting config from cache: %w", err)
}
- m, err := s.dal.FindOrCreateConfig(ctx)
+ cfg, err := s.findOrCreateConfig(ctx)
if err != nil {
return ServerConfig{}, errutil.DatabaseErr("Failed to initialize server config").WithErrf("Init: %w", err)
}
- return configFromModel(m), nil
+ return cfg, nil
}
// GetConfig returns the server admin config, using a Redis cache with a 60s TTL.
@@ -160,12 +173,12 @@ func (s *Service) GetConfig(ctx context.Context) (ServerConfig, error) {
}
// Cache miss — read from DB.
- m, err := s.dal.FindByID(ctx, adminConfigDBUUID)
+ row, err := s.findByID(ctx, adminConfigDBUUID)
if err != nil {
return ServerConfig{}, errutil.DatabaseErr("Failed to read server config").WithErrf("GetConfig: %w", err)
}
- cfg := configFromModel(m)
+ cfg := configFromRow(row)
// Populate cache (non-fatal on error).
if data, err := json.Marshal(cfg); err == nil {
@@ -182,3 +195,111 @@ func (s *Service) InvalidateCache(ctx context.Context) error {
_, err := s.keyStore.DeleteItem(ctx, adminConfigCacheKey)
return err
}
+
+// --- Query methods ---
+
+// findByID returns the super_admin config row by ID.
+func (s *Service) findByID(ctx context.Context, id uuid.UUID) (*superAdminRow, error) {
+ query := `
+ SELECT
+ id, initialized, "allowSignUp", "createdAt", "updatedAt",
+ "allowedSignUpDomain", "instanceId", "trustSamlEmails", "trustLdapEmails", "trustOidcEmails",
+ "defaultAuthOrgId", "enabledLoginMethods", "authConsentContent", "pageFrameContent",
+ "adminIdentityIds", "fipsEnabled"
+ FROM super_admin
+ WHERE id = @id
+ `
+ args := pgx.NamedArgs{"id": id}
+
+ row := s.db.Replica().QueryRow(ctx, query, args)
+
+ var r superAdminRow
+ err := row.Scan(
+ &r.ID, &r.Initialized, &r.AllowSignUp, &r.CreatedAt, &r.UpdatedAt,
+ &r.AllowedSignUpDomain, &r.InstanceID, &r.TrustSamlEmails, &r.TrustLdapEmails, &r.TrustOidcEmails,
+ &r.DefaultAuthOrgID, &r.EnabledLoginMethods, &r.AuthConsentContent, &r.PageFrameContent,
+ &r.AdminIdentityIDs, &r.FipsEnabled,
+ )
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, errutil.NotFound("Server config not found")
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ return &r, nil
+}
+
+// findOrCreateConfig atomically ensures the config row exists.
+// It acquires a PG advisory lock, checks for an existing row, and creates one if missing.
+func (s *Service) findOrCreateConfig(ctx context.Context) (ServerConfig, error) {
+ tx, err := s.db.Primary().Begin(ctx)
+ if err != nil {
+ return ServerConfig{}, fmt.Errorf("beginning transaction: %w", err)
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+
+ // Acquire advisory lock to prevent concurrent init.
+ if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock($1)", PgLockSuperAdminInit); err != nil {
+ return ServerConfig{}, fmt.Errorf("acquiring advisory lock: %w", err)
+ }
+
+ // Check if config already exists.
+ query := `
+ SELECT
+ id, initialized, "allowSignUp", "createdAt", "updatedAt",
+ "allowedSignUpDomain", "instanceId", "trustSamlEmails", "trustLdapEmails", "trustOidcEmails",
+ "defaultAuthOrgId", "enabledLoginMethods", "authConsentContent", "pageFrameContent",
+ "adminIdentityIds", "fipsEnabled"
+ FROM super_admin
+ WHERE id = @id
+ `
+ args := pgx.NamedArgs{"id": adminConfigDBUUID}
+
+ row := tx.QueryRow(ctx, query, args)
+
+ var r superAdminRow
+ err = row.Scan(
+ &r.ID, &r.Initialized, &r.AllowSignUp, &r.CreatedAt, &r.UpdatedAt,
+ &r.AllowedSignUpDomain, &r.InstanceID, &r.TrustSamlEmails, &r.TrustLdapEmails, &r.TrustOidcEmails,
+ &r.DefaultAuthOrgID, &r.EnabledLoginMethods, &r.AuthConsentContent, &r.PageFrameContent,
+ &r.AdminIdentityIDs, &r.FipsEnabled,
+ )
+ if err == nil {
+ if cerr := tx.Commit(ctx); cerr != nil {
+ return ServerConfig{}, fmt.Errorf("committing config read: %w", cerr)
+ }
+ return configFromRow(&r), nil
+ }
+ if !errors.Is(err, pgx.ErrNoRows) {
+ return ServerConfig{}, fmt.Errorf("checking existing config: %w", err)
+ }
+
+ // Create the initial config row.
+ insertQuery := `
+ INSERT INTO super_admin (id, initialized, "allowSignUp", "fipsEnabled")
+ VALUES (@id, false, true, false)
+ RETURNING
+ id, initialized, "allowSignUp", "createdAt", "updatedAt",
+ "allowedSignUpDomain", "instanceId", "trustSamlEmails", "trustLdapEmails", "trustOidcEmails",
+ "defaultAuthOrgId", "enabledLoginMethods", "authConsentContent", "pageFrameContent",
+ "adminIdentityIds", "fipsEnabled"
+ `
+
+ row = tx.QueryRow(ctx, insertQuery, args)
+ err = row.Scan(
+ &r.ID, &r.Initialized, &r.AllowSignUp, &r.CreatedAt, &r.UpdatedAt,
+ &r.AllowedSignUpDomain, &r.InstanceID, &r.TrustSamlEmails, &r.TrustLdapEmails, &r.TrustOidcEmails,
+ &r.DefaultAuthOrgID, &r.EnabledLoginMethods, &r.AuthConsentContent, &r.PageFrameContent,
+ &r.AdminIdentityIDs, &r.FipsEnabled,
+ )
+ if err != nil {
+ return ServerConfig{}, fmt.Errorf("creating initial config: %w", err)
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ return ServerConfig{}, fmt.Errorf("committing init transaction: %w", err)
+ }
+
+ return configFromRow(&r), nil
+}
diff --git a/backend-go/internal/testutil/infra/nodejs.go b/backend-go/internal/testutil/infra/nodejs.go
index 3b1f1ec7b1..ed83afd452 100644
--- a/backend-go/internal/testutil/infra/nodejs.go
+++ b/backend-go/internal/testutil/infra/nodejs.go
@@ -537,7 +537,7 @@ func (n *NodeJSService) CreateUserAdditionalPrivilege(t *testing.T, userID, proj
// Look up the user's project membership ID from the unified memberships table.
var membershipID string
err := n.db.Primary().QueryRow(context.Background(),
- `SELECT id FROM memberships WHERE actor_user_id = $1 AND scope_project_id = $2 AND scope = 'project'`,
+ `SELECT id FROM memberships WHERE "actorUserId" = $1 AND "scopeProjectId" = $2 AND scope = 'project'`,
userID, projectID).Scan(&membershipID)
if err != nil {
t.Fatalf("infra.CreateUserAdditionalPrivilege: query membership ID: %v", err)