← Writing

Policy-based access control · Part 2 of 2

Building a Policy EngineConditions, Masking, List Filters and an Editor

Part 2: combining policies attached at five levels, conditions that survive missing data, masked fields and how they still leak, compiling policies to SQL, and an editor non-engineers can trust.

Oct 24, 2026 · 30 min read

Part 1 looked at how AWS, Google Cloud, Kubernetes, Cedar and XACML turn a pile of policies into one answer. This part builds one.

The big systems agree on more than their documentation suggests. Strip away the syntax and the consensus from part 1 fits in one line:

Default deny, deny overrides allow, and restrictions are a different kind of thing from grants.

That line is the foundation, but it isn’t the hard part. The hard part is what the cloud providers never have to deal with: policies written by your customers’ managers at five different levels, records with fields missing, screens that hide half a record, and list pages that need the same rules as a WHERE clause.

The examples continue with Cliniq, the made-up chain of clinics from part 1:

01Combining policies from many places

Every system in part 1 had to answer the same question: when several policies apply, which one wins? In your product the question gets harder, because the policies don’t just come from one console. At Cliniq they come from five levels, written by five kinds of people:

Five levels, five different authors. The combining rule decides what happens when they disagree.

Each of those people is reasonable, and they don’t talk to each other. The clinic manager doesn’t know what compliance wrote. The combining rule is how the system settles their disagreements without a meeting. The strategies from part 1 each fail somewhere:

No strategy is free. The question is which surprise you can live with.

The shape that holds up

The big systems converge on one shape, and it’s the one I’d build:

The shape AWS, Google and Cedar share, written down as a rule you can hold everyone to.
  1. Grants add up. A permit at any level can give access. Two permits never conflict; they just both apply.
  2. Restrictions cut, and lower levels can’t loosen them. A forbid at the organisation level holds in every clinic. A clinic manager can add their own forbids but can’t lift one from above.
  3. Exceptions live inside the restriction. The emergency exception to the psychiatry rule is an unless clause on that rule, owned by whoever owns the rule. It isn’t a permit somewhere else that happens to outrank it. That’s Google’s exceptionPrincipals and Cedar’s unless.
  4. Unknown never lets anyone in. A grant whose condition can’t be evaluated doesn’t grant. A restriction whose condition can’t be evaluated still restricts.

With these four rules the result doesn’t depend on order, on who saved last, or on which level is “more specific.” You can explain any decision by listing the grants that matched and the restrictions that didn’t.

Attaching a policy is scoping it

One more rule makes multi-level policies safe: a policy only ever applies below the place it’s attached. A clinic manager at Indiranagar who writes “front desk can read records” should grant that at Indiranagar, and nowhere else, even if they forgot to say so. Don’t trust authors to add the scope. Add it when the policy is evaluated:

// A policy saved at a clinic only ever applies inside that clinic.
function scoped(policy: Policy): Condition {
  if (policy.attachedTo.kind === "organisation") return policy.when;
  return {
    all: [
      { attr: "resource.ancestors", op: "contains", value: policy.attachedTo.id },
      policy.when,
    ],
  };
}

Pair that with Kubernetes’ escalation rule: someone can only grant actions they hold themselves, and only at levels they administer. Then an Indiranagar manager can’t hand out a permission they don’t have, or hand it out at Koramangala. Those two rules together are what let you give customers a policy editor without giving them a way to become administrators.

02Designing your own

Here is a policy engine for Cliniq, small enough to read in one sitting and complete enough to run. It has four parts: a schema, a policy format, a source for attributes, and one function that decides.

1. A schema before any policy

Declare the attributes policies may use, with types, in code. A policy that mentions resource.noteTyp should be rejected when it’s saved, not discovered at 2 a.m. when it silently never matches. This is the same job Cedar’s schema does.

export const schema = {
  principal: { id: "id", roles: "set<string>", clinicId: "id", shift: "window" },
  record: {
    id: "id",
    clinicId: "id",
    patientId: "id",
    noteType: "enum<general|lab|psychiatry>",
    treatingPsychiatristId: "id?",          // optional: may be missing
  },
  context: { minuteOfDay: "int", mfa: "bool", emergency: "bool" },
} as const;

export const actions = ["record.read", "record.update", "record.export"] as const;

2. Policies as data

If customers or admins will write policies through a screen, store them as a JSON condition tree. It’s easy to validate against the schema, easy to render as a form, and, as we’ll see, easy to compile to SQL:

{
  "id": "doctors-own-clinic",
  "effect": "permit",
  "actions": ["record.read"],
  "resourceType": "record",
  "attachedTo": { "kind": "organisation" },
  "when": {
    "all": [
      { "attr": "principal.roles", "op": "contains", "value": "doctor" },
      { "attr": "resource.clinicId", "op": "eq", "ref": "principal.clinicId" },
      { "attr": "context.minuteOfDay", "op": "within", "ref": "principal.shift" }
    ]
  },
  "obligations": [
    { "type": "mask", "field": "patient.phone", "level": "last4" }
  ]
}

If only engineers write policies, embedding Cedar is a strong alternative: you get the language, the validator and the analysis without building them. Either way, keep the format behind one interface so you can switch later.

3. Attributes from sources you trust

The caller chooses what to ask. It never gets to describe itself.

The rule from part 1’s anatomy section, made concrete. The principal’s attributes come from your identity service, usually cached per user with a version number so changes take effect on the next request. The resource’s attributes come from the record the API handler just loaded, which it had to load anyway. Context comes from the server: its clock, the session’s MFA state. If an attribute arrives in the request body, it’s a claim, not a fact.

4. One function that decides

type Decision = {
  allowed: boolean;
  policies: string[];        // which policies decided it
  obligations: Obligation[]; // what the PEP must do along with it
  reason: string;
};

export function decide(req: AccessRequest, index: PolicyIndex): Decision {
  const { permits, forbids } = index.candidates(req.action, req.resource.type);
  const { principal, resource, context } = req;
  const env = { principal, resource, context };

  // Restrictions first. Anything not definitely false blocks, so a
  // restriction that can't be evaluated still restricts.
  for (const p of forbids) {
    const r = evaluate(scoped(p), env);
    if (r !== false) {
      const why = r === null ? "could not be checked" : "restricts this";
      return deny([p.id], `${p.id} ${why}`);
    }
  }

  // Then grants. Only a definite true grants.
  const granted = permits.filter(p => evaluate(scoped(p), env) === true);
  if (granted.length === 0) return deny([], `no policy grants ${req.action}`);

  return {
    allowed: true,
    policies: granted.map(p => p.id),
    obligations: mergeObligations(granted),
    reason: `granted by ${granted.map(p => p.id).join(", ")}`,
  };
}

That’s the whole combining rule from the first section in twenty lines: forbids override, permits add up, unknown never lets anyone in, and every answer carries the policies that produced it. The reason isn’t decoration. It’s what you log, what support reads, and what the “why can’t I?” screen shows.

index.candidates matters for speed. A product with a few thousand policies shouldn’t evaluate all of them per request. Index them by action and resource type, which is exactly why Cedar separates a policy’s scope from its when clause. Then a request touches the handful of policies that could possibly apply.

The interesting part is evaluate, and specifically what it returns when an attribute is missing. That gets its own section.

03Conditions, done properly

Conditions are where a policy engine is either trustworthy or quietly wrong. The operators are the easy part. The hard part is everything around them: which attributes a condition may read, what happens when one is missing, and what “now” means.

Operators and limits

Give each attribute type its operators and nothing else: eq and ne for ids and enums, in for lists, lt through gte for numbers, money and dates, contains for sets, within for time windows. Combine them with all, any and not. Cap the size, say twenty comparisons and three levels deep, because every condition will also have to become a SQL WHERE clause, and an unbounded tree becomes an unbounded query. No regular expressions and no calls out to other services.

Four things a condition can read

  • principal.*: the person or service asking, from your identity service.
  • resource.*: the record as it is stored now.
  • next.*: the record as it would be after the change. Only for updates.
  • context.*: the time, the session, a declared emergency.

next is the one most systems forget. Anil may update records at his clinic. A request changes a record’s clinicId from Koramangala to Indiranagar. Checking only the stored record says yes, since it’s at his clinic. But the result is a record at a clinic he has no rights over, which he has effectively given away. An update has to be allowed for the record before and after:

export function decideUpdate(req: UpdateRequest, index: PolicyIndex) {
  const next = { ...req.resource, ...req.changes };
  const before = decide({ ...req, resource: req.resource }, index);
  if (!before.allowed) return before;
  // The same rules, applied to the record as it would be afterwards.
  const after = decide({ ...req, resource: next }, index);
  if (after.allowed) return before;
  return deny(after.policies, `the result is outside your access: ${after.reason}`);
}

The missing-attribute trap

Cliniq imports old records from a clinic it acquired. Some arrive with no noteType. There’s a policy that front desk staff may read records whose note type isn’t psychiatry. Should Riya see one of those records?

Front desk may read records whose note type isn’t psychiatry. This record has no note type.

Four honest implementations, two answers. The JavaScript and AWS answers both come from treating “not equal” as true when there’s nothing to compare. AWS documents this behaviour for its negated operators, and it’s why its ...IfExists and Null operators exist. It’s the safe direction for a deny and the dangerous one for an allow.

The worst version is when your own system gives both answers. If the detail endpoint evaluates the rule in JavaScript and the list endpoint compiles it to SQL, Riya won’t see the record in her list, but she can open it by its URL. Nobody wrote a bug; two layers just disagree about nothing.

Three values, the same as SQL

The fix is to stop pretending a missing value is a value. A comparison with a missing side is unknown, for every operator, including ne and not in. Then decide what unknown means for each kind of policy:

Unknown is never the answer that lets someone in.

This is three-valued logic, the same logic SQL uses for NULL. all is false if any part is false, otherwise unknown if any part is unknown. any is true if any part is true, otherwise unknown if any part is unknown. not of unknown is unknown. Implement exactly that, and your in-memory evaluator and your SQL agree by construction:

type Tri = true | false | null; // null: unknown

export function evaluate(c: Condition, env: Env): Tri {
  if ("all" in c) {
    let out: Tri = true;
    for (const part of c.all) {
      const r = evaluate(part, env);
      if (r === false) return false; // false wins over unknown
      if (r === null) out = null;
    }
    return out;
  }
  if ("any" in c) {
    let out: Tri = false;
    for (const part of c.any) {
      const r = evaluate(part, env);
      if (r === true) return true; // true wins over unknown
      if (r === null) out = null;
    }
    return out;
  }
  if ("not" in c) {
    const r = evaluate(c.not, env);
    return r === null ? null : !r;
  }
  const left = read(env, c.attr);
  const right = c.ref ? read(env, c.ref) : c.value;
  // Missing is unknown, for every operator.
  if (left == null || right == null) return null;
  return compare(c.op, left, right);
}

With two values, not is dangerous: not(amount > 5000) on a missing amount flips false into true and lets the request through. With three values it stays unknown, and unknown never grants. That’s why the decide function earlier only grants on a definite true and only skips a forbid on a definite false.

Time is an attribute too

“During their shift” sounds simple until Anil works nights:

22:00 to 06:00. A naive start ≤ now < end check is never true for this shift.

start <= now && now < end with a start of 22:00 and an end of 06:00 is false at every minute of the day, so Anil can never read anything, and the bug report will say “nurses can’t log in at night.” A window that wraps midnight is two ranges:

function within(minute: number, w: { start: number; end: number }) {
  return w.start <= w.end
    ? minute >= w.start && minute < w.end   // 09:00–17:00
    : minute >= w.start || minute < w.end;  // 22:00–06:00 wraps midnight
}

And minute must be computed in the clinic’s time zone, by the server, not in UTC and not from a timestamp the client sent. A Mumbai clinic’s 09:00 is 03:30 UTC; a check against the server’s clock that runs in UTC would move every shift five and a half hours.

04Fields: masking and redaction

So far a decision has been yes or no for a whole record. Real screens need something finer. Riya at the front desk needs Kavya’s record to book an appointment, but not her diagnosis. Dev in billing needs the amount, but not the phone number. This is where XACML’s obligations earn their place: the decision says yes and says what has to happen to the response.

Reveal levels

Hidden or shown is too coarse. Most sensitive fields have useful in-between forms:

Each field declares the levels it supports, from least to most revealing.

Declare the levels next to each field, in the same schema policies are checked against, and tag fields by sensitivity so a policy can talk about a whole class at once:

export const fields = {
  record: {
    // ids can't be hidden: filters and joins need them
    id:        { always: true },
    clinicId:  { always: true },
    diagnosis: { tags: ["clinical"],
                 levels: ["hidden", "chapter", "category", "full"] },
    notes:     { tags: ["clinical"], levels: ["hidden", "full"] },
  },
  patient: {
    phone:     { tags: ["pii"], levels: ["hidden", "redacted", "last4", "full"] },
    email:     { tags: ["pii"], levels: ["hidden", "masked", "full"] },
  },
  invoice: {
    amount:    { tags: ["financial"], levels: ["hidden", "band", "rounded", "full"],
                 bands: [0, 1_000, 5_000, 10_000, 50_000], roundTo: 100 },
  },
} as const;

A policy then carries field rules as obligations. “Front desk may read records; #clinical fields hidden, phone at last4.” When several permits match, the person gets the most revealing level any of them grants, since grants add up. A forbid can carry a field rule too, which then caps everyone: “#pii never above last4, except the records team,” the exception again living on the restriction.

Masking happens on the server

The real value must never reach the device. Not in the JSON with a CSS class that hides it, not in a field the UI ignores. Mask in the response mapper, after the decision, and say what was removed so the UI can show a lock instead of a blank:

Stored
{
  "id": "k-881",
  "patient": {
    "name": "Kavya R.",
    "phone": "+91 98765 43421"
  },
  "diagnosis": "F32.1",
  "notes": "Follow-up in 2 weeks."
}
Riya receives
{
  "id": "k-881",
  "patient": {
    "name": "Kavya R.",
    "phone": "••••••3421"
  },
  "_hidden": ["diagnosis", "notes"]
}

How hidden fields leak anyway

Masking the response is the part everyone builds. The leaks come from everything else the API lets you do with a field. Suppose Dev’s team lead hides bill amounts from junior billing staff, but the invoice list still accepts ?amount_gt=:

Each answer halves the range. Seventeen requests pin ₹0 – ₹1,00,000 down to the rupee.

No response ever contained the amount. The filter answered seventeen yes-or-no questions about it, which is the same thing. The same goes for the other ways an API touches a field:

The rule that closes the first three is short: sorting, filtering and searching by a field need full access to it. Anything less returns an error, not an empty result. An empty result is itself an answer.

Totals are subtler. A minimum group size, such as “only show totals over at least five patients,” stops the obvious case but not differencing. The total for six patients minus the total for the same filter with one more condition that happens to exclude Kavya gives Kavya’s bill. If totals over hidden fields matter, only allow them sliced along a few fixed dimensions, or look at differential privacy, which adds calibrated noise for exactly this reason.

Two more rules round it out. Writing a field needs full read access to it, or someone can overwrite a value they can’t see. And a token level, a keyed hash, lets staff match records (“same phone as the last booking”) without seeing the value. Use a keyed hash with a secret, not a plain one, or anyone can hash every phone number in India and reverse it.

Then go through every other place the value can escape:

  • CSV and PDF exports, which often use a different code path
  • Nested objects: an invoice embedded in a patient, expanded by an include parameter
  • Emails, SMS messages, push notifications and webhooks
  • Search indexes that return documents directly
  • Audit logs that show before and after values
  • Error messages that echo the record back
  • Shared caches keyed by URL rather than by viewer

05The list problem: from policy to SQL

Everything so far answers “may Dr. Mehta read this record?” Most screens ask a different question: “which records may Dr. Mehta see, newest first, twenty-five at a time?”

The tempting answer is to load records and filter them through decide. It falls apart quickly. Page two depends on how many rows page one threw away. The total count is wrong. A doctor who can see three records out of two million makes the server read two million rows. Exports and dashboards inherit all of it.

The policy has to run inside the query, as a WHERE clause, or lists will never be right.

Partial evaluation

The trick that makes this possible is called partial evaluation, and OPA, Cedar and Cerbos all offer a version of it. Before the query, you already know everything about the principal and the context. The only unknown is the row. So evaluate everything you can, and keep what’s left over:

Everything about the person and the moment is settled before the query. Only the part about rows is left, and that part is SQL.

The leftover, the residual, only mentions the resource, so it maps onto columns. Do the same for the forbid on psychiatric notes, and the list query for Dr. Mehta becomes:

SELECT r.*
FROM records r
WHERE r.tenant_id = $1
  -- permit: doctors, own clinic (what's left of it)
  AND r.clinic_id = 'kor'
  -- forbid: psychiatric notes, unless treating.
  -- A row passes only if the forbid is definitely false.
  AND (r.note_type = 'psychiatry'
       AND NOT (r.treating_psychiatrist_id = 'dr-mehta')) IS FALSE
ORDER BY r.updated_at DESC
LIMIT 25;

Look at the last condition. SQL’s WHERE already keeps only rows where the condition is true, which is exactly the rule for permits: unknown doesn’t grant. For forbids, IS FALSE keeps only rows where the restriction is definitely off, so unknown still blocks. A psychiatric note with no treating psychiatrist gives TRUE AND NOT NULL, which is NULL, which isn’t false, so it stays hidden. That’s the same answer the three-valued evaluate gives, for the same reason.

Several permits become an OR of their residuals; several forbids become an AND of IS FALSE checks. A permit whose residual folds to true (the person can see everything) drops out; one that folds to false or unknown is removed before the query is built.

export function listFilter(
  req: ListRequest,
  index: PolicyIndex,
  columns: ColumnMap,
): Sql {
  const { permits, forbids } = index.candidates(req.action, req.resourceType);
  const known = { principal: req.principal, context: req.context };

  const grants = permits
    .map(p => residual(scoped(p), known))          // fold everything but resource.*
    .filter(r => r !== false && r !== null);       // can't grant: drop it
  if (grants.length === 0) return sql`FALSE`;
  // Sees everything, minus what the forbids remove.
  if (grants.some(r => r === true)) return blocks();

  return sql`(${or(grants.map(r => toSql(r, columns)))}) AND ${blocks()}`;

  function blocks() {
    const rs = forbids
      .map(f => residual(scoped(f), known))
      .filter(r => r !== false);
    // A forbid that is true or unknown for this person blocks every row.
    if (rs.some(r => r === true || r === null)) return sql`FALSE`;
    return and(rs.map(r => sql`(${toSql(r, columns)}) IS FALSE`));
  }
}

This is also the strongest argument for keeping conditions small and typed. Every operator you allow must have a SQL form that gives the same answer, including for NULL. Regular expressions, calls to other services, and loops over related data all make the residual impossible to express as a query, and every list endpoint becomes its own project.

Prove the two paths agree

You now have two implementations of every policy: evaluate in memory and toSql in the database. They will drift unless something checks them against each other. A property-based test does it: generate random records, including missing values, and random conditions, and require that both paths agree on every one.

test("in-memory and SQL decisions agree", async () => {
  await fc.assert(
    fc.asyncProperty(
      arbPolicies,
      arbPrincipal,
      fc.array(arbRecord, { maxLength: 50 }),
      async (policies, principal, records) => {
        await db.reset(records);                     // a real Postgres, not a mock
        const index = PolicyIndex.from(policies);
        const req = { principal, action: "record.read", context: now() };

        const filter = listFilter({ ...req, resourceType: "record" }, index, columns);
        const inSql = new Set(await db.ids(filter));
        for (const r of records) {
          const inMemory = decide({ ...req, resource: r }, index).allowed;
          expect(inSql.has(r.id)).toBe(inMemory);
        }
      }),
    { numRuns: 500 },
  );
});

This one test finds the bugs that matter: a NULL handled differently, an operator whose SQL form is off by one, a time zone applied on one side only. When it fails, the generator hands you the smallest record and policy that disagree.

06Where the decision point runs

The decision point from part 1’s anatomy section has to run somewhere. There are three common answers:

The decision is the same in all three. What changes is latency, and what happens when something is down.

For one product with list filters, the library wins: decisions take microseconds, the list compiler lives next to the query builder, and there’s no new thing to keep running. Sidecars suit a fleet of services in different languages. A central service suits a company that wants one team to own every decision and can afford a network hop per request.

Whichever you pick, the same three questions decide whether it’s safe.

What do you cache? Cache attributes and compiled policies, not decisions. A cached decision is right only for one principal, one resource and one moment. A cached attribute set, keyed by a version number that changes whenever the person’s roles change, is right until the version moves. Putting the version in the cache key means there’s nothing to delete when access changes, and nothing to forget to delete.

How fast does revocation take effect? When Anil leaves, how long until he can’t read records? That number is your cache lifetime or your token lifetime, whichever is longer. Decide it on purpose, write it down, and test it.

What happens when it’s down? If the PDP or its attribute source is unreachable, the answer is deny. A clinic system that fails open during an outage has turned an availability problem into a privacy breach. Keep a short-lived local copy so a brief blip isn’t an outage, and fail closed after that.

07Living with policies

A policy engine is software that changes every week without a deploy. It needs the same care as code, plus a few things code doesn’t.

Policies are reviewed like code

Keep policies in version control, or in a store that keeps every revision with who saved it and why. A change to a policy is a change to who can see patient records, so it gets a review. The most useful thing to show the reviewer isn’t the diff of the policy text. It’s the diff of access: “this change lets 14 front-desk staff read lab results at two clinics.” Cedar’s analysis tools and AWS’s Access Analyzer exist to answer that question. In your own system, run the old and new policy sets over a sample of real principals and resources and compare.

Sentences are the tests

Write the access rules as plain sentences and turn each one into a test case, with most of them expecting a denial. Features get tested by people using them. Nobody tests the thing they aren’t supposed to be able to do, except an attacker.

const cases = [
  { name: "Dr. Mehta reads Kavya's record on shift",
    who: mehta, action: "record.read", resource: kavyaRecord, expect: true },
  { name: "Dr. Mehta reads it off shift",
    who: mehta, action: "record.read", resource: kavyaRecord, context: { at: "23:00" }, expect: false },
  { name: "Dr. Mehta reads a psychiatric note",
    who: mehta, action: "record.read", resource: psychNote, expect: false },
  { name: "Anil reads a record at 02:00 on his night shift",
    who: anil, action: "record.read", resource: korRecord, context: { at: "02:00" }, expect: true },
  { name: "Riya reads a record with no note type",
    who: riya, action: "record.read", resource: legacyRecord, expect: false },
  { name: "Dev reads any clinical record",
    who: dev, action: "record.read", resource: kavyaRecord, expect: false },
];

Shadow mode before enforcement

Run new policies against real traffic for a week before they decide anything.

When you replace a policy set, or move from hand-written checks to an engine, run both. The old one decides; the new one is evaluated on the same requests and its disagreements are logged. A week of real traffic finds the cases nobody wrote a sentence for. Switch over when the disagreement log is empty or every entry is one you meant.

Explain every decision

Because every decision carries the policies that produced it, three features come almost free, and each saves support hours:

  • “Why can’t I?” A refused action shows which restriction applied, or that nothing granted it.
  • “What can this person do?” Run the person against the policy index for each action and show the grants with their residual conditions.
  • “Who could read Kavya’s record last Tuesday?” Keep every policy revision and attribute change, and replay them. Log refusals and sensitive reads always; sample the rest.

08An editor people can trust

Everything so far assumed engineers write the policies. At Cliniq they won’t. The clinic manager at Indiranagar wants front desk staff to read records, the compliance lead wants a rule about psychiatric notes, and neither will open a pull request. If you give them an editor, the editor becomes part of your security model. A confusing one produces policies that say something nobody meant.

A sentence with blanks, not a language

Every blank is a picker, typed by the schema. There is nothing to misspell.

Don’t show non-engineers a policy language, not even a friendly one. Show them a sentence with blanks. Each blank is a picker built from the schema: the actions come from the action list, the attributes from the resource type, and the operators from the attribute’s type, so a date offers “before” and “after” and an enum offers “is” and “is one of.” The “where” blank only lists places the author administers, and the “who” blank only lists roles they hold. That’s the escalation rule from earlier, enforced by the form rather than by a server error.

Always render the policy back as plain language, generated from the stored JSON rather than from the form. If the sentence reads wrong, the policy is wrong. Two phrasing rules prevent most mistakes:

  • Say “never” for restrictions. A forbid reads “Front desk may never read psychiatric notes,” not “Deny front desk read where note type equals psychiatry.” People should be able to tell a grant from a restriction without reading the details.
  • Let people say “block when…”, store “allow only when…”. Admins think in blocks: “block edits when the record is closed.” Store it as a condition the record must meet, so a record with no status is unknown and therefore blocked, instead of “not closed” and therefore editable.

Test as someone, before saving

The same decide() the product uses, with its reasons, before anything is saved.

The most useful button in a policy editor is “test as.” Pick a person and a record, and run the real decide() against the draft policy set: the decision, the policies that produced it, and the obligations. It’s the same function and the same reasons the “why can’t I?” screen uses, so admins learn to read decisions the way support does. Offer a few suggested tests, such as the author themselves, a random member of each role, and the most sensitive record type, because people only test the case they had in mind.

Show the access diff

Reviewers approve a change in access, not a change in policy text.

Before a policy saves, show what it changes in people and records, not in text: who gains access, who loses it, and to how many records. Run the old and new policy sets over the organisation’s principals and a sample of each resource type. For list access you can count exactly, because the policy compiles to a WHERE clause.

The diff is also where you catch policies that can’t do what they say:

  • Dead grants. A permit that an organisation-level forbid blocks completely. The author thinks they gave access; they gave nothing.
  • Surprisingly large grants. A permit that reaches more than, say, ten times the records the author can see themselves gets a confirmation step.
  • Unreachable conditions. A condition on an attribute that’s missing on most records, which will be unknown, and therefore block or fail to grant, far more often than the author expects.

Every save is a revision

Store each save as a new revision with its author, a required reason, and the access diff it showed. Then “who changed this, and what did they see when they did?” has an answer, revert is one click, and the “who could read Kavya’s record last Tuesday?” question from the last section can be replayed exactly. Sensitive changes, such as anything touching #clinical fields or an organisation-level forbid, can require a second person to approve the diff before it takes effect.

09Build or adopt

Everything in this post can be built in a few thousand lines, and for one product that owns its data it’s often the right call. But it isn’t the only call:

One case sits outside all of these. If your access rules are mostly about sharing, “Kavya shared her scans with a second-opinion doctor,” and access follows a graph of who shared what with whom, you’re looking at relationship-based access in the style of Google’s Zanzibar. OpenFGA and SpiceDB implement it. It can live alongside a policy engine: the graph answers “is there a share?”, and policies add the conditions.

Whichever you choose, keep one function that the rest of the product calls, and keep its answer shape: allowed, the policies that decided, the obligations, and a reason. Then changing the engine later is a change behind one interface, not a change in every handler.

10The short version

  1. 01Deny by default. Restrictions override grants. Order never matters.
  2. 02Keep grants and restrictions as different kinds of policy.
  3. 03Put exceptions inside the restriction they’re exceptions to.
  4. 04Scope every policy to the place it’s attached.
  5. 05Let people grant only what they hold, where they administer.
  6. 06Take attributes from trusted sources, never from the request.
  7. 07Treat missing as unknown, and never let unknown in.
  8. 08Check updates against the record before and after.
  9. 09Mask on the server, and require full access to sort, filter or search.
  10. 10Compile policies to SQL for lists, and test both paths agree.
  11. 11Give admins a sentence to fill in, a “test as” button, and an access diff.
  12. 12Return the deciding policies with every answer, and log refusals.

None of the big systems got here in one step. AWS added permission boundaries, then resource control policies. Google added deny policies, then principal access boundaries. Each one closed a gap the simpler model couldn’t. The advantage of building now is that you can start with the shape they converged on, and skip the years of finding it.

Further reading

Cliniq, its people, and its policies are invented for this article. The AWS, Google Cloud, Kubernetes, Cedar and XACML behaviour described is from their documentation; the code is a sketch of the shape, not a library to copy.