Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: completed kms service for secrets
=5382b05bfebb
diff --git a/backend-go/CLAUDE.md b/backend-go/CLAUDE.mdindex 74fb23a57c..62b3eb6af4 100644--- a/backend-go/CLAUDE.md+++ b/backend-go/CLAUDE.md@@ -112,6 +112,10 @@ go-jet generated table types live in `internal/database/pg/gen/table/` (50+ tabl**All database operations must go through a DAL, never directly from a service.** Services must not import `table`, `postgres`, or `qrm` packages or construct queries themselves. Instead, create or extend a DAL with the required method and call it from the service. This keeps query logic centralized and testable.+**Always use type-safe go-jet queries — never raw SQL.** Use go-jet's generated table types for all SELECT, INSERT, UPDATE, and DELETE operations. For UPDATE, use `Table.UPDATE(columns...).SET(values...).WHERE(...)` or the column-expression form `Column.SET(expression)`. See [go-jet UPDATE docs](https://github.com/go-jet/jet/wiki/UPDATE). Raw `tx.ExecContext(ctx, "UPDATE ...")` is not allowed — the only exception is PostgreSQL advisory locks (`pg_advisory_xact_lock`) which have no go-jet equivalent.++**Keep code lean.** Organize DAL files by functionality. If a helper function is only called once, inline it at the call site instead of extracting a separate method. Only extract shared helpers when they have multiple callers. Split files needed to organize similiar functionality ones+### ConfigurationEnvironment variables loaded via koanf (`internal/config/config.go`). 186+ settings covering DB, Redis, auth, encryption, SSO, integrations, etc. Validated on startup with `config.ValidationError`.diff --git a/backend-go/cmd/dev/pg_gen/main.go b/backend-go/cmd/dev/pg_gen/main.goindex 4641ffc175..4d2f216523 100644--- a/backend-go/cmd/dev/pg_gen/main.go+++ b/backend-go/cmd/dev/pg_gen/main.go@@ -57,6 +57,35 @@ func main() {if isPartitionTable(table.Name) {m.Skip = true}++ m = m.UseField(func(columnMetaData metadata.Column) template.TableModelField {+ defaultTableModelField := template.DefaultTableModelField(columnMetaData)++ switch defaultTableModelField.Type.Name {+ case "*string":+ defaultTableModelField.Type = template.NewType(sql.Null[string]{})+ case "*int32":+ defaultTableModelField.Type = template.NewType(sql.Null[int32]{})+ case "*int64":+ defaultTableModelField.Type = template.NewType(sql.Null[int64]{})+ case "*bool":+ defaultTableModelField.Type = template.NewType(sql.Null[bool]{})+ case "*float64":+ defaultTableModelField.Type = template.NewType(sql.Null[float64]{})+ case "*time.Time":+ defaultTableModelField.Type = template.NewType(sql.NullTime{})+ case "*[]byte":+ defaultTableModelField.Type = template.NewType(sql.Null[[]byte]{})+ case "*uuid.UUID":+ defaultTableModelField.Type = template.Type{+ ImportPath: "database/sql",+ Name: "sql.Null[uuid.UUID]",+ AdditionalImportPaths: []string{"github.com/google/uuid"},+ }+ }+ return defaultTableModelField+ })+return m}),).diff --git a/backend-go/cmd/infisical/main.go b/backend-go/cmd/infisical/main.goindex a407c3ffa7..67d6121420 100644--- a/backend-go/cmd/infisical/main.go+++ b/backend-go/cmd/infisical/main.go@@ -15,6 +15,7 @@ import ("github.com/infisical/api/internal/libs/bootstrap""github.com/infisical/api/internal/server""github.com/infisical/api/internal/services"+ "github.com/infisical/api/internal/services/shared")func main() {@@ -51,8 +52,14 @@ func main() {dbReport := bootstrap.CheckDBConnection(ctx, db)dbReport.PrintReport(logger)- // Initialize all services.- svc := services.NewRegistry(logger)+ svc, err := services.NewRegistry(logger, shared.SharedServicesDeps{+ Config: cfg,+ DB: db,+ })+ if err != nil {+ logger.Error("failed to initialize services", "error", err)+ os.Exit(1)+ }// Create server.srv := server.NewServer(svc, logger)diff --git a/backend-go/docker-compose.test.yml b/backend-go/docker-compose.test.ymlindex 3d0a73f471..ddb3d75a28 100644--- a/backend-go/docker-compose.test.yml+++ b/backend-go/docker-compose.test.yml@@ -8,7 +8,7 @@ services:POSTGRES_USER: infisicalPOSTGRES_DB: infisicalhealthcheck:- test: ["CMD-SHELL", "pg_isready -U infisical"]+ test: [ "CMD-SHELL", "pg_isready -U infisical" ]interval: 5stimeout: 5sretries: 5@@ -18,7 +18,7 @@ services:ports:- "6379:6379"healthcheck:- test: ["CMD", "redis-cli", "ping"]+ test: [ "CMD", "redis-cli", "ping" ]interval: 5stimeout: 5sretries: 5diff --git a/backend-go/internal/database/ormify/ormify.go b/backend-go/internal/database/ormify/ormify.goindex 404103e441..e302def913 100644--- a/backend-go/internal/database/ormify/ormify.go+++ b/backend-go/internal/database/ormify/ormify.go@@ -6,6 +6,7 @@ import ("github.com/go-jet/jet/v2/postgres""github.com/go-jet/jet/v2/qrm"+ "github.com/google/uuid")// TableDef holds go-jet table metadata needed for generic CRUD operations.@@ -66,10 +67,10 @@ func (d *DAL[M]) WithTx(tx *sql.Tx) *DAL[M] {}// FindByID returns a single row by its primary key.-func (d *DAL[M]) FindByID(ctx context.Context, id string) (*M, error) {+func (d *DAL[M]) FindByID(ctx context.Context, id uuid.UUID) (*M, error) {stmt := d.def.Table.SELECT(d.def.AllColumns).- WHERE(d.def.IDColumn.EQ(postgres.String(id)))+ WHERE(d.def.IDColumn.EQ(postgres.UUID(id)))var result Merr := stmt.QueryContext(ctx, d.replica, &result)diff --git a/backend-go/internal/database/pg/pg.go b/backend-go/internal/database/pg/pg.goindex 92927a0c2b..ae166dc8e0 100644--- a/backend-go/internal/database/pg/pg.go+++ b/backend-go/internal/database/pg/pg.go@@ -17,18 +17,35 @@ import ("github.com/infisical/api/internal/config")-// DB wraps a primary pgxpool and zero or more read-replica pools,-// exposing them as *sql.DB for compatibility with go-jet and database/sql consumers.-type DB struct {- primary *pgxpool.Pool- replicas []*pgxpool.Pool- primarySQL *sql.DB- replicaSQL []*sql.DB+// Tx represents a database transaction executor.+// Satisfied by *sql.Tx and keystore.Tx. Includes Exec/Query to satisfy go-jet's qrm.DB.+type Tx interface {+ Exec(query string, args ...any) (sql.Result, error)+ ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)+ Query(query string, args ...any) (*sql.Rows, error)+ QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)+}++type DB interface {+ Primary() *sql.DB+ Replica() *sql.DB+ ReplicaCount() int+ PrimaryPool() *pgxpool.Pool+ Close()+}++// pgDatabase wraps a primary pgxpool and zero or more read-replica pools,+// exposing them as *sql.pgDatabase for compatibility with go-jet and database/sql consumers.+type pgDatabase struct {+ primary *pgxpool.Pool+ replicas []*pgxpool.Pool+ primarySQL *sql.DB+ replicaSQL []*sql.DB}// NewPostgresDB creates a connection pool for the primary database and optional read replicas.// primaryRootCert is used as fallback for replicas that don't specify their own cert.-func NewPostgresDB(ctx context.Context, primaryURI, primaryRootCert string, readReplicas []config.DBReadReplica) (*DB, error) {+func NewPostgresDB(ctx context.Context, primaryURI, primaryRootCert string, readReplicas []config.DBReadReplica) (DB, error) {primaryPool, err := openPool(ctx, primaryURI, primaryRootCert)if err != nil {return nil, fmt.Errorf("primary db: %w", err)@@ -61,7 +78,7 @@ func NewPostgresDB(ctx context.Context, primaryURI, primaryRootCert string, readreplicaSQLDBs[i] = stdlib.OpenDBFromPool(p)}- return &DB{+ return &pgDatabase{primary: primaryPool,replicas: replicaPools,primarySQL: primarySQLDB,@@ -70,13 +87,13 @@ func NewPostgresDB(ctx context.Context, primaryURI, primaryRootCert string, read}// Primary returns the primary database as *sql.DB.-func (db *DB) Primary() *sql.DB {+func (db *pgDatabase) Primary() *sql.DB {return db.primarySQL}// Replica returns a random read-replica as *sql.DB, or the primary if no replicas are configured.// Matches the Node.js behavior: Math.floor(Math.random() * readReplicaDbs.length).-func (db *DB) Replica() *sql.DB {+func (db *pgDatabase) Replica() *sql.DB {if len(db.replicaSQL) == 0 {return db.primarySQL}@@ -84,17 +101,17 @@ func (db *DB) Replica() *sql.DB {}// ReplicaCount returns the number of read replicas configured.-func (db *DB) ReplicaCount() int {+func (db *pgDatabase) ReplicaCount() int {return len(db.replicas)}// PrimaryPool returns the underlying primary pgxpool.Pool for operations that need it directly.-func (db *DB) PrimaryPool() *pgxpool.Pool {+func (db *pgDatabase) PrimaryPool() *pgxpool.Pool {return db.primary}// Close closes all connection pools (primary + replicas) and their sql.DB wrappers.-func (db *DB) Close() {+func (db *pgDatabase) Close() {db.primarySQL.Close()for _, s := range db.replicaSQL {s.Close()diff --git a/backend-go/internal/keystore/keystore.go b/backend-go/internal/keystore/keystore.goindex 838d202d09..06ea24d3d0 100644--- a/backend-go/internal/keystore/keystore.go+++ b/backend-go/internal/keystore/keystore.go@@ -11,8 +11,11 @@ import (// Tx represents a database transaction. *sql.Tx satisfies this interface.// Consumers can use lock.Tx() with DAL operations that accept this interface.+// Includes Exec/Query (non-context variants) so Tx satisfies go-jet's qrm.DB.type Tx interface {+ Exec(query string, args ...any) (sql.Result, error)ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)+ Query(query string, args ...any) (*sql.Rows, error)QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)Commit() errorRollback() errordiff --git a/backend-go/internal/libs/bootstrap/bootstrap.go b/backend-go/internal/libs/bootstrap/bootstrap.goindex fff3b06173..117baf4bdb 100644--- a/backend-go/internal/libs/bootstrap/bootstrap.go+++ b/backend-go/internal/libs/bootstrap/bootstrap.go@@ -40,7 +40,7 @@ func (r *DBReport) PrintReport(logger *slog.Logger) {// CheckDBConnection pings the primary database and all read replicas,// returning a report with the status of each.-func CheckDBConnection(ctx context.Context, db *pg.DB) *DBReport {+func CheckDBConnection(ctx context.Context, db pg.DB) *DBReport {report := &DBReport{}if err := db.Primary().PingContext(ctx); err != nil {diff --git a/backend-go/internal/services/services.go b/backend-go/internal/services/services.goindex 5653b0746b..481bb6589e 100644--- a/backend-go/internal/services/services.go+++ b/backend-go/internal/services/services.go@@ -1,6 +1,7 @@package servicesimport (+ "fmt""log/slog""github.com/infisical/api/internal/services/platform"@@ -14,12 +15,15 @@ type Registry struct {Libs *shared.SharedServices}-func NewRegistry(logger *slog.Logger) *Registry {- sharedLibs := shared.NewSharedServices()+func NewRegistry(logger *slog.Logger, sharedDeps shared.SharedServicesDeps) (*Registry, error) {+ sharedLibs, err := shared.NewSharedServices(sharedDeps)+ if err != nil {+ return nil, fmt.Errorf("shared services: %w", err)+ }return &Registry{Libs: sharedLibs,Platform: platform.NewRegistry(logger, sharedLibs),SecretManager: secretmanager.NewRegistry(logger, sharedLibs),- }+ }, nil}diff --git a/backend-go/internal/services/shared/kms/dal.go b/backend-go/internal/services/shared/kms/dal.gonew file mode 100644index 0000000000..44fd860d11--- /dev/null+++ b/backend-go/internal/services/shared/kms/dal.go@@ -0,0 +1,440 @@+package kms++import (+ "context"+ "database/sql"+ "fmt"++ "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/model"+ "github.com/infisical/api/internal/database/pg/gen/table"+ "github.com/infisical/api/internal/keystore"+)++// dalLockStore provides advisory locking for the DAL.+type dalLockStore interface {+ AcquirePgLock(ctx context.Context, lockID string, tx keystore.Tx) (*keystore.Lock, error)+}++// KmsKeyWithAssociatedKms is the join result of kms_keys LEFT JOIN internal_kms LEFT JOIN external_kms.+// Exactly one of InternalKms or ExternalKms will be non-nil.+type KmsKeyWithAssociatedKms struct {+ model.KmsKeys++ InternalKms *model.InternalKms+ ExternalKms *model.ExternalKms+}++// OrgKmsInfo holds the narrow org fields needed by the KMS service.+type OrgKmsInfo struct {+ ID uuid.UUID `alias:"organizations.id"`+ KmsDefaultKeyId sql.Null[uuid.UUID] `alias:"organizations.kmsDefaultKeyId"`+ KmsEncryptedDataKey *[]byte `alias:"organizations.kmsEncryptedDataKey"`+}++// ProjectKmsInfo holds the narrow project fields needed by the KMS service.+type ProjectKmsInfo struct {+ ID string `alias:"projects.id"`+ OrgId uuid.UUID `alias:"projects.orgId"`+ KmsSecretManagerKeyId sql.Null[uuid.UUID] `alias:"projects.kmsSecretManagerKeyId"`+ KmsSecretManagerEncryptedDataKey *[]byte `alias:"projects.kmsSecretManagerEncryptedDataKey"`+}++// DAL handles all KMS-related database operations across+// kms_root_config, kms_keys, internal_kms, organizations, and projects.+type DAL struct {+ db pg.DB+ lockStore dalLockStore+}++// NewDAL creates a new KMS DAL.+func NewDAL(db pg.DB, lockStore dalLockStore) *DAL {+ return &DAL{db: db, lockStore: lockStore}+}++// --- Root config ---++// FindOrCreateRootConfig atomically ensures the KMS root config row exists.+// Acquires a PG advisory lock, checks for an existing row, and calls createFn only+// when no config exists (avoiding unnecessary key generation on the hot path).+func (d *DAL) FindOrCreateRootConfig(ctx context.Context, createFn func() (encryptedRootKey []byte, encryptionStrategy string, err error)) (*model.KmsRootConfig, error) {+ tx, err := d.db.Primary().BeginTx(ctx, nil)+ if err != nil {+ return nil, fmt.Errorf("beginning transaction: %w", err)+ }++ if _, err := tx.ExecContext(ctx, "SELECT pg_advisory_xact_lock($1)", PgLockKmsRootKeyInit); err != nil {+ tx.Rollback()+ return nil, fmt.Errorf("acquiring advisory lock: %w", err)+ }++ // Check if root config already exists.+ var existing model.KmsRootConfig+ err = table.KmsRootConfig.+ SELECT(table.KmsRootConfig.AllColumns).+ WHERE(table.KmsRootConfig.ID.EQ(postgres.UUID(KmsRootConfigUUID))).+ QueryContext(ctx, tx, &existing)+ if err == nil {+ tx.Commit()+ return &existing, nil+ }+ if err != qrm.ErrNoRows {+ tx.Rollback()+ return nil, fmt.Errorf("checking existing root config: %w", err)+ }++ // Config doesn't exist — invoke callback to generate the new root key.+ encryptionRootKey, encryptionStrategy, err := createFn()+ if err != nil {+ tx.Rollback()+ return nil, fmt.Errorf("generating root config: %w", err)+ }++ // Create the initial root config row.+ var result model.KmsRootConfig+ err = table.KmsRootConfig.+ INSERT(table.KmsRootConfig.ID, table.KmsRootConfig.EncryptedRootKey, table.KmsRootConfig.EncryptionStrategy).+ MODEL(model.KmsRootConfig{+ ID: KmsRootConfigUUID,+ EncryptedRootKey: encryptionRootKey,+ EncryptionStrategy: sql.Null[string]{V: encryptionStrategy, Valid: true},+ }).+ RETURNING(table.KmsRootConfig.AllColumns).+ QueryContext(ctx, tx, &result)+ if err != nil {+ tx.Rollback()+ return nil, fmt.Errorf("creating root config: %w", err)+ }++ if err := tx.Commit(); err != nil {+ return nil, fmt.Errorf("committing transaction: %w", err)+ }++ return &result, nil+}++// --- Organization KMS key ---++// FindOrCreateOrgKmsKey atomically ensures the org has a default KMS key.+// Acquires an advisory lock, checks for an existing key, and calls createFn only+// when no key exists. createFn should return the encrypted key material.+func (d *DAL) FindOrCreateOrgKmsKey(ctx context.Context, orgID uuid.UUID, createFn func() (encryptedKey []byte, err error)) (uuid.UUID, error) {+ lock, err := d.lockStore.AcquirePgLock(ctx, fmt.Sprintf("kms-org-key:%s", orgID), nil)+ if err != nil {+ return uuid.Nil, fmt.Errorf("acquiring org key lock: %w", err)+ }+ defer lock.Rollback()++ tx := lock.Tx()++ // Re-check after lock — another request may have created it.+ org, err := d.findOrgKmsInfo(ctx, tx, orgID)+ if err != nil {+ return uuid.Nil, fmt.Errorf("finding org: %w", err)+ }+ if org.KmsDefaultKeyId.Valid {+ if err := lock.Release(); err != nil {+ return uuid.Nil, err+ }+ return org.KmsDefaultKeyId.V, nil+ }++ encryptedKey, err := createFn()+ if err != nil {+ return uuid.Nil, fmt.Errorf("generating KMS key: %w", err)+ }++ createdID, err := d.CreateKmsKeyWithInternal(ctx, tx,+ model.KmsKeys{+ Name: generateRandomKeyName(),+ OrgId: org.ID,+ IsReserved: sql.Null[bool]{V: true, Valid: true},+ KeyUsage: "encrypt-decrypt",+ },+ model.InternalKms{+ EncryptedKey: encryptedKey,+ EncryptionAlgorithm: "aes-256-gcm",+ Version: 1,+ },+ )+ if err != nil {+ return uuid.Nil, err+ }++ if _, err := table.Organizations.+ UPDATE(table.Organizations.KmsDefaultKeyId).+ SET(createdID.String()).+ WHERE(table.Organizations.ID.EQ(postgres.UUID(orgID))).+ ExecContext(ctx, tx); err != nil {+ return uuid.Nil, fmt.Errorf("updating org default key: %w", err)+ }++ if err := lock.Release(); err != nil {+ return uuid.Nil, err+ }+ return createdID, nil+}++// --- Organization data key ---++// FindOrCreateOrgDataKey atomically ensures the org has an encrypted data key.+// Acquires an advisory lock, checks for an existing key, and calls createFn only+// when no key exists. createFn should return the encrypted data key.+// Returns the encrypted data key (existing or newly created).+//+// The caller must ensure the org's KMS key exists before calling this+// to avoid deadlocks with concurrent KMS key + data key creation.+func (d *DAL) FindOrCreateOrgDataKey(ctx context.Context, orgID uuid.UUID, createFn func() (encryptedDataKey []byte, err error)) ([]byte, error) {+ lock, err := d.lockStore.AcquirePgLock(ctx, fmt.Sprintf("kms-org-data-key:%s", orgID), nil)+ if err != nil {+ return nil, fmt.Errorf("acquiring org data key lock: %w", err)+ }+ defer lock.Rollback()++ tx := lock.Tx()++ // Re-check after lock — another request may have created it.+ org, err := d.findOrgKmsInfo(ctx, tx, orgID)+ if err != nil {+ return nil, fmt.Errorf("finding org: %w", err)+ }+ if org.KmsEncryptedDataKey != nil {+ if err := lock.Release(); err != nil {+ return nil, err+ }+ return *org.KmsEncryptedDataKey, nil+ }++ encryptedDataKey, err := createFn()+ if err != nil {+ return nil, fmt.Errorf("generating data key: %w", err)+ }++ if _, err := table.Organizations.+ UPDATE(table.Organizations.KmsEncryptedDataKey).+ SET(encryptedDataKey).+ WHERE(table.Organizations.ID.EQ(postgres.UUID(orgID))).+ ExecContext(ctx, tx); err != nil {+ return nil, fmt.Errorf("setting org encrypted data key: %w", err)+ }++ if err := lock.Release(); err != nil {+ return nil, err+ }+ return encryptedDataKey, nil+}++// --- KMS key reads ---++// FindKmsKeyByID loads a kms_keys row with its associated internal or external KMS material.+func (d *DAL) FindKmsKeyByID(ctx context.Context, kmsKeyID uuid.UUID) (*KmsKeyWithAssociatedKms, error) {+ var result KmsKeyWithAssociatedKms++ err := table.KmsKeys.+ LEFT_JOIN(table.InternalKms, table.InternalKms.KmsKeyId.EQ(table.KmsKeys.ID)).+ LEFT_JOIN(table.ExternalKms, table.ExternalKms.KmsKeyId.EQ(table.KmsKeys.ID)).+ SELECT(table.KmsKeys.AllColumns, table.InternalKms.AllColumns, table.ExternalKms.AllColumns).+ WHERE(table.KmsKeys.ID.EQ(postgres.UUID(kmsKeyID))).+ QueryContext(ctx, d.db.Replica(), &result)+ if err != nil {+ return nil, fmt.Errorf("finding KMS key: %w", err)+ }++ return &result, nil+}++// --- KMS key creation ---++// CreateKmsKeyWithInternal inserts a kms_keys row and its internal_kms material within a transaction.+// Returns the generated kms_keys.id.+func (d *DAL) CreateKmsKeyWithInternal(ctx context.Context, tx pg.Tx, kmsKey model.KmsKeys, internalKms model.InternalKms) (uuid.UUID, error) {+ var kmsKeyResult model.KmsKeys+ err := table.KmsKeys.+ INSERT(table.KmsKeys.Name, table.KmsKeys.OrgId, table.KmsKeys.IsReserved, table.KmsKeys.KeyUsage).+ MODEL(kmsKey).+ RETURNING(table.KmsKeys.AllColumns).+ QueryContext(ctx, tx, &kmsKeyResult)+ if err != nil {+ return uuid.Nil, fmt.Errorf("inserting kms_keys: %w", err)+ }++ // Link internal_kms to the created kms_keys row.+ internalKms.KmsKeyId = kmsKeyResult.ID+ var internalResult model.InternalKms+ err = table.InternalKms.+ INSERT(table.InternalKms.EncryptedKey, table.InternalKms.EncryptionAlgorithm, table.InternalKms.Version, table.InternalKms.KmsKeyId).+ MODEL(internalKms).+ RETURNING(table.InternalKms.AllColumns).+ QueryContext(ctx, tx, &internalResult)+ if err != nil {+ return uuid.Nil, fmt.Errorf("inserting internal_kms: %w", err)+ }++ return kmsKeyResult.ID, nil+}++// --- Organization reads ---++// FindOrgKmsInfo returns the narrow org fields needed for KMS data key operations.+func (d *DAL) FindOrgKmsInfo(ctx context.Context, orgID uuid.UUID) (*OrgKmsInfo, error) {+ return d.findOrgKmsInfo(ctx, d.db.Replica(), orgID)+}++func (d *DAL) findOrgKmsInfo(ctx context.Context, db qrm.DB, orgID uuid.UUID) (*OrgKmsInfo, error) {+ var result OrgKmsInfo++ err := table.Organizations.+ SELECT(+ table.Organizations.ID,+ table.Organizations.KmsDefaultKeyId,+ table.Organizations.KmsEncryptedDataKey,+ ).+ WHERE(table.Organizations.ID.EQ(postgres.UUID(orgID))).+ QueryContext(ctx, db, &result)+ if err != nil {+ return nil, fmt.Errorf("finding org KMS info: %w", err)+ }++ return &result, nil+}++// --- Project KMS key ---++// FindOrCreateProjectKmsKey atomically ensures the project has a secret manager KMS key.+// Acquires an advisory lock, checks for an existing key, and calls createFn only+// when no key exists. createFn should return the encrypted key material.+func (d *DAL) FindOrCreateProjectKmsKey(ctx context.Context, projectID string, createFn func() (encryptedKey []byte, err error)) (uuid.UUID, error) {+ lock, err := d.lockStore.AcquirePgLock(ctx, fmt.Sprintf("kms-project-key:%s", projectID), nil)+ if err != nil {+ return uuid.Nil, fmt.Errorf("acquiring project key lock: %w", err)+ }+ defer lock.Rollback()++ tx := lock.Tx()++ // Re-check after lock — another request may have created it.+ project, err := d.findProjectKmsInfo(ctx, tx, projectID)+ if err != nil {+ return uuid.Nil, fmt.Errorf("finding project: %w", err)+ }+ if project.KmsSecretManagerKeyId.Valid {+ if err := lock.Release(); err != nil {+ return uuid.Nil, err+ }+ return project.KmsSecretManagerKeyId.V, nil+ }++ encryptedKey, err := createFn()+ if err != nil {+ return uuid.Nil, fmt.Errorf("generating KMS key: %w", err)+ }++ createdID, err := d.CreateKmsKeyWithInternal(ctx, tx,+ model.KmsKeys{+ Name: generateRandomKeyName(),+ OrgId: project.OrgId,+ IsReserved: sql.Null[bool]{V: true, Valid: true},+ KeyUsage: "encrypt-decrypt",+ },+ model.InternalKms{+ EncryptedKey: encryptedKey,+ EncryptionAlgorithm: "aes-256-gcm",+ Version: 1,+ },+ )+ if err != nil {+ return uuid.Nil, err+ }++ if _, err := table.Projects.+ UPDATE(table.Projects.KmsSecretManagerKeyId).+ SET(createdID.String()).+ WHERE(table.Projects.ID.EQ(postgres.String(projectID))).+ ExecContext(ctx, tx); err != nil {+ return uuid.Nil, fmt.Errorf("updating project KMS key: %w", err)+ }++ if err := lock.Release(); err != nil {+ return uuid.Nil, err+ }+ return createdID, nil+}++// --- Project data key ---++// FindOrCreateProjectDataKey atomically ensures the project has an encrypted data key.+// Acquires an advisory lock, checks for an existing key, and calls createFn only+// when no key exists. createFn should return the encrypted data key.+// Returns the encrypted data key (existing or newly created).+//+// The caller must ensure the project's KMS key exists before calling this+// to avoid deadlocks with concurrent KMS key + data key creation.+func (d *DAL) FindOrCreateProjectDataKey(ctx context.Context, projectID string, createFn func() (encryptedDataKey []byte, err error)) ([]byte, error) {+ lock, err := d.lockStore.AcquirePgLock(ctx, fmt.Sprintf("kms-project-data-key:%s", projectID), nil)+ if err != nil {+ return nil, fmt.Errorf("acquiring project data key lock: %w", err)+ }+ defer lock.Rollback()++ tx := lock.Tx()++ // Re-check after lock — another request may have created it.+ project, err := d.findProjectKmsInfo(ctx, tx, projectID)+ if err != nil {+ return nil, fmt.Errorf("finding project: %w", err)+ }+ if project.KmsSecretManagerEncryptedDataKey != nil {+ if err := lock.Release(); err != nil {+ return nil, err+ }+ return *project.KmsSecretManagerEncryptedDataKey, nil+ }++ encryptedDataKey, err := createFn()+ if err != nil {+ return nil, fmt.Errorf("generating data key: %w", err)+ }++ if _, err := table.Projects.+ UPDATE(table.Projects.KmsSecretManagerEncryptedDataKey).+ SET(encryptedDataKey).+ WHERE(table.Projects.ID.EQ(postgres.String(projectID))).+ ExecContext(ctx, tx); err != nil {+ return nil, fmt.Errorf("setting project encrypted data key: %w", err)+ }++ if err := lock.Release(); err != nil {+ return nil, err+ }+ return encryptedDataKey, nil+}++// --- Project reads ---++// FindProjectKmsInfo returns the narrow project fields needed for KMS data key operations.+func (d *DAL) FindProjectKmsInfo(ctx context.Context, projectID string) (*ProjectKmsInfo, error) {+ return d.findProjectKmsInfo(ctx, d.db.Replica(), projectID)+}++func (d *DAL) findProjectKmsInfo(ctx context.Context, db qrm.DB, projectID string) (*ProjectKmsInfo, error) {+ var result ProjectKmsInfo++ err := table.Projects.+ SELECT(+ table.Projects.ID,+ table.Projects.OrgId,+ table.Projects.KmsSecretManagerKeyId,+ table.Projects.KmsSecretManagerEncryptedDataKey,+ ).+ WHERE(table.Projects.ID.EQ(postgres.String(projectID))).+ QueryContext(ctx, db, &result)+ if err != nil {+ return nil, fmt.Errorf("finding project KMS info: %w", err)+ }++ return &result, nil+}diff --git a/backend-go/internal/services/shared/kms/kms.go b/backend-go/internal/services/shared/kms/kms.gonew file mode 100644index 0000000000..a494a18b48--- /dev/null+++ b/backend-go/internal/services/shared/kms/kms.go@@ -0,0 +1,362 @@+package kms++import (+ "context"+ "crypto/rand"+ "encoding/base64"+ "fmt"+ "sync"++ "github.com/google/uuid"++ "github.com/infisical/api/internal/config"+ "github.com/infisical/api/internal/crypto/cipher"+ "github.com/infisical/api/internal/database/pg/gen/model"+)++// KmsRootConfigUUID is the fixed UUID for the single kms_root_config row.+var KmsRootConfigUUID = uuid.MustParse("00000000-0000-0000-0000-000000000000")++const (++ // KMSVersion is the version tag appended to all KMS-encrypted blobs.+ KMSVersion = "v01"+ // KMSVersionBlobLength is the byte length of KMSVersion.+ KMSVersionBlobLength = 3++ // PgLockKmsRootKeyInit is the advisory lock ID for root config initialization.+ // Must match the Node.js backend value (PgSqlLock.KmsRootKeyInit = 2025).+ PgLockKmsRootKeyInit int64 = 2025+)++// RootKeyEncryptionStrategy determines how the root key is encrypted at rest.+type RootKeyEncryptionStrategy string++const (+ StrategyHSM RootKeyEncryptionStrategy = "HSM"+ StrategySoftware RootKeyEncryptionStrategy = "SOFTWARE"+)++// DataKeyType selects between org-level and project-level data keys.+type DataKeyType int++const (+ DataKeyOrganization DataKeyType = iota+ DataKeyProject+)++// Encryptor encrypts plaintext and returns the ciphertext blob (with version suffix).+type Encryptor func(plainText []byte) ([]byte, error)++// Decryptor decrypts a versioned ciphertext blob and returns the plaintext.+type Decryptor func(cipherTextBlob []byte) ([]byte, error)++// CipherPair holds matched encrypt/decrypt functions bound to a single data key.+type CipherPair struct {+ Encrypt Encryptor+ Decrypt Decryptor+}++// CreateCipherPairDTO selects which data key to use.+type CreateCipherPairDTO struct {+ Type DataKeyType+ ProjectID string // required when Type == DataKeyProject+ OrgID uuid.UUID // required when Type == DataKeyOrganization+}++// dal defines the subset of DAL operations this service needs.+type dal interface {+ // Root config.+ FindOrCreateRootConfig(ctx context.Context, createFn func() (encryptedRootKey []byte, encryptionStrategy string, err error)) (*model.KmsRootConfig, error)++ // Organization find-or-create with advisory lock.+ FindOrCreateOrgKmsKey(ctx context.Context, orgID uuid.UUID, generateKeyFn func() (encryptedKey []byte, err error)) (uuid.UUID, error)+ FindOrCreateOrgDataKey(ctx context.Context, orgID uuid.UUID, createFn func() (encryptedDataKey []byte, err error)) ([]byte, error)++ // Project find-or-create with advisory lock.+ FindOrCreateProjectKmsKey(ctx context.Context, projectID string, createFn func() (encryptedKey []byte, err error)) (uuid.UUID, error)+ FindOrCreateProjectDataKey(ctx context.Context, projectID string, createFn func() (encryptedDataKey []byte, err error)) ([]byte, error)++ // KMS key reads.+ FindKmsKeyByID(ctx context.Context, kmsKeyID uuid.UUID) (*KmsKeyWithAssociatedKms, error)++ // Organization reads.+ FindOrgKmsInfo(ctx context.Context, orgID uuid.UUID) (*OrgKmsInfo, error)++ // Project reads.+ FindProjectKmsInfo(ctx context.Context, projectID string) (*ProjectKmsInfo, error)+}++// HsmService defines the HSM operations needed by the KMS service.+// Pass nil when HSM is not configured.+type HsmService interface {+ IsActive() bool+ Encrypt(data []byte) ([]byte, error)+ Decrypt(blob []byte) ([]byte, error)+ RandomBytes(n int) ([]byte, error)+}++// SharedService manages the KMS key hierarchy:+//+// ROOT_ENCRYPTION_KEY (in memory)+// → decrypts KMS key material (internal_kms.encrypted_key)+// → decrypts data key (org/project encrypted data key)+// → encrypts/decrypts secrets (via CipherPair)+type SharedService struct {+ mu sync.RWMutex+ rootEncryptionKey []byte // loaded during Start(), protected by mu++ encryptionKey []byte // from env (ENCRYPTION_KEY / ROOT_ENCRYPTION_KEY)+ dal dal // database operations+ hsm HsmService // nil when HSM is not configured+}++// NewSharedService creates a new KMS service.+// encryptionKey is the raw 32-byte key derived from ENCRYPTION_KEY or ROOT_ENCRYPTION_KEY env var.+// hsm may be nil if HSM is not configured.+func NewSharedService(dal dal, hsm HsmService, cfg *config.Config) (*SharedService, error) {++ var encryptionKey []byte+ if cfg.EncryptionKey != "" {+ encryptionKey = []byte(cfg.EncryptionKey)+ } else if cfg.RootEncryptionKey != "" {+ var decErr error+ encryptionKey, decErr = base64.StdEncoding.DecodeString(cfg.RootEncryptionKey)+ if decErr != nil {+ return nil, fmt.Errorf("failed to decode ROOT_ENCRYPTION_KEY from base64: %w", decErr)+ }+ }++ return &SharedService{+ encryptionKey: encryptionKey,+ dal: dal,+ hsm: hsm,+ }, nil+}++// Start bootstraps the KMS root key. It must be called once during server startup+// before any calls to CreateCipherPairWithDataKey.+//+// It atomically finds or creates the root config in the database (using a PG advisory lock),+// then decrypts the root key into memory.+func (s *SharedService) Start(ctx context.Context, hsmConfigured bool) error {+ strategy := StrategySoftware+ if hsmConfigured {+ strategy = StrategyHSM+ }+ s.mu.Lock()+ defer s.mu.Unlock()++ rootConfig, err := s.dal.FindOrCreateRootConfig(ctx, func() (encryptedRootKey []byte, encryptionStrategy string, err error) {+ var newRootKey []byte+ if hsmConfigured && s.hsm != nil {+ var genErr error+ newRootKey, genErr = s.hsm.RandomBytes(32)+ if genErr != nil {+ return nil, "", fmt.Errorf("generating root key with HSM: %w", genErr)+ }+ } else {+ newRootKey = make([]byte, 32)+ if _, genErr := rand.Read(newRootKey); genErr != nil {+ return nil, "", fmt.Errorf("generating root key: %w", genErr)+ }+ }++ encryptedNewKey, encErr := s.encryptRootKey(newRootKey, strategy)+ if encErr != nil {+ return nil, "", fmt.Errorf("encrypting new root key: %w", encErr)+ }++ strategyStr := string(strategy)+ return encryptedNewKey, strategyStr, nil+ })++ if err != nil {+ return fmt.Errorf("KMS: finding/creating root config: %w", err)+ }++ decryptedRootKey, err := s.decryptRootKey(rootConfig)+ if err != nil {+ return fmt.Errorf("KMS: decrypting root key: %w", err)+ }++ s.rootEncryptionKey = decryptedRootKey+ return nil+}++// CreateCipherPairWithDataKey returns an Encryptor/Decryptor pair bound to the+// data key for the given org or project. All blobs include a "v01" version suffix.+func (s *SharedService) CreateCipherPairWithDataKey(ctx context.Context, dto CreateCipherPairDTO) (*CipherPair, error) {+ dataKey, err := s.getDataKey(ctx, dto)+ if err != nil {+ return nil, err+ }++ return &CipherPair{+ Encrypt: func(plainText []byte) ([]byte, error) {+ return encryptWithVersion(plainText, dataKey)+ },+ Decrypt: func(cipherTextBlob []byte) ([]byte, error) {+ return decryptWithVersion(cipherTextBlob, dataKey)+ },+ }, nil+}++// --- internal helpers ---++func (s *SharedService) getRootKey() []byte {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return s.rootEncryptionKey+}++func (s *SharedService) getDataKey(ctx context.Context, dto CreateCipherPairDTO) ([]byte, error) {+ if dto.Type == DataKeyProject && dto.ProjectID == "" {+ return nil, fmt.Errorf("project ID is required for project data key")+ }++ if dto.Type == DataKeyOrganization && dto.OrgID == uuid.Nil {+ return nil, fmt.Errorf("org ID is required for organization data key")+ }++ switch dto.Type {+ case DataKeyProject:+ return s.getProjectDataKey(ctx, dto.ProjectID)+ case DataKeyOrganization:+ return s.getOrgDataKey(ctx, dto.OrgID)+ default:+ return nil, fmt.Errorf("KMS: unknown data key type: %d", dto.Type)+ }+}++// --- KMS key material ---++// generateEncryptedKeyMaterial generates a random 32-byte key and encrypts it+// with the root key (no version suffix). Used as the callback for find-or-create DAL methods.+func (s *SharedService) generateEncryptedKeyMaterial() ([]byte, error) {+ rootKey := s.getRootKey()+ if len(rootKey) == 0 {+ return nil, fmt.Errorf("KMS: root key not loaded")+ }++ keyMaterial := make([]byte, 32)+ if _, err := rand.Read(keyMaterial); err != nil {+ return nil, fmt.Errorf("KMS: generating key material: %w", err)+ }++ encryptedKey, err := cipher.SymmetricEncrypt(keyMaterial, rootKey)+ if err != nil {+ return nil, fmt.Errorf("KMS: encrypting key material: %w", err)+ }++ return encryptedKey, nil+}++// decryptKmsKey loads a KMS key record and decrypts its key material using the root key.+// For internal KMS keys, decrypts locally. External KMS keys are not yet supported.+func (s *SharedService) decryptKmsKey(ctx context.Context, kmsKeyID uuid.UUID) ([]byte, error) {+ kmsKeyDoc, err := s.dal.FindKmsKeyByID(ctx, kmsKeyID)+ if err != nil {+ return nil, fmt.Errorf("KMS: finding KMS key %s: %w", kmsKeyID, err)+ }+ return s.decryptKmsKeyMaterial(kmsKeyDoc)+}++// decryptKmsKeyMaterial decrypts the key material from a KmsKeyWithAssociatedKms record.+// Branches on internal (local AES-GCM) vs external (cloud provider — not yet implemented).+func (s *SharedService) decryptKmsKeyMaterial(kmsKeyDoc *KmsKeyWithAssociatedKms) ([]byte, error) {+ if kmsKeyDoc.ExternalKms != nil {+ panic("external KMS not implemented")+ }++ if kmsKeyDoc.InternalKms == nil {+ return nil, fmt.Errorf("KMS: key %s has no internal or external KMS association", kmsKeyDoc.ID.String())+ }++ rootKey := s.getRootKey()+ if len(rootKey) == 0 {+ return nil, fmt.Errorf("KMS: root encryption key not loaded, call Start first")+ }++ if kmsKeyDoc.InternalKms.EncryptionAlgorithm != "aes-256-gcm" {+ return nil, fmt.Errorf("KMS: unsupported encryption algorithm: %s", kmsKeyDoc.InternalKms.EncryptionAlgorithm)+ }++ // internal_kms.encrypted_key is AES-GCM encrypted with ROOT_KEY (no version suffix).+ return cipher.SymmetricDecrypt(kmsKeyDoc.InternalKms.EncryptedKey, rootKey)+}++// --- Root key encrypt/decrypt ---++func (s *SharedService) encryptRootKey(plainKey []byte, strategy RootKeyEncryptionStrategy) ([]byte, error) {+ switch strategy {+ case StrategyHSM:+ if s.hsm == nil {+ return nil, fmt.Errorf("KMS: HSM service not configured")+ }+ return s.hsm.Encrypt(plainKey)+ case StrategySoftware:+ if len(s.encryptionKey) == 0 {+ return nil, fmt.Errorf("KMS: ENCRYPTION_KEY / ROOT_ENCRYPTION_KEY not set")+ }+ // Root key is encrypted with AES-GCM (no version suffix).+ return cipher.SymmetricEncrypt(plainKey, s.encryptionKey)+ default:+ return nil, fmt.Errorf("KMS: unknown encryption strategy: %s", strategy)+ }+}++func (s *SharedService) decryptRootKey(config *model.KmsRootConfig) ([]byte, error) {+ strategy := StrategySoftware+ if config.EncryptionStrategy.Valid {+ strategy = RootKeyEncryptionStrategy(config.EncryptionStrategy.V)+ }++ switch strategy {+ case StrategyHSM:+ if s.hsm == nil {+ return nil, fmt.Errorf("KMS: HSM service not configured")+ }+ if !s.hsm.IsActive() {+ return nil, fmt.Errorf("KMS: HSM service is not active")+ }+ return s.hsm.Decrypt(config.EncryptedRootKey)+ case StrategySoftware:+ if len(s.encryptionKey) == 0 {+ return nil, fmt.Errorf("KMS: ENCRYPTION_KEY / ROOT_ENCRYPTION_KEY not set")+ }+ // Root key is encrypted with AES-GCM (no version suffix).+ return cipher.SymmetricDecrypt(config.EncryptedRootKey, s.encryptionKey)+ default:+ return nil, fmt.Errorf("KMS: unknown encryption strategy: %s", strategy)+ }+}++// --- Versioned encrypt/decrypt ---++// encryptWithVersion encrypts plaintext with AES-GCM-256 and appends the "v01" version suffix.+func encryptWithVersion(plaintext, key []byte) ([]byte, error) {+ encrypted, err := cipher.SymmetricEncrypt(plaintext, key)+ if err != nil {+ return nil, err+ }+ return append(encrypted, []byte(KMSVersion)...), nil+}++// decryptWithVersion strips the "v01" version suffix and decrypts with AES-GCM-256.+func decryptWithVersion(blob, key []byte) ([]byte, error) {+ if len(blob) < KMSVersionBlobLength {+ return nil, fmt.Errorf("KMS: encrypted blob too short")+ }+ ciphertext := blob[:len(blob)-KMSVersionBlobLength]+ return cipher.SymmetricDecrypt(ciphertext, key)+}++// --- Utilities ---++// generateRandomKeyName generates a random 8-character hex name for a KMS key.+func generateRandomKeyName() string {+ b := make([]byte, 4)+ rand.Read(b)+ return fmt.Sprintf("%x", b)+}diff --git a/backend-go/internal/services/shared/kms/kms_org.go b/backend-go/internal/services/shared/kms/kms_org.gonew file mode 100644index 0000000000..4c3cb05d6e--- /dev/null+++ b/backend-go/internal/services/shared/kms/kms_org.go@@ -0,0 +1,71 @@+package kms++import (+ "context"+ "crypto/rand"+ "fmt"++ "github.com/google/uuid"+)++func (s *SharedService) getOrgDataKey(ctx context.Context, orgID uuid.UUID) ([]byte, error) {+ org, err := s.dal.FindOrgKmsInfo(ctx, orgID)+ if err != nil {+ return nil, fmt.Errorf("KMS: finding org: %w", err)+ }++ // Ensure org has a KMS key (lazy create if missing).+ kmsKeyID := org.KmsDefaultKeyId+ if !kmsKeyID.Valid {+ createdKmsKeyID, kmsErr := s.dal.FindOrCreateOrgKmsKey(ctx, orgID, func() ([]byte, error) {+ return s.generateEncryptedKeyMaterial()+ })+ if kmsErr != nil {+ return nil, fmt.Errorf("KMS: ensuring org KMS key: %w", kmsErr)+ }+ kmsKeyID.V = createdKmsKeyID+ kmsKeyID.Valid = true+ }++ // Ensure org has a data key (lazy create if missing).+ if org.KmsEncryptedDataKey == nil {+ dataKey, dataErr := s.generateOrgDataKey(ctx, orgID, kmsKeyID.V)+ if dataErr != nil {+ return nil, fmt.Errorf("KMS: ensuring org data key: %w", dataErr)+ }+ return dataKey, nil+ }++ // Decrypt existing data key.+ kmsKey, err := s.decryptKmsKey(ctx, kmsKeyID.V)+ if err != nil {+ return nil, err+ }+ return decryptWithVersion(*org.KmsEncryptedDataKey, kmsKey)+}++// generateOrgDataKey creates the org's encrypted data key if it doesn't exist.+// Returns the plaintext data key.+// The caller must ensure the org's KMS key exists before calling this+// to avoid deadlocks with concurrent KMS key + data key creation.+func (s *SharedService) generateOrgDataKey(ctx context.Context, orgID uuid.UUID, kmsKeyID uuid.UUID) ([]byte, error) {+ // Decrypt KMS key once — used both for encrypting (create) and decrypting (existing).+ kmsKey, err := s.decryptKmsKey(ctx, kmsKeyID)+ if err != nil {+ return nil, err+ }++ encryptedDataKey, err := s.dal.FindOrCreateOrgDataKey(ctx, orgID, func() ([]byte, error) {+ plainDataKey := make([]byte, 32)+ if _, err := rand.Read(plainDataKey); err != nil {+ return nil, fmt.Errorf("generating data key: %w", err)+ }+ return encryptWithVersion(plainDataKey, kmsKey)+ })++ if err != nil {+ return nil, err+ }++ return decryptWithVersion(encryptedDataKey, kmsKey)+}diff --git a/backend-go/internal/services/shared/kms/kms_project.go b/backend-go/internal/services/shared/kms/kms_project.gonew file mode 100644index 0000000000..d05e7e1ccf--- /dev/null+++ b/backend-go/internal/services/shared/kms/kms_project.go@@ -0,0 +1,70 @@+package kms++import (+ "context"+ "crypto/rand"+ "fmt"++ "github.com/google/uuid"+)++func (s *SharedService) getProjectDataKey(ctx context.Context, projectID string) ([]byte, error) {+ project, err := s.dal.FindProjectKmsInfo(ctx, projectID)+ if err != nil {+ return nil, fmt.Errorf("KMS: finding project: %w", err)+ }++ // Ensure project has a KMS key (lazy create if missing).+ kmsKeyID := project.KmsSecretManagerKeyId+ if !kmsKeyID.Valid {+ createdKmsKeyID, kmsErr := s.dal.FindOrCreateProjectKmsKey(ctx, projectID, func() ([]byte, error) {+ return s.generateEncryptedKeyMaterial()+ })+ if kmsErr != nil {+ return nil, fmt.Errorf("KMS: ensuring project KMS key: %w", kmsErr)+ }+ kmsKeyID.V = createdKmsKeyID+ kmsKeyID.Valid = true+ }++ // Ensure project has a data key (lazy create if missing).+ if project.KmsSecretManagerEncryptedDataKey == nil {+ dataKey, dataErr := s.generateProjectDataKey(ctx, projectID, kmsKeyID.V)+ if dataErr != nil {+ return nil, fmt.Errorf("KMS: ensuring project data key: %w", dataErr)+ }+ return dataKey, nil+ }++ // Decrypt existing data key.+ kmsKey, err := s.decryptKmsKey(ctx, kmsKeyID.V)+ if err != nil {+ return nil, err+ }+ return decryptWithVersion(*project.KmsSecretManagerEncryptedDataKey, kmsKey)+}++// generateProjectDataKey creates the project's encrypted data key if it doesn't exist.+// Returns the plaintext data key.+// The caller must ensure the project's KMS key exists before calling this+// to avoid deadlocks with concurrent KMS key + data key creation.+func (s *SharedService) generateProjectDataKey(ctx context.Context, projectID string, kmsKeyID uuid.UUID) ([]byte, error) {+ // Decrypt KMS key once — used both for encrypting (create) and decrypting (existing).+ kmsKey, err := s.decryptKmsKey(ctx, kmsKeyID)+ if err != nil {+ return nil, err+ }++ encryptedDataKey, err := s.dal.FindOrCreateProjectDataKey(ctx, projectID, func() ([]byte, error) {+ plainDataKey := make([]byte, 32)+ if _, err := rand.Read(plainDataKey); err != nil {+ return nil, fmt.Errorf("generating data key: %w", err)+ }+ return encryptWithVersion(plainDataKey, kmsKey)+ })+ if err != nil {+ return nil, err+ }++ return decryptWithVersion(encryptedDataKey, kmsKey)+}diff --git a/backend-go/internal/services/shared/kms/kms_test.go b/backend-go/internal/services/shared/kms/kms_test.gonew file mode 100644index 0000000000..e006dbc241--- /dev/null+++ b/backend-go/internal/services/shared/kms/kms_test.go@@ -0,0 +1,393 @@+package kms_test++import (+ "context"+ "database/sql"+ "log"+ "os"+ "sync"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/jackc/pgx/v5/stdlib"+ "github.com/redis/go-redis/v9"+ "github.com/stretchr/testify/require"++ "github.com/infisical/api/internal/config"+ "github.com/infisical/api/internal/keystore"+ "github.com/infisical/api/internal/services/shared/kms"+ "github.com/infisical/api/internal/testutil"+)++var orgID uuid.UUID++var (+ infra *testutil.TestInfra+ cfg *config.Config+)++// testDB satisfies pg.DB using a single pool for both primary and replica.+type testDB struct {+ pool *pgxpool.Pool+ sqlDB *sql.DB+}++func (d *testDB) Primary() *sql.DB { return d.sqlDB }+func (d *testDB) Replica() *sql.DB { return d.sqlDB }+func (d *testDB) ReplicaCount() int { return 0 }+func (d *testDB) PrimaryPool() *pgxpool.Pool { return d.pool }+func (d *testDB) Close() { d.sqlDB.Close() }++func TestMain(m *testing.M) {+ infra = testutil.SetupInfra()++ // Set env vars matching docker-compose.test.yml so config.LoadConfig() works.+ os.Setenv("DB_CONNECTION_URI", infra.DBURI)+ os.Setenv("REDIS_URL", infra.RedisURL)+ os.Setenv("AUTH_SECRET", testutil.AuthSecret)+ os.Setenv("ENCRYPTION_KEY", testutil.EncryptionKey)+ os.Setenv("NODE_ENV", testutil.NodeEnv)++ var err error+ cfg, err = config.LoadConfig()+ if err != nil {+ log.Fatalf("kms_test: loading config: %v", err)+ }++ orgID, err = uuid.Parse(infra.OrgID)+ if err != nil {+ log.Fatalf("kms_test: parsing org ID: %v", err)+ }++ code := m.Run()+ infra.Teardown()+ os.Exit(code)+}++// setupService creates a KMS service wired to real PostgreSQL + Redis.+func setupService(t *testing.T) *kms.SharedService {+ t.Helper()++ sqlDB := stdlib.OpenDBFromPool(infra.DB)+ t.Cleanup(func() { sqlDB.Close() })++ db := &testDB{pool: infra.DB, sqlDB: sqlDB}++ opts, err := redis.ParseURL(infra.RedisURL)+ require.NoError(t, err)+ redisClient := redis.NewClient(opts)+ t.Cleanup(func() { redisClient.Close() })++ ks := keystore.NewKeyStore(redisClient, sqlDB)+ dal := kms.NewDAL(db, ks)++ svc, err := kms.NewSharedService(dal, nil, cfg)+ require.NoError(t, err)+ return svc+}++// startedService returns a service with Start() already called.+func startedService(t *testing.T) *kms.SharedService {+ t.Helper()+ svc := setupService(t)+ require.NoError(t, svc.Start(context.Background(), false))+ return svc+}++// ==========================================================================+// Start+// ==========================================================================++func TestStart(t *testing.T) {+ svc := setupService(t)+ err := svc.Start(context.Background(), false)+ require.NoError(t, err)+}++func TestStart_Idempotent(t *testing.T) {+ svc := setupService(t)+ ctx := context.Background()++ require.NoError(t, svc.Start(ctx, false))+ require.NoError(t, svc.Start(ctx, false))+}++func TestStart_Concurrent(t *testing.T) {+ ctx := context.Background()+ const n = 10++ // Set up services before spawning goroutines (require.NoError isn't goroutine-safe).+ services := make([]*kms.SharedService, n)+ for i := 0; i < n; i++ {+ services[i] = setupService(t)+ }++ errs := make([]error, n)+ var wg sync.WaitGroup+ wg.Add(n)++ for i := 0; i < n; i++ {+ go func(idx int) {+ defer wg.Done()+ errs[idx] = services[idx].Start(ctx, false)+ }(i)+ }++ wg.Wait()+ for i, err := range errs {+ require.NoError(t, err, "goroutine %d", i)+ }+}++// ==========================================================================+// Organization cipher pair+// ==========================================================================++func TestOrgCipherPair_EncryptDecryptRoundTrip(t *testing.T) {+ svc := startedService(t)+ ctx := context.Background()++ pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{+ Type: kms.DataKeyOrganization,+ OrgID: orgID,+ })+ require.NoError(t, err)+ require.NotNil(t, pair)++ plaintext := []byte("hello secret world")+ ciphertext, err := pair.Encrypt(plaintext)+ require.NoError(t, err)+ require.NotEqual(t, plaintext, ciphertext)++ decrypted, err := pair.Decrypt(ciphertext)+ require.NoError(t, err)+ require.Equal(t, plaintext, decrypted)+}++func TestOrgCipherPair_Idempotent(t *testing.T) {+ svc := startedService(t)+ ctx := context.Background()++ dto := kms.CreateCipherPairDTO{+ Type: kms.DataKeyOrganization,+ OrgID: orgID,+ }++ pair1, err := svc.CreateCipherPairWithDataKey(ctx, dto)+ require.NoError(t, err)++ pair2, err := svc.CreateCipherPairWithDataKey(ctx, dto)+ require.NoError(t, err)++ // Encrypt with pair1, decrypt with pair2 — both bound to the same data key.+ plaintext := []byte("cross-pair test")+ ciphertext, err := pair1.Encrypt(plaintext)+ require.NoError(t, err)++ decrypted, err := pair2.Decrypt(ciphertext)+ require.NoError(t, err)+ require.Equal(t, plaintext, decrypted)+}++func TestOrgCipherPair_Concurrent(t *testing.T) {+ svc := startedService(t)+ ctx := context.Background()++ const n = 10+ plaintext := []byte("concurrent org test")+ ciphertexts := make([][]byte, n)+ errs := make([]error, n)++ var wg sync.WaitGroup+ wg.Add(n)++ for i := 0; i < n; i++ {+ go func(idx int) {+ defer wg.Done()+ pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{+ Type: kms.DataKeyOrganization,+ OrgID: orgID,+ })+ if err != nil {+ errs[idx] = err+ return+ }+ ciphertexts[idx], errs[idx] = pair.Encrypt(plaintext)+ }(i)+ }++ wg.Wait()+ for i, err := range errs {+ require.NoError(t, err, "goroutine %d", i)+ }++ // All ciphertexts should decrypt to the same plaintext.+ pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{+ Type: kms.DataKeyOrganization,+ OrgID: orgID,+ })+ require.NoError(t, err)++ for i, ct := range ciphertexts {+ decrypted, err := pair.Decrypt(ct)+ require.NoError(t, err, "decrypting goroutine %d ciphertext", i)+ require.Equal(t, plaintext, decrypted, "goroutine %d", i)+ }+}++// ==========================================================================+// Project cipher pair+// ==========================================================================++func TestProjectCipherPair_CreatesFromScratch(t *testing.T) {+ svc := startedService(t)+ ctx := context.Background()++ proj := infra.CreateProject(t, "kms-scratch")++ pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{+ Type: kms.DataKeyProject,+ ProjectID: proj.ID,+ })+ require.NoError(t, err)+ require.NotNil(t, pair)++ plaintext := []byte("project secret data")+ ciphertext, err := pair.Encrypt(plaintext)+ require.NoError(t, err)++ decrypted, err := pair.Decrypt(ciphertext)+ require.NoError(t, err)+ require.Equal(t, plaintext, decrypted)+}++func TestProjectCipherPair_Idempotent(t *testing.T) {+ svc := startedService(t)+ ctx := context.Background()++ proj := infra.CreateProject(t, "kms-idempotent")++ dto := kms.CreateCipherPairDTO{+ Type: kms.DataKeyProject,+ ProjectID: proj.ID,+ }++ pair1, err := svc.CreateCipherPairWithDataKey(ctx, dto)+ require.NoError(t, err)++ pair2, err := svc.CreateCipherPairWithDataKey(ctx, dto)+ require.NoError(t, err)++ // Cross-decrypt: encrypt with first, decrypt with second.+ plaintext := []byte("idempotent project test")+ ciphertext, err := pair1.Encrypt(plaintext)+ require.NoError(t, err)++ decrypted, err := pair2.Decrypt(ciphertext)+ require.NoError(t, err)+ require.Equal(t, plaintext, decrypted)+}++func TestProjectCipherPair_Concurrent(t *testing.T) {+ svc := startedService(t)+ ctx := context.Background()++ // All goroutines race on the same fresh project.+ proj := infra.CreateProject(t, "kms-concurrent")++ const n = 10+ plaintext := []byte("concurrent project test")+ ciphertexts := make([][]byte, n)+ errs := make([]error, n)++ var wg sync.WaitGroup+ wg.Add(n)++ for i := 0; i < n; i++ {+ go func(idx int) {+ defer wg.Done()+ pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{+ Type: kms.DataKeyProject,+ ProjectID: proj.ID,+ })+ if err != nil {+ errs[idx] = err+ return+ }+ ciphertexts[idx], errs[idx] = pair.Encrypt(plaintext)+ }(i)+ }++ wg.Wait()+ for i, err := range errs {+ require.NoError(t, err, "goroutine %d", i)+ }++ // All should decrypt to same plaintext.+ pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{+ Type: kms.DataKeyProject,+ ProjectID: proj.ID,+ })+ require.NoError(t, err)++ for i, ct := range ciphertexts {+ decrypted, err := pair.Decrypt(ct)+ require.NoError(t, err, "decrypting goroutine %d ciphertext", i)+ require.Equal(t, plaintext, decrypted, "goroutine %d", i)+ }+}++// TestProjectCipherPair_IsolatedPerProject verifies that different projects+// get different data keys — ciphertexts are not cross-decryptable.+func TestProjectCipherPair_IsolatedPerProject(t *testing.T) {+ svc := startedService(t)+ ctx := context.Background()++ proj1 := infra.CreateProject(t, "kms-iso-1")+ proj2 := infra.CreateProject(t, "kms-iso-2")++ pair1, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{+ Type: kms.DataKeyProject,+ ProjectID: proj1.ID,+ })+ require.NoError(t, err)++ pair2, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{+ Type: kms.DataKeyProject,+ ProjectID: proj2.ID,+ })+ require.NoError(t, err)++ plaintext := []byte("isolation test")+ ciphertext, err := pair1.Encrypt(plaintext)+ require.NoError(t, err)++ // Decrypting project1's ciphertext with project2's key should fail.+ _, err = pair2.Decrypt(ciphertext)+ require.Error(t, err)+}++// ==========================================================================+// Error paths+// ==========================================================================++func TestCipherPair_MissingProjectID(t *testing.T) {+ svc := startedService(t)++ _, err := svc.CreateCipherPairWithDataKey(context.Background(), kms.CreateCipherPairDTO{+ Type: kms.DataKeyProject,+ })+ require.Error(t, err)+ require.Contains(t, err.Error(), "project ID is required")+}++func TestCipherPair_MissingOrgID(t *testing.T) {+ svc := startedService(t)++ _, err := svc.CreateCipherPairWithDataKey(context.Background(), kms.CreateCipherPairDTO{+ Type: kms.DataKeyOrganization,+ })+ require.Error(t, err)+ require.Contains(t, err.Error(), "org ID is required")+}diff --git a/backend-go/internal/services/shared/libs.go b/backend-go/internal/services/shared/libs.goindex 26a04aa433..f27cfdf2f9 100644--- a/backend-go/internal/services/shared/libs.go+++ b/backend-go/internal/services/shared/libs.go@@ -1,17 +1,41 @@package sharedimport (+ "fmt"++ "github.com/infisical/api/internal/config"+ "github.com/infisical/api/internal/database/pg"+ "github.com/infisical/api/internal/keystore"+ "github.com/infisical/api/internal/services/shared/kms""github.com/infisical/api/internal/services/shared/permission")+// SharedServicesDeps holds the external dependencies needed to construct shared services.+type SharedServicesDeps struct {+ Config *config.Config+ DB pg.DB // primary DB connection (writes)+ HSM kms.HsmService // nil when HSM is not configured+ KeyStore keystore.KeyStore // Redis-backed keystore for PG advisory locks+}+type SharedServices struct {+ Config *config.ConfigPermission *permission.SharedService+ KMS *kms.SharedService}-func NewSharedServices() *SharedServices {+func NewSharedServices(deps SharedServicesDeps) (*SharedServices, error) {permissionDAL := permission.NewDAL()+ kmsDAL := kms.NewDAL(deps.DB, deps.KeyStore)++ kmsSvc, err := kms.NewSharedService(kmsDAL, deps.HSM, deps.Config)+ if err != nil {+ return nil, fmt.Errorf("kms: %w", err)+ }return &SharedServices{+ Config: deps.Config,Permission: permission.NewSharedService(permissionDAL),- }+ KMS: kmsSvc,+ }, nil}diff --git a/backend-go/internal/services/shared/serverconfig/dal.go b/backend-go/internal/services/shared/serverconfig/dal.goindex df91187ff4..2abe5ffba3 100644--- a/backend-go/internal/services/shared/serverconfig/dal.go+++ b/backend-go/internal/services/shared/serverconfig/dal.go@@ -49,7 +49,7 @@ func (d *DAL) FindOrCreateConfig(ctx context.Context) (*model.SuperAdmin, error)// Check if config already exists.txDAL := d.WithTx(tx)- cfg, err := txDAL.FindByID(ctx, AdminConfigDBUUID)+ cfg, err := txDAL.FindByID(ctx, adminConfigDBUUID)if err == nil {tx.Commit()return cfg, nil@@ -63,7 +63,7 @@ func (d *DAL) FindOrCreateConfig(ctx context.Context) (*model.SuperAdmin, error)var result model.SuperAdminerr = table.SuperAdmin.INSERT(table.SuperAdmin.ID, table.SuperAdmin.Initialized, table.SuperAdmin.AllowSignUp, table.SuperAdmin.FipsEnabled).- VALUES(postgres.String(AdminConfigDBUUID), postgres.Bool(false), postgres.Bool(true), postgres.Bool(false)).+ VALUES(postgres.UUID(adminConfigDBUUID), postgres.Bool(false), postgres.Bool(true), postgres.Bool(false)).RETURNING(table.SuperAdmin.AllColumns).QueryContext(ctx, tx, &result)if err != nil {diff --git a/backend-go/internal/services/shared/serverconfig/serverconfig.go b/backend-go/internal/services/shared/serverconfig/serverconfig.goindex b28cafb12c..492abcaa33 100644--- a/backend-go/internal/services/shared/serverconfig/serverconfig.go+++ b/backend-go/internal/services/shared/serverconfig/serverconfig.go@@ -12,9 +12,10 @@ import ("github.com/infisical/api/internal/database/pg/gen/model")+var adminConfigDBUUID = uuid.MustParse("00000000-0000-0000-0000-000000000000")+const (// AdminConfigDBUUID is the fixed UUID for the single super_admin config row.- AdminConfigDBUUID = "00000000-0000-0000-0000-000000000000"// PgLockSuperAdminInit is the advisory lock ID used during config initialization.PgLockSuperAdminInit int64 = 2024@@ -52,35 +53,35 @@ func configFromModel(m *model.SuperAdmin) ServerConfig {FipsEnabled: m.FipsEnabled,}- if m.Initialized != nil {- cfg.Initialized = *m.Initialized+ if m.Initialized.Valid {+ cfg.Initialized = m.Initialized.V}- if m.AllowSignUp != nil {- cfg.AllowSignUp = *m.AllowSignUp+ if m.AllowSignUp.Valid {+ cfg.AllowSignUp = m.AllowSignUp.V}- if m.AllowedSignUpDomain != nil {- cfg.AllowedSignUpDomain = *m.AllowedSignUpDomain+ if m.AllowedSignUpDomain.Valid {+ cfg.AllowedSignUpDomain = m.AllowedSignUpDomain.V}- if m.TrustSamlEmails != nil {- cfg.TrustSamlEmails = *m.TrustSamlEmails+ if m.TrustSamlEmails.Valid {+ cfg.TrustSamlEmails = m.TrustSamlEmails.V}- if m.TrustLdapEmails != nil {- cfg.TrustLdapEmails = *m.TrustLdapEmails+ if m.TrustLdapEmails.Valid {+ cfg.TrustLdapEmails = m.TrustLdapEmails.V}- if m.TrustOidcEmails != nil {- cfg.TrustOidcEmails = *m.TrustOidcEmails+ if m.TrustOidcEmails.Valid {+ cfg.TrustOidcEmails = m.TrustOidcEmails.V}- if m.DefaultAuthOrgId != nil {- cfg.DefaultAuthOrgID = m.DefaultAuthOrgId+ if m.DefaultAuthOrgId.Valid {+ cfg.DefaultAuthOrgID = &m.DefaultAuthOrgId.V}if m.EnabledLoginMethods != nil {cfg.EnabledLoginMethods = []string(*m.EnabledLoginMethods)}- if m.AuthConsentContent != nil {- cfg.AuthConsentContent = *m.AuthConsentContent+ if m.AuthConsentContent.Valid {+ cfg.AuthConsentContent = m.AuthConsentContent.V}- if m.PageFrameContent != nil {- cfg.PageFrameContent = *m.PageFrameContent+ if m.PageFrameContent.Valid {+ cfg.PageFrameContent = m.PageFrameContent.V}if m.AdminIdentityIds != nil {cfg.AdminIdentityIDs = []string(*m.AdminIdentityIds)@@ -98,7 +99,7 @@ type keyStore interface {// dal defines the subset of DAL operations this service needs.type dal interface {- FindByID(ctx context.Context, id string) (*model.SuperAdmin, error)+ 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)}@@ -147,7 +148,7 @@ func (s *SharedService) GetConfig(ctx context.Context) (ServerConfig, error) {}// Cache miss — read from DB.- m, err := s.dal.FindByID(ctx, AdminConfigDBUUID)+ m, err := s.dal.FindByID(ctx, adminConfigDBUUID)if err != nil {return ServerConfig{}, fmt.Errorf("reading config from database: %w", err)}diff --git a/backend-go/internal/testutil/constants.go b/backend-go/internal/testutil/constants.gonew file mode 100644index 0000000000..01a1b82e86--- /dev/null+++ b/backend-go/internal/testutil/constants.go@@ -0,0 +1,8 @@+package testutil++// Test constants matching docker-compose.test.yml environment.+const (+ AuthSecret = "test-auth-secret-long-enough-for-jwt"+ EncryptionKey = "a984ecdf82ec779e55dbcc21303a900f"+ NodeEnv = "test"+)diff --git a/backend-go/internal/testutil/seed.go b/backend-go/internal/testutil/seed.goindex 3a9e2e29a1..f79c3dc8a0 100644--- a/backend-go/internal/testutil/seed.go+++ b/backend-go/internal/testutil/seed.go@@ -1,6 +1,7 @@package testutilimport (+ "crypto/rand""fmt""log""testing"@@ -94,7 +95,12 @@ func (infra *TestInfra) MustCreateProject(name string) *ProjectSeed {func (infra *TestInfra) CreateProject(t *testing.T, name string) *ProjectSeed {t.Helper()- slug := fmt.Sprintf("test-%s-%s", name, t.Name())+ b := make([]byte, 4)+ rand.Read(b)+ slug := fmt.Sprintf("t-%s-%x", name, b)+ if len(slug) > 36 {+ slug = slug[:36]+ }var projectResp map[string]anyresp, err := infra.client.R().@@ -114,8 +120,8 @@ func (infra *TestInfra) CreateProject(t *testing.T, name string) *ProjectSeed {}return &ProjectSeed{- ID: jsonStr(projectResp, "id"),- Slug: jsonStr(projectResp, "slug"),+ ID: jsonStr(projectResp, "project.id"),+ Slug: jsonStr(projectResp, "project.slug"),EnvSlug: "dev",}}