Skip to content

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

feat: switch tree look ups to csr based setup and simplified the functions for secrets

=b712dac5e3d1
diff --git a/backend-go/internal/services/secretmanager/secret/get_secret_by_name.go b/backend-go/internal/services/secretmanager/secret/get_secret_by_name.go
index 37bcc3e30c..6695f74bad 100644
--- a/backend-go/internal/services/secretmanager/secret/get_secret_by_name.go
+++ b/backend-go/internal/services/secretmanager/secret/get_secret_by_name.go
@@ -2,10 +2,8 @@ package secret
import (
"context"
- "errors"
"github.com/google/uuid"
- "github.com/jackc/pgx/v5"
"github.com/infisical/api/internal/libs/errutil"
"github.com/infisical/api/internal/services/kms"
@@ -33,27 +31,25 @@ type GetSecretByNameResult struct {
// GetSecretByName retrieves a single secret by name with full processing.
func (s *Service) GetSecretByName(ctx context.Context, opts *GetSecretByNameOpts) (*GetSecretByNameResult, error) {
- // 1. Get starting environment by slug
- envID, err := s.getEnvBySlug(ctx, opts.ProjectID, opts.Environment)
+ // 1. Load all folders for project
+ folderLookup, err := s.secretFolderService.LoadFolders(ctx, opts.ProjectID, nil)
if err != nil {
- if errors.Is(err, pgx.ErrNoRows) {
- return nil, errutil.NotFound("Environment not found")
- }
- return nil, errutil.DatabaseErr("Failed to load environment").WithErrf("GetSecretByName: %w", err)
+ return nil, errutil.DatabaseErr("Failed to load folders").WithErrf("GetSecretByName: %w", err)
}
- // 2. Load folder
- folderLookup, err := s.secretFolderService.LoadProjectFolders(ctx, opts.ProjectID, []uuid.UUID{envID})
- if err != nil {
- return nil, errutil.DatabaseErr("Failed to load folders").WithErrf("GetSecretByName: %w", err)
+ // 2. Get starting environment by slug (every env has a root folder)
+ envID, ok := folderLookup.GetEnvIDBySlug(opts.Environment)
+ if !ok {
+ return nil, errutil.NotFound("Environment not found")
}
+ // 3. Get folder
folderNode, ok := folderLookup.GetByPath(envID, opts.SecretPath)
if !ok {
return nil, errutil.NotFound("Folder not found")
}
- // 3. Get cipher pair
+ // 4. Get cipher pair
cipherPair, err := s.kmsService.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
Type: kms.DataKeyProject,
ProjectID: opts.ProjectID,
@@ -62,7 +58,7 @@ func (s *Service) GetSecretByName(ctx context.Context, opts *GetSecretByNameOpts
return nil, errutil.InternalServer("Failed to get decryption key").WithErrf("GetSecretByName: %w", err)
}
- // 4. Find secret
+ // 5. Find secret
secretType := opts.SecretType
if secretType == "" {
secretType = "shared"
@@ -76,30 +72,39 @@ func (s *Service) GetSecretByName(ctx context.Context, opts *GetSecretByNameOpts
secretEnv := opts.Environment
secretPath := opts.SecretPath
- // 5. Search imports if not found
+ // 6. Search imports if not found
+ var importLookup *secretimport.ImportLookup
+ var allImports []secretimport.ResolvedImport
+
if foundSecret == nil && opts.IncludeImports {
- importLookup, err := s.secretImportService.LoadProjectImports(ctx, opts.ProjectID)
+ importLookup, err = s.secretImportService.LoadProjectImports(ctx, opts.ProjectID)
if err != nil {
return nil, errutil.DatabaseErr("Failed to load imports").WithErrf("GetSecretByName: %w", err)
}
- chainResolver := secretimport.NewChainResolver(importLookup, s.secretFolderService)
- chainResult, err := chainResolver.Resolve(ctx, opts.ProjectID, envID, opts.SecretPath, false)
- if err == nil && len(chainResult.Imports) > 0 {
- folderLookup.Merge(chainResult.FolderLookup)
+ // Resolve import chain
+ resolveFolder := func(envID uuid.UUID, path string) (uuid.UUID, bool) {
+ node, ok := folderLookup.GetByPath(envID, path)
+ if !ok {
+ return uuid.Nil, false
+ }
+ return node.ID, true
+ }
- for i := len(chainResult.Imports) - 1; i >= 0; i-- {
- imp := &chainResult.Imports[i]
- importedSecret, err := s.FindByKey(ctx, imp.FolderID, opts.SecretName, secretType, opts.UserID)
- if err != nil {
- continue
- }
- if importedSecret != nil {
- foundSecret = importedSecret
- secretEnv, _ = folderLookup.GetEnvSlug(imp.EnvID)
- secretPath = imp.Path
- break
- }
+ allImports = importLookup.ResolveChain(folderNode.ID, resolveFolder)
+
+ // Search imports in reverse order (later imports have higher priority)
+ for i := len(allImports) - 1; i >= 0; i-- {
+ imp := &allImports[i]
+ importedSecret, err := s.FindByKey(ctx, imp.FolderID, opts.SecretName, secretType, opts.UserID)
+ if err != nil {
+ continue
+ }
+ if importedSecret != nil {
+ foundSecret = importedSecret
+ secretEnv, _ = folderLookup.GetEnvSlug(imp.EnvID)
+ secretPath = imp.Path
+ break
}
}
}
@@ -108,7 +113,7 @@ func (s *Service) GetSecretByName(ctx context.Context, opts *GetSecretByNameOpts
return nil, errutil.NotFound("Secret not found")
}
- // 6. Check permissions
+ // 7. Check permissions
tagSlugs := make([]string, len(foundSecret.Tags))
for i, tag := range foundSecret.Tags {
tagSlugs[i] = tag.Slug
@@ -126,7 +131,7 @@ func (s *Service) GetSecretByName(ctx context.Context, opts *GetSecretByNameOpts
}
}
- // 7. Decrypt value and comment
+ // 8. Decrypt value and comment
valueHidden := !opts.ViewSecretValue
if opts.AccessChecker != nil {
canReadValue := opts.AccessChecker.CanReadSecretValue(secretEnv, secretPath, foundSecret.Key, tagSlugs)
@@ -147,23 +152,29 @@ func (s *Service) GetSecretByName(ctx context.Context, opts *GetSecretByNameOpts
ValueHidden: valueHidden,
}
- // 8. Expand references if requested
+ // 9. Expand references if requested
if opts.ExpandSecretReferences && !valueHidden && rawValue != "" {
- importLookup, err := s.secretImportService.LoadProjectImports(ctx, opts.ProjectID)
- if err != nil {
- return nil, errutil.InternalServer("Failed to load imports for expansion").WithErrf("GetSecretByName: %w", err)
- }
- chainResolver := secretimport.NewChainResolver(importLookup, s.secretFolderService)
- chainResult, err := chainResolver.Resolve(ctx, opts.ProjectID, envID, opts.SecretPath, false)
- if err != nil {
- return nil, errutil.InternalServer("Failed to resolve import chain for expansion").WithErrf("GetSecretByName: %w", err)
+ // Load imports if not already loaded
+ if importLookup == nil {
+ importLookup, err = s.secretImportService.LoadProjectImports(ctx, opts.ProjectID)
+ if err != nil {
+ return nil, errutil.InternalServer("Failed to load imports for expansion").WithErrf("GetSecretByName: %w", err)
+ }
+
+ resolveFolder := func(envID uuid.UUID, path string) (uuid.UUID, bool) {
+ node, ok := folderLookup.GetByPath(envID, path)
+ if !ok {
+ return uuid.Nil, false
+ }
+ return node.ID, true
+ }
+ allImports = importLookup.ResolveChain(folderNode.ID, resolveFolder)
}
- folderLookup.Merge(chainResult.FolderLookup)
- // Always fetch from same folder + imported folders for relative ref resolution
+ // Fetch context secrets from same folder + imported folders
allFolderIDs := []uuid.UUID{folderNode.ID}
- if len(chainResult.Imports) > 0 {
- allFolderIDs = append(allFolderIDs, chainResult.ImportedFolderIDs()...)
+ for _, imp := range allImports {
+ allFolderIDs = append(allFolderIDs, imp.FolderID)
}
// Build list of secrets for expansion: main secret + context secrets
@@ -185,10 +196,10 @@ func (s *Service) GetSecretByName(ctx context.Context, opts *GetSecretByNameOpts
ctxPath := secretPath
if sec.FolderID != folderNode.ID {
// This is from an imported folder
- for i := range chainResult.Imports {
- if chainResult.Imports[i].FolderID == sec.FolderID {
- ctxEnvSlug, _ = folderLookup.GetEnvSlug(chainResult.Imports[i].EnvID)
- ctxPath = chainResult.Imports[i].Path
+ for j := range allImports {
+ if allImports[j].FolderID == sec.FolderID {
+ ctxEnvSlug, _ = folderLookup.GetEnvSlug(allImports[j].EnvID)
+ ctxPath = allImports[j].Path
break
}
}
@@ -228,7 +239,6 @@ func (s *Service) GetSecretByName(ctx context.Context, opts *GetSecretByNameOpts
if expander.HasDeniedRefs() {
return nil, errutil.Forbidden("Permission denied for secret reference expansion").WithErrf("GetSecretByName: denied refs: %v", expander.DeniedRefs())
}
- // resultSecret.Value is already expanded in place
}
return &GetSecretByNameResult{
diff --git a/backend-go/internal/services/secretmanager/secret/list_secrets.go b/backend-go/internal/services/secretmanager/secret/list_secrets.go
index 81d8a352c8..36f93ab9cc 100644
--- a/backend-go/internal/services/secretmanager/secret/list_secrets.go
+++ b/backend-go/internal/services/secretmanager/secret/list_secrets.go
@@ -2,11 +2,8 @@ package secret
import (
"context"
- "errors"
- "log/slog"
"github.com/google/uuid"
- "github.com/jackc/pgx/v5"
"github.com/infisical/api/internal/libs/errutil"
"github.com/infisical/api/internal/services/kms"
@@ -53,30 +50,73 @@ type ListSecretsResult struct {
// ListSecrets retrieves secrets for a project/environment/path with full processing.
func (s *Service) ListSecrets(ctx context.Context, opts *ListSecretsOpts) (*ListSecretsResult, error) {
- // 1. Get starting environment by slug
- envID, err := s.getEnvBySlug(ctx, opts.ProjectID, opts.Environment)
+ // 1. Load all folders for project
+ folderLookup, err := s.secretFolderService.LoadFolders(ctx, opts.ProjectID, nil)
if err != nil {
- if errors.Is(err, pgx.ErrNoRows) {
- return nil, errutil.NotFound("Environment not found")
+ return nil, errutil.DatabaseErr("Failed to load folders").WithErrf("ListSecrets: %w", err)
+ }
+
+ // 2. Get starting environment by slug (every env has a root folder)
+ envID, ok := folderLookup.GetEnvIDBySlug(opts.Environment)
+ if !ok {
+ return nil, errutil.NotFound("Environment not found")
+ }
+
+ // 3. Resolve direct folders
+ var directFolderIDs []uuid.UUID
+ directPaths := make(map[uuid.UUID]string)
+
+ if opts.Recursive {
+ nodes, ok := folderLookup.GetSubTree(envID, opts.SecretPath)
+ if !ok || len(nodes) == 0 {
+ return nil, errutil.NotFound("Folder not found").WithErrf("ListSecrets: path=%s", opts.SecretPath)
+ }
+ for _, node := range nodes {
+ directFolderIDs = append(directFolderIDs, node.ID)
+ directPaths[node.ID] = node.GetPath()
+ }
+ } else {
+ node, ok := folderLookup.GetByPath(envID, opts.SecretPath)
+ if !ok {
+ return nil, errutil.NotFound("Folder not found").WithErrf("ListSecrets: path=%s", opts.SecretPath)
}
- return nil, errutil.DatabaseErr("Failed to load environment").WithErrf("ListSecrets: %w", err)
+ directFolderIDs = []uuid.UUID{node.ID}
+ directPaths[node.ID] = opts.SecretPath
}
- // 2. Load imports
+ // 4. Load imports and resolve chain
importLookup, err := s.secretImportService.LoadProjectImports(ctx, opts.ProjectID)
if err != nil {
return nil, errutil.DatabaseErr("Failed to load imports").WithErrf("ListSecrets: %w", err)
}
- // 3. Resolve folder chain (lazy-loads folders for imported envs)
- chainResolver := secretimport.NewChainResolver(importLookup, s.secretFolderService)
- chainResult, err := chainResolver.Resolve(ctx, opts.ProjectID, envID, opts.SecretPath, opts.Recursive)
- if err != nil {
- return nil, errutil.NotFound("Folder not found").WithErrf("ListSecrets: %w", err)
+ // Resolve import chain using folder lookup
+ resolveFolder := func(envID uuid.UUID, path string) (uuid.UUID, bool) {
+ node, ok := folderLookup.GetByPath(envID, path)
+ if !ok {
+ return uuid.Nil, false
+ }
+ return node.ID, true
+ }
+
+ var allImports []secretimport.ResolvedImport
+ visitedImports := make(map[uuid.UUID]bool)
+ for _, folderID := range directFolderIDs {
+ imports := importLookup.ResolveChain(folderID, resolveFolder)
+ for _, imp := range imports {
+ if !visitedImports[imp.FolderID] {
+ visitedImports[imp.FolderID] = true
+ allImports = append(allImports, imp)
+ }
+ }
}
- // 4. Fetch secrets from all folders
- allFolderIDs := chainResult.AllFolderIDs()
+ // 5. Fetch secrets from all folders
+ allFolderIDs := make([]uuid.UUID, 0, len(directFolderIDs)+len(allImports))
+ allFolderIDs = append(allFolderIDs, directFolderIDs...)
+ for _, imp := range allImports {
+ allFolderIDs = append(allFolderIDs, imp.FolderID)
+ }
var dalFilters *FindByFolderIdsFilter
if len(opts.TagSlugs) > 0 || len(opts.MetadataFilter) > 0 {
@@ -88,10 +128,10 @@ func (s *Service) ListSecrets(ctx context.Context, opts *ListSecretsOpts) (*List
secrets, err := s.FindByFolderIds(ctx, allFolderIDs, opts.UserID, dalFilters)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to load environments").WithErrf("ListSecrets: %w", err)
+ return nil, errutil.DatabaseErr("Failed to load secrets").WithErrf("ListSecrets: %w", err)
}
- // 5. Get cipher pair for decryption
+ // 6. Get cipher pair for decryption
cipherPair, err := s.kmsService.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
Type: kms.DataKeyProject,
ProjectID: opts.ProjectID,
@@ -100,14 +140,15 @@ func (s *Service) ListSecrets(ctx context.Context, opts *ListSecretsOpts) (*List
return nil, errutil.InternalServer("Failed to get decryption key").WithErrf("ListSecrets: %w", err)
}
- // 6. Process secrets with permission filtering
+ // 7. Process secrets with permission filtering
directSecrets, importedSecrets := s.processSecretsWithPermissions(
secrets,
- chainResult.DirectFolderIDs,
- chainResult.DirectPaths,
- chainResult.Imports,
+ directFolderIDs,
+ directPaths,
+ allImports,
opts.Environment,
- chainResult.FolderLookup,
+ folderLookup,
+ importLookup,
secretProcessorOpts{
ViewSecretValue: opts.ViewSecretValue,
AccessChecker: opts.AccessChecker,
@@ -117,14 +158,14 @@ func (s *Service) ListSecrets(ctx context.Context, opts *ListSecretsOpts) (*List
},
)
- // 7. Apply personal overrides behavior
+ // 8. Apply personal overrides behavior
directSecrets = filterByPersonalOverridesBehavior(directSecrets, opts.PersonalOverridesBehavior)
importedSecrets = filterByPersonalOverridesBehavior(importedSecrets, opts.PersonalOverridesBehavior)
- // 8. Expand secret references if requested
+ // 9. Expand secret references if requested
if opts.ExpandSecretReferences {
// Build expansion list: direct secrets first, then imported in reverse import order
- allSecrets := buildExpansionSecretList(directSecrets, importedSecrets, chainResult.Imports)
+ allSecrets := buildExpansionSecretList(directSecrets, importedSecrets, allImports)
var expansionUserID *uuid.UUID
if opts.ExpandPersonalOverrides &&
@@ -143,7 +184,7 @@ func (s *Service) ListSecrets(ctx context.Context, opts *ListSecretsOpts) (*List
FetchAbsoluteSecrets: func(refs []AbsoluteSecretRef) []*ProcessedSecret {
return s.fetchAbsoluteSecrets(ctx, refs, absoluteFetchOpts{
projectID: opts.ProjectID,
- folderLookup: chainResult.FolderLookup,
+ folderLookup: folderLookup,
cipherPair: cipherPair,
userID: expansionUserID,
})
@@ -154,14 +195,13 @@ func (s *Service) ListSecrets(ctx context.Context, opts *ListSecretsOpts) (*List
if expander.HasDeniedRefs() {
return nil, errutil.Forbidden("Permission denied for secret reference expansion").WithErrf("ListSecrets: denied refs: %v", expander.DeniedRefs())
}
- // Values are already expanded in place - no need to copy back
}
return &ListSecretsResult{
DirectSecrets: directSecrets,
ImportedSecrets: importedSecrets,
- Imports: chainResult.Imports,
- FolderLookup: chainResult.FolderLookup,
+ Imports: allImports,
+ FolderLookup: folderLookup,
}, nil
}
@@ -182,6 +222,7 @@ func (s *Service) processSecretsWithPermissions(
imports []secretimport.ResolvedImport,
requestedEnv string,
folderLookup *secretfolder.FolderLookup,
+ importLookup *secretimport.ImportLookup,
opts secretProcessorOpts,
) (directSecrets, importedSecrets []ProcessedSecret) {
directFolderSet := make(map[uuid.UUID]bool, len(directFolderIDs))
@@ -209,7 +250,7 @@ func (s *Service) processSecretsWithPermissions(
secretPath = imp.Path
envSlug, _ = folderLookup.GetEnvSlug(imp.EnvID)
isImported = true
- importFolderID = imp.Import.FolderID
+ importFolderID = importLookup.FolderID(imp.ImportIdx)
importEnv = envSlug
importPath = imp.Path
} else {
@@ -347,45 +388,7 @@ func (s *Service) fetchAbsoluteSecrets(ctx context.Context, refs []AbsoluteSecre
return nil
}
- // First pass: collect unique slugs that aren't in FolderLookup yet
- var missingSlugs []string
- seenSlugs := make(map[string]bool)
- for i := range refs {
- slug := refs[i].Env
- if seenSlugs[slug] {
- continue
- }
- seenSlugs[slug] = true
-
- if _, ok := opts.folderLookup.GetEnvIDBySlug(slug); !ok {
- missingSlugs = append(missingSlugs, slug)
- }
- }
-
- // Batch fetch missing env IDs in a single query
- if len(missingSlugs) > 0 {
- slugToEnvID, err := s.getEnvsBySlugs(ctx, opts.projectID, missingSlugs)
- if err != nil {
- s.logger.WarnContext(ctx, "fetchAbsoluteSecrets: failed to get envs by slugs", slog.Any("error", err))
- return nil
- }
-
- var newEnvIDs []uuid.UUID
- for _, envID := range slugToEnvID {
- newEnvIDs = append(newEnvIDs, envID)
- }
-
- if len(newEnvIDs) > 0 {
- newLookup, err := s.secretFolderService.LoadProjectFolders(ctx, opts.projectID, newEnvIDs)
- if err != nil {
- s.logger.WarnContext(ctx, "fetchAbsoluteSecrets: failed to load project folders", slog.String("projectID", opts.projectID), slog.Any("error", err))
- return nil
- }
- opts.folderLookup.Merge(newLookup)
- }
- }
-
- // Second pass: build location map
+ // Build location map
type locationKey struct {
envID uuid.UUID
path string
@@ -425,7 +428,6 @@ func (s *Service) fetchAbsoluteSecrets(ctx context.Context, refs []AbsoluteSecre
rawSecrets, err := s.FindByFolderIds(ctx, folderIDs, opts.userID, nil)
if err != nil {
- s.logger.WarnContext(ctx, "fetchAbsoluteSecrets: failed to find secrets by folder IDs", slog.Any("error", err))
return nil
}
diff --git a/backend-go/internal/services/secretmanager/secret/secret.go b/backend-go/internal/services/secretmanager/secret/secret.go
index c2b20c5007..a8dae201d2 100644
--- a/backend-go/internal/services/secretmanager/secret/secret.go
+++ b/backend-go/internal/services/secretmanager/secret/secret.go
@@ -148,7 +148,7 @@ type ProcessedSecret struct {
// SecretFolderService loads folder hierarchies for a project.
type SecretFolderService interface {
- LoadProjectFolders(ctx context.Context, projectID string, envIDs []uuid.UUID) (*secretfolder.FolderLookup, error)
+ LoadFolders(ctx context.Context, projectID string, envIDs []uuid.UUID) (*secretfolder.FolderLookup, error)
}
// SecretImportService loads import configurations for a project.
@@ -491,47 +491,6 @@ func scanSecretRow(row pgx.CollectableRow) (Secret, error) {
return secret, nil
}
-// --- Environment Lookup Methods ---
-
-// getEnvBySlug fetches a single environment ID by project ID and slug.
-func (s *Service) getEnvBySlug(ctx context.Context, projectID, slug string) (uuid.UUID, error) {
- query := `SELECT id FROM project_environments WHERE "projectId" = @projectID AND slug = @slug`
- args := pgx.NamedArgs{"projectID": projectID, "slug": slug}
-
- var envID uuid.UUID
- err := s.db.Replica().QueryRow(ctx, query, args).Scan(&envID)
- return envID, err
-}
-
-// getEnvsBySlugs fetches environment IDs for multiple slugs in a single query.
-// Returns a map of slug -> envID for found environments.
-func (s *Service) getEnvsBySlugs(ctx context.Context, projectID string, slugs []string) (map[string]uuid.UUID, error) {
- if len(slugs) == 0 {
- return nil, nil
- }
-
- query := `SELECT id, slug FROM project_environments WHERE "projectId" = @projectID AND slug = ANY(@slugs)`
- args := pgx.NamedArgs{"projectID": projectID, "slugs": slugs}
-
- rows, err := s.db.Replica().Query(ctx, query, args)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- result := make(map[string]uuid.UUID)
- for rows.Next() {
- var envID uuid.UUID
- var slug string
- if err := rows.Scan(&envID, &slug); err != nil {
- return nil, err
- }
- result[slug] = envID
- }
-
- return result, rows.Err()
-}
-
// --- Decryption Helpers ---
// decryptSecretFields decrypts the value, comment, and metadata of a secret.
diff --git a/backend-go/internal/services/secretmanager/secretfolder/lookup.go b/backend-go/internal/services/secretmanager/secretfolder/lookup.go
index 9b823d8eab..b570103b85 100644
--- a/backend-go/internal/services/secretmanager/secretfolder/lookup.go
+++ b/backend-go/internal/services/secretmanager/secretfolder/lookup.go
@@ -1,148 +1,232 @@
package secretfolder
import (
- "maps"
"sort"
"strings"
"github.com/google/uuid"
)
-// FolderNode is a single folder in the tree.
+// FolderNode is returned from lookups - provides read-only access to folder data.
type FolderNode struct {
- ID uuid.UUID
- Name string
- parent *FolderNode
- children map[string]*FolderNode // nil on leaf nodes
+ ID uuid.UUID
+ Name string
+ path string
}
// GetPath returns the full path from root to this node (e.g. "/hello/world").
func (n *FolderNode) GetPath() string {
- var segments []string
- for cur := n; cur.parent != nil; cur = cur.parent {
- segments = append(segments, cur.Name)
- }
- for i, j := 0, len(segments)-1; i < j; i, j = i+1, j-1 {
- segments[i], segments[j] = segments[j], segments[i]
- }
- return "/" + strings.Join(segments, "/")
+ return n.path
}
-// FolderLookup is an in-memory folder tree for a project, scoped to requested environments.
+// FolderLookup is a CSR-based in-memory folder tree for a project.
type FolderLookup struct {
- byID map[uuid.UUID]*FolderNode
- envRoots map[uuid.UUID]*FolderNode // envID → root
- envSlugs map[uuid.UUID]string // envID → slug
+ // Folder data - parallel arrays
+ ids []uuid.UUID
+ names []string
+ parentIdx []int32
+
+ // CSR children: children of folder i are at childrenIdx[childStart[i]:childStart[i+1]]
+ childStart []int32
+ childrenIdx []int32
+
+ // Lookups
+ idToIdx map[uuid.UUID]int32
+ rootIdx map[uuid.UUID]int32 // envID -> root folder index
+
+ // Environment - single map
+ envSlugByID map[uuid.UUID]string
}
func newFolderLookup(rows []folderRow) *FolderLookup {
+ if len(rows) == 0 {
+ return &FolderLookup{
+ idToIdx: make(map[uuid.UUID]int32),
+ rootIdx: make(map[uuid.UUID]int32),
+ envSlugByID: make(map[uuid.UUID]string),
+ }
+ }
+
+ n := len(rows)
l := &FolderLookup{
- byID: make(map[uuid.UUID]*FolderNode, len(rows)),
- envRoots: make(map[uuid.UUID]*FolderNode),
- envSlugs: make(map[uuid.UUID]string),
+ ids: make([]uuid.UUID, n),
+ names: make([]string, n),
+ parentIdx: make([]int32, n),
+ childStart: make([]int32, n+1),
+ idToIdx: make(map[uuid.UUID]int32, n),
+ rootIdx: make(map[uuid.UUID]int32),
+ envSlugByID: make(map[uuid.UUID]string),
}
- // Pass 1: create all nodes.
- for _, r := range rows {
- l.byID[r.ID] = &FolderNode{
- ID: r.ID,
- Name: r.Name,
- }
+ // Build temporary ID -> row index map for parent resolution
+ rowIdxByID := make(map[uuid.UUID]int32, n)
+ for i, r := range rows {
+ rowIdxByID[r.ID] = int32(i)
}
- // Pass 2: link parent ↔ children, identify roots, collect env slugs.
- for _, r := range rows {
- node := l.byID[r.ID]
+ // Pass 1: populate parallel arrays
+ for i, r := range rows {
+ l.ids[i] = r.ID
+ l.names[i] = r.Name
+ l.idToIdx[r.ID] = int32(i)
+
if !r.ParentID.Valid {
- l.envRoots[r.EnvID] = node
- l.envSlugs[r.EnvID] = r.EnvSlug
- continue
+ l.parentIdx[i] = -1
+ l.rootIdx[r.EnvID] = int32(i)
+ l.envSlugByID[r.EnvID] = r.EnvSlug
+ } else {
+ l.parentIdx[i] = rowIdxByID[r.ParentID.V]
}
- if p, ok := l.byID[r.ParentID.V]; ok {
- node.parent = p
- if p.children == nil {
- p.children = make(map[string]*FolderNode, 4)
- }
- p.children[node.Name] = node
+ }
+
+ // Pass 2: count children per node
+ childCount := make([]int32, n)
+ for i := range n {
+ if l.parentIdx[i] != -1 {
+ childCount[l.parentIdx[i]]++
+ }
+ }
+
+ // Pass 3: build childStart (prefix sum)
+ l.childStart[0] = 0
+ for i := range n {
+ l.childStart[i+1] = l.childStart[i] + childCount[i]
+ }
+
+ // Pass 4: populate childrenIdx
+ totalChildren := l.childStart[n]
+ l.childrenIdx = make([]int32, totalChildren)
+ insertPos := make([]int32, n)
+ copy(insertPos, l.childStart[:n])
+
+ for i := int32(0); i < int32(n); i++ {
+ if l.parentIdx[i] != -1 {
+ parent := l.parentIdx[i]
+ l.childrenIdx[insertPos[parent]] = i
+ insertPos[parent]++
+ }
+ }
+
+ // Pass 5: sort children by name for each node
+ for i := range n {
+ start := l.childStart[i]
+ end := l.childStart[i+1]
+ if end > start {
+ children := l.childrenIdx[start:end]
+ sort.Slice(children, func(a, b int) bool {
+ return l.names[children[a]] < l.names[children[b]]
+ })
}
}
return l
}
-// GetByPath resolves envID + path (e.g. "/hello/world") to a node.
+// getPath computes path for a folder index.
+func (l *FolderLookup) getPath(idx int32) string {
+ if idx < 0 || int(idx) >= len(l.ids) {
+ return ""
+ }
+
+ var segments []string
+ for cur := idx; l.parentIdx[cur] != -1; cur = l.parentIdx[cur] {
+ segments = append(segments, l.names[cur])
+ }
+
+ // Reverse segments
+ for i, j := 0, len(segments)-1; i < j; i, j = i+1, j-1 {
+ segments[i], segments[j] = segments[j], segments[i]
+ }
+
+ return "/" + strings.Join(segments, "/")
+}
+
+// toNode converts an index to a FolderNode.
+func (l *FolderLookup) toNode(idx int32) *FolderNode {
+ return &FolderNode{
+ ID: l.ids[idx],
+ Name: l.names[idx],
+ path: l.getPath(idx),
+ }
+}
+
+// GetByPath resolves envID + path to a node.
func (l *FolderLookup) GetByPath(envID uuid.UUID, path string) (*FolderNode, bool) {
- root, ok := l.envRoots[envID]
+ rootIdx, ok := l.rootIdx[envID]
if !ok {
return nil, false
}
- return walkPath(root, path)
+
+ segments := splitPath(path)
+ idx := rootIdx
+
+ for _, seg := range segments {
+ found := false
+ children := l.childrenIdx[l.childStart[idx]:l.childStart[idx+1]]
+ for _, childIdx := range children {
+ if l.names[childIdx] == seg {
+ idx = childIdx
+ found = true
+ break
+ }
+ }
+ if !found {
+ return nil, false
+ }
+ }
+
+ return l.toNode(idx), true
}
// GetByID returns the node for the given folder ID.
func (l *FolderLookup) GetByID(folderID uuid.UUID) (*FolderNode, bool) {
- node, ok := l.byID[folderID]
- return node, ok
+ idx, ok := l.idToIdx[folderID]
+ if !ok {
+ return nil, false
+ }
+ return l.toNode(idx), true
}
// GetPathByID returns the full path for a folder ID.
func (l *FolderLookup) GetPathByID(id uuid.UUID) (string, bool) {
- node, ok := l.byID[id]
+ idx, ok := l.idToIdx[id]
if !ok {
return "", false
}
- return node.GetPath(), true
+ return l.getPath(idx), true
}
-// GetSubTree resolves envID + path to a node and returns it along
-// with all its descendants in depth-first pre-order (parent before children).
+// GetSubTree returns the node and all descendants in depth-first pre-order.
func (l *FolderLookup) GetSubTree(envID uuid.UUID, path string) ([]*FolderNode, bool) {
node, ok := l.GetByPath(envID, path)
if !ok {
return nil, false
}
- return collectTree(node), true
+
+ startIdx := l.idToIdx[node.ID]
+ return l.collectTree(startIdx), true
}
-func collectTree(root *FolderNode) []*FolderNode {
+func (l *FolderLookup) collectTree(rootIdx int32) []*FolderNode {
var result []*FolderNode
- stack := []*FolderNode{root}
+ stack := []int32{rootIdx}
for len(stack) > 0 {
- node := stack[len(stack)-1]
+ idx := stack[len(stack)-1]
stack = stack[:len(stack)-1]
- result = append(result, node)
-
- // Sort children by name, then push in reverse so that
- // alphabetically first child is popped first (DFS pre-order).
- names := make([]string, 0, len(node.children))
- for name := range node.children {
- names = append(names, name)
- }
- sort.Sort(sort.Reverse(sort.StringSlice(names)))
+ result = append(result, l.toNode(idx))
- for _, name := range names {
- stack = append(stack, node.children[name])
+ // Push children in reverse order so first child is popped first
+ children := l.childrenIdx[l.childStart[idx]:l.childStart[idx+1]]
+ for i := len(children) - 1; i >= 0; i-- {
+ stack = append(stack, children[i])
}
}
return result
}
-func walkPath(root *FolderNode, path string) (*FolderNode, bool) {
- segments := splitPath(path)
- node := root
- for _, seg := range segments {
- child, ok := node.children[seg]
- if !ok {
- return nil, false
- }
- node = child
- }
- return node, true
-}
-
func splitPath(p string) []string {
trimmed := strings.Trim(p, "/")
if trimmed == "" {
@@ -151,23 +235,15 @@ func splitPath(p string) []string {
return strings.Split(trimmed, "/")
}
-// Merge combines another FolderLookup into this one.
-// Used to add folders from additional environments after initial load.
-func (l *FolderLookup) Merge(other *FolderLookup) {
- maps.Copy(l.byID, other.byID)
- maps.Copy(l.envRoots, other.envRoots)
- maps.Copy(l.envSlugs, other.envSlugs)
-}
-
// GetEnvSlug returns the slug for the given environment ID.
func (l *FolderLookup) GetEnvSlug(envID uuid.UUID) (string, bool) {
- slug, ok := l.envSlugs[envID]
+ slug, ok := l.envSlugByID[envID]
return slug, ok
}
-// GetEnvIDBySlug returns the environment ID for the given slug.
+// GetEnvIDBySlug returns the environment ID for the given slug by iterating the map.
func (l *FolderLookup) GetEnvIDBySlug(slug string) (uuid.UUID, bool) {
- for id, s := range l.envSlugs {
+ for id, s := range l.envSlugByID {
if s == slug {
return id, true
}
@@ -177,6 +253,6 @@ func (l *FolderLookup) GetEnvIDBySlug(slug string) (uuid.UUID, bool) {
// HasEnv reports whether folders for the given environment have been loaded.
func (l *FolderLookup) HasEnv(envID uuid.UUID) bool {
- _, ok := l.envRoots[envID]
+ _, ok := l.rootIdx[envID]
return ok
}
diff --git a/backend-go/internal/services/secretmanager/secretfolder/service.go b/backend-go/internal/services/secretmanager/secretfolder/service.go
index e37830b6a5..4d69d8b854 100644
--- a/backend-go/internal/services/secretmanager/secretfolder/service.go
+++ b/backend-go/internal/services/secretmanager/secretfolder/service.go
@@ -8,6 +8,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/infisical/api/internal/database/pg"
+ "github.com/infisical/api/internal/database/pg/qb"
"github.com/infisical/api/internal/libs/errutil"
)
@@ -31,40 +32,42 @@ func NewService(deps *Deps) *Service {
return &Service{db: deps.DB}
}
-// LoadProjectFolders fetches folders for the given environments in a project and builds an in-memory lookup tree.
-func (s *Service) LoadProjectFolders(ctx context.Context, projectID string, envIDs []uuid.UUID) (*FolderLookup, error) {
- rows, err := s.getFoldersByProjectAndEnvIDs(ctx, projectID, envIDs)
+// LoadFolders loads folders for a project.
+// If envIDs is nil or empty, loads ALL folders for the project.
+// If envIDs is provided, loads only folders for those environments.
+func (s *Service) LoadFolders(ctx context.Context, projectID string, envIDs []uuid.UUID) (*FolderLookup, error) {
+ rows, err := s.getFolders(ctx, projectID, envIDs)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to get folders for project").WithErrf("LoadProjectFolders(projectId=%s): %w", projectID, err)
+ return nil, errutil.DatabaseErr("Failed to get folders").WithErrf("LoadFolders(projectId=%s): %w", projectID, err)
}
return newFolderLookup(rows), nil
}
-func (s *Service) getFoldersByProjectAndEnvIDs(ctx context.Context, projectID string, envIDs []uuid.UUID) ([]folderRow, error) {
+func (s *Service) getFolders(ctx context.Context, projectID string, envIDs []uuid.UUID) ([]folderRow, error) {
+ args := pgx.NamedArgs{"projectID": projectID}
+
+ where := qb.NewWhere().
+ Add(`env."projectId" = @projectID`).
+ AddIf(len(envIDs) > 0, `folder."envId" = ANY(@envIDs)`)
+
+ if len(envIDs) > 0 {
+ args["envIDs"] = envIDs
+ }
+
query := `
SELECT folder.id, folder.name, folder."parentId", folder."envId", env.slug
FROM secret_folders folder
INNER JOIN project_environments env ON folder."envId" = env.id
- WHERE env."projectId" = @projectID AND folder."envId" = ANY(@envIDs)
- `
- args := pgx.NamedArgs{
- "projectID": projectID,
- "envIDs": envIDs,
- }
+ WHERE ` + where.String()
rows, err := s.db.Replica().Query(ctx, query, args)
if err != nil {
return nil, err
}
- folders, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (folderRow, error) {
+ return pgx.CollectRows(rows, func(row pgx.CollectableRow) (folderRow, error) {
var f folderRow
err := row.Scan(&f.ID, &f.Name, &f.ParentID, &f.EnvID, &f.EnvSlug)
return f, err
})
- if err != nil {
- return nil, err
- }
-
- return folders, nil
}
diff --git a/backend-go/internal/services/secretmanager/secretimport/lookup.go b/backend-go/internal/services/secretmanager/secretimport/lookup.go
index 2a1de45e1c..fd9a521698 100644
--- a/backend-go/internal/services/secretmanager/secretimport/lookup.go
+++ b/backend-go/internal/services/secretmanager/secretimport/lookup.go
@@ -1,104 +1,235 @@
package secretimport
import (
+ "bytes"
"sort"
"github.com/google/uuid"
)
-// ImportEntry represents a single secret import configured on a folder.
-type ImportEntry struct {
- ID uuid.UUID
- FolderID uuid.UUID
- ImportPath string
- ImportEnvID uuid.UUID
- Position int32
- IsReplication bool
- IsReserved bool
-}
+const (
+ flagReplication = 1 << 0
+ flagReserved = 1 << 1
+)
-// importTarget is a composite key for the reverse index.
+// importTarget is a composite key for reverse lookups.
type importTarget struct {
envID uuid.UUID
path string
}
-// ImportLookup provides O(1) lookup of secret imports for a project.
-// Forward index: folder ID → imports configured on that folder (sorted by position).
-// Reverse index: (envID, path) → imports that reference this target.
+// ImportLookup provides efficient lookup of secret imports using CSR structure.
type ImportLookup struct {
- byFolderID map[uuid.UUID][]ImportEntry
- byID map[uuid.UUID]*ImportEntry
- byTarget map[importTarget][]*ImportEntry
+ // Parallel arrays - sorted by (folderID, position)
+ ids []uuid.UUID
+ folderIDs []uuid.UUID
+ targetEnvIDs []uuid.UUID
+ positions []int32
+ flags []uint8
+
+ // Path arena - deduplicated string storage
+ pathOffsets []uint32
+ pathLens []uint16
+ pathArena []byte
+
+ // Index: folder -> range in arrays
+ folderStart map[uuid.UUID]int32
+ folderEnd map[uuid.UUID]int32
+
+ // Index: ID -> array index (binary search)
+ idOrder []int32
+
+ // Reverse index (cold path)
+ byTarget map[importTarget][]int32
}
func newImportLookup(rows []importRow) *ImportLookup {
- l := &ImportLookup{
- byFolderID: make(map[uuid.UUID][]ImportEntry),
- byID: make(map[uuid.UUID]*ImportEntry, len(rows)),
- byTarget: make(map[importTarget][]*ImportEntry),
+ if len(rows) == 0 {
+ return &ImportLookup{
+ folderStart: make(map[uuid.UUID]int32),
+ folderEnd: make(map[uuid.UUID]int32),
+ byTarget: make(map[importTarget][]int32),
+ }
}
- // Group rows by folder ID.
- for _, r := range rows {
- entry := ImportEntry{
- ID: r.ID,
- FolderID: r.FolderID,
- ImportPath: r.ImportPath,
- ImportEnvID: r.ImportEnvID,
- Position: r.Position,
- IsReplication: r.IsReplication.Valid && r.IsReplication.V,
- IsReserved: r.IsReserved.Valid && r.IsReserved.V,
+ n := len(rows)
+
+ // Sort rows by (folderID, position)
+ sort.Slice(rows, func(i, j int) bool {
+ cmp := bytes.Compare(rows[i].FolderID[:], rows[j].FolderID[:])
+ if cmp != 0 {
+ return cmp < 0
}
- l.byFolderID[r.FolderID] = append(l.byFolderID[r.FolderID], entry)
+ return rows[i].Position < rows[j].Position
+ })
+
+ l := &ImportLookup{
+ ids: make([]uuid.UUID, n),
+ folderIDs: make([]uuid.UUID, n),
+ targetEnvIDs: make([]uuid.UUID, n),
+ positions: make([]int32, n),
+ flags: make([]uint8, n),
+ pathOffsets: make([]uint32, n),
+ pathLens: make([]uint16, n),
+ pathArena: make([]byte, 0, n*20), // estimate avg path length
+ folderStart: make(map[uuid.UUID]int32),
+ folderEnd: make(map[uuid.UUID]int32),
+ idOrder: make([]int32, n),
+ byTarget: make(map[importTarget][]int32),
}
- // Sort each folder's imports by position, then build secondary indexes.
- for folderID := range l.byFolderID {
- entries := l.byFolderID[folderID]
- sort.Slice(entries, func(i, j int) bool {
- return entries[i].Position < entries[j].Position
- })
- l.byFolderID[folderID] = entries
-
- for i := range entries {
- e := &entries[i]
- l.byID[e.ID] = e
- key := importTarget{envID: e.ImportEnvID, path: e.ImportPath}
- l.byTarget[key] = append(l.byTarget[key], e)
+ // Path interning map
+ pathPool := make(map[string]struct {
+ offset uint32
+ length uint16
+ })
+
+ // Populate parallel arrays
+ var currentFolder uuid.UUID
+ var currentStart int32
+
+ for i, r := range rows {
+ // Track folder ranges
+ if i == 0 || r.FolderID != currentFolder {
+ if i > 0 {
+ l.folderEnd[currentFolder] = int32(i)
+ }
+ currentFolder = r.FolderID
+ currentStart = int32(i)
+ l.folderStart[currentFolder] = currentStart
+ }
+
+ l.ids[i] = r.ID
+ l.folderIDs[i] = r.FolderID
+ l.targetEnvIDs[i] = r.ImportEnvID
+ l.positions[i] = r.Position
+
+ // Flags
+ var f uint8
+ if r.IsReplication.Valid && r.IsReplication.V {
+ f |= flagReplication
}
+ if r.IsReserved.Valid && r.IsReserved.V {
+ f |= flagReserved
+ }
+ l.flags[i] = f
+
+ // Intern path
+ if existing, ok := pathPool[r.ImportPath]; ok {
+ l.pathOffsets[i] = existing.offset
+ l.pathLens[i] = existing.length
+ } else {
+ offset := uint32(len(l.pathArena))
+ length := uint16(len(r.ImportPath))
+ l.pathArena = append(l.pathArena, r.ImportPath...)
+ l.pathOffsets[i] = offset
+ l.pathLens[i] = length
+ pathPool[r.ImportPath] = struct {
+ offset uint32
+ length uint16
+ }{offset, length}
+ }
+
+ // Build reverse index
+ key := importTarget{envID: r.ImportEnvID, path: r.ImportPath}
+ l.byTarget[key] = append(l.byTarget[key], int32(i))
}
+ // Close last folder range
+ if n > 0 {
+ l.folderEnd[currentFolder] = int32(n)
+ }
+
+ // Build sorted ID index for binary search
+ for i := range l.idOrder {
+ l.idOrder[i] = int32(i)
+ }
+ sort.Slice(l.idOrder, func(a, b int) bool {
+ return bytes.Compare(l.ids[l.idOrder[a]][:], l.ids[l.idOrder[b]][:]) < 0
+ })
+
return l
}
-// GetByFolderID returns imports for a folder, sorted by position (ascending).
-// Returns nil if the folder has no imports.
-func (l *ImportLookup) GetByFolderID(folderID uuid.UUID) []ImportEntry {
- return l.byFolderID[folderID]
+// Len returns the total number of imports.
+func (l *ImportLookup) Len() int {
+ return len(l.ids)
+}
+
+// ImportsOfFolder returns the range [start, end) of imports for a folder.
+// Returns (0, 0) if folder has no imports.
+func (l *ImportLookup) ImportsOfFolder(folderID uuid.UUID) (start, end int32) {
+ start, ok := l.folderStart[folderID]
+ if !ok {
+ return 0, 0
+ }
+ return start, l.folderEnd[folderID]
}
-// GetByID returns a single import entry by its ID.
-func (l *ImportLookup) GetByID(id uuid.UUID) (*ImportEntry, bool) {
- entry, ok := l.byID[id]
- return entry, ok
+// ID returns the import ID at index i.
+func (l *ImportLookup) ID(i int32) uuid.UUID {
+ return l.ids[i]
+}
+
+// FolderID returns the source folder ID at index i.
+func (l *ImportLookup) FolderID(i int32) uuid.UUID {
+ return l.folderIDs[i]
+}
+
+// TargetEnvID returns the target environment ID at index i.
+func (l *ImportLookup) TargetEnvID(i int32) uuid.UUID {
+ return l.targetEnvIDs[i]
+}
+
+// TargetPath returns the target path at index i.
+func (l *ImportLookup) TargetPath(i int32) string {
+ offset := l.pathOffsets[i]
+ length := l.pathLens[i]
+ return string(l.pathArena[offset : offset+uint32(length)])
+}
+
+// Position returns the position at index i.
+func (l *ImportLookup) Position(i int32) int32 {
+ return l.positions[i]
+}
+
+// IsReplication returns whether the import at index i is a replication.
+func (l *ImportLookup) IsReplication(i int32) bool {
+ return l.flags[i]&flagReplication != 0
+}
+
+// IsReserved returns whether the import at index i is reserved.
+func (l *ImportLookup) IsReserved(i int32) bool {
+ return l.flags[i]&flagReserved != 0
+}
+
+// IndexByID returns the array index for an import ID using binary search.
+// Returns (-1, false) if not found.
+func (l *ImportLookup) IndexByID(id uuid.UUID) (int32, bool) {
+ i := sort.Search(len(l.idOrder), func(k int) bool {
+ return bytes.Compare(l.ids[l.idOrder[k]][:], id[:]) >= 0
+ })
+ if i < len(l.idOrder) && l.ids[l.idOrder[i]] == id {
+ return l.idOrder[i], true
+ }
+ return -1, false
}
-// GetImportersOf returns all imports that reference the given env + path.
-// Useful for answering "which folders import from this location?".
-func (l *ImportLookup) GetImportersOf(envID uuid.UUID, path string) []*ImportEntry {
+// ImportersOf returns indices of imports that target the given env + path.
+// Returns nil if no imports target this location.
+func (l *ImportLookup) ImportersOf(envID uuid.UUID, path string) []int32 {
return l.byTarget[importTarget{envID: envID, path: path}]
}
const maxImportDepth = 10
-// ResolvedImport is a folder in the import chain with the import that led to it.
+// ResolvedImport represents a folder in the import chain.
type ResolvedImport struct {
- FolderID uuid.UUID
- Import ImportEntry
- Depth int
- EnvID uuid.UUID
- Path string
+ FolderID uuid.UUID
+ ImportIdx int32
+ Depth int
+ EnvID uuid.UUID
+ Path string
}
// ResolveChain walks the full import chain starting from a folder and returns
@@ -119,22 +250,27 @@ func (l *ImportLookup) ResolveChain(
return
}
- for _, entry := range l.GetByFolderID(folderID) {
- key := importTarget{envID: entry.ImportEnvID, path: entry.ImportPath}
+ start, end := l.ImportsOfFolder(folderID)
+ for i := start; i < end; i++ {
+ envID := l.TargetEnvID(i)
+ path := l.TargetPath(i)
+ key := importTarget{envID: envID, path: path}
if visited[key] {
continue
}
visited[key] = true
- resolvedID, ok := resolveFolder(entry.ImportEnvID, entry.ImportPath)
+ resolvedID, ok := resolveFolder(envID, path)
if !ok {
continue
}
result = append(result, ResolvedImport{
- FolderID: resolvedID,
- Import: entry,
- Depth: depth,
+ FolderID: resolvedID,
+ ImportIdx: i,
+ Depth: depth,
+ EnvID: envID,
+ Path: path,
})
walk(resolvedID, depth+1)
diff --git a/backend-go/internal/services/secretmanager/secretimport/lookup_test.go b/backend-go/internal/services/secretmanager/secretimport/lookup_test.go
index e01044133d..00f7d691ad 100644
--- a/backend-go/internal/services/secretmanager/secretimport/lookup_test.go
+++ b/backend-go/internal/services/secretmanager/secretimport/lookup_test.go
@@ -46,57 +46,59 @@ func buildTestImports() *ImportLookup {
}
// ---------------------------------------------------------------------------
-// GetByFolderID
+// ImportsOfFolder
// ---------------------------------------------------------------------------
-func TestGetByFolderID(t *testing.T) {
+func TestImportsOfFolder(t *testing.T) {
l := buildTestImports()
t.Run("returns imports sorted by position", func(t *testing.T) {
- entries := l.GetByFolderID(folderRoot)
- require.Len(t, entries, 2)
- assert.Equal(t, importID1, entries[0].ID)
- assert.Equal(t, int32(1), entries[0].Position)
- assert.Equal(t, importID2, entries[1].ID)
- assert.Equal(t, int32(2), entries[1].Position)
+ start, end := l.ImportsOfFolder(folderRoot)
+ require.Equal(t, int32(2), end-start)
+
+ assert.Equal(t, importID1, l.ID(start))
+ assert.Equal(t, int32(1), l.Position(start))
+ assert.Equal(t, importID2, l.ID(start+1))
+ assert.Equal(t, int32(2), l.Position(start+1))
})
t.Run("returns all fields correctly", func(t *testing.T) {
- entries := l.GetByFolderID(folderRoot)
- require.Len(t, entries, 2)
-
- assert.Equal(t, folderRoot, entries[0].FolderID)
- assert.Equal(t, "/", entries[0].ImportPath)
- assert.Equal(t, prodEnvID, entries[0].ImportEnvID)
- assert.False(t, entries[0].IsReplication)
- assert.False(t, entries[0].IsReserved)
+ start, end := l.ImportsOfFolder(folderRoot)
+ require.Equal(t, int32(2), end-start)
+
+ assert.Equal(t, folderRoot, l.FolderID(start))
+ assert.Equal(t, "/", l.TargetPath(start))
+ assert.Equal(t, prodEnvID, l.TargetEnvID(start))
+ assert.False(t, l.IsReplication(start))
+ assert.False(t, l.IsReserved(start))
})
t.Run("replication and reserved flags", func(t *testing.T) {
- entries := l.GetByFolderID(folderA)
- require.Len(t, entries, 2)
+ start, end := l.ImportsOfFolder(folderA)
+ require.Equal(t, int32(2), end-start)
- assert.True(t, entries[0].IsReplication)
- assert.False(t, entries[0].IsReserved)
+ assert.True(t, l.IsReplication(start))
+ assert.False(t, l.IsReserved(start))
- assert.False(t, entries[1].IsReplication)
- assert.True(t, entries[1].IsReserved)
+ assert.False(t, l.IsReplication(start+1))
+ assert.True(t, l.IsReserved(start+1))
})
t.Run("single import folder", func(t *testing.T) {
- entries := l.GetByFolderID(folderB)
- require.Len(t, entries, 1)
- assert.Equal(t, importID5, entries[0].ID)
- assert.Equal(t, "/a", entries[0].ImportPath)
+ start, end := l.ImportsOfFolder(folderB)
+ require.Equal(t, int32(1), end-start)
+ assert.Equal(t, importID5, l.ID(start))
+ assert.Equal(t, "/a", l.TargetPath(start))
})
- t.Run("folder with no imports returns nil", func(t *testing.T) {
- entries := l.GetByFolderID(uuid.MustParse("99999999-9999-9999-9999-999999999999"))
- assert.Nil(t, entries)
+ t.Run("folder with no imports returns empty range", func(t *testing.T) {
+ start, end := l.ImportsOfFolder(uuid.MustParse("99999999-9999-9999-9999-999999999999"))
+ assert.Equal(t, int32(0), start)
+ assert.Equal(t, int32(0), end)
})
}
-func TestGetByFolderID_PositionOrdering(t *testing.T) {
+func TestImportsOfFolder_PositionOrdering(t *testing.T) {
// Insert rows in reverse position order to verify sorting.
rows := []importRow{
{ID: importID3, ImportPath: "/c", ImportEnvID: devEnvID, Position: 3, FolderID: folderRoot},
@@ -105,66 +107,66 @@ func TestGetByFolderID_PositionOrdering(t *testing.T) {
}
l := newImportLookup(rows)
- entries := l.GetByFolderID(folderRoot)
- require.Len(t, entries, 3)
- assert.Equal(t, int32(1), entries[0].Position)
- assert.Equal(t, int32(2), entries[1].Position)
- assert.Equal(t, int32(3), entries[2].Position)
+ start, end := l.ImportsOfFolder(folderRoot)
+ require.Equal(t, int32(3), end-start)
+ assert.Equal(t, int32(1), l.Position(start))
+ assert.Equal(t, int32(2), l.Position(start+1))
+ assert.Equal(t, int32(3), l.Position(start+2))
}
// ---------------------------------------------------------------------------
-// GetByID
+// IndexByID
// ---------------------------------------------------------------------------
-func TestGetByID(t *testing.T) {
+func TestIndexByID(t *testing.T) {
l := buildTestImports()
t.Run("existing import", func(t *testing.T) {
- entry, ok := l.GetByID(importID3)
+ idx, ok := l.IndexByID(importID3)
require.True(t, ok)
- assert.Equal(t, importID3, entry.ID)
- assert.Equal(t, folderA, entry.FolderID)
- assert.True(t, entry.IsReplication)
+ assert.Equal(t, importID3, l.ID(idx))
+ assert.Equal(t, folderA, l.FolderID(idx))
+ assert.True(t, l.IsReplication(idx))
})
t.Run("nonexistent import", func(t *testing.T) {
- _, ok := l.GetByID(uuid.MustParse("99999999-9999-9999-9999-999999999999"))
+ _, ok := l.IndexByID(uuid.MustParse("99999999-9999-9999-9999-999999999999"))
assert.False(t, ok)
})
}
// ---------------------------------------------------------------------------
-// GetImportersOf
+// ImportersOf
// ---------------------------------------------------------------------------
-func TestGetImportersOf(t *testing.T) {
+func TestImportersOf(t *testing.T) {
l := buildTestImports()
t.Run("multiple folders import prod:/", func(t *testing.T) {
- importers := l.GetImportersOf(prodEnvID, "/")
+ importers := l.ImportersOf(prodEnvID, "/")
require.Len(t, importers, 2)
folderIDs := make(map[uuid.UUID]bool)
- for _, e := range importers {
- folderIDs[e.FolderID] = true
+ for _, idx := range importers {
+ folderIDs[l.FolderID(idx)] = true
}
assert.True(t, folderIDs[folderRoot], "folderRoot should import prod:/")
assert.True(t, folderIDs[folderA], "folderA should import prod:/")
})
t.Run("single importer", func(t *testing.T) {
- importers := l.GetImportersOf(prodEnvID, "/d")
+ importers := l.ImportersOf(prodEnvID, "/d")
require.Len(t, importers, 1)
- assert.Equal(t, folderRoot, importers[0].FolderID)
+ assert.Equal(t, folderRoot, l.FolderID(importers[0]))
})
t.Run("no importers for path", func(t *testing.T) {
- importers := l.GetImportersOf(devEnvID, "/nonexistent")
+ importers := l.ImportersOf(devEnvID, "/nonexistent")
assert.Nil(t, importers)
})
t.Run("no importers for unknown env", func(t *testing.T) {
- importers := l.GetImportersOf(uuid.MustParse("99999999-9999-9999-9999-999999999999"), "/")
+ importers := l.ImportersOf(uuid.MustParse("99999999-9999-9999-9999-999999999999"), "/")
assert.Nil(t, importers)
})
}
@@ -176,12 +178,14 @@ func TestGetImportersOf(t *testing.T) {
func TestEmptyLookup(t *testing.T) {
l := newImportLookup(nil)
- assert.Nil(t, l.GetByFolderID(uuid.New()))
+ start, end := l.ImportsOfFolder(uuid.New())
+ assert.Equal(t, int32(0), start)
+ assert.Equal(t, int32(0), end)
- _, ok := l.GetByID(uuid.New())
+ _, ok := l.IndexByID(uuid.New())
assert.False(t, ok)
- assert.Nil(t, l.GetImportersOf(uuid.New(), "/"))
+ assert.Nil(t, l.ImportersOf(uuid.New(), "/"))
}
// ---------------------------------------------------------------------------
@@ -199,10 +203,38 @@ func TestNullBoolsDefaultToFalse(t *testing.T) {
}
l := newImportLookup(rows)
- entries := l.GetByFolderID(folderRoot)
- require.Len(t, entries, 1)
- assert.False(t, entries[0].IsReplication)
- assert.False(t, entries[0].IsReserved)
+ start, end := l.ImportsOfFolder(folderRoot)
+ require.Equal(t, int32(1), end-start)
+ assert.False(t, l.IsReplication(start))
+ assert.False(t, l.IsReserved(start))
+}
+
+// ---------------------------------------------------------------------------
+// Path arena deduplication
+// ---------------------------------------------------------------------------
+
+func TestPathArenaDeduplication(t *testing.T) {
+ rows := []importRow{
+ {ID: importID1, ImportPath: "/shared", ImportEnvID: devEnvID, Position: 1, FolderID: folderRoot},
+ {ID: importID2, ImportPath: "/shared", ImportEnvID: prodEnvID, Position: 2, FolderID: folderRoot},
+ {ID: importID3, ImportPath: "/shared", ImportEnvID: devEnvID, Position: 1, FolderID: folderA},
+ {ID: importID4, ImportPath: "/unique", ImportEnvID: devEnvID, Position: 1, FolderID: folderB},
+ }
+ l := newImportLookup(rows)
+
+ // Verify all paths are correct
+ idx1, _ := l.IndexByID(importID1)
+ idx2, _ := l.IndexByID(importID2)
+ idx3, _ := l.IndexByID(importID3)
+ idx4, _ := l.IndexByID(importID4)
+
+ assert.Equal(t, "/shared", l.TargetPath(idx1))
+ assert.Equal(t, "/shared", l.TargetPath(idx2))
+ assert.Equal(t, "/shared", l.TargetPath(idx3))
+ assert.Equal(t, "/unique", l.TargetPath(idx4))
+
+ // Verify arena only contains "/shared" + "/unique" = 14 bytes
+ assert.Equal(t, 14, len(l.pathArena))
}
// ---------------------------------------------------------------------------
@@ -272,7 +304,7 @@ func TestResolveChain_DepthFirst(t *testing.T) {
assert.Equal(t, 1, chain[3].Depth)
}
-func TestResolveChain_PreservesImportEntry(t *testing.T) {
+func TestResolveChain_PreservesImportIndex(t *testing.T) {
l := buildChainImports()
resolver := mockResolver(map[importTarget]uuid.UUID{
{devEnvID, "/b"}: chainFolderB,
@@ -283,8 +315,8 @@ func TestResolveChain_PreservesImportEntry(t *testing.T) {
// Only B and D resolve (prod:/ not in resolver).
require.Len(t, chain, 2)
- assert.Equal(t, chainImp1, chain[0].Import.ID)
- assert.Equal(t, chainImp3, chain[1].Import.ID)
+ assert.Equal(t, chainImp1, l.ID(chain[0].ImportIdx))
+ assert.Equal(t, chainImp3, l.ID(chain[1].ImportIdx))
}
func TestResolveChain_CycleDetection(t *testing.T) {
diff --git a/backend-go/internal/services/secretmanager/secretimport/resolver.go b/backend-go/internal/services/secretmanager/secretimport/resolver.go
deleted file mode 100644
index 6a7e6d0540..0000000000
--- a/backend-go/internal/services/secretmanager/secretimport/resolver.go
+++ /dev/null
@@ -1,164 +0,0 @@
-package secretimport
-
-import (
- "context"
- "fmt"
-
- "github.com/google/uuid"
-
- "github.com/infisical/api/internal/services/secretmanager/secretfolder"
-)
-
-const maxImportChainDepth = 10
-
-type FolderLoader interface {
- LoadProjectFolders(ctx context.Context, projectID string, envIDs []uuid.UUID) (*secretfolder.FolderLookup, error)
-}
-
-type ChainResult struct {
- FolderLookup *secretfolder.FolderLookup
- DirectFolderIDs []uuid.UUID
- DirectPaths map[uuid.UUID]string
- Imports []ResolvedImport
- UsedEnvIDs []uuid.UUID
-}
-
-func (r *ChainResult) ImportedFolderIDs() []uuid.UUID {
- ids := make([]uuid.UUID, len(r.Imports))
- for i := range r.Imports {
- ids[i] = r.Imports[i].FolderID
- }
- return ids
-}
-
-func (r *ChainResult) AllFolderIDs() []uuid.UUID {
- all := make([]uuid.UUID, 0, len(r.DirectFolderIDs)+len(r.Imports))
- all = append(all, r.DirectFolderIDs...)
- all = append(all, r.ImportedFolderIDs()...)
- return all
-}
-
-type ChainResolver struct {
- importLookup *ImportLookup
- folderLoader FolderLoader
-}
-
-func NewChainResolver(importLookup *ImportLookup, folderLoader FolderLoader) *ChainResolver {
- return &ChainResolver{
- importLookup: importLookup,
- folderLoader: folderLoader,
- }
-}
-
-func (r *ChainResolver) Resolve(
- ctx context.Context,
- projectID string,
- startEnvID uuid.UUID,
- secretPath string,
- recursive bool,
-) (*ChainResult, error) {
- loadedEnvs := make(map[uuid.UUID]bool)
-
- // Load folders for starting env
- folderLookup, err := r.folderLoader.LoadProjectFolders(ctx, projectID, []uuid.UUID{startEnvID})
- if err != nil {
- return nil, fmt.Errorf("failed to load folders for starting env: %w", err)
- }
- loadedEnvs[startEnvID] = true
-
- // Resolve direct folders
- var directFolderIDs []uuid.UUID
- directPaths := make(map[uuid.UUID]string)
-
- if recursive {
- nodes, ok := folderLookup.GetSubTree(startEnvID, secretPath)
- if !ok || len(nodes) == 0 {
- return nil, fmt.Errorf("folder not found: %s", secretPath)
- }
- for _, node := range nodes {
- directFolderIDs = append(directFolderIDs, node.ID)
- directPaths[node.ID] = node.GetPath()
- }
- } else {
- node, ok := folderLookup.GetByPath(startEnvID, secretPath)
- if !ok {
- return nil, fmt.Errorf("folder not found: %s", secretPath)
- }
- directFolderIDs = []uuid.UUID{node.ID}
- directPaths[node.ID] = secretPath
- }
-
- // Iteratively resolve import chain
- var allImports []ResolvedImport
- currentFolders := directFolderIDs
- visited := make(map[uuid.UUID]bool)
-
- for depth := 0; depth < maxImportChainDepth && len(currentFolders) > 0; depth++ {
- // Collect new envs needed from current folders' imports
- var newEnvIDs []uuid.UUID
- for _, folderID := range currentFolders {
- for _, imp := range r.importLookup.GetByFolderID(folderID) {
- if imp.IsReplication {
- continue
- }
- if !loadedEnvs[imp.ImportEnvID] {
- newEnvIDs = append(newEnvIDs, imp.ImportEnvID)
- loadedEnvs[imp.ImportEnvID] = true
- }
- }
- }
-
- // Load folders for new envs
- if len(newEnvIDs) > 0 {
- newLookup, err := r.folderLoader.LoadProjectFolders(ctx, projectID, newEnvIDs)
- if err != nil {
- return nil, fmt.Errorf("failed to load folders for imported envs: %w", err)
- }
- folderLookup.Merge(newLookup)
- }
-
- // Resolve imports to folder IDs
- var nextFolders []uuid.UUID
- for _, folderID := range currentFolders {
- for _, imp := range r.importLookup.GetByFolderID(folderID) {
- if imp.IsReplication {
- continue
- }
-
- targetNode, ok := folderLookup.GetByPath(imp.ImportEnvID, imp.ImportPath)
- if !ok {
- continue
- }
-
- if visited[targetNode.ID] {
- continue
- }
- visited[targetNode.ID] = true
-
- allImports = append(allImports, ResolvedImport{
- FolderID: targetNode.ID,
- EnvID: imp.ImportEnvID,
- Path: imp.ImportPath,
- Import: imp,
- })
- nextFolders = append(nextFolders, targetNode.ID)
- }
- }
-
- currentFolders = nextFolders
- }
-
- // Collect all used env IDs
- usedEnvIDs := make([]uuid.UUID, 0, len(loadedEnvs))
- for envID := range loadedEnvs {
- usedEnvIDs = append(usedEnvIDs, envID)
- }
-
- return &ChainResult{
- FolderLookup: folderLookup,
- DirectFolderIDs: directFolderIDs,
- DirectPaths: directPaths,
- Imports: allImports,
- UsedEnvIDs: usedEnvIDs,
- }, nil
-}