Implementing Policy-Based Access Control
1. Understanding Policy-Based Authorization
| Aspect | Detail |
|---|---|
| Definition | Decisions made by evaluating declarative policies |
| Separation | Policy logic separate from business code |
| Modes | Embedded library, sidecar, central service |
| Benefit | Centralized governance, auditable |
2. Writing Authorization Policies
| Style | Example Engine |
|---|---|
| Declarative DSL | Rego (OPA), Cedar (AWS) |
| Expression | CEL (Google) |
| Config | Casbin (model + policy CSV) |
| Code | Spring Security SecurityExpressionRoot |
3. Using Policy Decision Points
| Deployment | Pros / Cons |
|---|---|
| Library (in-process) | Fastest; tied to app lifecycle |
| Sidecar | Independent updates; +1 RTT |
| Central service | Single source of truth; network latency |
| Edge | Cloudflare Workers / Lambda@Edge for low-latency |
4. Implementing Policy Enforcement Points
| Layer | Pattern |
|---|---|
| API gateway | Enforce coarse-grained per route |
| Service middleware | Method-level annotations |
| Database | Row-level security (RLS), views |
| UI | Render guards (UX only) |
5. Using Open Policy Agent
Example: OPA bundle + REST query
curl -X POST http://opa:8181/v1/data/authz/allow \
-d '{"input": {"user":{"role":"admin"}, "action":"delete", "resource":{"type":"order"}}}'
# {"result": true}
| Feature | Detail |
|---|---|
| Language | Rego (declarative datalog-like) |
| Distribution | Bundles via HTTP/S3/GCS |
| Decision logs | Streamed for audit |
6. Implementing Casbin
Example: Casbin RBAC with domains
# model.conf
[request_definition]
r = sub, dom, obj, act
[policy_definition]
p = sub, dom, obj, act
[role_definition]
g = _, _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.obj == p.obj && r.act == p.act
7. Creating Fine-Grained Policies
| Practice | Detail |
|---|---|
| Per-resource | Object-level rules (owner, classification) |
| Per-action | Different rules per CRUD operation |
| Contextual | Time, IP, device, MFA strength |
| Composable | Reusable predicates |
8. Implementing Policy Versioning
| Mechanism | Detail |
|---|---|
| Source control | Policies in Git; PR review |
| Tagged bundles | OPA bundle revisions |
| Canary rollout | Subset of PDPs first |
| Rollback | One-command revert to previous bundle |
9. Testing Authorization Policies
Example: OPA Rego unit test
package authz_test
import data.authz
test_admin_can_delete if {
authz.allow with input as {"user":{"role":"admin"}, "action":"delete"}
}
test_user_denied if {
not authz.allow with input as {"user":{"role":"user"}, "action":"delete"}
}
10. Caching Policy Decisions
| Strategy | Detail |
|---|---|
| Decision cache | Key on (sub, action, resource, env-digest) |
| TTL | Seconds (must respect env changes) |
| Invalidate | Policy bundle update, user role change |
| Negative cache | Cache denies briefly to absorb attacks |