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: made acquire lock as a seperate package and simplified db one
=5b3e1e619664
diff --git a/backend-go/cmd/infisical/main.go b/backend-go/cmd/infisical/main.goindex 1087ecba63..5aac9f5b46 100644--- a/backend-go/cmd/infisical/main.go+++ b/backend-go/cmd/infisical/main.go@@ -59,7 +59,7 @@ func run(cfg *config.Config, logger *slog.Logger) error {logger.ErrorContext(ctx, "failed to initialize database", slog.Any("error", err))return err}- defer errutil.DeferErr(ctx, db.Close, "closing database")+ defer db.Close()dbReport := bootstrap.CheckDBConnection(ctx, db)dbReport.PrintReport(logger)@@ -73,7 +73,7 @@ func run(cfg *config.Config, logger *slog.Logger) error {defer errutil.DeferErr(ctx, redisClient.Close, "closing redis")// Initialize KeyStore and Queue.- ks := keystore.NewKeyStore(redisClient, db.Primary())+ ks := keystore.NewKeyStore(redisClient)queueSvc := queue.NewService(logger, redisClient)defer errutil.DeferErr(ctx, queueSvc.Close, "closing queue")diff --git a/backend-go/internal/database/pg/pg.go b/backend-go/internal/database/pg/pg.goindex 2f456a7370..102de216e7 100644--- a/backend-go/internal/database/pg/pg.go+++ b/backend-go/internal/database/pg/pg.go@@ -4,7 +4,6 @@ import ("context""crypto/tls""crypto/x509"- "database/sql""encoding/base64""fmt""math/rand/v2"@@ -12,35 +11,21 @@ import ("strings""github.com/jackc/pgx/v5/pgxpool"- "github.com/jackc/pgx/v5/stdlib""github.com/infisical/api/internal/config")-// 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+ Primary() *pgxpool.Pool+ Replica() *pgxpool.PoolReplicaCount() int- PrimaryPool() *pgxpool.Pool- Close() error+ 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.+// pgDatabase wraps a primary pgxpool and zero or more read-replica pools.type pgDatabase struct {- primary *pgxpool.Pool- replicas []*pgxpool.Pool- primarySQL *sql.DB- replicaSQL []*sql.DB+ primary *pgxpool.Pool+ replicas []*pgxpool.Pool}// NewPostgresDB creates a connection pool for the primary database and optional read replicas.@@ -53,7 +38,6 @@ func NewPostgresDB(ctx context.Context, primaryURI, primaryRootCert string, readreplicaPools := make([]*pgxpool.Pool, 0, len(readReplicas))for i, r := range readReplicas {- // Fall back to primary root cert if replica doesn't have its own.rootCert := r.DBRootCertif rootCert == "" {rootCert = primaryRootCert@@ -61,7 +45,6 @@ func NewPostgresDB(ctx context.Context, primaryURI, primaryRootCert string, readpool, err := openPool(ctx, r.DBConnectionURI, rootCert)if err != nil {- // Close already-opened pools on failure.primaryPool.Close()for _, p := range replicaPools {p.Close()@@ -71,33 +54,23 @@ func NewPostgresDB(ctx context.Context, primaryURI, primaryRootCert string, readreplicaPools = append(replicaPools, pool)}- // Wrap pgxpool.Pool as *sql.DB for go-jet / database/sql compatibility.- primarySQLDB := stdlib.OpenDBFromPool(primaryPool)- replicaSQLDBs := make([]*sql.DB, len(replicaPools))- for i, p := range replicaPools {- replicaSQLDBs[i] = stdlib.OpenDBFromPool(p)- }-return &pgDatabase{- primary: primaryPool,- replicas: replicaPools,- primarySQL: primarySQLDB,- replicaSQL: replicaSQLDBs,+ primary: primaryPool,+ replicas: replicaPools,}, nil}-// Primary returns the primary database as *sql.DB.-func (db *pgDatabase) Primary() *sql.DB {- return db.primarySQL+// Primary returns the primary database pool for writes.+func (db *pgDatabase) Primary() *pgxpool.Pool {+ return db.primary}-// 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 *pgDatabase) Replica() *sql.DB {- if len(db.replicaSQL) == 0 {- return db.primarySQL+// Replica returns a random read-replica pool, or the primary if no replicas are configured.+func (db *pgDatabase) Replica() *pgxpool.Pool {+ if len(db.replicas) == 0 {+ return db.primary}- return db.replicaSQL[rand.IntN(len(db.replicaSQL))]+ return db.replicas[rand.IntN(len(db.replicas))]}// ReplicaCount returns the number of read replicas configured.@@ -105,24 +78,12 @@ func (db *pgDatabase) ReplicaCount() int {return len(db.replicas)}-// PrimaryPool returns the underlying primary pgxpool.Pool for operations that need it directly.-func (db *pgDatabase) PrimaryPool() *pgxpool.Pool {- return db.primary-}--// Close closes all connection pools (primary + replicas) and their sql.DB wrappers.-func (db *pgDatabase) Close() error {- firstErr := db.primarySQL.Close()- for _, s := range db.replicaSQL {- if err := s.Close(); err != nil && firstErr == nil {- firstErr = err- }- }+// Close closes all connection pools (primary + replicas).+func (db *pgDatabase) Close() {db.primary.Close()for _, r := range db.replicas {r.Close()}- return firstErr}// openPool creates a pgxpool.Pool from a connection URI and optional base64-encoded root CA cert.@@ -170,7 +131,6 @@ func parseSslConfig(connURI, dbRootCert string) (string, *tls.Config, error) {return connURI, nil, nil}- // Decode the base64-encoded CA certificate.caPEM, err := base64.StdEncoding.DecodeString(dbRootCert)if err != nil {return "", nil, fmt.Errorf("decoding DB_ROOT_CERT base64: %w", err)@@ -181,8 +141,6 @@ func parseSslConfig(connURI, dbRootCert string) (string, *tls.Config, error) {return "", nil, fmt.Errorf("failed to parse DB root certificate PEM")}- // Default: trust the CA but don't strictly verify server identity- // (matches Node.js rejectUnauthorized: false with a CA present).tlsCfg := &tls.Config{RootCAs: certPool,InsecureSkipVerify: true,@@ -190,18 +148,15 @@ func parseSslConfig(connURI, dbRootCert string) (string, *tls.Config, error) {modifiedURI := connURI- // Check sslmode in the URI.parsed, err := url.Parse(connURI)if err == nil {sslMode := parsed.Query().Get("sslmode")if sslMode != "" && !strings.EqualFold(sslMode, "disable") {- // Strip sslmode — we handle TLS ourselves via pgx TLSConfig.q := parsed.Query()q.Del("sslmode")parsed.RawQuery = q.Encode()modifiedURI = parsed.String()- // verify-ca and verify-full → reject unauthorized (InsecureSkipVerify = false).if strings.EqualFold(sslMode, "verify-ca") || strings.EqualFold(sslMode, "verify-full") {tlsCfg.InsecureSkipVerify = false}diff --git a/backend-go/internal/database/pg/pglock/lock.go b/backend-go/internal/database/pg/pglock/lock.gonew file mode 100644index 0000000000..2ea90fb13d--- /dev/null+++ b/backend-go/internal/database/pg/pglock/lock.go@@ -0,0 +1,47 @@+package pglock++import (+ "context"+ "crypto/sha256"+ "encoding/binary"+ "fmt"++ "github.com/jackc/pgx/v5"+)++// Lock represents an acquired PostgreSQL advisory lock tied to a transaction.+// The lock is automatically released when the transaction commits or rolls back.+type Lock struct {+ tx pgx.Tx+}++// Tx returns the underlying transaction.+func (l *Lock) Tx() pgx.Tx {+ return l.tx+}++// Release commits the transaction and releases the advisory lock.+func (l *Lock) Release(ctx context.Context) error {+ return l.tx.Commit(ctx)+}++// Rollback rolls back the transaction and releases the advisory lock.+func (l *Lock) Rollback(ctx context.Context) error {+ return l.tx.Rollback(ctx)+}++// AcquireBlockingLock acquires a PostgreSQL transaction-level advisory lock (pg_advisory_xact_lock).+// This is a blocking call - it waits until the lock is available.+// The lock is automatically released when the transaction commits or rolls back.+func AcquireBlockingLock(ctx context.Context, tx pgx.Tx, lockID string) (*Lock, error) {+ numericLockID := stringToLockID(lockID)+ if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock($1)", numericLockID); err != nil {+ return nil, fmt.Errorf("acquiring advisory lock %d: %w", numericLockID, err)+ }+ return &Lock{tx: tx}, nil+}++func stringToLockID(s string) int64 {+ hash := sha256.Sum256([]byte(s))+ return int64(binary.BigEndian.Uint64(hash[:8]))+}diff --git a/backend-go/internal/keystore/keystore.go b/backend-go/internal/keystore/keystore.goindex df1f71cfbe..c083f1e3b9 100644--- a/backend-go/internal/keystore/keystore.go+++ b/backend-go/internal/keystore/keystore.go@@ -2,63 +2,13 @@ package keystoreimport ("context"- "database/sql""errors"- "fmt""time""github.com/redis/go-redis/v9")-// 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() error- Rollback() error-}--// TxStarter can begin new database transactions. *sql.DB satisfies this interface.-type TxStarter interface {- BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)-}--// Lock represents an acquired PostgreSQL advisory lock tied to a transaction.-type Lock struct {- tx Tx- ownedTx bool // true if we created the tx; false if caller provided it-}--// Tx returns the underlying transaction so it can be used with DAL operations.-func (l *Lock) Tx() Tx {- return l.tx-}--// Release commits the transaction and frees the advisory lock.-// If the transaction was provided by the caller, Release is a no-op —-// the caller is responsible for committing/rolling back their own transaction.-func (l *Lock) Release() error {- if !l.ownedTx {- return nil- }- return l.tx.Commit()-}--// Rollback rolls back the transaction and frees the advisory lock.-// If the transaction was provided by the caller, Rollback is a no-op.-func (l *Lock) Rollback() error {- if !l.ownedTx {- return nil- }- return l.tx.Rollback()-}--// KeyStore provides key-value operations backed by Redis and-// PostgreSQL advisory locks.+// KeyStore provides key-value operations backed by Redis.type KeyStore interface {SetItem(ctx context.Context, key string, value string) errorGetItem(ctx context.Context, key string) (string, error)@@ -72,21 +22,14 @@ type KeyStore interface {// StreamAdd adds an entry to a Redis stream (XADD).// Pass "*" as id to auto-generate the entry ID.StreamAdd(ctx context.Context, stream string, id string, values map[string]string) (string, error)-- // AcquirePgLock acquires a PostgreSQL transaction-level advisory lock (pg_advisory_xact_lock).- // If tx is nil, a new transaction is created and owned by the Lock (Release commits it).- // If tx is provided, the lock is acquired within that transaction and Release is a no-op —- // the caller manages the transaction lifecycle.- AcquirePgLock(ctx context.Context, lockID string, tx Tx) (*Lock, error)}type redisKeyStore struct {client redis.UniversalClient- db TxStarter}-func NewKeyStore(client redis.UniversalClient, db TxStarter) KeyStore {- return &redisKeyStore{client: client, db: db}+func NewKeyStore(client redis.UniversalClient) KeyStore {+ return &redisKeyStore{client: client}}func (k *redisKeyStore) SetItem(ctx context.Context, key, value string) error {@@ -135,28 +78,3 @@ func (k *redisKeyStore) StreamAdd(ctx context.Context, stream, id string, valuesValues: values,}).Result()}--func (k *redisKeyStore) AcquirePgLock(ctx context.Context, stringLockId string, tx Tx) (*Lock, error) {- ownedTx := false-- lockID := stringToLockID(stringLockId)- if tx == nil {- sqlTx, err := k.db.BeginTx(ctx, nil)- if err != nil {- return nil, fmt.Errorf("beginning transaction for advisory lock: %w", err)- }- tx = sqlTx- ownedTx = true- }-- if _, err := tx.ExecContext(ctx, "SELECT pg_advisory_xact_lock($1)", lockID); err != nil {- if ownedTx {- if err := tx.Rollback(); err != nil {- return nil, fmt.Errorf("acquiring advisory lock %d: %w", lockID, err)- }- }- return nil, fmt.Errorf("acquiring advisory lock %d: %w", lockID, err)- }-- return &Lock{tx: tx, ownedTx: ownedTx}, nil-}diff --git a/backend-go/internal/keystore/lock.go b/backend-go/internal/keystore/lock.godeleted file mode 100644index a4ffa1fa05..0000000000--- a/backend-go/internal/keystore/lock.go+++ /dev/null@@ -1,12 +0,0 @@-package keystore--import (- "crypto/sha256"- "encoding/binary"-)--func stringToLockID(s string) int64 {- hash := sha256.Sum256([]byte(s))- // Take the first 8 bytes and interpret as int64- return int64(binary.BigEndian.Uint64(hash[:8]))-}diff --git a/backend-go/internal/libs/bootstrap/bootstrap.go b/backend-go/internal/libs/bootstrap/bootstrap.goindex 117baf4bdb..9748398817 100644--- a/backend-go/internal/libs/bootstrap/bootstrap.go+++ b/backend-go/internal/libs/bootstrap/bootstrap.go@@ -43,7 +43,7 @@ func (r *DBReport) PrintReport(logger *slog.Logger) {func CheckDBConnection(ctx context.Context, db pg.DB) *DBReport {report := &DBReport{}- if err := db.Primary().PingContext(ctx); err != nil {+ if err := db.Primary().Ping(ctx); err != nil {report.Primary = ConnectionStatus{Name: "primary", Ok: false, Err: fmt.Errorf("primary database: %w", err)}} else {report.Primary = ConnectionStatus{Name: "primary", Ok: true}@@ -52,7 +52,7 @@ func CheckDBConnection(ctx context.Context, db pg.DB) *DBReport {for i := range db.ReplicaCount() {name := fmt.Sprintf("read-replica-%d", i)// Ping via a random replica — if any fail the report captures it.- if err := db.Replica().PingContext(ctx); err != nil {+ if err := db.Replica().Ping(ctx); err != nil {report.Replicas = append(report.Replicas, ConnectionStatus{Name: name, Ok: false, Err: fmt.Errorf("%s: %w", name, err)})} else {report.Replicas = append(report.Replicas, ConnectionStatus{Name: name, Ok: true})