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: implemented keystore, lock and serverconfig. service
=2631824afc4c
diff --git a/CLAUDE.md b/CLAUDE.mdindex a630ffef25..4380590c02 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -7,6 +7,9 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co- `make reviewable-api` / `make reviewable-ui` — lint:fix + type:check (run before PRs)- `cd backend && npm run migration:new` — create new DB migration- `cd backend && npm run generate:schema` — regenerate Zod types from DB after migration changes+- `cd backend-go && make gen-goa` — regenerate Goa HTTP handlers from DSL+- `cd backend-go && make gen-db` — regenerate go-jet table types from DB+- `cd backend-go && make test` — run Go integration testsBoth backend and frontend use `@app/*` as path alias to `./src/*`.@@ -17,6 +20,7 @@ Infisical is an open-source secret management platform. Monorepo layout:```infisical/├── backend/ # Fastify 4 API server (see backend/CLAUDE.md)+├── backend-go/ # Go API server — partial rewrite (see backend-go/CLAUDE.md)├── frontend/ # React 18 SPA (see frontend/CLAUDE.md)├── docs/ # Documentation site (Mintlify-based)├── docker-compose.dev.yml # Local dev (PostgreSQL, Redis, backend, frontend, Nginx)@@ -30,6 +34,7 @@ infisical/```- **`backend/`** — Fastify 4 API server, TypeScript, PostgreSQL via Knex, BullMQ queues. See [`backend/CLAUDE.md`](backend/CLAUDE.md) for architecture, patterns, and commands.+- **`backend-go/`** — Go API server (partial rewrite), Goa v3 for API design, go-jet for type-safe SQL, same PostgreSQL database. See [`backend-go/CLAUDE.md`](backend-go/CLAUDE.md) for architecture, patterns, and commands.- **`frontend/`** — React 18 SPA, Vite 6, TanStack Router + React Query, Tailwind CSS v4. See [`frontend/CLAUDE.md`](frontend/CLAUDE.md) for architecture, patterns, and commands.- **`docs/`** — Product documentation site. Has its own Dockerfile for building. Reference docs for up-to-date feature descriptions and API usage.@@ -59,7 +64,9 @@ Auth modes (JWT, IDENTITY_ACCESS_TOKEN, SCIM_TOKEN, MCP_JWT) are extracted in `b### Service Factory + Manual DI (Backend)-No IoC container. Every service is a factory function with explicit dependencies. The entire dependency graph is wired in `backend/src/server/routes/index.ts` — see `backend/CLAUDE.md` for the full wiring map and patterns.+No IoC container in either backend. Every service is a factory function with explicit dependencies.+- **Node.js**: Wired in `backend/src/server/routes/index.ts` — see `backend/CLAUDE.md`.+- **Go**: Wired in `backend-go/internal/services/services.go` via `NewRegistry()` — see `backend-go/CLAUDE.md`.### API Layer (Frontend)@@ -67,7 +74,7 @@ React Query + Axios with query key factories per domain. Each API domain in `fro## Keeping CLAUDE.md Up to Date-When making significant changes to the codebase (new services, architectural shifts, new patterns, major refactors), update the relevant CLAUDE.md file(s) with high-level findings. This includes this root file for cross-cutting concerns, `backend/CLAUDE.md` for backend changes, and `frontend/CLAUDE.md` for frontend changes. The goal is to keep these files accurate as living documentation so future sessions start with correct context.+When making significant changes to the codebase (new services, architectural shifts, new patterns, major refactors), update the relevant CLAUDE.md file(s) with high-level findings. This includes this root file for cross-cutting concerns, `backend/CLAUDE.md` for Node.js backend changes, `backend-go/CLAUDE.md` for Go backend changes, and `frontend/CLAUDE.md` for frontend changes. The goal is to keep these files accurate as living documentation so future sessions start with correct context.## Wiring a New Full-Stack Featurediff --git a/backend-go/CLAUDE.md b/backend-go/CLAUDE.mdnew file mode 100644index 0000000000..74fb23a57c--- /dev/null+++ b/backend-go/CLAUDE.md@@ -0,0 +1,154 @@+# CLAUDE.md++This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.++This is the **backend-go** package of the Infisical monorepo — a partial Go rewrite of the Node.js backend using Goa v3 for API design and go-jet for type-safe SQL.++## Essential Commands++All commands run from the `backend-go/` directory:++- `make build` — build binary (`go build -o infisical ./cmd/infisical/...`)+- `make dev` — start hot-reloading server via docker-compose + air+- `make gen-goa` — regenerate HTTP handlers from Goa DSL definitions+- `make gen-db` — regenerate go-jet table types from live PostgreSQL schema+- `make test` — run integration tests (testcontainers, `-race`, 300s timeout)+- `make test-cleanup` — tear down test compose stack + remove state file++## Architecture++### Startup Flow++```+cmd/infisical/main.go+├─ Load config (koanf, env vars)+├─ Connect to DB (primary + read replicas)+├─ Bootstrap health checks+├─ Create services.Registry (wires all DI)+├─ Create server.Server (mounts product routes)+└─ Listen on configured addr+```++### Directory Structure++```+backend-go/+├── cmd/+│ ├── infisical/main.go # Main server entry point+│ └── dev/pg_gen/main.go # go-jet code generation utility+├── internal/+│ ├── config/ # Centralized env-var config (koanf)+│ ├── database/+│ │ ├── pg/ # PostgreSQL driver (primary + read replicas)+│ │ │ └── gen/ # go-jet generated table types (50+ tables)+│ │ ├── redis/ # Redis client factory (standalone/cluster/sentinel)+│ │ └── ormify/ # Generic CRUD layer (DAL[M any])+│ ├── keystore/ # Key-value store (Redis) + PG advisory locks+│ ├── libs/bootstrap/ # Startup health checks+│ ├── server/+│ │ ├── design/ # Goa DSL API definitions (source of truth)+│ │ │ ├── platform/ # Platform product routes+│ │ │ └── secretmanager/ # Secret Manager product routes+│ │ ├── gen/ # Goa-generated code (DO NOT EDIT)+│ │ ├── server.go # HTTP server + route mounting+│ │ ├── platform.go # Mount platform routes+│ │ └── secretmanager.go # Mount secret manager routes+│ ├── services/+│ │ ├── services.go # Root registry wiring (DI entry point)+│ │ ├── platform/ # Platform product services+│ │ │ └── projects/ # Projects service+│ │ ├── secretmanager/ # Secret Manager product services+│ │ │ └── secrets/ # Secrets service+│ │ └── shared/ # Cross-product shared services+│ │ ├── permission/ # Permission checking+│ │ └── secretmanager/ # Product-scoped shared libs+│ │ └── secretfolder/ # Folder path resolution+│ └── testutil/ # Test infrastructure+├── llm/ # LLM-friendly architecture docs+├── Makefile+├── docker-compose.test.yml # Test infrastructure (PG, Redis, Node.js)+├── Dockerfile.dev # Dev image with air hot-reload+└── .air.toml # Hot-reload config+```++### API Design (Goa DSL)++API definitions live in `internal/server/design/` using Goa v3 DSL. This is the **source of truth** — running `make gen-goa` generates HTTP handlers, types, encoders/decoders into `internal/server/gen/`. Never edit generated code in `gen/` directly.++Routes are organized by product line:+- `design/platform/` — platform routes (e.g., projects)+- `design/secretmanager/` — secret manager routes (e.g., secrets CRUD)++### Service Factory + Manual DI++Same pattern as the Node.js backend — no IoC container. All services are factory functions with explicit dependencies, wired in `internal/services/services.go` via `NewRegistry()`.++**Always use interfaces when consuming dependencies.** Services must accept dependencies as interfaces, not concrete types. This keeps packages decoupled and testable. The interface should be defined by the consumer (in the consuming package), not the provider. Use narrow interfaces — only the methods the consumer actually needs.++```go+// In the consuming service package — define the interface you need:+type keyStore interface {+ GetItem(ctx context.Context, key string) (string, error)+ SetItemWithExpiry(ctx context.Context, key string, expiry time.Duration, value string) error+}++type Service struct {+ keyStore keyStore // accept interface, not *keystore.redisKeyStore+}+```++Services are organized in a three-tier hierarchy:+1. **Shared services** (`services/shared/`) — cross-product (permission, secretfolder), instantiated once+2. **Product registries** (`services/platform/`, `services/secretmanager/`) — product-specific wiring, may instantiate product-scoped shared libs+3. **Domain services** (`services/platform/projects/`, `services/secretmanager/secrets/`) — implement Goa-generated service interfaces++### DAL Layer (Data Access)++Generic CRUD via `internal/database/ormify/` using Go generics (`DAL[M any]`). Provides: `FindByID`, `FindOne`, `Find`, `FindAll`, `Create`, `InsertMany`, `UpdateByID`, `Update`, `DeleteByID`, `Delete`, `Count`. Functional options for limit/offset/orderBy.++go-jet generated table types live in `internal/database/pg/gen/table/` (50+ tables, auto-generated — do not edit).++**Read replica pattern**: The `pg.DB` wrapper supports primary + read replica connection pools. Reads go to a random replica (with fallback to primary). Writes always hit primary.++**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.++### Configuration++Environment variables loaded via koanf (`internal/config/config.go`). 186+ settings covering DB, Redis, auth, encryption, SSO, integrations, etc. Validated on startup with `config.ValidationError`.++### Testing++Integration tests using testcontainers-go with shared infrastructure:++1. **`testutil.SetupInfra()`** — acquires file lock, starts/reuses `docker-compose.test.yml` (PostgreSQL 14, Redis 7, Node.js backend), bootstraps org/user/identity tokens, saves state to `.test-infra-state.json`+2. **Per-test `setupMux()`** — instantiates real services + DALs, wires onto `testutil.TestMux` (httptest)+3. **Fluent test builder**:+ ```go+ mux.Request(t, http.MethodPost, "/api/v1/...").+ WithAuth(infra.IdentityToken).+ WithBody(payload).+ Do().+ ExpectStatus(http.StatusCreated).+ ParseJSON(&result)+ ```++Tests run with `-race` flag. Test infrastructure is shared across packages via file lock coordination — subsequent test packages reuse the running compose stack.++### Generated Code (Do Not Edit)++Two categories of generated code:+- **Goa generated** (`internal/server/gen/`) — regenerate with `make gen-goa`+- **go-jet generated** (`internal/database/pg/gen/`) — regenerate with `make gen-db`++Always regenerate rather than manually editing these directories.++## Wiring a New Feature (Checklist)++1. Define API in Goa DSL (`internal/server/design/<product>/`)+2. Run `make gen-goa` to generate handlers and types+3. Create domain service in `internal/services/<product>/<name>/` implementing the generated interface+4. If needed, add shared services in `internal/services/shared/`+5. Wire in `internal/services/services.go` (product registry → root registry)+6. Mount in `internal/server/<product>.go`+7. Add tests in the service package with `setupMux()` pattern+8. Run `make test` to verifydiff --git a/backend-go/go.mod b/backend-go/go.modindex 498252929a..8530288079 100644--- a/backend-go/go.mod+++ b/backend-go/go.mod@@ -44,6 +44,7 @@ require (github.com/containerd/typeurl/v2 v2.2.3 // indirectgithub.com/cpuguy83/dockercfg v0.3.2 // indirectgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect+ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirectgithub.com/dimfeld/httppath v0.0.0-20170720192232-ee938bf73598 // indirectgithub.com/distribution/reference v0.6.0 // indirectgithub.com/docker/buildx v0.31.1 // indirect@@ -123,6 +124,7 @@ require (github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirectgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirectgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect+ github.com/redis/go-redis/v9 v9.18.0 // indirectgithub.com/rivo/uniseg v0.4.7 // indirectgithub.com/santhosh-tekuri/jsonschema/v6 v6.0.1 // indirectgithub.com/secure-systems-lab/go-securesystemslib v0.9.1 // indirect@@ -159,6 +161,7 @@ require (go.opentelemetry.io/otel/sdk/metric v1.41.0 // indirectgo.opentelemetry.io/otel/trace v1.41.0 // indirectgo.opentelemetry.io/proto/otlp v1.9.0 // indirect+ go.uber.org/atomic v1.11.0 // indirectgo.yaml.in/yaml/v3 v3.0.4 // indirectgo.yaml.in/yaml/v4 v4.0.0-rc.4 // indirectgolang.org/x/crypto v0.49.0 // indirectdiff --git a/backend-go/go.sum b/backend-go/go.sumindex 6659b2797d..945161472a 100644--- a/backend-go/go.sum+++ b/backend-go/go.sum@@ -88,6 +88,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsgithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=github.com/digitorus/pkcs7 v0.0.0-20230818184609-3a137a874352 h1:ge14PCmCvPjpMQMIAH7uKg0lrtNSOdpYsRXlwk3QbaE=github.com/digitorus/pkcs7 v0.0.0-20230818184609-3a137a874352/go.mod h1:SKVExuS+vpu2l9IoOc0RwqE7NYnb0JlcFHFnEJkVDzc=github.com/digitorus/timestamp v0.0.0-20231217203849-220c5c2851b7 h1:lxmTCgmHE1GUYL7P0MlNa00M67axePTq+9nBSGddR8I=@@ -416,6 +418,8 @@ github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9Zgithub.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=+github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=+github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=@@ -554,6 +558,8 @@ go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=diff --git a/backend-go/internal/database/redis/redis.go b/backend-go/internal/database/redis/redis.gonew file mode 100644index 0000000000..909de9b56c--- /dev/null+++ b/backend-go/internal/database/redis/redis.go@@ -0,0 +1,92 @@+package redis++import (+ "context"+ "crypto/tls"+ "fmt"+ "net"++ "github.com/infisical/api/internal/config"+ "github.com/redis/go-redis/v9"+)++// maxRetries mirrors the Node.js ioredis reconnectOnError behaviour.+// On a READONLY error (e.g. during failover when a master becomes a replica),+// go-redis marks the connection as bad (isBadConn), removes it from the pool,+// and on the next retry creates a fresh connection with new DNS resolution —+// equivalent to ioredis reconnectOnError returning 2 ("reconnect and resend").+// See: https://github.com/redis/go-redis/blob/master/error.go (isBadConn / shouldRetry)+const maxRetries = 3++// NewClientFromEnvConfig creates a redis.UniversalClient from the application's+// Config. It supports standalone (REDIS_URL), cluster, and sentinel modes,+// matching the Node.js backend's buildRedisFromConfig behaviour.+func NewClientFromEnvConfig(cfg *config.Config) (redis.UniversalClient, error) {+ // Standalone mode via REDIS_URL.+ if cfg.RedisURL != "" {+ opts, err := redis.ParseURL(cfg.RedisURL)+ if err != nil {+ return nil, fmt.Errorf("parsing REDIS_URL: %w", err)+ }+ opts.MaxRetries = maxRetries+ return redis.NewClient(opts), nil+ }++ // Cluster mode.+ // go-redis automatically handles READONLY/MOVED/ASK redirects.+ if len(cfg.ParsedRedisClusterHosts) > 0 {+ addrs := hostPortAddrs(cfg.ParsedRedisClusterHosts)++ clusterOpts := &redis.ClusterOptions{+ Addrs: addrs,+ Username: cfg.RedisUsername,+ Password: cfg.RedisPassword,+ MaxRetries: maxRetries,+ }++ if cfg.RedisClusterEnableTLS {+ clusterOpts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}+ }++ if cfg.RedisClusterAWSElastiCacheDNSLookupMode {+ // Skip DNS resolution for AWS ElastiCache — pass address through as-is.+ clusterOpts.Dialer = func(_ context.Context, network, addr string) (net.Conn, error) {+ return net.Dial(network, addr)+ }+ }++ return redis.NewClusterClient(clusterOpts), nil+ }++ // Sentinel mode.+ // go-redis FailoverClient detects master switchover and reconnects automatically.+ if len(cfg.ParsedRedisSentinelHosts) > 0 {+ sentinelAddrs := hostPortAddrs(cfg.ParsedRedisSentinelHosts)++ failoverOpts := &redis.FailoverOptions{+ MasterName: cfg.RedisSentinelMasterName,+ SentinelAddrs: sentinelAddrs,+ SentinelUsername: cfg.RedisSentinelUsername,+ SentinelPassword: cfg.RedisSentinelPassword,+ Username: cfg.RedisUsername,+ Password: cfg.RedisPassword,+ MaxRetries: maxRetries,+ }++ if cfg.RedisSentinelEnableTLS {+ failoverOpts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}+ }++ return redis.NewFailoverClient(failoverOpts), nil+ }++ return nil, fmt.Errorf("no Redis configuration found: set REDIS_URL, REDIS_CLUSTER_HOSTS, or REDIS_SENTINEL_HOSTS")+}++func hostPortAddrs(hosts []config.RedisHostPort) []string {+ addrs := make([]string, len(hosts))+ for i, hp := range hosts {+ addrs[i] = fmt.Sprintf("%s:%d", hp.Host, hp.Port)+ }+ return addrs+}diff --git a/backend-go/internal/keystore/keystore.go b/backend-go/internal/keystore/keystore.gonew file mode 100644index 0000000000..838d202d09--- /dev/null+++ b/backend-go/internal/keystore/keystore.go@@ -0,0 +1,144 @@+package keystore++import (+ "context"+ "database/sql"+ "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.+type Tx interface {+ ExecContext(ctx context.Context, query string, args ...any) (sql.Result, 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.+type KeyStore interface {+ SetItem(ctx context.Context, key string, value string) error+ GetItem(ctx context.Context, key string) (string, error)+ SetExpiry(ctx context.Context, key string, expiry time.Duration) (bool, error)+ SetItemWithExpiry(ctx context.Context, key string, expiry time.Duration, value string) error+ SetItemWithExpiryNX(ctx context.Context, key string, expiry time.Duration, value string) (bool, error)+ DeleteItem(ctx context.Context, key string) (int64, error)+ DeleteItems(ctx context.Context, keys []string) (int64, error)+ IncrementBy(ctx context.Context, key string, value int64) (int64, 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 (k *redisKeyStore) SetItem(ctx context.Context, key string, value string) error {+ return k.client.Set(ctx, key, value, 0).Err()+}++func (k *redisKeyStore) GetItem(ctx context.Context, key string) (string, error) {+ val, err := k.client.Get(ctx, key).Result()+ if err == redis.Nil {+ return "", nil+ }+ return val, err+}++func (k *redisKeyStore) SetExpiry(ctx context.Context, key string, expiry time.Duration) (bool, error) {+ return k.client.Expire(ctx, key, expiry).Result()+}++func (k *redisKeyStore) SetItemWithExpiry(ctx context.Context, key string, expiry time.Duration, value string) error {+ return k.client.Set(ctx, key, value, expiry).Err()+}++func (k *redisKeyStore) SetItemWithExpiryNX(ctx context.Context, key string, expiry time.Duration, value string) (bool, error) {+ return k.client.SetNX(ctx, key, value, expiry).Result()+}++func (k *redisKeyStore) DeleteItem(ctx context.Context, key string) (int64, error) {+ return k.client.Del(ctx, key).Result()+}++func (k *redisKeyStore) DeleteItems(ctx context.Context, keys []string) (int64, error) {+ if len(keys) == 0 {+ return 0, nil+ }+ return k.client.Del(ctx, keys...).Result()+}++func (k *redisKeyStore) IncrementBy(ctx context.Context, key string, value int64) (int64, error) {+ return k.client.IncrBy(ctx, key, value).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 {+ tx.Rollback()+ }+ 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.gonew file mode 100644index 0000000000..a4ffa1fa05--- /dev/null+++ b/backend-go/internal/keystore/lock.go@@ -0,0 +1,12 @@+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/services/shared/serverconfig/dal.go b/backend-go/internal/services/shared/serverconfig/dal.gonew file mode 100644index 0000000000..df91187ff4--- /dev/null+++ b/backend-go/internal/services/shared/serverconfig/dal.go@@ -0,0 +1,79 @@+package serverconfig++import (+ "context"+ "database/sql"+ "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 {+ tx.Commit()+ return cfg, nil+ }+ if 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.String(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/shared/serverconfig/serverconfig.go b/backend-go/internal/services/shared/serverconfig/serverconfig.gonew file mode 100644index 0000000000..b28cafb12c--- /dev/null+++ b/backend-go/internal/services/shared/serverconfig/serverconfig.go@@ -0,0 +1,169 @@+package serverconfig++import (+ "context"+ "encoding/json"+ "fmt"+ "time"++ "github.com/google/uuid"+ "github.com/lib/pq"++ "github.com/infisical/api/internal/database/pg/gen/model"+)++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++ adminConfigCacheKey = "infisical-admin-cfg"+ adminConfigCacheTTL = 60 * time.Second+)++// ServerConfig is the service-level representation of the server admin configuration.+type ServerConfig struct {+ ID uuid.UUID+ Initialized bool+ AllowSignUp bool+ CreatedAt time.Time+ UpdatedAt time.Time+ AllowedSignUpDomain string+ InstanceID uuid.UUID+ TrustSamlEmails bool+ TrustLdapEmails bool+ TrustOidcEmails bool+ DefaultAuthOrgID *uuid.UUID+ EnabledLoginMethods []string+ AuthConsentContent string+ PageFrameContent string+ AdminIdentityIDs []string+ FipsEnabled bool+}++func configFromModel(m *model.SuperAdmin) ServerConfig {+ cfg := ServerConfig{+ ID: m.ID,+ CreatedAt: m.CreatedAt,+ UpdatedAt: m.UpdatedAt,+ InstanceID: m.InstanceId,+ FipsEnabled: m.FipsEnabled,+ }++ if m.Initialized != nil {+ cfg.Initialized = *m.Initialized+ }+ if m.AllowSignUp != nil {+ cfg.AllowSignUp = *m.AllowSignUp+ }+ if m.AllowedSignUpDomain != nil {+ cfg.AllowedSignUpDomain = *m.AllowedSignUpDomain+ }+ if m.TrustSamlEmails != nil {+ cfg.TrustSamlEmails = *m.TrustSamlEmails+ }+ if m.TrustLdapEmails != nil {+ cfg.TrustLdapEmails = *m.TrustLdapEmails+ }+ if m.TrustOidcEmails != nil {+ cfg.TrustOidcEmails = *m.TrustOidcEmails+ }+ if m.DefaultAuthOrgId != nil {+ cfg.DefaultAuthOrgID = m.DefaultAuthOrgId+ }+ if m.EnabledLoginMethods != nil {+ cfg.EnabledLoginMethods = []string(*m.EnabledLoginMethods)+ }+ if m.AuthConsentContent != nil {+ cfg.AuthConsentContent = *m.AuthConsentContent+ }+ if m.PageFrameContent != nil {+ cfg.PageFrameContent = *m.PageFrameContent+ }+ if m.AdminIdentityIds != nil {+ cfg.AdminIdentityIDs = []string(*m.AdminIdentityIds)+ }++ return cfg+}++// keyStore defines the subset of keystore operations this service needs.+type keyStore interface {+ GetItem(ctx context.Context, key string) (string, error)+ SetItemWithExpiry(ctx context.Context, key string, expiry time.Duration, value string) error+ 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 string) (*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)+}++// SharedService manages the server admin configuration (the single super_admin row).+// It provides cached reads (via Redis) and idempotent initialization (via PG advisory lock).+type SharedService struct {+ dal dal+ keyStore keyStore+}++// NewSharedService creates a new server config service.+func NewSharedService(dal dal, ks keyStore) *SharedService {+ return &SharedService{+ dal: dal,+ keyStore: ks,+ }+}++// Init ensures the super_admin config row exists.+// Delegates to the DAL which handles the advisory lock and transaction internally.+func (s *SharedService) Init(ctx context.Context) (ServerConfig, error) {+ s.keyStore.DeleteItem(ctx, adminConfigCacheKey)++ m, err := s.dal.FindOrCreateConfig(ctx)+ if err != nil {+ return ServerConfig{}, err+ }+ return configFromModel(m), nil+}++// GetConfig returns the server admin config, using a Redis cache with a 60s TTL.+// On cache miss, it reads from the database and populates the cache.+func (s *SharedService) GetConfig(ctx context.Context) (ServerConfig, error) {+ cached, err := s.keyStore.GetItem(ctx, adminConfigCacheKey)+ if err != nil {+ return ServerConfig{}, fmt.Errorf("reading config from cache: %w", err)+ }++ if cached != "" {+ var cfg ServerConfig+ if err := json.Unmarshal([]byte(cached), &cfg); err != nil {+ return ServerConfig{}, fmt.Errorf("unmarshaling cached config: %w", err)+ }+ return cfg, nil+ }++ // Cache miss — read from DB.+ m, err := s.dal.FindByID(ctx, AdminConfigDBUUID)+ if err != nil {+ return ServerConfig{}, fmt.Errorf("reading config from database: %w", err)+ }++ cfg := configFromModel(m)++ // Populate cache (non-fatal on error).+ if data, err := json.Marshal(cfg); err == nil {+ s.keyStore.SetItemWithExpiry(ctx, adminConfigCacheKey, adminConfigCacheTTL, string(data))+ }++ return cfg, nil+}++// InvalidateCache removes the config from the Redis cache.+func (s *SharedService) InvalidateCache(ctx context.Context) error {+ _, err := s.keyStore.DeleteItem(ctx, adminConfigCacheKey)+ return err+}diff --git a/backend-go/llm/project-structure.md b/backend-go/llm/project-structure.mddeleted file mode 100644index 477361bf04..0000000000--- a/backend-go/llm/project-structure.md+++ /dev/null@@ -1,58 +0,0 @@-# Backend-Go Architecture--## Folder Structure--```-backend-go/internal/-├── config/ # App config (koanf)-├── database/-│ ├── pg/ # Postgres connection (primary + replicas, returns *sql.DB)-│ └── ormify/ # Generic CRUD via go-jet + Go generics-├── libs/bootstrap/ # Startup health checks-├── server/-│ ├── design/ # Goa DSL (source of truth for API)-│ │ ├── platform/ # Platform API design-│ │ └── secretmanager/-│ └── gen/ # Goa-generated handlers (DO NOT EDIT)-└── services/- ├── services.go # Root registry — wires shared libs → product registries- ├── shared/ # Cross-cutting libs (NOT api-facing)- │ ├── libs.go # Shared libs registry- │ ├── permission/ # Permission checking (SharedService + DAL)- │ └── secretmanager/secretfolder/ # Folder resolution (product-scoped shared lib)- ├── platform/ # Product: platform- │ ├── platform.go # Product registry- │ └── projects/ # API-facing service- └── secretmanager/ # Product: secret manager- ├── secretmanager.go- └── secrets/ # API-facing service-```--## Key Rules--**Shared vs API-facing:**-- `services/shared/` holds reusable services (permission, secretfolder). These are NEVER api-facing — they don't implement Goa service interfaces.-- `services/<product>/<domain>/` holds API-facing services that implement Goa-generated interfaces (e.g. `genprojects.Service`, `gensecrets.Service`).-- Shared services must NOT be shared directly between API-facing services at the same level. They flow down: `shared.Libs` → product registry → domain service.--**Shared lib scoping:**-- Truly cross-product libs (e.g. permission) live in `shared/` and are instantiated once in `shared.NewLibs()`.-- Product-scoped shared libs (e.g. secretfolder) live under `shared/<product>/` but are instantiated inside the product registry (e.g. `secretmanager.NewRegistry()`), NOT in `shared.NewLibs()`.--**Interface pattern:**-- Each API-facing service defines its own small interface for each dependency (consumer-side interfaces).-- Interface names use `Svc` suffix: `permissionSvc`, `secretFolderSvc`.-- Shared service structs are named `SharedService` with constructor `NewSharedService()`.-- No compile-time interface satisfaction checks (`var _ iface = (*Type)(nil)`).--**DI wiring flow:**-```-main.go → services.NewRegistry()- → shared.NewSharedServices() # cross-product shared shared services- → platform.NewRegistry() # receives shared shared services, creates product services- → secretmanager.NewRegistry() # receives shared shared services, creates product-scoped shared services + services-```--This avoids cyclic imports — shared services under `shared/` can be consumed by any product without products importing each other.--When adding a new shared lib: cross-product → `shared/` + `NewSharedServices()`. Product-scoped → `shared/<product>/` + instantiate in product registry.diff --git a/backend-go/llm/testing-strategy.md b/backend-go/llm/testing-strategy.mddeleted file mode 100644index e4889c8478..0000000000--- a/backend-go/llm/testing-strategy.md+++ /dev/null@@ -1,98 +0,0 @@-# Backend-Go Testing--## Commands--```-make test (testcontainers, race detector, 300s timeout)-```--## Infrastructure--Tests use `docker-compose.test.yml` via testcontainers-go. Stack: PostgreSQL 14, Redis 7, Node.js backend (handles migrations + seed APIs).--**Shared infra pattern:** First test package to run acquires a file lock (`.test-infra.lock`), starts compose, bootstraps credentials, and writes state to `.test-infra-state.json`. Subsequent packages reuse the running stack. Only `make test-cleanup` tears down containers.--## Test File Structure--Each API-facing service gets a `_test.go` in its package:--```-services/<product>/<domain>/<domain>_test.go-```--### TestMain (once per package)--```go-var (- infra *testutil.TestInfra- project *testutil.ProjectSeed-)--func TestMain(m *testing.M) {- infra = testutil.SetupInfra() // start/reuse compose stack- project = infra.MustCreateProject("my-svc") // isolated project via Node.js API- code := m.Run()- infra.Teardown() // closes DB pool only- os.Exit(code)-}-```--### setupMux (per test helper)--Wires the Goa module under test onto `testutil.TestMux` (httptest, no full server):--```go-func setupMux(t *testing.T) *testutil.TestMux {- t.Helper()- // Instantiate real shared services + DALs- permDAL := permission.NewDAL()- permSvc := permission.NewSharedService(permDAL)- // Create the service under test- svc := mysvc.NewService(testutil.NopLogger(), permSvc)- // Mount Goa module- mux := testutil.NewTestMux()- endpoints := genmysvc.NewEndpoints(svc)- server := mysvcsvr.New(endpoints, mux.Mux, mux.Dec, mux.Enc, mux.Eh, nil)- mysvcsvr.Mount(mux.Mux, server)- return mux-}-```--### Test functions--Fluent request builder → assert status → parse JSON:--```go-func TestCreateThing(t *testing.T) {- mux := setupMux(t)-- var result map[string]any- mux.Request(t, http.MethodPost, "/api/v1/my-endpoint").- WithAuth(infra.IdentityToken).- WithBody(map[string]any{"key": "value", "projectId": project.ID}).- Do().- ExpectStatus(http.StatusCreated).- ParseJSON(&result)-- require.Equal(t, "expected", result["key"])-}-```--## Test Utilities (`internal/testutil/`)--| File | Purpose |-|------|---------|-| `infra.go` | `SetupInfra()` — compose lifecycle, file-lock coordination, DB pool, bootstrap credentials |-| `seed.go` | `MustCreateProject()`, `CreateProject()`, `DeleteProject()` — project seeding via Node.js API |-| `goahelper.go` | `TestMux`, `RequestBuilder`, `Response` — fluent HTTP testing for Goa modules |-| `logger.go` | `NopLogger()` — discarding slog logger |--## Key Tokens from TestInfra--- `infra.IdentityToken` — machine identity access token (for API auth)-- `infra.UserToken` — user JWT-- `project.ID`, `project.EnvSlug` — isolated project per test package--## Unit Tests--No special setup needed. Use for pure logic (crypto, validation, permission evaluation). No build tags — `make test-unit` runs all tests but skips integration since compose won't be available.