Skip to content

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

feat: updated the error messages to be more clear

=4e254ddd6b99
diff --git a/backend-go/CLAUDE.md b/backend-go/CLAUDE.md
index 128cabeefc..09941edeb2 100644
--- a/backend-go/CLAUDE.md
+++ b/backend-go/CLAUDE.md
@@ -1,137 +1,83 @@
-# CLAUDE.md
+# backend-go
-This is the **backend-go** package — a partial Go rewrite of the Node.js backend using Goa v3 for API design and go-jet for type-safe SQL.
+Partial Go rewrite of the Node.js backend using Goa v3 + go-jet.
## Commands
-All commands run from `backend-go/`:
-
-- `make build` — build binary
-- `make dev` — hot-reloading server via docker-compose + air
-- `make gen-goa` — regenerate Goa HTTP handlers from DSL (`internal/server/design/` → `internal/server/gen/`)
-- `make gen-db` — regenerate go-jet table types from DB (`internal/database/pg/gen/`)
-- `make test` — integration tests (testcontainers, `-race`, 300s timeout)
-- `make lint` — **must pass before submission**
-- `make lint-fix` — **use to fix auto fixable ones**
+```
+make build # build binary
+make dev # hot-reload via docker-compose + air
+make gen-goa # regenerate Goa handlers (design/ → gen/)
+make gen-db # regenerate go-jet types from DB
+make test # integration tests (testcontainers, -race)
+make lint # must pass before submission
+make lint-fix # auto-fix linting issues
+```
-Never edit generated code in `gen/` directories — always regenerate.
+Never edit `gen/` directories — always regenerate.
## Code Rules
-- **Linting**: All code must pass `make lint`. Do not suppress with `//nolint` unless clearly justified.
-- **Constructor signature**: Both services and DALs initialize with `(logger *slog.Logger, deps Deps)`. All external dependencies go in a `Deps` struct (name must end with `Deps`). The `exhaustruct` linter enforces every field is set at the call site — no silent nil dependencies.
-- **Context everywhere**: Every service and DAL method that does I/O **must accept `context.Context` as its first argument**. Constructors are the only exception.
-- **Explicit logger**: Services and DALs receive `*slog.Logger` via constructor — **never use `slog.Default()` or package-level `slog.*` functions**. Tag with `logger.With("service", "name")`.
-- **Interfaces for dependencies**: Consumer defines the interface (narrow, only needed methods). Accept interfaces, not concrete types.
-- **DAL boundary**: Services must not import `table`, `postgres`, or `qrm`. All queries go through a DAL. Always use type-safe go-jet — no raw SQL (exception: `pg_advisory_xact_lock`).
-- **Database error wrapping**: All `err` values returned from DAL/database calls must be wrapped with `errutil.DatabaseErr("<user-facing message>").WithErr(err)` at the service/caller level, NOT inside DAL methods. This logs the real DB error internally but only shows the safe message to clients.
-- **Error cause context**: When returning `errutil` service errors, always attach origin context via `.WithErr()` using `fmt.Errorf` with the function name and relevant args: `errutil.DatabaseErr("Failed to load resource").WithErr(fmt.Errorf("secretfolder.LoadProjectFolders(project=%s): %w", projectID, err))`. Keep client-facing messages generic — the cause is never exposed to clients, it only appears in server logs alongside the Goa service/method from context.
-- **Lean code**: Inline helpers with one caller. Only extract when shared. Split DAL files by functionality.
+- **Linting**: `make lint` must pass. No `//nolint` unless justified.
+- **Constructor**: `(logger *slog.Logger, deps Deps)` — deps struct name ends with `Deps`.
+- **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:
+ ```go
+ errutil.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.
## Architecture
-### Key Directories
-
```
-cmd/infisical/main.go # Entry point: config → DB → api.Registry → server
-cmd/dev/pg_gen/main.go # go-jet codegen utility
+cmd/infisical/main.go # Entry point
internal/
-├── config/ # Env-var config via koanf (186+ settings)
+├── config/ # Env config via koanf
├── database/
-│ ├── pg/gen/ # go-jet generated types (DO NOT EDIT)
-│ ├── redis/ # Redis client (standalone/cluster/sentinel)
-│ └── ormify/ # Generic CRUD: DAL[M any] with FindByID, Create, Update, etc.
-├── keystore/ # Redis key-value + PG advisory locks
+│ ├── pg/gen/ # go-jet generated (DO NOT EDIT)
+│ ├── redis/ # Redis client
+│ └── ormify/ # Generic CRUD: DAL[M] with Find/Create/Update/Delete
├── server/
-│ ├── design/
-│ │ ├── auth/ # Goa security schemes (JWT, identity, service token)
-│ │ ├── common/ # Shared error types
-│ │ ├── platform/ # Platform Goa DSL
-│ │ └── secretmanager/ # Secret manager Goa DSL
-│ ├── gen/ # Goa generated (DO NOT EDIT)
-│ └── api/ # Goa endpoint implementations
-│ ├── api.go # Root DI wiring (NewRegistry)
-│ ├── platform/ # Platform API (projects, etc.)
-│ └── secretmanager/ # Secret manager API (secrets, etc.)
-├── services/ # Shared business logic (cross-product)
-│ ├── libs.go # SharedServices wiring
-│ ├── auth/ # Authentication & token validation
-│ ├── permission/ # CASL-based permission checks
-│ ├── kms/ # Key management service
-│ ├── license/ # License validation
-│ ├── secretmanager/ # Shared secret manager services (secretfolder, secretimport)
-│ └── serverconfig/ # Server configuration
-└── testutil/ # Test infra (testcontainers, fluent HTTP builder)
+│ ├── design/ # Goa DSL definitions
+│ ├── gen/ # Goa generated (DO NOT EDIT)
+│ └── api/ # Endpoint implementations + DI wiring
+├── services/ # Shared business logic (auth, permission, kms)
+└── testutil/ # Test infra (testcontainers)
```
-### Two-Tier Service Architecture
-
-- **`server/api/`** — Goa endpoint implementations. Each module implements a Goa-generated `Service` interface and orchestrates shared services. Always 1:1 with a Goa endpoint. These should NOT be imported by anything outside `server/`.
-- **`services/`** — Shared business logic (auth, permission, kms, etc.). Consumed by API implementations and by each other. No dependency on Goa-generated code.
+**Two tiers:**
+- `server/api/` — Goa endpoint implementations. 1:1 with endpoints. Not imported elsewhere.
+- `services/` — Shared logic. No Goa dependency.
-DI wiring: `api.NewRegistry()` constructs shared services first, then passes them into product-specific API registries.
+**DAL**: `ormify.DAL[M]` provides `FindByID`, `Find`, `Create`, `Update`, `Delete`, `Count`.
-### Data Access (DAL)
+**Read replicas**: `pg.DB` wraps primary + replica pools. Reads hit replicas, writes hit primary.
-`ormify.DAL[M any]` provides: `FindByID`, `FindOne`, `Find`, `FindAll`, `Create`, `InsertMany`, `UpdateByID`, `Update`, `DeleteByID`, `Delete`, `Count` with functional options (limit/offset/orderBy).
+### Go-Jet Nesting
-**Read replica pattern**: `pg.DB` wraps primary + replica pools. Reads go to a random replica (fallback to primary). Writes always hit primary.
-
-### Go-Jet QRM Automatic Nesting
-
-For queries with LEFT JOINs that create one-to-many relationships (e.g., secrets → tags), use go-jet's automatic nesting via struct definitions instead of manual nesting functions.
-
-**Define nested structs with slice fields and primary key tags:**
+For JOINs with one-to-many, use struct tags:
```go
type Secret struct {
- ID uuid.UUID `sql:"primary_key" alias:"secrets_v2.id"`
- Key string `alias:"secrets_v2.key"`
- Tags []SecretTag `alias:"secret_tags"` // go-jet auto-groups into slices
+ ID uuid.UUID `sql:"primary_key" alias:"secrets_v2.id"`
+ Tags []SecretTag `alias:"secret_tags"`
}
-
type SecretTag struct {
ID uuid.UUID `sql:"primary_key" alias:"secret_tags.id"`
Slug string `alias:"secret_tags.slug"`
}
```
-**Query directly into nested struct:**
-
-```go
-var secrets []Secret
-err := stmt.QueryContext(ctx, d.db.Replica(), &secrets)
-// secrets[].Tags[] automatically populated and deduplicated
-```
-
-**Key requirements:**
-- Include `sql:"primary_key"` tag on ID fields — go-jet uses these for grouping/deduplication
-- Use `alias:"table.column"` tags to map columns from JOINed tables
-- Child slices must have their own primary keys to avoid duplicates from cartesian products
-- No manual nesting function needed — go-jet handles it automatically
-
-See `internal/services/secretmanager/secret/dal.go` for a complete example with multiple nested slices (tags, metadata, reminder recipients).
-
-### Testing
-
-Integration tests with testcontainers-go (PostgreSQL 14, Redis 7, Node.js backend):
-
-```go
-mux.Request(t, http.MethodPost, "/api/v1/...").
- WithAuth(infra.IdentityToken).
- WithBody(payload).
- Do().
- ExpectStatus(http.StatusCreated).
- ParseJSON(&result)
-```
-
-Tests run with `-race`. Infrastructure shared across packages via file lock + `.test-infra-state.json`.
+Go-jet auto-groups slices. Requires `sql:"primary_key"` on IDs.
## Wiring a New Feature
-1. Define API in Goa DSL (`internal/server/design/<product>/`)
+1. Define API in Goa DSL (`server/design/<product>/`)
2. `make gen-goa`
-3. Create API implementation in `internal/server/api/<product>/<name>/` implementing generated interface
-4. Wire in `api.go`, mount in `internal/server/<product>.go`
-5. Add tests with `setupMux()` pattern
-6. `make test` + `make lint`
+3. Implement in `server/api/<product>/<name>/`
+4. Wire in `api.go`
+5. Add tests, run `make test && make lint`, auto fix lint command `make lint-fix`
diff --git a/backend-go/internal/libs/errutil/error.go b/backend-go/internal/libs/errutil/error.go
index 52b2b023ab..f4d9e38cb0 100644
--- a/backend-go/internal/libs/errutil/error.go
+++ b/backend-go/internal/libs/errutil/error.go
@@ -60,6 +60,14 @@ func (e *Error) WithErr(err error) *Error {
return e
}
+// WithErrf wraps an underlying cause using fmt.Errorf formatting.
+// Use this to add function context: .WithErrf("FunctionName(arg=%s): %w", argValue, err)
+func (e *Error) WithErrf(format string, args ...any) *Error {
+ e.Err = fmt.Errorf(format, args...)
+
+ return e
+}
+
// BadRequest creates a 400 error.
func BadRequest(format string, args ...any) *Error {
return &Error{Name: "BadRequest", Status: 400, Message: fmt.Sprintf(format, args...)}
diff --git a/backend-go/internal/server/api/secretmanager/secrets/get_secret_by_name.go b/backend-go/internal/server/api/secretmanager/secrets/get_secret_by_name.go
index e666d5e8d8..d5cd7e95f3 100644
--- a/backend-go/internal/server/api/secretmanager/secrets/get_secret_by_name.go
+++ b/backend-go/internal/server/api/secretmanager/secrets/get_secret_by_name.go
@@ -2,7 +2,6 @@ package secrets
import (
"context"
- "fmt"
"log/slog"
"github.com/google/uuid"
@@ -34,7 +33,7 @@ type GetSecretOpts struct {
func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts) (*gensecrets.GetSecretResult, error) {
identity := auth.IdentityFromContext(ctx)
if identity == nil {
- return nil, errutil.Unauthorized("Authentication required")
+ return nil, errutil.Unauthorized("Authentication required").WithErrf("getSecretByNameCore: identity not in context")
}
actorID := identity.ActorID
@@ -50,13 +49,13 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
ActionProjectType: permission.ActionProjectTypeSecretManager,
})
if err != nil {
- return nil, errutil.DatabaseErr("Failed to get project permission").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to get project permission").WithErrf("GetSecretByName(projectId=%s): %w", opts.ProjectID, err)
}
// Load environments
allEnvs, err := h.secretManagerSvc.EnvironmentDAL.GetAllByProjectID(ctx, opts.ProjectID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to load environments").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to load environments").WithErrf("GetSecretByName(projectId=%s): %w", opts.ProjectID, err)
}
envByID := make(map[uuid.UUID]secretimport.EnvironmentInfo, len(allEnvs))
@@ -73,22 +72,18 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
}
}
if env == nil {
- return nil, errutil.NotFound("Environment not found").WithErr(
- fmt.Errorf("environment '%s' not found in project", opts.Environment),
- )
+ return nil, errutil.NotFound("Environment not found").WithErrf("GetSecretByName: environment '%s' not found in project", opts.Environment)
}
// Load folder
folderLookup, err := h.secretManagerSvc.SecretFolder.LoadProjectFolders(ctx, opts.ProjectID, []uuid.UUID{env.ID})
if err != nil {
- return nil, errutil.DatabaseErr("Failed to load folders").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to load folders").WithErrf("GetSecretByName(projectId=%s): %w", opts.ProjectID, err)
}
folderNode, ok := folderLookup.GetByPath(env.ID, opts.SecretPath)
if !ok {
- return nil, errutil.NotFound("Folder not found").WithErr(
- fmt.Errorf("folder path '%s' not found in environment '%s'", opts.SecretPath, opts.Environment),
- )
+ return nil, errutil.NotFound("Folder not found").WithErrf("GetSecretByName: folder path '%s' not found in environment '%s'", opts.SecretPath, opts.Environment)
}
// Get KMS cipher pair
@@ -97,7 +92,7 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
ProjectID: opts.ProjectID,
})
if err != nil {
- return nil, errutil.InternalServer("Failed to get decryption key").WithErr(err)
+ return nil, errutil.InternalServer("Failed to get decryption key").WithErrf("GetSecretByName(projectId=%s): %w", opts.ProjectID, err)
}
// Prepare user ID for personal secrets
@@ -117,14 +112,14 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
// Find the secret by name
foundSecret, err := h.secretManagerSvc.SecretDAL.FindByKey(ctx, folderNode.ID, opts.SecretName, secretType, userID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find secret").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find secret").WithErrf("GetSecretByName(secretName=%s): %w", opts.SecretName, err)
}
// If not found in direct folder and includeImports is true, search imports
if foundSecret == nil && opts.IncludeImports {
importLookup, err := h.secretManagerSvc.SecretImport.LoadProjectImports(ctx, opts.ProjectID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to load imports").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to load imports").WithErrf("GetSecretByName(projectId=%s): %w", opts.ProjectID, err)
}
chainResolver := secretimport.NewChainResolver(importLookup, h.secretManagerSvc.SecretFolder)
@@ -146,9 +141,7 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
}
if foundSecret == nil {
- return nil, errutil.NotFound("Secret not found").WithErr(
- fmt.Errorf("secret with name '%s' not found", opts.SecretName),
- )
+ return nil, errutil.NotFound("Secret not found").WithErrf("GetSecretByName: secret with name '%s' not found", opts.SecretName)
}
// Check permissions
@@ -159,14 +152,14 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
canDescribe := permission.CanDescribeSecret(permResult.Permission.Ability, opts.Environment, opts.SecretPath, foundSecret.Key, tagSlugs)
if !canDescribe {
- return nil, errutil.Forbidden("You do not have permission to access this secret")
+ return nil, errutil.Forbidden("You do not have permission to access this secret").WithErrf("getSecretByNameCore(secretName=%s, env=%s, path=%s): describe denied", opts.SecretName, opts.Environment, opts.SecretPath)
}
canReadValue := permission.CanReadSecretValue(permResult.Permission.Ability, opts.Environment, opts.SecretPath, foundSecret.Key, tagSlugs)
valueHidden := !opts.ViewSecretValue || !canReadValue
if opts.ViewSecretValue && !canReadValue {
- return nil, errutil.Forbidden("You do not have permission to view this secret value")
+ return nil, errutil.Forbidden("You do not have permission to view this secret value").WithErrf("getSecretByNameCore(secretName=%s, env=%s, path=%s): read value denied", opts.SecretName, opts.Environment, opts.SecretPath)
}
// Decrypt value and comment
@@ -250,7 +243,7 @@ func (h *Handler) getSecretByNameCore(ctx context.Context, opts *GetSecretOpts)
if expander.HasDeniedRefs() {
deniedRefs := expander.DeniedRefs()
return nil, errutil.Forbidden("Failed to expand one or more secret references").
- WithErr(fmt.Errorf("denied refs: %v", deniedRefs))
+ WithErrf("denied refs: %v", deniedRefs)
}
if expanded, ok := expander.LookUp(foundSecret.ID); ok {
@@ -316,7 +309,7 @@ func (h *Handler) GetSecretByNameRawV3(ctx context.Context, p *gensecrets.GetSec
// Environment is required for this endpoint
if p.Environment == nil || *p.Environment == "" {
- return nil, errutil.BadRequest("Environment is required")
+ return nil, errutil.BadRequest("Environment is required").WithErrf("GetSecretByNameRawV3: environment param missing")
}
result, err := h.getSecretByNameCore(ctx, &GetSecretOpts{
@@ -381,9 +374,8 @@ func (h *Handler) createGetSecretAuditLog(ctx context.Context, projectID, env, s
}
if err := h.sharedSvc.AuditLog.CreateAuditLog(ctx, dto); err != nil {
- return errutil.InternalServer("Failed to create audit log").WithErr(
- fmt.Errorf("createGetSecretAuditLog(project=%s, env=%s, path=%s, key=%s): %w", projectID, env, secretPath, sec.SecretKey, err),
- )
+ return errutil.InternalServer("Failed to create audit log").WithErrf(
+ "createGetSecretAuditLog(project=%s, env=%s, path=%s, key=%s): %w", projectID, env, secretPath, sec.SecretKey, err)
}
return nil
diff --git a/backend-go/internal/server/api/secretmanager/secrets/list_secrets.go b/backend-go/internal/server/api/secretmanager/secrets/list_secrets.go
index b54acd1d21..6ac8d9f1fe 100644
--- a/backend-go/internal/server/api/secretmanager/secrets/list_secrets.go
+++ b/backend-go/internal/server/api/secretmanager/secrets/list_secrets.go
@@ -2,7 +2,6 @@ package secrets
import (
"context"
- "fmt"
"log/slog"
"strings"
@@ -109,7 +108,7 @@ func (h *Handler) listSecretsCore(ctx context.Context, opts *ListSecretsOpts) (*
// 1. Get identity from context
identity := auth.IdentityFromContext(ctx)
if identity == nil {
- return nil, errutil.Unauthorized("Authentication required")
+ return nil, errutil.Unauthorized("Authentication required").WithErrf("listSecretsCore: identity not in context")
}
actorID := identity.ActorID
@@ -127,13 +126,13 @@ func (h *Handler) listSecretsCore(ctx context.Context, opts *ListSecretsOpts) (*
ActionProjectType: permission.ActionProjectTypeSecretManager,
})
if err != nil {
- return nil, errutil.DatabaseErr("Failed to get project permission").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to get project permission").WithErrf("ListSecrets(projectId=%s): %w", opts.ProjectID, err)
}
// 3. Load all environments for the project (metadata only, for envID -> slug mapping)
allEnvs, err := h.secretManagerSvc.EnvironmentDAL.GetAllByProjectID(ctx, opts.ProjectID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to load environments").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to load environments").WithErrf("ListSecrets(projectId=%s): %w", opts.ProjectID, err)
}
// Build environment lookups and find requested env
@@ -151,22 +150,20 @@ func (h *Handler) listSecretsCore(ctx context.Context, opts *ListSecretsOpts) (*
}
}
if env == nil {
- return nil, errutil.NotFound("Environment not found").WithErr(
- fmt.Errorf("environment '%s' not found in project", opts.Environment),
- )
+ return nil, errutil.NotFound("Environment not found").WithErrf("ListSecrets: environment '%s' not found in project", opts.Environment)
}
// 4. Load imports for the project
importLookup, err := h.secretManagerSvc.SecretImport.LoadProjectImports(ctx, opts.ProjectID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to load imports").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to load imports").WithErrf("ListSecrets(projectId=%s): %w", opts.ProjectID, err)
}
// 5. Resolve direct folders + import chain
chainResolver := secretimport.NewChainResolver(importLookup, h.secretManagerSvc.SecretFolder)
chainResult, err := chainResolver.Resolve(ctx, opts.ProjectID, env.ID, opts.SecretPath, opts.Recursive, envByID)
if err != nil {
- return nil, errutil.NotFound("Folder not found").WithErr(err)
+ return nil, errutil.NotFound("Folder not found").WithErrf("ListSecrets(path=%s): %w", opts.SecretPath, err)
}
// 6. Prepare user ID for personal secrets
@@ -198,7 +195,7 @@ func (h *Handler) listSecretsCore(ctx context.Context, opts *ListSecretsOpts) (*
secrets, err := h.secretManagerSvc.SecretDAL.FindByFolderIds(ctx, allFolderIDs, userID, dalFilters)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to fetch secrets").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to fetch secrets").WithErrf("ListSecrets(projectId=%s): %w", opts.ProjectID, err)
}
// 8. Get KMS cipher pair for decryption
@@ -207,7 +204,7 @@ func (h *Handler) listSecretsCore(ctx context.Context, opts *ListSecretsOpts) (*
ProjectID: opts.ProjectID,
})
if err != nil {
- return nil, errutil.InternalServer("Failed to get decryption key").WithErr(err)
+ return nil, errutil.InternalServer("Failed to get decryption key").WithErrf("ListSecrets(projectId=%s): %w", opts.ProjectID, err)
}
// 9. Process secrets with permission filtering
@@ -270,7 +267,7 @@ func (h *Handler) listSecretsCore(ctx context.Context, opts *ListSecretsOpts) (*
details[i] = "Permission denied for secret reference: " + ref
}
return nil, errutil.Forbidden("Failed to expand one or more secret references").
- WithErr(fmt.Errorf("denied refs: %v", deniedRefs))
+ WithErrf("listSecretsCore: denied refs: %v", deniedRefs)
}
applyExpandedValues(directSecrets, importedSecrets, expander)
@@ -378,7 +375,7 @@ func (h *Handler) ListSecretsRawV3(ctx context.Context, p *gensecrets.ListSecret
// Environment is required for this endpoint
if p.Environment == nil || *p.Environment == "" {
- return nil, errutil.BadRequest("Environment is required")
+ return nil, errutil.BadRequest("Environment is required").WithErrf("ListSecretsRawV3: environment param missing")
}
// v3 raw: Always include all (both shared and personal)
@@ -582,9 +579,7 @@ func (h *Handler) createGetSecretsAuditLog(ctx context.Context, projectID, env,
}
if err := h.sharedSvc.AuditLog.CreateAuditLog(ctx, dto); err != nil {
- return errutil.InternalServer("Failed to create audit log").WithErr(
- fmt.Errorf("createGetSecretsAuditLog(project=%s, env=%s, path=%s): %w", projectID, env, secretPath, err),
- )
+ return errutil.InternalServer("Failed to create audit log").WithErrf("createGetSecretsAuditLog(project=%s, env=%s, path=%s): %w", projectID, env, secretPath, err)
}
return nil
diff --git a/backend-go/internal/server/api/secretmanager/secrets/secrets.go b/backend-go/internal/server/api/secretmanager/secrets/secrets.go
index 0e272e38a8..51e0fcce2c 100644
--- a/backend-go/internal/server/api/secretmanager/secrets/secrets.go
+++ b/backend-go/internal/server/api/secretmanager/secrets/secrets.go
@@ -2,7 +2,6 @@ package secrets
import (
"context"
- "fmt"
"log/slog"
"github.com/google/uuid"
@@ -56,25 +55,21 @@ func (h *Handler) resolveProjectID(ctx context.Context, workspaceID, workspaceSl
// Fall back to workspaceSlug
if workspaceSlug == nil || *workspaceSlug == "" {
- return "", errutil.BadRequest("Either workspaceId or workspaceSlug is required")
+ return "", errutil.BadRequest("Either workspaceId or workspaceSlug is required").WithErrf("resolveProjectID: both workspaceId and workspaceSlug are empty")
}
// Get identity to extract org ID
identity := auth.IdentityFromContext(ctx)
if identity == nil {
- return "", errutil.Unauthorized("Authentication required")
+ return "", errutil.Unauthorized("Authentication required").WithErrf("resolveProjectID: identity not in context")
}
proj, err := h.sharedSvc.Project.GetBySlug(ctx, identity.OrgID, *workspaceSlug)
if err != nil {
- return "", errutil.DatabaseErr("Failed to resolve project").WithErr(
- fmt.Errorf("project.GetBySlug(slug=%s): %w", *workspaceSlug, err),
- )
+ return "", errutil.DatabaseErr("Failed to resolve project").WithErrf("resolveProjectID(slug=%s): %w", *workspaceSlug, err)
}
if proj == nil {
- return "", errutil.NotFound("Project not found").WithErr(
- fmt.Errorf("project with slug '%s' not found in org", *workspaceSlug),
- )
+ return "", errutil.NotFound("Project not found").WithErrf("resolveProjectID: project with slug '%s' not found in org", *workspaceSlug)
}
return proj.ID, nil
diff --git a/backend-go/internal/services/actor/actor.go b/backend-go/internal/services/actor/actor.go
index 1edce46bf5..1a58e5c8c7 100644
--- a/backend-go/internal/services/actor/actor.go
+++ b/backend-go/internal/services/actor/actor.go
@@ -21,6 +21,25 @@ const (
// An empty string means no specific method (e.g. platform-level actions).
type AuthMethod string
+// IdentityAuthMethod represents the authentication method used by machine identities.
+type IdentityAuthMethod string
+
+const (
+ IdentityAuthMethodUniversal IdentityAuthMethod = "universal_auth"
+ IdentityAuthMethodKubernetes IdentityAuthMethod = "kubernetes_auth"
+ IdentityAuthMethodGCP IdentityAuthMethod = "gcp_auth"
+ IdentityAuthMethodAliCloud IdentityAuthMethod = "alicloud_auth"
+ IdentityAuthMethodAWS IdentityAuthMethod = "aws_auth"
+ IdentityAuthMethodAzure IdentityAuthMethod = "azure_auth"
+ IdentityAuthMethodToken IdentityAuthMethod = "token_auth"
+ IdentityAuthMethodTLSCert IdentityAuthMethod = "tls_cert_auth"
+ IdentityAuthMethodOCI IdentityAuthMethod = "oci_auth"
+ IdentityAuthMethodOIDC IdentityAuthMethod = "oidc_auth"
+ IdentityAuthMethodJWT IdentityAuthMethod = "jwt_auth"
+ IdentityAuthMethodLDAP IdentityAuthMethod = "ldap_auth"
+ IdentityAuthMethodSPIFFE IdentityAuthMethod = "spiffe_auth"
+)
+
// AuthOIDC holds OIDC-specific claims from the identity JWT payload.
// Used for permission template interpolation (e.g., {{identity.auth.oidc.sub}}).
type AuthOIDC struct {
@@ -51,7 +70,7 @@ type AuthAWS struct {
type AuthInfo struct {
IdentityID uuid.UUID
IdentityName string
- AuthMethod string
+ AuthMethod IdentityAuthMethod
OIDC *AuthOIDC
Kubernetes *AuthKubernetes
AWS *AuthAWS
diff --git a/backend-go/internal/services/auditlog/service.go b/backend-go/internal/services/auditlog/service.go
index 48299c8035..f641b0bd9d 100644
--- a/backend-go/internal/services/auditlog/service.go
+++ b/backend-go/internal/services/auditlog/service.go
@@ -38,7 +38,7 @@ func (s *Service) CreateAuditLog(ctx context.Context, dto *CreateAuditLogDTO) er
}
if dto.ProjectID == nil && dto.OrgID == nil {
- return errutil.BadRequest("Must specify either projectId or orgId")
+ return errutil.BadRequest("Must specify either projectId or orgId").WithErrf("CreateAuditLog: both projectId and orgId are nil")
}
if err := queue.Enqueue(s.queue, TaskAuditLog, dto, queue.WithMaxRetry(3)); err != nil {
@@ -46,7 +46,7 @@ func (s *Service) CreateAuditLog(ctx context.Context, dto *CreateAuditLogDTO) er
slog.String("eventType", string(dto.Event.Type())),
slog.Any("error", err),
)
- return errutil.InternalServer("Failed to create audit log").WithErr(err)
+ return errutil.InternalServer("Failed to create audit log").WithErrf("CreateAuditLog(eventType=%s): %w", dto.Event.Type(), err)
}
return nil
diff --git a/backend-go/internal/services/auth/dal.go b/backend-go/internal/services/auth/dal.go
index 61cf27683f..244b6da410 100644
--- a/backend-go/internal/services/auth/dal.go
+++ b/backend-go/internal/services/auth/dal.go
@@ -147,18 +147,18 @@ func (d *DAL) FindProjectByID(ctx context.Context, id string) (*ProjectRow, erro
// IdentityAccessTokenRow holds the identity_access_tokens columns + joined identity fields
// used by the auth handler. Nearly all token columns are needed for validation.
type IdentityAccessTokenRow struct {
- ID string `alias:"identity_access_tokens.id"`
- AccessTokenTTL int64 `alias:"identity_access_tokens.access_token_ttl"`
- AccessTokenMaxTTL int64 `alias:"identity_access_tokens.access_token_max_ttl"`
- AccessTokenNumUses int64 `alias:"identity_access_tokens.access_token_num_uses"`
- AccessTokenNumUsesLimit int64 `alias:"identity_access_tokens.access_token_num_uses_limit"`
- AccessTokenLastRenewedAt sql.NullTime `alias:"identity_access_tokens.access_token_last_renewed_at"`
- IsAccessTokenRevoked bool `alias:"identity_access_tokens.is_access_token_revoked"`
- IdentityId uuid.UUID `alias:"identity_access_tokens.identity_id"`
- CreatedAt sql.NullTime `alias:"identity_access_tokens.created_at"`
- AuthMethod string `alias:"identity_access_tokens.auth_method"`
- AccessTokenPeriod int64 `alias:"identity_access_tokens.access_token_period"`
- SubOrganizationId sql.Null[uuid.UUID] `alias:"identity_access_tokens.sub_organization_id"`
+ ID string `alias:"identity_access_tokens.id"`
+ AccessTokenTTL int64 `alias:"identity_access_tokens.access_token_ttl"`
+ AccessTokenMaxTTL int64 `alias:"identity_access_tokens.access_token_max_ttl"`
+ AccessTokenNumUses int64 `alias:"identity_access_tokens.access_token_num_uses"`
+ AccessTokenNumUsesLimit int64 `alias:"identity_access_tokens.access_token_num_uses_limit"`
+ AccessTokenLastRenewedAt sql.NullTime `alias:"identity_access_tokens.access_token_last_renewed_at"`
+ IsAccessTokenRevoked bool `alias:"identity_access_tokens.is_access_token_revoked"`
+ IdentityId uuid.UUID `alias:"identity_access_tokens.identity_id"`
+ CreatedAt sql.NullTime `alias:"identity_access_tokens.created_at"`
+ AuthMethod actor.IdentityAuthMethod `alias:"identity_access_tokens.auth_method"`
+ AccessTokenPeriod int64 `alias:"identity_access_tokens.access_token_period"`
+ SubOrganizationId sql.Null[uuid.UUID] `alias:"identity_access_tokens.sub_organization_id"`
// Joined from identities table.
IdentityOrgID uuid.UUID `alias:"identities.org_id"`
@@ -334,7 +334,7 @@ type trustedIPRow struct {
// FindTrustedIpsByAuthMethod returns the parsed trusted IPs for an identity's auth method.
// Exact port of Node.js identityDAL.getTrustedIpsByAuthMethod.
-func (d *DAL) FindTrustedIpsByAuthMethod(ctx context.Context, identityID uuid.UUID, authMethod string) ([]TrustedIP, error) {
+func (d *DAL) FindTrustedIpsByAuthMethod(ctx context.Context, identityID uuid.UUID, authMethod actor.IdentityAuthMethod) ([]TrustedIP, error) {
iua := table.IdentityUniversalAuths
ika := table.IdentityKubernetesAuths
iga := table.IdentityGcpAuths
@@ -349,37 +349,37 @@ func (d *DAL) FindTrustedIpsByAuthMethod(ctx context.Context, identityID uuid.UU
ila := table.IdentityLdapAuths
isa := table.IdentitySpiffeAuths
- // Map auth method string → table + column references.
+ // Map auth method → table + column references.
var tbl postgres.ReadableTable
var identityCol postgres.Column
var trustedIPsProj postgres.Projection
switch authMethod {
- case "universal_auth":
+ case actor.IdentityAuthMethodUniversal:
tbl, identityCol, trustedIPsProj = iua, iua.IdentityId, iua.AccessTokenTrustedIps
- case "kubernetes_auth":
+ case actor.IdentityAuthMethodKubernetes:
tbl, identityCol, trustedIPsProj = ika, ika.IdentityId, ika.AccessTokenTrustedIps
- case "gcp_auth":
+ case actor.IdentityAuthMethodGCP:
tbl, identityCol, trustedIPsProj = iga, iga.IdentityId, iga.AccessTokenTrustedIps
- case "alicloud_auth":
+ case actor.IdentityAuthMethodAliCloud:
tbl, identityCol, trustedIPsProj = iaa, iaa.IdentityId, iaa.AccessTokenTrustedIps
- case "aws_auth":
+ case actor.IdentityAuthMethodAWS:
tbl, identityCol, trustedIPsProj = iwa, iwa.IdentityId, iwa.AccessTokenTrustedIps
- case "azure_auth":
+ case actor.IdentityAuthMethodAzure:
tbl, identityCol, trustedIPsProj = iza, iza.IdentityId, iza.AccessTokenTrustedIps
- case "token_auth":
+ case actor.IdentityAuthMethodToken:
tbl, identityCol, trustedIPsProj = ita, ita.IdentityId, ita.AccessTokenTrustedIps
- case "tls_cert_auth":
+ case actor.IdentityAuthMethodTLSCert:
tbl, identityCol, trustedIPsProj = itca, itca.IdentityId, itca.AccessTokenTrustedIps
- case "oci_auth":
+ case actor.IdentityAuthMethodOCI:
tbl, identityCol, trustedIPsProj = ioa, ioa.IdentityId, ioa.AccessTokenTrustedIps
- case "oidc_auth":
+ case actor.IdentityAuthMethodOIDC:
tbl, identityCol, trustedIPsProj = ioda, ioda.IdentityId, ioda.AccessTokenTrustedIps
- case "jwt_auth":
+ case actor.IdentityAuthMethodJWT:
tbl, identityCol, trustedIPsProj = ija, ija.IdentityId, ija.AccessTokenTrustedIps
- case "ldap_auth":
+ case actor.IdentityAuthMethodLDAP:
tbl, identityCol, trustedIPsProj = ila, ila.IdentityId, ila.AccessTokenTrustedIps
- case "spiffe_auth":
+ case actor.IdentityAuthMethodSPIFFE:
tbl, identityCol, trustedIPsProj = isa, isa.IdentityId, isa.AccessTokenTrustedIps
default:
return nil, nil
diff --git a/backend-go/internal/services/auth/handler.go b/backend-go/internal/services/auth/handler.go
index bdd4803038..398367eba4 100644
--- a/backend-go/internal/services/auth/handler.go
+++ b/backend-go/internal/services/auth/handler.go
@@ -3,7 +3,6 @@ package auth
import (
"context"
"errors"
- "fmt"
"strings"
"time"
@@ -44,7 +43,7 @@ func (h AuthHandler) JWTAuth(ctx context.Context, token string, sc *security.JWT
}
if token == "" {
- return ctx, errutil.Unauthorized("Token missing")
+ return ctx, errutil.Unauthorized("Token missing").WithErrf("JWTAuth: token is empty")
}
tokenMode := ClassifyToken(token)
@@ -67,7 +66,7 @@ func (h AuthHandler) JWTAuth(ctx context.Context, token string, sc *security.JWT
// Fast reject: token type doesn't match the scheme being tried.
if tokenMode != expectedMode {
- return ctx, errutil.Unauthorized("You are not allowed to access this resource").WithErr(fmt.Errorf("provider token %v not supported", tokenMode))
+ return ctx, errutil.Unauthorized("You are not allowed to access this resource").WithErrf("provider token %v not supported", tokenMode)
}
var (
@@ -113,12 +112,12 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
})
if err != nil {
- return nil, errutil.Unauthorized("Invalid JWT token").WithErr(err)
+ return nil, errutil.Unauthorized("Invalid JWT token").WithErrf("validateJWT: %w", err)
}
// 2. Validate authTokenType.
if claims.AuthTokenType != AuthTokenTypeAccessToken {
- return nil, errutil.Unauthorized("You are not allowed to access this resource")
+ return nil, errutil.Unauthorized("You are not allowed to access this resource").WithErrf("validateJWT: invalid authTokenType %s", claims.AuthTokenType)
}
// 3. Find session by tokenVersionId + userId.
@@ -126,32 +125,32 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
userID := parseUUID(claims.UserID)
session, err := h.dal.FindSessionByIDAndUserID(ctx, sessionID, userID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to validate session").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to validate session").WithErrf("validateJWT(sessionId=%s, userId=%s): %w", sessionID, userID, err)
}
if session == nil {
- return nil, errutil.NotFound("Session not found")
+ return nil, errutil.NotFound("Session not found").WithErrf("validateJWT(sessionId=%s, userId=%s): session is nil", sessionID, userID)
}
// 4. Check access version.
if claims.AccessVersion != int(session.AccessVersion) {
- return nil, errutil.Unauthorized("User session is stale, please re-authenticate").WithName("StaleSession")
+ return nil, errutil.Unauthorized("User session is stale, please re-authenticate").WithName("StaleSession").WithErrf("validateJWT(sessionId=%s): access version mismatch claim=%d db=%d", sessionID, claims.AccessVersion, session.AccessVersion)
}
// 5. Find user.
user, err := h.dal.FindUserByID(ctx, session.UserId)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find user").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find user").WithErrf("validateJWT(userId=%s): %w", session.UserId, err)
}
if user == nil || !user.IsAccepted.V {
- return nil, errutil.NotFound("User with ID '%s' not found", session.UserId)
+ return nil, errutil.NotFound("User with ID '%s' not found", session.UserId).WithErrf("validateJWT: user not found or not accepted")
}
// 5a. Check user lock status.
if user.IsLocked.Valid && user.IsLocked.V {
- return nil, errutil.Unauthorized("Account is locked")
+ return nil, errutil.Unauthorized("Account is locked").WithErrf("validateJWT(userId=%s): user is permanently locked", user.ID)
}
if user.TemporaryLockDateEnd.Valid && time.Now().Before(user.TemporaryLockDateEnd.Time) {
- return nil, errutil.Unauthorized("Account is locked")
+ return nil, errutil.Unauthorized("Account is locked").WithErrf("validateJWT(userId=%s): user is temporarily locked", user.ID)
}
// 6. Organization scoping.
@@ -164,10 +163,10 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
subOrgUUID := parseUUID(claims.SubOrganizationID)
subOrg, err := h.dal.FindOrgByID(ctx, subOrgUUID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find sub-organization").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find sub-organization").WithErrf("validateJWT(subOrgId=%s): %w", subOrgUUID, err)
}
if subOrg == nil {
- return nil, errutil.BadRequest("Sub organization %s not found", claims.SubOrganizationID)
+ return nil, errutil.BadRequest("Sub organization %s not found", claims.SubOrganizationID).WithErrf("validateJWT: sub-organization not found")
}
// Verify the sub-org belongs to the token's root organization.
@@ -176,18 +175,18 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
subRootOrgID = subOrg.RootOrgId.V
}
if subRootOrgID != claimOrgUUID && subOrg.ID != claimOrgUUID {
- return nil, errutil.Forbidden("Sub-organization does not belong to the token's organization")
+ return nil, errutil.Forbidden("Sub-organization does not belong to the token's organization").WithErrf("validateJWT(subOrgId=%s, claimOrgId=%s): org mismatch", subOrg.ID, claimOrgUUID)
}
orgMembership, err := h.dal.FindEffectiveOrgMembership(ctx, actor.TypeUser, user.ID, subOrg.ID, "accepted")
if err != nil {
- return nil, errutil.DatabaseErr("Failed to check org membership").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to check org membership").WithErrf("validateJWT(userId=%s, orgId=%s): %w", user.ID, subOrg.ID, err)
}
if orgMembership == nil {
- return nil, errutil.Forbidden("User not member of organization")
+ return nil, errutil.Forbidden("User not member of organization").WithErrf("validateJWT(userId=%s, subOrgId=%s): no membership found", user.ID, subOrg.ID)
}
if !orgMembership.IsActive {
- return nil, errutil.Forbidden("User organization membership is inactive")
+ return nil, errutil.Forbidden("User organization membership is inactive").WithErrf("validateJWT(userId=%s, subOrgId=%s): membership inactive", user.ID, subOrg.ID)
}
orgID = subOrg.ID
@@ -200,18 +199,18 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
// 6b. Regular organization scope.
org, err := h.dal.FindOrgByID(ctx, claimOrgUUID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find organization").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find organization").WithErrf("validateJWT(orgId=%s): %w", claimOrgUUID, err)
}
orgMembership, err := h.dal.FindEffectiveOrgMembership(ctx, actor.TypeUser, user.ID, claimOrgUUID, "accepted")
if err != nil {
- return nil, errutil.DatabaseErr("Failed to check org membership").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to check org membership").WithErrf("validateJWT(userId=%s, orgId=%s): %w", user.ID, claimOrgUUID, err)
}
if orgMembership == nil {
- return nil, errutil.Forbidden("User not member of organization")
+ return nil, errutil.Forbidden("User not member of organization").WithErrf("validateJWT(userId=%s, orgId=%s): no membership found", user.ID, claimOrgUUID)
}
if !orgMembership.IsActive {
- return nil, errutil.Forbidden("User organization membership is inactive")
+ return nil, errutil.Forbidden("User organization membership is inactive").WithErrf("validateJWT(userId=%s, orgId=%s): membership inactive", user.ID, claimOrgUUID)
}
orgID = claimOrgUUID
@@ -263,26 +262,26 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
return h.authSecret, nil
})
if err != nil {
- return nil, errutil.Unauthorized("You are not allowed to access this resource")
+ return nil, errutil.Unauthorized("You are not allowed to access this resource").WithErrf("validateIdentityAccessToken: JWT parse failed: %w", err)
}
// 2. Validate authTokenType.
if claims.AuthTokenType != AuthTokenTypeIdentityAccessToken {
- return nil, errutil.Unauthorized("You are not allowed to access this resource")
+ return nil, errutil.Unauthorized("You are not allowed to access this resource").WithErrf("validateIdentityAccessToken: invalid authTokenType %s", claims.AuthTokenType)
}
// 3. Find identity access token (joined with identities table).
accessToken, err := h.dal.FindIdentityAccessTokenByID(ctx, claims.IdentityAccessTokenID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find identity access token").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find identity access token").WithErrf("validateIdentityAccessToken(tokenId=%s): %w", claims.IdentityAccessTokenID, err)
}
if accessToken == nil {
- return nil, errutil.Unauthorized("No identity access token found")
+ return nil, errutil.Unauthorized("No identity access token found").WithErrf("validateIdentityAccessToken(tokenId=%s): token not found in DB", claims.IdentityAccessTokenID)
}
// 4. Belt-and-suspenders revocation check.
if accessToken.IsAccessTokenRevoked {
- return nil, errutil.Unauthorized("Failed to authorize revoked access token, access token is revoked")
+ return nil, errutil.Unauthorized("Failed to authorize revoked access token, access token is revoked").WithErrf("validateIdentityAccessToken(tokenId=%s): token is revoked", accessToken.ID)
}
// 5. IP check.
@@ -290,7 +289,7 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
if ipAddress != "" {
trustedIPs, err := h.dal.FindTrustedIpsByAuthMethod(ctx, accessToken.IdentityId, accessToken.AuthMethod)
if err != nil {
- return nil, errutil.InternalServer("Failed to find trusted IPs")
+ return nil, errutil.DatabaseErr("Failed to find trusted IPs").WithErrf("validateIdentityAccessToken(identityId=%s, authMethod=%s): %w", accessToken.IdentityId, accessToken.AuthMethod, err)
}
if trustedIPs != nil {
if ipErr := checkIPAgainstBlocklist(ipAddress, trustedIPs); ipErr != nil {
@@ -310,10 +309,10 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
// 7. Find org.
org, err := h.dal.FindOrgByID(ctx, scopeOrgUUID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find organization").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find organization").WithErrf("validateIdentityAccessToken(orgId=%s): %w", scopeOrgUUID, err)
}
if org == nil {
- return nil, errutil.InternalServer("Organization not found for identity")
+ return nil, errutil.NotFound("Organization not found for identity").WithErrf("validateIdentityAccessToken(orgId=%s): org not found", scopeOrgUUID)
}
// 8. Resolve org hierarchy.
@@ -322,10 +321,10 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
// 9. Check org membership.
membership, err := h.dal.FindEffectiveOrgMembership(ctx, actor.TypeIdentity, accessToken.IdentityId, org.ID, "")
if err != nil {
- return nil, errutil.InternalServer("Failed to check org membership")
+ return nil, errutil.DatabaseErr("Failed to check org membership").WithErrf("validateIdentityAccessToken(identityId=%s, orgId=%s): %w", accessToken.IdentityId, org.ID, err)
}
if membership == nil {
- return nil, errutil.BadRequest("Identity does not belong to this organization")
+ return nil, errutil.BadRequest("Identity does not belong to this organization").WithErrf("validateIdentityAccessToken(identityId=%s, orgId=%s): no membership found", accessToken.IdentityId, org.ID)
}
// 10. Validate usage limit.
@@ -333,7 +332,7 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
accessTokenNumUses := accessToken.AccessTokenNumUses
if accessToken.AccessTokenNumUsesLimit > 0 && accessTokenNumUses > 0 && accessTokenNumUses >= accessToken.AccessTokenNumUsesLimit {
_ = h.dal.DeleteIdentityAccessTokenByID(ctx, accessToken.ID)
- return nil, errutil.Unauthorized("Unable to renew because access token number of uses limit reached")
+ return nil, errutil.Unauthorized("Unable to renew because access token number of uses limit reached").WithErrf("validateIdentityAccessToken(tokenId=%s): usage limit %d reached", accessToken.ID, accessToken.AccessTokenNumUsesLimit)
}
// 11. Validate TTL.
@@ -347,7 +346,7 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
expiry := base.Add(time.Duration(accessToken.AccessTokenTTL) * time.Second)
if time.Now().After(expiry) {
_ = h.dal.DeleteIdentityAccessTokenByID(ctx, accessToken.ID)
- return nil, errutil.Unauthorized("Failed to renew MI access token due to TTL expiration")
+ return nil, errutil.Unauthorized("Failed to renew MI access token due to TTL expiration").WithErrf("validateIdentityAccessToken(tokenId=%s): TTL expired", accessToken.ID)
}
}
@@ -360,13 +359,13 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
expirationDate := createdAt.Add(time.Duration(accessToken.AccessTokenMaxTTL) * time.Second)
if time.Now().After(expirationDate) {
_ = h.dal.DeleteIdentityAccessTokenByID(ctx, accessToken.ID)
- return nil, errutil.Unauthorized("Failed to renew MI access token due to Max TTL expiration")
+ return nil, errutil.Unauthorized("Failed to renew MI access token due to Max TTL expiration").WithErrf("validateIdentityAccessToken(tokenId=%s): Max TTL expired", accessToken.ID)
}
extendToDate := time.Now().Add(time.Duration(accessToken.AccessTokenTTL) * time.Second)
if extendToDate.After(expirationDate) {
_ = h.dal.DeleteIdentityAccessTokenByID(ctx, accessToken.ID)
- return nil, errutil.Unauthorized("Failed to renew MI access token past its Max TTL expiration")
+ return nil, errutil.Unauthorized("Failed to renew MI access token past its Max TTL expiration").WithErrf("validateIdentityAccessToken(tokenId=%s): would exceed Max TTL", accessToken.ID)
}
}
@@ -411,7 +410,7 @@ func (h AuthHandler) validateServiceToken(ctx context.Context, token string) (*I
// 1. Split token: "st.<tokenID>.<tokenSecret>"
parts := strings.SplitN(token, ".", 3)
if len(parts) != 3 || parts[0] != "st" {
- return nil, errutil.Unauthorized("You are not allowed to access this resource")
+ return nil, errutil.Unauthorized("You are not allowed to access this resource").WithErrf("validateServiceToken: invalid token format")
}
tokenID := parts[1]
tokenSecret := parts[2]
@@ -419,30 +418,30 @@ func (h AuthHandler) validateServiceToken(ctx context.Context, token string) (*I
// 2. Find service token.
serviceToken, err := h.dal.FindServiceTokenByID(ctx, tokenID)
if err != nil {
- return nil, errutil.InternalServer("Failed to find service token")
+ return nil, errutil.DatabaseErr("Failed to find service token").WithErrf("validateServiceToken(tokenId=%s): %w", tokenID, err)
}
if serviceToken == nil {
- return nil, errutil.NotFound("Service token with ID '%s' not found", tokenID)
+ return nil, errutil.NotFound("Service token with ID '%s' not found", tokenID).WithErrf("validateServiceToken: token not found in DB")
}
// 3. Find project.
project, err := h.dal.FindProjectByID(ctx, serviceToken.ProjectId)
if err != nil {
- return nil, errutil.InternalServer("Failed to find project")
+ return nil, errutil.DatabaseErr("Failed to find project").WithErrf("validateServiceToken(projectId=%s): %w", serviceToken.ProjectId, err)
}
if project == nil {
- return nil, errutil.NotFound("Project with ID '%s' not found", serviceToken.ProjectId)
+ return nil, errutil.NotFound("Project with ID '%s' not found", serviceToken.ProjectId).WithErrf("validateServiceToken: project not found")
}
// 4. Check expiration.
if serviceToken.ExpiresAt.Valid && serviceToken.ExpiresAt.Time.Before(time.Now()) {
_ = h.dal.DeleteServiceTokenByID(ctx, serviceToken.ID)
- return nil, errutil.Forbidden("Service token has expired")
+ return nil, errutil.Forbidden("Service token has expired").WithErrf("validateServiceToken(tokenId=%s): token expired", serviceToken.ID)
}
// 5. Verify secret hash (bcrypt).
if err := bcrypt.CompareHashAndPassword([]byte(serviceToken.SecretHash), []byte(tokenSecret)); err != nil {
- return nil, errutil.Unauthorized("Invalid service token")
+ return nil, errutil.Unauthorized("Invalid service token").WithErrf("validateServiceToken(tokenId=%s): secret hash mismatch", serviceToken.ID)
}
// TODO(go): accessTokenQueue.updateServiceTokenStatus — update lastUsed timestamp
@@ -450,10 +449,10 @@ func (h AuthHandler) validateServiceToken(ctx context.Context, token string) (*I
// 6. Find org.
org, err := h.dal.FindOrgByID(ctx, project.OrgId)
if err != nil {
- return nil, errutil.InternalServer("Failed to find organization")
+ return nil, errutil.DatabaseErr("Failed to find organization").WithErrf("validateServiceToken(orgId=%s): %w", project.OrgId, err)
}
if org == nil {
- return nil, errutil.InternalServer("Organization not found for project")
+ return nil, errutil.NotFound("Organization not found for project").WithErrf("validateServiceToken(orgId=%s): org not found", project.OrgId)
}
// 7. Build identity.
diff --git a/backend-go/internal/services/auth/ip.go b/backend-go/internal/services/auth/ip.go
index eff927047f..e14140087d 100644
--- a/backend-go/internal/services/auth/ip.go
+++ b/backend-go/internal/services/auth/ip.go
@@ -36,7 +36,7 @@ func checkIPAgainstBlocklist(ipAddress string, trustedIPs []TrustedIP) error {
incoming := net.ParseIP(ipAddress)
if incoming == nil {
- return errutil.Forbidden("You are not allowed to access this resource from the current IP address")
+ return errutil.Forbidden("You are not allowed to access this resource from the current IP address").WithErrf("checkIPAgainstBlocklist: failed to parse IP %s", ipAddress)
}
for _, tip := range trustedIPs {
@@ -58,7 +58,7 @@ func checkIPAgainstBlocklist(ipAddress string, trustedIPs []TrustedIP) error {
}
}
- return errutil.Forbidden("You are not allowed to access this resource from the current IP address")
+ return errutil.Forbidden("You are not allowed to access this resource from the current IP address").WithErrf("checkIPAgainstBlocklist: IP %s not in allowlist", ipAddress)
}
// itoa converts an int to its decimal string representation without importing strconv.
diff --git a/backend-go/internal/services/kms/kms.go b/backend-go/internal/services/kms/kms.go
index f7f1b5613b..c4f528cea3 100644
--- a/backend-go/internal/services/kms/kms.go
+++ b/backend-go/internal/services/kms/kms.go
@@ -181,7 +181,7 @@ func (s *Service) Start(ctx context.Context, hsmConfigured bool) error {
})
if err != nil {
- return errutil.DatabaseErr("Failed to find or create KMS root config").WithErr(err)
+ return errutil.DatabaseErr("Failed to find or create KMS root config").WithErrf("Start: %w", err)
}
decryptedRootKey, err := s.decryptRootKey(rootConfig)
@@ -304,7 +304,7 @@ func (s *Service) generateEncryptedKeyMaterial() ([]byte, error) {
func (s *Service) decryptKmsKey(ctx context.Context, kmsKeyID uuid.UUID) ([]byte, error) {
kmsKeyDoc, err := s.dal.FindKmsKeyByID(ctx, kmsKeyID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find KMS key").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find KMS key").WithErrf("decryptKmsKey(kmsKeyId=%s): %w", kmsKeyID, err)
}
return s.decryptKmsKeyMaterial(kmsKeyDoc)
}
diff --git a/backend-go/internal/services/kms/kms_org.go b/backend-go/internal/services/kms/kms_org.go
index 84a204fa6a..7224dea6a8 100644
--- a/backend-go/internal/services/kms/kms_org.go
+++ b/backend-go/internal/services/kms/kms_org.go
@@ -13,7 +13,7 @@ import (
func (s *Service) getOrgDataKey(ctx context.Context, orgID uuid.UUID) ([]byte, error) {
org, err := s.dal.FindOrgKmsInfo(ctx, orgID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find organization KMS info").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find organization KMS info").WithErrf("getOrgDataKey(orgId=%s): %w", orgID, err)
}
// Ensure org has a KMS key (lazy create if missing).
@@ -23,7 +23,7 @@ func (s *Service) getOrgDataKey(ctx context.Context, orgID uuid.UUID) ([]byte, e
return s.generateEncryptedKeyMaterial()
})
if kmsErr != nil {
- return nil, errutil.DatabaseErr("Failed to ensure organization KMS key").WithErr(kmsErr)
+ return nil, errutil.DatabaseErr("Failed to ensure organization KMS key").WithErrf("getOrgDataKey(orgId=%s): %w", orgID, kmsErr)
}
kmsKeyID.V = createdKmsKeyID
kmsKeyID.Valid = true
@@ -33,7 +33,7 @@ func (s *Service) getOrgDataKey(ctx context.Context, orgID uuid.UUID) ([]byte, e
if org.KmsEncryptedDataKey == nil {
dataKey, dataErr := s.generateOrgDataKey(ctx, orgID, kmsKeyID.V)
if dataErr != nil {
- return nil, errutil.DatabaseErr("Failed to ensure organization data key").WithErr(dataErr)
+ return nil, errutil.DatabaseErr("Failed to ensure organization data key").WithErrf("getOrgDataKey(orgId=%s): %w", orgID, dataErr)
}
return dataKey, nil
}
@@ -66,7 +66,7 @@ func (s *Service) generateOrgDataKey(ctx context.Context, orgID, kmsKeyID uuid.U
})
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find or create organization data key").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find or create organization data key").WithErrf("generateOrgDataKey(orgId=%s): %w", orgID, err)
}
return decryptWithVersion(encryptedDataKey, kmsKey)
diff --git a/backend-go/internal/services/kms/kms_project.go b/backend-go/internal/services/kms/kms_project.go
index 0d3609fc30..b9bd415a5b 100644
--- a/backend-go/internal/services/kms/kms_project.go
+++ b/backend-go/internal/services/kms/kms_project.go
@@ -13,7 +13,7 @@ import (
func (s *Service) getProjectDataKey(ctx context.Context, projectID string) ([]byte, error) {
project, err := s.dal.FindProjectKmsInfo(ctx, projectID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find project KMS info").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find project KMS info").WithErrf("getProjectDataKey(projectId=%s): %w", projectID, err)
}
// Ensure project has a KMS key (lazy create if missing).
@@ -23,7 +23,7 @@ func (s *Service) getProjectDataKey(ctx context.Context, projectID string) ([]by
return s.generateEncryptedKeyMaterial()
})
if kmsErr != nil {
- return nil, errutil.DatabaseErr("Failed to ensure project KMS key").WithErr(kmsErr)
+ return nil, errutil.DatabaseErr("Failed to ensure project KMS key").WithErrf("getProjectDataKey(projectId=%s): %w", projectID, kmsErr)
}
kmsKeyID.V = createdKmsKeyID
kmsKeyID.Valid = true
@@ -33,7 +33,7 @@ func (s *Service) getProjectDataKey(ctx context.Context, projectID string) ([]by
if project.KmsSecretManagerEncryptedDataKey == nil {
dataKey, dataErr := s.generateProjectDataKey(ctx, projectID, kmsKeyID.V)
if dataErr != nil {
- return nil, errutil.DatabaseErr("Failed to ensure project data key").WithErr(dataErr)
+ return nil, errutil.DatabaseErr("Failed to ensure project data key").WithErrf("getProjectDataKey(projectId=%s): %w", projectID, dataErr)
}
return dataKey, nil
}
@@ -65,7 +65,7 @@ func (s *Service) generateProjectDataKey(ctx context.Context, projectID string,
return encryptWithVersion(plainDataKey, kmsKey)
})
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find or create project data key").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to find or create project data key").WithErrf("generateProjectDataKey(projectId=%s): %w", projectID, err)
}
return decryptWithVersion(encryptedDataKey, kmsKey)
diff --git a/backend-go/internal/services/permission/permission.go b/backend-go/internal/services/permission/permission.go
index ccb5a223de..0d9567fbfa 100644
--- a/backend-go/internal/services/permission/permission.go
+++ b/backend-go/internal/services/permission/permission.go
@@ -133,7 +133,7 @@ func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPerm
// 3. Validate actor type
if args.Actor != ActorTypeUser && args.Actor != ActorTypeIdentity {
- return nil, errutil.BadRequest("Invalid actor provided")
+ return nil, errutil.BadRequest("Invalid actor provided").WithErrf("GetProjectPermission: unsupported actor type %s", args.Actor)
}
// TODO(go): request-scoped memoization — avoid redundant permission checks within same request.
@@ -152,15 +152,15 @@ func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPerm
// 4. Find project
projectDetails, err := p.dal.FindProjectByID(ctx, args.ProjectID)
if err != nil {
- return nil, errutil.DatabaseErr("finding project").WithErr(err)
+ return nil, errutil.DatabaseErr("finding project").WithErrf("GetProjectPermission(projectId=%s): %w", args.ProjectID, err)
}
if projectDetails == nil {
- return nil, errutil.NotFound("Project with %s not found", args.ProjectID)
+ return nil, errutil.NotFound("Project with %s not found", args.ProjectID).WithErrf("GetProjectPermission: project not found in DB")
}
// 5. Org ownership
if projectDetails.OrgID != args.ActorOrgID {
- return nil, errutil.Forbidden("This project does not belong to your selected organization.")
+ return nil, errutil.Forbidden("This project does not belong to your selected organization.").WithErrf("GetProjectPermission(projectId=%s): org mismatch projectOrg=%s actorOrg=%s", args.ProjectID, projectDetails.OrgID, args.ActorOrgID)
}
// 6. ActionProjectType check
@@ -168,7 +168,7 @@ func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPerm
return nil, errutil.BadRequest(
"The project is of type %s. Operations of type %s are not allowed.",
projectDetails.Type, string(args.ActionProjectType),
- )
+ ).WithErrf("GetProjectPermission(projectId=%s): type mismatch", args.ProjectID)
}
// 7. Query permission data
@@ -180,7 +180,7 @@ func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPerm
ActorType: args.Actor,
})
if err != nil {
- return nil, errutil.DatabaseErr("getting project permission").WithErr(err)
+ return nil, errutil.DatabaseErr("getting project permission").WithErrf("GetProjectPermission(projectId=%s, actorId=%s): %w", args.ProjectID, args.ActorID, err)
}
// 8. Empty check
@@ -188,7 +188,7 @@ func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPerm
return nil, errutil.Forbidden(
"You are not a member of this project with ID %s. Please assign this %s to the project with the appropriate permissions, then try again.",
args.ProjectID, string(args.Actor),
- )
+ ).WithErrf("GetProjectPermission(projectId=%s, actorId=%s): no membership found", args.ProjectID, args.ActorID)
}
// 9. Flatten active roles
@@ -215,12 +215,12 @@ func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPerm
if args.Actor == ActorTypeUser {
username, err = p.dal.FindUserUsername(ctx, args.ActorID)
if err != nil {
- return nil, errutil.DatabaseErr("finding user username").WithErr(err)
+ return nil, errutil.DatabaseErr("finding user username").WithErrf("GetProjectPermission(userId=%s): %w", args.ActorID, err)
}
} else {
username, err = p.dal.FindIdentityName(ctx, args.ActorID)
if err != nil {
- return nil, errutil.DatabaseErr("finding identity name").WithErr(err)
+ return nil, errutil.DatabaseErr("finding identity name").WithErrf("GetProjectPermission(identityId=%s): %w", args.ActorID, err)
}
}
@@ -278,29 +278,29 @@ func (p *Service) getServiceTokenProjectPermission(
// 1. Find service token
serviceToken, err := p.dal.FindServiceTokenByID(ctx, serviceTokenID)
if err != nil {
- return nil, errutil.DatabaseErr("finding service token").WithErr(err)
+ return nil, errutil.DatabaseErr("finding service token").WithErrf("getServiceTokenProjectPermission(tokenId=%s): %w", serviceTokenID, err)
}
if serviceToken == nil {
- return nil, errutil.NotFound("Service token with ID '%s' not found", serviceTokenID)
+ return nil, errutil.NotFound("Service token with ID '%s' not found", serviceTokenID).WithErrf("getServiceTokenProjectPermission: token not found in DB")
}
// 2. Verify project linked
serviceTokenProject, err := p.dal.FindProjectByID(ctx, serviceToken.ProjectID)
if err != nil {
- return nil, errutil.DatabaseErr("finding service token project").WithErr(err)
+ return nil, errutil.DatabaseErr("finding service token project").WithErrf("getServiceTokenProjectPermission(projectId=%s): %w", serviceToken.ProjectID, err)
}
if serviceTokenProject == nil {
- return nil, errutil.BadRequest("Service token not linked to a project")
+ return nil, errutil.BadRequest("Service token not linked to a project").WithErrf("getServiceTokenProjectPermission(tokenId=%s): project not found", serviceTokenID)
}
// 3. Verify projectId match
if serviceToken.ProjectID != projectID {
- return nil, errutil.Forbidden("Service token not a part of the specified project with ID %s", projectID)
+ return nil, errutil.Forbidden("Service token not a part of the specified project with ID %s", projectID).WithErrf("getServiceTokenProjectPermission(tokenId=%s): project mismatch tokenProject=%s requestedProject=%s", serviceTokenID, serviceToken.ProjectID, projectID)
}
// 4. Verify orgId match
if serviceTokenProject.OrgID != actorOrgID {
- return nil, errutil.Forbidden("Service token not a part of the specified organization with ID %s", actorOrgID.String())
+ return nil, errutil.Forbidden("Service token not a part of the specified organization with ID %s", actorOrgID.String()).WithErrf("getServiceTokenProjectPermission(tokenId=%s): org mismatch", serviceTokenID)
}
// 5. Verify actionProjectType match
@@ -308,7 +308,7 @@ func (p *Service) getServiceTokenProjectPermission(
return nil, errutil.BadRequest(
"The project is of type %s. Operations of type %s are not allowed.",
serviceTokenProject.Type, string(actionProjectType),
- )
+ ).WithErrf("getServiceTokenProjectPermission(tokenId=%s): type mismatch", serviceTokenID)
}
// 6. Parse scopes and build rules
diff --git a/backend-go/internal/services/secretmanager/secretfolder/secret_folder.go b/backend-go/internal/services/secretmanager/secretfolder/secret_folder.go
index 92160efd44..7260fe3023 100644
--- a/backend-go/internal/services/secretmanager/secretfolder/secret_folder.go
+++ b/backend-go/internal/services/secretmanager/secretfolder/secret_folder.go
@@ -29,7 +29,7 @@ func NewService(deps Deps) *Service {
func (s *Service) LoadProjectFolders(ctx context.Context, projectID string, envIDs []uuid.UUID) (*FolderLookup, error) {
rows, err := s.dal.GetFoldersByProjectAndEnvIDs(ctx, projectID, envIDs)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to get folders for project").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to get folders for project").WithErrf("LoadProjectFolders(projectId=%s): %w", projectID, err)
}
return newFolderLookup(rows), nil
}
diff --git a/backend-go/internal/services/secretmanager/secretimport/secret_import.go b/backend-go/internal/services/secretmanager/secretimport/secret_import.go
index 8ea8269f5a..6fbad7de4a 100644
--- a/backend-go/internal/services/secretmanager/secretimport/secret_import.go
+++ b/backend-go/internal/services/secretmanager/secretimport/secret_import.go
@@ -27,7 +27,7 @@ func NewService(deps Deps) *Service {
func (s *Service) LoadProjectImports(ctx context.Context, projectID string) (*ImportLookup, error) {
rows, err := s.dal.GetImportsByProjectID(ctx, projectID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to get imports for project").WithErr(err)
+ return nil, errutil.DatabaseErr("Failed to get imports for project").WithErrf("LoadProjectImports(projectId=%s): %w", projectID, err)
}
return newImportLookup(rows), nil
}
diff --git a/backend-go/internal/services/serverconfig/serverconfig.go b/backend-go/internal/services/serverconfig/serverconfig.go
index 3fb7ef8325..bac6efa7c9 100644
--- a/backend-go/internal/services/serverconfig/serverconfig.go
+++ b/backend-go/internal/services/serverconfig/serverconfig.go
@@ -138,7 +138,7 @@ func (s *Service) Init(ctx context.Context) (ServerConfig, error) {
m, err := s.dal.FindOrCreateConfig(ctx)
if err != nil {
- return ServerConfig{}, errutil.DatabaseErr("Failed to initialize server config").WithErr(err)
+ return ServerConfig{}, errutil.DatabaseErr("Failed to initialize server config").WithErrf("Init: %w", err)
}
return configFromModel(m), nil
}
@@ -162,7 +162,7 @@ func (s *Service) GetConfig(ctx context.Context) (ServerConfig, error) {
// Cache miss — read from DB.
m, err := s.dal.FindByID(ctx, adminConfigDBUUID)
if err != nil {
- return ServerConfig{}, errutil.DatabaseErr("Failed to read server config").WithErr(err)
+ return ServerConfig{}, errutil.DatabaseErr("Failed to read server config").WithErrf("GetConfig: %w", err)
}
cfg := configFromModel(m)