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: moved away from dal for license
=44cc764a0485
diff --git a/backend-go/CLAUDE.md b/backend-go/CLAUDE.mdindex 09941edeb2..a22b6f8886 100644--- a/backend-go/CLAUDE.md+++ b/backend-go/CLAUDE.md@@ -1,6 +1,6 @@# backend-go-Partial Go rewrite of the Node.js backend using Goa v3 + go-jet.+Partial Go rewrite of the Node.js backend using Goa v3 + raw pgx queries.## Commands@@ -8,7 +8,6 @@ Partial Go rewrite of the Node.js backend using Goa v3 + go-jet.make build # build binarymake dev # hot-reload via docker-compose + airmake gen-goa # regenerate Goa handlers (design/ → gen/)-make gen-db # regenerate go-jet types from DBmake test # integration tests (testcontainers, -race)make lint # must pass before submissionmake lint-fix # auto-fix linting issues@@ -23,13 +22,13 @@ Never edit `gen/` directories — always regenerate.- **Context**: Every I/O method takes `context.Context` first. Constructors are the exception.- **Logger**: Pass `*slog.Logger` via constructor — never use `slog.Default()`.- **Interfaces**: Service Consumer defines narrow interfaces. Accept interfaces, not concrete types.-- **DAL boundary**: Services must not import `table`, `postgres`, `qrm`. Use go-jet only.-- **Error wrapping**: Wrap DAL errors at caller level with context:+- **No DAL layer**: Services directly use `pg.DB` and execute raw pgx queries.+- **Error wrapping**: Wrap database errors at service level with context:```goerrutil.DatabaseErr("Failed to load").WithErrf("FuncName(arg=%s): %w", arg, err)errutil.Forbidden("Access denied").WithErrf("FuncName: permission check failed")```-- **Lean code**: Inline single-use helpers. Split DAL files by functionality.+- **Lean code**: Inline single-use helpers.## Architecture@@ -38,41 +37,113 @@ cmd/infisical/main.go # Entry pointinternal/├── config/ # Env config via koanf├── database/-│ ├── pg/gen/ # go-jet generated (DO NOT EDIT)-│ ├── redis/ # Redis client-│ └── ormify/ # Generic CRUD: DAL[M] with Find/Create/Update/Delete+│ ├── pg/+│ │ ├── pg.go # DB interface (primary + replicas via pgxpool)+│ │ ├── qb/ # Query builders (Where, Insert, Update, Delete)+│ │ ├── sqln/ # SQL nesting (GroupRows for LEFT JOIN flattening)+│ │ └── pglock/ # PostgreSQL advisory locks+│ └── redis/ # Redis client+├── libs/+│ ├── fn/ # Generic utilities (AppendUnique, etc.)+│ └── errutil/ # Error types and formatting├── server/│ ├── design/ # Goa DSL definitions│ ├── gen/ # Goa generated (DO NOT EDIT)│ └── api/ # Endpoint implementations + DI wiring├── services/ # Shared business logic (auth, permission, kms)+├── keystore/ # Redis key-value operations└── testutil/ # Test infra (testcontainers)```**Two tiers:**- `server/api/` — Goa endpoint implementations. 1:1 with endpoints. Not imported elsewhere.-- `services/` — Shared logic. No Goa dependency.+- `services/` — Shared logic. No Goa dependency. Directly uses `pg.DB` for queries.-**DAL**: `ormify.DAL[M]` provides `FindByID`, `Find`, `Create`, `Update`, `Delete`, `Count`.+**Database access**: Services receive `pg.DB` and execute raw pgx queries using helper packages.-**Read replicas**: `pg.DB` wraps primary + replica pools. Reads hit replicas, writes hit primary.+**Read replicas**: `pg.DB` wraps primary + replica pools. Use `db.Primary()` for writes, `db.Replica()` for reads.-### Go-Jet Nesting+### Query Helpers-For JOINs with one-to-many, use struct tags:+**`qb` package** — Query builders for dynamic SQL:+```go+// WHERE builder (for SELECT with named args)+args := pgx.NamedArgs{"folderID": folderID}+where := qb.NewWhere().+ Add("folder_id = @folderID").+ AddIf(len(keys) > 0, "key = ANY(@keys)")+args["keys"] = keys++query := `SELECT * FROM secrets WHERE ` + where.String()+rows, err := db.Replica().Query(ctx, query, args)++// INSERT (numbered args for bulk)+sql, args := qb.Insert("secrets", "id", "key", "folder_id").+ Values(id1, key1, folder1).+ Values(id2, key2, folder2).+ Returning("*").+ Build()++// UPDATE (named args)+sql, args := qb.Update("secrets").+ Set("key", newKey).+ Where("id = @id", "id", id).+ Returning("*").+ Build()++// DELETE (named args)+sql, args := qb.Delete("secrets").+ Where("id = @id", "id", id).+ Build()+```+**`sqln` package** — Transform flat LEFT JOIN rows into nested structs:```go-type Secret struct {- ID uuid.UUID `sql:"primary_key" alias:"secrets_v2.id"`- Tags []SecretTag `alias:"secret_tags"`+grouper := sqln.Grouper[Secret, uuid.UUID]{+ Key: func(s *Secret) uuid.UUID { return s.ID },+ Merge: func(existing, row *Secret) {+ if len(row.Tags) > 0 {+ existing.Tags = fn.AppendUnique(existing.Tags, row.Tags[0],+ func(t Tag) uuid.UUID { return t.ID })+ }+ },}-type SecretTag struct {- ID uuid.UUID `sql:"primary_key" alias:"secret_tags.id"`- Slug string `alias:"secret_tags.slug"`+secrets := sqln.GroupRows(flatSecrets, grouper)+```++**`pglock` package** — PostgreSQL advisory locks:+```go+tx, _ := db.Primary().Begin(ctx)+lock, err := pglock.AcquireBlockingLock(ctx, tx, "my_lock_id")+if err != nil {+ tx.Rollback(ctx)+ return err}+defer lock.Rollback(ctx) // safety net++// ... do work within lock ...++lock.Release(ctx) // commits transaction```-Go-jet auto-groups slices. Requires `sql:"primary_key"` on IDs.+### Writing Raw Queries++Use `pgx.NamedArgs` for parameterized queries:+```go+query := `+ SELECT id, key, encrypted_value+ FROM secrets_v2+ WHERE folder_id = @folderID AND user_id IS NULL+ ORDER BY key ASC+`+args := pgx.NamedArgs{"folderID": folderID}+rows, err := db.Replica().Query(ctx, query, args)+```++Scan rows using `pgx.CollectRows` or manual scanning:+```go+secrets, err := pgx.CollectRows(rows, pgx.RowToStructByName[Secret])+```## Wiring a New Featurediff --git a/backend-go/internal/database/pg/sqln/group.go b/backend-go/internal/database/pg/sqln/group.gonew file mode 100644index 0000000000..d2461be458--- /dev/null+++ b/backend-go/internal/database/pg/sqln/group.go@@ -0,0 +1,51 @@+package sqln++// Grouper defines how to group and merge rows by a key.+// Used to transform flat LEFT JOIN results into nested structures.+type Grouper[T any, K comparable] struct {+ // Key extracts the grouping key from a row (typically the primary key).+ Key func(*T) K+ // Merge combines data from a duplicate row into the existing row.+ // Called when a row with the same key is encountered.+ Merge func(existing *T, row *T)+}++// GroupRows groups flat rows by key and merges duplicates.+// Preserves the order of first occurrence for each unique key.+//+// Example usage for LEFT JOIN with tags:+//+// grouper := sqln.Grouper[Secret, uuid.UUID]{+// Key: func(s *Secret) uuid.UUID { return s.ID },+// Merge: func(existing, row *Secret) {+// if len(row.Tags) > 0 {+// existing.Tags = fn.AppendUnique(existing.Tags, row.Tags[0], func(t SecretTag) uuid.UUID { return t.ID })+// }+// },+// }+// secrets := sqln.GroupRows(flatSecrets, grouper)+func GroupRows[T any, K comparable](rows []T, g Grouper[T, K]) []T {+ if len(rows) == 0 {+ return rows+ }++ result := make(map[K]*T, len(rows))+ order := make([]K, 0, len(rows))++ for i := range rows {+ key := g.Key(&rows[i])+ if existing, ok := result[key]; ok {+ g.Merge(existing, &rows[i])+ } else {+ rowCopy := rows[i]+ result[key] = &rowCopy+ order = append(order, key)+ }+ }++ out := make([]T, 0, len(order))+ for _, k := range order {+ out = append(out, *result[k])+ }+ return out+}diff --git a/backend-go/internal/database/pg/sqln/group_test.go b/backend-go/internal/database/pg/sqln/group_test.gonew file mode 100644index 0000000000..6e9a14e591--- /dev/null+++ b/backend-go/internal/database/pg/sqln/group_test.go@@ -0,0 +1,197 @@+package sqln++import (+ "testing"++ "github.com/google/uuid"++ "github.com/infisical/api/internal/libs/fn"+)++type Tag struct {+ ID uuid.UUID+ Slug string+}++type Secret struct {+ ID uuid.UUID+ Key string+ Tags []Tag+}++func TestGroupRows_Empty(t *testing.T) {+ var rows []Secret+ grouper := Grouper[Secret, uuid.UUID]{+ Key: func(s *Secret) uuid.UUID { return s.ID },+ Merge: func(existing, row *Secret) {},+ }++ result := GroupRows(rows, grouper)++ if len(result) != 0 {+ t.Errorf("expected 0 items, got %d", len(result))+ }+}++func TestGroupRows_NoMergeNeeded(t *testing.T) {+ id1 := uuid.MustParse("11111111-1111-1111-1111-111111111111")+ id2 := uuid.MustParse("22222222-2222-2222-2222-222222222222")++ rows := []Secret{+ {ID: id1, Key: "SECRET_1"},+ {ID: id2, Key: "SECRET_2"},+ }++ grouper := Grouper[Secret, uuid.UUID]{+ Key: func(s *Secret) uuid.UUID { return s.ID },+ Merge: func(existing, row *Secret) {},+ }++ result := GroupRows(rows, grouper)++ if len(result) != 2 {+ t.Errorf("expected 2 items, got %d", len(result))+ }+}++func TestGroupRows_MergesTags(t *testing.T) {+ secretID := uuid.MustParse("11111111-1111-1111-1111-111111111111")+ tagID1 := uuid.MustParse("aaaa1111-1111-1111-1111-111111111111")+ tagID2 := uuid.MustParse("bbbb2222-2222-2222-2222-222222222222")++ rows := []Secret{+ {ID: secretID, Key: "SECRET_1", Tags: []Tag{{ID: tagID1, Slug: "tag1"}}},+ {ID: secretID, Key: "SECRET_1", Tags: []Tag{{ID: tagID2, Slug: "tag2"}}},+ }++ grouper := Grouper[Secret, uuid.UUID]{+ Key: func(s *Secret) uuid.UUID { return s.ID },+ Merge: func(existing, row *Secret) {+ if len(row.Tags) > 0 {+ existing.Tags = fn.AppendUnique(existing.Tags, row.Tags[0], func(t Tag) uuid.UUID { return t.ID })+ }+ },+ }++ result := GroupRows(rows, grouper)++ if len(result) != 1 {+ t.Fatalf("expected 1 secret, got %d", len(result))+ }+ if len(result[0].Tags) != 2 {+ t.Errorf("expected 2 tags, got %d", len(result[0].Tags))+ }+}++func TestGroupRows_PreservesOrder(t *testing.T) {+ id1 := uuid.MustParse("11111111-1111-1111-1111-111111111111")+ id2 := uuid.MustParse("22222222-2222-2222-2222-222222222222")+ id3 := uuid.MustParse("33333333-3333-3333-3333-333333333333")++ rows := []Secret{+ {ID: id2, Key: "SECOND"},+ {ID: id1, Key: "FIRST"},+ {ID: id3, Key: "THIRD"},+ {ID: id2, Key: "SECOND_DUP"},+ }++ grouper := Grouper[Secret, uuid.UUID]{+ Key: func(s *Secret) uuid.UUID { return s.ID },+ Merge: func(existing, row *Secret) {},+ }++ result := GroupRows(rows, grouper)++ if len(result) != 3 {+ t.Fatalf("expected 3 secrets, got %d", len(result))+ }+ if result[0].ID != id2 {+ t.Errorf("expected first result ID %v, got %v", id2, result[0].ID)+ }+ if result[1].ID != id1 {+ t.Errorf("expected second result ID %v, got %v", id1, result[1].ID)+ }+ if result[2].ID != id3 {+ t.Errorf("expected third result ID %v, got %v", id3, result[2].ID)+ }+}++func TestGroupRows_SkipsDuplicateTags(t *testing.T) {+ secretID := uuid.MustParse("11111111-1111-1111-1111-111111111111")+ tagID := uuid.MustParse("aaaa1111-1111-1111-1111-111111111111")++ rows := []Secret{+ {ID: secretID, Key: "SECRET_1", Tags: []Tag{{ID: tagID, Slug: "tag1"}}},+ {ID: secretID, Key: "SECRET_1", Tags: []Tag{{ID: tagID, Slug: "tag1"}}},+ {ID: secretID, Key: "SECRET_1", Tags: []Tag{{ID: tagID, Slug: "tag1"}}},+ }++ grouper := Grouper[Secret, uuid.UUID]{+ Key: func(s *Secret) uuid.UUID { return s.ID },+ Merge: func(existing, row *Secret) {+ if len(row.Tags) > 0 {+ existing.Tags = fn.AppendUnique(existing.Tags, row.Tags[0], func(t Tag) uuid.UUID { return t.ID })+ }+ },+ }++ result := GroupRows(rows, grouper)++ if len(result) != 1 {+ t.Fatalf("expected 1 secret, got %d", len(result))+ }+ if len(result[0].Tags) != 1 {+ t.Errorf("expected 1 tag (deduplicated), got %d", len(result[0].Tags))+ }+}++func TestGroupRows_ComplexMerge(t *testing.T) {+ type Meta struct {+ ID uuid.UUID+ Key string+ Value string+ }++ type ComplexSecret struct {+ ID uuid.UUID+ Key string+ Tags []Tag+ Metadata []Meta+ }++ secretID := uuid.MustParse("11111111-1111-1111-1111-111111111111")+ tagID1 := uuid.MustParse("aaaa1111-1111-1111-1111-111111111111")+ tagID2 := uuid.MustParse("bbbb2222-2222-2222-2222-222222222222")+ metaID1 := uuid.MustParse("cccc3333-3333-3333-3333-333333333333")+ metaID2 := uuid.MustParse("dddd4444-4444-4444-4444-444444444444")++ rows := []ComplexSecret{+ {ID: secretID, Key: "SECRET", Tags: []Tag{{ID: tagID1, Slug: "t1"}}, Metadata: []Meta{{ID: metaID1, Key: "k1", Value: "v1"}}},+ {ID: secretID, Key: "SECRET", Tags: []Tag{{ID: tagID2, Slug: "t2"}}, Metadata: []Meta{{ID: metaID1, Key: "k1", Value: "v1"}}},+ {ID: secretID, Key: "SECRET", Tags: []Tag{{ID: tagID1, Slug: "t1"}}, Metadata: []Meta{{ID: metaID2, Key: "k2", Value: "v2"}}},+ }++ grouper := Grouper[ComplexSecret, uuid.UUID]{+ Key: func(s *ComplexSecret) uuid.UUID { return s.ID },+ Merge: func(existing, row *ComplexSecret) {+ if len(row.Tags) > 0 {+ existing.Tags = fn.AppendUnique(existing.Tags, row.Tags[0], func(t Tag) uuid.UUID { return t.ID })+ }+ if len(row.Metadata) > 0 {+ existing.Metadata = fn.AppendUnique(existing.Metadata, row.Metadata[0], func(m Meta) uuid.UUID { return m.ID })+ }+ },+ }++ result := GroupRows(rows, grouper)++ if len(result) != 1 {+ t.Fatalf("expected 1 secret, got %d", len(result))+ }+ if len(result[0].Tags) != 2 {+ t.Errorf("expected 2 tags, got %d", len(result[0].Tags))+ }+ if len(result[0].Metadata) != 2 {+ t.Errorf("expected 2 metadata entries, got %d", len(result[0].Metadata))+ }+}diff --git a/backend-go/internal/libs/fn/slice.go b/backend-go/internal/libs/fn/slice.gonew file mode 100644index 0000000000..e17512eafa--- /dev/null+++ b/backend-go/internal/libs/fn/slice.go@@ -0,0 +1,21 @@+package fn++// AppendUnique appends an item to a slice only if no existing item has the same key.+// Returns the original slice if item already exists, otherwise returns a new slice with the item appended.+func AppendUnique[T any, K comparable](slice []T, item T, key func(T) K) []T {+ itemKey := key(item)+ for i := range slice {+ if key(slice[i]) == itemKey {+ return slice+ }+ }+ return append(slice, item)+}++// AppendUniqueSlice appends all items from src to dst, skipping duplicates by key.+func AppendUniqueSlice[T any, K comparable](dst, src []T, key func(T) K) []T {+ for _, item := range src {+ dst = AppendUnique(dst, item, key)+ }+ return dst+}diff --git a/backend-go/internal/libs/fn/slice_test.go b/backend-go/internal/libs/fn/slice_test.gonew file mode 100644index 0000000000..dde98399a3--- /dev/null+++ b/backend-go/internal/libs/fn/slice_test.go@@ -0,0 +1,125 @@+package fn++import (+ "testing"++ "github.com/google/uuid"+)++type testItem struct {+ ID uuid.UUID+ Name string+}++func TestAppendUnique_AddsNewItem(t *testing.T) {+ id1 := uuid.MustParse("11111111-1111-1111-1111-111111111111")+ id2 := uuid.MustParse("22222222-2222-2222-2222-222222222222")++ slice := []testItem{{ID: id1, Name: "first"}}+ newItem := testItem{ID: id2, Name: "second"}++ result := AppendUnique(slice, newItem, func(t testItem) uuid.UUID { return t.ID })++ if len(result) != 2 {+ t.Errorf("expected 2 items, got %d", len(result))+ }+ if result[1].ID != id2 {+ t.Errorf("expected second item ID %v, got %v", id2, result[1].ID)+ }+}++func TestAppendUnique_SkipsDuplicate(t *testing.T) {+ id1 := uuid.MustParse("11111111-1111-1111-1111-111111111111")++ slice := []testItem{{ID: id1, Name: "first"}}+ duplicate := testItem{ID: id1, Name: "duplicate"}++ result := AppendUnique(slice, duplicate, func(t testItem) uuid.UUID { return t.ID })++ if len(result) != 1 {+ t.Errorf("expected 1 item, got %d", len(result))+ }+ if result[0].Name != "first" {+ t.Errorf("expected original name 'first', got %q", result[0].Name)+ }+}++func TestAppendUnique_EmptySlice(t *testing.T) {+ id1 := uuid.MustParse("11111111-1111-1111-1111-111111111111")++ var slice []testItem+ newItem := testItem{ID: id1, Name: "first"}++ result := AppendUnique(slice, newItem, func(t testItem) uuid.UUID { return t.ID })++ if len(result) != 1 {+ t.Errorf("expected 1 item, got %d", len(result))+ }+}++func TestAppendUnique_StringKey(t *testing.T) {+ type item struct {+ Slug string+ Val int+ }++ slice := []item{{Slug: "a", Val: 1}}+ result := AppendUnique(slice, item{Slug: "b", Val: 2}, func(i item) string { return i.Slug })+ result = AppendUnique(result, item{Slug: "a", Val: 3}, func(i item) string { return i.Slug })++ if len(result) != 2 {+ t.Errorf("expected 2 items, got %d", len(result))+ }+ if result[0].Val != 1 {+ t.Errorf("expected first item Val 1, got %d", result[0].Val)+ }+}++func TestAppendUniqueSlice_MergesSlices(t *testing.T) {+ id1 := uuid.MustParse("11111111-1111-1111-1111-111111111111")+ id2 := uuid.MustParse("22222222-2222-2222-2222-222222222222")+ id3 := uuid.MustParse("33333333-3333-3333-3333-333333333333")++ dst := []testItem{{ID: id1, Name: "first"}}+ src := []testItem{+ {ID: id2, Name: "second"},+ {ID: id1, Name: "duplicate"},+ {ID: id3, Name: "third"},+ }++ result := AppendUniqueSlice(dst, src, func(t testItem) uuid.UUID { return t.ID })++ if len(result) != 3 {+ t.Errorf("expected 3 items, got %d", len(result))+ }+}++func TestAppendUniqueSlice_EmptySrc(t *testing.T) {+ id1 := uuid.MustParse("11111111-1111-1111-1111-111111111111")++ dst := []testItem{{ID: id1, Name: "first"}}+ var src []testItem++ result := AppendUniqueSlice(dst, src, func(t testItem) uuid.UUID { return t.ID })++ if len(result) != 1 {+ t.Errorf("expected 1 item, got %d", len(result))+ }+}++func TestAppendUniqueSlice_EmptyDst(t *testing.T) {+ id1 := uuid.MustParse("11111111-1111-1111-1111-111111111111")+ id2 := uuid.MustParse("22222222-2222-2222-2222-222222222222")++ var dst []testItem+ src := []testItem{+ {ID: id1, Name: "first"},+ {ID: id2, Name: "second"},+ }++ result := AppendUniqueSlice(dst, src, func(t testItem) uuid.UUID { return t.ID })++ if len(result) != 2 {+ t.Errorf("expected 2 items, got %d", len(result))+ }+}diff --git a/backend-go/internal/services/libs.go b/backend-go/internal/services/libs.goindex f0560fd4e9..183741c6f0 100644--- a/backend-go/internal/services/libs.go+++ b/backend-go/internal/services/libs.go@@ -58,11 +58,10 @@ func NewServices(ctx context.Context, deps *ServicesDeps) (*Services, error) {return nil, fmt.Errorf("kms start: %w", err)}- licenseDAL := license.NewDAL(deps.DB)licenseSvc := license.NewService(ctx, deps.Logger, license.Deps{Config: deps.Config,+ DB: deps.DB,KeyStore: deps.KeyStore,- DAL: licenseDAL,})authDAL := auth.NewDAL(deps.DB)diff --git a/backend-go/internal/services/license/api.go b/backend-go/internal/services/license/api.gonew file mode 100644index 0000000000..ab365939a4--- /dev/null+++ b/backend-go/internal/services/license/api.go@@ -0,0 +1,85 @@+package license++import (+ "context"+ "fmt"+ "sync"+ "time"++ "github.com/go-resty/resty/v2"+)++// licenseAPI wraps a resty client with token-based auth and auto-refresh.+type licenseAPI struct {+ client *resty.Client+ serverURL string+ loginPath string+ apiKey string+ mu sync.Mutex+}++func newLicenseAPI(serverURL, loginPath, apiKey, region string) *licenseAPI {+ api := &licenseAPI{+ serverURL: serverURL,+ loginPath: loginPath,+ apiKey: apiKey,+ }++ api.client = resty.New().+ SetBaseURL(serverURL).+ SetTimeout(35 * time.Second)++ if region != "" {+ api.client.SetHeader("x-region", region)+ }++ return api+}++// refreshToken authenticates with the license server and stores the token.+func (api *licenseAPI) refreshToken(ctx context.Context) (string, error) {+ api.mu.Lock()+ defer api.mu.Unlock()++ var result struct {+ Token string `json:"token"`+ }++ resp, err := resty.New().R().+ SetContext(ctx).+ SetHeader("X-API-KEY", api.apiKey).+ SetResult(&result).+ Post(api.serverURL + api.loginPath)+ if err != nil {+ return "", fmt.Errorf("license token refresh: %w", err)+ }+ if resp.IsError() {+ return "", fmt.Errorf("license token refresh: status %d", resp.StatusCode())+ }++ api.client.SetAuthToken(result.Token)+ return result.Token, nil+}++// get performs a GET with a single retry on 401/403 (token refresh).+func (api *licenseAPI) get(ctx context.Context, path string, result any) error {+ resp, err := api.client.R().SetContext(ctx).SetResult(result).Get(path)+ if err != nil {+ return err+ }++ if resp.StatusCode() == 401 || resp.StatusCode() == 403 {+ if _, refreshErr := api.refreshToken(ctx); refreshErr != nil {+ return refreshErr+ }+ resp, err = api.client.R().SetContext(ctx).SetResult(result).Get(path)+ if err != nil {+ return err+ }+ }++ if resp.IsError() {+ return fmt.Errorf("license server GET %s: status %d", path, resp.StatusCode())+ }+ return nil+}diff --git a/backend-go/internal/services/license/dal.go b/backend-go/internal/services/license/dal.godeleted file mode 100644index 950a56eb76..0000000000--- a/backend-go/internal/services/license/dal.go+++ /dev/null@@ -1,66 +0,0 @@-package license--import (- "context"- "database/sql"- "errors"-- "github.com/go-jet/jet/v2/postgres"- "github.com/go-jet/jet/v2/qrm"-- "github.com/infisical/api/internal/database/pg"- "github.com/infisical/api/internal/database/pg/gen/table"-)--type orgRow struct {- ID string `alias:"organizations.id"`- CustomerID sql.NullString `alias:"organizations.customerId"`- RootOrgID sql.NullString `alias:"organizations.rootOrgId"`-}--type DAL struct {- db pg.DB-}--func NewDAL(db pg.DB) *DAL {- return &DAL{db: db}-}--// FindRootOrgDetails resolves the root org for the given orgID and returns its customer ID.-// If the org has a rootOrgId, the root org is returned instead.-func (d *DAL) FindRootOrgDetails(ctx context.Context, orgID string) (*orgRow, error) {- o := table.Organizations-- // First fetch the org to check if it has a rootOrgId.- stmt := postgres.SELECT(o.ID, o.CustomerId, o.RootOrgId).- FROM(o).- WHERE(o.ID.EQ(postgres.String(orgID)))-- var row orgRow- err := stmt.QueryContext(ctx, d.db.Primary(), &row)- if err != nil {- if errors.Is(err, qrm.ErrNoRows) {- return nil, nil- }- return nil, err- }-- // If the org has a root org, resolve it.- if row.RootOrgID.Valid && row.RootOrgID.String != "" && row.RootOrgID.String != row.ID {- rootStmt := postgres.SELECT(o.ID, o.CustomerId, o.RootOrgId).- FROM(o).- WHERE(o.ID.EQ(postgres.String(row.RootOrgID.String)))-- var rootRow orgRow- err := rootStmt.QueryContext(ctx, d.db.Primary(), &rootRow)- if err != nil {- if errors.Is(err, qrm.ErrNoRows) {- return nil, nil- }- return nil, err- }- return &rootRow, nil- }-- return &row, nil-}diff --git a/backend-go/internal/services/license/license.go b/backend-go/internal/services/license/license.goindex 0f45b7db07..e88929e87a 100644--- a/backend-go/internal/services/license/license.go+++ b/backend-go/internal/services/license/license.go@@ -2,16 +2,18 @@ package licenseimport ("context"+ "database/sql""encoding/base64""encoding/json"+ "errors""fmt""log/slog"- "sync""time"- "github.com/go-resty/resty/v2"+ "github.com/jackc/pgx/v5""github.com/infisical/api/internal/config"+ "github.com/infisical/api/internal/database/pg")const (@@ -29,86 +31,6 @@ type keyStore interface {DeleteItem(ctx context.Context, key string) (int64, error)}-// dal is the narrow interface for org lookups needed by getPlan.-type dal interface {- FindRootOrgDetails(ctx context.Context, orgID string) (*orgRow, error)-}--// licenseAPI wraps a resty client with token-based auth and auto-refresh.-type licenseAPI struct {- client *resty.Client- serverURL string- loginPath string- apiKey string- mu sync.Mutex-}--func newLicenseAPI(serverURL, loginPath, apiKey, region string) *licenseAPI {- api := &licenseAPI{- serverURL: serverURL,- loginPath: loginPath,- apiKey: apiKey,- }-- api.client = resty.New().- SetBaseURL(serverURL).- SetTimeout(35 * time.Second)-- if region != "" {- api.client.SetHeader("x-region", region)- }-- return api-}--// refreshToken authenticates with the license server and stores the token.-func (api *licenseAPI) refreshToken(ctx context.Context) (string, error) {- api.mu.Lock()- defer api.mu.Unlock()-- var result struct {- Token string `json:"token"`- }-- resp, err := resty.New().R().- SetContext(ctx).- SetHeader("X-API-KEY", api.apiKey).- SetResult(&result).- Post(api.serverURL + api.loginPath)- if err != nil {- return "", fmt.Errorf("license token refresh: %w", err)- }- if resp.IsError() {- return "", fmt.Errorf("license token refresh: status %d", resp.StatusCode())- }-- api.client.SetAuthToken(result.Token)- return result.Token, nil-}--// get performs a GET with a single retry on 401/403 (token refresh).-func (api *licenseAPI) get(ctx context.Context, path string, result any) error {- resp, err := api.client.R().SetContext(ctx).SetResult(result).Get(path)- if err != nil {- return err- }-- if resp.StatusCode() == 401 || resp.StatusCode() == 403 {- if _, refreshErr := api.refreshToken(ctx); refreshErr != nil {- return refreshErr- }- resp, err = api.client.R().SetContext(ctx).SetResult(result).Get(path)- if err != nil {- return err- }- }-- if resp.IsError() {- return fmt.Errorf("license server GET %s: status %d", path, resp.StatusCode())- }- return nil-}-const syncInterval = 10 * time.Minute// Service manages license validation and feature gating.@@ -119,8 +41,8 @@ type Service struct {onPremFeatures FeatureSetofflineLicense *OfflineLicenseInfo+ db pg.DBkeyStore keyStore- dal dalcloudAPI *licenseAPIonPremAPI *licenseAPI@@ -130,16 +52,16 @@ type Service struct {// Deps holds the dependencies for the license shared service.type Deps struct {Config *config.Config+ DB pg.DBKeyStore keyStore- DAL dal}func NewService(ctx context.Context, logger *slog.Logger, deps Deps) *Service {svc := &Service{logger: logger.With(slog.String("svc", "license")),onPremFeatures: DefaultFeatures(),+ db: deps.DB,keyStore: deps.KeyStore,- dal: deps.DAL,}serverURL := deps.Config.LicenseServerURL@@ -301,6 +223,49 @@ func (s *Service) syncOnPremFeatures(ctx context.Context) error {return nil}+// orgDetails holds the org fields needed for license lookups.+type orgDetails struct {+ ID string+ CustomerID sql.Null[string]+ RootOrgID sql.Null[string]+}++// findRootOrgDetails resolves the root org for the given orgID and returns its customer ID.+// If the org has a rootOrgId, the root org is returned instead.+func (s *Service) findRootOrgDetails(ctx context.Context, orgID string) (*orgDetails, error) {+ query := `SELECT id, customer_id, root_org_id FROM organizations WHERE id = @orgID`+ args := pgx.NamedArgs{"orgID": orgID}++ row := s.db.Primary().QueryRow(ctx, query, args)++ var org orgDetails+ err := row.Scan(&org.ID, &org.CustomerID, &org.RootOrgID)+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, fmt.Errorf("findRootOrgDetails: %w", err)+ }++ // If the org has a root org, resolve it.+ if org.RootOrgID.Valid && org.RootOrgID.V != "" && org.RootOrgID.V != org.ID {+ args["orgID"] = org.RootOrgID.V+ row = s.db.Primary().QueryRow(ctx, query, args)++ var rootOrg orgDetails+ err := row.Scan(&rootOrg.ID, &rootOrg.CustomerID, &rootOrg.RootOrgID)+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, fmt.Errorf("findRootOrgDetails (root): %w", err)+ }+ return &rootOrg, nil+ }++ return &org, nil+}+// GetPlan returns the feature set for a given organization.// For cloud instances it uses Redis caching + license server API.// For on-prem instances it returns the in-memory feature set.@@ -321,18 +286,18 @@ func (s *Service) GetPlan(ctx context.Context, orgID string) (*FeatureSet, error}// Cache miss — fetch from license server.- org, err := s.dal.FindRootOrgDetails(ctx, orgID)+ org, err := s.findRootOrgDetails(ctx, orgID)if err != nil {return s.fallbackPlan(ctx, cacheKey), nil //nolint:nilerr // intentional fallback on DB error}- if org == nil || !org.CustomerID.Valid || org.CustomerID.String == "" {+ if org == nil || !org.CustomerID.Valid || org.CustomerID.V == "" {return s.fallbackPlan(ctx, cacheKey), nil}var resp struct {CurrentPlan FeatureSet `json:"currentPlan"`}- endpoint := fmt.Sprintf("/api/license-server/v1/customers/%s/cloud-plan", org.CustomerID.String)+ endpoint := fmt.Sprintf("/api/license-server/v1/customers/%s/cloud-plan", org.CustomerID.V)if err := s.cloudAPI.get(ctx, endpoint, &resp); err != nil {s.logger.ErrorContext(ctx, "failed to fetch cloud plan", slog.String("orgID", orgID), slog.Any("error", err))return s.fallbackPlan(ctx, cacheKey), nil