Skip to content

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

feat: updated auth handler to authenticator and removed dal

=cec46e17172e
diff --git a/backend-go/internal/server/api/platform/platform.go b/backend-go/internal/server/api/platform/platform.go
index d2e115e43e..df04c32185 100644
--- a/backend-go/internal/server/api/platform/platform.go
+++ b/backend-go/internal/server/api/platform/platform.go
@@ -16,8 +16,8 @@ func NewRegistry(logger *slog.Logger, sharedLibs *services.Services) *Registry {
l := logger.With(slog.String("product", "platform"))
return &Registry{
Projects: projects.NewService(l, projects.Deps{
- AuthHandler: sharedLibs.AuthHandler,
- Permission: sharedLibs.Permission,
+ Authenticator: sharedLibs.Authenticator,
+ Permission: sharedLibs.Permission,
}),
}
}
diff --git a/backend-go/internal/server/api/platform/projects/projects.go b/backend-go/internal/server/api/platform/projects/projects.go
index 018064482a..9dd9d6121c 100644
--- a/backend-go/internal/server/api/platform/projects/projects.go
+++ b/backend-go/internal/server/api/platform/projects/projects.go
@@ -15,22 +15,22 @@ type permissionGetter interface {
}
type service struct {
- auth.AuthHandler
+ auth.Authenticator
logger *slog.Logger
permission permissionGetter
}
// Deps holds the dependencies for the projects service.
type Deps struct {
- AuthHandler auth.AuthHandler
- Permission permissionGetter
+ Authenticator auth.Authenticator
+ Permission permissionGetter
}
func NewService(logger *slog.Logger, deps Deps) genprojects.Service {
return &service{
- AuthHandler: deps.AuthHandler,
- logger: logger.With(slog.String("service", "projects")),
- permission: deps.Permission,
+ Authenticator: deps.Authenticator,
+ logger: logger.With(slog.String("service", "projects")),
+ permission: deps.Permission,
}
}
diff --git a/backend-go/internal/server/api/platform/projects/projects_integration_test.go b/backend-go/internal/server/api/platform/projects/projects_integration_test.go
index a7acbd7ea4..15874c7404 100644
--- a/backend-go/internal/server/api/platform/projects/projects_integration_test.go
+++ b/backend-go/internal/server/api/platform/projects/projects_integration_test.go
@@ -39,12 +39,11 @@ func setupMux(t *testing.T) *testutil.TestMux {
permDAL := permission.NewDAL(stack.DB())
permLib := permission.NewService(testutil.NopLogger(), permission.Deps{DAL: permDAL})
- authDAL := auth.NewDAL(stack.DB())
- authHandler := auth.NewAuthHandler(authDAL, infra.AuthSecret)
+ authenticator := auth.NewAuthenticator(stack.DB(), infra.AuthSecret)
svc := projects.NewService(testutil.NopLogger(), projects.Deps{
- AuthHandler: authHandler,
- Permission: permLib,
+ Authenticator: authenticator,
+ Permission: permLib,
})
mux := testutil.NewTestMux()
diff --git a/backend-go/internal/server/api/secretmanager/secrets/secrets.go b/backend-go/internal/server/api/secretmanager/secrets/secrets.go
index 51e0fcce2c..0a98437c51 100644
--- a/backend-go/internal/server/api/secretmanager/secrets/secrets.go
+++ b/backend-go/internal/server/api/secretmanager/secrets/secrets.go
@@ -23,7 +23,7 @@ const secretValueHiddenMask = "<hidden-by-infisical>"
// Handler implements the Goa secrets service interface.
type Handler struct {
- auth.AuthHandler
+ auth.Authenticator
logger *slog.Logger
sharedSvc *services.Services
secretManagerSvc *secretmanager.Services
@@ -39,7 +39,7 @@ type Deps struct {
// NewHandler creates a new secrets handler.
func NewHandler(deps Deps) *Handler {
return &Handler{
- AuthHandler: deps.SharedSvc.AuthHandler,
+ Authenticator: deps.SharedSvc.Authenticator,
logger: deps.Logger.With(slog.String("handler", "secrets")),
sharedSvc: deps.SharedSvc,
secretManagerSvc: deps.SecretManagerSvc,
diff --git a/backend-go/internal/server/api/secretmanager/secrets/secrets_integration_test.go b/backend-go/internal/server/api/secretmanager/secrets/secrets_integration_test.go
index 5eb9d85e63..4bb2fca71b 100644
--- a/backend-go/internal/server/api/secretmanager/secrets/secrets_integration_test.go
+++ b/backend-go/internal/server/api/secretmanager/secrets/secrets_integration_test.go
@@ -52,8 +52,7 @@ func newSecretsHandler(t *testing.T) gensecrets.Service {
permDAL := permission.NewDAL(stack.DB())
permSvc := permission.NewService(testutil.NopLogger(), permission.Deps{DAL: permDAL})
- authDAL := auth.NewDAL(stack.DB())
- authHandler := auth.NewAuthHandler(authDAL, infra.AuthSecret)
+ authenticator := auth.NewAuthenticator(stack.DB(), infra.AuthSecret)
redisClient := stack.Redis().Client()
t.Cleanup(func() { redisClient.Close() })
@@ -77,12 +76,12 @@ func newSecretsHandler(t *testing.T) gensecrets.Service {
// Build shared services struct for handler
sharedSvc := &services.Services{
- Config: stack.Config(),
- AuthHandler: authHandler,
- Permission: permSvc,
- KMS: kmsSvc,
- Project: projectSvc,
- AuditLog: auditlog.NewService(testutil.NopLogger(), auditlog.Deps{Queue: queueSvc, Config: stack.Config()}),
+ Config: stack.Config(),
+ Authenticator: authenticator,
+ Permission: permSvc,
+ KMS: kmsSvc,
+ Project: projectSvc,
+ AuditLog: auditlog.NewService(testutil.NopLogger(), auditlog.Deps{Queue: queueSvc, Config: stack.Config()}),
}
secretManagerSvc := smShared.NewServices(smShared.ServicesDeps{DB: stack.DB()})
diff --git a/backend-go/internal/services/auth/claims.go b/backend-go/internal/services/auth/claims.go
index 8a96ca7b48..a021951105 100644
--- a/backend-go/internal/services/auth/claims.go
+++ b/backend-go/internal/services/auth/claims.go
@@ -1,6 +1,9 @@
package auth
-import "github.com/golang-jwt/jwt/v5"
+import (
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/google/uuid"
+)
// UserJWTClaims represents the JWT payload for user browser sessions.
// Exact match of the Node.js AuthModeJwtTokenPayload.
@@ -8,11 +11,11 @@ type UserJWTClaims struct {
jwt.RegisteredClaims
AuthTokenType AuthTokenType `json:"authTokenType"`
AuthMethod string `json:"authMethod,omitempty"`
- UserID string `json:"userId"`
- TokenVersionID string `json:"tokenVersionId"`
+ UserID uuid.UUID `json:"userId"`
+ TokenVersionID uuid.UUID `json:"tokenVersionId"`
AccessVersion int `json:"accessVersion"`
- OrganizationID string `json:"organizationId,omitempty"`
- SubOrganizationID string `json:"subOrganizationId,omitempty"`
+ OrganizationID uuid.UUID `json:"organizationId,omitempty"`
+ SubOrganizationID uuid.UUID `json:"subOrganizationId,omitempty"`
IsMfaVerified bool `json:"isMfaVerified,omitempty"`
MfaMethod string `json:"mfaMethod,omitempty"`
MCP bool `json:"mcp,omitempty"`
@@ -23,7 +26,7 @@ type UserJWTClaims struct {
type IdentityJWTClaims struct {
jwt.RegisteredClaims
AuthTokenType AuthTokenType `json:"authTokenType"`
- IdentityID string `json:"identityId"`
+ IdentityID uuid.UUID `json:"identityId"`
ClientSecretID string `json:"clientSecretId"`
IdentityAccessTokenID string `json:"identityAccessTokenId"`
IdentityAuth *IdentityAuth `json:"identityAuth,omitempty"`
diff --git a/backend-go/internal/services/auth/dal.go b/backend-go/internal/services/auth/dal.go
deleted file mode 100644
index 244b6da410..0000000000
--- a/backend-go/internal/services/auth/dal.go
+++ /dev/null
@@ -1,421 +0,0 @@
-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/actor"
-)
-
-// 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"`
- Username sql.NullString `alias:"users.username"`
- IsAccepted sql.Null[bool] `alias:"users.is_accepted"`
- SuperAdmin sql.Null[bool] `alias:"users.super_admin"`
- IsLocked sql.Null[bool] `alias:"users.is_locked"`
- TemporaryLockDateEnd sql.NullTime `alias:"users.temporary_lock_date_end"`
-}
-
-// 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.Username, u.IsAccepted, u.SuperAdmin, u.IsLocked, u.TemporaryLockDateEnd).
- 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"`
- Name string `alias:"organizations.name"`
- 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.Name, 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 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"`
- 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"`
- Name string `alias:"service_tokens.name"`
- 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.Name, 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 actor.Type, 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 == actor.TypeUser {
- 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 actor.IdentityAuthMethod) ([]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 → table + column references.
- var tbl postgres.ReadableTable
- var identityCol postgres.Column
- var trustedIPsProj postgres.Projection
-
- switch authMethod {
- case actor.IdentityAuthMethodUniversal:
- tbl, identityCol, trustedIPsProj = iua, iua.IdentityId, iua.AccessTokenTrustedIps
- case actor.IdentityAuthMethodKubernetes:
- tbl, identityCol, trustedIPsProj = ika, ika.IdentityId, ika.AccessTokenTrustedIps
- case actor.IdentityAuthMethodGCP:
- tbl, identityCol, trustedIPsProj = iga, iga.IdentityId, iga.AccessTokenTrustedIps
- case actor.IdentityAuthMethodAliCloud:
- tbl, identityCol, trustedIPsProj = iaa, iaa.IdentityId, iaa.AccessTokenTrustedIps
- case actor.IdentityAuthMethodAWS:
- tbl, identityCol, trustedIPsProj = iwa, iwa.IdentityId, iwa.AccessTokenTrustedIps
- case actor.IdentityAuthMethodAzure:
- tbl, identityCol, trustedIPsProj = iza, iza.IdentityId, iza.AccessTokenTrustedIps
- case actor.IdentityAuthMethodToken:
- tbl, identityCol, trustedIPsProj = ita, ita.IdentityId, ita.AccessTokenTrustedIps
- case actor.IdentityAuthMethodTLSCert:
- tbl, identityCol, trustedIPsProj = itca, itca.IdentityId, itca.AccessTokenTrustedIps
- case actor.IdentityAuthMethodOCI:
- tbl, identityCol, trustedIPsProj = ioa, ioa.IdentityId, ioa.AccessTokenTrustedIps
- case actor.IdentityAuthMethodOIDC:
- tbl, identityCol, trustedIPsProj = ioda, ioda.IdentityId, ioda.AccessTokenTrustedIps
- case actor.IdentityAuthMethodJWT:
- tbl, identityCol, trustedIPsProj = ija, ija.IdentityId, ija.AccessTokenTrustedIps
- case actor.IdentityAuthMethodLDAP:
- tbl, identityCol, trustedIPsProj = ila, ila.IdentityId, ila.AccessTokenTrustedIps
- case actor.IdentityAuthMethodSPIFFE:
- 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/auth/handler.go b/backend-go/internal/services/auth/handler.go
index 398367eba4..1354b437fe 100644
--- a/backend-go/internal/services/auth/handler.go
+++ b/backend-go/internal/services/auth/handler.go
@@ -2,29 +2,33 @@ package auth
import (
"context"
+ "database/sql"
"errors"
+ "fmt"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
"goa.design/goa/v3/security"
"golang.org/x/crypto/bcrypt"
+ "github.com/infisical/api/internal/database/pg"
"github.com/infisical/api/internal/libs/errutil"
"github.com/infisical/api/internal/services/actor"
)
-// AuthHandler implements the Goa-generated authorization interface (JWTAuth method).
+// Authenticator 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
+type Authenticator struct {
+ db pg.DB
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)}
+// NewAuthenticator creates an Authenticator with real validation backed by pg.DB.
+func NewAuthenticator(db pg.DB, authSecret string) Authenticator {
+ return Authenticator{db: db, authSecret: []byte(authSecret)}
}
// authFailKey is a context key used to propagate the authoritative auth error
@@ -36,7 +40,7 @@ type authFailKey struct{}
// 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) {
+func (a Authenticator) JWTAuth(ctx context.Context, token string, sc *security.JWTScheme) (context.Context, error) {
// If a previous scheme already matched the token and failed, return that error.
if prevErr, ok := ctx.Value(authFailKey{}).(error); ok {
return ctx, prevErr
@@ -75,14 +79,14 @@ func (h AuthHandler) JWTAuth(ctx context.Context, token string, sc *security.JWT
)
switch expectedMode {
case AuthModeJWT:
- identity, err = h.validateJWT(ctx, token)
+ identity, err = a.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, "")
+ identity, err = a.validateIdentityAccessToken(ctx, token, "")
case AuthModeServiceToken:
- identity, err = h.validateServiceToken(ctx, token)
+ identity, err = a.validateServiceToken(ctx, token)
}
if err != nil {
@@ -102,13 +106,14 @@ func (h AuthHandler) JWTAuth(ctx context.Context, token string, sc *security.JWT
return WithIdentity(ctx, identity), nil
}
+// TODO(gov0): Missing test
// 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) {
+func (a Authenticator) 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
+ return a.authSecret, nil
})
if err != nil {
@@ -121,49 +126,45 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
}
// 3. Find session by tokenVersionId + userId.
- sessionID := parseUUID(claims.TokenVersionID)
- userID := parseUUID(claims.UserID)
- session, err := h.dal.FindSessionByIDAndUserID(ctx, sessionID, userID)
+ session, err := a.findSessionByIDAndUserID(ctx, claims.TokenVersionID, claims.UserID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to validate session").WithErrf("validateJWT(sessionId=%s, userId=%s): %w", sessionID, userID, err)
+ return nil, errutil.DatabaseErr("Failed to validate session").WithErrf("validateJWT(sessionId=%s, userId=%s): %w", claims.TokenVersionID, claims.UserID, err)
}
if session == nil {
- return nil, errutil.NotFound("Session not found").WithErrf("validateJWT(sessionId=%s, userId=%s): session is nil", sessionID, userID)
+ return nil, errutil.NotFound("Session not found").WithErrf("validateJWT(sessionId=%s, userId=%s): session is nil", claims.TokenVersionID, claims.UserID)
}
// 4. Check access version.
if claims.AccessVersion != int(session.AccessVersion) {
- 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)
+ return nil, errutil.Unauthorized("User session is stale, please re-authenticate").WithName("StaleSession").WithErrf("validateJWT(sessionId=%s): access version mismatch claim=%d db=%d", claims.TokenVersionID, claims.AccessVersion, session.AccessVersion)
}
// 5. Find user.
- user, err := h.dal.FindUserByID(ctx, session.UserId)
+ user, err := a.findUserByID(ctx, session.UserID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find user").WithErrf("validateJWT(userId=%s): %w", session.UserId, 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).WithErrf("validateJWT: user not found or not accepted")
+ 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").WithErrf("validateJWT(userId=%s): user is permanently locked", user.ID)
}
- if user.TemporaryLockDateEnd.Valid && time.Now().Before(user.TemporaryLockDateEnd.Time) {
+ if user.TemporaryLockDateEnd.Valid && time.Now().Before(user.TemporaryLockDateEnd.V) {
return nil, errutil.Unauthorized("Account is locked").WithErrf("validateJWT(userId=%s): user is temporarily locked", user.ID)
}
// 6. Organization scoping.
var orgID, rootOrgID, parentOrgID uuid.UUID
var orgName string
- if claims.OrganizationID != "" {
- claimOrgUUID := parseUUID(claims.OrganizationID)
- if claims.SubOrganizationID != "" {
+ if claims.OrganizationID != uuid.Nil {
+ if claims.SubOrganizationID != uuid.Nil {
// 6a. Sub-organization scope.
- subOrgUUID := parseUUID(claims.SubOrganizationID)
- subOrg, err := h.dal.FindOrgByID(ctx, subOrgUUID)
+ subOrg, err := a.findOrgByID(ctx, claims.SubOrganizationID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find sub-organization").WithErrf("validateJWT(subOrgId=%s): %w", subOrgUUID, err)
+ return nil, errutil.DatabaseErr("Failed to find sub-organization").WithErrf("validateJWT(subOrgId=%s): %w", claims.SubOrganizationID, err)
}
if subOrg == nil {
return nil, errutil.BadRequest("Sub organization %s not found", claims.SubOrganizationID).WithErrf("validateJWT: sub-organization not found")
@@ -171,14 +172,14 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
// Verify the sub-org belongs to the token's root organization.
var subRootOrgID uuid.UUID
- if nullUUIDValid(subOrg.RootOrgId) {
- subRootOrgID = subOrg.RootOrgId.V
+ if nullUUIDValid(subOrg.RootOrgID) {
+ subRootOrgID = subOrg.RootOrgID.V
}
- if subRootOrgID != claimOrgUUID && subOrg.ID != claimOrgUUID {
- 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)
+ if subRootOrgID != claims.OrganizationID && subOrg.ID != claims.OrganizationID {
+ return nil, errutil.Forbidden("Sub-organization does not belong to the token's organization").WithErrf("validateJWT(subOrgId=%s, claimOrgId=%s): org mismatch", subOrg.ID, claims.OrganizationID)
}
- orgMembership, err := h.dal.FindEffectiveOrgMembership(ctx, actor.TypeUser, user.ID, subOrg.ID, "accepted")
+ orgMembership, err := a.findEffectiveOrgMembership(ctx, actor.TypeUser, user.ID, subOrg.ID, "accepted")
if err != nil {
return nil, errutil.DatabaseErr("Failed to check org membership").WithErrf("validateJWT(userId=%s, orgId=%s): %w", user.ID, subOrg.ID, err)
}
@@ -191,32 +192,32 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
orgID = subOrg.ID
orgName = subOrg.Name
- rootOrgID = claimOrgUUID
- if nullUUIDValid(subOrg.ParentOrgId) {
- parentOrgID = subOrg.ParentOrgId.V
+ rootOrgID = claims.OrganizationID
+ if nullUUIDValid(subOrg.ParentOrgID) {
+ parentOrgID = subOrg.ParentOrgID.V
}
} else {
// 6b. Regular organization scope.
- org, err := h.dal.FindOrgByID(ctx, claimOrgUUID)
+ org, err := a.findOrgByID(ctx, claims.OrganizationID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find organization").WithErrf("validateJWT(orgId=%s): %w", claimOrgUUID, err)
+ return nil, errutil.DatabaseErr("Failed to find organization").WithErrf("validateJWT(orgId=%s): %w", claims.OrganizationID, err)
}
- orgMembership, err := h.dal.FindEffectiveOrgMembership(ctx, actor.TypeUser, user.ID, claimOrgUUID, "accepted")
+ orgMembership, err := a.findEffectiveOrgMembership(ctx, actor.TypeUser, user.ID, claims.OrganizationID, "accepted")
if err != nil {
- return nil, errutil.DatabaseErr("Failed to check org membership").WithErrf("validateJWT(userId=%s, orgId=%s): %w", user.ID, claimOrgUUID, err)
+ return nil, errutil.DatabaseErr("Failed to check org membership").WithErrf("validateJWT(userId=%s, orgId=%s): %w", user.ID, claims.OrganizationID, err)
}
if orgMembership == nil {
- return nil, errutil.Forbidden("User not member of organization").WithErrf("validateJWT(userId=%s, orgId=%s): no membership found", user.ID, claimOrgUUID)
+ return nil, errutil.Forbidden("User not member of organization").WithErrf("validateJWT(userId=%s, orgId=%s): no membership found", user.ID, claims.OrganizationID)
}
if !orgMembership.IsActive {
- return nil, errutil.Forbidden("User organization membership is inactive").WithErrf("validateJWT(userId=%s, orgId=%s): membership inactive", user.ID, claimOrgUUID)
+ return nil, errutil.Forbidden("User organization membership is inactive").WithErrf("validateJWT(userId=%s, orgId=%s): membership inactive", user.ID, claims.OrganizationID)
}
- orgID = claimOrgUUID
+ orgID = claims.OrganizationID
orgName = org.Name
- rootOrgID = claimOrgUUID
- parentOrgID = claimOrgUUID
+ rootOrgID = claims.OrganizationID
+ parentOrgID = claims.OrganizationID
}
}
@@ -224,12 +225,12 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
isSuperAdmin := user.SuperAdmin.Valid && user.SuperAdmin.V
email := ""
if user.Email.Valid {
- email = user.Email.String
+ email = user.Email.V
}
username := ""
if user.Username.Valid {
- username = user.Username.String
+ username = user.Username.V
}
return &Identity{
@@ -255,11 +256,11 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
// 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) {
+func (a Authenticator) 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
+ return a.authSecret, nil
})
if err != nil {
return nil, errutil.Unauthorized("You are not allowed to access this resource").WithErrf("validateIdentityAccessToken: JWT parse failed: %w", err)
@@ -271,7 +272,7 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
}
// 3. Find identity access token (joined with identities table).
- accessToken, err := h.dal.FindIdentityAccessTokenByID(ctx, claims.IdentityAccessTokenID)
+ accessToken, err := a.findIdentityAccessTokenByID(ctx, claims.IdentityAccessTokenID)
if err != nil {
return nil, errutil.DatabaseErr("Failed to find identity access token").WithErrf("validateIdentityAccessToken(tokenId=%s): %w", claims.IdentityAccessTokenID, err)
}
@@ -287,9 +288,9 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
// 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)
+ trustedIPs, err := a.findTrustedIPsByAuthMethod(ctx, accessToken.IdentityID, accessToken.AuthMethod)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find trusted IPs").WithErrf("validateIdentityAccessToken(identityId=%s, authMethod=%s): %w", accessToken.IdentityId, accessToken.AuthMethod, err)
+ 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 {
@@ -300,14 +301,14 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
// 6. Resolve scope org.
var scopeOrgUUID uuid.UUID
- if nullUUIDValid(accessToken.SubOrganizationId) {
- scopeOrgUUID = accessToken.SubOrganizationId.V
+ if nullUUIDValid(accessToken.SubOrganizationID) {
+ scopeOrgUUID = accessToken.SubOrganizationID.V
} else {
scopeOrgUUID = accessToken.IdentityOrgID
}
// 7. Find org.
- org, err := h.dal.FindOrgByID(ctx, scopeOrgUUID)
+ org, err := a.findOrgByID(ctx, scopeOrgUUID)
if err != nil {
return nil, errutil.DatabaseErr("Failed to find organization").WithErrf("validateIdentityAccessToken(orgId=%s): %w", scopeOrgUUID, err)
}
@@ -319,19 +320,19 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
orgID, rootOrgID, parentOrgID, orgName := resolveOrgHierarchy(org)
// 9. Check org membership.
- membership, err := h.dal.FindEffectiveOrgMembership(ctx, actor.TypeIdentity, accessToken.IdentityId, org.ID, "")
+ membership, err := a.findEffectiveOrgMembership(ctx, actor.TypeIdentity, accessToken.IdentityID, org.ID, "")
if err != nil {
- return nil, errutil.DatabaseErr("Failed to check org membership").WithErrf("validateIdentityAccessToken(identityId=%s, orgId=%s): %w", accessToken.IdentityId, org.ID, err)
+ 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").WithErrf("validateIdentityAccessToken(identityId=%s, orgId=%s): no membership found", accessToken.IdentityId, org.ID)
+ 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.
// 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)
+ _ = a.deleteIdentityAccessTokenByID(ctx, accessToken.ID)
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)
}
@@ -339,13 +340,13 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
if accessToken.AccessTokenTTL > 0 {
var base time.Time
if accessToken.AccessTokenLastRenewedAt.Valid {
- base = accessToken.AccessTokenLastRenewedAt.Time
+ base = accessToken.AccessTokenLastRenewedAt.V
} else if accessToken.CreatedAt.Valid {
- base = accessToken.CreatedAt.Time
+ base = accessToken.CreatedAt.V
}
expiry := base.Add(time.Duration(accessToken.AccessTokenTTL) * time.Second)
if time.Now().After(expiry) {
- _ = h.dal.DeleteIdentityAccessTokenByID(ctx, accessToken.ID)
+ _ = a.deleteIdentityAccessTokenByID(ctx, accessToken.ID)
return nil, errutil.Unauthorized("Failed to renew MI access token due to TTL expiration").WithErrf("validateIdentityAccessToken(tokenId=%s): TTL expired", accessToken.ID)
}
}
@@ -354,17 +355,17 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
if accessToken.AccessTokenMaxTTL > 0 && accessToken.AccessTokenPeriod == 0 {
var createdAt time.Time
if accessToken.CreatedAt.Valid {
- createdAt = accessToken.CreatedAt.Time
+ createdAt = accessToken.CreatedAt.V
}
expirationDate := createdAt.Add(time.Duration(accessToken.AccessTokenMaxTTL) * time.Second)
if time.Now().After(expirationDate) {
- _ = h.dal.DeleteIdentityAccessTokenByID(ctx, accessToken.ID)
+ _ = a.deleteIdentityAccessTokenByID(ctx, accessToken.ID)
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)
+ _ = a.deleteIdentityAccessTokenByID(ctx, accessToken.ID)
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)
}
}
@@ -373,7 +374,7 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
// 12. Build identity auth info (for audit logging).
identityAuthInfo := &IdentityAuthInfo{
- IdentityID: accessToken.IdentityId,
+ IdentityID: accessToken.IdentityID,
IdentityName: accessToken.IdentityName,
AuthMethod: accessToken.AuthMethod,
}
@@ -393,7 +394,7 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
return &Identity{
AuthMode: AuthModeIdentityAccessToken,
Actor: actor.TypeIdentity,
- ActorID: accessToken.IdentityId,
+ ActorID: accessToken.IdentityID,
OrgID: orgID,
RootOrgID: rootOrgID,
ParentOrgID: parentOrgID,
@@ -406,7 +407,7 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
// 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) {
+func (a Authenticator) 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" {
@@ -416,7 +417,7 @@ func (h AuthHandler) validateServiceToken(ctx context.Context, token string) (*I
tokenSecret := parts[2]
// 2. Find service token.
- serviceToken, err := h.dal.FindServiceTokenByID(ctx, tokenID)
+ serviceToken, err := a.findServiceTokenByID(ctx, tokenID)
if err != nil {
return nil, errutil.DatabaseErr("Failed to find service token").WithErrf("validateServiceToken(tokenId=%s): %w", tokenID, err)
}
@@ -425,17 +426,17 @@ func (h AuthHandler) validateServiceToken(ctx context.Context, token string) (*I
}
// 3. Find project.
- project, err := h.dal.FindProjectByID(ctx, serviceToken.ProjectId)
+ project, err := a.findProjectByID(ctx, serviceToken.ProjectID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find project").WithErrf("validateServiceToken(projectId=%s): %w", serviceToken.ProjectId, err)
+ 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).WithErrf("validateServiceToken: project not found")
+ 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)
+ if serviceToken.ExpiresAt.Valid && serviceToken.ExpiresAt.V.Before(time.Now()) {
+ _ = a.deleteServiceTokenByID(ctx, serviceToken.ID)
return nil, errutil.Forbidden("Service token has expired").WithErrf("validateServiceToken(tokenId=%s): token expired", serviceToken.ID)
}
@@ -447,21 +448,20 @@ func (h AuthHandler) validateServiceToken(ctx context.Context, token string) (*I
// TODO(go): accessTokenQueue.updateServiceTokenStatus — update lastUsed timestamp
// 6. Find org.
- org, err := h.dal.FindOrgByID(ctx, project.OrgId)
+ org, err := a.findOrgByID(ctx, project.OrgID)
if err != nil {
- return nil, errutil.DatabaseErr("Failed to find organization").WithErrf("validateServiceToken(orgId=%s): %w", project.OrgId, err)
+ return nil, errutil.DatabaseErr("Failed to find organization").WithErrf("validateServiceToken(orgId=%s): %w", project.OrgID, err)
}
if org == nil {
- return nil, errutil.NotFound("Organization not found for project").WithErrf("validateServiceToken(orgId=%s): org not found", project.OrgId)
+ return nil, errutil.NotFound("Organization not found for project").WithErrf("validateServiceToken(orgId=%s): org not found", project.OrgID)
}
// 7. Build identity.
orgID, rootOrgID, parentOrgID, orgName := resolveOrgHierarchy(org)
- serviceTokenUUID := parseUUID(serviceToken.ID)
return &Identity{
AuthMode: AuthModeServiceToken,
Actor: actor.TypeService,
- ActorID: serviceTokenUUID,
+ ActorID: serviceToken.ID,
OrgID: orgID,
RootOrgID: rootOrgID,
ParentOrgID: parentOrgID,
@@ -470,17 +470,383 @@ func (h AuthHandler) validateServiceToken(ctx context.Context, token string) (*I
}, nil
}
-// resolveOrgHierarchy extracts orgID, rootOrgID, parentOrgID, and orgName from an OrgRow.
-func resolveOrgHierarchy(org *OrgRow) (orgID, rootOrgID, parentOrgID uuid.UUID, orgName string) {
+// resolveOrgHierarchy extracts orgID, rootOrgID, parentOrgID, and orgName from an orgRow.
+func resolveOrgHierarchy(org *orgRow) (orgID, rootOrgID, parentOrgID uuid.UUID, orgName string) {
orgID = org.ID
orgName = org.Name
rootOrgID = orgID
parentOrgID = orgID
- if nullUUIDValid(org.RootOrgId) {
- rootOrgID = org.RootOrgId.V
+ if nullUUIDValid(org.RootOrgID) {
+ rootOrgID = org.RootOrgID.V
}
- if nullUUIDValid(org.ParentOrgId) {
- parentOrgID = org.ParentOrgId.V
+ if nullUUIDValid(org.ParentOrgID) {
+ parentOrgID = org.ParentOrgID.V
}
return
}
+
+// --- Row types ---
+
+// sessionRow holds the subset of auth_token_sessions used by the authenticator.
+type sessionRow struct {
+ AccessVersion int32 `db:"access_version"`
+ UserID uuid.UUID `db:"user_id"`
+}
+
+// userRow holds the subset of users used by the authenticator.
+type userRow struct {
+ ID uuid.UUID `db:"id"`
+ Email sql.Null[string] `db:"email"`
+ Username sql.Null[string] `db:"username"`
+ IsAccepted sql.Null[bool] `db:"is_accepted"`
+ SuperAdmin sql.Null[bool] `db:"super_admin"`
+ IsLocked sql.Null[bool] `db:"is_locked"`
+ TemporaryLockDateEnd sql.Null[time.Time] `db:"temporary_lock_date_end"`
+}
+
+// orgRow holds the subset of organizations used by the authenticator.
+type orgRow struct {
+ ID uuid.UUID `db:"id"`
+ Name string `db:"name"`
+ RootOrgID sql.Null[uuid.UUID] `db:"root_org_id"`
+ ParentOrgID sql.Null[uuid.UUID] `db:"parent_org_id"`
+}
+
+// projectRow holds the subset of projects used by the authenticator.
+type projectRow struct {
+ OrgID uuid.UUID `db:"org_id"`
+}
+
+// identityAccessTokenRow holds the identity_access_tokens columns + joined identity fields.
+type identityAccessTokenRow struct {
+ ID uuid.UUID `db:"id"`
+ AccessTokenTTL int64 `db:"access_token_ttl"`
+ AccessTokenMaxTTL int64 `db:"access_token_max_ttl"`
+ AccessTokenNumUses int64 `db:"access_token_num_uses"`
+ AccessTokenNumUsesLimit int64 `db:"access_token_num_uses_limit"`
+ AccessTokenLastRenewedAt sql.Null[time.Time] `db:"access_token_last_renewed_at"`
+ IsAccessTokenRevoked bool `db:"is_access_token_revoked"`
+ IdentityID uuid.UUID `db:"identity_id"`
+ CreatedAt sql.Null[time.Time] `db:"created_at"`
+ AuthMethod actor.IdentityAuthMethod `db:"auth_method"`
+ AccessTokenPeriod int64 `db:"access_token_period"`
+ SubOrganizationID sql.Null[uuid.UUID] `db:"sub_organization_id"`
+ IdentityOrgID uuid.UUID `db:"identity_org_id"`
+ IdentityName string `db:"identity_name"`
+}
+
+// serviceTokenRow holds the subset of service_tokens used by the authenticator.
+type serviceTokenRow struct {
+ ID uuid.UUID `db:"id"`
+ Name string `db:"name"`
+ ProjectID string `db:"project_id"`
+ ExpiresAt sql.Null[time.Time] `db:"expires_at"`
+ SecretHash string `db:"secret_hash"`
+}
+
+// membershipRow holds the subset of memberships used by the authenticator.
+type membershipRow struct {
+ IsActive bool `db:"is_active"`
+}
+
+// --- Query methods ---
+
+// findSessionByIDAndUserID returns the session matching id + userId, or nil if not found.
+func (a Authenticator) findSessionByIDAndUserID(ctx context.Context, sessionID, userID uuid.UUID) (*sessionRow, error) {
+ query := `
+ SELECT access_version, user_id
+ FROM auth_token_sessions
+ WHERE id = @sessionID AND user_id = @userID
+ `
+ args := pgx.NamedArgs{"sessionID": sessionID, "userID": userID}
+
+ row := a.db.Replica().QueryRow(ctx, query, args)
+ var session sessionRow
+ err := row.Scan(&session.AccessVersion, &session.UserID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &session, nil
+}
+
+// findUserByID returns the user matching id, or nil if not found.
+func (a Authenticator) findUserByID(ctx context.Context, id uuid.UUID) (*userRow, error) {
+ query := `
+ SELECT id, email, username, is_accepted, super_admin, is_locked, temporary_lock_date_end
+ FROM users
+ WHERE id = @id
+ `
+ args := pgx.NamedArgs{"id": id}
+
+ row := a.db.Replica().QueryRow(ctx, query, args)
+ var user userRow
+ err := row.Scan(&user.ID, &user.Email, &user.Username, &user.IsAccepted, &user.SuperAdmin, &user.IsLocked, &user.TemporaryLockDateEnd)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &user, nil
+}
+
+// findOrgByID returns the organization matching id, or nil if not found.
+func (a Authenticator) findOrgByID(ctx context.Context, id uuid.UUID) (*orgRow, error) {
+ query := `
+ SELECT id, name, root_org_id, parent_org_id
+ FROM organizations
+ WHERE id = @id
+ `
+ args := pgx.NamedArgs{"id": id}
+
+ row := a.db.Replica().QueryRow(ctx, query, args)
+ var org orgRow
+ err := row.Scan(&org.ID, &org.Name, &org.RootOrgID, &org.ParentOrgID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &org, nil
+}
+
+// findProjectByID returns the project matching id, or nil if not found.
+func (a Authenticator) findProjectByID(ctx context.Context, id string) (*projectRow, error) {
+ query := `
+ SELECT org_id
+ FROM projects
+ WHERE id = @id
+ `
+ args := pgx.NamedArgs{"id": id}
+
+ row := a.db.Replica().QueryRow(ctx, query, args)
+ var project projectRow
+ err := row.Scan(&project.OrgID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &project, nil
+}
+
+// findIdentityAccessTokenByID returns the token (joined with identity) if not revoked, or nil.
+func (a Authenticator) findIdentityAccessTokenByID(ctx context.Context, id string) (*identityAccessTokenRow, error) {
+ query := `
+ SELECT
+ iat.id,
+ iat.access_token_ttl,
+ iat.access_token_max_ttl,
+ iat.access_token_num_uses,
+ iat.access_token_num_uses_limit,
+ iat.access_token_last_renewed_at,
+ iat.is_access_token_revoked,
+ iat.identity_id,
+ iat.created_at,
+ iat.auth_method,
+ iat.access_token_period,
+ iat.sub_organization_id,
+ i.org_id AS identity_org_id,
+ i.name AS identity_name
+ FROM identity_access_tokens iat
+ INNER JOIN identities i ON iat.identity_id = i.id
+ WHERE iat.id = @id AND iat.is_access_token_revoked = false
+ `
+ args := pgx.NamedArgs{"id": id}
+
+ row := a.db.Replica().QueryRow(ctx, query, args)
+ var token identityAccessTokenRow
+ err := row.Scan(
+ &token.ID,
+ &token.AccessTokenTTL,
+ &token.AccessTokenMaxTTL,
+ &token.AccessTokenNumUses,
+ &token.AccessTokenNumUsesLimit,
+ &token.AccessTokenLastRenewedAt,
+ &token.IsAccessTokenRevoked,
+ &token.IdentityID,
+ &token.CreatedAt,
+ &token.AuthMethod,
+ &token.AccessTokenPeriod,
+ &token.SubOrganizationID,
+ &token.IdentityOrgID,
+ &token.IdentityName,
+ )
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &token, nil
+}
+
+// deleteIdentityAccessTokenByID deletes the token on primary. Used for expired/exceeded tokens.
+func (a Authenticator) deleteIdentityAccessTokenByID(ctx context.Context, id uuid.UUID) error {
+ query := `DELETE FROM identity_access_tokens WHERE id = @id`
+ args := pgx.NamedArgs{"id": id}
+ _, err := a.db.Primary().Exec(ctx, query, args)
+ return err
+}
+
+// findServiceTokenByID returns the service token matching id, or nil.
+func (a Authenticator) findServiceTokenByID(ctx context.Context, id string) (*serviceTokenRow, error) {
+ query := `
+ SELECT id, name, project_id, expires_at, secret_hash
+ FROM service_tokens
+ WHERE id = @id
+ `
+ args := pgx.NamedArgs{"id": id}
+
+ row := a.db.Replica().QueryRow(ctx, query, args)
+ var token serviceTokenRow
+ err := row.Scan(&token.ID, &token.Name, &token.ProjectID, &token.ExpiresAt, &token.SecretHash)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &token, nil
+}
+
+// deleteServiceTokenByID deletes the service token on primary. Used for expired tokens.
+func (a Authenticator) deleteServiceTokenByID(ctx context.Context, id uuid.UUID) error {
+ query := `DELETE FROM service_tokens WHERE id = @id`
+ args := pgx.NamedArgs{"id": id}
+ _, err := a.db.Primary().Exec(ctx, query, args)
+ return err
+}
+
+// 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.
+func (a Authenticator) findEffectiveOrgMembership(ctx context.Context, actorType actor.Type, actorID, orgID uuid.UUID, filterStatus string) (*membershipRow, error) {
+ var actorCondition string
+ if actorType == actor.TypeUser {
+ actorCondition = `(
+ m.actor_user_id = @actorID
+ OR m.actor_group_id IN (
+ SELECT g.id FROM groups g
+ INNER JOIN user_group_membership ugm ON ugm.group_id = g.id
+ WHERE ugm.user_id = @actorID
+ )
+ )`
+ } else {
+ actorCondition = `(
+ m.actor_identity_id = @actorID
+ OR m.actor_group_id IN (
+ SELECT g.id FROM groups g
+ INNER JOIN identity_group_membership igm ON igm.group_id = g.id
+ WHERE igm.identity_id = @actorID
+ )
+ )`
+ }
+
+ statusFilter := "accepted"
+ if filterStatus != "" {
+ statusFilter = filterStatus
+ }
+
+ query := fmt.Sprintf(`
+ SELECT m.is_active
+ FROM memberships m
+ WHERE m.scope = 'organization'
+ AND m.scope_org_id = @orgID
+ AND %s
+ AND (m.status = @status OR m.status IS NULL)
+ LIMIT 1
+ `, actorCondition)
+
+ args := pgx.NamedArgs{
+ "actorID": actorID,
+ "orgID": orgID,
+ "status": statusFilter,
+ }
+
+ row := a.db.Replica().QueryRow(ctx, query, args)
+ var membership membershipRow
+ err := row.Scan(&membership.IsActive)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &membership, nil
+}
+
+// findTrustedIPsByAuthMethod returns the parsed trusted IPs for an identity's auth method.
+// Exact port of Node.js identityDAL.getTrustedIpsByAuthMethod.
+func (a Authenticator) findTrustedIPsByAuthMethod(ctx context.Context, identityID uuid.UUID, authMethod actor.IdentityAuthMethod) ([]TrustedIP, error) {
+ var tableName string
+ switch authMethod {
+ case actor.IdentityAuthMethodUniversal:
+ tableName = "identity_universal_auths"
+ case actor.IdentityAuthMethodKubernetes:
+ tableName = "identity_kubernetes_auths"
+ case actor.IdentityAuthMethodGCP:
+ tableName = "identity_gcp_auths"
+ case actor.IdentityAuthMethodAliCloud:
+ tableName = "identity_alicloud_auths"
+ case actor.IdentityAuthMethodAWS:
+ tableName = "identity_aws_auths"
+ case actor.IdentityAuthMethodAzure:
+ tableName = "identity_azure_auths"
+ case actor.IdentityAuthMethodToken:
+ tableName = "identity_token_auths"
+ case actor.IdentityAuthMethodTLSCert:
+ tableName = "identity_tls_cert_auths"
+ case actor.IdentityAuthMethodOCI:
+ tableName = "identity_oci_auths"
+ case actor.IdentityAuthMethodOIDC:
+ tableName = "identity_oidc_auths"
+ case actor.IdentityAuthMethodJWT:
+ tableName = "identity_jwt_auths"
+ case actor.IdentityAuthMethodLDAP:
+ tableName = "identity_ldap_auths"
+ case actor.IdentityAuthMethodSPIFFE:
+ tableName = "identity_spiffe_auths"
+ default:
+ return nil, nil
+ }
+
+ query := fmt.Sprintf(`
+ SELECT access_token_trusted_ips
+ FROM %s
+ WHERE identity_id = @identityID
+ LIMIT 1
+ `, tableName)
+
+ args := pgx.NamedArgs{"identityID": identityID}
+
+ row := a.db.Replica().QueryRow(ctx, query, args)
+ var trustedIPsJSON string
+ err := row.Scan(&trustedIPsJSON)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ return parseTrustedIPs(trustedIPsJSON)
+}
+
+// --- 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/libs.go b/backend-go/internal/services/libs.go
index 183741c6f0..9576717cd3 100644
--- a/backend-go/internal/services/libs.go
+++ b/backend-go/internal/services/libs.go
@@ -29,14 +29,14 @@ type ServicesDeps struct {
// Services holds all shared services.
type Services struct {
- Config *config.Config
- AuthHandler auth.AuthHandler
- Permission *permission.Service
- KMS *kms.Service
- License *license.Service
- Project *project.Service
- Queue *queue.Service
- AuditLog *auditlog.Service
+ Config *config.Config
+ Authenticator auth.Authenticator
+ Permission *permission.Service
+ KMS *kms.Service
+ License *license.Service
+ Project *project.Service
+ Queue *queue.Service
+ AuditLog *auditlog.Service
}
func NewServices(ctx context.Context, deps *ServicesDeps) (*Services, error) {
@@ -64,8 +64,7 @@ func NewServices(ctx context.Context, deps *ServicesDeps) (*Services, error) {
KeyStore: deps.KeyStore,
})
- authDAL := auth.NewDAL(deps.DB)
- authHandler := auth.NewAuthHandler(authDAL, deps.Config.AuthSecret)
+ authenticator := auth.NewAuthenticator(deps.DB, deps.Config.AuthSecret)
projectSvc := project.NewService(deps.Logger, project.Deps{DAL: projectDAL})
@@ -85,13 +84,13 @@ func NewServices(ctx context.Context, deps *ServicesDeps) (*Services, error) {
auditLogQueueHandler.Register(deps.Queue)
return &Services{
- Config: deps.Config,
- AuthHandler: authHandler,
- Permission: permission.NewService(deps.Logger, permission.Deps{DAL: permissionDAL}),
- KMS: kmsSvc,
- License: licenseSvc,
- Project: projectSvc,
- Queue: deps.Queue,
- AuditLog: auditLogSvc,
+ Config: deps.Config,
+ Authenticator: authenticator,
+ Permission: permission.NewService(deps.Logger, permission.Deps{DAL: permissionDAL}),
+ KMS: kmsSvc,
+ License: licenseSvc,
+ Project: projectSvc,
+ Queue: deps.Queue,
+ AuditLog: auditLogSvc,
}, nil
}
diff --git a/backend-go/internal/testutil/infra/nodejs.go b/backend-go/internal/testutil/infra/nodejs.go
index b5de99e4bb..3b1f1ec7b1 100644
--- a/backend-go/internal/testutil/infra/nodejs.go
+++ b/backend-go/internal/testutil/infra/nodejs.go
@@ -361,7 +361,7 @@ func (n *NodeJSService) InviteAndCreateUser(t *testing.T, email string) *UserSee
t.Fatal("infra.InviteAndCreateUser: db is nil, cannot query user ID")
}
var userID string
- err = n.db.Primary().QueryRowContext(context.Background(),
+ err = n.db.Primary().QueryRow(context.Background(),
`SELECT id FROM users WHERE username = $1`, email).Scan(&userID)
if err != nil {
t.Fatalf("infra.InviteAndCreateUser: query user ID: %v", err)
@@ -536,8 +536,8 @@ func (n *NodeJSService) CreateUserAdditionalPrivilege(t *testing.T, userID, proj
// Look up the user's project membership ID from the unified memberships table.
var membershipID string
- err := n.db.Primary().QueryRowContext(context.Background(),
- `SELECT id FROM memberships WHERE "actorUserId" = $1 AND "scopeProjectId" = $2 AND scope = 'project'`,
+ err := n.db.Primary().QueryRow(context.Background(),
+ `SELECT id FROM memberships WHERE actor_user_id = $1 AND scope_project_id = $2 AND scope = 'project'`,
userID, projectID).Scan(&membershipID)
if err != nil {
t.Fatalf("infra.CreateUserAdditionalPrivilege: query membership ID: %v", err)
diff --git a/backend-go/internal/testutil/infra/stack.go b/backend-go/internal/testutil/infra/stack.go
index 60414b168f..ab08781262 100644
--- a/backend-go/internal/testutil/infra/stack.go
+++ b/backend-go/internal/testutil/infra/stack.go
@@ -34,7 +34,7 @@ func (s *Stack) Stop() {
ctx := context.Background()
if s.db != nil {
- _ = s.db.Close()
+ s.db.Close()
}
if s.nodejs != nil {
if err := s.nodejs.container.Terminate(ctx); err != nil {