Identity, Authorization, and Least Privilege › Building the evaluator
Language AI HandbookAll chapters The notebook uses dataclasses, enums, and pre-resolved resource data. The enum describes the accepted vocabulary in the fixture. In a service, validate an incoming string against that vocabulary before building the request. Python type annotations alone do not enforce input types at runtime. The fixture starts with structured, typed values and explicitly handles an unrecognized operation in its evaluator.
PythonIn [3]Expand
from dataclasses import dataclass, replace
from enum import Enum
class Op(Enum):
READ = "read draft"
MARK_READY = "mark ready"
READ_REVIEW = "read review"
ANNOTATE = "annotate draft"
class Decision(str, Enum):
ALLOW = "Allow"
DENY = "Deny"
STEP_UP = "StepUp"
EXPIRED = "Expired"
REVOKED = "Revoked"The operation enum gives the fixture a small, readable vocabulary. Each label represents a proposed operation. The evaluator returns a decision and leaves the draft unchanged. The service that translates an incoming proposal into this vocabulary needs explicit validation. Annotations on Python data classes help the reader understand the expected types, but they do not validate runtime input.
Represent the principal, workspace and resource key, grant hops, and optional approval as frozen records. A resource key is a single pair so the caller cannot compare one component and assume it checked the other. The code uses immutable sets for scopes and resources, and an ordered tuple for the chain. As written, all fields supplied to the evaluator are already resolved by the fixture.
PythonIn [4]Expand
@dataclass(frozen=True)
class Principal:
id: str
tenant: str
@dataclass(frozen=True)
class ResourceKey:
tenant: str
id: str
@dataclass(frozen=True)
class DelegationHop:
delegator: Principal
delegate: Principal
scopes: frozenset[str]
resources: frozenset[ResourceKey]
issued_at: int
expires_at: int
revoked: bool = False
@dataclass(frozen=True)
class Approval:
principal: Principal
actor: Principal
op: Op
resource: ResourceKey
issued_at: int
expires_at: int
@dataclass(frozen=True)
class RequestContext:
principal: Principal
actor: Principal
op: Op
resource: ResourceKey
consented_scopes: frozenset[str]
delegated_scopes: frozenset[str]
chain: tuple[DelegationHop, ...]
now: int
approval: Approval | None = NoneThe request supplies the decision clock instead of reading the wall clock. Grant sets and the operation-to-scope mapping are policy inputs. For the same clock, authority records, and mapping, the evaluator returns the same label. A later request supplies a fresh clock and fresh authority. The frozen record structure helps isolate the example from mutable state, but it cannot prevent a change to a deployed authority store, resource, or approval before the effect occurs.
The scopes in the toy mapping identify distinct operations. The grant's resource set separately identifies the drafts on which the operations may be performed. Keeping scope and resource distinct makes it possible to mint the same operation for a smaller resource set while narrowing a delegation.
PythonIn [5]Expand
OP_TO_SCOPE = {
Op.READ: "scope_draft_read",
Op.MARK_READY: "scope_draft_mark_ready",
Op.READ_REVIEW: "scope_review_read",
Op.ANNOTATE: "scope_draft_annotate",
}
HIGH_IMPACT_OPS = frozenset({Op.MARK_READY, Op.ANNOTATE})The fixture treats marking a draft ready and adding an annotation as effects that require fresh approval. That is an example policy selection. Another workflow can use a different risk threshold and more precise approval binding. The fixture binds approval to the exact tuple of principal, workload, operation, and draft key and checks its validity interval. A deployed service may also need to bind reviewed parameters, a resource version, the approval source, or the identity of an independent approver.
The evaluator performs structural and authority checks before using an approval. A high-impact operation outside the delegated authority returns Deny, even when an approval record is present. The approval only applies once the base authority is sufficient.
PythonIn [6]Expand
def approval_matches(ctx: RequestContext) -> bool:
approval = ctx.approval
if approval is None:
return False
return (
approval.principal,
approval.actor,
approval.op,
approval.resource,
) == (
ctx.principal,
ctx.actor,
ctx.op,
ctx.resource,
) and approval.issued_at <= ctx.now < approval.expires_at
def evaluate(ctx: RequestContext) -> Decision:
if not ctx.chain or not ctx.principal.id or not ctx.actor.id:
return Decision.DENY
tenant = ctx.principal.tenant
if ctx.actor.tenant != tenant or ctx.resource.tenant != tenant:
return Decision.DENY
first, last = ctx.chain[0], ctx.chain[-1]
if first.delegator != ctx.principal or last.delegate != ctx.actor:
return Decision.DENY
if any(
not hop.delegator.id
or not hop.delegate.id
or hop.delegator.tenant != tenant
or hop.delegate.tenant != tenant
or hop.expires_at <= hop.issued_at
for hop in ctx.chain
):
return Decision.DENY
if any(hop.revoked for hop in ctx.chain):
return Decision.REVOKED
if any(ctx.now >= hop.expires_at for hop in ctx.chain):
return Decision.EXPIRED
if any(ctx.now < hop.issued_at for hop in ctx.chain):
return Decision.DENY
for parent, child in zip(ctx.chain, ctx.chain[1:]):
if child.delegator != parent.delegate:
return Decision.DENY
if not (
child.scopes <= parent.scopes
and child.resources <= parent.resources
):
return Decision.DENY
if (
not parent.issued_at
<= child.issued_at
< child.expires_at
<= parent.expires_at
):
return Decision.DENY
needed = OP_TO_SCOPE.get(ctx.op)
if needed is None:
return Decision.DENY
if not all(
needed in scopes
for scopes in (ctx.consented_scopes, ctx.delegated_scopes, last.scopes)
):
return Decision.DENY
if ctx.resource not in last.resources:
return Decision.DENY
if ctx.op in HIGH_IMPACT_OPS and not approval_matches(ctx):
return Decision.STEP_UP
return Decision.ALLOWThe earlier checks compare the tenant keys of the user, workload, and target. The caller is responsible for verifying identities and binding the request to its task. The chain checks bind its endpoints, its neighboring hops, and its scopes. The code consults the final hop for the selected resource and operation because the subset checks ensure every ancestor covers those values. In this deliberately narrow policy, a request without authority on the final hop is denied even when the context includes the same operation name in consent and delegated scope. The authority context is only useful when the service can establish where its fields came from.
The result is a decision value. A service receiving it would either stop, request approval without creating an effect, or apply the action to the checked resource. Implementations that separate policy evaluation from enforcement need stable communication of the checked effect, authority, and target. The example service assumes trusted issuance of the first grant. Its checks cannot independently determine all the underlying rights of the user who issued it.
We can now create a common case and change one policy-relevant field at a time. For the baseline, subject and actor records both belong to the orchard workspace. The selected draft key is used consistently in the grant and request.
PythonIn [7]Expand
alice = Principal(id="reader-a", tenant="orchard")
agent = Principal(id="summary-worker", tenant="orchard")
subtask = Principal(id="verification-worker", tenant="orchard")
draft = ResourceKey(tenant="orchard", id="draft-a")
other_draft = ResourceKey(tenant="orchard", id="draft-b")
other_tenant = ResourceKey(tenant="coast", id="draft-a")
read_scope = OP_TO_SCOPE[Op.READ]
base_hop = DelegationHop(
delegator=alice,
delegate=agent,
scopes=frozenset({read_scope}),
resources=frozenset({draft}),
issued_at=1000,
expires_at=1900,
)
base_ctx = RequestContext(
principal=alice,
actor=agent,
op=Op.READ,
resource=draft,
consented_scopes=frozenset({read_scope}),
delegated_scopes=frozenset({read_scope}),
chain=(base_hop,),
now=1100,
)The canonical context is fresh (now is 100 seconds past issuance, inside the 900-second window), in-scope, same tenant, and not revoked. We expect Allow. The next block confirms this and sweeps the variants.
PythonIn [8]Expand
scenarios = {
"baseline": (base_ctx, Decision.ALLOW),
"at_issue": (replace(base_ctx, now=base_hop.issued_at), Decision.ALLOW),
"not_yet_valid": (
replace(base_ctx, now=base_hop.issued_at - 1),
Decision.DENY,
),
"at_expiry": (replace(base_ctx, now=base_hop.expires_at), Decision.EXPIRED),
"withdrawn": (
replace(base_ctx, chain=(replace(base_hop, revoked=True),)),
Decision.REVOKED,
),
"both_invalid": (
replace(
base_ctx,
now=base_hop.expires_at,
chain=(replace(base_hop, revoked=True),),
),
Decision.REVOKED,
),
"other_workspace": (
replace(base_ctx, resource=other_tenant),
Decision.DENY,
),
"other_operation": (replace(base_ctx, op=Op.MARK_READY), Decision.DENY),
"consent_gap": (
replace(base_ctx, consented_scopes=frozenset()),
Decision.DENY,
),
"other_draft": (replace(base_ctx, resource=other_draft), Decision.DENY),
"missing_chain": (replace(base_ctx, chain=()), Decision.DENY),
"other_workload": (replace(base_ctx, actor=subtask), Decision.DENY),
}
results = {name: evaluate(ctx) for name, (ctx, _) in scenarios.items()}
assert all(
results[name] is expected for name, (_, expected) in scenarios.items()
)ConsoleOut [9]Expand
baseline -> Allow at_issue -> Allow not_yet_valid -> Deny at_expiry -> Expired withdrawn -> Revoked both_invalid -> Revoked other_workspace -> Deny other_operation -> Deny consent_gap -> Deny other_draft -> Deny missing_chain -> Deny other_workload -> Deny
The two time boundaries demonstrate the half-open interval. At exactly the issue tick the grant is valid, while exactly at expiry it is expired. Before issue the example returns Deny. A grant marked withdrawn has a different state from an expired grant, and the combined case demonstrates the selected diagnostic priority.
The other-workspace case changes only the resource's workspace; it keeps the draft identifier equal. The other-draft case stays in the original workspace and changes the identifier. The other-workload case substitutes a recognized workload in the same workspace, yet the credential's final hop does not bind that workload. These cases help locate the condition a regression changed before tracing its broader consequences.
Testing delegation monotonicity
For a two-hop chain, the first hop is from the user to the agent. The next hop is from that agent to a subtask. The subtask needs only read authority on the selected draft. Both the scope set and the resource set of the child must stay within the parent's. The time interval must also stay within the parent's. Equality is allowed on an individual dimension. A service can still prefer a strictly narrower grant when a particular task needs less authority.
PythonIn [10]Expand
parent = replace(
base_hop,
scopes=frozenset({read_scope, OP_TO_SCOPE[Op.READ_REVIEW]}),
resources=frozenset({draft, other_draft}),
)
child = DelegationHop(
delegator=agent,
delegate=subtask,
scopes=frozenset({read_scope}),
resources=frozenset({draft}),
issued_at=1050,
expires_at=1400,
)
narrowing_ctx = replace(base_ctx, actor=subtask, chain=(parent, child))PythonIn [11]Expand
chain_cases = {
"narrowing": (narrowing_ctx, Decision.ALLOW),
"broader_scope": (
replace(
narrowing_ctx,
chain=(
parent,
replace(
child, scopes=parent.scopes | {OP_TO_SCOPE[Op.ANNOTATE]}
),
),
),
Decision.DENY,
),
"broader_resources": (
replace(
narrowing_ctx,
chain=(
parent,
replace(child, resources=child.resources | {other_tenant}),
),
),
Decision.DENY,
),
"longer_interval": (
replace(narrowing_ctx, chain=(parent, replace(child, expires_at=1901))),
Decision.DENY,
),
"disconnected_chain": (
replace(narrowing_ctx, chain=(parent, replace(child, delegator=alice))),
Decision.DENY,
),
"child_without_scope": (
replace(
narrowing_ctx, chain=(parent, replace(child, scopes=frozenset()))
),
Decision.DENY,
),
}
assert all(evaluate(ctx) is expected for ctx, expected in chain_cases.values())ConsoleOut [12]Expand
narrowing -> Allow broader_scope -> Deny broader_resources -> Deny longer_interval -> Deny disconnected_chain -> Deny child_without_scope -> Deny
The narrowing example keeps the endpoint binding and still contains the requested read authority. The changed child grants exercise three separate dimensions of containment. The scope change adds an operation absent from the parent, the resources change adds another resource key, and the interval change advances expiry from 1,400 to 1,901 while the parent still expires at 1,900. Each case is denied. The disconnected chain keeps scope and resource compatible, but the child delegator does not match the parent delegate. In the last case both hop sets remain valid subsets while the final set omits the requested permission. These examples show why a chain needs connection, containment, and a final positive authorization at the same time.
Step-up for high-impact operations
A user may allow the worker to prepare a draft for review but want to check which draft it changes at the time of the effect. This example represents the review-state change with an enum and adds a trusted approval record for eligible proposals. The notebook shows a decision label, with no draft modification.
PythonIn [13]Expand
effect_scope = OP_TO_SCOPE[Op.MARK_READY]
review_ctx = replace(
base_ctx,
op=Op.MARK_READY,
consented_scopes=frozenset({effect_scope}),
delegated_scopes=frozenset({effect_scope}),
chain=(replace(base_hop, scopes=frozenset({effect_scope})),),
)
approved = Approval(
alice, agent, Op.MARK_READY, draft, issued_at=1090, expires_at=1200
)
approved_ctx = replace(review_ctx, approval=approved)
approval_cases = {
"approval_missing": (review_ctx, Decision.STEP_UP),
"approval_matches": (approved_ctx, Decision.ALLOW),
"approval_other_draft": (
replace(review_ctx, approval=replace(approved, resource=other_draft)),
Decision.STEP_UP,
),
"approval_at_expiry": (replace(approved_ctx, now=1200), Decision.STEP_UP),
"no_delegated_effect": (
replace(base_ctx, op=Op.MARK_READY, approval=approved),
Decision.DENY,
),
}
assert all(
evaluate(ctx) is expected for ctx, expected in approval_cases.values()
)ConsoleOut [14]Expand
approval_missing -> StepUp approval_matches -> Allow approval_other_draft -> StepUp approval_at_expiry -> StepUp no_delegated_effect -> Deny
For the first two cases, the base authority covers this effect and the only changed field is the approval. The authorized effect receives StepUp when approval is absent and Allow when the recorded approval matches. The next two cases check a mismatched draft and an expired approval. The final case shows that a correctly formed approval still cannot supply authority omitted by the delegation. A production service needs its own trusted approval source, freshness policy and resource versioning.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!