Switch AuthorizationAttributes to batch and add AuthorizeBatch
Change AuthorizationAttributer.AuthorizationAttributes to take a slice
of resource ids and return policy.AttributesByID, so a single SQL
round-trip can load condition attributes for a whole batch. All
coredata implementations are migrated to a single
`WHERE id = ANY(@resource_ids::text[])` query that returns only the
rows it finds.
Authorizer gains:
- AuthorizeBatch — all-or-nothing across a homogeneous (same entity
type, same organization) resource set; rejects mixed entity types,
mixed organizations, and empty batches with structured errors.
- AuthorizeMulti — heterogeneous evaluation that returns one error
per item and writes audit log entries in a single bulk insert.
The single-resource Authorize is rewired to delegate to AuthorizeBatch
so all paths share the same condition evaluation and audit logging.
recordAuditLog is split into buildAuditLogEntry plus a batch insert.
Tests cover the new batch and multi paths, mixed/empty/unsupported
resource cases, audit log batching, and dry-run behaviour.
Signed-off-by: Bryan Frimin <bryan@probo.com>
This commit is contained in:
@@ -16,10 +16,10 @@ package iam
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -30,10 +30,14 @@ import (
|
||||
"go.probo.inc/probo/pkg/iam/policy"
|
||||
)
|
||||
|
||||
// AuthorizationAttributer is implemented by entities that provide attributes
|
||||
// for policy condition evaluation.
|
||||
// AuthorizationAttributer is implemented by entities that can provide
|
||||
// authorization attributes for multiple resources in one query.
|
||||
type AuthorizationAttributer interface {
|
||||
AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error)
|
||||
AuthorizationAttributes(
|
||||
ctx context.Context,
|
||||
conn pg.Querier,
|
||||
resourceIDs []gid.GID,
|
||||
) (policy.AttributesByID, error)
|
||||
}
|
||||
|
||||
// AuthorizeParams contains the parameters for an authorization request.
|
||||
@@ -42,11 +46,40 @@ type AuthorizeParams struct {
|
||||
Resource gid.GID
|
||||
Session *gid.GID
|
||||
Action string
|
||||
ResourceAttributes map[string]string
|
||||
ResourceAttributes policy.Attributes
|
||||
DryRun bool
|
||||
SkipAssumptionCheck bool
|
||||
}
|
||||
|
||||
// AuthorizeBatchParams contains the parameters for a batch authorization request.
|
||||
type AuthorizeBatchParams struct {
|
||||
Principal gid.GID
|
||||
Session *gid.GID
|
||||
Action string
|
||||
Resources []gid.GID
|
||||
ResourceAttributes policy.Attributes
|
||||
DryRun bool
|
||||
SkipAssumptionCheck bool
|
||||
}
|
||||
|
||||
// MultiAuthorizeItem contains one authorization request in a multi-authorization batch.
|
||||
// ResourceAttributes are merged on top of the resource attributes loaded
|
||||
// for the resource before the policy is evaluated.
|
||||
type MultiAuthorizeItem struct {
|
||||
Resource gid.GID
|
||||
Action string
|
||||
ResourceAttributes policy.Attributes
|
||||
DryRun bool
|
||||
SkipAssumptionCheck bool
|
||||
}
|
||||
|
||||
// AuthorizeMultiParams contains the parameters for a multi-authorization request.
|
||||
type AuthorizeMultiParams struct {
|
||||
Principal gid.GID
|
||||
Session *gid.GID
|
||||
Items []MultiAuthorizeItem
|
||||
}
|
||||
|
||||
// Authorizer evaluates authorization requests against registered policies.
|
||||
type Authorizer struct {
|
||||
pg *pg.Client
|
||||
@@ -72,58 +105,303 @@ func (a *Authorizer) RegisterPolicySet(ps *PolicySet) {
|
||||
|
||||
// Authorize checks if the principal is allowed to perform the action on the resource.
|
||||
func (a *Authorizer) Authorize(ctx context.Context, params AuthorizeParams) (*coredata.Scope, error) {
|
||||
return a.AuthorizeBatch(
|
||||
ctx,
|
||||
AuthorizeBatchParams{
|
||||
Principal: params.Principal,
|
||||
Session: params.Session,
|
||||
Action: params.Action,
|
||||
Resources: []gid.GID{params.Resource},
|
||||
ResourceAttributes: params.ResourceAttributes,
|
||||
DryRun: params.DryRun,
|
||||
SkipAssumptionCheck: params.SkipAssumptionCheck,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// AuthorizeBatch checks whether the principal is allowed to perform the action
|
||||
// on all provided resources.
|
||||
func (a *Authorizer) AuthorizeBatch(ctx context.Context, params AuthorizeBatchParams) (*coredata.Scope, error) {
|
||||
if params.Principal.EntityType() != coredata.IdentityEntityType {
|
||||
return nil, NewUnsupportedPrincipalTypeError(params.Principal.EntityType())
|
||||
}
|
||||
|
||||
var scope *coredata.Scope
|
||||
if len(params.Resources) == 0 {
|
||||
return nil, NewEmptyResourceBatchError(params.Action)
|
||||
}
|
||||
|
||||
if err := a.pg.WithTx(ctx, func(ctx context.Context, tx pg.Tx) error {
|
||||
authorizedScope, err := a.authorize(ctx, tx, params)
|
||||
if err != nil {
|
||||
return err
|
||||
expectedEntityType := params.Resources[0].EntityType()
|
||||
items := make([]MultiAuthorizeItem, 0, len(params.Resources))
|
||||
|
||||
for _, resourceID := range params.Resources {
|
||||
if resourceID.EntityType() != expectedEntityType {
|
||||
entityTypes := make([]uint16, 0, len(params.Resources))
|
||||
for _, r := range params.Resources {
|
||||
entityTypes = append(entityTypes, r.EntityType())
|
||||
}
|
||||
|
||||
return nil, NewMixedEntityTypeBatchError(
|
||||
params.Action,
|
||||
uniqueSortedEntityTypes(entityTypes),
|
||||
)
|
||||
}
|
||||
|
||||
scope = authorizedScope
|
||||
return nil
|
||||
}); err != nil {
|
||||
items = append(
|
||||
items,
|
||||
MultiAuthorizeItem{
|
||||
Resource: resourceID,
|
||||
Action: params.Action,
|
||||
DryRun: params.DryRun,
|
||||
SkipAssumptionCheck: params.SkipAssumptionCheck,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
var scope *coredata.Scope
|
||||
|
||||
if err := a.pg.WithTx(
|
||||
ctx,
|
||||
func(ctx context.Context, tx pg.Tx) error {
|
||||
authorizedScope, err := a.authorizeMulti(
|
||||
ctx,
|
||||
tx,
|
||||
AuthorizeMultiParams{
|
||||
Principal: params.Principal,
|
||||
Session: params.Session,
|
||||
Items: items,
|
||||
},
|
||||
params.ResourceAttributes,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
scope = authorizedScope
|
||||
|
||||
return nil
|
||||
},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return scope, nil
|
||||
}
|
||||
|
||||
func (a *Authorizer) authorize(ctx context.Context, tx pg.Tx, params AuthorizeParams) (*coredata.Scope, error) {
|
||||
resourceAttrs, err := a.buildResourceAttributes(ctx, tx, params)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot build resource attributes: %w", err)
|
||||
// AuthorizeMulti evaluates each item independently and returns one decision
|
||||
// per item: a nil entry means allowed, a non-nil entry carries the iam
|
||||
// error explaining the denial (typically *ErrInsufficientPermissions).
|
||||
//
|
||||
// Audit log entries for allowed, non-dry-run items are written in a single
|
||||
// bulk insert. Use AuthorizeBatch instead when callers want all-or-nothing
|
||||
// semantics for a homogeneous batch.
|
||||
func (a *Authorizer) AuthorizeMulti(
|
||||
ctx context.Context,
|
||||
params AuthorizeMultiParams,
|
||||
) (*coredata.Scope, []error, error) {
|
||||
if params.Principal.EntityType() != coredata.IdentityEntityType {
|
||||
return nil, nil, NewUnsupportedPrincipalTypeError(params.Principal.EntityType())
|
||||
}
|
||||
|
||||
resourceOrgID := resourceAttrs["organization_id"]
|
||||
if len(params.Items) == 0 {
|
||||
return nil, nil, NewEmptyResourceBatchError("")
|
||||
}
|
||||
|
||||
var (
|
||||
scope *coredata.Scope
|
||||
decisions []error
|
||||
)
|
||||
|
||||
if err := a.pg.WithTx(
|
||||
ctx,
|
||||
func(ctx context.Context, tx pg.Tx) error {
|
||||
s, itemAttrs, d, err := a.evaluateMultiInTx(ctx, tx, params, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
entries := make(coredata.AuditLogEntries, 0, len(params.Items))
|
||||
for i, item := range params.Items {
|
||||
if d[i] != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
entry := a.buildAuditLogEntry(
|
||||
ctx,
|
||||
AuthorizeParams{
|
||||
Principal: params.Principal,
|
||||
Resource: item.Resource,
|
||||
Session: params.Session,
|
||||
Action: item.Action,
|
||||
DryRun: item.DryRun,
|
||||
},
|
||||
itemAttrs[i],
|
||||
)
|
||||
if entry == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
|
||||
if len(entries) > 0 {
|
||||
if err := entries.BulkInsert(ctx, tx, s); err != nil {
|
||||
a.logger.ErrorCtx(
|
||||
ctx,
|
||||
"cannot bulk insert audit log entries",
|
||||
log.Error(err),
|
||||
log.String("action", params.Items[0].Action),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
scope = s
|
||||
decisions = d
|
||||
|
||||
return nil
|
||||
},
|
||||
); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return scope, decisions, nil
|
||||
}
|
||||
|
||||
func (a *Authorizer) authorizeMulti(
|
||||
ctx context.Context,
|
||||
tx pg.Tx,
|
||||
params AuthorizeMultiParams,
|
||||
extraResourceAttributes policy.Attributes,
|
||||
) (*coredata.Scope, error) {
|
||||
scope, itemAttrs, decisions, err := a.evaluateMultiInTx(
|
||||
ctx,
|
||||
tx,
|
||||
params,
|
||||
extraResourceAttributes,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, decision := range decisions {
|
||||
if decision != nil {
|
||||
return nil, decision
|
||||
}
|
||||
}
|
||||
|
||||
entries := make(coredata.AuditLogEntries, 0, len(params.Items))
|
||||
for i, item := range params.Items {
|
||||
entry := a.buildAuditLogEntry(
|
||||
ctx,
|
||||
AuthorizeParams{
|
||||
Principal: params.Principal,
|
||||
Resource: item.Resource,
|
||||
Session: params.Session,
|
||||
Action: item.Action,
|
||||
DryRun: item.DryRun,
|
||||
},
|
||||
itemAttrs[i],
|
||||
)
|
||||
if entry == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
|
||||
if len(entries) > 0 {
|
||||
if err := entries.BulkInsert(ctx, tx, scope); err != nil {
|
||||
a.logger.ErrorCtx(
|
||||
ctx,
|
||||
"cannot bulk insert audit log entries",
|
||||
log.Error(err),
|
||||
log.String("action", params.Items[0].Action),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return scope, nil
|
||||
}
|
||||
|
||||
// evaluateMultiInTx evaluates every item in params against the loaded
|
||||
// policies and resource attributes. It returns the shared scope, the merged
|
||||
// per-item resource attributes (used for both evaluation and audit log
|
||||
// building), and a parallel slice of per-item decisions (nil = allowed).
|
||||
// Callers decide which decisions to persist to the audit log.
|
||||
func (a *Authorizer) evaluateMultiInTx(
|
||||
ctx context.Context,
|
||||
tx pg.Tx,
|
||||
params AuthorizeMultiParams,
|
||||
extraResourceAttributes policy.Attributes,
|
||||
) (*coredata.Scope, []policy.Attributes, []error, error) {
|
||||
uniqueResourceIDs := make([]gid.GID, 0, len(params.Items))
|
||||
seenResourceIDs := make(map[gid.GID]struct{}, len(params.Items))
|
||||
requiresAssumptionCheck := false
|
||||
|
||||
for _, item := range params.Items {
|
||||
if !item.SkipAssumptionCheck {
|
||||
requiresAssumptionCheck = true
|
||||
}
|
||||
|
||||
if _, ok := seenResourceIDs[item.Resource]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
seenResourceIDs[item.Resource] = struct{}{}
|
||||
uniqueResourceIDs = append(uniqueResourceIDs, item.Resource)
|
||||
}
|
||||
|
||||
resourceAttrsByResourceID, err := a.buildResourceAttributesBatch(
|
||||
ctx,
|
||||
tx,
|
||||
uniqueResourceIDs,
|
||||
extraResourceAttributes,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("cannot build resource attributes batch: %w", err)
|
||||
}
|
||||
|
||||
actionForErrors := params.Items[0].Action
|
||||
|
||||
resourceOrgID := resourceAttrsByResourceID[uniqueResourceIDs[0]]["organization_id"]
|
||||
for _, resourceID := range uniqueResourceIDs[1:] {
|
||||
if resourceAttrsByResourceID[resourceID]["organization_id"] != resourceOrgID {
|
||||
orgIDs := make([]string, 0, len(uniqueResourceIDs))
|
||||
for _, id := range uniqueResourceIDs {
|
||||
orgIDs = append(orgIDs, resourceAttrsByResourceID[id]["organization_id"])
|
||||
}
|
||||
|
||||
return nil, nil, nil, NewMixedOrganizationBatchError(
|
||||
actionForErrors,
|
||||
uniqueSortedStrings(orgIDs),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Find role for resource's organization
|
||||
membership, err := a.loadMembership(ctx, tx, params.Principal, resourceOrgID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot load memberships for principal: %w", err)
|
||||
return nil, nil, nil, fmt.Errorf("cannot load memberships for principal: %w", err)
|
||||
}
|
||||
|
||||
// Check whether the viewer is currently assuming the org of the accessed resource
|
||||
if membership != nil && params.Session != nil && !params.SkipAssumptionCheck {
|
||||
if _, err := a.getActiveChildSessionForMembership(
|
||||
// The assumption check is a property of (principal, membership, session),
|
||||
// so it only runs once even though SkipAssumptionCheck is per-item.
|
||||
// On failure, ErrAssumptionRequired is recorded only against items that
|
||||
// did not opt out.
|
||||
var assumptionErr error
|
||||
if requiresAssumptionCheck {
|
||||
err := a.checkAssumption(
|
||||
ctx,
|
||||
tx,
|
||||
*params.Session,
|
||||
membership.ID,
|
||||
); err != nil {
|
||||
if _, ok := errors.AsType[*ErrSessionNotFound](err); ok {
|
||||
return nil, NewAssumptionRequiredError(params.Principal, membership.ID)
|
||||
params.Principal,
|
||||
params.Session,
|
||||
membership,
|
||||
false,
|
||||
)
|
||||
if err != nil {
|
||||
if _, ok := errors.AsType[*ErrAssumptionRequired](err); !ok {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
|
||||
if _, ok := errors.AsType[*ErrSessionExpired](err); ok {
|
||||
return nil, NewAssumptionRequiredError(params.Principal, membership.ID)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("cannot get active child session for membership: %w", err)
|
||||
assumptionErr = err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,10 +410,9 @@ func (a *Authorizer) authorize(ctx context.Context, tx pg.Tx, params AuthorizePa
|
||||
role = membership.Role.String()
|
||||
}
|
||||
|
||||
// Only set principal.organization_id if they have a role in this org
|
||||
var scopedPrincipalAttrs map[string]string
|
||||
var scopedPrincipalAttrs policy.Attributes
|
||||
if membership != nil && role != "" {
|
||||
scopedPrincipalAttrs = map[string]string{
|
||||
scopedPrincipalAttrs = policy.Attributes{
|
||||
"organization_id": membership.OrganizationID.String(),
|
||||
"role": membership.Role.String(),
|
||||
}
|
||||
@@ -143,7 +420,7 @@ func (a *Authorizer) authorize(ctx context.Context, tx pg.Tx, params AuthorizePa
|
||||
|
||||
principalAttrs, err := a.buildPrincipalAttributes(ctx, tx, params.Principal, scopedPrincipalAttrs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot build principal attributes: %w", err)
|
||||
return nil, nil, nil, fmt.Errorf("cannot build principal attributes: %w", err)
|
||||
}
|
||||
|
||||
if params.Session != nil {
|
||||
@@ -152,32 +429,162 @@ func (a *Authorizer) authorize(ctx context.Context, tx pg.Tx, params AuthorizePa
|
||||
|
||||
policies := a.buildPoliciesForRole(role)
|
||||
|
||||
req := policy.AuthorizationRequest{
|
||||
Principal: params.Principal,
|
||||
Resource: params.Resource,
|
||||
Action: params.Action,
|
||||
ConditionContext: policy.ConditionContext{
|
||||
Principal: principalAttrs,
|
||||
Resource: resourceAttrs,
|
||||
},
|
||||
}
|
||||
decisions := make([]error, len(params.Items))
|
||||
itemAttrs := make([]policy.Attributes, len(params.Items))
|
||||
for i, item := range params.Items {
|
||||
resAttrs := resourceAttrsByResourceID[item.Resource]
|
||||
if len(item.ResourceAttributes) > 0 {
|
||||
merged := maps.Clone(resAttrs)
|
||||
maps.Copy(merged, item.ResourceAttributes)
|
||||
resAttrs = merged
|
||||
}
|
||||
itemAttrs[i] = resAttrs
|
||||
|
||||
if a.evaluator.Evaluate(req, policies).IsAllowed() {
|
||||
scope := coredata.NewScopeFromObjectID(params.Resource)
|
||||
if resourceOrgID != "" {
|
||||
orgID, err := gid.ParseGID(resourceOrgID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot parse organization id from resource attributes: %w", err)
|
||||
}
|
||||
|
||||
scope = coredata.NewScope(orgID.TenantID())
|
||||
if assumptionErr != nil && !item.SkipAssumptionCheck {
|
||||
decisions[i] = assumptionErr
|
||||
continue
|
||||
}
|
||||
|
||||
a.recordAuditLog(ctx, tx, params, resourceAttrs)
|
||||
return scope, nil
|
||||
req := policy.AuthorizationRequest{
|
||||
Principal: params.Principal,
|
||||
Resource: item.Resource,
|
||||
Action: item.Action,
|
||||
ConditionContext: policy.ConditionContext{
|
||||
Principal: principalAttrs,
|
||||
Resource: resAttrs,
|
||||
},
|
||||
}
|
||||
|
||||
if !a.evaluator.Evaluate(req, policies).IsAllowed() {
|
||||
decisions[i] = NewInsufficientPermissionsError(params.Principal, item.Resource, item.Action)
|
||||
}
|
||||
}
|
||||
|
||||
return nil, NewInsufficientPermissionsError(params.Principal, params.Resource, params.Action)
|
||||
scope := coredata.NewScopeFromObjectID(uniqueResourceIDs[0])
|
||||
|
||||
if resourceOrgID != "" {
|
||||
orgID, _ := gid.ParseGID(resourceOrgID)
|
||||
scope = coredata.NewScope(orgID.TenantID())
|
||||
}
|
||||
|
||||
return scope, itemAttrs, decisions, nil
|
||||
}
|
||||
|
||||
func (a *Authorizer) buildResourceAttributesBatch(
|
||||
ctx context.Context,
|
||||
conn pg.Querier,
|
||||
uniqueResourceIDs []gid.GID,
|
||||
extraResourceAttributes policy.Attributes,
|
||||
) (policy.AttributesByID, error) {
|
||||
resourceAttrsByID, err := a.loadResourceAttributesByType(ctx, conn, uniqueResourceIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resourceAttrsByResourceID := make(policy.AttributesByID, len(uniqueResourceIDs))
|
||||
for _, resourceID := range uniqueResourceIDs {
|
||||
resourceAttrs := resourceAttrsByID[resourceID]
|
||||
|
||||
attrs := policy.Attributes{
|
||||
"id": resourceID.String(),
|
||||
}
|
||||
maps.Copy(attrs, resourceAttrs)
|
||||
|
||||
if extraResourceAttributes != nil {
|
||||
maps.Copy(attrs, extraResourceAttributes)
|
||||
}
|
||||
|
||||
resourceAttrsByResourceID[resourceID] = attrs
|
||||
}
|
||||
|
||||
return resourceAttrsByResourceID, nil
|
||||
}
|
||||
|
||||
func (a *Authorizer) loadResourceAttributesByType(
|
||||
ctx context.Context,
|
||||
conn pg.Querier,
|
||||
resourceIDs []gid.GID,
|
||||
) (policy.AttributesByID, error) {
|
||||
resourceIDsByEntityType := make(map[uint16][]gid.GID)
|
||||
orderedEntityTypes := make([]uint16, 0, len(resourceIDs))
|
||||
|
||||
for _, resourceID := range resourceIDs {
|
||||
entityType := resourceID.EntityType()
|
||||
|
||||
if _, ok := resourceIDsByEntityType[entityType]; !ok {
|
||||
orderedEntityTypes = append(orderedEntityTypes, entityType)
|
||||
}
|
||||
|
||||
resourceIDsByEntityType[entityType] = append(resourceIDsByEntityType[entityType], resourceID)
|
||||
}
|
||||
|
||||
resourceAttrsByID := make(policy.AttributesByID, len(resourceIDs))
|
||||
|
||||
for _, entityType := range orderedEntityTypes {
|
||||
groupResourceIDs := resourceIDsByEntityType[entityType]
|
||||
|
||||
entity, ok := coredata.NewEntityFromID(groupResourceIDs[0])
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unsupported resource type: %d", groupResourceIDs[0].EntityType())
|
||||
}
|
||||
|
||||
attributer, ok := entity.(AuthorizationAttributer)
|
||||
if !ok {
|
||||
return nil, NewBatchAuthorizationUnsupportedResourceTypeError(entityType)
|
||||
}
|
||||
|
||||
groupAttrsByID, err := attributer.AuthorizationAttributes(ctx, conn, groupResourceIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"cannot load batched resource attributes for entity type %d: %w",
|
||||
entityType,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
for _, resourceID := range groupResourceIDs {
|
||||
resourceAttrs, ok := groupAttrsByID[resourceID]
|
||||
if !ok {
|
||||
return nil, coredata.ErrResourceNotFound
|
||||
}
|
||||
|
||||
resourceAttrsByID[resourceID] = resourceAttrs
|
||||
}
|
||||
}
|
||||
|
||||
return resourceAttrsByID, nil
|
||||
}
|
||||
|
||||
func (a *Authorizer) checkAssumption(
|
||||
ctx context.Context,
|
||||
tx pg.Tx,
|
||||
principalID gid.GID,
|
||||
sessionID *gid.GID,
|
||||
membership *coredata.Membership,
|
||||
skipAssumptionCheck bool,
|
||||
) error {
|
||||
if membership == nil || sessionID == nil || skipAssumptionCheck {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := a.getActiveChildSessionForMembership(
|
||||
ctx,
|
||||
tx,
|
||||
*sessionID,
|
||||
membership.ID,
|
||||
); err != nil {
|
||||
if _, ok := errors.AsType[*ErrSessionNotFound](err); ok {
|
||||
return NewAssumptionRequiredError(principalID, membership.ID)
|
||||
}
|
||||
|
||||
if _, ok := errors.AsType[*ErrSessionExpired](err); ok {
|
||||
return NewAssumptionRequiredError(principalID, membership.ID)
|
||||
}
|
||||
|
||||
return fmt.Errorf("cannot get active child session for membership: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Authorizer) loadMembership(
|
||||
@@ -234,55 +641,30 @@ func (a *Authorizer) buildPrincipalAttributes(
|
||||
ctx context.Context,
|
||||
conn pg.Querier,
|
||||
principalID gid.GID,
|
||||
defaultAttrs map[string]string,
|
||||
) (map[string]string, error) {
|
||||
attrs := map[string]string{
|
||||
defaultAttrs policy.Attributes,
|
||||
) (policy.Attributes, error) {
|
||||
attrs := policy.Attributes{
|
||||
"id": principalID.String(),
|
||||
}
|
||||
maps.Copy(attrs, defaultAttrs)
|
||||
|
||||
if entity, ok := coredata.NewEntityFromID(principalID); ok {
|
||||
if attributer, ok := entity.(AuthorizationAttributer); ok {
|
||||
entityAttrs, err := attributer.AuthorizationAttributes(ctx, conn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot load principal attributes: %w", err)
|
||||
}
|
||||
|
||||
maps.Copy(attrs, entityAttrs)
|
||||
attributer, ok := entity.(AuthorizationAttributer)
|
||||
if !ok {
|
||||
return nil, NewBatchAuthorizationUnsupportedResourceTypeError(principalID.EntityType())
|
||||
}
|
||||
}
|
||||
|
||||
return attrs, nil
|
||||
}
|
||||
entityAttrsByID, err := attributer.AuthorizationAttributes(ctx, conn, []gid.GID{principalID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot load principal attributes: %w", err)
|
||||
}
|
||||
|
||||
func (a *Authorizer) buildResourceAttributes(
|
||||
ctx context.Context,
|
||||
conn pg.Querier,
|
||||
params AuthorizeParams,
|
||||
) (map[string]string, error) {
|
||||
attrs := map[string]string{
|
||||
"id": params.Resource.String(),
|
||||
}
|
||||
entityAttrs, ok := entityAttrsByID[principalID]
|
||||
if !ok {
|
||||
return nil, coredata.ErrResourceNotFound
|
||||
}
|
||||
|
||||
entity, ok := coredata.NewEntityFromID(params.Resource)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unsupported resource type: %d", params.Resource.EntityType())
|
||||
}
|
||||
|
||||
attributer, ok := entity.(AuthorizationAttributer)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("resource %d does not implement AuthorizationAttributer", params.Resource.EntityType())
|
||||
}
|
||||
|
||||
entityAttrs, err := attributer.AuthorizationAttributes(ctx, conn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot load resource attributes: %w", err)
|
||||
}
|
||||
|
||||
maps.Copy(attrs, entityAttrs)
|
||||
|
||||
if params.ResourceAttributes != nil {
|
||||
maps.Copy(attrs, params.ResourceAttributes)
|
||||
maps.Copy(attrs, entityAttrs)
|
||||
}
|
||||
|
||||
return attrs, nil
|
||||
@@ -298,9 +680,44 @@ func (a *Authorizer) buildPoliciesForRole(role string) []*policy.Policy {
|
||||
return policies
|
||||
}
|
||||
|
||||
// resourceTypeFromAction extracts the resource type name from an action
|
||||
// string. For example, "core:thirdParty:create" returns "ThirdParty" and
|
||||
// "core:webhook-subscription:delete" returns "WebhookSubscription".
|
||||
func uniqueSortedStrings(values []string) []string {
|
||||
set := make(map[string]struct{}, len(values))
|
||||
unique := make([]string, 0, len(values))
|
||||
|
||||
for _, value := range values {
|
||||
if _, ok := set[value]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
set[value] = struct{}{}
|
||||
unique = append(unique, value)
|
||||
}
|
||||
|
||||
slices.Sort(unique)
|
||||
|
||||
return unique
|
||||
}
|
||||
|
||||
func uniqueSortedEntityTypes(values []uint16) []uint16 {
|
||||
set := make(map[uint16]struct{}, len(values))
|
||||
unique := make([]uint16, 0, len(values))
|
||||
|
||||
for _, value := range values {
|
||||
if _, ok := set[value]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
set[value] = struct{}{}
|
||||
unique = append(unique, value)
|
||||
}
|
||||
|
||||
slices.Sort(unique)
|
||||
|
||||
return unique
|
||||
}
|
||||
|
||||
// resourceTypeFromAction extracts the PascalCase resource type from an
|
||||
// action string, e.g. "core:webhook-subscription:delete" -> "WebhookSubscription".
|
||||
func resourceTypeFromAction(action string) string {
|
||||
parts := strings.Split(action, ":")
|
||||
if len(parts) < 3 {
|
||||
@@ -317,19 +734,20 @@ func resourceTypeFromAction(action string) string {
|
||||
return strings.Join(segments, "")
|
||||
}
|
||||
|
||||
func (a *Authorizer) recordAuditLog(
|
||||
// buildAuditLogEntry returns nil when no entry should be recorded
|
||||
// (dry run or missing/invalid organization id).
|
||||
func (a *Authorizer) buildAuditLogEntry(
|
||||
ctx context.Context,
|
||||
tx pg.Tx,
|
||||
params AuthorizeParams,
|
||||
resourceAttrs map[string]string,
|
||||
) {
|
||||
resourceAttrs policy.Attributes,
|
||||
) *coredata.AuditLogEntry {
|
||||
if params.DryRun {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
orgIDStr := resourceAttrs["organization_id"]
|
||||
if orgIDStr == "" {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
orgID, err := gid.ParseGID(orgIDStr)
|
||||
@@ -340,7 +758,7 @@ func (a *Authorizer) recordAuditLog(
|
||||
log.Error(err),
|
||||
)
|
||||
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
var actorType coredata.AuditLogActorType
|
||||
@@ -352,18 +770,9 @@ func (a *Authorizer) recordAuditLog(
|
||||
|
||||
resourceType := resourceTypeFromAction(params.Action)
|
||||
|
||||
metadata, err := json.Marshal(map[string]any{})
|
||||
if err != nil {
|
||||
a.logger.ErrorCtx(
|
||||
ctx,
|
||||
"cannot marshal audit log metadata",
|
||||
log.Error(err),
|
||||
)
|
||||
metadata := []byte("{}")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
entry := &coredata.AuditLogEntry{
|
||||
return &coredata.AuditLogEntry{
|
||||
ID: gid.New(orgID.TenantID(), coredata.AuditLogEntryEntityType),
|
||||
OrganizationID: orgID,
|
||||
ActorID: params.Principal,
|
||||
@@ -374,16 +783,4 @@ func (a *Authorizer) recordAuditLog(
|
||||
Metadata: metadata,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
scope := coredata.NewScope(orgID.TenantID())
|
||||
|
||||
if err := entry.Insert(ctx, tx, scope); err != nil {
|
||||
a.logger.ErrorCtx(
|
||||
ctx,
|
||||
"cannot insert audit log entry",
|
||||
log.Error(err),
|
||||
log.String("action", params.Action),
|
||||
log.String("resource_id", params.Resource.String()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
1104
pkg/iam/authorizer_batch_test.go
Normal file
1104
pkg/iam/authorizer_batch_test.go
Normal file
File diff suppressed because it is too large
Load Diff
489
pkg/iam/authorizer_unit_test.go
Normal file
489
pkg/iam/authorizer_unit_test.go
Normal file
@@ -0,0 +1,489 @@
|
||||
// Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package iam
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.gearno.de/kit/log"
|
||||
"go.gearno.de/kit/pg"
|
||||
"go.probo.inc/probo/pkg/coredata"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
"go.probo.inc/probo/pkg/iam/policy"
|
||||
)
|
||||
|
||||
func TestAuthorizer_ValidateInputs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("authorize rejects unsupported principal type", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a := &Authorizer{}
|
||||
_, err := a.Authorize(
|
||||
context.Background(),
|
||||
AuthorizeParams{
|
||||
Principal: gid.New(gid.NewTenantID(), coredata.OrganizationEntityType),
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
|
||||
errUnsupported, ok := errors.AsType[*ErrUnsupportedPrincipalType](err)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, coredata.OrganizationEntityType, errUnsupported.EntityType)
|
||||
})
|
||||
|
||||
t.Run("authorize batch rejects unsupported principal type", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a := &Authorizer{}
|
||||
_, err := a.AuthorizeBatch(
|
||||
context.Background(),
|
||||
AuthorizeBatchParams{
|
||||
Principal: gid.New(gid.NewTenantID(), coredata.OrganizationEntityType),
|
||||
Resources: []gid.GID{gid.New(gid.NewTenantID(), coredata.FrameworkEntityType)},
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
|
||||
errUnsupported, ok := errors.AsType[*ErrUnsupportedPrincipalType](err)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, coredata.OrganizationEntityType, errUnsupported.EntityType)
|
||||
})
|
||||
|
||||
t.Run("authorize batch rejects empty resources", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a := &Authorizer{}
|
||||
_, err := a.AuthorizeBatch(
|
||||
context.Background(),
|
||||
AuthorizeBatchParams{
|
||||
Principal: gid.New(gid.NilTenant, coredata.IdentityEntityType),
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
_, ok := errors.AsType[*ErrEmptyResourceBatch](err)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestAuthorizer_InternalErrorPaths(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
identityID := gid.New(gid.NilTenant, coredata.IdentityEntityType)
|
||||
unknownResourceID := gid.New(gid.NewTenantID(), 65535)
|
||||
unsupportedResourceID := gid.New(gid.NewTenantID(), coredata.OAuth2AccessTokenEntityType)
|
||||
|
||||
a := &Authorizer{
|
||||
evaluator: policy.NewEvaluator(),
|
||||
policySet: NewPolicySet(),
|
||||
}
|
||||
|
||||
t.Run("authorize batch returns wrapped resource attributes batch error", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := a.authorizeMulti(
|
||||
ctx,
|
||||
nil,
|
||||
AuthorizeMultiParams{
|
||||
Principal: identityID,
|
||||
Items: []MultiAuthorizeItem{
|
||||
{
|
||||
Resource: unknownResourceID,
|
||||
Action: "core:test:list",
|
||||
},
|
||||
},
|
||||
},
|
||||
nil,
|
||||
)
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "cannot build resource attributes batch")
|
||||
})
|
||||
|
||||
t.Run("authorize batch rejects mixed entity types", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
firstResourceID := gid.New(gid.NewTenantID(), coredata.FrameworkEntityType)
|
||||
secondResourceID := gid.New(gid.NewTenantID(), coredata.OrganizationEntityType)
|
||||
|
||||
_, err := a.AuthorizeBatch(
|
||||
ctx,
|
||||
AuthorizeBatchParams{
|
||||
Principal: identityID,
|
||||
Action: "core:test:list",
|
||||
Resources: []gid.GID{firstResourceID, secondResourceID},
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
|
||||
errMixedEntityType, ok := errors.AsType[*ErrMixedEntityTypeBatch](err)
|
||||
require.True(t, ok)
|
||||
assert.Equal(
|
||||
t,
|
||||
[]uint16{coredata.OrganizationEntityType, coredata.FrameworkEntityType},
|
||||
errMixedEntityType.EntityTypes,
|
||||
)
|
||||
})
|
||||
|
||||
t.Run("build principal attributes rejects unsupported batch interface type", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := a.buildPrincipalAttributes(
|
||||
ctx,
|
||||
nil,
|
||||
unsupportedResourceID,
|
||||
map[string]string{"role": "OWNER"},
|
||||
)
|
||||
require.Error(t, err)
|
||||
errUnsupported, ok := errors.AsType[*ErrBatchAuthorizationUnsupportedResourceType](err)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, coredata.OAuth2AccessTokenEntityType, errUnsupported.EntityType)
|
||||
})
|
||||
|
||||
t.Run("build principal attributes keeps defaults when entity type is unknown", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
attrs, err := a.buildPrincipalAttributes(
|
||||
ctx,
|
||||
nil,
|
||||
unknownResourceID,
|
||||
map[string]string{"role": "OWNER"},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, unknownResourceID.String(), attrs["id"])
|
||||
assert.Equal(t, "OWNER", attrs["role"])
|
||||
})
|
||||
}
|
||||
|
||||
func TestAuthorizer_HelperMethods(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("check assumption short-circuits", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a := &Authorizer{}
|
||||
identityID := gid.New(gid.NilTenant, coredata.IdentityEntityType)
|
||||
sessionID := gid.New(gid.NilTenant, coredata.SessionEntityType)
|
||||
membership := &coredata.Membership{ID: gid.New(gid.NewTenantID(), coredata.MembershipEntityType)}
|
||||
|
||||
require.NoError(t, a.checkAssumption(context.Background(), nil, identityID, nil, membership, false))
|
||||
require.NoError(t, a.checkAssumption(context.Background(), nil, identityID, &sessionID, nil, false))
|
||||
require.NoError(t, a.checkAssumption(context.Background(), nil, identityID, &sessionID, membership, true))
|
||||
})
|
||||
|
||||
t.Run("build policies for role includes identity scoped policies", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a := &Authorizer{
|
||||
policySet: NewPolicySet().
|
||||
AddIdentityScopedPolicy(policy.NewPolicy("identity", "Identity", policy.Allow("identity:read"))).
|
||||
AddRolePolicy("OWNER", policy.NewPolicy("owner", "Owner", policy.Allow("core:*"))),
|
||||
}
|
||||
|
||||
withRole := a.buildPoliciesForRole("OWNER")
|
||||
require.Len(t, withRole, 2)
|
||||
|
||||
withoutRole := a.buildPoliciesForRole("VIEWER")
|
||||
require.Len(t, withoutRole, 1)
|
||||
})
|
||||
|
||||
t.Run("unique sorted strings deduplicates and sorts", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
got := uniqueSortedStrings([]string{"b", "a", "b", "", "c", "a"})
|
||||
assert.Equal(t, []string{"", "a", "b", "c"}, got)
|
||||
})
|
||||
|
||||
t.Run("unique sorted entity types deduplicates and sorts", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
got := uniqueSortedEntityTypes(
|
||||
[]uint16{
|
||||
coredata.FrameworkEntityType,
|
||||
coredata.OrganizationEntityType,
|
||||
coredata.FrameworkEntityType,
|
||||
coredata.OrganizationEntityType,
|
||||
},
|
||||
)
|
||||
assert.Equal(
|
||||
t,
|
||||
[]uint16{coredata.OrganizationEntityType, coredata.FrameworkEntityType},
|
||||
got,
|
||||
)
|
||||
})
|
||||
|
||||
t.Run("resource type from action parses segments", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
assert.Equal(t, "ThirdParty", resourceTypeFromAction("core:third-party:get"))
|
||||
assert.Equal(t, "WebhookSubscription", resourceTypeFromAction("core:webhook-subscription:delete"))
|
||||
assert.Equal(t, "Unknown", resourceTypeFromAction("invalid-action"))
|
||||
})
|
||||
}
|
||||
|
||||
func TestAuthorizer_LoadMembership(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a := &Authorizer{}
|
||||
|
||||
t.Run("empty organization id returns nil membership", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
membership, err := a.loadMembership(
|
||||
context.Background(),
|
||||
nil,
|
||||
gid.New(gid.NilTenant, coredata.IdentityEntityType),
|
||||
"",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, membership)
|
||||
})
|
||||
|
||||
t.Run("invalid organization id returns parse error", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := a.loadMembership(
|
||||
context.Background(),
|
||||
nil,
|
||||
gid.New(gid.NilTenant, coredata.IdentityEntityType),
|
||||
"not-a-gid",
|
||||
)
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "cannot parse gid")
|
||||
})
|
||||
}
|
||||
|
||||
func TestAuthorizer_BuildAuditLogEntry(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tenantID := gid.NewTenantID()
|
||||
orgID := gid.New(tenantID, coredata.OrganizationEntityType)
|
||||
principalID := gid.New(gid.NilTenant, coredata.IdentityEntityType)
|
||||
resourceID := gid.New(tenantID, coredata.FrameworkEntityType)
|
||||
sessionID := gid.New(gid.NilTenant, coredata.SessionEntityType)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
params AuthorizeParams
|
||||
resourceAttrs policy.Attributes
|
||||
wantNil bool
|
||||
wantActorType coredata.AuditLogActorType
|
||||
}{
|
||||
{
|
||||
name: "dry run returns nil",
|
||||
params: AuthorizeParams{
|
||||
Principal: principalID,
|
||||
Resource: resourceID,
|
||||
Action: "core:framework:get",
|
||||
DryRun: true,
|
||||
},
|
||||
resourceAttrs: policy.Attributes{
|
||||
"organization_id": orgID.String(),
|
||||
},
|
||||
wantNil: true,
|
||||
},
|
||||
{
|
||||
name: "missing organization id returns nil",
|
||||
params: AuthorizeParams{
|
||||
Principal: principalID,
|
||||
Resource: resourceID,
|
||||
Action: "core:framework:get",
|
||||
},
|
||||
resourceAttrs: policy.Attributes{
|
||||
"id": resourceID.String(),
|
||||
},
|
||||
wantNil: true,
|
||||
},
|
||||
{
|
||||
name: "unparseable organization id returns nil",
|
||||
params: AuthorizeParams{
|
||||
Principal: principalID,
|
||||
Resource: resourceID,
|
||||
Action: "core:framework:get",
|
||||
},
|
||||
resourceAttrs: policy.Attributes{
|
||||
"organization_id": "invalid-gid",
|
||||
},
|
||||
wantNil: true,
|
||||
},
|
||||
{
|
||||
name: "session present sets user actor type",
|
||||
params: AuthorizeParams{
|
||||
Principal: principalID,
|
||||
Resource: resourceID,
|
||||
Action: "core:framework:get",
|
||||
Session: &sessionID,
|
||||
},
|
||||
resourceAttrs: policy.Attributes{
|
||||
"organization_id": orgID.String(),
|
||||
},
|
||||
wantActorType: coredata.AuditLogActorTypeUser,
|
||||
},
|
||||
{
|
||||
name: "nil session sets api key actor type",
|
||||
params: AuthorizeParams{
|
||||
Principal: principalID,
|
||||
Resource: resourceID,
|
||||
Action: "core:framework:get",
|
||||
},
|
||||
resourceAttrs: policy.Attributes{
|
||||
"organization_id": orgID.String(),
|
||||
},
|
||||
wantActorType: coredata.AuditLogActorTypeAPIKey,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a := &Authorizer{
|
||||
logger: log.NewLogger(log.WithOutput(io.Discard)),
|
||||
}
|
||||
|
||||
entry := a.buildAuditLogEntry(context.Background(), tt.params, tt.resourceAttrs)
|
||||
if tt.wantNil {
|
||||
assert.Nil(t, entry)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
require.NotNil(t, entry)
|
||||
assert.Equal(t, tt.wantActorType, entry.ActorType)
|
||||
assert.Equal(t, tt.params.Principal, entry.ActorID)
|
||||
assert.Equal(t, tt.params.Resource, entry.ResourceID)
|
||||
assert.Equal(t, tt.params.Action, entry.Action)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizer_WrappedInternalErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a := &Authorizer{
|
||||
logger: log.NewLogger(log.WithOutput(io.Discard)),
|
||||
}
|
||||
|
||||
queryErr := errors.New("query failed")
|
||||
tx := &errorTx{queryErr: queryErr}
|
||||
principalID := gid.New(gid.NilTenant, coredata.IdentityEntityType)
|
||||
membershipID := gid.New(gid.NewTenantID(), coredata.MembershipEntityType)
|
||||
sessionID := gid.New(gid.NilTenant, coredata.SessionEntityType)
|
||||
resourceOrgID := gid.New(gid.NewTenantID(), coredata.OrganizationEntityType).String()
|
||||
|
||||
t.Run("load membership wraps load errors", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := a.loadMembership(context.Background(), tx, principalID, resourceOrgID)
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "cannot load active membership")
|
||||
})
|
||||
|
||||
t.Run("get active child session wraps load errors", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := a.getActiveChildSessionForMembership(
|
||||
context.Background(),
|
||||
tx,
|
||||
sessionID,
|
||||
membershipID,
|
||||
)
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "cannot load child session")
|
||||
})
|
||||
|
||||
t.Run("check assumption wraps non-assumption errors", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := a.checkAssumption(
|
||||
context.Background(),
|
||||
tx,
|
||||
principalID,
|
||||
&sessionID,
|
||||
&coredata.Membership{ID: membershipID},
|
||||
false,
|
||||
)
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "cannot get active child session for membership")
|
||||
|
||||
_, ok := errors.AsType[*ErrAssumptionRequired](err)
|
||||
assert.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("build principal attributes wraps load errors", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := a.buildPrincipalAttributes(context.Background(), tx, principalID, nil)
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "cannot load principal attributes")
|
||||
})
|
||||
|
||||
t.Run("load resource attributes by type wraps load errors", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resourceID := gid.New(gid.NewTenantID(), coredata.FrameworkEntityType)
|
||||
|
||||
_, err := a.loadResourceAttributesByType(context.Background(), tx, []gid.GID{resourceID})
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "cannot load batched resource attributes")
|
||||
})
|
||||
}
|
||||
|
||||
type errorRow struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *errorRow) Scan(...any) error {
|
||||
return r.err
|
||||
}
|
||||
|
||||
type errorTx struct {
|
||||
queryErr error
|
||||
}
|
||||
|
||||
var _ pg.Tx = (*errorTx)(nil)
|
||||
|
||||
func (tx *errorTx) Exec(context.Context, string, ...any) (pgconn.CommandTag, error) {
|
||||
return pgconn.CommandTag{}, tx.queryErr
|
||||
}
|
||||
|
||||
func (tx *errorTx) Query(context.Context, string, ...any) (pgx.Rows, error) {
|
||||
return nil, tx.queryErr
|
||||
}
|
||||
|
||||
func (tx *errorTx) QueryRow(context.Context, string, ...any) pgx.Row {
|
||||
return &errorRow{err: tx.queryErr}
|
||||
}
|
||||
|
||||
func (tx *errorTx) CopyFrom(context.Context, pgx.Identifier, []string, pgx.CopyFromSource) (int64, error) {
|
||||
return 0, tx.queryErr
|
||||
}
|
||||
|
||||
func (tx *errorTx) SendBatch(context.Context, *pgx.Batch) pgx.BatchResults {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *errorTx) Savepoint(context.Context, pg.ExecFunc[pg.Tx]) error {
|
||||
return tx.queryErr
|
||||
}
|
||||
Reference in New Issue
Block a user