On a Thursday afternoon an auditor reviews the underwriting decisions of the week and finds one that should not exist. Submission SUB-1004 belongs to unit commercial-west and is assigned to underwriter u-uw-w1. The decision on it was recorded by u-uw-w2, the peer underwriter of the same unit, who is assigned to SUB-1007 and not to this one. The current authorization policy refuses exactly that: only the assigned underwriter may record a decision.
So which rule allowed it? The platform team checks the policy repository: the assignment check is there, merged weeks ago. They check the decision service: three replicas, two running the current policy authz-2026.11.1, one still running the previous release authz-2026.10.3, which had no assignment check. The request happened to land on the old one. The audit record says "allow". If it did not also say which policy version decided, nobody could have found the stale replica.
This is this site's own case UW-A09, and it is the reason this page exists. Once authorization rules leave scattered if statements and become a policy that one team writes and many services evaluate, the policy has the problems of any software: versions, releases, tests, owners, drift and logs. The rule itself can be written in many languages. This page writes one rule six ways, all of which ran, and then deals with what happens around it.
What "policy as code" means#
Authorization rules can live in three places: hidden inside application code next to the business logic, in a console where someone clicks permissions together, or in files that are written in a language made for rules, kept in version control, reviewed, tested and released. The third is policy as code. A tiny example: a Rego file in a Git repository that says a broker may read a quote only when the quote's tenant equals the broker's tenant, with a test next to it that proves the cross-tenant read is denied.
The point is not the language. The point is that the rule becomes an artefact with a name and a version, which a person other than its author can read, and which a machine can test before it reaches production.
Before AI. Backend teams have done this for years without the name. A Spring Security configuration class in the repository, with@PreAuthorizeexpressions and integration tests, is policy as code. So are Kafka ACLs managed in Terraform, LDAP group mappings kept in a reviewed file, and databaseGRANTscripts run by a migration tool. What changed is that dedicated policy engines now exist, so the rules can leave the application process.
The terms used below, briefly. A policy engine evaluates rules written in its own language: OPA (Open Policy Agent, a general-purpose engine whose language is Rego), Cedar (a policy language and engine with permit and forbid rules over typed entities), and OpenFGA (a relationship engine in the style of Google's Zanzibar paper, which answers "does this user have this relation to this object?"). The four roles of a decision, PEP, PDP, PIP and PAP, are on Enforcement; this page lives in the PAP.
The one rule#
Every implementation below enforces the same two parts of policy authz-2026.11.1, simplified on purpose so the six versions stay comparable:
| Part | Rule | Example facts |
|---|---|---|
| R-AZ-03 | A broker reads a quote only of their own tenant | u-broker-n1 (tenant brk-north) reads Q-5531: allow; Q-6620 (tenant brk-south): deny |
| R-AZ-09 | decision.record needs a person, role underwriter, same business unit, assignment to that submission, and strong authentication (acr = urn:insurer.example:acr:phishing-resistant) | u-uw-w1 on SUB-1004: allow; peer u-uw-w2: deny; u-uw-e1 (other unit): deny |
| R-AZ-09, never | An agent never records a decision, whatever scopes or entitlements it carries | wl-underwriting-agent with uw.decide: deny |
Left out of the five framework demos and kept in pdp.py: the uw.decide entitlement as a separate fact, the cockpit-only client, the 300-second maximum age of the step-up, delegation, and audit. The broker sees a quote, Q-5531; the insurer works the same record as submission SUB-1004; every version decides on the record.
Six engines, one rule#
Each tab shows the source as it is in examples/ and the result of a real run on 2026-11-18, with versions and the command. Every demo is synthetic; signing keys were generated at run time and never written to disk. The agent in the example is a scripted stand-in, so these results show how the access controls work, not how good any model is.
Python (pdp.py)
Application code. The rule as an ordinary function in the service's language, from examples/uw-auth/pdp.py. The block shows the decision.record branch of pdp.decide; the body is verbatim, and the function header is added so the block reads on its own (_d, POLICIES and the constants are defined in pdp.py).
def r_az_09_branch(action, subject, res, v, now, ptype, roles, unit, sub_id):
if action == "decision.record":
if ptype != "person":
return _d(False, 403, "R-AZ-09", "an agent or service principal never records an underwriting decision", v)
if "underwriter" not in roles:
return _d(False, 403, "R-AZ-09", "role underwriter required", v)
if "uw.decide" not in (subject.get("entitlements") or []):
return _d(False, 403, "R-AZ-09", "entitlement uw.decide required", v)
if res.get("business_unit") != unit:
return _d(False, 404, "R-AZ-09", "record belongs to another business unit: not found (existence not revealed)", v)
if POLICIES[v]["assignment_check"] and sub_id not in (subject.get("assignments") or []):
return _d(False, 403, "R-AZ-09", "underwriter is not assigned to " + str(sub_id), v)
if res.get("risk_tier") == "high" and HIGH_RISK_ENTITLEMENT not in (subject.get("entitlements") or []):
return _d(False, 403, "R-AZ-09", "risk tier high needs the entitlement " + HIGH_RISK_ENTITLEMENT, v)
if subject.get("client_id") != DECISION_CLIENT:
return _d(False, 403, "R-AZ-09", "decisions are accepted only through " + DECISION_CLIENT, v)
at = subject.get("auth_time")
recent = isinstance(at, int) and now - at <= STEP_UP_MAX_AGE_S
if subject.get("acr") != ACR_STRONG or not recent:
return _d(False, 401, "R-AZ-09", "step-up required: strong authentication within " + str(STEP_UP_MAX_AGE_S) + " s",
v, [AUDIT, "challenge: Bearer error=insufficient_user_authentication acr_values=" + ACR_STRONG
+ " max_age=" + str(STEP_UP_MAX_AGE_S)])
who = ("assigned underwriter" if POLICIES[v]["assignment_check"]
else "underwriter of the unit (this policy version does not check assignment)")
return _d(True, 200, "R-AZ-09", who + " decides through the cockpit after step-up",
v, [AUDIT, "record human_decision with decided_by"])
Command: /opt/homebrew/bin/python3 -m unittest test_pdp -v in a scratch copy (standard-library Python). Result: Ran 13 tests, OK. Strength: the full rule, with every reason, status and obligation. Weakness: the policy ships with the service, and only a Python reader can review it. Stays in your code: everything, which is the point and the risk.
Java (Spring Security)
Library: Spring Security 7.1.2 with Spring Boot 4.1.2. Method security calls a bean for the object-level check. From examples/frameworks/spring-security/, one method of UwController.java and one of UwAuthz.java (verbatim; imports and the data maps left out):
@PostMapping("/submissions/{submissionId}/decision")
@PreAuthorize("@uwAuthz.canRecordDecision(authentication, #submissionId)")
public Map<String, Object> recordDecision(@PathVariable String submissionId, @AuthenticationPrincipal Jwt jwt) {
return Map.of("submission_id", submissionId, "decided_by", jwt.getSubject(),
"policy_version", "authz-2026.11.1");
}
public boolean canRecordDecision(Authentication authentication, String submissionId) {
Jwt jwt = jwt(authentication);
Submission submission = SUBMISSIONS.get(submissionId);
return jwt != null && submission != null
&& "person".equals(jwt.getClaimAsString("principal_type")) // an agent never decides, whatever its scopes
&& roles(jwt).contains("underwriter")
&& submission.businessUnit().equals(jwt.getClaimAsString("business_unit"))
&& ASSIGNMENTS.getOrDefault(jwt.getSubject(), Set.of()).contains(submissionId)
&& ACR_STRONG.equals(jwt.getClaimAsString("acr"));
}
Command: ./run.sh <scratch-dir> (copies the project, then mvn -q test), JDK Temurin 23.0.1, Maven 3.9.16. Result: Tests run: 17, Failures: 0, Errors: 0, Skipped: 0, including peerUnderwriter_403, agentWithUwDecideScope_403, otherUnitUnderwriter_403 and assignedUnderwriterWeakAcr_403. Product (Spring Security, as documented on 2026-11-18): @EnableMethodSecurity enables @PreAuthorize, and a bean is referenced in the expression as @beanName.method(...). Differences on purpose: a weak acr answers 403 here, not a 401 step-up challenge, because a @PreAuthorize bean returns allow or deny only; and the other-unit underwriter gets 403, not 404. Stays in your code: the UwAuthz bean (the rule itself), the assignment data, and the step-up challenge.
Rego (OPA)
Engine: OPA 1.22.4, Rego v1. The rule as data-free policy; the application sends what it knows as input. From examples/frameworks/opa/policy/uw_authz.rego (excerpt: the R-AZ-03 rule and the status, reasons and decision rules are left out; lines shown are verbatim):
package uw.authz
default allow := false
policy_version := "authz-2026.11.1"
acr_strong := "urn:insurer.example:acr:phishing-resistant"
scopes contains s if some s in split(input.subject.scope, " ")
# R-AZ-09: decision.record needs a person, role underwriter, same unit, assigned, strong authentication.
allow if {
input.action == "decision.record"
"uw.decide" in scopes
input.subject.principal_type == "person"
"underwriter" in input.subject.roles
input.resource.business_unit == input.subject.business_unit
input.subject.sub in input.resource.assigned_underwriters
input.subject.acr == acr_strong
}
Command: ./run.sh (each step a docker run --rm of openpolicyagent/opa:1.22.4). Result: check: ok for opa check --strict, PASS: 10/10 for opa test -v, and this opa eval of data.uw.authz.decision for the peer underwriter's input:
== opa eval: uw-w2-decides-SUB-1004.json ==
{
"allow": false,
"policy_version": "authz-2026.11.1",
"reasons": [
"not assigned to this submission"
],
"status": 403
}
Stays in your code: token validation, loading the record, sending assigned_underwriters in input, and enforcing the answer. OPA cannot know an assignment you did not send. Checked how far: the Rego was checked by opa check --strict and tested by opa test in that run; the build of this site does not check Rego.
Cedar
Engine: Cedar, through cedarpy 4.12.2 (the cedarpy README maps it to Cedar engine 4.12.0). permit rules plus a forbid that wins over any permit. From examples/frameworks/cedar/uw.cedar (excerpt: the R-AZ-03 permit is left out):
@id("R-AZ-09 assigned underwriter records a decision after step-up")
permit (
principal is Person,
action == Action::"decision.record",
resource is Submission
)
when {
principal.roles.contains("underwriter") &&
principal has business_unit &&
principal.business_unit == resource.business_unit &&
resource.assigned_underwriters.contains(principal) &&
context.scopes.contains("uw.decide") &&
context.acr == "urn:insurer.example:acr:phishing-resistant"
};
// Belt and braces: even if someone later widens the permit above, an agent never records a decision.
@id("R-AZ-09 forbid agents")
forbid (
principal is Agent,
action == Action::"decision.record",
resource
);
Command: ./run.sh <scratch-dir> (uv environment, uv pip install cedarpy, python run_cedar.py). Result excerpt:
validate uw.cedar against uw.cedarschema: passed=True errors=[]
validate deliberately wrong policy: passed=False
error: [policy0] for policy `policy0`, attribute `tenant` on entity type `Submission` not found
uw-w2 (peer, not assigned) decides SUB-1004 Deny Deny (none: default deny) ok
agent with uw.decide decides SUB-1004 Deny Deny ['R-AZ-09 forbid agents'] ok
Product (Cedar, as documented on 2026-11-18): "no request is authorized ... unless there is a specific permit policy that grants it", and "any satisfied forbid policy overrides it". Schema validation caught a typo (resource.tenant on a Submission) before any request was evaluated. Stays in your code: building the entities (tenant, unit, assignment) from your data, putting token facts in context, and mapping Deny to 404, 403 or a step-up challenge. The build of this site does not check Cedar; the run above validated it.
SQL (PostgreSQL RLS)
Product: PostgreSQL 18.7 row-level security. Only the tenant part of the rule fits here; the database filters rows by a per-transaction setting the application sets from the verified token. From examples/frameworks/postgres-rls/rls.sql (excerpt, statements in a different order from the file, which first shows the owner bypass before FORCE):
ALTER TABLE quotes ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON quotes
USING (tenant = current_setting('app.tenant', true))
WITH CHECK (tenant = current_setting('app.tenant', true));
ALTER TABLE quotes FORCE ROW LEVEL SECURITY;
BEGIN;
SET LOCAL ROLE uw_owner;
SET LOCAL app.tenant = 'brk-north';
SELECT quote_id, tenant FROM quotes WHERE quote_id = 'Q-6620';
COMMIT;
Command: ./run.sh (throwaway container postgres:18.7-alpine3.24, no published port, psql -X -e -f rls.sql). Result: the cross-tenant SELECT returns (0 rows); a cross-tenant INSERT fails with new row violates row-level security policy for table "quotes". Assignment, role and acr are not row facts, so R-AZ-09 does not belong here. Stays in your code: setting app.tenant from the verified token in every transaction, and connecting with a role that is subject to the policy. The owner, FORCE and superuser details are on Tenants. The SQL was executed in that run; the build of this site does not check SQL.
OpenFGA (relationships)
Engine: OpenFGA v1.22.1. Relationships instead of attributes: a decider is the assigned underwriter AND an underwriter of the submission's unit, and the assignment carries a condition on acr. From examples/frameworks/openfga/model.json:
{
"schema_version": "1.1",
"type_definitions": [
{"type": "user"},
{"type": "agent"},
{
"type": "business_unit",
"relations": {"underwriter": {"this": {}}},
"metadata": {"relations": {"underwriter": {"directly_related_user_types": [{"type": "user"}]}}}
},
{
"type": "submission",
"relations": {
"unit": {"this": {}},
"assigned_underwriter": {"this": {}},
"decider": {"intersection": {"child": [
{"computedUserset": {"relation": "assigned_underwriter"}},
{"tupleToUserset": {"tupleset": {"relation": "unit"}, "computedUserset": {"relation": "underwriter"}}}
]}}
},
"metadata": {"relations": {
"unit": {"directly_related_user_types": [{"type": "business_unit"}]},
"assigned_underwriter": {"directly_related_user_types": [{"type": "user", "condition": "strong_auth"}]}
}}
}
],
"conditions": {
"strong_auth": {
"name": "strong_auth",
"expression": "acr == 'urn:insurer.example:acr:phishing-resistant'",
"parameters": {"acr": {"type_name": "TYPE_NAME_STRING"}}
}
}
}
The block above is the decision part of the model; the full file also defines tenant and quote for R-AZ-03. Command: ./run.sh (local server on 127.0.0.1 only, in-memory, removed afterwards; Check over the HTTP API). Result excerpt:
write tuple agent:wl-underwriting-agent assigned_underwriter SUB-1004: HTTP 400 code=validation_error message=Invalid tuple 'submission:SUB-1004#assigned_underwriter@agent:wl-underwriting-agent'. Reason: type 'agent' is not an allowed type restriction for 'submission#assigned_underwriter'
u-uw-w2 decider SUB-1004 (peer, acr strong) 200 False False ok
u-uw-w1 decider SUB-1004 (NO context sent) 400 None code=validation_error message=failed to evaluate relationship condition: 'strong_auth' - tuple 'submission:SUB-1004#assigned_underwriter@user:u-uw-w1' is missing context parameters '[acr]'
The agent cannot even be written into the relation. The last line matters most: when the application forgot to send acr, OpenFGA returned an error, not allowed: false. Stays in your code: writing tuples when an assignment changes and deleting them when it ends, passing acr as context, and treating an error as deny.
Read side by side, every engine evaluates the rule and none of them knows the facts. Spring reads it from a map in the bean, OPA and Cedar receive it from the caller, OpenFGA stores it as a tuple someone must write and delete, and the database cannot express it at all.
Diagram: Six engines, one rule · what each needs from your application, decides, and leaves to you
Rows are the six implementations that ran. Read across a row: the first column is what the application must hand the engine, the second what the engine decides, the third what stays in your code. Read down the third column: token validation, the HTTP answer and treating an error as deny are never the engine's job.
- Application code
- verified subject + the record: The service builds the subject from validated claims and the directory, and loads the record.
- full R-AZ-09: Every condition of the rule, with a status code, a reason and obligations.
- everything: The rule ships with the service and only a Python reader can review it.
- Spring Security
- validated token + assignment map: The resource server validates the token; the bean reads claims and the application's assignment data.
- true or false: A boolean from the bean; a denial throws an exception answered 403.
- the rule, the data, the step-up answer: The bean is the rule. A 401 step-up challenge needs extra code; the demo answers 403.
- OPA / Rego
- input: claims + record facts: The enforcement point sends verified claims and the record's unit and assigned underwriters as input.
- allow, status, reasons, version: Default deny; the policy returns a decision object stamped with its version.
- token, facts, enforcement: OPA never sees a signature and cannot know an assignment you did not send.
- Cedar
- typed entities + context: The application builds Person, Agent and Submission entities and puts token facts in the context.
- Allow or Deny: Default deny, any satisfied forbid overrides permits, diagnostics name the deciding policies.
- entities, mapping to 404 or 401: Cedar answers Allow or Deny only; status codes and challenges are the application's.
- PostgreSQL RLS
- app.tenant per transaction: The application sets the tenant from the verified token as a transaction-local setting.
- which rows exist: Rows of other tenants are invisible; writes for another tenant are refused.
- roles, assignment, acr: None of R-AZ-09 is a row fact. The connection role must be subject to the policy.
- OpenFGA
- stored tuples + acr context: Assignments and memberships are written as tuples; acr is sent with each Check.
- allowed true or false: Answers whether the user has the relation; the agent type cannot even be written into the relation.
- tuple writes and deletes, error = deny: Missing condition context returns an error, not false. Treat it as deny.
| Engine | Label | How facts arrive | No matching rule | Missing input |
|---|---|---|---|---|
pdp.py | application code | the service loads them | deny (R-AZ-00) | deny, by the code's own checks |
Spring Security @PreAuthorize | library | the bean reads them | 403 (AccessDeniedException) | whatever the bean does: write it |
| OPA / Rego | engine | the PEP sends input | default allow := false | the expression is undefined, so the rule does not fire |
| Cedar | engine | entities and context from the caller | Deny | schema validation catches typos before deploy; a policy that errors at evaluation is skipped |
| PostgreSQL RLS | product feature | a per-transaction setting | zero rows (default deny with no policy) | current_setting(..., true) is NULL: zero rows |
| OpenFGA | engine | stored tuples plus request context | allowed: false | HTTP 400 error: treat as deny |
The last column is where engines differ in a way that bites. Product (OPA, as documented on 2026-11-18): "Expressions that refer to undefined values are also undefined. This includes comparisons such as !=." In the demo's Rego, the 404 rule for another tenant is written with !=; by reading the policy (this input was not run), an input without tenant makes it undefined, and the status falls through to 403. That is still a denial, but a forgotten field quietly changes which denial. Product (Cedar): a policy with an evaluation error "does not factor into the authorization response; it is skipped", which is safe for a permit and unsafe for a forbid you were counting on. Write a test for missing input in every engine you use.
Common confusion. A policy engine is not an authentication system. None of these engines checks a token signature. Product (Amazon Verified Permissions, as documented on 2026-11-18): it "presumes that the principal has been previously identified and authenticated through other means". The same holds for OPA, Cedar and OpenFGA: token validation happens before, in your code or your framework (see Tokens).
Versions, and the drift that started this page#
A policy version is a name for one exact text of the rules, released as a unit. In the example, pdp.POLICIES keeps two: authz-2026.11.1 with the assignment check on decision.record, and authz-2026.10.3 without it. The snippet below asks both versions about the peer underwriter's request from the opening. A successful run proves that the two versions disagree on exactly this request; it does not show how a stale replica happens in a real deployment.
import pdp
from clock import START_EPOCH_S as NOW
from directory import ACR_STRONG, resource_for, subject_for
peer = subject_for("u-uw-w2", now=NOW, acr=ACR_STRONG, auth_time=NOW, client_id="svc-cockpit-bff")
res = resource_for("SUB-1004", "submission")
for version in (pdp.CURRENT_POLICY, pdp.PREVIOUS_POLICY):
d = pdp.decide(peer, "decision.record", res, {"now": NOW}, version)
print(version, d["allow"], d["status"], d["rule"], "|", d["reason"])
print(pdp.POLICIES)
Run in a scratch copy on 2026-11-18:
authz-2026.11.1 False 403 R-AZ-09 | underwriter is not assigned to SUB-1004
authz-2026.10.3 True 200 R-AZ-09 | underwriter of the unit (this policy version does not check assignment) decides through the cockpit after step-up
{'authz-2026.11.1': {'assignment_check': True, 'note': 'current'}, 'authz-2026.10.3': {'assignment_check': False, 'note': 'previous: no assignment check on decision.record'}}
Notice the old version's reason: it says the version does not check assignment, rather than claiming the underwriter is assigned, and test_old_policy_reason_does_not_claim_assignment holds it to that.
Policy drift is the state where the policy that decides is not the policy you think is deployed: a replica on an old bundle, a service that vendored an old copy of the library, a hotfix applied in one environment only. It is invisible in the decision itself. Allow looks like allow. It becomes visible only if every decision records its version, and if something compares the versions in use with the version released.
Diagram: Policy drift · two replicas, two versions, one decision log (UW-A09)
Time runs down the page. The peer underwriter's decision request is load-balanced. A replica on the current version authz-2026.11.1 refuses it. A replica still on authz-2026.10.3 allows it. Both decisions are recorded with the rule and the version, so the auditor's query finds the stale replica.
- Cockpit backend (PEP) to Decision replica A authz-2026.11.1: decide (09:10). First attempt lands on replica A.
- Decision replica A authz-2026.11.1 to Cockpit backend (PEP): deny 403. The current version checks assignment.
- Cockpit backend (PEP) to Decision replica C authz-2026.10.3: decide (09:12). A retry lands on the stale replica.
- Decision replica C authz-2026.10.3 to Cockpit backend (PEP): allow 200. The old version lets any underwriter of the unit decide.
- Cockpit backend (PEP) to Decision log: both decisions + versions. Each record names the rule and the version that decided.
- Auditor to Decision log: allows not on the released version. A one-line query finds every decision made by a stale version.
The policy lab opens on the drift preset: the peer underwriter after step-up, the same request, with the deployed version set to authz-2026.10.3. Switch the version and watch the decision and the deciding line change.
| Subject | Request | authz-2026.11.1 | authz-2026.10.3 | Reason (current) |
|---|---|---|---|---|
| peer underwriter u-uw-w2, cockpit, step-up now | decision.record SUB-1004 | deny 403 (R-AZ-09) | allow 200 (drift) | underwriter is not assigned to SUB-1004 |
| assigned underwriter u-uw-w1, cockpit, step-up now | decision.record SUB-1004 | allow 200 (R-AZ-09) | allow 200 | assigned underwriter decides through the cockpit after step-up |
| u-uw-w1, basic login 600 s ago | decision.record SUB-1004 | deny 401 (R-AZ-09) | deny 401 | step-up required: strong authentication within 300 s |
| underwriting agent with a misgranted cockpit client | decision.record SUB-1004 | deny 403 (R-AZ-09) | deny 403 | an agent or service principal never records an underwriting decision |
Only one row differs between the versions, which is what the release note and a test should pin.
Common confusion. Two different "policy versions" run through this example.UW-GUIDE 2026.2is the business policy, the underwriting rules the model and the rules engine cite.authz-2026.11.1is the authorization policy, which decides who may do what. They are released, owned and logged separately.
Tests: what a policy suite must prove#
A policy test is a small, deterministic check: given this subject, action, resource and context, the answer is this. The example's suites ran on 2026-11-18: test_pdp (13 tests, OK) and opa test -v (PASS: 10/10, for example test_peer_underwriter_denied_403). Product (OPA, as documented on 2026-11-18): tests are Rego rules prefixed test_; opa test also supports --coverage.
A useful policy suite has five kinds of test, and the negative ones matter most:
| Kind | Example from this site | Why |
|---|---|---|
| The intended allow | assigned underwriter with strong acr records a decision | the rule is not so strict that work stops |
| One negative per condition | peer (assignment), other unit, weak acr, wrong client, agent | removing any single condition makes a test fail |
| Unknowns | unknown action, unknown policy version, unknown record | deny by default really is the default |
| Missing input | no acr sent to OpenFGA; no tenant in Rego input | missing data ends in deny, and in the denial you expect |
| Version difference | authz-2026.10.3 allows the peer, authz-2026.11.1 does not, nothing else changes | a release changes only what its note says |
The "one negative per condition" row is the test design that would have caught authz-2026.10.3 before release: a test named "peer underwriter is denied" fails against a policy without the assignment check. Cross-tenant tests for the data layer are on Tenants; the full negative suite of the site is on Threats and tests.
Decision logs: the version that decided#
A decision log records each authorization decision: who asked, about what, the answer, why, and under which policy version. It is the evidence the auditor in the opening needed. Here is the record the example writes for the drifted decision, from the scratch run of the cockpit with the old version:
{
"acr": "urn:insurer.example:acr:phishing-resistant",
"action": "decision.record",
"authz_policy_version": "authz-2026.10.3",
"decision": "allow",
"kind": "authz.allow",
"principal_id": "u-uw-w2",
"reason": "underwriter of the unit (this policy version does not check assignment) decides through the cockpit after step-up",
"request_id": "req-authz-2026.10.3",
"resource": "SUB-1004",
"rule": "R-AZ-09",
"run_id": null,
"seq": 2,
"span_id": "534c22632612c62e",
"time": "2026-11-18T09:00:00Z",
"trace_id": "87facf76911133d9e46c4917608be1b9"
}
With authz_policy_version and rule in the record, the auditor's question has a one-line answer: the old version allowed it. The hash-chain fields (prev_hash, hash) are left out of the block above; the example's integrity scheme is on Audit.
Engines have their own logs. Product (OPA, as documented on 2026-11-18): a decision log event carries decision_id, input, result, bundles (the bundle revision at evaluation time), path and timestamp; before upload OPA queries data.system.log.mask so a mask policy can erase or replace fields, and a drop rule can keep matching decisions out of the log. The bundles revision is OPA's version of authz_policy_version. The input field is the risk: it holds whatever the PEP sent, so a PEP that sends a raw token in input puts the token in the log unless a mask removes it. This site's recommendation: never send tokens to a policy engine at all; send validated claims, and mask anything personal the decision does not need to explain.
Ownership and review#
Who may change R-AZ-09? If the answer is "anyone who can merge to the service", the policy is not administered. A policy owner is a named team that approves every change to a rule set, independent of the services that evaluate it.
Pattern: keep authorization policy in its own directory or repository, with a code owner rule requiring the policy owner's review, tests that must pass before merge, and a version name stamped into the policy (as the Rego demo does with policy_version). The data's business owner approves changes in meaning; the security team approves changes in mechanism: separation of duties for the rules themselves (see Governance).
In a coding agent. A coding agent may propose a change touw_authz.regoin a pull request. It must not merge it. Branch protection requires the policy owner's review and a greenopa test, and the agent's repo-scoped GitHub App installation has no right to bypass either. The agent writes a suggestion; a person with merge rights decides. Shipping that change is the subject of Diff to Deploy.
What evaluation costs#
Evaluating a small rule set is rarely the slow part of a request. What costs time is getting the facts to the engine (the record, the assignment lookup, a relationship graph walk) and, for a remote engine, the network hop. Product (OpenFGA, as documented on 2026-11-18): conditions are evaluated in Google CEL "with a max evaluation cost of 100 by default", a guard against expensive expressions. This page gives no timings: none were measured, and figures from vendor pages do not transfer to your rules and data. Measure with your own policies, under your own load, and keep the policy suite fast enough to run on every commit.
Choosing where the rule lives#
| Situation | Simplest credible choice | Grow when | Alternatives |
|---|---|---|---|
| One service, rules owned by its team | Application code or Spring @PreAuthorize with a bean, plus tests | a second service needs the same rule | a shared library with a version |
| Many services, one policy team | OPA or Cedar, policy in its own repository, versioned bundles | facts are relationships no service owns | a central PDP service |
| Sharing, delegation, hierarchies ("member of the tenant that owns the quote") | OpenFGA-style relationship engine | relationship writes become a consistency problem | relationships in your own tables with a SQL check |
| Tenant isolation at the data layer | PostgreSQL RLS as a backstop under the service's check | per-tenant compliance needs | schema or database per tenant (see Tenants) |
None of these replaces another. The example uses application code for the full rule, a tenant predicate in the repository, and could add RLS beneath it. Pick the engine whose model matches the shape of your rules (attributes, relationships, rows), and keep the facts flowing from the systems that own them.
What this is not. This page does not rank engines or compare products in depth. Each engine, library and product gets its own neutral section on Frameworks, with versions and documentation links. The access-control models themselves (RBAC, ABAC, ReBAC) are on Access models.
Security notes#
- Treat an engine error, a timeout and an undefined result as deny, in the PEP's code (OpenFGA's 400 for missing context is the example).
- Never send raw tokens or secrets to a policy engine; send validated claims, and mask decision logs.
- Stamp the version into the policy and into every decision record.
- Facts that change during the day (assignments) come from their owner at decision time, not from token claims.
- Write a
forbid-style rule for "never" cases (an agent never decides), so a later widening of apermitcannot undo it.
Monday checklist#
- Find your authorization rules. List every place a rule lives: annotations,
ifstatements, gateway config, database grants. - Every decision record has
ruleand policy version fields. Query last week's allows for versions other than the released one. - One negative test per condition of each sensitive rule, plus a missing-input test per engine.
- A named owner and a required review for the policy directory.
- A deploy check that fails when any replica reports a policy version other than the released one.
Exercises#
Exercise 1. The Spring demo answers 403 when the underwriter's acr is weak, while pdp.py answers 401 with a step-up challenge. Which is right, and where would you change the Spring code?
Answer401 with a challenge; outside the boolean bean
The 401 challenge tells the client what to do (sign in again with a stronger method), so it is the better answer. A @PreAuthorize bean returns only true or false; the challenge needs code that distinguishes "weak authentication" from "not allowed" and writes the WWW-Authenticate header, for example a denied-invocation handler that inspects why the bean said no.
Exercise 2. A team moves R-AZ-09 to OpenFGA and their PEP code is if response.get("allowed") is False: return 403. What happens when they forget to pass acr after a refactor?
AnswerFail open on the 400
OpenFGA returns HTTP 400 with no allowed field, so allowed is None, the condition is false, and the request passes. Allow only when allowed is True and the status is 200.
Exercise 3. Your decision records carry the policy version. Write the one-line query that would have found the drift in the opening.
AnswerAllows where the version is not the released one
All records with kind = authz.allow and authz_policy_version != 'authz-2026.11.1' since the release time of authz-2026.11.1. Every hit is either drift or a decision made before the rollout finished.
Advanced perspective#
Rolling out a policy version safelyShadow, compare, switch, retire
A policy change is a change in production behaviour, and it can be rolled out like one. Evaluate the new version in shadow next to the current one, for the same requests, and log both answers without enforcing the new one. Every disagreement is either the intended change (the peer underwriter's decision) or a surprise. Only when the disagreements match the release note do you switch enforcement, and only after every replica reports the new version do you retire the old one. The example's two versions differ on exactly one row of the policy lab; a shadow run that shows two differing rows is a stop signal. Keep "merged", "deployed to all replicas" and "enforcing" as three separate states, each with its own check.
What the engine decides, what the domain decidesKeep business rules out of the authorization policy
It is tempting to move every rule into the engine: "only approve if roof age is under 15 years". That is business policy (UW-GUIDE), not authorization, and it belongs in the underwriting rules engine with its own owner. The authorization policy answers "may this principal perform this action on this record now"; the domain decides what the action means and whether its content is valid. Mixing them puts underwriting rules under the security team's review and security rules under the business owner's, and neither review is then competent. A clean test: if the rule would still apply when a person does the work by hand in the cockpit, and it is about who, it is authorization; if it is about what the right answer is, it is domain logic.
Relationship engines: consistency and the forgotten deleteA tuple outlives the assignment unless someone removes it
In OpenFGA the assignment of SUB-1004 to u-uw-w1 is a stored tuple. When the team lead reassigns the submission, two writes must happen: delete the old tuple and write the new one. If the delete fails or is never coded, the old assignee keeps decider rights indefinitely, and no token expiry will end it. Treat tuple writes as part of the business transaction (an outbox that retries until both are applied), reconcile tuples against the system of record on a schedule, and alert on drift between them. Product (OpenFGA, as documented on 2026-11-18): Check accepts a consistency option and contextual_tuples for facts sent with the request instead of stored; sending the current assignment as a contextual tuple avoids the stale-tuple problem at the cost of a lookup in the PEP.
In one breath#
The same rule fits in application code, Spring Security, Rego, Cedar, a PostgreSQL policy and an OpenFGA model, and all six ran here with the same answers on the peer underwriter and the agent. In every one of them, the engine evaluates and your application supplies the facts, validates the token, chooses the HTTP answer and treats an error as deny. Policy becomes software: a version stamped in the rules and in every decision record, tests with one negative per condition, a named owner, and a check that every replica runs the released version. UW-A09 was found because the log named authz-2026.10.3.
The policy now decides the peer underwriter correctly, and the repository adds a tenant predicate beneath it. But a single WHERE tenant = ? is a thin wall between two brokerages sharing one table, and owners, superusers and service accounts can walk around it. Tenants looks at that wall: shared tables, row-level security, schemas and separate databases, and the tests that prove no broker ever reads another brokerage's quote.