API Security, Authentication and Authorization Questions
Controlling who can call an API, what they may do, and defending it against abuse. Covers the access-control mechanics: API keys, OAuth 2.0 flows, OpenID Connect, JWT issuance/validation, session vs. token auth, scopes/roles for fine-grained authorization, token lifetime and refresh, mutual TLS, and machine-to-machine vs. user-delegated access. Also covers the adversarial hardening view: input validation, injection and deserialization risks, broken object-level authorization (BOLA), mass assignment, secrets handling, and the OWASP API Security Top 10, plus securing data in transit, preventing enumeration/scraping, and testing APIs for vulnerabilities.
Explain the differences between input validation, schema/contract validation (OpenAPI/JSON Schema), and output encoding. Give concrete examples of how each prevents different attack classes such as SQL injection, XSS, and parameter pollution, and list common developer mistakes that lead to validation bypasses.
Sample Answer
Direct answer
Input validation checks that a value is well-formed for the field it fills (a phone number
looks like a phone number); schema or contract validation (commonly using OpenAPI, a
specification format for describing an API's shape, or JSON Schema, a specification for
describing the structure of JSON data) checks that an entire request or response matches the
API's declared shape (required fields present, correct types, no unexpected extra fields); output
encoding transforms data on the way out so that a value which is safe as data cannot be
reinterpreted as code by whatever consumes the output (a browser rendering HTML, a database
executing a query). They are complementary layers, not substitutes for each other, and each
blocks a different attack class.
Structured elaboration
Input validation. Confirms an individual value conforms to expected format, range, and type
before it is used: a string that should be an email address actually looks like one, a quantity
field is a positive integer, a date is a real calendar date. This is the first line of defense
against malformed or unexpected data reaching business logic, but on its own it does not
guarantee an entire request is well-formed (a required field could simply be missing) or that
data is safe wherever it eventually ends up being used.
Schema and contract validation. Validates the request or response as a whole against a
formal contract: every required field present, every field the correct type, no unrecognized
fields silently accepted. Enforcing this at the API boundary (often automatically, since an
OpenAPI or JSON Schema definition can generate a validator) catches an entire category of bug
before it reaches handler code at all, and it directly prevents mass assignment style problems,
where an unexpected extra field in a request body ("isAdmin": true tacked onto a normal
profile-update payload) gets silently accepted and bound onto an internal object because nothing
rejected the unexpected field in the first place.
Output encoding. Transforms data based on where it is being written to, so that untrusted
data embedded in an output cannot be reinterpreted as a command by whatever parses that output.
The same string needs different encoding depending on its destination: HTML-encoding before
writing into an HTML page (so <script> in a stored value renders as visible text, not as an
executed tag), parameterization (not encoding) before using a value in a SQL query, so the
database engine never treats the value as part of the query's syntax.
How each prevents a different attack class:
- SQL injection is fundamentally an output-encoding problem, even though it is often
discussed as if it were an input-validation problem: a value that passes every reasonable
input-validation rule (a legitimate-looking last name likeO'Brien) can still break a
hand-built SQL string if it is concatenated directly into the query rather than passed as a
parameter. Parameterized queries (or an ORM that parameterizes for you) are the actual fix,
since they keep the value as data and never let it become part of the query's syntax,
regardless of what characters it contains. - Cross-site scripting (XSS) is an output-encoding problem specifically for the HTML/JS
context: a stored value that was correctly input-validated as "a non-empty string under 500
characters" can still contain<script>alert(1)</script>, and only encoding at render time
(or a strict content-security policy as defense in depth) stops that string from executing as
code when rendered in a browser. - Parameter pollution (sending the same parameter name multiple times, or in an unexpected
location, to see which value a poorly-specified handler actually uses) is primarily a
schema/contract validation problem: a strict schema that specifies exactly one value is
expected per field, and rejects a request that violates that shape, closes the ambiguity that
parameter pollution exploits.
Common developer mistakes that lead to validation bypasses:
- Validating on the client side only (in JavaScript in a browser, for example) and trusting that
client-side check server-side; any client-side validation is a request the server never sees
if the caller bypasses the browser entirely. - Validating a nested or optional field's presence but not revalidating its contents once it
is inside a larger, already-validated object. - Doing input validation and then building output by string concatenation anyway (
f"SELECT * FROM users WHERE name = '{name}'"), which discards everything input validation bought you the
moment it hits the output boundary, since input validation was never the layer responsible for
safe output construction in the first place. - Allowlisting only some fields in a schema (
additionalProperties: truein JSON Schema, or the
API framework's default of silently accepting unknown fields) rather than explicitly rejecting
unrecognized fields, which reopens the mass-assignment gap schema validation is supposed to
close.
Worked example
A profile-update endpoint expects {"displayName": string, "bio": string}. An attacker sends
{"displayName": "Jane", "bio": "hi", "isAdmin": true}.
- Input validation alone (checking
displayNameandbioare non-empty strings under some
length) says nothing about theisAdminfield, since input validation as commonly implemented
checks the fields it knows about, not the absence of fields it does not. - Schema validation with
additionalProperties: falserejects the whole request outright,
becauseisAdminis not a field the schema declares, closing the mass-assignment path before
it ever reaches the handler. - Separately, if
displayNameis later rendered on a public profile page as
<h1>{displayName}</h1>with no output encoding, an attacker who sets
displayName = "<img src=x onerror=alert(1)>"(a value that legitimately passes "non-empty
string under some length") gets that payload executed in every visitor's browser; only
HTML-encoding at render time (or an equivalent templating engine that encodes by default)
closes that specific gap, and it closes it regardless of what input validation rule was or was
not applied at write time.
Trade-offs and pitfalls
- These three layers fail independently, so skipping any one leaves a real gap, not a
redundant one: a request can pass schema validation perfectly (every field the right shape)
and still carry a payload that is dangerous purely because of where it later gets rendered or
interpreted, which is exactly why output encoding cannot be replaced by "we already validated
the input." - Overly strict schema validation has a real cost. Rejecting anything not explicitly listed
in the schema (additionalProperties: false) is the right default for security, but it also
means any new field a client starts sending, even a harmless one, breaks until the schema is
updated; this is a deliberate trade of forward-compatibility for safety, worth stating rather
than treating as a free win. - Common wrong turn: encoding once, at input time, and trusting it downstream. Encoding for
the wrong destination (or encoding too early, before the value passes through another layer
that expects raw data) is a frequent source of both broken functionality and residual
vulnerability; encode as close as possible to the point of output, for the destination that
specific output is going to.
Walk through the API key management lifecycle you'd put in place: issuance workflow, key metadata (owner, scopes, creation time), secure storage (hashed keys vs plaintext), rotation policies (automatic/manual), revocation propagation, and tying rate limits/auditing to keys. Describe how to discover keys across services and how to handle emergency revocation.
Sample Answer
Direct answer
An API key management lifecycle covers the key from birth to death: issue it through a
controlled workflow that captures ownership and scope up front, store only a hash of it (never
the plaintext) so a database leak does not directly hand out usable keys, rotate and revoke it
through processes that do not require redeploying the calling service, and tie every request
back to the key that made it so rate limits and audit trails are meaningful per key rather than
anonymous.
Structured elaboration
Issuance workflow. Generate keys with a cryptographically random, sufficiently long value
(not a predictable or sequential identifier), and require the requester to specify an owner (a
team or service, not just an individual, since individuals leave) and the intended scopes before
a key is minted. Return the plaintext key exactly once, at creation time, and never again,
setting the expectation from day one that "I lost my key" means "generate a new one," not
"look up the old one."
Key metadata. Persist, separately from the key material itself, an owner, a creation
timestamp, the granted scopes, a human-readable description of what the key is for, and a
last-used timestamp. This metadata is what makes the rest of the lifecycle possible: without a
recorded owner, revocation has nobody to notify; without last-used tracking, you cannot tell a
stale, unused key from an active one when deciding what is safe to clean up.
Secure storage: hashed keys, not plaintext. Store a one-way hash of the key (a fast
cryptographic hash is appropriate here, unlike password storage, since API keys are already
high-entropy random values rather than low-entropy human-chosen secrets, so the slow,
work-factor-heavy hashing used for passwords is not the load-bearing defense here the way key
length and randomness are); at request time, hash the presented key and compare against the
stored hash. This means a database compromise reveals hashes, not usable keys, mirroring the
same principle password storage uses, applied to a different kind of secret.
Rotation policies. Support both automatic rotation on a schedule (appropriate for
machine-to-machine keys with no human in the loop to notice a problem) and manual, on-demand
rotation (for a suspected leak). Rotation should support a brief overlap window where both the
old and new key remain valid, so a caller can pick up the new key without a hard cutover causing
a synchronized outage the moment the old key stops working.
Revocation propagation. Revoking a key must take effect everywhere that validates it, quickly
and consistently; a design where each service caches key-validity locally for an hour means a
revoked key can still work in some parts of the system for up to an hour after the security team
believed it was dead. Either centralize validation (every service checks a shared, low-latency
key-validation service or cache) or keep local cache TTLs short enough that the propagation delay
is an accepted, explicit part of the incident-response plan rather than a surprise.
Tying rate limits and auditing to keys. Once a request is authenticated by a specific key,
apply rate limits and log the key's identifier (not the raw key) on every request. This is what
turns "someone is abusing our API" into "key k_a1b2... (owned by Acme Corp, integration
service) is abusing our API," which is the difference between a vague alert and an actionable
one.
Discovering keys across services. In any organization beyond a handful of services, keys
proliferate faster than any single team tracks manually; maintain a central inventory (the
metadata store described above, exposed through a dashboard or API) that every service's
key-issuance path writes to, so "list every key that has ever been granted the billing:write
scope" is a query, not an archaeology project during an incident.
Emergency revocation. For a confirmed leak, the process needs to go faster than the routine
rotation path: revoke the specific key immediately (propagating per the point above), and, if the
leaked key's blast radius is unclear, treat the associated owner's other keys and any resources
the leaked key could reach as suspect until proven otherwise, since attackers who obtain one
credential frequently pivot to look for others nearby.
Worked example
A key k_live_9f8e... is issued to a partner integration with scope orders:read. Its stored
record: {owner: "Acme Corp integration", scopes: ["orders:read"], created: "2026-01-15", last_used: "2026-08-09", hash: "<stored hash, not the key>"}. Only the SHA-256 hash of the key
is stored server-side; the plaintext was shown once, at creation. On 2026-08-09, this key is
found committed to a public repository. Emergency revocation: the key is immediately marked
revoked in the central store; every validating service, whether it checks a shared low-latency
cache or the store directly, rejects it on the next request within the accepted propagation
window; a new key is issued to the same owner with the same scope so the partner integration can
resume without a scope-approval round trip; and the access log for k_live_9f8e... is pulled to
determine whether any orders:read calls occurred from an unexpected source between when the
leak likely occurred (the commit's timestamp) and when it was revoked, which is the concrete
answer to "was this actually exploited."
Trade-offs and pitfalls
- Fast hashing is the right choice for API keys specifically because the key itself is already
high-entropy, unlike a human-chosen password; applying slow, password-style hashing here adds
latency to every authenticated request for no real security benefit, since the attack this
defends against (an attacker guessing the key by brute force) is already infeasible given the
key's own randomness. - A short cache TTL for key validation trades a small amount of extra load on the central
validation path for a much shorter revocation-propagation window; a design that instead
caches key validity for hours to reduce load quietly turns every emergency revocation into a
slower, less certain process than the team believes it to be. - Common wrong turn: treating "the key still works" as proof it has not leaked. Attackers
frequently use a leaked credential quietly rather than immediately and obviously, so
last-used and usage-pattern monitoring (a sudden change in call volume, source IP, or accessed
scopes for a given key) matters as much as reacting to an explicit leak report. - Common wrong turn: no supported rotation path, only revocation. If the only lifecycle event
a system supports is "kill the key," every rotation becomes an emergency-shaped event (an
outage while the new key propagates to the caller) instead of a routine, low-drama one with a
planned overlap window.
Write a Python function verify_jwt(token: str, expected_aud: str, expected_iss: str, jwks_url: str) -> dict that validates a JWT. Requirements: verify signature using JWKS, reject tokens with alg 'none', validate aud/iss/exp/nbf fields, support key rotation by using kid header and caching JWKS with TTL. Pseudocode is acceptable: show the key validation and caching logic.
Sample Answer
Approach
Reject unsafe algorithms before touching any key material, look up the signing key by its kid (key ID) header against a cached JSON Web Key Set (JWKS), refresh that cache on a time-to-live (TTL) and on a cache-miss (to support rotation), then let a JWT library do the actual signature and claim verification rather than hand-rolling cryptography. This example uses the real PyJWT library so the validation logic is genuine, not pseudocode dressed up as real code.
import time
import jwt # PyJWT
class JWKSCache:
def __init__(self, jwks_url: str, ttl_seconds: int = 300):
self.jwks_url = jwks_url
self.ttl_seconds = ttl_seconds
self._keys = {}
self._fetched_at = 0.0
def _fetch(self):
# real implementation: requests.get(self.jwks_url).json()["keys"],
# indexed by each key's "kid"
self._keys = fetch_jwks_keys_by_kid(self.jwks_url)
self._fetched_at = time.time()
def get_key(self, kid: str, force_refresh: bool = False):
stale = (time.time() - self._fetched_at) > self.ttl_seconds
if force_refresh or stale or kid not in self._keys:
self._fetch()
return self._keys.get(kid)
def verify_jwt(token: str, expected_aud: str, expected_iss: str, jwks_url: str, cache: JWKSCache) -> dict:
header = jwt.get_unverified_header(token)
alg = header.get("alg", "")
if alg.lower() == "none" or not alg.startswith(("RS", "ES", "PS")):
raise jwt.InvalidTokenError(f"rejected alg: {alg!r}")
kid = header.get("kid")
if not kid:
raise jwt.InvalidTokenError("token header missing 'kid'")
key = cache.get_key(kid) or cache.get_key(kid, force_refresh=True)
if key is None:
raise jwt.InvalidTokenError(f"no matching key for kid={kid}")
return jwt.decode(
token,
key=key,
algorithms=[alg],
audience=expected_aud,
issuer=expected_iss,
options={"require": ["exp", "iat", "nbf"]},
)
Worked example
This continues directly from the JWKSCache/verify_jwt code in the Approach section above, in the same session (pip install pyjwt cryptography covers both), and was actually run immediately after that code against a real RSA-signed token and a real in-memory JWKS. It generates its own RSA key pair and stubs the JWKS HTTP fetch with a plain dict, so - combined with the code above - there is nothing left undefined:
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
KID = "2026-08-key-a"
rsa_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
private_pem = rsa_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
public_pem = rsa_key.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
def fetch_jwks_keys_by_kid(jwks_url: str) -> dict:
# Stands in for requests.get(jwks_url).json()["keys"] indexed by kid;
# here it just returns the one public key generated above.
return {KID: public_pem}
cache = JWKSCache(jwks_url="https://issuer.example.com/.well-known/jwks.json")
now = int(time.time())
claims = {
"sub": "user-4471", "aud": "orders-api", "iss": "https://issuer.example.com",
"iat": now, "nbf": now, "exp": now + 3600,
}
token = jwt.encode(claims, private_pem, algorithm="RS256", headers={"kid": KID})
print("token header:", jwt.get_unverified_header(token))
result = verify_jwt(token, "orders-api", "https://issuer.example.com", cache.jwks_url, cache)
print("verified claims sub/aud/iss:", result["sub"], result["aud"], result["iss"])
Actual printed output:
token header: {'alg': 'RS256', 'kid': '2026-08-key-a', 'typ': 'JWT'}
verified claims sub/aud/iss: user-4471 orders-api https://issuer.example.com
And the two rejection paths, also actually run against the same cache:
none_token = jwt.encode(claims, None, algorithm="none")
try:
verify_jwt(none_token, "orders-api", "https://issuer.example.com", cache.jwks_url, cache)
except jwt.InvalidTokenError as e:
print("alg:none correctly rejected:", e)
wrong_aud_token = jwt.encode({**claims, "aud": "wrong-api"}, private_pem, algorithm="RS256", headers={"kid": KID})
try:
verify_jwt(wrong_aud_token, "orders-api", "https://issuer.example.com", cache.jwks_url, cache)
except jwt.InvalidTokenError as e:
print("wrong audience correctly rejected:", type(e).__name__)
alg:none correctly rejected: rejected alg: 'none'
wrong audience correctly rejected: InvalidAudienceError
(The RSA key pair is generated fresh each run, so its bytes will differ if you rerun this, but the verification outcomes shown above do not depend on the specific key material and will reproduce identically.)
Key points
- Algorithm is checked and constrained before any key lookup, since accepting
alg: noneor letting the token dictate an unexpected algorithm (such as switching an RSA-verified endpoint to HMAC using the public key as the HMAC secret) is the classic algorithm-confusion attack this design has to close off first. - The
kidheader, not just the algorithm, selects which cached key to use, which is what makes key rotation possible: the issuer can publish a new key under a newkidwhile old tokens signed under the previouskidkeep validating until they naturally expire. - A cache miss on a known-valid
kidtriggers exactly one forced refresh, handling the case where the issuer just rotated and this service's cache has not caught up yet, without falling back to an unbounded retry loop.
Complexity
Aside from the underlying signature verification itself (a constant-time cryptographic operation for a fixed key size), this is O(1): one dictionary lookup for the cached key, refreshed only on TTL expiry or a genuine cache miss, never a network call on the common path.
Edge cases
An unrecognized kid should trigger exactly one forced refresh, not unbounded retries, since an attacker sending garbage kid values could otherwise force repeated JWKS fetches as a denial-of-service amplification vector. Clock skew between the issuer and this service means exp and nbf checks should allow a small leeway (PyJWT's leeway parameter) rather than failing on a difference of only a few seconds. Empty or malformed key material returned from the JWKS endpoint should fail closed, raising an error, never silently treated as "no key required."
Trade-offs & pitfalls
Pseudocode that skips the algorithm check entirely, or that checks it after fetching the key, is a real, exploitable ordering bug, not a stylistic nitpick. Caching JWKS forever (no TTL) defeats rotation; caching with no TTL and no force-refresh-on-miss defeats it just as badly, since a legitimate just-rotated key would look like a permanent cache miss.
Architect a security model for a large-scale microservices platform (~1000 services) that uses a service mesh (e.g., Envoy/Istio) and an API gateway. Goals: enforce strong service-to-service authentication and authorization, minimize blast radius, centralize policy where sensible but avoid bottlenecks, ensure observability and incident response. Provide key components, identity model, policy enforcement points, rollout plan and scaling considerations.
Sample Answer
Direct answer
At roughly 1,000 services, service-to-service authentication and authorization has to be
enforced by infrastructure (a service mesh sidecar, such as Envoy, paired with a control plane
like Istio) rather than by each service's own application code, because you cannot reliably
audit or update security logic duplicated across a thousand codebases owned by many different
teams. The mesh's sidecar proxies handle mutual TLS (mTLS) and per-request authorization
uniformly, the control plane distributes identity and policy to every sidecar, and the API
gateway stays a separate, thinner layer that only handles edge concerns (external traffic
authentication, coarse rate limiting) rather than trying to be the single point enforcing every
internal rule.
Structured elaboration
Identity model. Every service instance gets a workload identity, most commonly a SPIFFE
(Secure Production Identity Framework For Everyone) identity encoded into a short-lived X.509
certificate, tied to what the workload is (its Kubernetes service account and namespace, for
example) rather than a static shared secret. The mesh's control plane (Istio's istiod, for
example) issues and continuously rotates these certificates automatically; no individual service
team manages its own certificate lifecycle.
Enforcing service-to-service auth and authorization. The sidecar proxy next to each service
terminates and originates mTLS transparently, so two services communicate over an encrypted,
mutually-authenticated channel without either one's application code implementing TLS itself.
Authorization (which services may call which other services, and for which operations) is
expressed as policy (Istio's AuthorizationPolicy resources, for example) and enforced by the
sidecar before a request ever reaches the application, giving every service the same
authorization enforcement mechanism regardless of what language or framework it is written in.
Policy enforcement points. At this scale there are exactly two places policy actually gets
enforced, and each has a distinct job: the API gateway is the enforcement point for traffic
entering the mesh from outside (external clients, partners), handling coarse checks like
authentication and rate limiting once at the edge; each service's own sidecar is the enforcement
point for everything after that, deciding, per call, whether one internal service may reach
another. Keeping these two enforcement points separate, rather than routing all internal traffic
back through the gateway, is what keeps the gateway from becoming a bottleneck for traffic that
never needed to leave the mesh.
Minimizing blast radius. Default-deny between services (a service can only call, or be
called by, the specific services its policy explicitly allows) turns a compromised service into
a contained incident instead of a pivot point to the rest of the fleet; without this, one
compromised service with network reachability to everything else effectively compromises the
whole mesh.
Centralizing policy without creating a bottleneck. Policy is authored and versioned
centrally (so the security posture is auditable in one place, as code) but distributed to
every sidecar so each one can make allow/deny decisions locally, at line rate, without a
synchronous call back to a central decision service on every request. This is the key design
move for enforcing at 1,000-service scale: centralize the authoring and distribution of
policy, not the evaluation of it.
Observability and incident response. Every sidecar can emit consistent access logs, metrics,
and distributed traces for the traffic passing through it, giving uniform visibility across all
1,000 services without depending on each service team to instrument request-level auth logging
themselves. This uniformity is what makes incident response at this scale tractable: a security
team traces a suspicious request across service boundaries using the mesh's own telemetry rather
than reconciling a thousand different logging formats.
Rollout plan. Introduce the mesh incrementally rather than flipping mTLS enforcement on
everywhere at once: start in permissive mode (the sidecar accepts both plaintext and mTLS
traffic while metrics show which callers have and have not migrated), onboard services namespace
by namespace or team by team, and only flip to strict mTLS enforcement for a given service once
its traffic is confirmed fully migrated. A big-bang cutover at 1,000 services risks a
simultaneous outage across the fleet if any meaningful fraction of callers have not yet adopted
the sidecar.
Scaling considerations. The sidecar's own resource footprint (CPU and memory per pod) and the
control plane's config-push fan-out both need capacity planning at this scale; a control-plane
change that pushes new policy to 1,000 sidecars simultaneously needs to be paced (canaried,
rate-limited) rather than broadcast all at once, since a bad policy pushed everywhere
simultaneously turns a policy bug into a fleet-wide outage instead of a contained one.
Worked example
graph TD
Ext[External Traffic] --> GW[API Gateway - Edge AuthN and AuthZ]
GW --> SM[Service Mesh Ingress]
SM --> SVA[Service A plus Envoy Sidecar]
SM --> SVB[Service B plus Envoy Sidecar]
SVA -->|mTLS plus SPIFFE ID| SVB
CP[Istio Control Plane] -.->|distributes policy and certs| SVA
CP -.-> SVB
SVA --> OBS[Telemetry: access logs, traces]
SVB --> OBS
The gateway handles only the edge boundary (authenticating and rate-limiting external traffic
before it enters the mesh at all); everything after that, service A calling service B, for
example, goes sidecar-to-sidecar over mTLS with an authorization decision made locally by
service B's own sidecar, based on policy the control plane already pushed to it. If the control
plane is briefly unavailable, existing sidecars keep enforcing their last-known policy and
certificates until they expire, since evaluation never depended on a live call to the control
plane; only new certificate issuance and policy updates pause during that window, which is
the direct payoff of "centralize distribution, not evaluation."
Trade-offs and pitfalls
- A service mesh adds real operational complexity and per-request latency overhead (an extra
network hop through the sidecar in each direction); this is a deliberate trade against the
alternative of every service reimplementing TLS and authorization independently, which does not
scale to 1,000 services being maintained correctly and consistently over time. The trade-off
is worth stating explicitly rather than presenting the mesh as free. - Permissive mode during rollout is a temporary state, not a target state. Leaving services
in permissive mode indefinitely (common when a migration stalls) means mTLS is not actually
being enforced for those services even though the infrastructure exists, which is easy to miss
in metrics that only measure "sidecar deployed" rather than "strict mode enforced." - Common wrong turn: routing all internal traffic back through the central API gateway to
reuse its authorization logic. This defeats the scaling argument for a mesh in the first place
and turns the gateway into both a latency bottleneck and a single point of failure for traffic
that never needed to leave the mesh's own service-to-service path. - Common wrong turn: pushing a policy change to all 1,000 sidecars simultaneously without a
canary. A syntactically valid but logically wrong authorization policy (an overly broad deny
rule, for example) pushed everywhere at once can cause a fleet-wide outage in the time it takes
the control plane to distribute the update, which is why staged rollout applies to policy
changes, not just to the initial mesh adoption.
Propose a policy-as-code solution (for example using Open Policy Agent - OPA) to enforce attribute-based access control across APIs. Describe where policies should evaluate (sidecar, gateway, service), policy distribution/versioning, performance strategies (caching/compile-time optimizations), CI testing of policies, and how to secure attribute sources and mitigate stale attributes.
Sample Answer
Direct answer
A policy-as-code approach to attribute-based access control (ABAC, where access decisions depend
on attributes of the user, resource, and context rather than a fixed role list) centers on Open
Policy Agent (OPA), a general-purpose policy engine, evaluating policies written in its Rego
language as close to the request as latency allows, most often colocated in a sidecar next to
each service, with policies distributed as versioned bundles from a central server and pulled
(or pushed) to every OPA instance on a schedule.
Structured elaboration
Where policies should evaluate. There are three realistic placement options, and they are
not mutually exclusive:
- Gateway: good for coarse, cross-cutting checks (is this caller authenticated at all, is
this API version deprecated) that apply uniformly regardless of which backend service handles
the request. - Sidecar (colocated with each service): the most common choice for fine-grained
authorization, since it evaluates in-process (a local network call at most) rather than
requiring a round trip to a shared service, and each service's sidecar can be configured with
only the policy bundle relevant to that service. - In-service (embedded as a library): lowest latency of all (no network hop, not even to a
sidecar) but couples the policy engine's lifecycle to the service's own deploys, which fits
latency-critical paths but loses some of the operational uniformity a sidecar gives you.
The general principle: evaluate as close to the request as the latency budget allows, and prefer
the sidecar pattern by default since it keeps policy evaluation decoupled from application code
without paying a network round trip to a remote service.
Policy distribution and versioning. Author policies as code, version them in the same way
application code is versioned (a git repository, code review, CI checks), and package them into
signed, versioned bundles that a bundle server serves to every OPA instance. Each OPA instance
polls for and pulls new bundle versions on an interval (or the server pushes them), so a policy
change rolls out without redeploying the services that consume it; the bundle's version is
itself an auditable artifact, so "which policy was in effect for this request" is answerable
after the fact.
Performance strategies. OPA compiles Rego policies before evaluation and can serve most
authorization decisions in well under a millisecond once a bundle is loaded, since the decision
is a local, in-memory evaluation, not a network call to an external service. For very
high-throughput paths, further techniques include partial evaluation (precompiling a policy
against known-at-compile-time inputs to shrink the runtime decision), and caching decisions for
identical inputs over a short, explicitly bounded window when the policy and the underlying
attributes are not expected to change within that window.
CI testing of policies. Treat Rego policies exactly like application code under test: write
unit tests (OPA's own test framework, opa test) asserting that specific input attribute
combinations produce the expected allow/deny decision, including deliberately adversarial and
edge-case inputs (a request with a missing or malformed attribute, a role that should never gain
a specific permission), and run those tests in CI before a policy bundle is built and published,
the same gate application code changes go through.
Securing attribute sources and mitigating stale attributes. ABAC decisions are only as
trustworthy as the attributes feeding them (a user's department, a resource's sensitivity
classification, a device's posture); if OPA is fed attributes forwarded from an upstream caller
without verifying their source, a caller can forge a favorable attribute directly. Attributes
should come from a trusted source the policy engine (or the service feeding it) independently
verifies, a signed token's claims, a lookup against a system of record, rather than an
unauthenticated header. Staleness is a related but separate risk: an attribute cached or fetched
minutes ago (a user's role, changed since) can produce a decision based on outdated reality;
mitigate it by keeping high-consequence attributes (role, employment status) on a short refresh
interval or fetched fresh for sensitive operations, while accepting a longer, cheaper refresh
interval for low-consequence, slow-changing attributes (a user's display name).
Worked example
graph TD
Req[API Request] --> GWEnf[Gateway - coarse policy]
Req --> Sidecar[Sidecar - per service policy]
Req --> App[In app - fine grained ABAC]
GWEnf --> OPA[OPA Engine - local decision]
Sidecar --> OPA
App --> OPA
Bundle[Policy Bundle Server] -.->|versioned push| OPA
Attr[Attribute Sources: user, resource, context] --> OPA
A concrete Rego-shaped decision (illustrative, not executed): a request to approve an expense
report carries attributes {user.department: "finance", user.role: "manager", resource.amount: 4500, resource.owner_department: "finance"}. A policy rule such as allow if input.user.role == "manager" and input.user.department == input.resource.owner_department and input.resource.amount <= 5000 evaluates entirely from attributes already present on the
request, with no network call needed at decision time, which is what keeps this pattern fast
enough to sit on the request path even at the sidecar. Changing the approval ceiling from 5000 to
a new value is a policy bundle change, published and rolled out to every sidecar, with no service
code redeployed.
Trade-offs and pitfalls
- ABAC's flexibility is also its main operational risk. Because rules combine arbitrary
attributes instead of a fixed role list, it is easy to write a policy that is logically correct
for the cases you tested and subtly wrong for a combination you did not, which is exactly why
CI testing of policies (including adversarial edge cases) is not optional here the way it might
feel optional for a small, fixed RBAC (role-based access control) rule set. - Colocated evaluation trades a small memory and CPU footprint per service for latency and
availability. A centralized policy-decision service is simpler to operate as a single thing,
but makes every authorization check depend on that service's availability and adds a network
hop to every request; the sidecar pattern avoids both costs at the price of running many small
OPA instances instead of one larger one. - Common wrong turn: trusting client-supplied or upstream-forwarded attributes without
verifying their source. A well-tested policy is still exploitable if an attacker can simply
set the attribute the policy checks; verify attribute provenance, not just the policy logic
itself. - Common wrong turn: refreshing all attributes on the same schedule. Treating a user's
display name and a user's active-employment status as equally safe to cache for, say, an hour
ignores that the second one directly gates access; calibrate refresh/staleness tolerance per
attribute by how consequential it is, not uniformly.
Unlock Full Question Bank
Get access to all 28 API Security, Authentication and Authorization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.