The user wants a comprehensive cross-service permission system.
This is a big request. It involves:
Modeling: Defining how permissions work (RBAC, ABAC, ReBAC).
Architecture: How it works across services (microservices).
Components:
Policy Store (where rules live).
Decision Engine (the logic).
Caching (performance).
Auditing (compliance/security).
Implementation: Code structure (likely in a popular language like Go, Python, or Java, or maybe just a generic design with snippets). I'll aim for a generic but detailed technical design with pseudo-code/Go examples as Go is standard for infrastructure.
Testing: How to ensure it works.
1. Deconstruct the Concepts:
RBAC (Role-Based Access Control):User -> Role -> Permission. Good for broad strokes (Admin, Editor, Viewer).
ABAC (Attribute-Based Access Control):Subject (with attrs) + Action + Resource (with attrs) + Context -> Allow/Deny. Good for fine-grained logic (e.g., "User can edit Doc if User.Location == Doc.Location").
ReBAC (Relationship-Based Access Control):User -> Relation -> Resource. Good for hierarchies/graphs (e.g., "User is Owner of Team, Team has Repo, therefore User has access to Repo"). Zanzibar is the gold standard here.
2. Architectural Strategy:
Centralized vs. Decentralized: A centralized "Policy Decision Point" (PDP) is best for consistency. Services ask the PDP.
Language/Stack: I'll use Go (Golang) for the examples because it's strongly typed, performant, and common in auth systems (e.g., Ory Keto, Casbin, AuthZEN).
Tech Stack:
Database: Postgres (relational) or Redis (graph/cache). Let's assume Postgres for durability + Redis for cache.
API: gRPC (internal) or REST.
3. Step-by-Step Design:
Step 1: The Model (The "Schema"):
Need a definition language. I'll sketch a simplified DSL (Domain Specific Language) or use JSON.
Implementation (Go): Code snippets for the engine.
Performance (Caching): Handling scale.
Observability & Testing: Audits and verification.
Self-Correction during drafting: Don't just write code. Explain why ReBAC is different from RBAC.
RBAC: user has role.
ReBAC: user is member of group.
ABAC: user is member AND time is daytime.
I'll provide a concrete scenario: "Document Management System".
RBAC: Admins can do everything.
ReBAC: Owners of a folder can delete files in it.
ABAC: You can only edit files if your IP is within the corporate VPN (Context attribute).
6. Final Polish:
Ensure the code is readable. Use clear variable names. Make sure the distinction between "Policy Administration Point" (PAP - writing rules) and "Policy Decision Point" (PDP - checking rules) is clear, even if I implement them in one service for brevity.
Let's write the response.
Building a cross-service permission system requires moving beyond simple "if admin" checks. You need a centralized Policy Decision Point (PDP) that supports complex relationships while maintaining low latency.
Below is a comprehensive design and implementation guide for a hybrid RBAC/ABAC/ReBAC system using Go.
1. Conceptual Modeling (The "Zanzibar" Approach)
To handle all three models seamlessly, we model permissions as a Directed Acyclic Graph (DAG) of relations.
RBAC (Role-Based):User→Role→Permission.
ReBAC (Relation-Based):User→Group→Resource. (e.g., "Alice is a member of the 'Engineering' Team").
ABAC (Attribute-Based): Logic applied to the graph traversal context (e.g., Resource.IpRange == User.IpRange).
The Schema (Namespace Config)
We define a configuration that acts as our "Truth".
yaml
# schema.yaml
namespace: document
relations:
# RBAC: Static roles defined on the document
viewer:
types: ["user"]
editor:
types: ["user"]
# ReBAC: Inheritance (Editors are automatically viewers)
view:
union:
- viewer
- editor
# ABAC/ReBAC Hybrid: Permissions inherited from the parent folder
parent_folder:
types: ["folder"]
# Logic: You can edit if you are an editor OR an editor on the parent folder
edit_access:
union:
- editor
- parent_folder#edit_access
2. System Architecture
Policy Administration Point (PAP): Service to manage roles/relations (CRUD).
Policy Decision Point (PDP): The core engine. Given (User, Resource, Action), returns Allow/Deny.
Policy Information Point (PIP): The database storing the relation tuples.
Cache: Two layers (Redis for distributed, In-Memory for local hot paths).
Audit: Asynchronous log shipping for compliance.
3. Implementation (Go)
A. Data Model (PIP)
We store relations as "Tuples".
go
// pkg/model/tuple.go
type RelationTuple struct {
Object string // e.g., "document:1"
Relation string // e.g., "viewer"
User string // e.g., "user:alice" or "group:eng#member"
}
// Storage Interface
type RelationRepository interface {
// Returns all tuples where Object = resourceID
GetRelations(ctx context.Context, object string) ([]RelationTuple, error)
}
B. The Decision Engine (PDP)
This engine performs a recursive depth-first search (DFS) to check permissions. It handles the ReBAC traversal and hooks in ABAC logic.
go
// pkg/engine/check.go
package engine
import (
"context"
"strings"
)
type CheckEngine struct {
Repo RelationRepository
Cache CacheInterface
// ABAC Hooks
AttributeCheckFunc func(ctx context.Context, user, resource string) (bool, error)
}
func (e *CheckEngine) Check(ctx context.Context, user string, resource string, action string) (bool, error) {
// 1. Cache Lookup (Hot Path)
cacheKey := genCacheKey(user, resource, action)
if allowed, found := e.Cache.Get(cacheKey); found {
return allowed.(bool), nil
}
// 2. Graph Traversal
// Map action to schema relation (e.g., action "read" -> relation "view")
requiredRelation := mapActionToRelation(action)
visited := make(map[string]bool)
allowed, err := e.resolve(ctx, user, resource, requiredRelation, visited)
if err != nil {
return false, err
}
// 3. ABAC Injection
// If ReBAC didn't explicitly allow, check specific Attribute logic
if !allowed && e.AttributeCheckFunc != nil {
allowed, err = e.AttributeCheckFunc(ctx, user, resource)
if err != nil {
return false, err
}
}
// 4. Update Cache
// Cache negative results briefly to prevent hammering, positive longer
ttl := 30 * time.Second
if allowed { ttl = 5 * time.Minute }
e.Cache.Set(cacheKey, allowed, ttl)
return allowed, nil
}
// Recursive resolver
func (e *CheckEngine) resolve(ctx context.Context, user string, object string, relation string, visited map[string]bool) (bool, error) {
// Cycle detection
nodeKey := object + "#" + relation
if visited[nodeKey] {
return false, nil
}
visited[nodeKey] = true
// Fetch tuples for this object (e.g., who has access to doc:1?)
tuples, err := e.Repo.GetRelations(ctx, object)
if err != nil {
return false, err
}
for _, tuple := range tuples {
// Direct User Check (RBAC)
if tuple.User == user && tuple.Relation == relation {
return true, nil
}
// Rewriting / Indirect Check (ReBAC)
// If tuple is "group:eng#member", we check if user is a member of eng
if strings.Contains(tuple.User, "#") {
parts := strings.Split(tuple.User, "#")
subjectID := parts[0] // group:eng
subjectRel := parts[1] // member
// Recursive step: Check if user has "member" relation on "group:eng"
isMember, err := e.resolve(ctx, user, subjectID, subjectRel, visited)
if err != nil {
return false, err
}
if isMember && tuple.Relation == relation {
return true, nil
}
}
}
return false, nil
}
C. ABAC Implementation Detail
Notice the AttributeCheckFunc in the engine. This is where we inject logic that doesn't fit the graph (like time of day or IP address).
Permissions are security-critical. You must log why a decision was made.
go
// pkg/audit/logger.go
type AuditLog struct {
Timestamp time.Time
User string
Resource string
Action string
Decision bool
Reason string // "RBAC: Role Admin" or "ReBAC: Group Owner"
TraceID string
}
func LogDecision(ctx context.Context, log AuditLog) {
// Fire and forget to a queue (Kafka/SNS) or strict write to DB
data, _ := json.Marshal(log)
// asyncProducer.Write(data)
}
6. Testing Strategy
Permissions systems require exhaustive testing. We use Table-Driven Tests.
go
// pkg/engine/check_test.go
func TestCheckEngine(t *testing.T) {
// Mock Repo
mockRepo := &MockRepo{
Data: map[string][]RelationTuple{
"doc:1": {
{Object: "doc:1", Relation: "viewer", User: "user:bob"},
{Object: "doc:1", Relation: "parent_folder", User: "folder:A"},
},
"folder:A": {
{Object: "folder:A", Relation: "editor", User: "user:alice"},
},
},
}
engine := &CheckEngine{Repo: mockRepo}
tests := []struct {
name string
user string
resource string
action string
want bool
}{
// RBAC Test
{"Bob reads doc", "user:bob", "doc:1", "read", true},
// ReBAC Inheritance Test
// Alice is editor on Folder A. Doc 1 is in Folder A.
// Schema implies editors can read.
{"Alice reads doc via folder", "user:alice", "doc:1", "read", true},
// Negative Test
{"Alice writes doc (denied if schema requires direct editor)", "user:alice", "doc:1", "write", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, _ := engine.Check(context.Background(), tt.user, tt.resource, tt.action)
if got != tt.want {
t.Errorf("got %v, want %v", got, tt.want)
}
})
}
}
Summary of Best Practices
Fail Closed: If the engine crashes or returns an error, default to DENY.
Context Timeouts: Permission checks should be fast (< 10ms). Set strict context deadlines.
Limit Recursion: In ReBAC, limit the depth of the graph traversal (e.g., max 10 hops) to prevent infinite loops (Cycle Detection).
Normalized Keys: Ensure User and Resource IDs are consistently namespaced (e.g., user:123, doc:456) to avoid collision.