permissions

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: Apache-2.0 Imports: 27 Imported by: 0

README ΒΆ

AuthSome Permissions Plugin

Enterprise-grade permissions system with ABAC, dynamic resources, and CEL policy language.

Features

πŸš€ Advanced Authorization
  • ABAC (Attribute-Based Access Control) - Policy decisions based on user, resource, and request attributes
  • CEL Policy Language - Google's Common Expression Language for safe, fast policy evaluation
  • Dynamic Resources - Organizations define their own resource types and actions
  • Sub-millisecond latency - <5ms p99 with 10K+ policies per org
🏒 Multi-Tenant SaaS
  • Organization-scoped namespaces - Complete isolation between tenants
  • Custom resource definitions - Each org defines what they need to protect
  • Policy templates - Pre-built patterns for common scenarios
  • Platform inheritance - Share common policies across organizations
⚑ Performance
  • Three-tier caching - Local LRU + Redis + Database
  • Compiled policies - Parse once, evaluate millions of times
  • Parallel evaluation - Concurrent policy checks with early exit
  • Query optimization - Cost-based evaluation ordering
πŸ”§ Production-Ready
  • Migration tool - Seamless migration from existing RBAC
  • Hybrid mode - Run both systems during transition
  • Comprehensive metrics - Prometheus + OpenTelemetry integration
  • Audit logging - Complete trail of policy changes
  • Policy versioning - Rollback to previous versions

Quick Start

1. Enable the Plugin

Add to your authsome.yaml:

auth:
  permissions:
    enabled: true
    mode: hybrid  # Use hybrid mode during migration
    
    engine:
      maxPolicyComplexity: 100
      evaluationTimeout: 10ms
      parallelEvaluation: true
    
    cache:
      enabled: true
      backend: redis
      localCacheSize: 10000
2. Register the Plugin
import (
    "github.com/xraph/authsome"
    "github.com/xraph/authsome/plugins/permissions"
)

func main() {
    auth := authsome.New(authsome.Config{
        ModeSaaS: true,
        // ... other config
    })
    
    // Register permissions plugin
    auth.RegisterPlugin(permissions.NewPlugin())
    
    // Initialize
    if err := auth.Init(); err != nil {
        log.Fatal(err)
    }
}
3. Create Your First Policy
curl -X POST http://localhost:8080/permissions/policies \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Document owners can edit",
    "expression": "resource.owner == principal.id",
    "resourceType": "document",
    "actions": ["read", "write", "delete"],
    "enabled": true
  }'
4. Evaluate Permissions
curl -X POST http://localhost:8080/permissions/evaluate \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "principalId": "user_123",
    "action": "write",
    "resourceType": "document",
    "resourceId": "doc_456"
  }'

Response:

{
  "allowed": true,
  "matchedPolicies": ["policy_789"],
  "evaluationTime": "2.3ms"
}

Policy Examples

Owner-Only Access
resource.owner == principal.id
Admin or Owner
has_role("admin") || resource.owner == principal.id
Business Hours Only
is_weekday() && in_time_range("09:00", "17:00")
IP Allowlist
ip_in_range(["10.0.0.0/8", "192.168.0.0/16"])
Team Members
principal.team_id == resource.team_id && 
principal.department in ["engineering", "operations"]
Time-Limited Access
request.time < resource.expires_at && 
days_since(resource.created_at) < 90
Confidentiality-Based
resource.metadata.confidentiality == "public" ||
(resource.metadata.confidentiality == "internal" && is_member_of(resource.org_id)) ||
(resource.metadata.confidentiality == "restricted" && principal.clearance_level >= 3)

Organization Setup

1. Create Namespace
curl -X POST http://localhost:8080/permissions/namespaces \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "orgId": "org_abc123",
    "inheritPlatform": true,
    "templateId": "enterprise-base"
  }'
2. Define Custom Resources
curl -X POST http://localhost:8080/permissions/resources \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "namespaceId": "ns_xyz",
    "type": "document",
    "attributes": [
      {"name": "owner", "type": "string", "required": true},
      {"name": "team_id", "type": "string"},
      {"name": "confidentiality", "type": "string"},
      {"name": "tags", "type": "array"}
    ]
  }'
3. Define Actions
curl -X POST http://localhost:8080/permissions/actions \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "namespaceId": "ns_xyz",
    "name": "export",
    "description": "Export resource data"
  }'

Migration from RBAC

Automatic Migration
curl -X POST http://localhost:8080/permissions/migrate/rbac \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "orgId": "org_abc123",
    "dryRun": true,
    "validateEquivalence": true
  }'
Hybrid Mode

Run both systems during migration:

auth:
  permissions:
    mode: hybrid  # Try permissions first, fallback to RBAC

Check migration status:

curl http://localhost:8080/permissions/migrate/rbac/status?orgId=org_abc123 \
  -H "Authorization: Bearer $TOKEN"

Configuration Reference

Engine Settings
engine:
  maxPolicyComplexity: 100      # Max operations per policy
  evaluationTimeout: 10ms       # Max evaluation time
  maxPoliciesPerOrg: 10000      # Policy limit per org
  parallelEvaluation: true      # Concurrent evaluation
  maxParallelEvaluations: 4     # Concurrency level
  enableAttributeCaching: true  # Cache attributes
  attributeCacheTTL: 5m         # Attribute cache TTL
Cache Settings
cache:
  enabled: true
  backend: hybrid               # memory, redis, hybrid
  localCacheSize: 10000         # LRU cache size
  localCacheTTL: 5m             # Local TTL
  redisTTL: 15m                 # Redis TTL
  warmupOnStart: true           # Pre-load on startup
  invalidateOnChange: true      # Immediate invalidation
Performance Tuning
performance:
  enableMetrics: true           # Prometheus metrics
  enableTracing: false          # OpenTelemetry traces
  traceSamplingRate: 0.01       # 1% sampling
  slowQueryThreshold: 5ms       # Log slow queries
  enableProfiling: false        # pprof endpoints

Performance Benchmarks

Scenario Latency (p50) Latency (p99) Throughput
Simple policy (owner check) <1ms <2ms 50K RPS
Complex policy (ABAC) 2ms 4ms 25K RPS
1K policies, local cache 1ms 3ms 30K RPS
1K policies, Redis cache 2ms 5ms 20K RPS
10K policies, optimized 3ms 8ms 15K RPS

Benchmarked on: 4 CPU, 8GB RAM, PostgreSQL + Redis

API Reference

Policy Management
Endpoint Method Description
/permissions/policies POST Create policy
/permissions/policies GET List policies
/permissions/policies/:id GET Get policy
/permissions/policies/:id PUT Update policy
/permissions/policies/:id DELETE Delete policy
/permissions/policies/validate POST Validate syntax
/permissions/policies/test POST Test policy
Resource Management
Endpoint Method Description
/permissions/resources POST Define resource type
/permissions/resources GET List resource types
/permissions/resources/:id GET Get resource definition
/permissions/resources/:id DELETE Delete resource type
Evaluation
Endpoint Method Description
/permissions/evaluate POST Check authorization
/permissions/evaluate/batch POST Batch evaluation
Templates
Endpoint Method Description
/permissions/templates GET List templates
/permissions/templates/:id GET Get template
/permissions/templates/:id/instantiate POST Use template

Monitoring

Prometheus Metrics
permissions_evaluations_total{org_id, resource_type, action, result}
permissions_evaluation_duration_seconds{org_id}
permissions_cache_hits_total{tier="local|redis|db"}
permissions_policy_count{org_id}
permissions_errors_total{type}
Grafana Dashboard

Import dashboard from: /plugins/permissions/monitoring/grafana-dashboard.json

Health Check
curl http://localhost:8080/health/permissions

Security Considerations

Policy Validation
  • All policies validated at creation time
  • Type checking prevents runtime errors
  • Complexity limits prevent DoS
Cache Security
  • Cache keys include org ID for isolation
  • Redis ACLs recommended
  • Automatic cache invalidation on updates
Audit Trail
  • All policy changes logged
  • Actor, timestamp, old/new values tracked
  • Queryable audit API
Rate Limiting
  • Per-org policy limits
  • Evaluation timeout protection
  • Request rate limiting recommended

Troubleshooting

Slow Evaluations

Check metrics:

curl http://localhost:8080/metrics | grep permissions_evaluation_duration

Enable profiling:

performance:
  enableProfiling: true

Profile: curl http://localhost:8080/debug/pprof/profile

Cache Misses

Check hit rate:

curl http://localhost:8080/metrics | grep permissions_cache_hits

Adjust cache sizes:

cache:
  localCacheSize: 20000  # Increase
  localCacheTTL: 10m     # Increase
Policy Errors

Validate before creating:

curl -X POST http://localhost:8080/permissions/policies/validate \
  -d '{"expression": "resource.owner == principal.id"}'

Test with sample data:

curl -X POST http://localhost:8080/permissions/policies/test \
  -d '{
    "expression": "...",
    "testCases": [...]
  }'

Documentation

Examples

See /examples/permissions/ for:

  • Basic policy examples
  • ABAC scenarios
  • Multi-tenant setup
  • Performance testing
  • Client integration

Support

License

Same as AuthSome (see root LICENSE file)

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	PluginID      = "permissions"
	PluginName    = "Advanced Permissions"
	PluginVersion = "1.0.0"
)

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type CacheConfig ΒΆ

type CacheConfig struct {
	// Enabled controls whether caching is active
	// Default: true
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Backend specifies the cache backend
	// Options: "memory", "redis", "hybrid"
	// Default: "hybrid"
	Backend string `json:"backend" yaml:"backend"`

	// LocalCacheSize is the size of the in-memory LRU cache
	// Default: 10000
	LocalCacheSize int `json:"localCacheSize" yaml:"localCacheSize"`

	// LocalCacheTTL is the TTL for local cache entries
	// Default: 5 minutes
	LocalCacheTTL time.Duration `json:"localCacheTTL" yaml:"localCacheTTL"`

	// RedisTTL is the TTL for Redis cache entries
	// Default: 15 minutes
	RedisTTL time.Duration `json:"redisTTL" yaml:"redisTTL"`

	// WarmupOnStart pre-loads policies on startup
	// Default: true
	WarmupOnStart bool `json:"warmupOnStart" yaml:"warmupOnStart"`

	// InvalidateOnChange immediately invalidates cache on policy changes
	// Default: true
	InvalidateOnChange bool `json:"invalidateOnChange" yaml:"invalidateOnChange"`
}

CacheConfig controls caching behavior

type Config ΒΆ

type Config struct {
	// Enabled controls whether the permissions system is active
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Mode determines the evaluation mode
	// - "strict": Only use permissions system (RBAC disabled)
	// - "hybrid": Try permissions first, fallback to RBAC
	// - "rbac-primary": Try RBAC first, fallback to permissions
	Mode string `json:"mode" yaml:"mode"`

	// Engine configuration
	Engine EngineConfig `json:"engine" yaml:"engine"`

	// Cache configuration
	Cache CacheConfig `json:"cache" yaml:"cache"`

	// Performance tuning
	Performance PerformanceConfig `json:"performance" yaml:"performance"`

	// Migration settings
	Migration MigrationConfig `json:"migration" yaml:"migration"`

	// Organization-specific overrides
	Organizations map[string]*OrgConfig `json:"organizations" yaml:"organizations"`
}

Config represents the permissions plugin configuration

func DefaultConfig ΒΆ

func DefaultConfig() *Config

DefaultConfig returns the default configuration

func LoadConfig ΒΆ

func LoadConfig(configManager forge.ConfigManager) (*Config, error)

LoadConfig loads configuration from Forge config manager

func (*Config) GetOrgConfig ΒΆ

func (c *Config) GetOrgConfig(orgID string) *Config

GetOrgConfig returns the effective configuration for an organization

func (*Config) MergeOrgConfig ΒΆ

func (c *Config) MergeOrgConfig(orgID string, override *OrgConfig)

MergeOrgConfig merges organization-specific settings

func (*Config) Validate ΒΆ

func (c *Config) Validate() error

Validate checks if the configuration is valid

type EngineConfig ΒΆ

type EngineConfig struct {
	// MaxPolicyComplexity limits the number of operations in a policy
	// Default: 100
	MaxPolicyComplexity int `json:"maxPolicyComplexity" yaml:"maxPolicyComplexity"`

	// EvaluationTimeout is the maximum time for policy evaluation
	// Default: 10ms
	EvaluationTimeout time.Duration `json:"evaluationTimeout" yaml:"evaluationTimeout"`

	// MaxPoliciesPerOrg limits policies per organization
	// Default: 10000
	MaxPoliciesPerOrg int `json:"maxPoliciesPerOrg" yaml:"maxPoliciesPerOrg"`

	// ParallelEvaluation enables concurrent policy evaluation
	// Default: true
	ParallelEvaluation bool `json:"parallelEvaluation" yaml:"parallelEvaluation"`

	// MaxParallelEvaluations controls concurrency level
	// Default: 4
	MaxParallelEvaluations int `json:"maxParallelEvaluations" yaml:"maxParallelEvaluations"`

	// EnableAttributeCaching caches attribute lookups
	// Default: true
	EnableAttributeCaching bool `json:"enableAttributeCaching" yaml:"enableAttributeCaching"`

	// AttributeCacheTTL is the TTL for attribute cache
	// Default: 5 minutes
	AttributeCacheTTL time.Duration `json:"attributeCacheTTL" yaml:"attributeCacheTTL"`
}

EngineConfig controls the policy evaluation engine

type Handler ΒΆ

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

Handler handles HTTP requests for the permissions plugin V2 Architecture: App β†’ Environment β†’ Organization

func NewHandler ΒΆ

func NewHandler(service *Service) *Handler

NewHandler creates a new handler instance

func (*Handler) CreateAction ΒΆ

func (h *Handler) CreateAction(c forge.Context) error

CreateAction handles POST /permissions/actions

func (*Handler) CreateNamespace ΒΆ

func (h *Handler) CreateNamespace(c forge.Context) error

CreateNamespace handles POST /permissions/namespaces

func (*Handler) CreatePolicy ΒΆ

func (h *Handler) CreatePolicy(c forge.Context) error

CreatePolicy handles POST /permissions/policies

func (*Handler) CreateResource ΒΆ

func (h *Handler) CreateResource(c forge.Context) error

CreateResource handles POST /permissions/resources

func (*Handler) DeleteAction ΒΆ

func (h *Handler) DeleteAction(c forge.Context) error

DeleteAction handles DELETE /permissions/actions/:id

func (*Handler) DeleteNamespace ΒΆ

func (h *Handler) DeleteNamespace(c forge.Context) error

DeleteNamespace handles DELETE /permissions/namespaces/:id

func (*Handler) DeletePolicy ΒΆ

func (h *Handler) DeletePolicy(c forge.Context) error

DeletePolicy handles DELETE /permissions/policies/:id

func (*Handler) DeleteResource ΒΆ

func (h *Handler) DeleteResource(c forge.Context) error

DeleteResource handles DELETE /permissions/resources/:id

func (*Handler) Evaluate ΒΆ

func (h *Handler) Evaluate(c forge.Context) error

Evaluate handles POST /permissions/evaluate

func (*Handler) EvaluateBatch ΒΆ

func (h *Handler) EvaluateBatch(c forge.Context) error

EvaluateBatch handles POST /permissions/evaluate/batch

func (*Handler) GetAnalytics ΒΆ

func (h *Handler) GetAnalytics(c forge.Context) error

GetAnalytics handles GET /permissions/analytics

func (*Handler) GetAuditLog ΒΆ

func (h *Handler) GetAuditLog(c forge.Context) error

GetAuditLog handles GET /permissions/audit

func (*Handler) GetMigrationStatus ΒΆ

func (h *Handler) GetMigrationStatus(c forge.Context) error

GetMigrationStatus handles GET /permissions/migrate/rbac/status

func (*Handler) GetNamespace ΒΆ

func (h *Handler) GetNamespace(c forge.Context) error

GetNamespace handles GET /permissions/namespaces/:id

func (*Handler) GetPolicy ΒΆ

func (h *Handler) GetPolicy(c forge.Context) error

GetPolicy handles GET /permissions/policies/:id

func (*Handler) GetResource ΒΆ

func (h *Handler) GetResource(c forge.Context) error

GetResource handles GET /permissions/resources/:id

func (*Handler) GetTemplate ΒΆ

func (h *Handler) GetTemplate(c forge.Context) error

GetTemplate handles GET /permissions/templates/:id

func (*Handler) InstantiateTemplate ΒΆ

func (h *Handler) InstantiateTemplate(c forge.Context) error

InstantiateTemplate handles POST /permissions/templates/:id/instantiate

func (*Handler) ListActions ΒΆ

func (h *Handler) ListActions(c forge.Context) error

ListActions handles GET /permissions/actions

func (*Handler) ListNamespaces ΒΆ

func (h *Handler) ListNamespaces(c forge.Context) error

ListNamespaces handles GET /permissions/namespaces

func (*Handler) ListPolicies ΒΆ

func (h *Handler) ListPolicies(c forge.Context) error

ListPolicies handles GET /permissions/policies

func (*Handler) ListResources ΒΆ

func (h *Handler) ListResources(c forge.Context) error

ListResources handles GET /permissions/resources

func (*Handler) ListTemplates ΒΆ

func (h *Handler) ListTemplates(c forge.Context) error

ListTemplates handles GET /permissions/templates

func (*Handler) MigrateFromRBAC ΒΆ

func (h *Handler) MigrateFromRBAC(c forge.Context) error

MigrateFromRBAC handles POST /permissions/migrate/rbac

func (*Handler) TestPolicy ΒΆ

func (h *Handler) TestPolicy(c forge.Context) error

TestPolicy handles POST /permissions/policies/test

func (*Handler) UpdateNamespace ΒΆ

func (h *Handler) UpdateNamespace(c forge.Context) error

UpdateNamespace handles PUT /permissions/namespaces/:id

func (*Handler) UpdatePolicy ΒΆ

func (h *Handler) UpdatePolicy(c forge.Context) error

UpdatePolicy handles PUT /permissions/policies/:id

func (*Handler) ValidatePolicy ΒΆ

func (h *Handler) ValidatePolicy(c forge.Context) error

ValidatePolicy handles POST /permissions/policies/validate

type MessageResponse ΒΆ

type MessageResponse = handlers.MessageResponse

Response types - use from handlers package

type MigrationConfig ΒΆ

type MigrationConfig struct {
	// AutoMigrate automatically converts RBAC policies
	// Default: false (requires manual migration)
	AutoMigrate bool `json:"autoMigrate" yaml:"autoMigrate"`

	// ValidateEquivalence checks that migrated policies match RBAC
	// Default: true
	ValidateEquivalence bool `json:"validateEquivalence" yaml:"validateEquivalence"`

	// KeepRBACPolicies retains RBAC policies after migration
	// Default: true (safe to delete after validation)
	KeepRBACPolicies bool `json:"keepRBACPolicies" yaml:"keepRBACPolicies"`

	// DryRun simulates migration without making changes
	// Default: false
	DryRun bool `json:"dryRun" yaml:"dryRun"`
}

MigrationConfig controls RBAC β†’ Permissions migration

type OrgConfig ΒΆ

type OrgConfig struct {
	// Enabled controls if permissions are enabled for this org
	Enabled *bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`

	// MaxPolicies overrides the global limit for this org
	MaxPolicies *int `json:"maxPolicies,omitempty" yaml:"maxPolicies,omitempty"`

	// CustomResources defines org-specific resource types
	CustomResources []string `json:"customResources,omitempty" yaml:"customResources,omitempty"`

	// CustomActions defines org-specific actions
	CustomActions []string `json:"customActions,omitempty" yaml:"customActions,omitempty"`

	// TemplateID specifies which platform template to inherit
	TemplateID *string `json:"templateId,omitempty" yaml:"templateId,omitempty"`

	// InheritPlatform controls platform policy inheritance
	InheritPlatform *bool `json:"inheritPlatform,omitempty" yaml:"inheritPlatform,omitempty"`
}

OrgConfig allows organization-specific overrides

type PerformanceConfig ΒΆ

type PerformanceConfig struct {
	// EnableMetrics enables Prometheus metrics
	// Default: true
	EnableMetrics bool `json:"enableMetrics" yaml:"enableMetrics"`

	// EnableTracing enables OpenTelemetry tracing
	// Default: false (enable in production)
	EnableTracing bool `json:"enableTracing" yaml:"enableTracing"`

	// TraceSamplingRate is the percentage of requests to trace
	// Default: 0.01 (1%)
	TraceSamplingRate float64 `json:"traceSamplingRate" yaml:"traceSamplingRate"`

	// SlowQueryThreshold logs queries slower than this
	// Default: 5ms
	SlowQueryThreshold time.Duration `json:"slowQueryThreshold" yaml:"slowQueryThreshold"`

	// EnableProfiling enables pprof endpoints
	// Default: false (enable for debugging)
	EnableProfiling bool `json:"enableProfiling" yaml:"enableProfiling"`
}

PerformanceConfig controls performance tuning

type PermissionMiddleware ΒΆ added in v0.0.3

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

PermissionMiddleware provides middleware for automatic permission checking on routes

func NewPermissionMiddleware ΒΆ added in v0.0.3

func NewPermissionMiddleware(service *Service, config PermissionMiddlewareConfig, logger forge.Logger) *PermissionMiddleware

NewPermissionMiddleware creates a new permission middleware

func (*PermissionMiddleware) Middleware ΒΆ added in v0.0.3

func (m *PermissionMiddleware) Middleware() func(next forge.Handler) forge.Handler

Middleware returns the forge middleware function

type PermissionMiddlewareConfig ΒΆ added in v0.0.3

type PermissionMiddlewareConfig struct {
	// ResourceType is the type of resource being protected (e.g., "document", "project")
	ResourceType string

	// Action is the action being performed (e.g., "read", "write", "delete")
	Action string

	// ResourceIDParam is the URL parameter name containing the resource ID (e.g., "id", "documentId")
	// If empty, the middleware checks access at the resource type level without a specific resource
	ResourceIDParam string

	// DenyHandler is an optional custom handler for denied requests
	// If nil, a default 403 response is returned
	DenyHandler forge.Handler

	// AllowAnonymous allows unauthenticated requests to proceed (useful with other conditions)
	AllowAnonymous bool

	// SkipIfNoUser skips permission check if no user is in context (useful for optional auth routes)
	SkipIfNoUser bool

	// CustomContext provides additional context for the permission check
	CustomContext map[string]interface{}
}

PermissionMiddlewareConfig configures the permission middleware behavior

type PermissionMiddlewareFunc ΒΆ added in v0.0.3

type PermissionMiddlewareFunc func(next forge.Handler) forge.Handler

PermissionMiddlewareFunc is the middleware function type

type Plugin ΒΆ

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

Plugin implements the AuthSome plugin interface for advanced permissions V2 Architecture: App β†’ Environment β†’ Organization

func NewPlugin ΒΆ

func NewPlugin(opts ...PluginOption) *Plugin

NewPlugin creates a new permissions plugin instance

func (*Plugin) AttributeResolver ΒΆ added in v0.0.3

func (p *Plugin) AttributeResolver() *engine.AttributeResolver

AttributeResolver returns the attribute resolver for registering custom providers

func (*Plugin) CheckPermission ΒΆ added in v0.0.3

func (p *Plugin) CheckPermission(c forge.Context, resourceType, action, resourceID string) (bool, error)

CheckPermission is a helper that evaluates a permission check inline without middleware Useful for conditional permission checks within handlers

func (*Plugin) Description ΒΆ

func (p *Plugin) Description() string

Description returns the plugin description

func (*Plugin) Health ΒΆ

func (p *Plugin) Health(ctx context.Context) error

Health checks plugin health

func (*Plugin) ID ΒΆ

func (p *Plugin) ID() string

ID returns the unique plugin identifier

func (*Plugin) Init ΒΆ

func (p *Plugin) Init(authInst core.Authsome) error

Init initializes the plugin with dependencies

func (*Plugin) Migrate ΒΆ

func (p *Plugin) Migrate() error

Migrate runs database migrations for the plugin

func (*Plugin) MigrationService ΒΆ added in v0.0.3

func (p *Plugin) MigrationService() *migration.RBACMigrationService

MigrationService returns the RBAC migration service (for programmatic access)

func (*Plugin) Name ΒΆ

func (p *Plugin) Name() string

Name returns the human-readable plugin name

func (*Plugin) RegisterHooks ΒΆ

func (p *Plugin) RegisterHooks(hookRegistry *hooks.HookRegistry) error

RegisterHooks registers lifecycle hooks

func (*Plugin) RegisterResourceLoader ΒΆ added in v0.0.3

func (p *Plugin) RegisterResourceLoader(resourceType string, loader providers.ResourceLoader)

RegisterResourceLoader registers a resource loader for a specific resource type This allows external code to provide resource data for policy evaluation

func (*Plugin) RegisterResourceLoaderFunc ΒΆ added in v0.0.3

func (p *Plugin) RegisterResourceLoaderFunc(resourceType string, fn providers.ResourceLoaderFunc)

RegisterResourceLoaderFunc registers a function as a resource loader

func (*Plugin) RegisterRoutes ΒΆ

func (p *Plugin) RegisterRoutes(router forge.Router) error

RegisterRoutes registers HTTP routes for the plugin

func (*Plugin) RegisterServiceDecorators ΒΆ added in v0.0.3

func (p *Plugin) RegisterServiceDecorators(services *registry.ServiceRegistry) error

RegisterServiceDecorators allows plugins to replace core services with decorated versions This is called automatically by AuthSome after all services are initialized

func (*Plugin) RequireAdmin ΒΆ added in v0.0.3

func (p *Plugin) RequireAdmin(resourceType string) PermissionMiddlewareFunc

RequireAdmin creates a middleware that requires admin permission on a resource type

func (*Plugin) RequireDelete ΒΆ added in v0.0.3

func (p *Plugin) RequireDelete(resourceType string) PermissionMiddlewareFunc

RequireDelete creates a middleware that requires delete permission

func (*Plugin) RequireOwnership ΒΆ added in v0.0.3

func (p *Plugin) RequireOwnership(resourceType, resourceIDParam string) PermissionMiddlewareFunc

RequireOwnership creates a middleware that requires the user to own the resource This is a common pattern for user-owned resources

func (*Plugin) RequirePermission ΒΆ added in v0.0.3

func (p *Plugin) RequirePermission(resourceType, action string) PermissionMiddlewareFunc

RequirePermission creates a permission-checking middleware for specific resource type and action This is a convenience function for common use cases

func (*Plugin) RequirePermissionWithConfig ΒΆ added in v0.0.3

func (p *Plugin) RequirePermissionWithConfig(config PermissionMiddlewareConfig) PermissionMiddlewareFunc

RequirePermissionWithConfig creates a middleware with full configuration

func (*Plugin) RequirePermissionWithID ΒΆ added in v0.0.3

func (p *Plugin) RequirePermissionWithID(resourceType, action, resourceIDParam string) PermissionMiddlewareFunc

RequirePermissionWithID creates a middleware that checks permission for a specific resource instance

func (*Plugin) RequireRead ΒΆ added in v0.0.3

func (p *Plugin) RequireRead(resourceType string) PermissionMiddlewareFunc

RequireRead creates a middleware that requires read permission

func (*Plugin) RequireWrite ΒΆ added in v0.0.3

func (p *Plugin) RequireWrite(resourceType string) PermissionMiddlewareFunc

RequireWrite creates a middleware that requires write permission

func (*Plugin) ResourceRegistry ΒΆ added in v0.0.3

func (p *Plugin) ResourceRegistry() *providers.ResourceProviderRegistry

ResourceRegistry returns the resource provider registry for registering resource loaders

func (*Plugin) Service ΒΆ

func (p *Plugin) Service() *Service

Service returns the permissions service (for programmatic access)

func (*Plugin) Shutdown ΒΆ

func (p *Plugin) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the plugin

func (*Plugin) Version ΒΆ

func (p *Plugin) Version() string

Version returns the plugin version

func (*Plugin) WireFromAuthsome ΒΆ added in v0.0.3

func (p *Plugin) WireFromAuthsome() error

WireFromAuthsome wires all services from the AuthSome instance This is the recommended method to call after plugin initialization

func (*Plugin) WireMigrationService ΒΆ added in v0.0.3

func (p *Plugin) WireMigrationService(rbacAdapter *migration.RBACServiceAdapter) error

WireMigrationService wires the migration service to RBAC repositories This should be called after plugin initialization when RBAC services are available

func (*Plugin) WireUserAttributeProvider ΒΆ added in v0.0.3

func (p *Plugin) WireUserAttributeProvider(cfg providers.AuthsomeUserProviderConfig) error

WireUserAttributeProvider wires the user attribute provider to AuthSome services This should be called after plugin initialization when services are available

type PluginOption ΒΆ added in v0.0.3

type PluginOption func(*Plugin)

PluginOption is a functional option for configuring the permissions plugin

func WithCacheBackend ΒΆ added in v0.0.3

func WithCacheBackend(backend string) PluginOption

WithCacheBackend sets the cache backend

func WithCacheEnabled ΒΆ added in v0.0.3

func WithCacheEnabled(enabled bool) PluginOption

WithCacheEnabled sets whether caching is enabled

func WithDefaultConfig ΒΆ added in v0.0.3

func WithDefaultConfig(cfg *Config) PluginOption

WithDefaultConfig sets the default configuration for the plugin

func WithMaxPoliciesPerOrg ΒΆ added in v0.0.3

func WithMaxPoliciesPerOrg(max int) PluginOption

WithMaxPoliciesPerOrg sets the maximum policies per organization

func WithMetricsEnabled ΒΆ added in v0.0.3

func WithMetricsEnabled(enabled bool) PluginOption

WithMetricsEnabled sets whether metrics are enabled

func WithMode ΒΆ added in v0.0.3

func WithMode(mode string) PluginOption

WithMode sets the evaluation mode

func WithParallelEvaluation ΒΆ added in v0.0.3

func WithParallelEvaluation(enabled bool) PluginOption

WithParallelEvaluation sets whether parallel evaluation is enabled

type Service ΒΆ

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

Service is the main permissions service V2 Architecture: App β†’ Environment β†’ Organization

func NewService ΒΆ added in v0.0.3

func NewService(db *bun.DB, config *Config, logger forge.Logger) *Service

NewService creates a new permissions service with all dependencies

func (*Service) CreateAction ΒΆ

func (s *Service) CreateAction(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, req *handlers.CreateActionRequest) (*core.ActionDefinition, error)

CreateAction creates a new action definition

func (*Service) CreateDefaultNamespace ΒΆ

func (s *Service) CreateDefaultNamespace(ctx context.Context, appID, envID xid.ID, orgID *xid.ID) error

CreateDefaultNamespace creates a default namespace for a new app/env or organization

func (*Service) CreateNamespace ΒΆ

func (s *Service) CreateNamespace(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, userID xid.ID, req *handlers.CreateNamespaceRequest) (*core.Namespace, error)

CreateNamespace creates a new namespace

func (*Service) CreatePolicy ΒΆ

func (s *Service) CreatePolicy(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, userID xid.ID, req *handlers.CreatePolicyRequest) (*core.Policy, error)

CreatePolicy creates a new permission policy

func (*Service) CreateResource ΒΆ

func (s *Service) CreateResource(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, req *handlers.CreateResourceRequest) (*core.ResourceDefinition, error)

CreateResource creates a new resource definition

func (*Service) DeleteAction ΒΆ

func (s *Service) DeleteAction(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, actionID xid.ID) error

DeleteAction deletes an action definition

func (*Service) DeleteNamespace ΒΆ

func (s *Service) DeleteNamespace(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, namespaceID xid.ID) error

DeleteNamespace deletes a namespace

func (*Service) DeletePolicy ΒΆ

func (s *Service) DeletePolicy(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, policyID xid.ID) error

DeletePolicy deletes a policy

func (*Service) DeleteResource ΒΆ

func (s *Service) DeleteResource(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, resourceID xid.ID) error

DeleteResource deletes a resource definition

func (*Service) Evaluate ΒΆ

func (s *Service) Evaluate(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, userID xid.ID, req *handlers.EvaluateRequest) (*engine.Decision, error)

Evaluate evaluates a permission check - THE CORE FEATURE

func (*Service) EvaluateBatch ΒΆ

func (s *Service) EvaluateBatch(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, userID xid.ID, req *handlers.BatchEvaluateRequest) ([]*handlers.BatchEvaluationResult, error)

EvaluateBatch evaluates multiple permission checks efficiently

func (*Service) GetAnalytics ΒΆ

func (s *Service) GetAnalytics(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, timeRange map[string]interface{}) (*handlers.AnalyticsSummary, error)

GetAnalytics retrieves analytics data

func (*Service) GetMigrationStatus ΒΆ

func (s *Service) GetMigrationStatus(ctx context.Context, appID, envID xid.ID, orgID *xid.ID) (*core.MigrationStatus, error)

GetMigrationStatus retrieves migration status

func (*Service) GetNamespace ΒΆ

func (s *Service) GetNamespace(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, namespaceID xid.ID) (*core.Namespace, error)

GetNamespace retrieves a namespace by ID

func (*Service) GetPolicy ΒΆ

func (s *Service) GetPolicy(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, policyID xid.ID) (*core.Policy, error)

GetPolicy retrieves a policy by ID

func (*Service) GetResource ΒΆ

func (s *Service) GetResource(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, resourceID xid.ID) (*core.ResourceDefinition, error)

GetResource retrieves a resource definition by ID

func (*Service) GetTemplate ΒΆ

func (s *Service) GetTemplate(ctx context.Context, templateID string) (*core.PolicyTemplate, error)

GetTemplate retrieves a specific policy template

func (*Service) Health ΒΆ

func (s *Service) Health(ctx context.Context) error

Health checks service health

func (*Service) InstantiateTemplate ΒΆ

func (s *Service) InstantiateTemplate(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, userID xid.ID, templateID string, req *handlers.InstantiateTemplateRequest) (*core.Policy, error)

InstantiateTemplate creates a policy from a template

func (*Service) InvalidateAppCache ΒΆ

func (s *Service) InvalidateAppCache(ctx context.Context, appID xid.ID) error

InvalidateAppCache invalidates the cache for a specific app

func (*Service) InvalidateEnvironmentCache ΒΆ added in v0.0.3

func (s *Service) InvalidateEnvironmentCache(ctx context.Context, appID, envID xid.ID) error

InvalidateEnvironmentCache invalidates the cache for a specific environment

func (*Service) InvalidateOrganizationCache ΒΆ

func (s *Service) InvalidateOrganizationCache(ctx context.Context, appID, envID, orgID xid.ID) error

InvalidateOrganizationCache invalidates the cache for a specific organization

func (*Service) InvalidateUserCache ΒΆ

func (s *Service) InvalidateUserCache(ctx context.Context, userID xid.ID) error

InvalidateUserCache invalidates the cache for a specific user

func (*Service) ListActions ΒΆ

func (s *Service) ListActions(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, namespaceID xid.ID) ([]*core.ActionDefinition, error)

ListActions lists action definitions for a namespace

func (*Service) ListAuditEvents ΒΆ

func (s *Service) ListAuditEvents(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, filters map[string]interface{}) ([]*core.AuditEvent, int, error)

ListAuditEvents lists audit log entries

func (*Service) ListNamespaces ΒΆ

func (s *Service) ListNamespaces(ctx context.Context, appID, envID xid.ID, orgID *xid.ID) ([]*core.Namespace, error)

ListNamespaces lists namespaces for an app/env/org

func (*Service) ListPolicies ΒΆ

func (s *Service) ListPolicies(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, filters map[string]interface{}) ([]*core.Policy, int, error)

ListPolicies lists policies for an app/env/org

func (*Service) ListResources ΒΆ

func (s *Service) ListResources(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, namespaceID xid.ID) ([]*core.ResourceDefinition, error)

ListResources lists resource definitions for a namespace

func (*Service) ListTemplates ΒΆ

func (s *Service) ListTemplates(ctx context.Context) ([]*core.PolicyTemplate, error)

ListTemplates lists available policy templates

func (*Service) Migrate ΒΆ

func (s *Service) Migrate(ctx context.Context) error

Migrate runs database migrations

func (*Service) MigrateFromRBAC ΒΆ

func (s *Service) MigrateFromRBAC(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, req *handlers.MigrateRBACRequest) (*core.MigrationStatus, error)

MigrateFromRBAC migrates RBAC policies to permissions

func (*Service) SetMigrationService ΒΆ added in v0.0.3

func (s *Service) SetMigrationService(svc *migration.RBACMigrationService)

SetMigrationService sets the migration service

func (*Service) Shutdown ΒΆ

func (s *Service) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the service

func (*Service) TestPolicy ΒΆ

TestPolicy tests a policy against test cases

func (*Service) UpdateNamespace ΒΆ

func (s *Service) UpdateNamespace(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, namespaceID xid.ID, req *handlers.UpdateNamespaceRequest) (*core.Namespace, error)

UpdateNamespace updates an existing namespace

func (*Service) UpdatePolicy ΒΆ

func (s *Service) UpdatePolicy(ctx context.Context, appID, envID xid.ID, orgID *xid.ID, userID xid.ID, policyID xid.ID, req *handlers.UpdatePolicyRequest) (*core.Policy, error)

UpdatePolicy updates an existing policy

func (*Service) ValidatePolicy ΒΆ

ValidatePolicy validates a policy expression

func (*Service) WarmCache ΒΆ added in v0.0.3

func (s *Service) WarmCache(ctx context.Context, appID, envID xid.ID, orgID *xid.ID) error

WarmCache pre-loads and compiles all active policies for a given scope into the cache This is called during plugin initialization to ensure fast permission evaluation from the start

func (*Service) WarmCacheForAllApps ΒΆ added in v0.0.3

func (s *Service) WarmCacheForAllApps(ctx context.Context) error

WarmCacheForAllApps warms the cache for all apps and environments This should be called sparingly as it can be resource intensive

type StatusResponse ΒΆ

type StatusResponse = handlers.StatusResponse

Response types - use from handlers package

Directories ΒΆ

Path Synopsis

Jump to

Keyboard shortcuts

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