Skip to content

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

feat: implemented auth injection

=d7ad73461a38
diff --git a/backend-go/CLAUDE.md b/backend-go/CLAUDE.md
index 22d347a085..bc5e31a49d 100644
--- a/backend-go/CLAUDE.md
+++ b/backend-go/CLAUDE.md
@@ -24,6 +24,7 @@ Never edit generated code in `gen/` directories — always regenerate.
- **Interfaces for dependencies**: Consumer defines the interface (narrow, only needed methods). Accept interfaces, not concrete types.
- **Service constructor signature**: `<NewService|NewSharedService>(ctx context.Context, 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.
- **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)`. This logs the real DB error internally but only shows the safe message to clients. Never return raw database errors to the caller.
- **Lean code**: Inline helpers with one caller. Only extract when shared. Split DAL files by functionality.
## Architecture
diff --git a/backend-go/go.mod b/backend-go/go.mod
index 81c1e2351e..d8dbac10d5 100644
--- a/backend-go/go.mod
+++ b/backend-go/go.mod
@@ -69,7 +69,7 @@ require (
github.com/gofrs/flock v0.13.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/gohugoio/hashstructure v0.6.0 // indirect
- github.com/golang-jwt/jwt/v5 v5.3.0 // indirect
+ github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
diff --git a/backend-go/go.sum b/backend-go/go.sum
index c01db72e1b..38590c726a 100644
--- a/backend-go/go.sum
+++ b/backend-go/go.sum
@@ -203,6 +203,8 @@ github.com/gohugoio/hashstructure v0.6.0 h1:7wMB/2CfXoThFYhdWRGv3u3rUM761Cq29CxU
github.com/gohugoio/hashstructure v0.6.0/go.mod h1:lapVLk9XidheHG1IQ4ZSbyYrXcaILU1ZEP/+vno5rBQ=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
diff --git a/backend-go/internal/libs/authutil/authutil.go b/backend-go/internal/libs/authutil/authutil.go
deleted file mode 100644
index f5dae1a6f0..0000000000
--- a/backend-go/internal/libs/authutil/authutil.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// Package authutil provides authentication types and context helpers
-// for propagating identity information through request handling.
-package authutil
-
-import (
- "context"
-
- "github.com/infisical/api/internal/services/shared/permission"
-)
-
-// AuthMode identifies the authentication mechanism used by the caller.
-type AuthMode string
-
-const (
- AuthModeJWT AuthMode = "jwt"
- AuthModeIdentityAccessToken AuthMode = "identity_access_token"
- AuthModeServiceToken AuthMode = "service_token"
-)
-
-// Identity holds the resolved actor information extracted from a request token.
-// It is the Go equivalent of the Node.js backend's req.permission object.
-type Identity struct {
- AuthMode AuthMode
- Actor permission.ActorType
- ActorID string
- OrgID string
- AuthMethod permission.ActorAuthMethod
-}
-
-type ctxKey struct{}
-
-// WithIdentity stores the given identity in the context.
-func WithIdentity(ctx context.Context, id *Identity) context.Context {
- return context.WithValue(ctx, ctxKey{}, id)
-}
-
-// IdentityFromContext returns the identity stored in ctx, or nil if absent.
-func IdentityFromContext(ctx context.Context) *Identity {
- id, _ := ctx.Value(ctxKey{}).(*Identity)
- return id
-}
diff --git a/backend-go/internal/libs/authutil/handler.go b/backend-go/internal/libs/authutil/handler.go
deleted file mode 100644
index 5456e44709..0000000000
--- a/backend-go/internal/libs/authutil/handler.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package authutil
-
-import (
- "context"
-
- "goa.design/goa/v3/security"
-
- "github.com/infisical/api/internal/libs/errutil"
- "github.com/infisical/api/internal/services/shared/permission"
-)
-
-// AuthHandler implements the Goa-generated authorization interface (JWTAuth method).
-// Embed this in service structs to satisfy the generated security contract.
-type AuthHandler struct{}
-
-// JWTAuth implements the authorization logic for all JWT-based security schemes.
-// Goa calls this for each scheme in order (jwt → identity_access_token → service_token)
-// with the scheme name in sc.Name. We classify the token cheaply and only accept
-// when the token type matches the scheme being tried.
-func (AuthHandler) JWTAuth(ctx context.Context, token string, sc *security.JWTScheme) (context.Context, error) {
- if token == "" {
- return ctx, errutil.Unauthorized("Token missing")
- }
-
- tokenMode := ClassifyToken(token)
- if tokenMode == "" {
- return ctx, errutil.Unauthorized("You are not allowed to access this resource")
- }
-
- // Map scheme name to the expected auth mode.
- var expectedMode AuthMode
- switch sc.Name {
- case "jwt":
- expectedMode = AuthModeJWT
- case "identity_access_token":
- expectedMode = AuthModeIdentityAccessToken
- case "service_token":
- expectedMode = AuthModeServiceToken
- default:
- return ctx, errutil.Unauthorized("You are not allowed to access this resource")
- }
-
- // 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")
- }
-
- // TODO: Replace mock with real token validation (JWT verification, DB lookups, etc.)
- identity := buildMockIdentity(tokenMode)
-
- return WithIdentity(ctx, identity), nil
-}
-
-// buildMockIdentity creates a placeholder identity from the classified token mode.
-// This will be replaced with real validation logic.
-func buildMockIdentity(mode AuthMode) *Identity {
- switch mode {
- case AuthModeJWT:
- return &Identity{
- AuthMode: AuthModeJWT,
- Actor: permission.ActorTypeUser,
- ActorID: "mock-user-id",
- OrgID: "mock-org-id",
- }
- case AuthModeIdentityAccessToken:
- return &Identity{
- AuthMode: AuthModeIdentityAccessToken,
- Actor: permission.ActorTypeIdentity,
- ActorID: "mock-identity-id",
- OrgID: "mock-org-id",
- }
- case AuthModeServiceToken:
- return &Identity{
- AuthMode: AuthModeServiceToken,
- Actor: permission.ActorTypeService,
- ActorID: "mock-service-token-id",
- OrgID: "mock-org-id",
- }
- default:
- return &Identity{
- AuthMode: mode,
- Actor: permission.ActorTypeUser,
- ActorID: "mock-unknown-id",
- OrgID: "mock-org-id",
- }
- }
-}
diff --git a/backend-go/internal/libs/errutil/error.go b/backend-go/internal/libs/errutil/error.go
index 714a21a4ab..52b2b023ab 100644
--- a/backend-go/internal/libs/errutil/error.go
+++ b/backend-go/internal/libs/errutil/error.go
@@ -19,6 +19,21 @@ type Error struct {
Err error
}
+func (e *Error) WithName(name string) *Error {
+ e.Name = name
+ return e
+}
+
+func (e *Error) WithStatus(status int) *Error {
+ e.Status = status
+ return e
+}
+
+func (e *Error) WithMessage(message string) *Error {
+ e.Message = message
+ return e
+}
+
func (e *Error) Error() string {
if e.Err != nil {
return e.Message + ": " + e.Err.Error()
diff --git a/backend-go/internal/services/platform/platform.go b/backend-go/internal/services/platform/platform.go
index 95ee9c11aa..57ca6c12e1 100644
--- a/backend-go/internal/services/platform/platform.go
+++ b/backend-go/internal/services/platform/platform.go
@@ -16,7 +16,8 @@ func NewRegistry(logger *slog.Logger, sharedLibs *shared.SharedServices) *Regist
l := logger.With(slog.String("product", "platform"))
return &Registry{
Projects: projects.NewService(l, projects.Deps{
- Permission: sharedLibs.Permission,
+ AuthHandler: sharedLibs.AuthHandler,
+ Permission: sharedLibs.Permission,
}),
}
}
diff --git a/backend-go/internal/services/platform/projects/projects.go b/backend-go/internal/services/platform/projects/projects.go
index 2543ebb881..c4908cd529 100644
--- a/backend-go/internal/services/platform/projects/projects.go
+++ b/backend-go/internal/services/platform/projects/projects.go
@@ -4,7 +4,8 @@ import (
"context"
"log/slog"
- "github.com/infisical/api/internal/libs/authutil"
+ "github.com/infisical/api/internal/services/shared/auth"
+
genprojects "github.com/infisical/api/internal/server/gen/projects"
"github.com/infisical/api/internal/services/shared/permission"
)
@@ -14,20 +15,22 @@ type permissionGetter interface {
}
type service struct {
- authutil.AuthHandler
+ auth.AuthHandler
logger *slog.Logger
permission permissionGetter
}
// Deps holds the dependencies for the projects service.
type Deps struct {
- Permission permissionGetter
+ AuthHandler auth.AuthHandler
+ Permission permissionGetter
}
func NewService(logger *slog.Logger, deps Deps) genprojects.Service {
return &service{
- logger: logger.With(slog.String("service", "projects")),
- permission: deps.Permission,
+ AuthHandler: deps.AuthHandler,
+ logger: logger.With(slog.String("service", "projects")),
+ permission: deps.Permission,
}
}
diff --git a/backend-go/internal/services/secretmanager/secret_manager.go b/backend-go/internal/services/secretmanager/secret_manager.go
index 3974b87aee..806223aecc 100644
--- a/backend-go/internal/services/secretmanager/secret_manager.go
+++ b/backend-go/internal/services/secretmanager/secret_manager.go
@@ -23,6 +23,7 @@ func NewRegistry(logger *slog.Logger, db pg.DB, sharedServices *shared.SharedSer
return &Registry{
Secrets: secrets.NewService(l, secrets.Deps{
+ AuthHandler: sharedServices.AuthHandler,
Permission: sharedServices.Permission,
SecretFolder: smSharedService.SecretFolder,
}),
diff --git a/backend-go/internal/services/secretmanager/secrets/secrets.go b/backend-go/internal/services/secretmanager/secrets/secrets.go
index 7d78e9d75b..ad78868d6f 100644
--- a/backend-go/internal/services/secretmanager/secrets/secrets.go
+++ b/backend-go/internal/services/secretmanager/secrets/secrets.go
@@ -4,7 +4,8 @@ import (
"context"
"log/slog"
- "github.com/infisical/api/internal/libs/authutil"
+ "github.com/infisical/api/internal/services/shared/auth"
+
gensecrets "github.com/infisical/api/internal/server/gen/secrets"
"github.com/infisical/api/internal/services/shared/permission"
)
@@ -16,7 +17,7 @@ type permissionSvc interface {
type secretFolderSvc any
type service struct {
- authutil.AuthHandler
+ auth.AuthHandler
logger *slog.Logger
permissionSvc permissionSvc
secretFolderSvc secretFolderSvc
@@ -24,12 +25,14 @@ type service struct {
// Deps holds the dependencies for the secrets service.
type Deps struct {
+ AuthHandler auth.AuthHandler
Permission permissionSvc
SecretFolder secretFolderSvc
}
func NewService(logger *slog.Logger, deps Deps) gensecrets.Service {
return &service{
+ AuthHandler: deps.AuthHandler,
logger: logger.With(slog.String("service", "secrets")),
permissionSvc: deps.Permission,
secretFolderSvc: deps.SecretFolder,
diff --git a/backend-go/internal/services/shared/auth/auth.go b/backend-go/internal/services/shared/auth/auth.go
new file mode 100644
index 0000000000..04c3238833
--- /dev/null
+++ b/backend-go/internal/services/shared/auth/auth.go
@@ -0,0 +1,89 @@
+// Package auth provides authentication types, token validation, and context helpers
+// for propagating identity information through request handling.
+package auth
+
+import (
+ "context"
+
+ "github.com/infisical/api/internal/services/shared/permission"
+)
+
+// AuthMode identifies the authentication mechanism used by the caller.
+type AuthMode string
+
+const (
+ AuthModeJWT AuthMode = "jwt"
+ AuthModeIdentityAccessToken AuthMode = "identity_access_token"
+ AuthModeServiceToken AuthMode = "service_token"
+)
+
+// UserAuthInfo holds the minimal user info stored in request context for audit logging.
+// Port of Node.js requestContext.userAuthInfo.
+type UserAuthInfo struct {
+ UserID string
+ Email string
+}
+
+// IdentityAuthInfo holds the minimal identity info stored in request context for audit logging.
+// Port of Node.js requestContext.identityAuthInfo.
+type IdentityAuthInfo struct {
+ IdentityID string
+ IdentityName string
+ AuthMethod string
+ OIDC *IdentityAuthOIDC
+ Kubernetes *IdentityAuthKubernetes
+ AWS *IdentityAuthAWS
+}
+
+// IdentityAuthOIDC holds OIDC-specific claims from the identity JWT payload.
+type IdentityAuthOIDC struct {
+ Claims map[string]string `json:"claims"`
+}
+
+// IdentityAuthKubernetes holds Kubernetes-specific metadata from the identity JWT payload.
+type IdentityAuthKubernetes struct {
+ Namespace string `json:"namespace"`
+ Name string `json:"name"`
+}
+
+// IdentityAuthAWS holds AWS-specific principal details from the identity JWT payload.
+type IdentityAuthAWS struct {
+ AccountID string `json:"accountId"`
+ ARN string `json:"arn"`
+ UserID string `json:"userId"`
+ Partition string `json:"partition"`
+ Service string `json:"service"`
+ ResourceType string `json:"resourceType"`
+ ResourceName string `json:"resourceName"`
+}
+
+// Identity holds the resolved actor information extracted from a request token.
+// It is the Go equivalent of the Node.js backend's req.auth / req.permission object.
+type Identity struct {
+ AuthMode AuthMode
+ Actor permission.ActorType
+ ActorID string
+ OrgID string
+ RootOrgID string
+ ParentOrgID string
+ AuthMethod permission.ActorAuthMethod
+ IsSuperAdmin bool
+
+ // UserAuthInfo is set for JWT (user) auth. Used for audit logging.
+ UserAuthInfo *UserAuthInfo
+ // IdentityAuthInfo is set for identity access token auth. Used for audit logging.
+ IdentityAuthInfo *IdentityAuthInfo
+}
+
+type ctxKey struct{}
+
+// WithIdentity stores the given identity in the context.
+func WithIdentity(ctx context.Context, id *Identity) context.Context {
+ return context.WithValue(ctx, ctxKey{}, id)
+}
+
+// IdentityFromContext returns the identity stored in ctx, or nil if absent.
+func IdentityFromContext(ctx context.Context) *Identity {
+ id, _ := ctx.Value(ctxKey{}).(*Identity)
+ return id
+}
diff --git a/backend-go/internal/services/shared/auth/claims.go b/backend-go/internal/services/shared/auth/claims.go
new file mode 100644
index 0000000000..eebd92274a
--- /dev/null
+++ b/backend-go/internal/services/shared/auth/claims.go
@@ -0,0 +1,36 @@
+package auth
+
+import "github.com/golang-jwt/jwt/v5"
+
+// UserJWTClaims represents the JWT payload for user browser sessions.
+// Exact match of the Node.js AuthModeJwtTokenPayload.
+type UserJWTClaims struct {
+ jwt.RegisteredClaims
+ AuthTokenType string `json:"authTokenType"`
+ AuthMethod string `json:"authMethod,omitempty"`
+ UserID string `json:"userId"`
+ TokenVersionID string `json:"tokenVersionId"`
+ AccessVersion int `json:"accessVersion"`
+ OrganizationID string `json:"organizationId,omitempty"`
+ SubOrganizationID string `json:"subOrganizationId,omitempty"`
+ IsMfaVerified bool `json:"isMfaVerified,omitempty"`
+}
+
+// IdentityJWTClaims represents the JWT payload for machine identity access tokens.
+// Exact match of the Node.js TIdentityAccessTokenJwtPayload.
+type IdentityJWTClaims struct {
+ jwt.RegisteredClaims
+ AuthTokenType string `json:"authTokenType"`
+ IdentityID string `json:"identityId"`
+ ClientSecretID string `json:"clientSecretId"`
+ IdentityAccessTokenID string `json:"identityAccessTokenId"`
+ IdentityAuth *IdentityAuth `json:"identityAuth,omitempty"`
+}
+
+// IdentityAuth holds auth-method-specific metadata from the identity JWT payload.
+// Used to populate IdentityAuthInfo for audit logging.
+type IdentityAuth struct {
+ OIDC *IdentityAuthOIDC `json:"oidc,omitempty"`
+ Kubernetes *IdentityAuthKubernetes `json:"kubernetes,omitempty"`
+ AWS *IdentityAuthAWS `json:"aws,omitempty"`
+}
diff --git a/backend-go/internal/libs/authutil/classify.go b/backend-go/internal/services/shared/auth/classify.go
similarity index 81%
rename from backend-go/internal/libs/authutil/classify.go
rename to backend-go/internal/services/shared/auth/classify.go
index 876263c9a5..265421178a 100644
--- a/backend-go/internal/libs/authutil/classify.go
+++ b/backend-go/internal/services/shared/auth/classify.go
@@ -1,4 +1,4 @@
-package authutil
+package auth
import (
"encoding/base64"
@@ -6,9 +6,9 @@ import (
"strings"
)
-// jwtClaims is a minimal struct for peeking at the token type
+// peekClaims is a minimal struct for peeking at the token type
// without performing signature verification.
-type jwtClaims struct {
+type peekClaims struct {
AuthTokenType string `json:"authTokenType"`
}
@@ -32,18 +32,18 @@ func ClassifyToken(token string) AuthMode {
// peekJWTClaims decodes the JWT payload segment (no signature verification)
// to inspect the authTokenType claim.
-func peekJWTClaims(token string) jwtClaims {
+func peekJWTClaims(token string) peekClaims {
parts := strings.SplitN(token, ".", 4)
if len(parts) < 3 {
- return jwtClaims{}
+ return peekClaims{}
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
- return jwtClaims{}
+ return peekClaims{}
}
- var claims jwtClaims
+ var claims peekClaims
_ = json.Unmarshal(payload, &claims)
return claims
diff --git a/backend-go/internal/services/shared/auth/classify_test.go b/backend-go/internal/services/shared/auth/classify_test.go
new file mode 100644
index 0000000000..a964689b50
--- /dev/null
+++ b/backend-go/internal/services/shared/auth/classify_test.go
@@ -0,0 +1,76 @@
+package auth
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "testing"
+)
+
+// makeJWT builds a minimal unsigned JWT with the given payload claims for testing.
+func makeJWT(claims map[string]any) string {
+ header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`))
+ payload, _ := json.Marshal(claims)
+ payloadEnc := base64.RawURLEncoding.EncodeToString(payload)
+ return header + "." + payloadEnc + ".fakesignature"
+}
+
+func TestClassifyToken(t *testing.T) {
+ t.Run("service token", func(t *testing.T) {
+ mode := ClassifyToken("st.abc123.secretpart")
+ if mode != AuthModeServiceToken {
+ t.Errorf("expected %q, got %q", AuthModeServiceToken, mode)
+ }
+ })
+
+ t.Run("JWT access token", func(t *testing.T) {
+ token := makeJWT(map[string]any{"authTokenType": "AccessToken", "userId": "u1"})
+ mode := ClassifyToken(token)
+ if mode != AuthModeJWT {
+ t.Errorf("expected %q, got %q", AuthModeJWT, mode)
+ }
+ })
+
+ t.Run("identity access token", func(t *testing.T) {
+ token := makeJWT(map[string]any{"authTokenType": "IdentityAccessToken", "identityId": "id1"})
+ mode := ClassifyToken(token)
+ if mode != AuthModeIdentityAccessToken {
+ t.Errorf("expected %q, got %q", AuthModeIdentityAccessToken, mode)
+ }
+ })
+
+ t.Run("empty token returns empty", func(t *testing.T) {
+ mode := ClassifyToken("")
+ if mode != "" {
+ t.Errorf("expected empty, got %q", mode)
+ }
+ })
+
+ t.Run("random string returns empty", func(t *testing.T) {
+ mode := ClassifyToken("some-random-string")
+ if mode != "" {
+ t.Errorf("expected empty, got %q", mode)
+ }
+ })
+
+ t.Run("JWT with unknown authTokenType returns empty", func(t *testing.T) {
+ token := makeJWT(map[string]any{"authTokenType": "SomethingElse"})
+ mode := ClassifyToken(token)
+ if mode != "" {
+ t.Errorf("expected empty, got %q", mode)
+ }
+ })
+
+ t.Run("malformed JWT with two parts returns empty", func(t *testing.T) {
+ mode := ClassifyToken("part1.part2")
+ if mode != "" {
+ t.Errorf("expected empty, got %q", mode)
+ }
+ })
+
+ t.Run("JWT with invalid base64 payload returns empty", func(t *testing.T) {
+ mode := ClassifyToken("header.!!!invalid!!!.signature")
+ if mode != "" {
+ t.Errorf("expected empty, got %q", mode)
+ }
+ })
+}
diff --git a/backend-go/internal/services/shared/auth/dal.go b/backend-go/internal/services/shared/auth/dal.go
new file mode 100644
index 0000000000..985149e40c
--- /dev/null
+++ b/backend-go/internal/services/shared/auth/dal.go
@@ -0,0 +1,416 @@
+package auth
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+
+ "github.com/go-jet/jet/v2/postgres"
+ "github.com/go-jet/jet/v2/qrm"
+ "github.com/google/uuid"
+
+ "github.com/infisical/api/internal/database/pg"
+ "github.com/infisical/api/internal/database/pg/gen/table"
+ "github.com/infisical/api/internal/services/shared/permission"
+)
+
+// DAL provides data access for authentication-related queries.
+// All reads use the replica; writes (deletes) hit primary.
+type DAL struct {
+ db pg.DB
+}
+
+// NewDAL creates a new auth DAL.
+func NewDAL(db pg.DB) *DAL {
+ return &DAL{db: db}
+}
+
+// --- Sessions ---
+
+// SessionRow holds the subset of auth_token_sessions used by the auth handler.
+type SessionRow struct {
+ AccessVersion int32 `alias:"auth_token_sessions.access_version"`
+ UserId uuid.UUID `alias:"auth_token_sessions.user_id"`
+}
+
+// FindSessionByIDAndUserID returns the session matching id + userId, or nil if not found.
+func (d *DAL) FindSessionByIDAndUserID(ctx context.Context, sessionID, userID uuid.UUID) (*SessionRow, error) {
+ s := table.AuthTokenSessions
+
+ stmt := postgres.SELECT(s.AccessVersion, s.UserId).
+ FROM(s).
+ WHERE(postgres.AND(
+ s.ID.EQ(postgres.UUID(sessionID)),
+ s.UserId.EQ(postgres.UUID(userID)),
+ ))
+
+ var row SessionRow
+ err := stmt.QueryContext(ctx, d.db.Replica(), &row)
+ if err != nil {
+ if errors.Is(err, qrm.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return &row, nil
+}
+
+// --- Users ---
+
+// UserRow holds the subset of users used by the auth handler.
+type UserRow struct {
+ ID uuid.UUID `alias:"users.id"`
+ Email sql.NullString `alias:"users.email"`
+ IsAccepted sql.Null[bool] `alias:"users.is_accepted"`
+ SuperAdmin sql.Null[bool] `alias:"users.super_admin"`
+}
+
+// FindUserByID returns the user matching id, or nil if not found.
+func (d *DAL) FindUserByID(ctx context.Context, id uuid.UUID) (*UserRow, error) {
+ u := table.Users
+
+ stmt := postgres.SELECT(u.ID, u.Email, u.IsAccepted, u.SuperAdmin).
+ FROM(u).
+ WHERE(u.ID.EQ(postgres.UUID(id)))
+
+ var row UserRow
+ err := stmt.QueryContext(ctx, d.db.Replica(), &row)
+ if err != nil {
+ if errors.Is(err, qrm.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return &row, nil
+}
+
+// --- Organizations ---
+
+// OrgRow holds the subset of organizations used by the auth handler.
+type OrgRow struct {
+ ID uuid.UUID `alias:"organizations.id"`
+ RootOrgId sql.Null[uuid.UUID] `alias:"organizations.root_org_id"`
+ ParentOrgId sql.Null[uuid.UUID] `alias:"organizations.parent_org_id"`
+}
+
+// FindOrgByID returns the organization matching id, or nil if not found.
+func (d *DAL) FindOrgByID(ctx context.Context, id uuid.UUID) (*OrgRow, error) {
+ o := table.Organizations
+
+ stmt := postgres.SELECT(o.ID, o.RootOrgId, o.ParentOrgId).
+ FROM(o).
+ WHERE(o.ID.EQ(postgres.UUID(id)))
+
+ var row OrgRow
+ err := stmt.QueryContext(ctx, d.db.Replica(), &row)
+ if err != nil {
+ if errors.Is(err, qrm.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return &row, nil
+}
+
+// --- Projects ---
+
+// ProjectRow holds the subset of projects used by the auth handler.
+type ProjectRow struct {
+ OrgId uuid.UUID `alias:"projects.org_id"`
+}
+
+// FindProjectByID returns the project matching id, or nil if not found.
+func (d *DAL) FindProjectByID(ctx context.Context, id string) (*ProjectRow, error) {
+ p := table.Projects
+
+ stmt := postgres.SELECT(p.OrgId).
+ FROM(p).
+ WHERE(p.ID.EQ(postgres.String(id)))
+
+ var row ProjectRow
+ err := stmt.QueryContext(ctx, d.db.Replica(), &row)
+ if err != nil {
+ if errors.Is(err, qrm.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return &row, nil
+}
+
+// --- Identity Access Tokens ---
+
+// 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"`
+
+ // Joined from identities table.
+ IdentityOrgID uuid.UUID `alias:"identities.org_id"`
+ IdentityName string `alias:"identities.name"`
+}
+
+// FindIdentityAccessTokenByID returns the token (joined with identity) if not revoked, or nil.
+func (d *DAL) FindIdentityAccessTokenByID(ctx context.Context, id string) (*IdentityAccessTokenRow, error) {
+ iat := table.IdentityAccessTokens
+ ident := table.Identities
+
+ stmt := postgres.SELECT(
+ iat.ID,
+ iat.AccessTokenTTL,
+ iat.AccessTokenMaxTTL,
+ iat.AccessTokenNumUses,
+ iat.AccessTokenNumUsesLimit,
+ iat.AccessTokenLastRenewedAt,
+ iat.IsAccessTokenRevoked,
+ iat.IdentityId,
+ iat.CreatedAt,
+ iat.AuthMethod,
+ iat.AccessTokenPeriod,
+ iat.SubOrganizationId,
+ ident.OrgId,
+ ident.Name,
+ ).FROM(
+ iat.INNER_JOIN(ident, iat.IdentityId.EQ(ident.ID)),
+ ).WHERE(postgres.AND(
+ iat.ID.EQ(postgres.String(id)),
+ iat.IsAccessTokenRevoked.EQ(postgres.Bool(false)),
+ ))
+
+ var row IdentityAccessTokenRow
+ err := stmt.QueryContext(ctx, d.db.Replica(), &row)
+ if err != nil {
+ if errors.Is(err, qrm.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return &row, nil
+}
+
+// DeleteIdentityAccessTokenByID deletes the token on primary. Used for expired/exceeded tokens.
+func (d *DAL) DeleteIdentityAccessTokenByID(ctx context.Context, id string) error {
+ iat := table.IdentityAccessTokens
+
+ stmt := iat.DELETE().WHERE(iat.ID.EQ(postgres.String(id)))
+ _, err := stmt.ExecContext(ctx, d.db.Primary())
+ return err
+}
+
+// --- Service Tokens ---
+
+// ServiceTokenRow holds the subset of service_tokens used by the auth handler.
+type ServiceTokenRow struct {
+ ID string `alias:"service_tokens.id"`
+ ProjectId string `alias:"service_tokens.project_id"`
+ ExpiresAt sql.NullTime `alias:"service_tokens.expires_at"`
+ SecretHash string `alias:"service_tokens.secret_hash"`
+}
+
+// FindServiceTokenByID returns the service token matching id, or nil.
+func (d *DAL) FindServiceTokenByID(ctx context.Context, id string) (*ServiceTokenRow, error) {
+ st := table.ServiceTokens
+
+ stmt := postgres.SELECT(st.ID, st.ProjectId, st.ExpiresAt, st.SecretHash).
+ FROM(st).
+ WHERE(st.ID.EQ(postgres.String(id)))
+
+ var row ServiceTokenRow
+ err := stmt.QueryContext(ctx, d.db.Replica(), &row)
+ if err != nil {
+ if errors.Is(err, qrm.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return &row, nil
+}
+
+// DeleteServiceTokenByID deletes the service token on primary. Used for expired tokens.
+func (d *DAL) DeleteServiceTokenByID(ctx context.Context, id string) error {
+ st := table.ServiceTokens
+
+ stmt := st.DELETE().WHERE(st.ID.EQ(postgres.String(id)))
+ _, err := stmt.ExecContext(ctx, d.db.Primary())
+ return err
+}
+
+// --- Memberships ---
+
+// MembershipRow holds the subset of memberships used by the auth handler.
+type MembershipRow struct {
+ IsActive bool `alias:"memberships.is_active"`
+}
+
+// FindEffectiveOrgMembership returns the first effective org membership for an actor (user or identity),
+// including direct membership and membership via groups.
+// Exact port of Node.js orgDAL.findEffectiveOrgMembership.
+// TODO(go): move this to dal like membership
+func (d *DAL) FindEffectiveOrgMembership(ctx context.Context, actorType permission.ActorType, actorID, orgID uuid.UUID, filterStatus string) (*MembershipRow, error) {
+ m := table.Memberships
+ g := table.Groups
+ ugm := table.UserGroupMembership
+ igm := table.IdentityGroupMembership
+
+ // Build the group subquery based on actor type.
+ var actorCondition postgres.BoolExpression
+ if actorType == permission.ActorTypeUser {
+ groupSubquery := postgres.SELECT(g.ID).
+ FROM(g.INNER_JOIN(ugm, ugm.GroupId.EQ(g.ID))).
+ WHERE(ugm.UserId.EQ(postgres.UUID(actorID)))
+
+ actorCondition = postgres.OR(
+ m.ActorUserId.EQ(postgres.UUID(actorID)),
+ m.ActorGroupId.IN(groupSubquery),
+ )
+ } else {
+ groupSubquery := postgres.SELECT(g.ID).
+ FROM(g.INNER_JOIN(igm, igm.GroupId.EQ(g.ID))).
+ WHERE(igm.IdentityId.EQ(postgres.UUID(actorID)))
+
+ actorCondition = postgres.OR(
+ m.ActorIdentityId.EQ(postgres.UUID(actorID)),
+ m.ActorGroupId.IN(groupSubquery),
+ )
+ }
+
+ // Status filter: match the requested status OR null (same as Node.js).
+ var statusCondition postgres.BoolExpression
+ if filterStatus != "" {
+ statusCondition = postgres.OR(
+ m.Status.EQ(postgres.String(filterStatus)),
+ m.Status.IS_NULL(),
+ )
+ } else {
+ statusCondition = postgres.OR(
+ m.Status.EQ(postgres.String("accepted")),
+ m.Status.IS_NULL(),
+ )
+ }
+
+ stmt := postgres.SELECT(m.IsActive).
+ FROM(m).
+ WHERE(postgres.AND(
+ m.Scope.EQ(postgres.String("organization")),
+ m.ScopeOrgId.EQ(postgres.UUID(orgID)),
+ actorCondition,
+ statusCondition,
+ )).
+ LIMIT(1)
+
+ var row MembershipRow
+ err := stmt.QueryContext(ctx, d.db.Replica(), &row)
+ if err != nil {
+ if errors.Is(err, qrm.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return &row, nil
+}
+
+// --- Trusted IPs ---
+
+// trustedIPRow holds the accessTokenTrustedIps JSON column from any identity auth table.
+type trustedIPRow struct {
+ AccessTokenTrustedIps string `alias:"access_token_trusted_ips"`
+}
+
+// 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) {
+ iua := table.IdentityUniversalAuths
+ ika := table.IdentityKubernetesAuths
+ iga := table.IdentityGcpAuths
+ iaa := table.IdentityAlicloudAuths
+ iwa := table.IdentityAwsAuths
+ iza := table.IdentityAzureAuths
+ ita := table.IdentityTokenAuths
+ itca := table.IdentityTLSCertAuths
+ ioa := table.IdentityOciAuths
+ ioda := table.IdentityOidcAuths
+ ija := table.IdentityJwtAuths
+ ila := table.IdentityLdapAuths
+ isa := table.IdentitySpiffeAuths
+
+ // Map auth method string → table + column references.
+ var tbl postgres.ReadableTable
+ var identityCol postgres.Column
+ var trustedIPsProj postgres.Projection
+
+ switch authMethod {
+ case "universal_auth":
+ tbl, identityCol, trustedIPsProj = iua, iua.IdentityId, iua.AccessTokenTrustedIps
+ case "kubernetes_auth":
+ tbl, identityCol, trustedIPsProj = ika, ika.IdentityId, ika.AccessTokenTrustedIps
+ case "gcp_auth":
+ tbl, identityCol, trustedIPsProj = iga, iga.IdentityId, iga.AccessTokenTrustedIps
+ case "alicloud_auth":
+ tbl, identityCol, trustedIPsProj = iaa, iaa.IdentityId, iaa.AccessTokenTrustedIps
+ case "aws_auth":
+ tbl, identityCol, trustedIPsProj = iwa, iwa.IdentityId, iwa.AccessTokenTrustedIps
+ case "azure_auth":
+ tbl, identityCol, trustedIPsProj = iza, iza.IdentityId, iza.AccessTokenTrustedIps
+ case "token_auth":
+ tbl, identityCol, trustedIPsProj = ita, ita.IdentityId, ita.AccessTokenTrustedIps
+ case "tls_cert_auth":
+ tbl, identityCol, trustedIPsProj = itca, itca.IdentityId, itca.AccessTokenTrustedIps
+ case "oci_auth":
+ tbl, identityCol, trustedIPsProj = ioa, ioa.IdentityId, ioa.AccessTokenTrustedIps
+ case "oidc_auth":
+ tbl, identityCol, trustedIPsProj = ioda, ioda.IdentityId, ioda.AccessTokenTrustedIps
+ case "jwt_auth":
+ tbl, identityCol, trustedIPsProj = ija, ija.IdentityId, ija.AccessTokenTrustedIps
+ case "ldap_auth":
+ tbl, identityCol, trustedIPsProj = ila, ila.IdentityId, ila.AccessTokenTrustedIps
+ case "spiffe_auth":
+ tbl, identityCol, trustedIPsProj = isa, isa.IdentityId, isa.AccessTokenTrustedIps
+ default:
+ return nil, nil
+ }
+
+ identityColStr, ok := identityCol.(postgres.ColumnString)
+ if !ok {
+ return nil, nil
+ }
+
+ stmt := postgres.SELECT(trustedIPsProj).
+ FROM(tbl).
+ WHERE(identityColStr.EQ(postgres.UUID(identityID))).
+ LIMIT(1)
+
+ var row trustedIPRow
+ err := stmt.QueryContext(ctx, d.db.Replica(), &row)
+ if err != nil {
+ if errors.Is(err, qrm.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+
+ return parseTrustedIPs(row.AccessTokenTrustedIps)
+}
+
+// --- Helpers ---
+
+// parseUUID parses a string to uuid.UUID. Returns uuid.Nil on failure.
+func parseUUID(s string) uuid.UUID {
+ id, _ := uuid.Parse(s)
+ return id
+}
+
+// nullUUIDValid returns true when the nullable UUID is present and non-nil.
+func nullUUIDValid(n sql.Null[uuid.UUID]) bool {
+ return n.Valid && n.V != uuid.Nil
+}
diff --git a/backend-go/internal/services/shared/auth/handler.go b/backend-go/internal/services/shared/auth/handler.go
new file mode 100644
index 0000000000..3e3699e539
--- /dev/null
+++ b/backend-go/internal/services/shared/auth/handler.go
@@ -0,0 +1,435 @@
+package auth
+
+import (
+ "context"
+ "strings"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/google/uuid"
+ "goa.design/goa/v3/security"
+ "golang.org/x/crypto/bcrypt"
+
+ "github.com/infisical/api/internal/libs/errutil"
+ "github.com/infisical/api/internal/services/shared/permission"
+)
+
+// AuthHandler implements the Goa-generated authorization interface (JWTAuth method).
+// It performs real token validation — an exact port of the Node.js inject-identity logic.
+type AuthHandler struct {
+ dal *DAL
+ authSecret []byte
+}
+
+// NewAuthHandler creates an AuthHandler with real validation backed by a DAL.
+func NewAuthHandler(dal *DAL, authSecret string) AuthHandler {
+ return AuthHandler{dal: dal, authSecret: []byte(authSecret)}
+}
+
+// JWTAuth implements the Goa security handler. Goa calls this for each scheme in order
+// (jwt → identity_access_token → service_token) with the scheme name in sc.Name.
+// We classify the token cheaply and only accept when the token type matches the scheme being tried.
+func (h AuthHandler) JWTAuth(ctx context.Context, token string, sc *security.JWTScheme) (context.Context, error) {
+ if token == "" {
+ return ctx, errutil.Unauthorized("Token missing")
+ }
+
+ tokenMode := ClassifyToken(token)
+ if tokenMode == "" {
+ return ctx, errutil.Unauthorized("You are not allowed to access this resource")
+ }
+
+ // Map scheme name to expected auth mode.
+ var expectedMode AuthMode
+ switch sc.Name {
+ case "jwt":
+ expectedMode = AuthModeJWT
+ case "identity_access_token":
+ expectedMode = AuthModeIdentityAccessToken
+ case "service_token":
+ expectedMode = AuthModeServiceToken
+ default:
+ return ctx, errutil.Unauthorized("You are not allowed to access this resource")
+ }
+
+ // 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")
+ }
+
+ var (
+ identity *Identity
+ err error
+ )
+ switch expectedMode {
+ case AuthModeJWT:
+ identity, err = h.validateJWT(ctx, token)
+ case AuthModeIdentityAccessToken:
+ // TODO(go): pass real IP address from HTTP layer instead of empty string
+ // IP address needs to come from HTTP layer. For now pass empty string
+ // (IP check is skipped when ipAddress is empty, matching Node.js: if (ipAddress && trustedIps)).
+ identity, err = h.validateIdentityAccessToken(ctx, token, "")
+ case AuthModeServiceToken:
+ identity, err = h.validateServiceToken(ctx, token)
+ }
+ if err != nil {
+ return ctx, err
+ }
+
+ return WithIdentity(ctx, identity), nil
+}
+
+// validateJWT performs real JWT validation.
+// Exact port of fnValidateJwtIdentity in auth-token-service.ts:212-285.
+func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity, error) {
+ // 1. Parse and verify JWT signature (HS256).
+ claims := &UserJWTClaims{}
+ _, err := jwt.ParseWithClaims(token, claims, func(_ *jwt.Token) (any, error) {
+ return h.authSecret, nil
+ })
+ if err != nil {
+ return nil, errutil.Unauthorized("Invalid JWT token")
+ }
+
+ // 2. Validate authTokenType.
+ if claims.AuthTokenType != "AccessToken" {
+ return nil, errutil.Unauthorized("You are not allowed to access this resource")
+ }
+
+ // 3. Find session by tokenVersionId + userId.
+ sessionID := parseUUID(claims.TokenVersionID)
+ 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)
+ }
+ if session == nil {
+ return nil, errutil.NotFound("Session not found")
+ }
+
+ // 4. Check access version.
+ if claims.AccessVersion != int(session.AccessVersion) {
+ return nil, errutil.Unauthorized("User session is stale, please re-authenticate").WithName("StaleSession")
+ }
+
+ // 5. Find user.
+ user, err := h.dal.FindUserByID(ctx, session.UserId)
+ if err != nil {
+ return nil, errutil.DatabaseErr("Failed to find user").WithErr(err)
+ }
+ if user == nil || !user.IsAccepted.V {
+ return nil, errutil.NotFound("User with ID '%s' not found", session.UserId)
+ }
+
+ // 6. Organization scoping.
+ var orgID, rootOrgID, parentOrgID string
+ if claims.OrganizationID != "" {
+ if claims.SubOrganizationID != "" {
+ // 6a. Sub-organization scope.
+ 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)
+ }
+ if subOrg == nil {
+ return nil, errutil.BadRequest("Sub organization %s not found", claims.SubOrganizationID)
+ }
+
+ // Verify the sub-org belongs to the token's root organization.
+ subRootOrgID := ""
+ if nullUUIDValid(subOrg.RootOrgId) {
+ subRootOrgID = subOrg.RootOrgId.V.String()
+ }
+ if subRootOrgID != claims.OrganizationID && subOrg.ID.String() != claims.OrganizationID {
+ return nil, errutil.Forbidden("Sub-organization does not belong to the token's organization")
+ }
+
+ orgMembership, err := h.dal.FindEffectiveOrgMembership(ctx, permission.ActorTypeUser, user.ID, subOrg.ID, "accepted")
+ if err != nil {
+ return nil, errutil.DatabaseErr("Failed to check org membership").WithErr(err)
+ }
+ if orgMembership == nil {
+ return nil, errutil.Forbidden("User not member of organization")
+ }
+ if !orgMembership.IsActive {
+ return nil, errutil.Forbidden("User organization membership is inactive")
+ }
+
+ orgID = subOrg.ID.String()
+ rootOrgID = claims.OrganizationID
+ if nullUUIDValid(subOrg.ParentOrgId) {
+ parentOrgID = subOrg.ParentOrgId.V.String()
+ }
+ } else {
+ // 6b. Regular organization scope.
+ claimOrgUUID := parseUUID(claims.OrganizationID)
+ _, err := h.dal.FindOrgByID(ctx, claimOrgUUID)
+ if err != nil {
+ return nil, errutil.DatabaseErr("Failed to find organization").WithErr(err)
+ }
+
+ orgMembership, err := h.dal.FindEffectiveOrgMembership(ctx, permission.ActorTypeUser, user.ID, claimOrgUUID, "accepted")
+ if err != nil {
+ return nil, errutil.DatabaseErr("Failed to check org membership").WithErr(err)
+ }
+ if orgMembership == nil {
+ return nil, errutil.Forbidden("User not member of organization")
+ }
+ if !orgMembership.IsActive {
+ return nil, errutil.Forbidden("User organization membership is inactive")
+ }
+
+ orgID = claims.OrganizationID
+ rootOrgID = claims.OrganizationID
+ parentOrgID = claims.OrganizationID
+ }
+ }
+
+ // 7. Build identity.
+ isSuperAdmin := user.SuperAdmin.Valid && user.SuperAdmin.V
+ email := ""
+ if user.Email.Valid {
+ email = user.Email.String
+ }
+
+ return &Identity{
+ AuthMode: AuthModeJWT,
+ Actor: permission.ActorTypeUser,
+ ActorID: user.ID.String(),
+ OrgID: orgID,
+ RootOrgID: rootOrgID,
+ ParentOrgID: parentOrgID,
+ AuthMethod: permission.ActorAuthMethod(claims.AuthMethod),
+ IsSuperAdmin: isSuperAdmin,
+ UserAuthInfo: &UserAuthInfo{
+ UserID: user.ID.String(),
+ Email: email,
+ },
+ }, nil
+}
+
+// validateIdentityAccessToken performs real identity access token validation.
+// Exact port of fnValidateIdentityAccessToken in identity-access-token-service.ts:185-239.
+func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipAddress string) (*Identity, error) {
+ // 1. Parse and verify JWT signature (HS256).
+ claims := &IdentityJWTClaims{}
+ _, err := jwt.ParseWithClaims(token, claims, func(_ *jwt.Token) (any, error) {
+ return h.authSecret, nil
+ })
+ if err != nil {
+ return nil, errutil.Unauthorized("You are not allowed to access this resource")
+ }
+
+ // 2. Validate authTokenType.
+ if claims.AuthTokenType != "IdentityAccessToken" {
+ return nil, errutil.Unauthorized("You are not allowed to access this resource")
+ }
+
+ // 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)
+ }
+ if accessToken == nil {
+ return nil, errutil.Unauthorized("No identity access token found")
+ }
+
+ // 4. Belt-and-suspenders revocation check.
+ if accessToken.IsAccessTokenRevoked {
+ return nil, errutil.Unauthorized("Failed to authorize revoked access token, access token is revoked")
+ }
+
+ // 5. IP check.
+ // TODO(go): this requires passing the real IP address from the HTTP layer. For now, IP check is skipped when ipAddress is empty, matching Node.js: if (ipAddress && trustedIps).
+ if ipAddress != "" {
+ trustedIPs, err := h.dal.FindTrustedIpsByAuthMethod(ctx, accessToken.IdentityId, accessToken.AuthMethod)
+ if err != nil {
+ return nil, errutil.InternalServer("Failed to find trusted IPs")
+ }
+ if trustedIPs != nil {
+ if ipErr := checkIPAgainstBlocklist(ipAddress, trustedIPs); ipErr != nil {
+ return nil, ipErr
+ }
+ }
+ }
+
+ // 6. Resolve scope org.
+ var scopeOrgUUID uuid.UUID
+ if nullUUIDValid(accessToken.SubOrganizationId) {
+ scopeOrgUUID = accessToken.SubOrganizationId.V
+ } else {
+ scopeOrgUUID = accessToken.IdentityOrgID
+ }
+
+ // 7. Find org.
+ org, err := h.dal.FindOrgByID(ctx, scopeOrgUUID)
+ if err != nil {
+ return nil, errutil.DatabaseErr("Failed to find organization").WithErr(err)
+ }
+ if org == nil {
+ return nil, errutil.InternalServer("Organization not found for identity")
+ }
+
+ // 8. Resolve org hierarchy.
+ orgID, rootOrgID, parentOrgID := resolveOrgHierarchy(org)
+
+ // 9. Check org membership.
+ membership, err := h.dal.FindEffectiveOrgMembership(ctx, permission.ActorTypeIdentity, accessToken.IdentityId, org.ID, "")
+ if err != nil {
+ return nil, errutil.InternalServer("Failed to check org membership")
+ }
+ if membership == nil {
+ return nil, errutil.BadRequest("Identity does not belong to this organization")
+ }
+
+ // 10. Validate usage limit.
+ // TODO(go): accessTokenQueue.getIdentityTokenDetailsInCache — read cached usage count instead of DB value
+ 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")
+ }
+
+ // 11. Validate TTL.
+ if accessToken.AccessTokenTTL > 0 {
+ var base time.Time
+ if accessToken.AccessTokenLastRenewedAt.Valid {
+ base = accessToken.AccessTokenLastRenewedAt.Time
+ } else if accessToken.CreatedAt.Valid {
+ base = accessToken.CreatedAt.Time
+ }
+ 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")
+ }
+ }
+
+ // Validate Max TTL (for non-periodic tokens).
+ if accessToken.AccessTokenMaxTTL > 0 && accessToken.AccessTokenPeriod == 0 {
+ var createdAt time.Time
+ if accessToken.CreatedAt.Valid {
+ createdAt = accessToken.CreatedAt.Time
+ }
+ 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")
+ }
+
+ 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")
+ }
+ }
+
+ // TODO(go): accessTokenQueue.updateIdentityAccessTokenStatus — increment usage counter
+
+ // 12. Build identity auth info (for audit logging).
+ identityAuthInfo := &IdentityAuthInfo{
+ IdentityID: accessToken.IdentityId.String(),
+ IdentityName: accessToken.IdentityName,
+ AuthMethod: accessToken.AuthMethod,
+ }
+ if claims.IdentityAuth != nil {
+ if claims.IdentityAuth.OIDC != nil {
+ identityAuthInfo.OIDC = claims.IdentityAuth.OIDC
+ }
+ if claims.IdentityAuth.Kubernetes != nil {
+ identityAuthInfo.Kubernetes = claims.IdentityAuth.Kubernetes
+ }
+ if claims.IdentityAuth.AWS != nil {
+ identityAuthInfo.AWS = claims.IdentityAuth.AWS
+ }
+ }
+
+ // 13. Build identity.
+ return &Identity{
+ AuthMode: AuthModeIdentityAccessToken,
+ Actor: permission.ActorTypeIdentity,
+ ActorID: accessToken.IdentityId.String(),
+ OrgID: orgID,
+ RootOrgID: rootOrgID,
+ ParentOrgID: parentOrgID,
+ AuthMethod: permission.ActorAuthMethod(accessToken.AuthMethod),
+ IdentityAuthInfo: identityAuthInfo,
+ }, nil
+}
+
+// validateServiceToken performs real service token validation.
+// Exact port of fnValidateServiceToken in service-token-service.ts:172-199.
+func (h AuthHandler) validateServiceToken(ctx context.Context, token string) (*Identity, error) {
+ // 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")
+ }
+ tokenID := parts[1]
+ tokenSecret := parts[2]
+
+ // 2. Find service token.
+ serviceToken, err := h.dal.FindServiceTokenByID(ctx, tokenID)
+ if err != nil {
+ return nil, errutil.InternalServer("Failed to find service token")
+ }
+ if serviceToken == nil {
+ return nil, errutil.NotFound("Service token with ID '%s' not found", tokenID)
+ }
+
+ // 3. Find project.
+ project, err := h.dal.FindProjectByID(ctx, serviceToken.ProjectId)
+ if err != nil {
+ return nil, errutil.InternalServer("Failed to find project")
+ }
+ if project == nil {
+ return nil, errutil.NotFound("Project with ID '%s' not found", serviceToken.ProjectId)
+ }
+
+ // 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")
+ }
+
+ // 5. Verify secret hash (bcrypt).
+ if err := bcrypt.CompareHashAndPassword([]byte(serviceToken.SecretHash), []byte(tokenSecret)); err != nil {
+ return nil, errutil.Unauthorized("Invalid service token")
+ }
+
+ // TODO(go): accessTokenQueue.updateServiceTokenStatus — update lastUsed timestamp
+
+ // 6. Find org.
+ org, err := h.dal.FindOrgByID(ctx, project.OrgId)
+ if err != nil {
+ return nil, errutil.InternalServer("Failed to find organization")
+ }
+ if org == nil {
+ return nil, errutil.InternalServer("Organization not found for project")
+ }
+
+ // 7. Build identity.
+ orgID, rootOrgID, parentOrgID := resolveOrgHierarchy(org)
+ return &Identity{
+ AuthMode: AuthModeServiceToken,
+ Actor: permission.ActorTypeService,
+ ActorID: serviceToken.ID,
+ OrgID: orgID,
+ RootOrgID: rootOrgID,
+ ParentOrgID: parentOrgID,
+ }, nil
+}
+
+// resolveOrgHierarchy extracts orgID, rootOrgID, and parentOrgID from an OrgRow.
+func resolveOrgHierarchy(org *OrgRow) (orgID, rootOrgID, parentOrgID string) {
+ orgID = org.ID.String()
+ rootOrgID = orgID
+ parentOrgID = orgID
+ if nullUUIDValid(org.RootOrgId) {
+ rootOrgID = org.RootOrgId.V.String()
+ }
+ if nullUUIDValid(org.ParentOrgId) {
+ parentOrgID = org.ParentOrgId.V.String()
+ }
+ return
+}
diff --git a/backend-go/internal/services/shared/auth/ip.go b/backend-go/internal/services/shared/auth/ip.go
new file mode 100644
index 0000000000..eff927047f
--- /dev/null
+++ b/backend-go/internal/services/shared/auth/ip.go
@@ -0,0 +1,79 @@
+package auth
+
+import (
+ "encoding/json"
+ "net"
+
+ "github.com/infisical/api/internal/libs/errutil"
+)
+
+// TrustedIP represents a single trusted IP entry stored as JSON in the DB.
+type TrustedIP struct {
+ IPAddress string `json:"ipAddress"`
+ Type string `json:"type"`
+ Prefix int `json:"prefix,omitempty"`
+}
+
+// parseTrustedIPs parses the JSON string from the DB into a slice of TrustedIP.
+func parseTrustedIPs(raw string) ([]TrustedIP, error) {
+ if raw == "" {
+ return nil, nil
+ }
+ var ips []TrustedIP
+ if err := json.Unmarshal([]byte(raw), &ips); err != nil {
+ return nil, err
+ }
+ return ips, nil
+}
+
+// checkIPAgainstBlocklist validates ipAddress against trustedIps.
+// Port of backend/src/lib/ip/index.ts:checkIPAgainstBlocklist.
+// Despite the name, trustedIps is an allowlist — if the IP is NOT in it, access is denied.
+func checkIPAgainstBlocklist(ipAddress string, trustedIPs []TrustedIP) error {
+ if len(trustedIPs) == 0 {
+ return nil
+ }
+
+ incoming := net.ParseIP(ipAddress)
+ if incoming == nil {
+ return errutil.Forbidden("You are not allowed to access this resource from the current IP address")
+ }
+
+ for _, tip := range trustedIPs {
+ trusted := net.ParseIP(tip.IPAddress)
+ if trusted == nil {
+ continue
+ }
+
+ if tip.Prefix > 0 {
+ _, cidr, err := net.ParseCIDR(tip.IPAddress + "/" + itoa(tip.Prefix))
+ if err != nil {
+ continue
+ }
+ if cidr.Contains(incoming) {
+ return nil
+ }
+ } else if trusted.Equal(incoming) {
+ return nil
+ }
+ }
+
+ return errutil.Forbidden("You are not allowed to access this resource from the current IP address")
+}
+
+// itoa converts an int to its decimal string representation without importing strconv.
+func itoa(n int) string {
+ if n == 0 {
+ return "0"
+ }
+ buf := make([]byte, 0, 4)
+ for n > 0 {
+ buf = append(buf, byte('0'+n%10))
+ n /= 10
+ }
+ // reverse
+ for i, j := 0, len(buf)-1; i < j; i, j = i+1, j-1 {
+ buf[i], buf[j] = buf[j], buf[i]
+ }
+ return string(buf)
+}
diff --git a/backend-go/internal/services/shared/auth/ip_test.go b/backend-go/internal/services/shared/auth/ip_test.go
new file mode 100644
index 0000000000..6a5560a4f4
--- /dev/null
+++ b/backend-go/internal/services/shared/auth/ip_test.go
@@ -0,0 +1,162 @@
+package auth
+
+import (
+ "testing"
+)
+
+func TestParseTrustedIPs(t *testing.T) {
+ t.Run("empty string returns nil", func(t *testing.T) {
+ ips, err := parseTrustedIPs("")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if ips != nil {
+ t.Fatalf("expected nil, got %v", ips)
+ }
+ })
+
+ t.Run("valid JSON", func(t *testing.T) {
+ raw := `[{"ipAddress":"10.0.0.1","type":"ipv4"},{"ipAddress":"192.168.1.0","type":"ipv4","prefix":24}]`
+ ips, err := parseTrustedIPs(raw)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if len(ips) != 2 {
+ t.Fatalf("expected 2 IPs, got %d", len(ips))
+ }
+ if ips[0].IPAddress != "10.0.0.1" {
+ t.Errorf("expected 10.0.0.1, got %s", ips[0].IPAddress)
+ }
+ if ips[1].Prefix != 24 {
+ t.Errorf("expected prefix 24, got %d", ips[1].Prefix)
+ }
+ })
+
+ t.Run("invalid JSON returns error", func(t *testing.T) {
+ _, err := parseTrustedIPs("not json")
+ if err == nil {
+ t.Fatal("expected error for invalid JSON")
+ }
+ })
+}
+
+func TestCheckIPAgainstBlocklist(t *testing.T) {
+ t.Run("empty list allows all", func(t *testing.T) {
+ err := checkIPAgainstBlocklist("1.2.3.4", nil)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ err = checkIPAgainstBlocklist("1.2.3.4", []TrustedIP{})
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ })
+
+ t.Run("exact IP match allows", func(t *testing.T) {
+ trusted := []TrustedIP{{IPAddress: "10.0.0.5", Type: "ipv4"}}
+ err := checkIPAgainstBlocklist("10.0.0.5", trusted)
+ if err != nil {
+ t.Fatalf("expected allowed, got: %v", err)
+ }
+ })
+
+ t.Run("exact IP mismatch denies", func(t *testing.T) {
+ trusted := []TrustedIP{{IPAddress: "10.0.0.5", Type: "ipv4"}}
+ err := checkIPAgainstBlocklist("10.0.0.6", trusted)
+ if err == nil {
+ t.Fatal("expected denied for mismatched IP")
+ }
+ })
+
+ t.Run("CIDR match allows", func(t *testing.T) {
+ trusted := []TrustedIP{{IPAddress: "192.168.1.0", Type: "ipv4", Prefix: 24}}
+ err := checkIPAgainstBlocklist("192.168.1.100", trusted)
+ if err != nil {
+ t.Fatalf("expected allowed within CIDR, got: %v", err)
+ }
+ })
+
+ t.Run("CIDR mismatch denies", func(t *testing.T) {
+ trusted := []TrustedIP{{IPAddress: "192.168.1.0", Type: "ipv4", Prefix: 24}}
+ err := checkIPAgainstBlocklist("192.168.2.1", trusted)
+ if err == nil {
+ t.Fatal("expected denied for IP outside CIDR range")
+ }
+ })
+
+ t.Run("multiple entries matches any", func(t *testing.T) {
+ trusted := []TrustedIP{
+ {IPAddress: "10.0.0.1", Type: "ipv4"},
+ {IPAddress: "172.16.0.0", Type: "ipv4", Prefix: 12},
+ }
+ // First entry exact match.
+ if err := checkIPAgainstBlocklist("10.0.0.1", trusted); err != nil {
+ t.Fatalf("expected match on first entry: %v", err)
+ }
+ // Second entry CIDR match.
+ if err := checkIPAgainstBlocklist("172.20.5.5", trusted); err != nil {
+ t.Fatalf("expected match on second entry (CIDR): %v", err)
+ }
+ // No match.
+ if err := checkIPAgainstBlocklist("8.8.8.8", trusted); err == nil {
+ t.Fatal("expected denied for IP matching neither entry")
+ }
+ })
+
+ t.Run("invalid incoming IP denies", func(t *testing.T) {
+ trusted := []TrustedIP{{IPAddress: "10.0.0.1", Type: "ipv4"}}
+ err := checkIPAgainstBlocklist("not-an-ip", trusted)
+ if err == nil {
+ t.Fatal("expected denied for invalid incoming IP")
+ }
+ })
+
+ t.Run("invalid trusted IP is skipped", func(t *testing.T) {
+ trusted := []TrustedIP{
+ {IPAddress: "not-valid", Type: "ipv4"},
+ {IPAddress: "10.0.0.1", Type: "ipv4"},
+ }
+ // Should skip the invalid entry and match the second one.
+ err := checkIPAgainstBlocklist("10.0.0.1", trusted)
+ if err != nil {
+ t.Fatalf("expected allowed after skipping invalid entry: %v", err)
+ }
+ })
+
+ t.Run("IPv6 exact match", func(t *testing.T) {
+ trusted := []TrustedIP{{IPAddress: "::1", Type: "ipv6"}}
+ err := checkIPAgainstBlocklist("::1", trusted)
+ if err != nil {
+ t.Fatalf("expected allowed for IPv6 loopback: %v", err)
+ }
+ })
+
+ t.Run("IPv6 CIDR match", func(t *testing.T) {
+ trusted := []TrustedIP{{IPAddress: "fd00::", Type: "ipv6", Prefix: 8}}
+ err := checkIPAgainstBlocklist("fd12:3456::1", trusted)
+ if err != nil {
+ t.Fatalf("expected allowed within IPv6 CIDR: %v", err)
+ }
+ })
+}
+
+func TestItoa(t *testing.T) {
+ tests := []struct {
+ input int
+ expected string
+ }{
+ {0, "0"},
+ {1, "1"},
+ {8, "8"},
+ {24, "24"},
+ {128, "128"},
+ {255, "255"},
+ }
+
+ for _, tc := range tests {
+ got := itoa(tc.input)
+ if got != tc.expected {
+ t.Errorf("itoa(%d) = %q, want %q", tc.input, got, tc.expected)
+ }
+ }
+}
diff --git a/backend-go/internal/services/shared/kms/kms.go b/backend-go/internal/services/shared/kms/kms.go
index 7718b95eee..14c4a927bc 100644
--- a/backend-go/internal/services/shared/kms/kms.go
+++ b/backend-go/internal/services/shared/kms/kms.go
@@ -12,6 +12,7 @@ import (
"github.com/infisical/api/internal/config"
"github.com/infisical/api/internal/crypto/cipher"
"github.com/infisical/api/internal/database/pg/gen/model"
+ "github.com/infisical/api/internal/libs/errutil"
)
// KmsRootConfigUUID is the fixed UUID for the single kms_root_config row.
@@ -176,7 +177,7 @@ func (s *SharedService) Start(ctx context.Context, hsmConfigured bool) error {
})
if err != nil {
- return fmt.Errorf("KMS: finding/creating root config: %w", err)
+ return errutil.DatabaseErr("Failed to find or create KMS root config").WithErr(err)
}
decryptedRootKey, err := s.decryptRootKey(rootConfig)
@@ -261,7 +262,7 @@ func (s *SharedService) generateEncryptedKeyMaterial() ([]byte, error) {
func (s *SharedService) decryptKmsKey(ctx context.Context, kmsKeyID uuid.UUID) ([]byte, error) {
kmsKeyDoc, err := s.dal.FindKmsKeyByID(ctx, kmsKeyID)
if err != nil {
- return nil, fmt.Errorf("KMS: finding KMS key %s: %w", kmsKeyID, err)
+ return nil, errutil.DatabaseErr("Failed to find KMS key").WithErr(err)
}
return s.decryptKmsKeyMaterial(kmsKeyDoc)
}
diff --git a/backend-go/internal/services/shared/kms/kms_org.go b/backend-go/internal/services/shared/kms/kms_org.go
index 3cd3086f89..d7baf2b06e 100644
--- a/backend-go/internal/services/shared/kms/kms_org.go
+++ b/backend-go/internal/services/shared/kms/kms_org.go
@@ -6,12 +6,14 @@ import (
"fmt"
"github.com/google/uuid"
+
+ "github.com/infisical/api/internal/libs/errutil"
)
func (s *SharedService) getOrgDataKey(ctx context.Context, orgID uuid.UUID) ([]byte, error) {
org, err := s.dal.FindOrgKmsInfo(ctx, orgID)
if err != nil {
- return nil, fmt.Errorf("KMS: finding org: %w", err)
+ return nil, errutil.DatabaseErr("Failed to find organization KMS info").WithErr(err)
}
// Ensure org has a KMS key (lazy create if missing).
@@ -21,7 +23,7 @@ func (s *SharedService) getOrgDataKey(ctx context.Context, orgID uuid.UUID) ([]b
return s.generateEncryptedKeyMaterial()
})
if kmsErr != nil {
- return nil, fmt.Errorf("KMS: ensuring org KMS key: %w", kmsErr)
+ return nil, errutil.DatabaseErr("Failed to ensure organization KMS key").WithErr(kmsErr)
}
kmsKeyID.V = createdKmsKeyID
kmsKeyID.Valid = true
@@ -31,7 +33,7 @@ func (s *SharedService) getOrgDataKey(ctx context.Context, orgID uuid.UUID) ([]b
if org.KmsEncryptedDataKey == nil {
dataKey, dataErr := s.generateOrgDataKey(ctx, orgID, kmsKeyID.V)
if dataErr != nil {
- return nil, fmt.Errorf("KMS: ensuring org data key: %w", dataErr)
+ return nil, errutil.DatabaseErr("Failed to ensure organization data key").WithErr(dataErr)
}
return dataKey, nil
}
@@ -64,7 +66,7 @@ func (s *SharedService) generateOrgDataKey(ctx context.Context, orgID, kmsKeyID
})
if err != nil {
- return nil, err
+ return nil, errutil.DatabaseErr("Failed to find or create organization data key").WithErr(err)
}
return decryptWithVersion(encryptedDataKey, kmsKey)
diff --git a/backend-go/internal/services/shared/kms/kms_project.go b/backend-go/internal/services/shared/kms/kms_project.go
index d05e7e1ccf..4256c354e5 100644
--- a/backend-go/internal/services/shared/kms/kms_project.go
+++ b/backend-go/internal/services/shared/kms/kms_project.go
@@ -6,12 +6,14 @@ import (
"fmt"
"github.com/google/uuid"
+
+ "github.com/infisical/api/internal/libs/errutil"
)
func (s *SharedService) getProjectDataKey(ctx context.Context, projectID string) ([]byte, error) {
project, err := s.dal.FindProjectKmsInfo(ctx, projectID)
if err != nil {
- return nil, fmt.Errorf("KMS: finding project: %w", err)
+ return nil, errutil.DatabaseErr("Failed to find project KMS info").WithErr(err)
}
// Ensure project has a KMS key (lazy create if missing).
@@ -21,7 +23,7 @@ func (s *SharedService) getProjectDataKey(ctx context.Context, projectID string)
return s.generateEncryptedKeyMaterial()
})
if kmsErr != nil {
- return nil, fmt.Errorf("KMS: ensuring project KMS key: %w", kmsErr)
+ return nil, errutil.DatabaseErr("Failed to ensure project KMS key").WithErr(kmsErr)
}
kmsKeyID.V = createdKmsKeyID
kmsKeyID.Valid = true
@@ -31,7 +33,7 @@ func (s *SharedService) getProjectDataKey(ctx context.Context, projectID string)
if project.KmsSecretManagerEncryptedDataKey == nil {
dataKey, dataErr := s.generateProjectDataKey(ctx, projectID, kmsKeyID.V)
if dataErr != nil {
- return nil, fmt.Errorf("KMS: ensuring project data key: %w", dataErr)
+ return nil, errutil.DatabaseErr("Failed to ensure project data key").WithErr(dataErr)
}
return dataKey, nil
}
@@ -63,7 +65,7 @@ func (s *SharedService) generateProjectDataKey(ctx context.Context, projectID st
return encryptWithVersion(plainDataKey, kmsKey)
})
if err != nil {
- return nil, err
+ return nil, errutil.DatabaseErr("Failed to find or create project data key").WithErr(err)
}
return decryptWithVersion(encryptedDataKey, kmsKey)
diff --git a/backend-go/internal/services/shared/libs.go b/backend-go/internal/services/shared/libs.go
index 99f4f35bea..f46f391559 100644
--- a/backend-go/internal/services/shared/libs.go
+++ b/backend-go/internal/services/shared/libs.go
@@ -8,6 +8,7 @@ import (
"github.com/infisical/api/internal/config"
"github.com/infisical/api/internal/database/pg"
"github.com/infisical/api/internal/keystore"
+ "github.com/infisical/api/internal/services/shared/auth"
"github.com/infisical/api/internal/services/shared/kms"
"github.com/infisical/api/internal/services/shared/license"
"github.com/infisical/api/internal/services/shared/permission"
@@ -23,10 +24,11 @@ type SharedServicesDeps struct {
}
type SharedServices struct {
- Config *config.Config
- Permission *permission.SharedService
- KMS *kms.SharedService
- License *license.SharedService
+ Config *config.Config
+ AuthHandler auth.AuthHandler
+ Permission *permission.SharedService
+ KMS *kms.SharedService
+ License *license.SharedService
}
func NewSharedServices(ctx context.Context, deps SharedServicesDeps) (*SharedServices, error) {
@@ -49,10 +51,14 @@ func NewSharedServices(ctx context.Context, deps SharedServicesDeps) (*SharedSer
DAL: licenseDAL,
})
+ authDAL := auth.NewDAL(deps.DB)
+ authHandler := auth.NewAuthHandler(authDAL, deps.Config.AuthSecret)
+
return &SharedServices{
- Config: deps.Config,
- Permission: permission.NewSharedService(permission.Deps{DAL: permissionDAL}),
- KMS: kmsSvc,
- License: licenseSvc,
+ Config: deps.Config,
+ AuthHandler: authHandler,
+ Permission: permission.NewSharedService(permission.Deps{DAL: permissionDAL}),
+ KMS: kmsSvc,
+ License: licenseSvc,
}, nil
}
diff --git a/backend-go/internal/services/shared/secretmanager/secretfolder/secret_folder.go b/backend-go/internal/services/shared/secretmanager/secretfolder/secret_folder.go
index cb59fc939b..1c451b0087 100644
--- a/backend-go/internal/services/shared/secretmanager/secretfolder/secret_folder.go
+++ b/backend-go/internal/services/shared/secretmanager/secretfolder/secret_folder.go
@@ -2,7 +2,8 @@ package secretfolder
import (
"context"
- "fmt"
+
+ "github.com/infisical/api/internal/libs/errutil"
)
type dal interface {
@@ -26,7 +27,7 @@ func NewSharedService(deps Deps) *SharedService {
func (s *SharedService) LoadProjectFolders(ctx context.Context, projectID string) (*FolderLookup, error) {
rows, err := s.dal.GetFoldersByProjectID(ctx, projectID)
if err != nil {
- return nil, fmt.Errorf("get folders for project %s: %w", projectID, err)
+ return nil, errutil.DatabaseErr("Failed to get folders for project").WithErr(err)
}
return newFolderLookup(rows), nil
}
diff --git a/backend-go/internal/services/shared/secretmanager/secretimport/secret_import.go b/backend-go/internal/services/shared/secretmanager/secretimport/secret_import.go
index 3ad96dd815..463e1d1183 100644
--- a/backend-go/internal/services/shared/secretmanager/secretimport/secret_import.go
+++ b/backend-go/internal/services/shared/secretmanager/secretimport/secret_import.go
@@ -2,7 +2,8 @@ package secretimport
import (
"context"
- "fmt"
+
+ "github.com/infisical/api/internal/libs/errutil"
)
type dal interface {
@@ -26,7 +27,7 @@ func NewSharedService(deps Deps) *SharedService {
func (s *SharedService) LoadProjectImports(ctx context.Context, projectID string) (*ImportLookup, error) {
rows, err := s.dal.GetImportsByProjectID(ctx, projectID)
if err != nil {
- return nil, fmt.Errorf("get imports for project %s: %w", projectID, err)
+ return nil, errutil.DatabaseErr("Failed to get imports for project").WithErr(err)
}
return newImportLookup(rows), nil
}
diff --git a/backend-go/internal/services/shared/serverconfig/serverconfig.go b/backend-go/internal/services/shared/serverconfig/serverconfig.go
index fe1e1c9d3b..ee20404e3d 100644
--- a/backend-go/internal/services/shared/serverconfig/serverconfig.go
+++ b/backend-go/internal/services/shared/serverconfig/serverconfig.go
@@ -11,6 +11,7 @@ import (
"github.com/lib/pq"
"github.com/infisical/api/internal/database/pg/gen/model"
+ "github.com/infisical/api/internal/libs/errutil"
)
var adminConfigDBUUID = uuid.MustParse("00000000-0000-0000-0000-000000000000")
@@ -137,7 +138,7 @@ func (s *SharedService) Init(ctx context.Context) (ServerConfig, error) {
m, err := s.dal.FindOrCreateConfig(ctx)
if err != nil {
- return ServerConfig{}, err
+ return ServerConfig{}, errutil.DatabaseErr("Failed to initialize server config").WithErr(err)
}
return configFromModel(m), nil
}
@@ -161,7 +162,7 @@ func (s *SharedService) GetConfig(ctx context.Context) (ServerConfig, error) {
// Cache miss — read from DB.
m, err := s.dal.FindByID(ctx, adminConfigDBUUID)
if err != nil {
- return ServerConfig{}, fmt.Errorf("reading config from database: %w", err)
+ return ServerConfig{}, errutil.DatabaseErr("Failed to read server config").WithErr(err)
}
cfg := configFromModel(m)