Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: simplified authenticator
=7561e63cee5d
diff --git a/backend-go/.golangci.yml b/backend-go/.golangci.ymlindex 108a79c897..76bad62b9b 100644--- a/backend-go/.golangci.yml+++ b/backend-go/.golangci.yml@@ -48,7 +48,7 @@ linters:- (net/http.ResponseWriter).Write- (*os.File).Write- (*encoding/json.Encoder).Encode- - (*github.com/jackc/pgx/v5.Tx).Rollback+ - (github.com/jackc/pgx/v5.Tx).Rollbackexhaustive:default-signifies-exhaustive: truediff --git a/backend-go/internal/server/middlewares/require_auth.go b/backend-go/internal/server/middlewares/require_auth.goindex c825bd4ca0..3ac235c587 100644--- a/backend-go/internal/server/middlewares/require_auth.go+++ b/backend-go/internal/server/middlewares/require_auth.go@@ -23,8 +23,8 @@ const (// Authenticator defines the methods needed for token validation.type Authenticator interface {- ValidateJWT(ctx context.Context, token string) (*auth.Identity, error)- ValidateIdentityAccessToken(ctx context.Context, token, ipAddress string) (*auth.Identity, error)+ // ValidateJWTToken validates any JWT (user or identity) and returns the identity and actual auth mode.+ ValidateJWTToken(ctx context.Context, token, ipAddress string) (*auth.Identity, auth.AuthMode, error)ValidateServiceToken(ctx context.Context, token string) (*auth.Identity, error)AssumePrivilege() apiauth.AssumePrivilegeVerifier}@@ -84,33 +84,32 @@ func RequireAuth(authenticator Authenticator, opts ...AuthOption) func(http.Handreturn}- classifiedMode := apiauth.ClassifyToken(token)- authMode, ok := mapClassifiedMode(classifiedMode)- if !ok {- writeUnauthorized(w, "Unsupported authentication method")- return- }-- if !cfg.allowedModes[authMode] {- writeUnauthorized(w, "Authentication method not allowed for this endpoint")- return- }-ctx := r.Context()var identity *auth.Identity+ var actualMode AuthModevar err error- switch authMode {- case JWTAuth:- identity, err = authenticator.ValidateJWT(ctx, token)- case IdentityAccessTokenAuth:+ // Classify and validate token+ classifiedMode := apiauth.ClassifyToken(token)+ switch classifiedMode {+ case auth.AuthModeServiceToken:+ identity, err = authenticator.ValidateServiceToken(ctx, token)+ actualMode = ServiceTokenAuth++ case auth.AuthModeJWT:+ // JWT tokens are validated and typed in one callipAddress := ""if httpInfo := auth.HTTPInfoFromContext(ctx); httpInfo != nil {ipAddress = httpInfo.IPAddress}- identity, err = authenticator.ValidateIdentityAccessToken(ctx, token, ipAddress)- case ServiceTokenAuth:- identity, err = authenticator.ValidateServiceToken(ctx, token)+ var authMode auth.AuthMode+ identity, authMode, err = authenticator.ValidateJWTToken(ctx, token, ipAddress)+ // Map the actual auth mode from validation+ actualMode, _ = mapClassifiedMode(authMode)++ default:+ writeUnauthorized(w, "Unsupported authentication method")+ return}if err != nil {@@ -128,6 +127,12 @@ func RequireAuth(authenticator Authenticator, opts ...AuthOption) func(http.Handreturn}+ // Check if the actual token type is allowed for this endpoint+ if !cfg.allowedModes[actualMode] {+ writeUnauthorized(w, "Authentication method not allowed for this endpoint")+ return+ }+populateHTTPInfo(ctx, identity)ctx = auth.WithIdentity(ctx, identity)diff --git a/backend-go/internal/services/auth/apiauth/authenticator.go b/backend-go/internal/services/auth/apiauth/authenticator.goindex f0b76b9346..3867ab6cfc 100644--- a/backend-go/internal/services/auth/apiauth/authenticator.go+++ b/backend-go/internal/services/auth/apiauth/authenticator.go@@ -10,7 +10,6 @@ import ("strings""time"- "github.com/golang-jwt/jwt/v5""github.com/google/uuid""github.com/jackc/pgx/v5""golang.org/x/crypto/bcrypt"@@ -54,29 +53,47 @@ func (a *Authenticator) AssumePrivilege() AssumePrivilegeVerifier {return a.assumePrivilege}-// TODO(gov0): Missing test-// ValidateJWT performs real JWT validation.-// Exact port of fnValidateJwtIdentity in auth-token-service.ts:212-285.-func (a *Authenticator) ValidateJWT(ctx context.Context, token string) (*auth.Identity, error) {- // 1. Parse and verify JWT signature (HS256 only).- claims := &UserJWTClaims{}- _, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (any, error) {- if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {- return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])- }- return a.authSecret, nil- })+// ValidateJWTToken parses a JWT once, routes based on authTokenType, and validates.+// This is the unified entry point for all JWT validation.+// Returns (identity, authMode, error) where authMode indicates the actual token type.+func (a *Authenticator) ValidateJWTToken(ctx context.Context, token, ipAddress string) (*auth.Identity, auth.AuthMode, error) {+ claims, err := parseJWT(token, a.authSecret)+ if err != nil {+ return nil, "", errutil.Unauthorized("Invalid JWT token").WithErrf("validateJWTToken: %w", err)+ }++ switch claims.AuthTokenType {+ case auth.AuthTokenTypeAccessToken:+ identity, err := a.validateUserTokenClaims(ctx, claims.ToUserClaims())+ return identity, auth.AuthModeJWT, err++ case auth.AuthTokenTypeIdentityAccessToken:+ identity, err := a.validateIdentityTokenClaims(ctx, claims.ToIdentityClaims(), ipAddress)+ return identity, auth.AuthModeIdentityAccessToken, err++ default:+ return nil, "", errutil.Unauthorized("Unsupported token type").WithErrf("validateJWTToken: unsupported authTokenType %s", claims.AuthTokenType)+ }+}+// ValidateJWT validates a user JWT token.+// For unified JWT handling that auto-routes based on token type, use ValidateJWTToken.+func (a *Authenticator) ValidateJWT(ctx context.Context, token string) (*auth.Identity, error) {+ claims, err := parseJWT(token, a.authSecret)if err != nil {return nil, errutil.Unauthorized("Invalid JWT token").WithErrf("validateJWT: %w", err)}- // 2. Validate authTokenType.if claims.AuthTokenType != auth.AuthTokenTypeAccessToken {return nil, errutil.Unauthorized("You are not allowed to access this resource").WithErrf("validateJWT: invalid authTokenType %s", claims.AuthTokenType)}- // 3. Find session by tokenVersionId + userId.+ return a.validateUserTokenClaims(ctx, claims.ToUserClaims())+}++// validateUserTokenClaims validates pre-parsed user JWT claims.+func (a *Authenticator) validateUserTokenClaims(ctx context.Context, claims *UserJWTClaims) (*auth.Identity, error) {+ // 1. Find session by tokenVersionId + 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", claims.TokenVersionID, claims.UserID, err)@@ -206,29 +223,24 @@ func (a *Authenticator) ValidateJWT(ctx context.Context, token string) (*auth.Id}, nil}-// ValidateIdentityAccessToken performs real identity access token validation.-// Port of fnValidateIdentityAccessTokenFast in identity-access-token-service.ts.-// New-format tokens carry all claims in the JWT for stateless validation; legacy tokens-// fall back to DB lookup.+// ValidateIdentityAccessToken validates an identity access token.+// For unified JWT handling that auto-routes based on token type, use ValidateJWTToken.func (a *Authenticator) ValidateIdentityAccessToken(ctx context.Context, token, ipAddress string) (*auth.Identity, error) {- // 1. Parse and verify JWT signature (HS256 only).- claims := &IdentityJWTClaims{}- _, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (any, error) {- if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {- return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])- }- return a.authSecret, nil- })+ claims, err := parseJWT(token, a.authSecret)if err != nil {return nil, errutil.Unauthorized("You are not allowed to access this resource").WithErrf("validateIdentityAccessToken: JWT parse failed: %w", err)}- // 2. Validate authTokenType.if claims.AuthTokenType != auth.AuthTokenTypeIdentityAccessToken {return nil, errutil.Unauthorized("You are not allowed to access this resource").WithErrf("validateIdentityAccessToken: invalid authTokenType %s", claims.AuthTokenType)}- // 3. Resolve token source - new format uses JWT claims, legacy falls back to DB.+ return a.validateIdentityTokenClaims(ctx, claims.ToIdentityClaims(), ipAddress)+}++// validateIdentityTokenClaims validates pre-parsed identity JWT claims.+func (a *Authenticator) validateIdentityTokenClaims(ctx context.Context, claims *IdentityJWTClaims, ipAddress string) (*auth.Identity, error) {+ // 1. Resolve token source - new format uses JWT claims, legacy falls back to DB.var (identityID = claims.IdentityIDidentityName stringdiff --git a/backend-go/internal/services/auth/apiauth/authenticator_test.go b/backend-go/internal/services/auth/apiauth/authenticator_test.goindex 46c091cd45..bfb9233700 100644--- a/backend-go/internal/services/auth/apiauth/authenticator_test.go+++ b/backend-go/internal/services/auth/apiauth/authenticator_test.go@@ -9,145 +9,8 @@ import ("github.com/google/uuid""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"-- "github.com/infisical/api/internal/services/auth")-// =============================================================================-// ClassifyToken Tests (no DB/backend needed)-// =============================================================================--func TestClassifyToken_ServiceToken(t *testing.T) {- t.Parallel()-- tests := []struct {- name string- token string- expected auth.AuthMode- }{- {- name: "valid service token format",- token: "st." + uuid.New().String() + ".secret123",- expected: auth.AuthModeServiceToken,- },- {- name: "service token with only prefix and id",- token: "st." + uuid.New().String(),- expected: auth.AuthModeServiceToken,- },- {- name: "service token with empty parts after prefix",- token: "st..",- expected: auth.AuthModeServiceToken,- },- {- name: "wrong prefix sv",- token: "sv." + uuid.New().String() + ".secret",- expected: "",- },- {- name: "wrong prefix ST uppercase",- token: "ST." + uuid.New().String() + ".secret",- expected: "",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- t.Parallel()- result := ClassifyToken(tt.token)- assert.Equal(t, tt.expected, result)- })- }-}--func TestClassifyToken_JWT(t *testing.T) {- t.Parallel()-- // Build valid JWTs with different authTokenType values- // JWT format: header.payload.signature (base64url encoded)- // We only need the payload to have the authTokenType claim-- tests := []struct {- name string- token string- expected auth.AuthMode- }{- {- name: "JWT with accessToken type",- // payload: {"authTokenType":"accessToken"}- token: "eyJhbGciOiJIUzI1NiJ9.eyJhdXRoVG9rZW5UeXBlIjoiYWNjZXNzVG9rZW4ifQ.sig",- expected: auth.AuthModeJWT,- },- {- name: "JWT with identityAccessToken type",- // payload: {"authTokenType":"identityAccessToken"}- token: "eyJhbGciOiJIUzI1NiJ9.eyJhdXRoVG9rZW5UeXBlIjoiaWRlbnRpdHlBY2Nlc3NUb2tlbiJ9.sig",- expected: auth.AuthModeIdentityAccessToken,- },- {- name: "JWT with refreshToken type returns empty",- // payload: {"authTokenType":"refreshToken"}- token: "eyJhbGciOiJIUzI1NiJ9.eyJhdXRoVG9rZW5UeXBlIjoicmVmcmVzaFRva2VuIn0.sig",- expected: "",- },- {- name: "JWT with unknown type returns empty",- // payload: {"authTokenType":"unknownType"}- token: "eyJhbGciOiJIUzI1NiJ9.eyJhdXRoVG9rZW5UeXBlIjoidW5rbm93blR5cGUifQ.sig",- expected: "",- },- {- name: "JWT without authTokenType returns empty",- // payload: {"sub":"1234567890"}- token: "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.sig",- expected: "",- },- {- name: "JWT with empty payload returns empty",- token: "eyJhbGciOiJIUzI1NiJ9..sig",- expected: "",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- t.Parallel()- result := ClassifyToken(tt.token)- assert.Equal(t, tt.expected, result)- })- }-}--func TestClassifyToken_Malformed(t *testing.T) {- t.Parallel()-- tests := []struct {- name string- token string- }{- {"empty token", ""},- {"single dot", "."},- {"two dots", ".."},- {"three dots only", "..."},- {"two parts only", "header.payload"},- {"four parts", "a.b.c.d"},- {"random string", "not-a-token-at-all"},- {"base64 garbage in payload", "eyJhbGciOiJIUzI1NiJ9.!!!invalid!!!.sig"},- {"only header valid base64", "eyJhbGciOiJIUzI1NiJ9"},- {"whitespace", " "},- {"newlines", "header\n.payload\n.sig"},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- t.Parallel()- result := ClassifyToken(tt.token)- assert.Equal(t, auth.AuthMode(""), result, "malformed token should return empty AuthMode")- })- }-}-// =============================================================================// ParseTrustedIPs Tests (no DB needed)// =============================================================================diff --git a/backend-go/internal/services/auth/apiauth/claims.go b/backend-go/internal/services/auth/apiauth/claims.goindex bca1065527..57d22e6861 100644--- a/backend-go/internal/services/auth/apiauth/claims.go+++ b/backend-go/internal/services/auth/apiauth/claims.go@@ -1,12 +1,102 @@package apiauthimport (+ "fmt"+"github.com/golang-jwt/jwt/v5""github.com/google/uuid""github.com/infisical/api/internal/services/auth")+// UnifiedJWTClaims is a union of all JWT claim fields from both user and identity tokens.+// Only the fields relevant to the AuthTokenType will be populated.+type UnifiedJWTClaims struct {+ jwt.RegisteredClaims+ AuthTokenType auth.AuthTokenType `json:"authTokenType"`++ // User JWT fields+ AuthMethod string `json:"authMethod,omitempty"`+ UserID uuid.UUID `json:"userId,omitempty"`+ TokenVersionID uuid.UUID `json:"tokenVersionId,omitempty"`+ AccessVersion int `json:"accessVersion,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"`++ // Identity JWT fields+ IdentityID uuid.UUID `json:"identityId,omitempty"`+ ClientSecretID string `json:"clientSecretId,omitempty"`+ IdentityAccessTokenID string `json:"identityAccessTokenId,omitempty"`+ IdentityAuth *IdentityAuth `json:"identityAuth,omitempty"`+ IdentityName string `json:"identityName,omitempty"`+ OrgID uuid.UUID `json:"orgId,omitempty"`+ RootOrgID uuid.UUID `json:"rootOrgId,omitempty"`+ ParentOrgID uuid.UUID `json:"parentOrgId,omitempty"`+ AccessTokenTTL int64 `json:"accessTokenTTL,omitempty"`+ AccessTokenMaxTTL int64 `json:"accessTokenMaxTTL,omitempty"`+ AccessTokenPeriod int64 `json:"accessTokenPeriod,omitempty"`+ CreationEpoch int64 `json:"creationEpoch,omitempty"`+ NumUsesLimit int64 `json:"numUsesLimit,omitempty"`+}++// ToUserClaims converts to UserJWTClaims for user token validation.+func (c *UnifiedJWTClaims) ToUserClaims() *UserJWTClaims {+ return &UserJWTClaims{+ RegisteredClaims: c.RegisteredClaims,+ AuthTokenType: c.AuthTokenType,+ AuthMethod: c.AuthMethod,+ UserID: c.UserID,+ TokenVersionID: c.TokenVersionID,+ AccessVersion: c.AccessVersion,+ OrganizationID: c.OrganizationID,+ SubOrganizationID: c.SubOrganizationID,+ IsMfaVerified: c.IsMfaVerified,+ MfaMethod: c.MfaMethod,+ MCP: c.MCP,+ }+}++// ToIdentityClaims converts to IdentityJWTClaims for identity token validation.+func (c *UnifiedJWTClaims) ToIdentityClaims() *IdentityJWTClaims {+ return &IdentityJWTClaims{+ RegisteredClaims: c.RegisteredClaims,+ AuthTokenType: c.AuthTokenType,+ IdentityID: c.IdentityID,+ ClientSecretID: c.ClientSecretID,+ IdentityAccessTokenID: c.IdentityAccessTokenID,+ IdentityAuth: c.IdentityAuth,+ IdentityName: c.IdentityName,+ AuthMethod: c.AuthMethod,+ OrgID: c.OrgID,+ RootOrgID: c.RootOrgID,+ ParentOrgID: c.ParentOrgID,+ AccessTokenTTL: c.AccessTokenTTL,+ AccessTokenMaxTTL: c.AccessTokenMaxTTL,+ AccessTokenPeriod: c.AccessTokenPeriod,+ CreationEpoch: c.CreationEpoch,+ NumUsesLimit: c.NumUsesLimit,+ }+}++// parseJWT parses and validates a JWT with signature verification.+// Returns the unified claims which can be converted to specific types based on AuthTokenType.+func parseJWT(token string, secret []byte) (*UnifiedJWTClaims, error) {+ claims := &UnifiedJWTClaims{}+ _, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (any, error) {+ if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {+ return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])+ }+ return secret, nil+ })+ if err != nil {+ return nil, fmt.Errorf("invalid JWT: %w", err)+ }+ return claims, nil+}+// UserJWTClaims represents the JWT payload for user browser sessions.// Exact match of the Node.js AuthModeJwtTokenPayload.type UserJWTClaims struct {diff --git a/backend-go/internal/services/auth/apiauth/classify.go b/backend-go/internal/services/auth/apiauth/classify.goindex b762129f75..89976e8e33 100644--- a/backend-go/internal/services/auth/apiauth/classify.go+++ b/backend-go/internal/services/auth/apiauth/classify.go@@ -1,63 +1,26 @@package apiauthimport (- "encoding/base64"- "encoding/json""strings""github.com/infisical/api/internal/services/auth")-// peekClaims is a minimal struct for peeking at the token type-// without performing signature verification.-type peekClaims struct {- AuthTokenType auth.AuthTokenType `json:"authTokenType"`-}--// ClassifyToken determines the AuthMode from a raw token string-// using cheap checks only (string prefix, base64 decode) — no crypto.+// ClassifyToken determines the AuthMode from a raw token string using cheap checks only.+// Service tokens are identified by their "st." prefix.+// JWTs are identified by having exactly 3 dot-separated parts.+// This does NOT validate the token - only classifies it for routing.func ClassifyToken(token string) auth.AuthMode {if strings.HasPrefix(token, "st.") {return auth.AuthModeServiceToken}- claims := peekJWTClaims(token)- switch claims.AuthTokenType {- case auth.AuthTokenTypeAccessToken:- return auth.AuthModeJWT- case auth.AuthTokenTypeIdentityAccessToken:- return auth.AuthModeIdentityAccessToken- case auth.AuthTokenTypeRefreshToken,- auth.AuthTokenTypeSignupToken,- auth.AuthTokenTypeMfaToken,- auth.AuthTokenTypeProviderToken,- auth.AuthTokenTypeAPIKey,- auth.AuthTokenTypeServiceAccessToken,- auth.AuthTokenTypeServiceRefreshToken,- auth.AuthTokenTypeSCIMToken:- return ""- }-- return ""-}--// peekJWTClaims decodes the JWT payload segment (no signature verification)-// to inspect the authTokenType claim.-func peekJWTClaims(token string) peekClaims {+ // JWT format: header.payload.signature (exactly 3 parts)parts := strings.SplitN(token, ".", 4)- if len(parts) < 3 {- return peekClaims{}- }-- payload, err := base64.RawURLEncoding.DecodeString(parts[1])- if err != nil {- return peekClaims{}- }-- var claims peekClaims- if err := json.Unmarshal(payload, &claims); err != nil {- return peekClaims{}+ if len(parts) != 3 {+ return ""}- return claims+ // It looks like a JWT - actual type (user vs identity) is determined after validation+ return auth.AuthModeJWT}diff --git a/backend-go/internal/services/auth/apiauth/classify_test.go b/backend-go/internal/services/auth/apiauth/classify_test.goindex 5304c8d395..d7d7db0fb9 100644--- a/backend-go/internal/services/auth/apiauth/classify_test.go+++ b/backend-go/internal/services/auth/apiauth/classify_test.go@@ -1,78 +1,94 @@package apiauthimport (- "encoding/base64"- "encoding/json""testing""github.com/infisical/api/internal/services/auth")-// 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_ServiceToken(t *testing.T) {+ mode := ClassifyToken("st.abc123.secretpart")+ if mode != auth.AuthModeServiceToken {+ t.Errorf("expected %q, got %q", auth.AuthModeServiceToken, mode)+ }}-func TestClassifyToken_VariousInputTypes(t *testing.T) {- t.Run("service token", func(t *testing.T) {- mode := ClassifyToken("st.abc123.secretpart")- if mode != auth.AuthModeServiceToken {- t.Errorf("expected %q, got %q", auth.AuthModeServiceToken, mode)- }- })-- t.Run("JWT access token", func(t *testing.T) {- token := makeJWT(map[string]any{"authTokenType": string(auth.AuthTokenTypeAccessToken), "userId": "u1"})- mode := ClassifyToken(token)+func TestClassifyToken_JWT(t *testing.T) {+ t.Run("valid JWT format returns AuthModeJWT", func(t *testing.T) {+ // Any 3-part dot-separated string is classified as JWT+ mode := ClassifyToken("header.payload.signature")if mode != auth.AuthModeJWT {t.Errorf("expected %q, got %q", auth.AuthModeJWT, mode)}})- t.Run("identity access token", func(t *testing.T) {- token := makeJWT(map[string]any{"authTokenType": string(auth.AuthTokenTypeIdentityAccessToken), "identityId": "id1"})- mode := ClassifyToken(token)- if mode != auth.AuthModeIdentityAccessToken {- t.Errorf("expected %q, got %q", auth.AuthModeIdentityAccessToken, mode)+ t.Run("real JWT structure", func(t *testing.T) {+ // Even with actual base64 content, it's just classified as JWT+ mode := ClassifyToken("eyJhbGciOiJIUzI1NiJ9.eyJ0ZXN0IjoxfQ.signature")+ if mode != auth.AuthModeJWT {+ t.Errorf("expected %q, got %q", auth.AuthModeJWT, mode)}})+}- t.Run("empty token returns empty", func(t *testing.T) {+func TestClassifyToken_Malformed(t *testing.T) {+ t.Run("empty token", 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) {+ t.Run("random string without dots", 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)+ t.Run("two parts", func(t *testing.T) {+ mode := ClassifyToken("part1.part2")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")+ t.Run("four parts", func(t *testing.T) {+ mode := ClassifyToken("a.b.c.d")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)+ t.Run("service token prefix but wrong format", func(t *testing.T) {+ // Has st. prefix so classified as service token even if malformed+ mode := ClassifyToken("st.only-one-part")+ if mode != auth.AuthModeServiceToken {+ t.Errorf("expected %q, got %q", auth.AuthModeServiceToken, mode)}})}++func TestClassifyToken_VariousInputTypes(t *testing.T) {+ tests := []struct {+ name string+ token string+ expected auth.AuthMode+ }{+ {"service token", "st.abc.def", auth.AuthModeServiceToken},+ {"jwt format", "a.b.c", auth.AuthModeJWT},+ {"empty", "", ""},+ {"no dots", "nodots", ""},+ {"one dot", "one.dot", ""},+ {"three dots", "a.b.c.d", ""},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := ClassifyToken(tc.token)+ if got != tc.expected {+ t.Errorf("ClassifyToken(%q) = %q, want %q", tc.token, got, tc.expected)+ }+ })+ }+}diff --git a/backend-go/internal/services/kms/kms_org.go b/backend-go/internal/services/kms/kms_org.goindex 1b392d88ec..b5b38035a3 100644--- a/backend-go/internal/services/kms/kms_org.go+++ b/backend-go/internal/services/kms/kms_org.go@@ -82,7 +82,7 @@ func (s *Service) ensureOrgDataKey(ctx context.Context, orgID uuid.UUID) (dataKeif err != nil {return nil, fmt.Errorf("beginning transaction: %w", err)}- defer errutil.DeferErr(ctx, func() error { return tx.Rollback(ctx) }, "rolling back org data key tx")+ defer tx.Rollback(ctx)lock, err := pglock.AcquireBlockingLock(ctx, tx, keyLockID)if err != nil {diff --git a/backend-go/internal/services/kms/kms_project.go b/backend-go/internal/services/kms/kms_project.goindex 156abff290..213327ce9f 100644--- a/backend-go/internal/services/kms/kms_project.go+++ b/backend-go/internal/services/kms/kms_project.go@@ -83,7 +83,7 @@ func (s *Service) ensureProjectDataKey(ctx context.Context, projectID string) (dif err != nil {return nil, fmt.Errorf("beginning transaction: %w", err)}- defer errutil.DeferErr(ctx, func() error { return tx.Rollback(ctx) }, "rolling back project data key tx")+ defer tx.Rollback(ctx)lock, err := pglock.AcquireBlockingLock(ctx, tx, keyLockID)if err != nil {diff --git a/backend-go/internal/services/serverconfig/serverconfig.go b/backend-go/internal/services/serverconfig/serverconfig.goindex fc25d23e8d..c9b564cad3 100644--- a/backend-go/internal/services/serverconfig/serverconfig.go+++ b/backend-go/internal/services/serverconfig/serverconfig.go@@ -237,7 +237,7 @@ func (s *Service) findOrCreateConfig(ctx context.Context) (ServerConfig, error)if err != nil {return ServerConfig{}, fmt.Errorf("beginning transaction: %w", err)}- defer errutil.DeferErr(ctx, func() error { return tx.Rollback(ctx) }, "rolling back serverconfig tx")+ defer tx.Rollback(ctx)// Acquire advisory lock to prevent concurrent init.if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock($1)", PgLockSuperAdminInit); err != nil {