authz

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package authz provides a pluggable authorization interface for CoreForge applications.

The package defines a core Authorizer interface that applications use for access control, with multiple backend implementations available:

  • simple: Role hierarchy and permission mappings (no external dependencies)
  • casbin: Casbin-based RBAC/ABAC (flexible policy engine)
  • cedar: Cedar-based policy language (advanced, analyzable policies)

Applications depend only on the Authorizer interface, allowing backends to be swapped without changing application code.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMissingResourceID = &middlewareError{msg: "missing resource ID"}
	ErrInvalidResourceID = &middlewareError{msg: "invalid resource ID"}
)

Error types for resource extraction.

View Source
var DefaultRoleHierarchy = RoleHierarchy{
	"owner":  100,
	"admin":  80,
	"editor": 60,
	"member": 40,
	"viewer": 20,
	"guest":  10,
}

DefaultRoleHierarchy provides a common role hierarchy for multi-tenant SaaS apps.

View Source
var DefaultRolePermissions = RolePermissions{
	"owner": {
		"org.delete", "org.manage", "org.settings",
		"member.invite", "member.remove", "member.role.change", "member.list",
		"resource.create", "resource.read", "resource.update", "resource.delete",
	},
	"admin": {
		"org.settings",
		"member.invite", "member.remove", "member.role.change", "member.list",
		"resource.create", "resource.read", "resource.update", "resource.delete",
	},
	"editor": {
		"member.list",
		"resource.create", "resource.read", "resource.update", "resource.delete",
	},
	"member": {
		"member.list",
		"resource.create", "resource.read", "resource.update",
	},
	"viewer": {
		"resource.read",
	},
}

DefaultRolePermissions provides a common permission mapping.

Functions

This section is empty.

Types

type Action

type Action string

Action represents an operation being performed.

const (
	ActionCreate Action = "create"
	ActionRead   Action = "read"
	ActionUpdate Action = "update"
	ActionDelete Action = "delete"
	ActionList   Action = "list"
	ActionManage Action = "manage" // Full CRUD + admin operations
)

Common action constants.

type Authorizer

type Authorizer interface {
	// Can checks if a principal can perform an action on a resource.
	// This is the primary authorization method.
	Can(ctx context.Context, principal Principal, action Action, resource Resource) (bool, error)

	// CanAll checks if a principal can perform all specified actions on a resource.
	CanAll(ctx context.Context, principal Principal, actions []Action, resource Resource) (bool, error)

	// CanAny checks if a principal can perform any of the specified actions on a resource.
	CanAny(ctx context.Context, principal Principal, actions []Action, resource Resource) (bool, error)

	// Filter returns only the resources the principal can access with the given action.
	Filter(ctx context.Context, principal Principal, action Action, resources []Resource) ([]Resource, error)
}

Authorizer defines the core authorization interface. All authorization backends must implement this interface.

type Decision

type Decision struct {
	// Allowed indicates whether the action is permitted.
	Allowed bool

	// Reason provides context for the decision (useful for debugging/auditing).
	Reason string

	// PolicyID identifies which policy made the decision (if applicable).
	PolicyID string
}

Decision represents an authorization decision with optional explanation.

type DecisionAuthorizer

type DecisionAuthorizer interface {
	Authorizer

	// Decide returns a detailed authorization decision.
	Decide(ctx context.Context, principal Principal, action Action, resource Resource) (Decision, error)
}

DecisionAuthorizer provides detailed authorization decisions.

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message,omitempty"`
}

ErrorResponse represents an error response body.

type FeatureAuthorizer

type FeatureAuthorizer interface {
	Authorizer

	// CanWithFeature checks both permission and feature flag.
	CanWithFeature(ctx context.Context, principal Principal, action Action, resource Resource, feature string) (bool, error)
}

FeatureAuthorizer extends authorization with feature flag awareness.

type Middleware

type Middleware struct {
	// contains filtered or unexported fields
}

Middleware wraps an Authorizer for HTTP middleware use.

func NewMiddleware

func NewMiddleware(authorizer Authorizer) *Middleware

NewMiddleware creates a new authorization middleware.

func (*Middleware) RequireAction

func (m *Middleware) RequireAction(resourceType ResourceType, action Action) func(http.Handler) http.Handler

RequireAction returns middleware that checks if the user can perform an action on a resource type.

func (*Middleware) RequireAllActions

func (m *Middleware) RequireAllActions(resourceType ResourceType, actions ...Action) func(http.Handler) http.Handler

RequireAllActions returns middleware that checks if the user can perform all of the specified actions on a resource type.

func (*Middleware) RequireAnyAction

func (m *Middleware) RequireAnyAction(resourceType ResourceType, actions ...Action) func(http.Handler) http.Handler

RequireAnyAction returns middleware that checks if the user can perform any of the specified actions on a resource type.

func (*Middleware) RequireResourceAction

func (m *Middleware) RequireResourceAction(extractor ResourceExtractor, action Action) func(http.Handler) http.Handler

RequireResourceAction returns middleware that extracts a resource from the request and checks if the user can perform an action on it.

type OrgAuthorizer

type OrgAuthorizer interface {
	Authorizer

	// CanForOrg checks permission scoped to a specific organization.
	CanForOrg(ctx context.Context, principal Principal, orgID uuid.UUID, action Action, resource Resource) (bool, error)

	// GetRole returns the principal's role in an organization.
	GetRole(ctx context.Context, principal Principal, orgID uuid.UUID) (string, error)

	// IsMember checks if a principal is a member of an organization.
	IsMember(ctx context.Context, principal Principal, orgID uuid.UUID) (bool, error)
}

OrgAuthorizer extends Authorizer with organization-scoped methods. Use this for multi-tenant SaaS applications.

type OrgMiddleware

type OrgMiddleware struct {
	// contains filtered or unexported fields
}

OrgMiddleware wraps an OrgAuthorizer for organization-scoped middleware.

func NewOrgMiddleware

func NewOrgMiddleware(authorizer OrgAuthorizer) *OrgMiddleware

NewOrgMiddleware creates a new organization-scoped authorization middleware.

func (*OrgMiddleware) RequireMembership

func (m *OrgMiddleware) RequireMembership() func(http.Handler) http.Handler

RequireMembership returns middleware that requires the user to be a member of the current organization.

func (*OrgMiddleware) RequireRole

func (m *OrgMiddleware) RequireRole(role string, hierarchy RoleHierarchy) func(http.Handler) http.Handler

RequireRole returns middleware that requires a specific role in the current organization.

type PlatformAuthorizer

type PlatformAuthorizer interface {
	OrgAuthorizer

	// IsPlatformAdmin checks if a principal has platform-wide admin access.
	IsPlatformAdmin(ctx context.Context, principal Principal) (bool, error)
}

PlatformAuthorizer extends OrgAuthorizer with platform-level checks.

type PlatformMiddleware

type PlatformMiddleware struct {
	// contains filtered or unexported fields
}

PlatformMiddleware wraps a PlatformAuthorizer for platform-level middleware.

func NewPlatformMiddleware

func NewPlatformMiddleware(authorizer PlatformAuthorizer) *PlatformMiddleware

NewPlatformMiddleware creates a new platform-level authorization middleware.

func (*PlatformMiddleware) RequirePlatformAdmin

func (m *PlatformMiddleware) RequirePlatformAdmin() func(http.Handler) http.Handler

RequirePlatformAdmin returns middleware that requires platform admin status.

type Principal

type Principal struct {
	// ID is the unique identifier of the principal.
	ID uuid.UUID

	// Type identifies the kind of principal (user, service, api_key, etc.).
	Type PrincipalType

	// Attributes contains additional principal attributes for ABAC.
	Attributes map[string]any
}

Principal represents an entity requesting access (user, service, etc.).

func NewServicePrincipal

func NewServicePrincipal(serviceID uuid.UUID) Principal

NewServicePrincipal creates a Principal for a service.

func NewUserPrincipal

func NewUserPrincipal(userID uuid.UUID) Principal

NewUserPrincipal creates a Principal for a user.

func NewUserPrincipalWithAttrs

func NewUserPrincipalWithAttrs(userID uuid.UUID, attrs map[string]any) Principal

NewUserPrincipalWithAttrs creates a Principal for a user with attributes.

func (Principal) WithAttr

func (p Principal) WithAttr(key string, value any) Principal

WithAttr returns a copy of the Principal with an additional attribute.

type PrincipalType

type PrincipalType string

PrincipalType identifies the kind of principal.

const (
	PrincipalTypeUser    PrincipalType = "user"
	PrincipalTypeService PrincipalType = "service"
	PrincipalTypeAPIKey  PrincipalType = "api_key"
	PrincipalTypeSystem  PrincipalType = "system"
)

type Resource

type Resource struct {
	// Type identifies the kind of resource (course, organization, etc.).
	Type ResourceType

	// ID is the unique identifier of the resource (nil for type-level checks).
	ID *uuid.UUID

	// OwnerID is the owner of the resource (for ownership-based access).
	OwnerID *uuid.UUID

	// OrgID is the organization this resource belongs to.
	OrgID *uuid.UUID

	// Attributes contains additional resource attributes for ABAC.
	Attributes map[string]any
}

Resource represents something being accessed.

func NewOrgResource

func NewOrgResource(resourceType ResourceType, orgID uuid.UUID) Resource

NewOrgResource creates a Resource scoped to an organization.

func NewOwnedResource

func NewOwnedResource(resourceType ResourceType, id, ownerID uuid.UUID) Resource

NewOwnedResource creates a Resource with an owner.

func NewResource

func NewResource(resourceType ResourceType) Resource

NewResource creates a Resource with the given type.

func NewResourceWithID

func NewResourceWithID(resourceType ResourceType, id uuid.UUID) Resource

NewResourceWithID creates a Resource with type and ID.

func (Resource) IsOwner

func (r Resource) IsOwner(principalID uuid.UUID) bool

IsOwner checks if the principal owns this resource.

func (Resource) WithAttr

func (r Resource) WithAttr(key string, value any) Resource

WithAttr returns a copy of the Resource with an additional attribute.

func (Resource) WithOrg

func (r Resource) WithOrg(orgID uuid.UUID) Resource

WithOrg returns a copy of the Resource with the specified organization.

func (Resource) WithOwner

func (r Resource) WithOwner(ownerID uuid.UUID) Resource

WithOwner returns a copy of the Resource with the specified owner.

type ResourceExtractor

type ResourceExtractor func(r *http.Request) (Resource, error)

ResourceExtractor is a function that extracts a resource from an HTTP request. Use this for routes that include resource IDs in the path.

func WithResourceID

func WithResourceID(resourceType ResourceType, pathParamName string, getParam func(r *http.Request, key string) string) ResourceExtractor

WithResourceID creates a ResourceExtractor that parses a resource ID from a URL path parameter.

type ResourceType

type ResourceType string

ResourceType identifies the kind of resource.

const (
	ResourceTypeOrganization ResourceType = "organization"
	ResourceTypeMember       ResourceType = "member"
	ResourceTypeUser         ResourceType = "user"
)

Common resource type constants.

type RoleHierarchy

type RoleHierarchy map[string]int

RoleHierarchy defines a hierarchy of roles where higher values indicate more access. Roles with higher hierarchy values can access resources requiring lower levels.

func (RoleHierarchy) CanAccess

func (h RoleHierarchy) CanAccess(userRole, requiredRole string) bool

CanAccess checks if a user role can access resources requiring the target role. Higher hierarchy values can access lower ones.

func (RoleHierarchy) IsHigherOrEqual

func (h RoleHierarchy) IsHigherOrEqual(role1, role2 string) bool

IsHigherOrEqual checks if role1 is higher than or equal to role2.

func (RoleHierarchy) Level

func (h RoleHierarchy) Level(role string) int

Level returns the hierarchy level for a role, or 0 if not found.

type RolePermissions

type RolePermissions map[string][]string

RolePermissions maps roles to their granted permissions.

func (RolePermissions) GetPermissions

func (rp RolePermissions) GetPermissions(role string) []string

GetPermissions returns all permissions for a role.

func (RolePermissions) HasAllPermissions

func (rp RolePermissions) HasAllPermissions(role string, permissions []string) bool

HasAllPermissions checks if a role has all of the specified permissions.

func (RolePermissions) HasAnyPermission

func (rp RolePermissions) HasAnyPermission(role string, permissions []string) bool

HasAnyPermission checks if a role has any of the specified permissions.

func (RolePermissions) HasPermission

func (rp RolePermissions) HasPermission(role, permission string) bool

HasPermission checks if a role has a specific permission.

Directories

Path Synopsis
Package casbin provides a Casbin-based authorization provider.
Package casbin provides a Casbin-based authorization provider.
Package providertest provides conformance tests for authz.Provider implementations.
Package providertest provides conformance tests for authz.Provider implementations.
Package simple provides a simple role-based authorization provider.
Package simple provides a simple role-based authorization provider.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL