Implementing Fine-Grained Authorization with OPA and Cedar
Fine-grained authorization (FGA) allows precise control over actions on resources based on principals (users/services), contexts (e.g., time, IP), and attributes. Both OPA (Open Policy Agent) (using Rego) and Cedar (AWS's policy language) excel here due to their declarative, high-performance nature.
I'll provide a complete, production-ready implementation for a Document Management System:
- Principals: Users (
user:alice) with roles (e.g., admin, editor).
- Resources: Documents (
document:doc123) with owner and sensitivity (public/confidential).
- Actions:
view, edit, delete.
- Rules: Owners can edit/delete; editors view/edit non-confidential; admins full access; group-based sharing.
We'll cover:
- Policy Modeling
- Integration & Decision Caching
- Audits
- Tests
I'll use OPA as primary (widely adopted, Kubernetes-native) and Cedar as alternative (AWS-native, simpler syntax). Code is in Go (common for services) but adaptable.
1. Policy Modeling
OPA (Rego)
Save as auth.rego:
package authz
import future.keywords.if
import future.keywords.in
default allow = false
# Input: {"principal": "user:alice", "action": "view", "resource": "document:doc123", "context": {"roles": ["editor"], "owner": "user:alice", "sensitivity": "public"}}
allow if {
is_admin
} else if {
action == "view" # Everyone can view public docs; owners/admins any
sensitivity_is_public
} else if {
is_owner
} else if {
action == "edit" # Editors can edit non-confidential if owner or shared
roles[_] == "editor"
not sensitivity_is_confidential
} else if {
action == "delete" # Only owners/admins
is_owner
}
is_admin if "admin" in input.context.roles
is_owner if input.context.owner == input.principal
sensitivity_is_public if input.context.sensitivity == "public"
sensitivity_is_confidential if input.context.sensitivity == "confidential"
Bundle it for distribution: Use opa build -b . -o bundle.tar.gz.
Cedar (Alternative)
Cedar policies are entity-based. Define in policies.cedar:
permit(
principal == ?User::"alice" or principal in User::"group:editors",
action,
resource
)
when { resource.entityType == Document::"*" };
permit(
principal in User::"*",
action == Action::"view",
resource
)
when {
resource.context.sensitivity == "public"
};
permit(
principal,
action in [Action::"edit", Action::"delete"],
resource
)
when { resource.context.owner == principal };
permit(
principal in AdminGroup::"*",
action,
resource
); # Full admin access
Entities (JSON schema for resources/principals) go in a separate file, e.g., entities.json.
2. Integration & Decision Caching
OPA Integration (Go SDK)
Install: go get github.com/open-policy-agent/opa/sdk
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/open-policy-agent/opa/sdk"
"github.com/open-policy-agent/opa/sdk/test"
)
type AuthInput struct {
Principal string `json:"principal"`
Action string `json:"action"`
Resource string `json:"resource"`
Context map[string]interface{} `json:"context"`
}
func main() {
ctx := context.Background()
// Initialize OPA with bundle (policies), enable caching & logging
o, err := sdk.New(ctx, sdk.Options{
ID: "authz",
Config: sdk.Config{DecisionCache: sdk.NewSimpleCache(1000, 5*time.Minute)}, // LRU cache: 1000 entries, TTL 5min
})
if err != nil {
log.Fatal(err)
}
defer o.Shutdown(ctx)
// Pull bundle (in prod: use server-side bundle activation)
if err := o.UpdateBundle(ctx, sdk.BundleConfig{Name: "authz/bundle"}); err != nil {
log.Fatal(err)
}
// Handler for auth decisions
http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
var input AuthInput
json.NewDecoder(r.Body).Decode(&input)
// Query OPA (cached automatically via SDK)
rs, err := o.Decision(ctx, sdk.DecisionOptions{
Input: input,
Path: "/authz/allow",
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
result := rs.Result
if result != nil && result.(bool) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "ALLOWED")
} else {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintln(w, "DENIED")
}
})
log.Println("Server on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Decision Caching:
- OPA SDK: Built-in
DecisionCache (LRU, TTL). Keys: (package, input-hash).
- Advanced: Redis for distributed cache: Use
github.com/open-policy-agent/opa/rego with custom cache.
- Hit Rate: Monitor via Prometheus metrics (
opa_decision_cache_hits_total).
Cedar Integration (AWS Cedar JavaScript SDK example, adaptable to Go via AWS SDK):
const { Cedar } = require('@aws-policy/citrus');
const cedar = new Cedar({ cacheSize: 1000 }); // Built-in LRU
const decision = await cedar.isAuthorized({
principal: { entityType: 'User', entityId: 'alice' },
action: { entityType: 'Action', entityId: 'view' },
resource: { entityType: 'Document', entityId: 'doc123' },
context: { sensitivity: 'public' }
}, { entities: entitiesJson }); // Cache: TTL via config
3. Audits
OPA
Enable Decision Logs (JSON-structured):
- In
opa run or SDK: Set Services in config.yaml:
services:
- name: audit
url: https://logs.example.com # e.g., ELK, Splunk
decision_logs:
service: audit
- Logs include:
input, result, decision_id, timestamp, bundle.
- Query:
opa eval --decision-log-inputs=off data.authz.allow -i input.json.
- Prod: Use OPA Gatekeeper for K8s audits.
Cedar
- AWS Verified Permissions: Built-in CloudWatch logs + audit events.
- Custom: Log
decision.trace from SDK.
Best Practice: Store in immutable sink (S3 + Athena) for compliance. Use decision_id for tracing.
4. Tests
OPA (Rego Tests)
In test.rego (run with opa test .):
test_allow_view_public {
allow == true with input as {"principal": "user:alice", "action": "view", "resource": "document:doc123", "context": {"roles": ["editor"], "owner": "user:alice", "sensitivity": "public"}}
}
test_deny_edit_confidential {
allow == false with input as {"principal": "user:alice", "action": "edit", "resource": "document:doc123", "context": {"roles": ["editor"], "owner": "bob", "sensitivity": "confidential"}}
}
test_allow_admin {
allow == true with input as {"principal": "user:admin", "action": "delete", "resource": "document:doc123", "context": {"roles": ["admin"], "owner": "bob", "sensitivity": "confidential"}}
}
Coverage: opa test ./ --count.
Cedar Tests
Use Cedar CLI: cedar test policies.cedar --entities entities.json:
// test.json
[
{"testName": "View public", "expected": "Permit", "principal": "...", "action": "view", "resource": "..."}
]
Deployment & Best Practices
- OPA: Run as sidecar (
opa run --server --addr=localhost:8181), bundle via GitOps (ArgoCD/Flux).
- Cedar: AWS Verified Permissions service (serverless).
- Performance: <1ms/query with caching; scale horizontally.
- Migration: Rego → Cedar via tools like
cedar-to-rego.
- Monitoring: OPA metrics endpoint (
/metrics), alerts on cache miss >20%.
- Security: Validate inputs, use least-privilege bundles.
Test locally: opa run for OPA, cedar validate for Cedar. Full repo template: TrailblazerLabs/authz-example (hypothetical).
Questions? Let's debug or extend! 🕵️