Skip to content
Tech Interview Prep
Technical interview guide

RBAC vs. ABAC Implementation

Assigning permissions via roles versus evaluating policies against attributes: the implementation tradeoffs of each.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v6
Editorial status
Reviewed

Scope: NIST RBAC and SP 800-162, NIST SP 800-207, current AWS/Azure/Google IAM, OPA, Cedar, and XACML guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-3

Define the authorization request contract.

Answer

Core answer (first 90 seconds)

The authorization request contract is the tuple a policy enforcement point (PEP) hands to a policy decision point (PDP): authenticated principal, canonical action, canonical resource type and ID, and the minimum context the policy cannot derive. Everything else (ownership, group membership, tenant boundaries, current resource state) the PDP resolves from authoritative sources at decision time. The caller supplies identifiers and claims; it never supplies the facts that decide the outcome.

Assumptions: one logical PDP per trust domain, PEP co-located with the service that owns the resource, policy and data versioned, PDP fails closed.

The shape

JSON
{
  "principal": { "type": "User", "id": "u_8812", "tenant_id": "t_44" },
  "action": "document:read",
  "resource": { "type": "Document", "id": "doc_901" },
  "context": { "request_time": "2025-06-01T14:03:11Z", "source_ip": "203.0.113.7", "mfa": true },
  "policy_version": "2025-05-30T00:00:00Z",
  "data_version": "doc_901@rev_17"
}

Cedar's request is exactly this four-tuple (principal, action, resource, context) and context is the only place arbitrary data goes. XACML 3.0 splits the same information into Subject, Resource, Action and Environment attributes; OPA takes it as one input document. The names differ; the contract does not.

Why each element earns its place:

  • principal: authenticated, not asserted. If the PEP trusts a client-supplied user ID, any caller impersonates any user.
  • action: canonical and namespaced (document:read, not read or GET /docs/901). Ambiguous action names are how a policy matches the wrong operation.
  • resource: type plus ID, not the object. The PDP fetches attributes from a policy information point.
  • context: only what policy needs and cannot derive.

Absent vs false. "mfa": false and a missing mfa key are different inputs. In Cedar, reading a missing attribute is an error, which denies; in OPA, input.context.mfa == false is undefined when the key is absent, so the rule simply does not fire. A contract that lets the key vanish silently turns a deny into a no-op. Require the key present with an explicit value, or write the policy to fail closed on absence.

Trace. Request hits the PEP → PEP validates the token, extracts the principal, maps the route to a canonical action, reads the resource ID → sends the tuple to the PDP → PDP calls the PIP for resource attributes (owner, classification, tenant) and principal attributes (groups, clearance) → evaluates policy → returns Permit/Deny plus obligations → PEP applies the decision to the same resource ID it sent. If the PEP re-resolves the resource after the decision, you have a time-of-check/time-of-use gap.

Failure modes

failurewhat breaksdetection
Caller-supplied attributesprivilege escalationpolicy tests asserting attributes come from the PIP
Stale data_versiondecision on a revoked resourcecompare version at enforcement; re-evaluate on change
policy_version skewdecision under the wrong policyPDP rejects unknown versions
Malformed inputPDP crash or default-allowschema validation at the PEP; PDP denies on parse error
Context bloatlatency, unused fieldsaudit which context keys any policy reads

Trade-off: include or resolve. Include a field when the PDP cannot reach the source. Request-time-only data like source IP or MFA freshness, or a source in another network zone. Resolve it when the source is authoritative and shared: group membership, resource ownership. Including those means every caller must compute them correctly, and you get N implementations of the same lookup, each a place to drift.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Design and review role inheritance.

Answer

What I'd say first

Assume RBAC with additive grants and a role graph where a role can include other roles. The design question isn't "should we inherit": it's whether the shared permission set is a stable capability or an accident of who needed what first. I'd model inheritance as a DAG of capability roles, cap depth at 2, make effective permissions computable and diffable, and gate edits to a parent harder than edits to a leaf. A parent edit is a change to every descendant, so its review cost scales with the descendant count, not with one role.

Mechanism

Effective permissions = union over the transitive closure of the role graph, intersected with any cap, minus explicit denies. Kubernetes RBAC has no deny and no ordering: the effective set is the union of every rule from every bound Role or ClusterRole, so adding a binding can only add. In AWS, the effective set is the intersection of identity-based policies, the permissions boundary, and SCPs, with an explicit Deny winning. Azure's NotActions is not a deny: it is subtracted from Actions inside the same role definition, so a second assignment at the same scope can re-grant it. GCP unions allow policies down the resource hierarchy and lets deny policies override.

SystemEffective setDeny?
Kubernetes RBACunion of all bound rulesno
AWS IAMidentity ∩ boundary ∩ SCPyes, explicit
Azure RBACunion across scopes of (Actions − NotActions)only deny assignments
GCP IAMunion of allow policies down the hierarchydeny policies override

Worked trace: silent expansion via aggregation

Kubernetes' built-in view, edit and admin ClusterRoles are aggregated: their aggregationRule.matchLabels selects any ClusterRole labeled rbac.authorization.k8s.io/aggregate-to-view: "true". Trace:

  1. A team ships a CRD and a ClusterRole for it, labeled aggregate-to-view: "true".
  2. The controller folds that ClusterRole's rules into view.
  3. Every principal bound to view, typically all developers, now reads the new CRD.

Nobody edited view, so the diff on view is empty. Detection: kubectl auth can-i --list --as=<subject> before and after, or diff the aggregated rules rather than the ClusterRole object. The same label is a privilege-injection path: whoever can create a ClusterRole carrying it can add permissions to view for everyone. The escalate verb on roles/clusterroles and bind on rolebindings are the RBAC controls that decide who can do this.

Failure modes and how to catch them

  • Revocation doesn't propagate. Cached effective-permission checks (Zanzibar-style systems use zookies to bound staleness) keep a revoked parent grant live until the cache TTL. Measure time from revoke to can-i returning no; if it's minutes, your TTL is the real revocation window.
  • Privilege expansion in a diff. A parent gains iam:PassRole or *; every descendant expands at once. Compute effective sets before and after, and alert when an action is added to a role with more than N descendants.
  • Unused-permission findings mislead. AWS IAM Access Analyzer unused-access findings are driven by CloudTrail activity, so a permission used quarterly reads as unused and gets pruned.

When not to inherit

Flat roles duplicate permission sets but have a blast radius of one. Composition, attaching capability roles directly to principals with no role-to-role edges, gets most of the reuse with no parent to over-grant. ReBAC (Zanzibar, OpenFGA, SpiceDB) moves the relationship into data and earns its keep when the graph changes faster than the policy. Rule of thumb: inherit when the capability set changes more slowly than the principals; flatten when depth exceeds 2 or a parent has more than roughly 10 descendants.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design an RBAC model for a growing operations platform.

Answer

Assumptions I'd state before designing. ~200 engineers, three environments (dev, staging, prod), Kubernetes workloads running on AWS, on-call rotations, and an audit requirement to show who can touch prod. Change any of those and the shape changes.

Core answer. Derive roles from resource actions, not job titles. A role is a named bundle of (resource, action) pairs scoped to exactly one environment. Bind roles to groups, never to people. Keep the hierarchy one level deep. Make prod write access a time-bound grant rather than a standing role.

LayerExampleWhy it sits there
Resource actiondeployments:patch in the payments namespaceThe unit you actually grant
Rolepayments-deployer-prod = {deployments:patch, pods:get, pods/log:get}Named bundle, one environment
Grouppayments-oncallPopulation, not a person
Bindinggroup → role, in one namespaceOne hop, auditable

Why two dimensions is the ceiling. Six job functions × three environments = 18 roles. Add a resource-tier dimension and it's 6×3×3 = 54; add region and it's 216. Past two dimensions you are maintaining a matrix nobody can review, and every new environment multiplies it. Keep the matrix small and push the rest into conditions.

Why environment is a dimension, not a condition. Kubernetes RBAC is purely additive: there is no deny rule. You cannot express "deployer except in prod" as a role; you express it by not binding the role in prod. That single fact drives the whole layout:

YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: payments-oncall-deployer
  namespace: payments-prod
subjects:
  - kind: Group
    name: payments-oncall
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: payments-deployer-prod
  apiGroup: rbac.authorization.k8s.io

Trade-offs against the alternatives. RBAC is cheap to reason about and audit but cannot say "only during your on-call shift" or "only resources you own." ABAC (OPA/Rego, Cedar) handles those conditions, at the cost of owning policy correctness and its test suite. ReBAC (Zanzibar-style, SpiceDB or OpenFGA) handles ownership graphs but adds a consistency model you now have to reason about. For a growing ops platform: RBAC for the stable 90%, a policy engine for the conditional 10%. On AWS, cap the blast radius with permission boundaries and an explicit-deny layer, since IAM evaluates explicit deny > allow > implicit deny.

Failure modes and how you detect them.

  • Role explosion. Count roles and bindings monthly. If roles grow faster than headcount, you are encoding combinations instead of conditions.
  • Stale grants. AWS IAM Access Analyzer unused-access findings plus CloudTrail for the AWS side. Kubernetes has no native last-used data, so you analyze audit logs for RoleBinding subjects that never appear in an authorization event over 90 days.
  • Privilege creep through nesting. If groups nest, effective permissions are transitive and no single binding shows the truth. Flatten groups and compute effective access by unioning every binding for a subject.
  • Separation-of-duty conflicts. NIST INCITS 359-2004 defines static and dynamic SoD; implement it by evaluating effective permission sets pairwise and rejecting bindings that grant both halves of a conflicting pair (e.g. deployments:patch and roles:bind in the same namespace).
  • Time-bound elevation. Prod write goes through a just-in-time grant with a session duration of 1–12 hours (AWS IAM Identity Center permission sets default to 1 hour). Detect drift by alerting on any standing prod-write binding that outlives its ticket.

Review effective access, not job titles: titles drift, bindings don't.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Decide between RBAC, ABAC, and a hybrid model.

Answer

What I'd say first

Two things decide this before any model comparison: can the policy decision point read trustworthy attributes at request time, and does scope vary per request or per job function? If attributes are trustworthy and scope varies, RBAC alone forces you to mint a role per scope. If attributes are not trustworthy, ABAC is decoration and you should stay with RBAC.

My default: RBAC for the action vocabulary, attributes for scope, one PDP in front of both.

Mechanism

RBAC (NIST INCITS 359) is set membership: subject → role assignment, role → permission, optional role hierarchy. A decision is a lookup, so it is cheap and explainable: "you hold role editor, editor has document:edit". It breaks on scope. 200 job functions across 50 tenants is 10,000 role bindings if tenant is baked into the role name; with a tenant attribute it is 200 role definitions and 50 attribute values.

ABAC (NIST SP 800-162) evaluates a policy over attributes of subject, resource, action and environment. XACML 3.0 is the standard architecture (PEP, PDP, PIP, PAP) with combining algorithms (deny-overrides, permit-overrides, first-applicable) and obligations. The cost is that every decision now depends on attribute fetches, so the PIP sits on your critical path as both a latency and an availability dependency.

Hybrid: the role grants the action, an attribute restricts the scope. In Cedar (AWS's policy language, used by Amazon Verified Permissions) that is a permit with a when clause; forbid always beats permit, and policies cannot loop or recurse, so evaluation always terminates.

CEDAR
permit(
  principal in Role::"editor",
  action == Action::"editDocument",
  resource
) when {
  resource.tenant == principal.tenant &&
  resource.classification != "restricted"
};

Trade-offs

RBACABACHybrid
decision costset lookupattribute fetch + evallookup + eval
policy countgrows with roles × scopesgrows with rulesroles + a few rules
explainabilityhighneeds decision logshigh if the role is logged
revocationrebind the rolechange the attributeeither
main failurerole explosionuntrusted or stale attributestwo sources of truth

Failure modes

Untrusted attribute source: if tenant comes from a client header, the policy is decorative. Attributes must come from a PIP the client cannot write.

Stale attributes: a revoked role still lives inside an issued token until it expires, so the token TTL is your revocation window. Zanzibar-style systems handle this with consistency tokens: SpiceDB's CheckPermission takes a consistency requirement, so you pick minimize_latency or fully_consistent per call rather than globally.

Default-allow: OPA's default allow := false and Cedar's deny-unless-permitted are the safe defaults. If a missing attribute evaluates to a grant, you have built an open door.

Policy sprawl: ABAC rules grow quietly. OPA decision logs plus opa test unit tests, or Cedar's policy validation, are how you catch a rule that silently widened access.

Before migrating

Run the new PDP in shadow mode beside the old one, log both decisions, and diff them. Prototype the cross-tenant deny and the revoked-role case specifically: those are the two that fail silently.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Specify policy precedence and combining behavior.

Answer

Assumptions. AWS IAM with its current evaluation logic, one account plus one cross-account case. GCP and Kubernetes differ; the deciding difference is at the end.

Core answer. AWS denies by default, and an explicit Deny in any applicable policy beats every Allow, wherever it sits. Past that, policies split into two classes that combine differently. Grant policies, identity-based and resource-based, union: any single allow is enough. Filter policies (SCPs/RCPs, permissions boundaries, session policies) intersect: they never grant, they only subtract, and every filter in effect must allow. AWS documents the sequence as explicit deny → SCP/RCP → resource-based → identity-based → permissions boundary → session policy. If nothing allows, the result is an implicit deny.

ClassGrants?Combines byFails the request when
Identity-basedyesunionno identity policy allows
Resource-basedyesunionno resource policy allows (cross-account: also needs an identity allow)
SCP / RCPnointersectionit doesn't allow the action
Permissions boundarynointersectionit doesn't allow the action
Session policynointersectionit doesn't allow the action
Explicit Deny (any policy)—overrides allalways

Worked trace. Role app-reader in account 111122223333, assumed via STS. Identity policy allows s3:GetObject on arn:aws:s3:::reports/*. Permissions boundary allows s3:* on the same prefix. SCP allows s3:*. Session policy allows s3:GetObject on the same prefix.

Request s3:GetObject on reports/q3.pdf:

  • explicit deny? none.
  • SCP allows s3:* → pass.
  • resource-based? none.
  • identity-based allows GetObject on reports/* → allow.
  • boundary allows s3:* on reports/* → pass.
  • session policy allows GetObject on reports/* → pass. → Allow.

Now request s3:PutObject on reports/q3.pdf. The boundary allows s3:*, but a boundary can't grant. The identity policy only allows GetObject, so the identity check finds no allow → implicit Deny. This is the case people misread as "the boundary allowed it."

Now add a bucket policy with an explicit Deny on s3:GetObject for reports/confidential/*, and request reports/confidential/payroll.pdf. Identity, boundary and session all allow, but the explicit deny is evaluated first and wins → Deny.

Failure modes.

  • Implicit deny looks like explicit deny. An SCP or boundary that doesn't allow produces the same AccessDenied as a missing identity allow. Detect by running the request through the IAM Policy Simulator (aws iam simulate-principal-policy), which takes the identity policy, permissions boundary and resource policy as separate inputs and reports a decision per policy type, so you can see which one returned no allow. CloudTrail gives you the raw event (principal, action, resource, errorCode) but not which policy type blocked.
  • Cross-account needs both sides. A resource policy alone doesn't grant cross-account access; the caller's identity policy must also allow. Detect by simulating with the caller's ARN, not the role's.
  • Session policy silently shrinks a role. A role that works with long-term credentials fails under STS because the passed session policy intersects. Detect by comparing a call made with long-term credentials against the same call made with the assumed role; if only the assumed-role call fails, the session policy is the cause.
  • SCP blast radius. An SCP that drops an action denies it for every principal in the member account, including the account root user. Detect by checking whether the same action fails for unrelated principals in that account.

Alternatives and when to pick them. GCP IAM is allow-only and hierarchical (org → folder → project → resource), additive union, with deny policies added for hard guardrails. Kubernetes RBAC is purely additive with no deny at all: you express "deny" by not granting, and reach for admission control (OPA Gatekeeper, Kyverno) when you need a real deny. Pick AWS-style filter policies when a central team must cap what account owners can grant themselves; pick RBAC-plus-admission when the cluster is the boundary; pick OPA when the combining rule itself is what you need to customize.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Handle missing, malformed, and stale attributes safely.

Answer

Assume attributes come from outside the PDP: an IdP, an HR feed, a CMDB. The PDP evaluates them per request and returns Permit, Deny, or Indeterminate. The safe default is that an attribute which is missing, malformed, or past its declared max age never satisfies a policy condition, and in Rego that is the language's own behaviour, not something you code. A reference to an absent field is undefined; an undefined term fails the rule body; a rule that fails yields no value. default allow := false converts all three cases into Deny with no null checks anywhere.

The bug this prevents is the opposite pattern: a policy with no default, where the caller treats "no rule fired" as "no objection" and allows. That is fail-open by omission, and it is invisible in code review because nothing looks wrong. Cedar takes the same stance: the authorizer's decision is Deny unless a policy permits, and evaluation errors land in diagnostics rather than in the decision.

Staleness. Carry issued_at with the attribute and compare it to the PDP's clock at decision time, not at fetch time. Allow bounded skew in both directions: an attribute dated in the future is as suspect as an old one. A 30-second allowance covers NTP drift without opening a replay window.

REGO
package authz

default allow := false

max_age_s := 3600
skew_s    := 30

allow if {
    is_string(input.attr.user.department)
    is_number(input.attr.user.issued_at)
    now := time.now_ns() / 1000000000
    now - input.attr.user.issued_at <= max_age_s + skew_s
    now - input.attr.user.issued_at >= -skew_s
    input.action == "read:own_dashboard"
}

Checked against OPA 1.x (Rego v1). Trace with department = "eng", issued_at = now - 7200, action matching: is_string passes, is_number passes, 7200 <= 3630 is false, the body fails, allow is undefined, the default applies → Deny. Same input with issued_at = now - 10: 10 <= 3630 true, 10 >= -30 true, action matches → Permit.

Trade-off. Fail-closed costs availability: a broken HR feed denies every approval workflow, not just the risky ones. The deciding criterion is blast radius and reversibility. Read-only, self-scoped, reversible operations, a user viewing their own dashboard, can fail open with a logged reason code. Money movement, bulk export, and privilege grants fail closed. The middle ground is Indeterminate → step-up: re-authenticate or require MFA, which is fail-closed against an attacker holding a stale token but not a hard outage for a legitimate user. Never map Indeterminate to Permit.

classexampledetectiondecision
missinguser.department absentundefined ref fails the bodyDeny
malformedroles: "admin" where an array is expectedingestion schema check, reject not coerceDeny, ATTR_MALFORMED
staleissued_at 7200s old, max 3600now - issued_at > max_age + skewDeny, ATTR_STALE
conflictingtwo IdPs disagree on clearanceper-source compare at mergeIndeterminate → step-up
delayed updaterevocation at source, cache not refreshednow - fetched_at on the bundlebounded by TTL

Coercion is the quiet one: an ingestion layer that wraps a scalar into a one-element list turns "admin" into ["admin"] and grants. Reject on type mismatch instead.

Exposure arithmetic. With a 3600s TTL, 60s source propagation, and a 30s cache refresh, worst-case exposure after a revocation is 3600 + 60 + 30 = 3690s, about 61 minutes. If the requirement is 5-minute revocation, the TTL has to come down to 240s, and that is a load decision on the source, not a policy decision.

Reason codes go out structured, ATTR_STALE user.clearance age=7200 max=3600 decision_id=..., so a spike in one code is alertable. A rising ATTR_MISSING rate for a single attribute means the source changed shape; that is a feed problem, not a user problem, and it should page the feed owner rather than the on-call for the service.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design attribute issuance and mutation governance.

Answer

Assumptions. Attributes arrive from several issuers (the IdP, the cloud provider, a CMDB, service-owned metadata) and a policy engine (OPA, Cedar, or the cloud's native ABAC) reads them at decision time. The invariant I'd design to: no principal can change an attribute in a way that increases its own effective permissions, or lowers a protection on data it does not own, without a second party's authorization.

Core answer. Split the system into an attribute plane and an access plane. The access plane reads attributes and never writes them. Every attribute has exactly one issuer, a single writer, and mutation is authorized by a policy that must not reference the attribute being mutated. That last clause is the whole trick. If "you may set department" is conditioned on department == 'admin', one successful call to the mutation endpoint is permanent self-escalation. The mutation policy has to key on something the principal cannot rewrite: its authenticated subject from the IdP, or a role granted out of band.

Design.

attributesingle issuerfreshnessmutation path
principal sub, groupsIdP (Okta/Entra) over SCIM (RFC 7644)token TTL, ~1 hadmin console; no self-service
workload identitySPIRE server, X.509-SVIDdefault 1 h TTLnode attestation, not human
resource classificationdata-governance pipelineon mergePR + two-person review
region, accountcloud providerimmutable at createrecreate the resource

Worked trace: the tag-lowering escalation. A bucket payroll carries classification=pii. The policy is allow read if resource.classification == "public". The service owner holds s3:PutObjectTagging on their own bucket. At t=0 they rewrite the tag to public; at t=1 the policy engine's next evaluation grants read to the whole engineering group. The owner never gained access to someone else's data: they lowered the guard on data they steward. Fix: classification is written only by the governance pipeline; owner edits land in proposed-classification, which no policy reads until a reviewer promotes it. Detection: an audit join on (attribute write, decision) that flags any decision using a version older than the latest write.

Alternatives and when not to use them. Centralizing every attribute in the IdP is the simplest single-issuer design, but it cannot express resource-side facts like classification or region, and it makes every policy depend on IdP availability: use it only when attributes are purely about the principal. Per-service attributes with a central engine (OPA/Rego, or Cedar) scale better and keep resource facts near their owner, at the cost of doing this governance per service. Between the two engines: Cedar is typed, default-deny, and loop-free, so a policy can be reasoned about statically; Rego is more expressive and easier to write something surprising in. Choose Cedar when analyzability matters more than reach.

Failure modes and detection.

  • Mutation policy reads the attribute it writes → static check that the two attribute sets are disjoint; fail CI.
  • Revocation lags the cache → compare decision-time attribute version to latest write version; alert when lag exceeds the cache TTL.
  • Policy references a renamed attribute → CI fails when a policy names an attribute absent from the registry.
  • Vocabulary drift (PII vs pii vs sensitive) → schema validation at write time rejects unknown values.

Pass/fail. Pass: a narrowly authorized issuer under a separate policy, with its own audit trail. Fail: any principal whose access would increase after the change. That is the definition of the bug.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Walk me through how you'd use environmental attributes (time of day, network location, device posture, risk signals) in an ABAC policy, and the pitfalls of relying on them?

Answer

What I'd say first

Environmental attributes (time, network zone, device posture, risk score) sit in the XACML environment category: they describe the request, not the principal. The rule I'd state up front is that they narrow, they don't grant. A context attribute can turn an allow into a deny or a step-up; it should never be the only reason a principal reaches a resource they have no entitlement to. If "corporate IP" alone grants access, whoever controls the IP controls the grant.

Assumptions: RBAC entitlement is evaluated first and produces a base decision; a PIP supplies environment attributes with per-attribute TTLs; the PDP is server-side and the clock is the server's, not the client's.

Mechanism

Model it as base grant AND NOT context_denied, with reason rules so denials stay explainable:

rego package authz import rego.v1

default allow := false

allow if { input.rbac.allowed # entitlement already established not context_denied }

context_denied if { input.action == "admin:write" input.env.device.posture != "compliant" }

context_denied if { input.action == "admin:write" input.env.network.zone == "public" }

context_denied if { input.action == "admin:write" input.env.risk.score >= 70 }

context_denied if { input.action == "admin:write" not in_change_window }

in_change_window if { [h, _, _] := time.clock([time.now_ns(), "UTC"]) h >= 6 h < 22 }

Trace: {rbac:{allowed:true}, action:"admin:write", env:{device:{posture:"compliant"}, network:{zone:"vpn"}, risk:{score:42}}} with the server clock at 14:32 UTC → allow is true. Flip risk.score to 78 and context_denied fires on the risk rule, so allow is false. The decision record carries the attribute snapshot, each attribute's source and fetch timestamp, and the matched rule ID: without that you cannot explain the denial a week later.

Note the clock: time.now_ns() is the PDP's clock. Never take time from the request. Same for network zone: derive it from the connection the PDP can see, not from X-Forwarded-For, which the client sets.

Pitfalls

attributesourcefreshnesswhat breaks itright use
time of dayserver clockper requestclient-supplied time, DST, tenant time zoneschange windows, break-glass expiry
network zoneconnection metadata / Access Context Manager access levelper requestVPN, NAT, CGNAT, spoofed XFFdeny public zone for admin actions
device postureMDM/EDR attestationminutes to hoursstale agent, rooted device, checked at login onlystep-up or deny for high-risk writes
risk scoreUEBA / signals pipelineseconds to minutesfeedback loops, false positives on travel and on-callstep-up MFA, shorten session

The failure modes I'd name: (1) privilege amplification, a spoofable attribute that grants; (2) TOCTOU, posture checked at login, request arrives eight hours later; (3) fail-open on missing attributes, where the PIP times out and the policy silently allows; (4) availability coupling. Device-posture service down means every admin write denied, so you need a documented degraded mode; (5) risk-score feedback loops, where blocking flagged users generates more anomalous signal.

Detection: emit a metric per context rule (deny count, PIP timeout count, attribute age at decision time) and alert on PIP error rate and on attribute age exceeding its TTL. A spike in risk_score_high denials in one region is usually a pipeline bug, not an attack.

When not to use it

Don't gate availability-critical paths on fast-changing context. And per SP 800-207, network location is not a trust boundary: treat "inside the VPN" as one weak signal among several, not as authentication.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Implement a hybrid authorization rule for a multi-tenant API.

Answer

Clarify and assume first. "Hybrid" here means two different questions get answered by two different mechanisms: can this principal do this kind of action at all (coarse, role-based) and is this particular object in scope (fine, attribute- or relationship-based). I'll assume the tenant id is a signed claim in the access token, every resource row carries a tenant_id, and we evaluate with an embedded policy engine, Cedar or Rego via OPA, rather than hand-rolled if statements.

The answer. Evaluate both checks in one policy decision, deny by default, and never let the coarse check short-circuit the scope check. A billing role is necessary but not sufficient; the resource's tenant must equal the principal's tenant, and any project or classification attribute must be satisfied.

CEDAR
permit(
  principal,
  action == Action::"readInvoice",
  resource
)
when {
  principal.role == "billing" &&
  principal.tenant == resource.tenant &&
  ["internal", "confidential"].contains(resource.classification)
};

No matching permit means deny: Cedar is default-deny, so there is no else branch to forget.

Why ordering matters. If you check the role first and return early on failure, you never evaluate scope, which is fine. The dangerous order is the reverse: authorize on scope, then treat role as an afterthought, or evaluate role in the gateway and scope in the service. Split evaluation is where cross-tenant bugs live, because the two halves can disagree about which tenant the request is for. One decision point, one principal object, one resource object.

Trace. Request: principal {tenant: acme, role: billing}, action readInvoice, resource {tenant: acme, classification: internal} → all three when clauses true → permit. Same principal, resource {tenant: globex, ...} → second clause false → no permit → 403. Same principal, resource {tenant: acme, classification: restricted} → third clause false → 403.

Trade-offs. Pure RBAC cannot express "same tenant" without exploding into per-tenant roles: thousands of roles, unmaintainable. Pure ABAC pushes every decision to attribute lookups, which is where latency and availability risk live. ReBAC (OpenFGA, Zanzibar-style) is the right tool when scope is a graph, "can read if they are on the project team", but it is overkill for a flat tenant column. The deciding criterion: if scope is a single equality on a column you already have, keep it in the policy; if scope is a relationship traversal, use a relationship store.

Where to evaluate. An embedded library (Cedar in-process) is microseconds and no network hop. OPA as a sidecar adds roughly a millisecond at p99 in typical deployments: illustrative, measure your own. A central authorization service adds a network round trip and becomes a hard dependency; only worth it if you need one audit trail across many services.

Failure modes and detection.

  • Missing tenant predicate: a policy that checks role and classification but forgets principal.tenant == resource.tenant. Detection: a CI negative test with a same-role principal against a sibling tenant must return 403; in production, alert on any permit where the two tenant ids differ. That count should be zero.
  • Attribute or role service down: default-deny turns into a 403 outage. Detection: 403 rate spike correlated with dependency health; cache roles with a short TTL and alert when the cache serves entries past TTL.
  • Stale role cache after revocation: a removed billing role still permits until TTL expires. Detection: log the policy version and role-cache generation with every decision, and reconcile against the source of truth.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Prevent IDOR when using a central policy engine.

Answer

Assumptions and the core answer

Assume a multi-tenant service, a central policy engine (OPA or Cedar) that evaluates a JSON input document against a policy, and an authenticated principal whose tenant is known server-side. The one-line answer: the policy engine must never see a scoping fact the caller controls. IDOR is not a policy bug. It is an input-provenance bug. You resolve the requested identifier to a canonical row, build the policy input from server-owned columns, ask for the exact action, and apply the decision to the same row instance you are about to read or mutate.

Why that defeats IDOR

A policy engine is a pure function: decision = policy(input). If input.tenant comes from a query param, a body field, or a JWT claim the client can forge, the attacker chooses the answer. So the input is assembled from two trusted sources only: the authenticated principal and the row you just fetched by primary key. The policy then compares them (principal.tenant == resource.tenant). The attacker's only lever, the ID, is used to look up the row, not to scope the decision.

Python
# Python 3.12, OPA 0.68 over local HTTP
# policy: allow if input.principal.tenant == input.resource.tenant
#         and input.action in input.principal.roles_actions

def get_invoice(principal, invoice_id):
    row = db.query_one(
        "SELECT id, tenant_id, owner_id, status, version "
        "FROM invoices WHERE id = %s", invoice_id)
    if row is None:
        raise NotFound()          # 404, not 403: don't leak existence
    inp = {
        "principal": {"id": principal.id, "tenant": principal.tenant_id,
                      "roles": principal.roles},
        "resource":  {"type": "invoice", "tenant": row.tenant_id,
                      "owner": row.owner_id, "status": row.status},
        "action":    "read",
    }
    if not opa.allow(inp):        # POST /v1/data/invoice/allow
        raise Forbidden()
    return row

Trace of the attack

Attacker in tenant A sends GET /invoices/8842, which belongs to tenant B. No tenant is in the request. The server resolves 8842 to a row with tenant_id = B. Input becomes principal.tenant = A, resource.tenant = B. The policy returns false → 403. Now change one line: pass tenant_id from a query param. The attacker sends ?tenant_id=B, the input reads principal.tenant = B, the policy returns true, and the row is returned. Same policy, same engine: the IDOR is entirely in where the input came from.

Enforcement point: pick by staleness budget

pointadded latency (typical)stalenessfailure mode
OPA sidecar, HTTP per request~1–3 ms p99noneengine down → must fail closed
in-process eval of a polled bundle~50–200 µsup to bundle poll interval (OPA default min_delay_seconds 60 s)revoked grant still allowed for up to 60 s
decision cached on (principal, resource, action)sub-µsstale on any resource-state changeownership transfer not reflected

Figures are typical, not measured here. The trade is latency against how fast a revocation must take effect.

Closing the check-then-use window

Between the policy check and the write, ownership can change. Bind the decision to the version you evaluated:

SQL
UPDATE invoices SET status = 'paid', version = version + 1
WHERE id = %s AND tenant_id = %s AND version = %s;

Zero rows affected means the row moved under you: re-evaluate or return 409. A transaction with SELECT ... FOR UPDATE achieves the same.

When central policy is the wrong tool

Single-tenant app with no shared resources: a WHERE owner_id = :current_user predicate in the query is cheaper and has no engine dependency. And note the engine is a decision point, not an enforcement point: it cannot stop a query that already returned the row, so the tenant predicate still belongs in the SQL.

Failure modes and tests

Engine unreachable → fail closed by default. Bulk/export endpoints that check once and iterate IDs → check each ID. GraphQL nested resolvers where the parent is authorized but the child is not. Indirect references (S3 keys, presigned URLs) → resolve to a canonical object before deciding. Negative-test with a sibling tenant's ID, a guessed sequential ID, a nested resource (invoice → line item), and an indirect reference.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Secure list, search, export, and bulk mutation endpoints.

Answer

Assume a multi-tenant service on Postgres, with a policy engine (OPA or Cedar) that already answers can_read(user, obj) for one object. The question is what changes when the client names a collection instead of an object.

The core answer: never authorize the first row and assume the rest match. Either push the policy into the query as a scope predicate, or authorize every candidate object in a batch, and prove the two are equivalent. Then bind that decision to pagination, snapshot, and version so it can't be escaped between requests.

Query scope. Translate the policy into a predicate the datastore evaluates. Postgres row-level security does this: CREATE POLICY tenant_read ON docs USING (tenant_id = current_setting('app.tenant_id')::uuid); with SET LOCAL app.tenant_id = '...' per request. Then SELECT ... FROM docs and SELECT count(*) FROM docs both return only authorized rows.

Equivalence proof: the single-object rule is can_read(user, obj); the scope is a predicate S(user). They are equivalent iff ∀ obj: obj ∈ S(user) ⇔ can_read(user, obj). Derive S from the same policy source, then run a differential test: sample 10k objects and compare obj ∈ S(user) against can_read(user, obj). Any mismatch is a bug.

Per-object authorization. When the policy can't be expressed in the query (it depends on a relationship in another service, or an external call) fetch candidate IDs and authorize them in one batched policy call (OPA can evaluate a policy over an array of inputs). Cost: a page of 100 items at 50 QPS is 5,000 checks/s. At 1 ms per check that's 5 cores of policy evaluation. Query scope moves that work into the database, where it's one indexed query.

Query scopePer-object
Policy runsIn the datastore (RLS / WHERE)In the app or policy engine
Cost, 100 items at 50 QPSOne indexed query5,000 checks/s ≈ 5 cores at 1 ms
Wrong whenPolicy needs external data, or session variables can't be trustedPolicy is expressible in SQL and the DB is the bottleneck

Binding. Pagination: a cursor must encode the scope or be re-evaluated per page. Keyset pagination on (created_at, id) with the scope predicate re-applied each page stops a client using page 1's authorization to read page 2. Offset pagination with a changing filter silently skips or duplicates rows. Snapshot: exports need a consistent read. BEGIN ISOLATION LEVEL REPEATABLE READ in Postgres gives one transaction a fixed snapshot, so a row that becomes unauthorized mid-export can't still land in the file. Version: bulk mutation is a TOCTOU. Authorize, the object changes owner, then you mutate. Bind the decision to the object's version with If-Match: <etag> and reject on mismatch with 412.

Mixed results and leaks. For a bulk mutation with some allowed and some denied items, pick all-or-nothing or partial. All-or-nothing is simpler; partial apply must return per-item results, which leaks the existence of denied items. Return 404 rather than 403 for denied items when existence is sensitive. A count endpoint that omits the scope leaks the total row count; a per-object loop leaks timing. Pick caps: page size 100, export 100k rows or stream, bulk batch 1,000, and set statement_timeout = '5s'.

Tests. Empty result, huge result (page and export caps), cross-tenant (user A's scope never returns tenant B's rows), concurrent change (object changes owner between authorize and mutate), export (snapshot consistency), background job (the worker's query carries the same scope).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Carry authorization through asynchronous jobs.

Answer

Assumptions: multi-tenant SaaS; workers are a shared pool running under one service identity, not the user's credentials; jobs can sit in the queue for seconds to days; roles and policy change while jobs wait.

The answer: Authorize at enqueue, but carry a decision, not a credential. The job envelope holds the principal, the canonical action and resource, the policy revision the decision was made under, an expiry, and an idempotency key: signed so the worker can detect tampering. At execution the worker authenticates as itself (SPIFFE ID, IAM task role, k8s service account), then either revalidates the envelope against the current policy store or redeems a downscoped capability. Revalidate when revocation must be immediate; use a capability when you need offline or low-latency execution and can tolerate revocation bounded by token lifetime.

Mechanism. Revalidation: the worker calls the PDP (OPA, Cedar, or your authz service) with sub/act/res from the envelope. The PDP evaluates against the current policy, so a role revoked five minutes ago denies now. The envelope's policy revision is not the input to the decision: it is a drift detector: if the PDP's current revision differs, you log that the decision was made under a policy that has since changed, which is what you need when auditing why a job ran.

Capability: at enqueue you exchange the user's authority for a downscoped token (RFC 8693 token exchange, or a macaroon with a caveat set). The token is audience-bound to the worker, scoped to the single action, and short-lived: 15 minutes is a common ceiling. The worker validates signature, audience, scope and expiry locally, with no PDP call. Revocation is now bounded by that expiry unless you add a revocation check, which puts the round trip back.

Failure modes.

  • Job outlives the grant. A 3-day-delayed job runs after the user's role was removed. Revalidation denies; a capability still allows until expiry. Detect: deny rate bucketed by job age; alert when p99 age exceeds token TTL.
  • Resource moved or deleted. Job targets a doc that changed tenant. Execution returns 403/404. Detect: correlate the deny with the resource's audit trail; a spike means enqueue-time checks are stale.
  • Retry re-executes a side effect. Detect: duplicate business effects sharing one idempotency key. The key must be enforced at the effect, not just the envelope.
  • Dead letter. A job that can never be authorized sits forever. Detect: dead-letter depth and oldest-message age alert.
  • Over-broad worker identity. If the envelope is forged or the worker ignores it, the service account can act on anything. Detect: audit log shows the worker acting on resources outside any envelope.

Artefacts.

Code (Python 3.12):

Python
import hmac, hashlib, json, time

def enqueue(sub, act, res, policy_rev, ttl=900):
    now = int(time.time())
    env = {"sub": sub, "act": act, "res": res, "pol": policy_rev,
           "exp": now + ttl, "jti": f"{sub}:{res}:{now}"}
    body = json.dumps(env, sort_keys=True).encode()
    return body, hmac.new(KEY, body, hashlib.sha256).hexdigest()

def execute(body, sig, pdp):
    if not hmac.compare_digest(sig, hmac.new(KEY, body, hashlib.sha256).hexdigest()):
        raise Deny("tampered")
    env = json.loads(body)
    if env["exp"] < time.time():
        raise Deny("expired")
    d = pdp.check(env["sub"], env["act"], env["res"])
    if not d.allow:
        raise Deny(d.reason)
    if d.policy_rev != env["pol"]:
        audit("drift", env["jti"], env["pol"], d.policy_rev)
    return perform(env["act"], env["res"], idem=env["jti"])

Trace, ttl=900:

  • t=0 enqueue, exp=900.
  • t=1200 execute: 900 < 1200 → Deny("expired"). The job never reaches the PDP.
  • t=30 execute, role revoked at t=10: exp ok, pdp.check → allow=False → Deny("revoked").
  • t=30 execute, unrelated policy bumped v7→v8: allow=True, policy_rev v8 ≠ env pol v7 → audit drift, then perform.

Table (illustrative latencies):

revalidatecapability
revocation latencynext PDP call≤ token exp (e.g. 15 min)
per-job costPDP round trip, ~5–20 mslocal verify, <1 ms
PDP outagefail closed or stalljobs continue
offline workernoyes

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Implement static and dynamic separation of duty.

Answer

What I'd say first. These are two enforcement points, not two features of one system. Static SoD is a constraint on the role assignment graph: you evaluate it when a grant is created, and the result is a property of the user's effective permissions. Dynamic SoD is a constraint on execution: you evaluate it at authorization time, and the result depends on what this principal already did inside this case or transaction. Static is cheap, auditable and coarse. Dynamic is fine-grained and stateful. Most regulated systems need both, and the deciding question is whether the conflict is absolute (a person must never hold both) or temporal (a person must not do both on the same case).

Assumptions I'd state out loud: role-based access with a hierarchy, a policy decision point in front of the app, and a case or transaction identifier that survives across steps.

Mechanism. Static: expand the user's roles through the hierarchy to effective permissions, intersect with a conflict matrix, then reject or route to an approver. This is NIST SP 800-53 AC-5; SOX ITGC access reviews are where auditors look for it. Dynamic: the PDP needs a shared store keyed by case, recording (principal, step) pairs, and it checks the incoming step against prior steps by the same principal. That store is the whole cost: it is why dynamic SoD breaks under stateless JWT auth or a horizontally scaled service with no shared state.

Trade-off.

StaticDynamic
Evaluatedgrant timeauthorization time
State needednoneper-case store
Blockslegitimate dual-role usersonly the conflicting sequence
Audit trailassignment recordsstep logs
Costone check per grantone store read per decision
Breaks whenrole hierarchy not expandedstate not shared across replicas

Deciding criteria: if the regulator names the roles (financial initiation vs approval), static. If the conflict only exists within one case and the team is too small to separate duties permanently, dynamic plus compensating review.

Code and trace.

Python
# Python 3.12
CONFLICTS = {frozenset(("initiate_payment", "approve_payment"))}

def check_static(effective: set[str], new_role: str) -> bool:
    # effective = roles expanded through the hierarchy, mapped to duties
    return all(frozenset((r, new_role)) not in CONFLICTS for r in effective)

def check_dynamic(case_id: str, principal: str, step: str, store) -> bool:
    prior = store.smembers(f"case:{case_id}:steps")   # {"alice:initiate_payment"}
    for entry in prior:
        p, s = entry.split(":", 1)
        if p == principal and frozenset((s, step)) in CONFLICTS:
            return False
    return True

Trace, case C-1. alice runs initiate_payment → store now holds alice:initiate_payment. alice runs approve_payment → prior contains alice:initiate_payment, the pair is in CONFLICTS → denied. bob runs approve_payment → the prior entry has p = alice ≠ bob → allowed.

Failure modes.

  • Inherited conflict: the static check reads direct grants only, so a role that inherits the conflicting permission slips through. Detect by expanding the hierarchy before the check and alerting when effective-permission conflicts exceed 0.
  • Delegation past expiry: an 8-hour delegation to the initiator stays live if the expiry job fails. Detect by counting grants whose expiry is in the past but which are still active.
  • Service identities: CI/CD accounts hold deploy and approve, and human-scoped checks skip them. Detect by including non-human principals in the scan.
  • Lost dynamic state: two replicas with no shared store let both steps succeed. Detect by running one case across two replicas in a test.
  • Concurrency: two conflicting requests in the same millisecond race the check-then-write. Detect with N concurrent conflicting requests; exactly one should succeed.

When not to. Don't add dynamic SoD where the conflict is absolute: it adds a store read and a race for nothing. Don't rely on static alone for a two-person approval workflow; it cannot see the case.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Handle joiner, mover, and leaver authorization lifecycle.

Answer

Assume an enterprise with Okta as the IdP, SCIM 2.0 for provisioning, OpenFGA for authorization, 10k users, and 200 downstream apps. SLOs are hypothetical but typical. The core is to treat the IdP as the source of truth, propagate changes with effective times, and ensure revocation is timely. For joiners, provision a minimal baseline (email, Slack, VPN) then role-based access via SCIM after manager approval, typically within 1 hour. For movers, recompute entitlements from the new role, revoke obsolete grants, and grant new ones. For leavers, disable the identity, revoke all sessions and tokens, remove every grant, and transfer service ownership. Use event-driven reconciliation with SLOs: leaver revocation under 5 minutes, mover under 15 minutes. The key trade-off is revoke-before vs atomic swap, decided by risk.

A policy engine evaluates attributes (department, title, location) against role definitions. On a mover event, it computes the new entitlement set, diffs against the current set, and applies changes. The diff is a set difference: new_entitlements - current_entitlements = grants_to_add; current_entitlements - new_entitlements = grants_to_revoke. Atomicity matters because granting before revoking creates a window where the user holds both old and new privileges. For high-risk roles (finance, admin), revoke-before-grant; for low-risk (engineering), atomic swap is fine. Reconciliation compares desired state (IdP + policy) to actual state (downstream systems) and reports drift. Run it every 15 minutes.

Revoke-before avoids privilege accumulation but causes downtime; atomic swap avoids downtime but risks a window. Deciding criteria: data sensitivity of old access and cost of user downtime. For a finance role, revoke first; for an engineer, atomic. Also, prefer just-in-time access over standing grants to reduce mover risk.

Failure modes:

  • Stale grants after mover: detection via reconciliation diff; symptom: user retains access to old system; cost: potential data breach. Example: Alice moves from Eng to Finance, still has code repo access for 3 days.
  • Leaver session still valid: detection: monitor active sessions post-termination; symptom: terminated user can access email; cost: data exfiltration. SLO breach: if revocation >5 min, alert. Use short-lived access tokens (e.g., 15 min) and revoke refresh tokens to limit the window.
  • Rehire identity collision: detection: duplicate accounts in IdP; symptom: new hire gets old permissions; cost: security risk. Test by simulating rehire.

Artefact: Lifecycle table.

StageTriggerActionsSLOFailure detection
JoinerHR hire eventProvision baseline (email, Slack), then role-based via SCIM1 hourMissing baseline access; alert if not provisioned within 1h
MoverHR transfer eventRecompute entitlements, revoke old, grant new (revoke-before for high-risk)15 minReconciliation diff shows stale grants; alert if drift >0
LeaverHR termination eventDisable identity, revoke sessions/tokens, remove all grants, transfer ownership5 minActive session post-termination; alert if any session >5 min

Trace: Alice moves from Engineering to Finance. IdP emits mover event at 10:00. Policy engine computes new entitlements: finance-db, payroll. Current: code-repo, ci-cd. Risk tier: high (finance). Revoke code-repo and ci-cd at 10:01, grant finance-db and payroll at 10:02. Reconciliation at 10:15 confirms no drift.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Build just-in-time privileged access on RBAC and ABAC.

Answer

Core answer (first 90 seconds)

Assume human operators on AWS plus Kubernetes, a handful of privileged roles, and an existing IdP. The design: keep the baseline role non-privileged, and make privilege a short-lived grant that a policy engine evaluates at request time. RBAC answers which role a person may activate; ABAC answers whether this specific request is honored right now. The grant is a temporary credential with an exp, not a role binding you have to remember to delete.

Concretely: an eligible assignment (Azure PIM "eligible", or an AWS Identity Center permission set assigned to a group) grants nothing until activation. Activation requires a ticket ID, phishing-resistant MFA, and an approver who is not the requester. On approval the system issues temporary credentials, sts:AssumeRole with DurationSeconds between 900 and 43200 (default 3600; role chaining caps at 3600), and stamps the session with tags (sts:TagSession) carrying ticket, approver, and expiry. The ABAC layer then evaluates those tags on every call.

How it binds to RBAC and ABAC

Two layers, evaluated in order:

LayerQuestionMechanism
RBACMay this principal activate this role?Eligible assignment / group membership
ABACIs this request allowed now?Conditions on session tags, time, resource tags

GCP does the ABAC half natively: an IAM Condition request.time < timestamp("2025-01-01T00:00:00Z") expires the binding without a cleanup job. AWS does it with session tags plus a trust-policy condition. Kubernetes has no expiry on RoleBindings, so you need a controller that deletes the binding at expiresAt, or better, don't bind at all: issue a short-lived OIDC token whose groups claim carries the elevated group, and let the API server's RBAC evaluate it.

Rego policy for the ABAC half:

REGO
package jit

default allow := false

allow if {
  input.action == "s3:DeleteObject"
  "break-glass-prod" in input.principal.eligible_roles
  input.session.mfa == "phishing_resistant"
  input.session.ticket != ""
  time.now_ns() < input.session.expires_ns
  input.resource.tags.env == "prod"
}

time.now_ns() is evaluated per request, so expiry is enforced by the engine, not by a cron job that might be down.

Trace

  1. Alice requests break-glass-prod, ticket INC-4471, MFA asserted.
  2. Approver Bob (≠ Alice) approves; activation row written: {principal, role, ticket, approver, expires_at}.
  3. STS issues credentials expiring at expires_at; session tags set.
  4. Each API call: engine checks tags + time.now_ns() < expires_ns.
  5. At expires_at the credential is rejected by STS itself: no revocation step needed.

Trade-offs

JIT costs an approval round-trip (seconds to minutes) and a dependency on the approval service. It is the wrong tool for machine identities that need continuous access: use workload identity (SPIFFE/SPIRE) instead. It is also wrong when the incident window is shorter than the approval latency; there, keep a break-glass role that activates without approval but pages the security channel and forces post-hoc review within 24h. A permanent elevated role is simpler and has no approval dependency, but it leaves no record of intent: you can't answer "why did Alice have prod-admin on March 3rd."

Failure modes and detection

  • Expiry boundary / clock skew. Issuer and enforcer clocks drift; a grant is honored past exp. Detect: alert when an enforcer accepts a token whose exp is in the past by more than the measured skew (keep it under 60s via NTP).
  • Orphaned grants. Revocation event lost to a queue backlog; grant outlives its window. Detect: reconcile the active-grant table against the source-of-truth activation log hourly; alert on grants with no matching activation row.
  • Approver conflict. Requester approves their own request. Detect: compare requester_id and approver_id in the audit stream; alert on equality.
  • Duplicate activation. Two requests for the same role race. Detect: idempotency key on (principal, role, ticket); alert on a second insert.
  • Approval service outage. Decide fail-closed (deny activation) unless a break-glass path exists; alert on activation latency p99 exceeding the approval SLA.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design break-glass and exception handling.

Answer

What I'd say first

Assume a production system where a policy engine (OPA/Gatekeeper, or cloud IAM) already denies standing admin, and an on-call rotation has to fix an outage at 3 a.m. The goal isn't "allow admins": it's make every bypass attributable, time-boxed, and visible while it's happening.

The core: nobody holds standing privilege. Responders are eligible for a role, not assigned it. Activation is a separate authenticated transaction that mints a short-lived credential, pages a channel, and expires on its own. If the activation path itself is down, the fallback is a sealed credential that is loud, not silent.

Mechanism

Eligibility is a directory group (Okta, Entra ID) mapped to a role. Activation requires phishing-resistant MFA (FIDO2/WebAuthn, not TOTP), a free-text justification, and an incident ID. The system issues a credential with a hard TTL: an AWS STS session capped at 60 minutes (AssumeRole's max is 12 h, default 1 h, so 60 min is a deliberate choice, not a limit), or a Kubernetes bound service-account token via the TokenRequest API with expirationSeconds=3600.

Auto-revoke is the credential's own expiry, not a cleanup job. A cron that revokes is a second thing that can fail; a token that expires cannot be forgotten.

Independent record: activation writes to a log the responder can't edit (CloudTrail, GCP Cloud Audit Logs, or Azure Activity Log) plus the ticketing system. Two stores, because the responder often has write access to one.

Lifecycle

stagecontrolparameter
eligiblegroup membership, no standing rolereviewed quarterly
activateFIDO2 + justification + incident IDapproval SLA 15 min, or auto-approve with page
holdscoped role, one resource setTTL 60 min, no renewal without new justification
observepage on-call + security channelalert < 60 s after activation
expirecredential TTLhard, no extension
reviewticket + audit-log diffwithin 24 h

Trade-offs

Approval is the tension. A second human adds 5–30 minutes to an incident; auto-approve with an immediate page is faster but relies on the page being read. For a customer-facing outage I'd auto-approve and page. For data-destructive actions (dropping a table, rotating a root key) I'd require approval even at 3 a.m. The criterion is reversibility, not severity.

Fail-open vs fail-closed: if the admission webhook is unreachable, failurePolicy: Fail blocks all deploys, including the fix. I'd run two webhook configurations with different namespaceSelectors (Fail for the guardrail namespaces, Ignore for the break-glass path) and alert on webhook errors so the Ignore window is measured in minutes.

Failure modes

  • Policy engine down → deploys blocked. Detect: webhook error-rate alert; drill by killing the webhook in staging.
  • MFA device lost → responder locked out. Detect: activation-failure alert; keep two enrolled keys per responder.
  • Standing wildcard left behind → the real risk. Detect: nightly diff of effective permissions against the eligible set; anything outside the set pages.
  • Alert fatigue → pages ignored. Detect: track activation-to-ack time; if it drifts past 5 min, the channel is dead.

Worked trace

03:12:04. Responder activates prod-break-glass in Entra ID PIM; FIDO2 asserted, justification "incident INC-4471, checkout 500s". 03:12:06. Role active, TTL 60 min; page fires to #on-call and #security. 03:12:31. Responder runs kubectl create token (1 h default) and applies a config fix. 03:14:10. Fix verified, responder deactivates early. 03:14:11. Credential invalid; CloudTrail shows the AssumeRole and every subsequent call. Next day: access review diffs effective permissions; no residual grant.

That's the shape: eligible, not assigned; short TTL, not cleanup; two logs, not one; and a drill that kills the policy engine on purpose.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Cache authorization decisions without breaking revocation.

Answer

What I'd say first

I'd assume the interviewer wants sub-second authorization at high QPS with a revocation SLA measured in seconds, not milliseconds. My default: cache the decision, key it on every input that can change the answer, and bound staleness with a short TTL plus an explicit invalidation signal. TTL is the backstop, not the mechanism.

The core mechanism

A cached decision is only safe if the key changes whenever the answer would change. So the key is a canonical serialization of the decision inputs: subject, tenant, action, resource, and, critically, the versions of the policy bundle and of the attribute/relationship data the decision read. Versioning is what makes revocation work: removing a role bumps the attribute version, so every key containing the old version misses.

Python
import json
def canonical(sub, tenant, action, resource, policy_ver, attr_ver):
    return json.dumps(
        {"s": sub, "t": tenant, "a": action, "r": resource,
         "pv": policy_ver, "av": attr_ver},
        sort_keys=True, separators=(",", ":"))

print(canonical("u42", "acme", "read", "doc:7", 118, 903))

Trace: sort_keys=True orders the six keys alphabetically. a, av, pv, r, s, t. separators=(",", ":") drops the default spaces after each separator. Strings get quotes, ints don't. Output:

{"a":"read","av":903,"pv":118,"r":"doc:7","s":"u42","t":"acme"}

Hash that to a fixed-length key. Two callers with the same inputs produce the same key regardless of dict insertion order.

Bounding the revocation window

Worst-case stale-allow = TTL + invalidation propagation delay. If TTL is 30s and a policy push reaches every cache node in 2s, the window is 32s. Zanzibar-style systems make this explicit with a consistency token (a "zookie") that encodes the data revision; you can require a read "at least as fresh as" a token, which turns unbounded staleness into a bounded one. OPA's decision logs and bundle versioning give you the same handle on the policy side.

Alternatives and when to pick them

approachrevocation windowcost
No cache, evaluate every request~0origin QPS = full traffic
Full-context keyed cache + versioned keyTTL + push delaykey size, version plumbing
Derived entitlement cache (precomputed "can u42 read doc:7")push delay onlywrite amplification on every relationship change

Pick the derived-entitlement cache when the relationship graph is small and changes are rare relative to reads: you get near-zero staleness. Pick the keyed cache when the graph is large and churny, and accept a TTL. Short-TTL-only, with no invalidation push, is acceptable when the revocation SLA is genuinely minutes (an internal dashboard, say) and not when it's a security control.

Failure modes and how you'd see them

  • Stale allow after revocation. Detect by shadow-evaluating recent decision keys against the new policy version on every push and alerting on the count that would flip. That's the only way you find out before an auditor does.
  • Indeterminate errors cached as allow. A timeout from the policy engine must never be stored as allow; cache it as a miss or a short-lived deny.
  • Replica lag. If you read attr_ver from a lagging replica you cache under a stale version. Compare the replica's lag metric against your TTL; if lag can exceed TTL, read versions from the primary.
  • Tighter TTLs cost origin capacity. Illustrative: at 20k decisions/s, a 60s TTL might give a 90% hit rate (2k/s to origin); dropping to 5s might drop the hit rate to ~55% (9k/s to origin). A 4.5x load increase. Measure before you tighten.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do you optimize PDP evaluation latency and attribute retrieval (PIP) in distributed ABAC architectures?

Answer

In distributed ABAC (NIST SP 800-162 / XACML 3.0), remote Policy Information Point (PIP) round-trips are the primary source of authorization latency. Resolving subject, resource, action, and environment attributes over synchronous network hops during policy evaluation turns a single API call into an N+1 query problem, easily driving p99 latency above 100 ms.

To keep p99 evaluation under 5 ms, you shift from runtime attribute pull to localized evaluation and attribute push.

1. Architectural Topology: Co-located PDPs

Do not route every microservice request to a centralized remote PDP cluster. Deploy the PDP as a local sidecar or in-process library (e.g., embedded Open Policy Agent or Cedar engine). This eliminates network transport latency for the PDP invocation itself, reducing evaluation to local CPU and memory access.

2. PIP Optimization Patterns

[Client Request]
       │
       ▼
[PEP / Gateway] ──(1. Subject Token w/ Claims)──► [Local PDP / Sidecar]
       │                                                │
       │ (2. Resource context pushed in-band)           │ (Reads local memory)
       ▼                                                ▼
[Target Service] ────────(Local In-Memory Cache)──► [Local PIP Cache]
                                                        ▲
                                                        │ (CDC / Pub-Sub sync)
                                                 [Attribute Source DB]
  • In-Band Attribute Push (PEP Pre-fetching): Instead of having the PDP reach out to PIPs mid-evaluation, the Policy Enforcement Point (PEP) or API Gateway populates predictable attributes before calling the PDP:
    • Subject attributes: Encode immutable or slow-changing attributes (tenant ID, clearance, department, role set) directly into signed JWT claims during authentication.
    • Resource attributes: When the service handler already fetches the database record for processing, pass those resource attributes (owner ID, status, classification tags) directly into the PDP evaluation payload.
  • Out-of-Band State Synchronization (CDC to In-Memory Engine Store): For dynamic attributes that cannot be passed in-band (e.g., organization-level quotas, project membership graphs, environment flags), replicate PIP state directly into the PDP's memory. Stream database changes via Change Data Capture (Debezium/Kafka) into local PDP storage (such as OPA's in-memory data store or an in-memory key-value store co-located with the sidecar).
  • Local PIP Read-Through Caching with Targeted Invalidation: When PIP calls must be synchronous (e.g., high-cardinality external inventory), implement an in-process PIP cache with deterministic, composite cache keys: hash(tenant_id, entity_type, entity_id, attribute_names, schema_version). Set tight, bounded TTLs (e.g., 5–30 seconds) coupled with pub/sub invalidation events on attribute mutation.

3. Worked Latency & Scale Comparison

Pipeline PatternAttribute Retrieval MechanismNetwork Hops per AuthZ RequestEvaluation p99Revocation Latency
Naive Remote PIP/PDPPDP synchronously calls remote DBs/services for each attribute3–5 hops (PEP→PDP→PIP 1..N)45–180 msImmediate (< 10 ms)
Sidecar PDP + Central CacheLocal PDP fetches attributes from remote Redis cluster1–2 network hops8–20 msCache TTL (~1–5 s)
Sidecar PDP + In-Band Push & CDCClaims in JWT + resource in PEP payload + background sync0 network hops (all in-memory)0.8–2.5 msCDC lag (~100–500 ms)

4. Failure Modes & Mitigations

  • Memory Exhaustion on PDP Sidecars: Replicating the entire enterprise attribute dataset into every PDP sidecar will exhaust container memory limits. Partition the synced data by tenant ID or service domain so each service only loads the attributes its assigned policies require.
  • Inconsistent Split-Brain Decisions during Replication Lag: If an attribute updates (e.g., clearance revoked from Secret to Unclassified) and CDC lag is 400 ms, the PDP may evaluate against stale data. For critical security boundaries, configure the policy to assert a minimum freshness timestamp (env.request_time - attribute.updated_at < max_staleness_ms), failing closed if attribute staleness exceeds tolerance.
  • Evaluation Time Complexity with Deep Graph Traversal: ABAC policies checking nested relationship hierarchies (e.g., parent group inheritance) can degrade to $O(N)$ or $O(N^2)$ algorithmic complexity. Normalize relational graphs into flat membership sets during the out-of-band ingest stage so policy evaluation reduces to an $O(1)$ set lookup.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design policy-engine availability and failure behavior.

Answer

Clarify before designing. Three things decide this: what fraction of decisions are privileged writes, what the revocation SLA is (how long a fired employee's credential can still authorize something), and whether the engine is in the request path or beside it. I'll assume a multi-tenant B2B SaaS: ~40k authz decisions/s at peak across three regions, a ~2 MB policy bundle (~4k rules), a 5 ms p99 budget for the local decision, a 60 s revocation SLA for privileged operations and 15 minutes for ordinary reads. Tighten that 60 s to 5 s and the caching design below changes completely.

The answer. Classify every operation by the consequence of a wrong allow, then give each class an explicit failure behavior. Three classes:

  1. Privileged writes: role grants, payouts, data export. Fail closed. No cached allow, no tolerance for a bundle older than what is already loaded. Timeout, parse failure, or unknown principal all resolve to deny, with a retry-after and an operator-visible counter.
  2. Ordinary reads and low-risk writes: list invoices, read a dashboard. Bounded-stale allow: serve from a local cache whose TTL is derived from the revocation SLA, not from a round number.
  3. Availability-critical, non-security paths: UI feature flags, rate-limit tiers. Fail open to a documented non-privileged default, and count every fallback.
classexampleon engine failurestaleness boundalert
privileged writerole grant, payoutdeny + retry-after0 (re-evaluate per request)deny rate > 2× baseline for 5 min
ordinary readlist invoicesserve cached allowTTL 30 sbundle age > 2× poll interval
non-securityfeature flagfail open to default15 minfallback counter > 0

Why bounded staleness, not "cache it". A cached allow is a claim about the world at time T. The risk isn't the cache, it's the gap between T and now: specifically, a permission revoked after T that the cache still honors. So the number to negotiate with security is the revocation window, not the TTL. Worst case here is poll max 60 s + bundle activation ~2 s + cache TTL 30 s = 92 s of stale allow, which blows the 60 s SLA. Two fixes: privileged ops already re-evaluate per request, and revocations ride a separate channel polled every 10 s instead of the full bundle.

Why versioned bundles give you last-known-good. Bundles are content-addressed and signed; activation is atomic, so a bundle that fails signature verification or parsing never replaces the running one. With persistence_directory set, OPA loads the last activated bundle from disk before its first poll: without it, a sidecar restart during a control-plane outage is a full outage.

YAML
# OPA sidecar
bundles:
  authz:
    service: controlplane
    resource: bundles/authz.tar.gz
    polling:
      min_delay_seconds: 30
      max_delay_seconds: 60
    signing:
      keyid: global
persistence_directory: /var/opa

On the gateway side, Envoy's ext_authz failure_mode_allow defaults to false; leave it there and set it explicitly so nobody "fixes" an outage by flipping it.

Failure modes and how you see them.

  • Control plane unreachable. Sidecars keep serving last-known-good. OPA's bundle polling defaults are 60–120 s, so page at bundle age > 5 min, not at the first missed poll.
  • Bad policy pushed. Signature check rejects tampering; canary 1% of sidecars for 10 min before full rollout; auto-rollback if the deny rate moves more than 3σ from baseline.
  • Clock skew. Compute TTLs from a monotonic clock, or a skewed node serves stale allows indefinitely.
  • Revocation list growth. Cap entries per tenant; on overflow, fail closed for that tenant rather than silently dropping revocations.

If the revocation SLA ever drops below the bundle poll interval, stop patching the cache and move to push-based revocation or per-request evaluation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design a safe policy-as-code delivery pipeline.

Answer

Assumptions: policies are OPA/Rego bundles evaluated by services; decisions are allow/deny plus obligations; attributes come from identity and resource services; production decision logs are available. Checked against OPA 1.x / Rego v1.

A safe pipeline treats policy, data, schemas, and fixtures as one versioned artifact, gates on differential decisions, and canaries by shadowing before enforcement.

StageGateFailure signal
VersionPolicy, data, JSON schemas, attribute contracts, and fixtures in one repo; lockfile pins OPA versionSchema and fixture drift
Static CIopa fmt (fail if it would rewrite), opa check, opa test --coverageCoverage below 90% on changed rules
PropertyGenerated inputs through opa test with with mocksUndefined result where allow/deny expected
Forbidden patternsopa eval for http.send, time.now_ns in authz pathsNon-deterministic builtin in decision path
Differential replayReplay last 7 days of decision logs through new bundleAny diff in allow/deny or obligations
ReviewCODEOWNERS, two approvals for authz/Single approver on sensitive path
Artifactopa build -b . -o bundle.tar.gz; sign with cosign; push to OCI registryUnsigned or mutable bundle
CanaryShadow 100% for 24h, then enforce 1% tenants, 5%, 10%, 50%, 100%Deny rate +2pp, latency +20ms, mixed revisions > 5 min
RollbackPrevious bundle revision and data version pinnedRollback takes longer than 60s

Differential replay is the load-bearing gate. Unit tests only cover fixtures; replaying logged inputs catches attribute contract drift and undefined results. A rule that previously returned false and now returns undefined is a silent deny or bypass depending on the caller. Compare the full result, not just allow, because obligations like redact_fields or require_mfa can change while allow stays true.

Canary by shadowing first: run the new bundle in parallel on live traffic, enforce nothing, and diff decisions. At 10k rps and 1 ms per eval, shadowing adds 10 CPU-seconds/s, so budget roughly 10 cores. Then enforce on 1% of tenants for 30 minutes, then 5%, 10%, 50%, 100%. Watch deny rate, allow expansion, and p99 latency. If the policy is safety-critical, do not canary by scope; shadow until zero diffs, then roll out fully. Bounded scope can give the same user different decisions across requests, which is worse than a short full outage for authz.

Failure modes and detection:

  • Attribute contract drift: identity service renames groups to group_ids; fixtures pass, production denies spike. Detect by replaying recent logs and by contract tests against the live schema.
  • Stale data: bundle data file is not updated; detect bundle revision mismatch and a data freshness metric.
  • Undefined result: new rule returns undefined instead of deny; differential replay flags it as a diff from false.
  • Bundle activation race: some instances run old revision, some new; decision logs include bundle revision, alert if mixed revisions persist over 5 minutes.
  • Canary scope leak: tenant ID missing from input; detect by comparing shadow decisions grouped by tenant.

Trade-offs: shadowing doubles eval cost and log volume; differential replay needs 7 days of logs and a replay harness. If the policy is small and low-risk, full CI plus a signed bundle and rollback is enough; shadowing and replay cost more than the risk. If the policy is safety-critical, skip scope canaries and use shadow plus full rollout after zero diffs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design privacy-aware authorization decision logging.

Answer

What I'd say first

A decision log exists to answer three questions after the fact: why was this allowed or denied, what policy was in force, and can I prove it without holding the data that made the decision sensitive. So I'd separate the decision record from the request payload. The record is small, structured, and long-lived; the payload is large, sensitive, and short-lived or never stored.

Assumptions I'd state: a central PDP (OPA, Cedar, or an in-process library) emits one event per decision; the log sink is append-only and separate from the application database; retention is driven by a compliance regime, not by debugging convenience.

The record

Every event carries: a server-generated decision ID (UUIDv4 or ULID), nanosecond timestamp, tenant ID, a pseudonymous principal handle, canonical action and resource identifiers (not raw URLs. Normalize /users/123?x=1 to user:read + user:123), outcome (allow/deny/indeterminate), policy bundle version and hash, the matched rule ID or reason code, enforcement point, decision latency, cache hit/miss, and error state.

Privacy technique: pick per field, not per system

techniquekeeps correlation?reversible?use whenwrong when
dropnonofield never needed for audityou later need to explain a denial
redact/maskpartialnofree-text reason stringsyou need to join across events
keyed hash (HMAC-SHA-256)yes, within key scopenoprincipal/resource IDs you must correlatekey rotation without a version tag breaks joins
tokenize (vault)yesyes, via vaultyou must re-identify under legal processvault becomes a new high-value target

The deciding criterion is correlation: if you need to answer "show every decision for this user," you need a stable pseudonym, so hashing beats redaction. If you must re-identify for a subpoena, tokenization is the only one that survives: at the cost of a vault you now have to defend.

Python
# Python 3.12
import hmac, hashlib, uuid, time

def decision_event(tenant, principal_id, action, resource, outcome, policy_ver, rule):
    key = TENANT_KEYS[tenant]          # per-tenant HMAC key, versioned
    handle = hmac.new(key, principal_id.encode(), hashlib.sha256).hexdigest()[:32]
    return {
        "decision_id": str(uuid.uuid4()),
        "ts_ns": time.time_ns(),
        "tenant": tenant,
        "principal": handle,
        "action": action,
        "resource": resource,
        "outcome": outcome,
        "policy_version": policy_ver,
        "rule": rule,
    }

Trace: principal_id="alice@acme.com" under tenant acme produces a fixed 32-hex-char handle. The same email under tenant globex produces a different handle, so cross-tenant joins fail by construction. Rotating TENANT_KEYS["acme"] changes every handle, so store the key version alongside the handle or you lose the ability to join old and new events.

Failure modes

  • Log injection / cardinality blowup: logging raw resource paths lets an attacker write arbitrary strings and explode index cardinality. Detect via per-field cardinality dashboards; cap field length.
  • Silent deny gap: if the PDP short-circuits before emitting on a malformed request, denials vanish. Detect by comparing PDP request count to emitted event count; alert on divergence.
  • Key loss: losing the HMAC key makes historical handles unjoinable. Detect at rotation time by verifying old events still resolve.
  • Retention drift: PCI DSS v4.0 requires 12 months of audit log retention with 3 months immediately available; GDPR Article 5(1)(c) pushes the other way. Detect by a scheduled job that asserts the oldest retained event is within policy.

Retention and access: store in an append-only sink (WORM bucket or a log store with object-lock), restrict read to a break-glass role, and log reads of the decision log itself.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Make ABAC access explainable to users and auditors.

Answer

In the first 60–120 seconds: I’d treat explainability as part of the decision, not a separate policy. For every request, the policy engine emits a decision record: allow/deny, stable rule IDs, policy version, attribute snapshot, and a minimal reason set. Then two renderers: user-facing (why denied, what to change) and auditor-facing (full trace, reproducible). Assumptions: OPA/Rego or Cedar, attributes from IdP/CMDB, audit retention 1 year, 5k decisions/s.

Mechanism: In Rego, don’t reimplement policy in prose. Add reason rules next to allow rules. Example:

REGO
package authz
import rego.v1

default allow := false

allow if {
    input.action == "read"
    input.resource.classification == "secret"
    input.subject.clearance >= 5
}

reasons contains "clearance_too_low" if {
    input.action == "read"
    input.resource.classification == "secret"
    input.subject.clearance < 5
}

For input {action:"read", resource:{classification:"secret"}, subject:{clearance:3}}, allow is false: the only allow rule fails at clearance >= 5. reasons contains clearance_too_low. The decision log carries result.reasons, policy_version, decision_id, and input_hash. A renderer maps clearance_too_low to: “Denied: alice (clearance=3) read doc:Q3 (classification=secret). Rule clearance_too_low (policy v42) matched: secret read requires clearance >= 5. To allow: raise clearance to >=5 or reclassify doc to internal.” That string is generated from the rule ID and the actual attribute values, so it cannot drift from the decision unless the renderer is untested.

Alternatives: OPA’s opa eval --explain=full gives an exact evaluation trace without extra rules, but it is verbose, exposes policy internals, and is too slow for every request. Post-hoc log replay is cheap and reproducible for auditors if you store the input and policy version, but it cannot explain a live decision to a user. A sidecar that reimplements policy is fast and tailored, but it duplicates semantics and drifts. Deciding criteria: user-facing explanations need minimal, redacted reasons; auditors need full, versioned, replayable traces. Use engine-native trace for audit sampling, decision-log reasons for users.

Failure modes: (1) Explanation drift: renderer says clearance >=5 while policy changed to >=4. Detect with golden tests: for each reason rule, generate a request that flips the decision, assert the rendered string matches the engine. Run in CI. (2) PII leak: explanation includes subject.ssn or full attribute. Detect with a redaction allowlist and log scanning; redaction adds a small cost per explanation. (3) Performance: full trace at 5k rps is not free. Worked example: 1 KB per decision log at 5k rps = 5 MB/s = 432 GB/day; sample 1% for full traces and keep 30 days. (4) Incomplete trace: Rego short-circuits at first allow, so a deny may have multiple reasons. Evaluate a separate reasons set and assert its size against expected. (5) Stale attributes: explanation cites clearance=3 from a 10-minute-old cache. Include attribute source and timestamp in the record; detect by comparing to IdP at audit time.

For auditors, the record must include decision_id, policy_version, input_hash, attribute_sources, rule_ids, and timestamp. That lets them replay the exact decision against the exact policy and attribute snapshot. For users, show only the matched rule and the smallest change that flips it. Validate the explainer against the same decision semantics, not prose.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Define authorization safety and operability metrics.

Answer

Core answer

Two families, answering different questions. Safety metrics ask: did anyone get access they shouldn't have, and when we take access away, does it actually stop working? Operability metrics ask: does the decision point stay up, fast and correct while it does that.

The assumption I'd state up front: "safe" means no unauthorized effective access, not no unauthorized policy. A grant that exists but is never enforced is a policy bug; a grant that is enforced is an incident. So every safety metric is measured at the enforcement point, not at the policy store.

The two headline numbers I'd put on a dashboard:

  • Revocation latency p99: time from the access-removal event (group removal, role change, offboarding) to the last request that still succeeds with the old entitlement. This is the number that decides whether offboarding is real.
  • Indeterminate decision rate: fraction of authorization decisions returning neither allow nor deny (PDP error, timeout, missing policy), per 10k decisions.

The metric set

metricdefinitiontarget / signal
revocation latency p99removal event → last allowed request with old entitlementbounded by token TTL + cache TTL; alert if > 2× design
stale grantsgrants not exercised in 90d, or whose source group no longer exists% of total grants; watch the trend, not the absolute
toxic combinationsidentities holding both sides of a separation-of-duties paircount + time-to-remediate; alert on any new pair
indeterminate ratenon-allow/non-deny decisions per 10kabove 0.1% is a page
cross-tenant denialsdenied requests where subject tenant ≠ resource tenanta spike means a bug or an attack
privilege-expansion diffnet new grants per policy deployreview any deploy that adds grants
enforcement coverage% of services/resources that call the PDP vs local allowlistscatches a fleet that bypasses the engine
decision latency p99PDP decision time10–50 ms typical for a cached PDP
cache stalenessmax age a cached decision can outlive a policy changemust be ≤ the revocation budget
access-review completion% reviews closed on time, % revocations actually executedexecution rate matters more than completion

Trade-offs

The real knob is cache TTL, because it sets a floor under revocation latency. Worked: access-token TTL 15 min, decision cache 60 s, PDP propagation 200 ms → end-to-end revocation p99 ≈ 15 min 60.2 s. Drop the token to 5 min and the cache to 10 s and you get ≈ 5 min 10.2 s, but you've tripled introspection load and made the PDP a hard dependency on every request. Shorter TTL buys revocation speed and costs availability.

Fail-open vs fail-closed is the other one. Fail-closed protects safety and turns a PDP outage into a full outage, so the PDP's availability target has to exceed every service it gates. Fail-open keeps services up and makes each PDP outage an unauthorized-access window: acceptable only if you bound it with a short fail-open TTL and alert on it. Decide by blast radius: a wrong-allow on a public read is cheap; a wrong-allow on money movement or cross-tenant data is not.

Failure modes

  • Revocation measured at the PDP but not the enforcement point. You revoke in 200 ms; the service caches for 5 min; real latency is 5 min. Detect by injecting a synthetic revocation and probing the enforcement point, not the PDP.
  • Indeterminate treated as allow. The PDP 500s, the sidecar defaults open. Detect by alerting on indeterminate rate and running a canary that asserts deny on a known-bad request.
  • Stale cache after rollback. Policy rolls back, caches hold the old decisions. Detect by versioning policy and putting the version in the cache key.
  • SoD drift. Combination rules evaluated nightly, new grants land in between. Detect by evaluating on every grant event.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Evolve authorization schemas and policy data safely.

Answer

Core answer

Assume the PDP is OPA evaluating Rego bundles, attributes are loaded into data.users from the IdP, and every decision is logged with its input and bundle revision. The change I'll use as the running example: role (one string) becomes roles (a list), because a person can now hold several roles.

The safe sequence is: version the contract, dual-read with a stated precedence, backfill, replay, then flip producers and delete the old field. The precedence rule is the whole game: write it down before you touch data.

Why dual-read, and what precedence means

A rename is not one schema change, it's two with a window between them. During the window both fields exist and the policy must read both. The rule: the new field wins whenever it is present, including when it is empty. "Present" is not "non-empty": an empty roles list means "this user has no roles", and falling back to role there silently re-grants access.

Rego, checked against OPA 0.60:

REGO
package authz

# New contract wins; old field is the fallback.
user_roles := data.users[input.user.id].roles if data.users[input.user.id].roles

user_roles := [data.users[input.user.id].role] if not data.users[input.user.id].roles

allow if user_roles[_] == "admin"

Trace, three users mid-migration:

data.users[uid]user_rolesallow
{"role":"admin","roles":["admin","billing"]}["admin","billing"]true
{"role":"admin"} (not backfilled)["admin"]true
{"roles":[]} (explicitly none)[]false

Row 3 is the one that bites: an empty list is a defined value in Rego, so the first rule fires and the fallback never runs. If you instead gate the fallback on count(roles) == 0, row 3 falls through to role and re-grants admin.

Order and rollback

Backfill before you flip producers, never after. Producers (the IdP sync job) write both fields during the window; consumers (policies) read both. Flip producers to write only roles once replay shows zero divergence, then delete role from the loader only after an inventory query proves no bundle references it.

Replay: sample decision logs, re-evaluate under the new bundle, diff allow/deny. At 40M decisions/day, a 1% sample over 30 days is 12M evaluations: cheap enough to run per deploy. Backfilling 12M user records at ~2k writes/s is about 100 minutes, so it fits a maintenance window.

Failure modes

  • Silent semantic drift: role:"admin" meant "is an admin"; roles:["admin"] might mean "may act as admin". Detection: replay diff plus a canary bundle on 1% of traffic.
  • Partial backfill: some users have roles, some don't. Detection: a count query for records missing roles; alert if it hasn't reached zero before the producer flip.
  • Rollback: keep the old bundle revision pinned and role populated until the new bundle has run clean for a full business cycle (a month, to cover month-end access reviews).

Alternatives

StrategyWhen it's rightCost
Big-bang renameSingle consumer, no logged decisionsAny missed reference is an outage
Dual-read + precedenceMultiple policies, logged decisionsTwo fields to keep consistent
New policy package, old untouchedYou can route by tenantDuplicate policy logic to maintain

Don't dual-read if the two fields can disagree on meaning rather than just shape, then you need a translation layer with an explicit mapping, not a fallback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Review an authorization system end to end.

Answer

Let me clarify the scope: we're reviewing an authorization system end to end to ensure it enforces the intended policy correctly, efficiently, and securely, and that it can be operated and evolved safely. I'll assume we have access to the policy, logs, and a staging environment where we can run tests without affecting production. The core answer is: map the request flow, then for each stage (authentication, resource resolution, policy input, decision, cache, enforcement) verify correctness, measure performance, and probe failure modes. Then review the operational and administrative aspects.

Start with authentication. Verify that identity is established and passed correctly. For JWT, check signature validation, expiry, and revocation. A common failure is accepting tokens with alg: none or not checking the audience. Test with expired and tampered tokens.

Resource resolution: ensure the resource identifier is canonicalized. For a request to /api/documents/123, the system must map 123 to the correct document. Failure modes include path traversal (/api/documents/../admin) or IDOR where a user can access another user's document by changing the ID. Detect by fuzzing IDs and checking access logs.

Policy input: gather attributes from trusted sources. For ABAC, this might be user roles from LDAP, resource tags from a database, and environment context like time of day. A failure is attribute injection: if a user can set their own role in a header, the policy might allow unintended access. Validate that all attributes come from authoritative sources.

Decision: evaluate the policy. In OPA/Rego, the default is deny unless an allow rule matches. Explicit deny rules take precedence. A common bug is a rule that allows when an attribute is missing, e.g., allow { input.user.role == "admin" } will not match if role is absent, but if the policy has a default allow, that's a bug. Test with missing attributes, empty arrays, and unexpected types. Measure evaluation latency: for a simple policy, it's ~1-2ms; complex policies with many rules can hit 10ms or more.

Cache: caching decisions can cut latency from 10ms to 1ms, but if a user's role is revoked, the cache may still allow access until TTL expires. Use short TTLs (e.g., 30s) or event-driven invalidation. A failure mode is cache key collision: if the key doesn't include all relevant attributes, a decision for one user might be served to another. Include user, action, resource, and any context in the key.

Enforcement: ensure the decision is applied at every entry point. A common gap is a service that calls another service directly, bypassing the API gateway. Detect by scanning all network paths or using a service mesh with mTLS and policy enforcement. Also check for alternate paths: legacy APIs, admin interfaces, or direct database access.

Tradeoffs: Centralized policy (OPA) gives consistency and easier auditing, but adds a network hop and a single point of failure. Distributed policy (library in each service) reduces latency but risks version drift. Choose centralized if you have many services and need strict compliance; distributed if latency is critical and you can manage deployments. RBAC is simple but can't express fine-grained rules like "editors can only edit documents they own". ABAC is flexible but harder to reason about and test.

Worked example (hypothetical): Trace a request to GET /api/documents/123.

  1. Auth: JWT validated, sub=alice, roles=[editor].
  2. Resource resolution: document 123 -> owner=bob, tags=[public].
  3. Policy input: {user: alice, action: read, resource: {owner: bob, tags: [public]}}.
  4. Policy (Rego): allow { input.action == "read" input.resource.tags[_] == "public" } Decision: allow.
  5. Cache: key = sha256(user+action+resource). TTL=60s. Miss -> evaluate -> store.
  6. Enforcement: API gateway allows request. Now test deny: user=charlie, roles=[viewer], resource tags=[private]. Policy denies. Test indeterminate: missing user role -> default deny. Measure: policy evaluation 2ms, cache hit 0.5ms. p99 with cache 3ms, without 15ms.

Operational review: Check role administration: who can grant "admin"? Is there separation of duty? For example, can a user approve their own access request? Lifecycle: when an employee leaves, are roles revoked within 24 hours? Exceptions: are there break-glass accounts? Are they logged and reviewed? Logs: do they capture the decision, input attributes, and policy version? Alternate paths: are there legacy SOAP APIs or direct database access that bypass policy?

Canary and rollback: Deploy policy changes to 1% of traffic. Monitor allow/deny rates and latency. During canary, watch for expansions (unexpected allows) and lockouts (unexpected denies). If allow rate jumps unexpectedly, rollback. Verify rollback by checking that the old policy version is active and decisions revert.

Residual risks: Document gaps, e.g., "cache TTL of 60s means revocation can take up to 60s to propagate." Assign owner and deadline.

Curated: · Written: · Reviewed:

Difficulty: Hard