Skip to content

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

feat: re-organize the dal and the types for permission and auth

=fdf064d5a31f
diff --git a/backend-go/internal/services/actor/actor.go b/backend-go/internal/services/actor/actor.go
new file mode 100644
index 0000000000..1edce46bf5
--- /dev/null
+++ b/backend-go/internal/services/actor/actor.go
@@ -0,0 +1,71 @@
+// Package actor provides shared types and context helpers for actor identity
+// used by both auth and permission packages to avoid import cycles.
+package actor
+
+import (
+ "context"
+
+ "github.com/google/uuid"
+)
+
+// Type identifies the kind of entity performing an action.
+type Type string
+
+const (
+ TypeUser Type = "user"
+ TypeIdentity Type = "identity"
+ TypeService Type = "service"
+)
+
+// AuthMethod represents the authentication method used by the actor (e.g. "jwt", "api-key").
+// An empty string means no specific method (e.g. platform-level actions).
+type AuthMethod string
+
+// AuthOIDC holds OIDC-specific claims from the identity JWT payload.
+// Used for permission template interpolation (e.g., {{identity.auth.oidc.sub}}).
+type AuthOIDC struct {
+ Claims map[string]string
+}
+
+// AuthKubernetes holds Kubernetes-specific metadata from the identity JWT payload.
+// Used for permission template interpolation (e.g., {{identity.auth.kubernetes.namespace}}).
+type AuthKubernetes struct {
+ Namespace string
+ Name string
+}
+
+// AuthAWS holds AWS-specific principal details from the identity JWT payload.
+// Used for permission template interpolation (e.g., {{identity.auth.aws.accountId}}).
+type AuthAWS struct {
+ AccountID string
+ ARN string
+ UserID string
+ Partition string
+ Service string
+ ResourceType string
+ ResourceName string
+}
+
+// AuthInfo holds auth-method-specific claims for permission template interpolation.
+// Set by the auth layer, read by the permission service.
+type AuthInfo struct {
+ IdentityID uuid.UUID
+ IdentityName string
+ AuthMethod string
+ OIDC *AuthOIDC
+ Kubernetes *AuthKubernetes
+ AWS *AuthAWS
+}
+
+type authInfoKey struct{}
+
+// WithAuthInfo stores the actor auth info in the context.
+func WithAuthInfo(ctx context.Context, info *AuthInfo) context.Context {
+ return context.WithValue(ctx, authInfoKey{}, info)
+}
+
+// AuthInfoFromContext returns the actor auth info stored in ctx, or nil if absent.
+func AuthInfoFromContext(ctx context.Context) *AuthInfo {
+ info, _ := ctx.Value(authInfoKey{}).(*AuthInfo)
+ return info
+}
diff --git a/backend-go/internal/services/auth/auth.go b/backend-go/internal/services/auth/auth.go
index 49da7015b3..446f00c30f 100644
--- a/backend-go/internal/services/auth/auth.go
+++ b/backend-go/internal/services/auth/auth.go
@@ -7,7 +7,7 @@ import (
"github.com/google/uuid"
- "github.com/infisical/api/internal/services/permission"
+ "github.com/infisical/api/internal/services/actor"
)
// AuthMode identifies the authentication mechanism used by the caller.
@@ -43,51 +43,36 @@ type UserAuthInfo struct {
Email string
}
-// IdentityAuthInfo holds the minimal identity info stored in request context for audit logging.
+// IdentityAuthInfo is an alias for actor.AuthInfo for backward compatibility.
// Port of Node.js requestContext.identityAuthInfo.
-type IdentityAuthInfo struct {
- IdentityID uuid.UUID
- IdentityName string
- AuthMethod string
- OIDC *IdentityAuthOIDC
- Kubernetes *IdentityAuthKubernetes
- AWS *IdentityAuthAWS
-}
+type IdentityAuthInfo = actor.AuthInfo
-// IdentityAuthOIDC holds OIDC-specific claims from the identity JWT payload.
-type IdentityAuthOIDC struct {
- Claims map[string]string `json:"claims"`
-}
+// IdentityAuthOIDC is an alias for actor.AuthOIDC for backward compatibility.
+type IdentityAuthOIDC = actor.AuthOIDC
-// IdentityAuthKubernetes holds Kubernetes-specific metadata from the identity JWT payload.
-type IdentityAuthKubernetes struct {
- Namespace string `json:"namespace"`
- Name string `json:"name"`
-}
+// IdentityAuthKubernetes is an alias for actor.AuthKubernetes for backward compatibility.
+type IdentityAuthKubernetes = actor.AuthKubernetes
-// 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"`
-}
+// IdentityAuthAWS is an alias for actor.AuthAWS for backward compatibility.
+type IdentityAuthAWS = actor.AuthAWS
// 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
+ Actor actor.Type
ActorID uuid.UUID
OrgID uuid.UUID
RootOrgID uuid.UUID
ParentOrgID uuid.UUID
- AuthMethod permission.ActorAuthMethod
+ OrgName string
+ AuthMethod actor.AuthMethod
IsSuperAdmin bool
+ // MFA fields (for JWT user auth).
+ IsMfaVerified bool
+ MfaMethod string
+
// 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.
diff --git a/backend-go/internal/services/auth/claims.go b/backend-go/internal/services/auth/claims.go
index 948c8e84de..8a96ca7b48 100644
--- a/backend-go/internal/services/auth/claims.go
+++ b/backend-go/internal/services/auth/claims.go
@@ -14,6 +14,8 @@ type UserJWTClaims struct {
OrganizationID string `json:"organizationId,omitempty"`
SubOrganizationID string `json:"subOrganizationId,omitempty"`
IsMfaVerified bool `json:"isMfaVerified,omitempty"`
+ MfaMethod string `json:"mfaMethod,omitempty"`
+ MCP bool `json:"mcp,omitempty"`
}
// IdentityJWTClaims represents the JWT payload for machine identity access tokens.
diff --git a/backend-go/internal/services/auth/dal.go b/backend-go/internal/services/auth/dal.go
index 8b13ce1926..61cf27683f 100644
--- a/backend-go/internal/services/auth/dal.go
+++ b/backend-go/internal/services/auth/dal.go
@@ -11,7 +11,7 @@ import (
"github.com/infisical/api/internal/database/pg"
"github.com/infisical/api/internal/database/pg/gen/table"
- "github.com/infisical/api/internal/services/permission"
+ "github.com/infisical/api/internal/services/actor"
)
// DAL provides data access for authentication-related queries.
@@ -59,18 +59,20 @@ func (d *DAL) FindSessionByIDAndUserID(ctx context.Context, sessionID, userID uu
// 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"`
+ 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).
+ 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)))
@@ -90,6 +92,7 @@ func (d *DAL) FindUserByID(ctx context.Context, id uuid.UUID) (*UserRow, error)
// 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"`
}
@@ -98,7 +101,7 @@ type OrgRow struct {
func (d *DAL) FindOrgByID(ctx context.Context, id uuid.UUID) (*OrgRow, error) {
o := table.Organizations
- stmt := postgres.SELECT(o.ID, o.RootOrgId, o.ParentOrgId).
+ stmt := postgres.SELECT(o.ID, o.Name, o.RootOrgId, o.ParentOrgId).
FROM(o).
WHERE(o.ID.EQ(postgres.UUID(id)))
@@ -259,7 +262,7 @@ type MembershipRow struct {
// 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) {
+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
@@ -267,7 +270,7 @@ func (d *DAL) FindEffectiveOrgMembership(ctx context.Context, actorType permissi
// Build the group subquery based on actor type.
var actorCondition postgres.BoolExpression
- if actorType == permission.ActorTypeUser {
+ 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)))
diff --git a/backend-go/internal/services/auth/handler.go b/backend-go/internal/services/auth/handler.go
index f889f2ad0e..bdd4803038 100644
--- a/backend-go/internal/services/auth/handler.go
+++ b/backend-go/internal/services/auth/handler.go
@@ -13,7 +13,7 @@ import (
"golang.org/x/crypto/bcrypt"
"github.com/infisical/api/internal/libs/errutil"
- "github.com/infisical/api/internal/services/permission"
+ "github.com/infisical/api/internal/services/actor"
)
// AuthHandler implements the Goa-generated authorization interface (JWTAuth method).
@@ -146,8 +146,17 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
return nil, errutil.NotFound("User with ID '%s' not found", session.UserId)
}
+ // 5a. Check user lock status.
+ if user.IsLocked.Valid && user.IsLocked.V {
+ return nil, errutil.Unauthorized("Account is locked")
+ }
+ if user.TemporaryLockDateEnd.Valid && time.Now().Before(user.TemporaryLockDateEnd.Time) {
+ return nil, errutil.Unauthorized("Account is locked")
+ }
+
// 6. Organization scoping.
var orgID, rootOrgID, parentOrgID uuid.UUID
+ var orgName string
if claims.OrganizationID != "" {
claimOrgUUID := parseUUID(claims.OrganizationID)
if claims.SubOrganizationID != "" {
@@ -170,7 +179,7 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
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")
+ orgMembership, err := h.dal.FindEffectiveOrgMembership(ctx, actor.TypeUser, user.ID, subOrg.ID, "accepted")
if err != nil {
return nil, errutil.DatabaseErr("Failed to check org membership").WithErr(err)
}
@@ -182,18 +191,19 @@ 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
}
} else {
// 6b. Regular organization scope.
- _, err := h.dal.FindOrgByID(ctx, claimOrgUUID)
+ org, 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")
+ orgMembership, err := h.dal.FindEffectiveOrgMembership(ctx, actor.TypeUser, user.ID, claimOrgUUID, "accepted")
if err != nil {
return nil, errutil.DatabaseErr("Failed to check org membership").WithErr(err)
}
@@ -205,6 +215,7 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
}
orgID = claimOrgUUID
+ orgName = org.Name
rootOrgID = claimOrgUUID
parentOrgID = claimOrgUUID
}
@@ -223,14 +234,17 @@ func (h AuthHandler) validateJWT(ctx context.Context, token string) (*Identity,
}
return &Identity{
- AuthMode: AuthModeJWT,
- Actor: permission.ActorTypeUser,
- ActorID: user.ID,
- OrgID: orgID,
- RootOrgID: rootOrgID,
- ParentOrgID: parentOrgID,
- AuthMethod: permission.ActorAuthMethod(claims.AuthMethod),
- IsSuperAdmin: isSuperAdmin,
+ AuthMode: AuthModeJWT,
+ Actor: actor.TypeUser,
+ ActorID: user.ID,
+ OrgID: orgID,
+ RootOrgID: rootOrgID,
+ ParentOrgID: parentOrgID,
+ OrgName: orgName,
+ AuthMethod: actor.AuthMethod(claims.AuthMethod),
+ IsSuperAdmin: isSuperAdmin,
+ IsMfaVerified: claims.IsMfaVerified,
+ MfaMethod: claims.MfaMethod,
UserAuthInfo: &UserAuthInfo{
UserID: user.ID,
Email: email,
@@ -303,10 +317,10 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
}
// 8. Resolve org hierarchy.
- orgID, rootOrgID, parentOrgID := resolveOrgHierarchy(org)
+ orgID, rootOrgID, parentOrgID, orgName := resolveOrgHierarchy(org)
// 9. Check org membership.
- membership, err := h.dal.FindEffectiveOrgMembership(ctx, permission.ActorTypeIdentity, accessToken.IdentityId, org.ID, "")
+ membership, err := h.dal.FindEffectiveOrgMembership(ctx, actor.TypeIdentity, accessToken.IdentityId, org.ID, "")
if err != nil {
return nil, errutil.InternalServer("Failed to check org membership")
}
@@ -379,12 +393,13 @@ func (h AuthHandler) validateIdentityAccessToken(ctx context.Context, token, ipA
// 13. Build identity.
return &Identity{
AuthMode: AuthModeIdentityAccessToken,
- Actor: permission.ActorTypeIdentity,
+ Actor: actor.TypeIdentity,
ActorID: accessToken.IdentityId,
OrgID: orgID,
RootOrgID: rootOrgID,
ParentOrgID: parentOrgID,
- AuthMethod: permission.ActorAuthMethod(accessToken.AuthMethod),
+ OrgName: orgName,
+ AuthMethod: actor.AuthMethod(accessToken.AuthMethod),
IdentityAuthInfo: identityAuthInfo,
Name: accessToken.IdentityName,
}, nil
@@ -442,22 +457,24 @@ func (h AuthHandler) validateServiceToken(ctx context.Context, token string) (*I
}
// 7. Build identity.
- orgID, rootOrgID, parentOrgID := resolveOrgHierarchy(org)
+ orgID, rootOrgID, parentOrgID, orgName := resolveOrgHierarchy(org)
serviceTokenUUID := parseUUID(serviceToken.ID)
return &Identity{
AuthMode: AuthModeServiceToken,
- Actor: permission.ActorTypeService,
+ Actor: actor.TypeService,
ActorID: serviceTokenUUID,
OrgID: orgID,
RootOrgID: rootOrgID,
ParentOrgID: parentOrgID,
+ OrgName: orgName,
Name: serviceToken.Name,
}, nil
}
-// resolveOrgHierarchy extracts orgID, rootOrgID, and parentOrgID from an OrgRow.
-func resolveOrgHierarchy(org *OrgRow) (orgID, rootOrgID, parentOrgID uuid.UUID) {
+// 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) {
diff --git a/backend-go/internal/services/permission/dal.go b/backend-go/internal/services/permission/dal.go
index 60dd1467d3..75f1024239 100644
--- a/backend-go/internal/services/permission/dal.go
+++ b/backend-go/internal/services/permission/dal.go
@@ -43,43 +43,49 @@ type GetPermissionParams struct {
ActorType ActorType
}
-// PermissionData is the nested result of the permission query.
-type PermissionData struct {
- ID uuid.UUID
- ScopeOrgID uuid.UUID
- OrgAuthEnforced *bool
- OrgGoogleSsoAuthEnforced bool
- BypassOrgAuthEnabled bool
- ShouldUseNewPrivilegeSystem bool
- RootOrgID *uuid.UUID
- Roles []RoleInfo
- AdditionalPrivileges []AdditionalPrivilegeInfo
- Metadata []MetadataInfo
-}
-
// RoleInfo represents a single role assignment from the permission query.
+// Uses go-jet automatic nesting via sql:"primary_key" tag.
type RoleInfo struct {
- ID uuid.UUID
- Role string
- Permissions *string // JSON for custom roles
- CustomRoleSlug *string
- IsTemporary bool
- TemporaryAccessEndTime *time.Time
+ ID uuid.UUID `sql:"primary_key" alias:"membership_roles.id"`
+ Role string `alias:"membership_roles.role"`
+ IsTemporary sql.Null[bool] `alias:"membership_roles.is_temporary"`
+ TemporaryAccessEndTime sql.NullTime `alias:"membership_roles.temporary_access_end_time"`
+ // Custom role fields from LEFT JOIN roles table
+ CustomRoleSlug sql.NullString `alias:"roles.slug"`
+ Permissions sql.NullString `alias:"roles.permissions"`
}
// AdditionalPrivilegeInfo represents an additional privilege from the permission query.
+// Uses go-jet automatic nesting via sql:"primary_key" tag.
type AdditionalPrivilegeInfo struct {
- ID uuid.UUID
- Permissions *string // JSON
- IsTemporary bool
- TemporaryAccessEndTime *time.Time
+ ID uuid.UUID `sql:"primary_key" alias:"additional_privileges.id"`
+ Permissions sql.NullString `alias:"additional_privileges.permissions"`
+ IsTemporary sql.Null[bool] `alias:"additional_privileges.is_temporary"`
+ TemporaryAccessEndTime sql.NullTime `alias:"additional_privileges.temporary_access_end_time"`
}
// MetadataInfo represents identity metadata key-value pair.
+// Uses go-jet automatic nesting via sql:"primary_key" tag.
type MetadataInfo struct {
- ID uuid.UUID
- Key string
- Value string
+ ID uuid.UUID `sql:"primary_key" alias:"identity_metadata.id"`
+ Key string `alias:"identity_metadata.key"`
+ Value string `alias:"identity_metadata.value"`
+}
+
+// PermissionData is the nested result of the permission query.
+// Go-jet automatically nests Roles, AdditionalPrivileges, and Metadata
+// based on sql:"primary_key" tags in child structs.
+type PermissionData struct {
+ ID uuid.UUID `sql:"primary_key" alias:"memberships.id"`
+ ScopeOrgID uuid.UUID `alias:"memberships.scope_org_id"`
+ OrgAuthEnforced sql.Null[bool] `alias:"organizations.auth_enforced"`
+ OrgGoogleSsoAuthEnforced bool `alias:"organizations.google_sso_auth_enforced"`
+ BypassOrgAuthEnabled bool `alias:"organizations.bypass_org_auth_enabled"`
+ ShouldUseNewPrivilegeSystem bool `alias:"organizations.should_use_new_privilege_system"`
+ RootOrgID sql.Null[uuid.UUID] `alias:"organizations.root_org_id"`
+ Roles []RoleInfo `alias:"membership_roles"`
+ AdditionalPrivileges []AdditionalPrivilegeInfo `alias:"additional_privileges"`
+ Metadata []MetadataInfo `alias:"identity_metadata"`
}
// ProjectDetail holds project info needed by the permission service.
@@ -101,43 +107,8 @@ type ServiceTokenDetail struct {
Permissions []string // e.g. ["read", "write"]
}
-// --- Flat row type for the join query ---
-
-type permissionFlatRow struct {
- // Membership fields
- MembershipID uuid.UUID `alias:"memberships.id"`
- ScopeOrgID uuid.UUID `alias:"memberships.scope_org_id"`
-
- // Organization fields
- OrgAuthEnforced sql.Null[bool] `alias:"organizations.auth_enforced"`
- OrgGoogleSsoAuthEnforced bool `alias:"organizations.google_sso_auth_enforced"`
- BypassOrgAuthEnabled bool `alias:"organizations.bypass_org_auth_enabled"`
- ShouldUseNewPrivilegeSystem bool `alias:"organizations.should_use_new_privilege_system"`
- RootOrgID sql.Null[uuid.UUID] `alias:"organizations.root_org_id"`
-
- // MembershipRole fields
- MembershipRoleID sql.Null[uuid.UUID] `alias:"membership_roles.id"`
- MembershipRole sql.Null[string] `alias:"membership_roles.role"`
- MembershipRoleIsTemporary sql.Null[bool] `alias:"membership_roles.is_temporary"`
- MembershipRoleTemporaryEnd sql.NullTime `alias:"membership_roles.temporary_access_end_time"`
-
- // Role (custom role) fields
- RoleSlug sql.Null[string] `alias:"roles.slug"`
- CustomRolePermissions sql.Null[string] `alias:"roles.permissions"`
-
- // AdditionalPrivilege fields
- AdditionalPrivilegeID sql.Null[uuid.UUID] `alias:"additional_privileges.id"`
- AdditionalPrivilegePerms sql.Null[string] `alias:"additional_privileges.permissions"`
- AdditionalPrivilegeIsTemp sql.Null[bool] `alias:"additional_privileges.is_temporary"`
- AdditionalPrivilegeTempEnd sql.NullTime `alias:"additional_privileges.temporary_access_end_time"`
-
- // IdentityMetadata fields
- MetadataID sql.Null[uuid.UUID] `alias:"identity_metadata.id"`
- MetadataKey sql.Null[string] `alias:"identity_metadata.key"`
- MetadataValue sql.Null[string] `alias:"identity_metadata.value"`
-}
-
// GetPermission executes the main permission join query.
+// Uses go-jet automatic nesting to populate Roles, AdditionalPrivileges, and Metadata arrays.
// Port of permission-dal.ts:173-366.
func (d *DAL) GetPermission(ctx context.Context, params *GetPermissionParams) ([]PermissionData, error) {
memberships := table.Memberships
@@ -224,8 +195,10 @@ func (d *DAL) GetPermission(ctx context.Context, params *GetPermissionParams) ([
AND(scopeFilter),
)
- var rows []permissionFlatRow
- err := stmt.QueryContext(ctx, d.db.Replica(), &rows)
+ // Go-jet automatically nests Roles, AdditionalPrivileges, and Metadata arrays
+ // based on sql:"primary_key" tags in the child structs.
+ var result []PermissionData
+ err := stmt.QueryContext(ctx, d.db.Replica(), &result)
if err != nil {
if errors.Is(err, qrm.ErrNoRows) {
return nil, nil
@@ -233,103 +206,7 @@ func (d *DAL) GetPermission(ctx context.Context, params *GetPermissionParams) ([
return nil, err
}
- return nestPermissionRows(rows), nil
-}
-
-// nestPermissionRows transforms flat join rows into nested PermissionData.
-func nestPermissionRows(rows []permissionFlatRow) []PermissionData {
- type entry struct {
- data PermissionData
- roleSeen map[uuid.UUID]bool
- apSeen map[uuid.UUID]bool
- metaSeen map[uuid.UUID]bool
- }
-
- orderKeys := make([]uuid.UUID, 0)
- lookup := make(map[uuid.UUID]*entry)
-
- for i := range rows {
- row := &rows[i]
- existing, ok := lookup[row.MembershipID]
- if !ok {
- var rootOrgID *uuid.UUID
- if row.RootOrgID.Valid {
- rootOrgID = &row.RootOrgID.V
- }
- var orgAuthEnforced *bool
- if row.OrgAuthEnforced.Valid {
- orgAuthEnforced = &row.OrgAuthEnforced.V
- }
- existing = &entry{
- data: PermissionData{
- ID: row.MembershipID,
- ScopeOrgID: row.ScopeOrgID,
- OrgAuthEnforced: orgAuthEnforced,
- OrgGoogleSsoAuthEnforced: row.OrgGoogleSsoAuthEnforced,
- BypassOrgAuthEnabled: row.BypassOrgAuthEnabled,
- ShouldUseNewPrivilegeSystem: row.ShouldUseNewPrivilegeSystem,
- RootOrgID: rootOrgID,
- },
- roleSeen: make(map[uuid.UUID]bool),
- apSeen: make(map[uuid.UUID]bool),
- metaSeen: make(map[uuid.UUID]bool),
- }
- orderKeys = append(orderKeys, row.MembershipID)
- lookup[row.MembershipID] = existing
- }
-
- // Dedup roles by membershipRoleId
- if row.MembershipRoleID.Valid && !existing.roleSeen[row.MembershipRoleID.V] {
- existing.roleSeen[row.MembershipRoleID.V] = true
- roleInfo := RoleInfo{
- ID: row.MembershipRoleID.V,
- Role: row.MembershipRole.V,
- IsTemporary: row.MembershipRoleIsTemporary.Valid && row.MembershipRoleIsTemporary.V,
- }
- if row.RoleSlug.Valid {
- roleInfo.CustomRoleSlug = &row.RoleSlug.V
- }
- if row.CustomRolePermissions.Valid {
- roleInfo.Permissions = &row.CustomRolePermissions.V
- }
- if row.MembershipRoleTemporaryEnd.Valid {
- roleInfo.TemporaryAccessEndTime = &row.MembershipRoleTemporaryEnd.Time
- }
- existing.data.Roles = append(existing.data.Roles, roleInfo)
- }
-
- // Dedup additional privileges
- if row.AdditionalPrivilegeID.Valid && !existing.apSeen[row.AdditionalPrivilegeID.V] {
- existing.apSeen[row.AdditionalPrivilegeID.V] = true
- privilegeInfo := AdditionalPrivilegeInfo{
- ID: row.AdditionalPrivilegeID.V,
- IsTemporary: row.AdditionalPrivilegeIsTemp.Valid && row.AdditionalPrivilegeIsTemp.V,
- }
- if row.AdditionalPrivilegePerms.Valid {
- privilegeInfo.Permissions = &row.AdditionalPrivilegePerms.V
- }
- if row.AdditionalPrivilegeTempEnd.Valid {
- privilegeInfo.TemporaryAccessEndTime = &row.AdditionalPrivilegeTempEnd.Time
- }
- existing.data.AdditionalPrivileges = append(existing.data.AdditionalPrivileges, privilegeInfo)
- }
-
- // Dedup metadata
- if row.MetadataID.Valid && !existing.metaSeen[row.MetadataID.V] {
- existing.metaSeen[row.MetadataID.V] = true
- existing.data.Metadata = append(existing.data.Metadata, MetadataInfo{
- ID: row.MetadataID.V,
- Key: row.MetadataKey.V,
- Value: row.MetadataValue.V,
- })
- }
- }
-
- result := make([]PermissionData, 0, len(orderKeys))
- for _, key := range orderKeys {
- result = append(result, lookup[key].data)
- }
- return result
+ return result, nil
}
// FindProjectByID returns basic project details needed for permission checks.
diff --git a/backend-go/internal/services/permission/permission.go b/backend-go/internal/services/permission/permission.go
index 9c48e5affc..ccb5a223de 100644
--- a/backend-go/internal/services/permission/permission.go
+++ b/backend-go/internal/services/permission/permission.go
@@ -11,21 +11,24 @@ import (
"github.com/infisical/gocasl"
"github.com/infisical/api/internal/libs/errutil"
+ "github.com/infisical/api/internal/services/actor"
"github.com/infisical/api/internal/services/permission/project"
)
// ActorType identifies the kind of entity performing an action.
-type ActorType string
+// Type alias for actor.Type for backward compatibility.
+type ActorType = actor.Type
const (
- ActorTypeUser ActorType = "user"
- ActorTypeIdentity ActorType = "identity"
- ActorTypeService ActorType = "service"
+ ActorTypeUser ActorType = actor.TypeUser
+ ActorTypeIdentity ActorType = actor.TypeIdentity
+ ActorTypeService ActorType = actor.TypeService
)
// ActorAuthMethod represents the authentication method used by the actor (e.g. "jwt", "api-key").
// An empty string means no specific method (e.g. platform-level actions).
-type ActorAuthMethod string
+// Type alias for actor.AuthMethod for backward compatibility.
+type ActorAuthMethod = actor.AuthMethod
// ActionProjectType scopes the permission check to a specific project type.
type ActionProjectType string
@@ -114,20 +117,38 @@ func NewService(logger *slog.Logger, deps Deps) *Service {
}
// GetProjectPermission resolves the effective permissions for an actor within a project.
-// Exact port of permission-service.ts:350-510.
+// Exact port of permission-service.ts:403-573.
func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPermissionArgs) (*GetProjectPermissionResult, error) {
// 1. SERVICE actor → delegate to service token path
if args.Actor == ActorTypeService {
return p.getServiceTokenProjectPermission(ctx, args.ActorID.String(), args.ProjectID, args.ActorOrgID, args.ActionProjectType)
}
- // 2. TODO(go): assumed privilege check
+ // 2. TODO(go): assumed privilege check — allows users to assume another actor's privileges
+ // (identity impersonation). Port of permission-service.ts:427-436.
+ // Implementation requires:
+ // - Request context key for AssumedPrivilegeDetails
+ // - Check if current user is assuming another identity's privileges
+ // - Swap actor/actorId if assumption is valid
// 3. Validate actor type
if args.Actor != ActorTypeUser && args.Actor != ActorTypeIdentity {
return nil, errutil.BadRequest("Invalid actor provided")
}
+ // TODO(go): request-scoped memoization — avoid redundant permission checks within same request.
+ // Port of permission-service.ts:447-455, 568.
+ // Implementation requires:
+ // - Request context with memoizer (similar to Node.js @fastify/request-context)
+ // - Memoization key based on projectId + actor + actorId + actorAuthMethod + actionProjectType + actorOrgId
+
+ // TODO(go): Redis fingerprint cache — two-tier caching with marker TTL (10s) + data TTL (10m).
+ // Port of permission-service.ts:465-483 (withCacheFingerprint).
+ // Implementation requires:
+ // - Redis keystore integration
+ // - Fingerprint-based cache invalidation (permissionDAL.getPermissionFingerprint)
+ // - Cache reviver for date fields
+
// 4. Find project
projectDetails, err := p.dal.FindProjectByID(ctx, args.ProjectID)
if err != nil {
@@ -173,7 +194,12 @@ func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPerm
// 9. Flatten active roles
permissionFromRoles := flattenActiveRolesFromMemberships(permissionData)
- // 10. TODO(go): SSO enforcement (validateOrgSSO + org permission bypass check)
+ // 10. TODO(go): SSO enforcement — validate SSO requirements and bypass permissions.
+ // Port of permission-service.ts:508-516 (validateOrgSSO) and L377-396 (canBypassSso).
+ // Implementation requires:
+ // - validateOrgSSO function checking orgAuthEnforced, googleSsoAuthEnforced, bypassOrgAuthEnabled
+ // - Org-level permission check for SSO bypass capability
+ // - Only applies to ActorTypeUser
// 11. Build rules
rules := buildProjectPermissionRules(permissionFromRoles)
@@ -198,7 +224,7 @@ func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPerm
}
}
- // 14. Build template vars
+ // 14. Build template vars with metadata
metadataMap := make(map[string]string)
if len(permissionData) > 0 {
for _, metadataEntry := range permissionData[0].Metadata {
@@ -206,18 +232,23 @@ func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPerm
}
}
+ // 15. Build identity auth info for template vars (OIDC/Kubernetes/AWS claims)
+ // Port of permission-service.ts:528-532.
+ identityAuthMap := buildIdentityAuthMap(ctx, args.ActorID)
+
vars := map[string]any{
"identity": map[string]any{
"id": args.ActorID.String(),
"username": username,
"metadata": metadataMap,
+ "auth": identityAuthMap,
},
}
- // 15. Interpolate Handlebars templates in rules JSON with actual values
+ // 16. Interpolate Handlebars templates in rules JSON with actual values
rulesStr := InterpolateRulesJSON(string(rulesJSON), vars)
- // 16. Load ability from interpolated JSON
+ // 17. Load ability from interpolated JSON
ability, err := gocasl.LoadFromJSON([]byte(rulesStr), gocasl.LoadOptions{
FieldOps: PermissionFieldOps(),
})
@@ -225,7 +256,7 @@ func (p *Service) GetProjectPermission(ctx context.Context, args *GetProjectPerm
return nil, fmt.Errorf("loading permission rules: %w", err)
}
- // 17. Build memberships for result
+ // 18. Build memberships for result
memberships := buildMembershipsFromPermissionData(permissionData)
return &GetProjectPermissionResult{
@@ -319,23 +350,33 @@ func flattenActiveRolesFromMemberships(memberships []PermissionData) []roleWithP
membership := &memberships[i]
for j := range membership.Roles {
role := &membership.Roles[j]
- if role.IsTemporary && (role.TemporaryAccessEndTime == nil || now.After(*role.TemporaryAccessEndTime)) {
+ isTemporary := role.IsTemporary.Valid && role.IsTemporary.V
+ if isTemporary && (!role.TemporaryAccessEndTime.Valid || now.After(role.TemporaryAccessEndTime.Time)) {
continue
}
+ var permissions *string
+ if role.Permissions.Valid {
+ permissions = &role.Permissions.String
+ }
result = append(result, roleWithPermissions{
Role: role.Role,
- Permissions: role.Permissions,
+ Permissions: permissions,
})
}
for j := range membership.AdditionalPrivileges {
additionalPrivilege := &membership.AdditionalPrivileges[j]
- if additionalPrivilege.IsTemporary && (additionalPrivilege.TemporaryAccessEndTime == nil || now.After(*additionalPrivilege.TemporaryAccessEndTime)) {
+ isTemporary := additionalPrivilege.IsTemporary.Valid && additionalPrivilege.IsTemporary.V
+ if isTemporary && (!additionalPrivilege.TemporaryAccessEndTime.Valid || now.After(additionalPrivilege.TemporaryAccessEndTime.Time)) {
continue
}
+ var permissions *string
+ if additionalPrivilege.Permissions.Valid {
+ permissions = &additionalPrivilege.Permissions.String
+ }
result = append(result, roleWithPermissions{
Role: project.RoleCustom,
- Permissions: additionalPrivilege.Permissions,
+ Permissions: permissions,
})
}
}
@@ -352,8 +393,8 @@ func buildMembershipsFromPermissionData(permissionData []PermissionData) []Membe
for j := range data.Roles {
role := &data.Roles[j]
membershipRole := MembershipRole{Role: role.Role}
- if role.CustomRoleSlug != nil {
- membershipRole.CustomRoleSlug = *role.CustomRoleSlug
+ if role.CustomRoleSlug.Valid {
+ membershipRole.CustomRoleSlug = role.CustomRoleSlug.String
}
membership.Roles = append(membership.Roles, membershipRole)
}
@@ -371,3 +412,44 @@ func checkProjectEnforcement(projectDetails *ProjectDetail) func(string) bool {
return false
}
}
+
+// buildIdentityAuthMap extracts identity auth info (OIDC/Kubernetes/AWS claims) from request context
+// for use in permission template variable interpolation.
+// Port of permission-service.ts:528-532.
+func buildIdentityAuthMap(ctx context.Context, actorID uuid.UUID) map[string]any {
+ authInfo := actor.AuthInfoFromContext(ctx)
+ if authInfo == nil {
+ return map[string]any{}
+ }
+
+ if authInfo.IdentityID != actorID {
+ return map[string]any{}
+ }
+
+ result := make(map[string]any)
+
+ if authInfo.OIDC != nil && len(authInfo.OIDC.Claims) > 0 {
+ result["oidc"] = authInfo.OIDC.Claims
+ }
+
+ if authInfo.Kubernetes != nil {
+ result["kubernetes"] = map[string]string{
+ "namespace": authInfo.Kubernetes.Namespace,
+ "name": authInfo.Kubernetes.Name,
+ }
+ }
+
+ if authInfo.AWS != nil {
+ result["aws"] = map[string]string{
+ "accountId": authInfo.AWS.AccountID,
+ "arn": authInfo.AWS.ARN,
+ "userId": authInfo.AWS.UserID,
+ "partition": authInfo.AWS.Partition,
+ "service": authInfo.AWS.Service,
+ "resourceType": authInfo.AWS.ResourceType,
+ "resourceName": authInfo.AWS.ResourceName,
+ }
+ }
+
+ return result
+}
diff --git a/backend-go/internal/services/permission/permission_test.go b/backend-go/internal/services/permission/permission_test.go
index a1627353b0..c93b6c9e78 100644
--- a/backend-go/internal/services/permission/permission_test.go
+++ b/backend-go/internal/services/permission/permission_test.go
@@ -1,6 +1,7 @@
package permission
import (
+ "database/sql"
"encoding/json"
"testing"
"time"
@@ -559,13 +560,13 @@ func TestTemplateVars_IdentityIdInterpolation(t *testing.T) {
func TestFlattenActiveRolesFromMemberships_ActiveRolesIncluded(t *testing.T) {
t.Parallel()
- perms := new(`[[["read"],["secrets"]]]`)
+ perms := `[[["read"],["secrets"]]]`
data := []PermissionData{
{
ID: uuid.New(),
Roles: []RoleInfo{
- {Role: project.RoleAdmin, IsTemporary: false},
- {Role: project.RoleCustom, IsTemporary: false, Permissions: perms},
+ {Role: project.RoleAdmin, IsTemporary: sql.Null[bool]{V: false, Valid: true}},
+ {Role: project.RoleCustom, IsTemporary: sql.Null[bool]{V: false, Valid: true}, Permissions: sql.NullString{String: perms, Valid: true}},
},
},
}
@@ -584,7 +585,7 @@ func TestFlattenActiveRolesFromMemberships_ExpiredTemporaryRoleExcluded(t *testi
{
ID: uuid.New(),
Roles: []RoleInfo{
- {Role: project.RoleAdmin, IsTemporary: true, TemporaryAccessEndTime: &pastTime},
+ {Role: project.RoleAdmin, IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.NullTime{Time: pastTime, Valid: true}},
},
},
}
@@ -601,7 +602,7 @@ func TestFlattenActiveRolesFromMemberships_ActiveTemporaryRoleIncluded(t *testin
{
ID: uuid.New(),
Roles: []RoleInfo{
- {Role: project.RoleMember, IsTemporary: true, TemporaryAccessEndTime: &futureTime},
+ {Role: project.RoleMember, IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.NullTime{Time: futureTime, Valid: true}},
},
},
}
@@ -618,7 +619,7 @@ func TestFlattenActiveRolesFromMemberships_TemporaryWithNilEndTimeExcluded(t *te
{
ID: uuid.New(),
Roles: []RoleInfo{
- {Role: project.RoleAdmin, IsTemporary: true, TemporaryAccessEndTime: nil},
+ {Role: project.RoleAdmin, IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.NullTime{Valid: false}},
},
},
}
@@ -631,12 +632,12 @@ func TestFlattenActiveRolesFromMemberships_ExpiredAdditionalPrivilegeExcluded(t
t.Parallel()
pastTime := time.Now().Add(-1 * time.Hour)
- perms := new(`[[["read"],["secrets"]]]`)
+ perms := `[[["read"],["secrets"]]]`
data := []PermissionData{
{
ID: uuid.New(),
AdditionalPrivileges: []AdditionalPrivilegeInfo{
- {IsTemporary: true, TemporaryAccessEndTime: &pastTime, Permissions: perms},
+ {IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.NullTime{Time: pastTime, Valid: true}, Permissions: sql.NullString{String: perms, Valid: true}},
},
},
}
@@ -649,12 +650,12 @@ func TestFlattenActiveRolesFromMemberships_ActiveAdditionalPrivilegeIncluded(t *
t.Parallel()
futureTime := time.Now().Add(1 * time.Hour)
- perms := new(`[[["read"],["secrets"]]]`)
+ perms := `[[["read"],["secrets"]]]`
data := []PermissionData{
{
ID: uuid.New(),
AdditionalPrivileges: []AdditionalPrivilegeInfo{
- {IsTemporary: true, TemporaryAccessEndTime: &futureTime, Permissions: perms},
+ {IsTemporary: sql.Null[bool]{V: true, Valid: true}, TemporaryAccessEndTime: sql.NullTime{Time: futureTime, Valid: true}, Permissions: sql.NullString{String: perms, Valid: true}},
},
},
}
@@ -667,12 +668,12 @@ func TestFlattenActiveRolesFromMemberships_ActiveAdditionalPrivilegeIncluded(t *
func TestFlattenActiveRolesFromMemberships_NonTemporaryAdditionalPrivilegeIncluded(t *testing.T) {
t.Parallel()
- perms := new(`[[["read"],["secrets"]]]`)
+ perms := `[[["read"],["secrets"]]]`
data := []PermissionData{
{
ID: uuid.New(),
AdditionalPrivileges: []AdditionalPrivilegeInfo{
- {IsTemporary: false, Permissions: perms},
+ {IsTemporary: sql.Null[bool]{V: false, Valid: true}, Permissions: sql.NullString{String: perms, Valid: true}},
},
},
}