Identity, Authorization, and Least Privilege

Michael BrenndoerferDecember 2, 202631 min read

Model authorization as a trusted function with identity, scope, expiry, and approval checks. Learn to gate agent proposals with least privilege.

Language AI HandbookAll chapters
Part 61 of 67Agentic AI and Protocol Security
Chapter 468Identity, Authorization, and Least Privilege
Reading the full chapter · 11 sections · 31 min11 sections · 31 min

All 11 sections · 31 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Identity, Authorization, and Least Privilege

A summary worker needs permission to read the selected draft. A review worker may be able to mark the same draft ready. The workspace and document identifier are identical, but the authority needed to perform those actions differs. When the language model proposes an operation, the service must have enough information to decide which user initiated the work, which workload is acting, and whether that workload may perform this operation on this resource now.

Untrusted content and stored state can influence an agent's proposals. Authorization sits between those proposals and the rest of the system. It uses evidence from independent sources, such as the authenticated workload context and the resource catalog. The model can propose a target or summarize a request. The service makes the permission decision from facts it resolves under its own rules.

We will represent the decision as a function, then test it with a small Python fixture. The same draft stays in view while we change who acts, how long the grant is valid, which workspace owns the document, and whether a delegated grant still applies. A separate example shows how an already permitted action can require an additional decision from a person.

The notebook fixture

The notebook uses invented principals, closed operation enums, in-memory grants and counters. The evaluator returns a decision and changes no resource. In the example architecture, a service would apply the accepted decision at the point where it performs the action.

Why the model cannot be the authorization layer

The application receives a proposal from the model and a trusted execution context from the surrounding service. Keep them separate through dispatch. The proposal can include the requested operation and a candidate draft reference. The execution context identifies the verified caller and the task. An authorization gate should use its own resource lookup to determine which workspace owns the draft and which policy governs it.

A deterministic fixture helps show the difference. Given the same inputs and policy snapshot, it returns the same decision. That makes it possible to trace a result to a rule and to reproduce the result in a regression test.

Determinism alone says nothing about correctness. A rule can give the same wrong answer on every run, and a well-written rule can still receive stale or untrusted inputs.

Three situations show why the inputs matter.

  • A retrieved document can influence which operation the model proposes. The authorization gate still checks the operation against trusted task scope.
  • A natural-language request can mention a workspace or user. The workspace and user used in policy come from trusted application state.
  • A workload's service account may have its own authority. A request on another principal's behalf needs a delegated grant, even when that account has authority for unrelated work.

OWASP's AI Agent Security guidance describes separating proposals from execution and independently checking scope, privilege, and approval state.

Principal

A principal is an actor to which the system can assign authority. An end user and an agent workload are distinct principals in the delegated workflow. The same person may authorize several workflows, and the same workload may act for many people. A decision needs the pair that applies to the specific request.

User, workload, and resource service identities

This workflow carries three identities. Other architectures can add services or use a different division of responsibility. Begin by identifying the parties whose roles differ in the decision.

  1. The end user asks for an outcome. The trusted user identity anchors workspace policy, consent, and the starting authority for the task.
  2. The agent workload asks a service to perform an operation. The workload may be permitted to act for this user on this task under the delegation recorded for it.
  3. The resource service controls the effect. It authenticates its caller, validates delegated authority, resolves the resource within the workspace, and enforces the applicable policy before performing the operation.

Authentication verifies an asserted identity. Authorization determines which action may be performed on a particular resource under current policy. NIST SP 800-207 treats these as distinct functions. A background task may still run under a valid workload identity even after the initiating user's access changes. The decision should use authority available when it acts.

In a deployed OAuth design, RFC 9700 §2.3 recommends restricting token privileges to those needed for the use case. It also recommends audience restriction where feasible, so the receiving service can verify that it is the intended recipient. An audience identifies where authority may be presented. Resource and action restrictions identify what that authority can authorize there. The chapter's invented grants represent resolved facts after relevant credential checks, with no token handling in the notebook.

Delegation

Delegation lets an actor use some of a subject's rights on the subject's behalf. RFC 8693 §1.1 distinguishes delegation from impersonation within a defined rights context. In the delegation case, the actor retains a distinct identity from the subject. Keeping actor and subject separate lets a service evaluate the acting workload and preserve both identities for audit.

Consent, scope, expiry, and revocation answer different questions about the same request.

  • Consent records the user's choice. The service resolves consent for the relevant task, user, operation, and resource under its own design. It also applies the underlying authorization policy, since a user choice cannot grant rights the user does not hold.
  • Scope bounds the operations and resources the authority covers. For the document worker, the useful distinction is between reading this draft and marking this draft ready. Access to the workspace does not supply every operation within it.
  • Expiry sets an end time for authority. An expiry limits the validity interval under the enforcement point's rules. It can leave an interval during which authority is still active after a task no longer needs it.
  • Revocation withdraws authority before its normal end. The enforcement point needs a design for learning the current state. RFC 7009 §2.2 notes that token revocation can have a propagation delay. The interval accepted by a particular service depends on its own authority freshness rules.

Keep a trusted field or policy input for each question the service must answer. In the fixture the user consent and delegated scope are explicit sets. The clock is an integer supplied with the request. Each hop has an interval and revocation state. A separate approval record models the example review action.

Authorization as a function

An authorization decision can be represented as a function ff from a trusted request context cc to a decision label:

f(c)∈{Allow,Deny,StepUp,Expired,Revoked}.f(c) \in \{\text{Allow},\text{Deny},\text{StepUp},\text{Expired},\text{Revoked}\}.

The context cc includes the resolved resource, the proposed operation, trusted principal records, and the preserved authority state. The function ff chooses one label. Only Allow admits the request to the effect step, where the service must apply the same authorization conditions. The remaining outcomes explain what needs to happen before any further effect can be considered.

  • Allow means all fixture conditions pass.
  • Deny means at least one required condition failed, such as workspace, scope, or delegation membership.
  • StepUp requests a separate human decision for an otherwise permitted effect.
  • Expired means the supplied clock is at or beyond at least one grant's exclusive expiry.
  • Revoked means at least one hop is already marked withdrawn in the supplied authority state.

The reason label is an engineering choice. This fixture gives revocation priority over expiry so one case with both conditions produces a predictable diagnostic. It does not recommend publishing detailed policy internals to the caller. Store safe internal reasons separately from an external result when details would expose protected policy or resource information.

We can illustrate these labels with a small matrix of named cases. The inputs are designed examples, so their counts describe the exercises only. They are not frequencies for live users or a measure of how well the control protects a deployment. The evaluator consumes the same context for the worked examples and for the outcome matrix later in this chapter. In the matrix each row identifies an operation and each column identifies one of its possible verdicts. Reporting counts preserves the distinction between expiration, explicit withdrawal, and a current request that requires a separate human decision. For a small toy suite the names of the individual cases remain more useful than percentages. In a live decision log, use a denominator that answers the operational question and keep policy changes visible when comparing different periods.

An expired request can be reconsidered only under fresh authority that still applies to the task. A revocation may reflect a canceled delegation or another authorized policy change. Automatic retries should respect the same authority and freshness conditions as the original attempt. A case requiring StepUp has to return through the policy gate after an independently recorded approval. The acceptance of a new context may change the outcome, while submitting the same unchanged context reproduces the same result.

A deny-by-default service needs an explicit answer when a required identity, scope, resource, or state is unknown. OWASP's authorization guidance recommends denying by default and checking permissions on each request. Some denial reasons are relevant to a service operator and others are safe to show to a user. Keep the observation needed to investigate a decision, along with the policy snapshot, without making the model the custodian of those records.

The example records the initiating principal, the acting workload, the operation enum, the resource identifier and its workspace, the consented scopes, the delegation chain, the decision clock, and an optional approval record. The resource key combines its workspace with its identifier. This makes two drafts with the same name in different workspaces distinct policy targets. The same namespace can contain multiple drafts, so a workspace match alone also provides insufficient information.

Least privilege means granting the authority necessary to complete the task. A narrow operation, resource set, and validity interval can all reduce delegated authority. An effect can require narrower controls than a read, even when both operations use the same workspace and resource identifier. In a more general policy, roles can establish common task permissions, while resource relationships and attributes qualify how those permissions apply.

The evaluator checks constraints in a fixed order so the displayed reason is reproducible. The order only controls the first failure we report. Each condition must still be checked before any Allow. The tests include cases with one failing condition and a case in which more than one validity rule applies.

Evaluation order

This fixture uses the following order.

  1. Require a delegated chain and nonempty identifiers on the trusted principal records. Require the user, workload, and resolved draft to be in the same workspace in this policy.
  2. Bind the first hop to the user and the last hop to the acting workload. Require a nonempty principal identity on each hop, the same workspace throughout, and a positive validity interval.
  3. Check current grant state. No revoked grant may authorize the operation. A grant applies in the half-open interval from its issue tick up to but excluding its expiry tick.
  4. Require adjacent hops to connect. Check that each child stays within its parent's resource set, scope set, and time interval. Check the request against trusted consent, the delegated scope, and the last hop.
  5. Apply an extra approval check for an otherwise permitted review action. The trusted approval refers to the particular user, workload, operation, resource, and validity interval.

The code checks revocation before expiry once the basic chain and identities are present. That choice gives an internal diagnosis when the context contains both states. It does not produce broader authority. The intended behavior is a conjunction of controls, so a grant satisfying scope still needs valid workspace, resource, time, chain and consent checks.

When a production service lacks trusted current facts, it can reject or defer the effect according to its policy. Logging the reason is useful for operators, but the type system and logs cannot substitute for a missing binding or an unavailable authority service.

Worked example: one action, several verdicts

Consider an invented user and summary worker that both belong to the orchard workspace. The worker has read authority for one draft for fifteen minutes. The first request arrives 100 seconds after the grant begins. The grant's issue tick is 1,000, its expiry tick is 1,900, and the first request uses tick 1,100. The difference between issuance and expiry is 900 seconds, or fifteen minutes. Integer ticks keep the issue and expiry boundaries easy to check.

The unchanged request is allowed. At tick 1,900 it is expired. Before tick 1,000 it is outside the grant's interval. The same clock value produces a revocation decision when the grant record is marked withdrawn. The other workspace is denied even when it happens to contain a draft with the same identifier. A second draft in the permitted workspace is denied when it falls outside the grant.

Changing a read proposal to a review-state operation also changes which scope the service requires. For a task where that effect is explicitly authorized, a valid approval for the effect can move a StepUp decision to Allow. An approval for a different draft does not cover the requested effect. The fixture treats these as separate scenarios because they answer different questions about a single decision.

Building the evaluator

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]
CollapseExpand
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]
CollapseExpand
@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 = None

The 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]
CollapseExpand
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]
CollapseExpand
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.ALLOW

The 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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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.

Measuring boundary behavior across many requests

A single decision is easy to trace. A small matrix lets us see whether the notebook covers every result label we introduced. Reuse the same cases for the matrix and the output table so the caption and counts have one source. Each row belongs to the operation the case proposes and each column belongs to its decision. The resulting counts measure the fixtures we chose. They say nothing about how often a production user will see a denial.

A count table is convenient when a project first introduces a new reason label. If every test still reaches an older rule before it can reach the new rule, the new reason may have no recorded examples. Count coverage gives a hint about this problem. The actual assertions remain the stronger signal because each names the intended expected decision.

The notebook groups the common, delegation, and approval cases by operation and counts the resulting verdicts. There is no random sampling. The total number of requests is the sum of the sizes of the three sets because each case in each set is evaluated once for the table. When a request changes two conditions, the test labels why that case is useful and what its diagnostic priority measures.

In a service review, the corresponding table would need a definition of its population. For example, a count could refer to all evaluated request attempts during one policy version, with retries still counted as distinct attempts. A count grouped by unique tasks answers a different question. The decision labels in this fixture are useful without assuming anything about the prevalence of one kind of request.

PythonIn [15]
CollapseExpand
from collections import Counter

combined_cases = [
    *scenarios.values(),
    *chain_cases.values(),
    *approval_cases.values(),
]
counts_by_op = {op: Counter() for op in Op}
for context, _ in combined_cases:
    counts_by_op[context.op][evaluate(context)] += 1

decision_counts = [
    sum(counts_by_op[op][decision] for op in Op) for decision in Decision
]
assert sum(decision_counts) == len(combined_cases)
PythonIn [16]
CollapseExpand
decision_labels = [decision.value for decision in Decision]

print(f"{'operation':16}", *(f"{label:>8}" for label in decision_labels))
for operation, counts in counts_by_op.items():
    if sum(counts.values()):
        print(
            f"{operation.value:16}",
            *(f"{counts[decision]:>8}" for decision in Decision),
        )
ConsoleOut [16]
CollapseExpand
operation           Allow     Deny   StepUp  Expired  Revoked
read draft              3       11        0        1        2
mark ready              1        2        3        0        0

The printed rows include operations that appear in the examples. The figure aggregates over operations and shows the number of cases leading to each label. The bars share a linear count axis starting from zero. Their lengths are counts from the same set of assertions checked earlier.

VisualizationOut [17]
CollapseExpand
A bar chart of the number of invented cases in each of five authorization verdicts.
Counts by verdict for the invented request cases. Each case contributes to one verdict. The relative bar lengths reflect the cases chosen for this notebook.

The Deny bar includes several separate reasons. The earlier named cases show which condition each is designed to test. Expired and Revoked are deliberately visible beside it, and StepUp still differs from Allow. Those distinctions are useful when reviewing why a workflow paused. In a monitoring system, a rise in any one label is a reason to investigate contributing requests and policy changes. The label alone does not establish the cause.

The operation rows also make a missing dimension easy to spot. The chapter defines four operations but the selected requests propose only read and mark ready. Review-read and annotate appear in delegation scope tests while remaining absent as proposed operations. The notebook checks the authority relationships it names. A more complete service regression suite needs positive and negative scenarios for every operation it exposes, including operation-specific effects and authorization decisions after an approval expires.

Least privilege in practice: minting, narrowing, and expiring

The evaluator is the check. Least privilege also depends on which authority the issuer grants. Start by identifying the resources and operation needed for one task. A summary workflow can use a draft-read grant, while publishing a review-state change can require a different grant and an independent approval decision. Giving both workflows an unrestricted service identity expands the effect that an application logic error can cause.

Keep renewed authority tied to the task. A long-running workflow might wait for a person to review a proposal, so the original grant or approval might no longer apply when the effect is ready. Determine which context can be refreshed, which parts require another user decision, and which parts are recovered by simply stopping the task. A stale grant should not become fresh merely because the application retries the operation.

Narrow the child grant when the subtask needs fewer operations, fewer resources, or less time. A child can keep a dimension unchanged if the task needs the same boundary on that dimension. The subset and interval checks in the fixture prevent broadening in these three dimensions during a hop. A deployed issuer also needs to establish which actor may delegate and in what context. The fixture demonstrates the comparisons, with trusted first-hop issuance as an assumption.

Record the consent information separately when a user authorizes a specific task. In production the consent record includes the details the service needs to evaluate the authorization boundary. A wider grant than the user intended can be limited by separate consent enforcement, but the system still needs to correct the issuer or policy that produced an overbroad grant. A scope field that says read describes one dimension. The service still needs to verify resource ownership and that the workload is acting under the right grant.

Revocation latency should be a design input. Consider a human withdrawing a task while a background worker waits for another result. A service with an authoritative current-state check can observe the withdrawal after the withdrawal reaches that enforcement point. A service using a cached decision may need an invalidation mechanism or a freshness limit consistent with its risk tolerance. The fixture models a resolved revocation flag, so it does not predict any propagation or cache latency.

Enforce authority at more than one point

The workload requests a bounded operation, an issuer grants scoped authority, and the resource service checks the effect it will apply. The controls protect different aspects of the task. The issuer limits the grant even if the workload later proposes too much. The service evaluates the resolved operation and resource even when the issuer allowed several operations. Auditing records which decision the service made without supplying permission itself.

Tenant separation as a hard invariant

In the orchard/coast example, a resource key includes its workspace because the same draft identifier can be reused across workspaces. A real catalog may have globally unique resource identifiers and still need authorization against the tenant or ownership relation. The policy should use a trusted ownership record to establish that relation. The service then applies the effect to that same resolved resource.

A business process that needs cross-tenant work requires an explicit policy for that scope. The fixture chooses the simpler invariant that all principals, chain endpoints, and the target share a workspace. Do not infer a production exception from the order of the tests. In this policy an operation scope can never substitute for the workspace invariant.

Report tenant-related decisions according to trusted observability policy. A mismatch can reflect an ordinary user action, a routing error, or a broken assumption in another component. A useful audit record preserves the reason, request or task correlation, and policy version while avoiding disclosure of unrelated tenant contents. Investigate patterns with enough context to distinguish expected rejects from an unexpected change.

Limitations and impact

The evaluator assumes its request facts are already authenticated and resolved. Consent provenance and the first issuer's right to grant authority are outside the fixture's checks. A service design must identify where it gets the user identity, workload identity, applicable tenant, requested resource, and approval facts. Each field needs a clear owner and an authority boundary. A well-typed record filled from untrusted text is still untrusted.

The example also assumes the checked action describes what the operation tier applies. If the action is delayed or the resource moves, a still-live grant may no longer be appropriate for the new state. Enforce the conditions needed for the action at the point of use. A conditional write or transaction can tie state validation and the write together when the relevant state shares a consistency boundary. Where two systems cannot update together, document what freshness the service can enforce and handle stale decisions explicitly.

The approval fixture checks the recorded principal, actor, operation, target and validity window. In a deployed application, a person may need to see what would change, whose authority will be used, and why the workflow is waiting. A service may also need to bind the approval to parameters, a draft version, an authorized approver, or a single effect. Choosing these bindings is a policy decision about the risk of that workflow. The shape of the trusted approval record should follow it.

The fixture represents a scoped credential with ordinary Python records. It does not decide token format, signature validation, or how a platform compares credential audience to the service identity. If a deployment uses OAuth, review the profile and its applicable audience and scope requirements. If it uses a different form of delegation, verify that the equivalent checks apply at every intended boundary.

Treat the reported decision as evidence of a rule evaluation, with the underlying assumptions kept visible. One unit test can show that the first request outside a grant's lifetime is rejected by the evaluator. A service test can exercise whether a real queued request reaches the same policy boundary with current authority and the correct resource. For changes to identity resolution, look at requests that still have the same local node or object name but a different authenticated context.

When designing the audit trail, decide what will help explain and replay a disputed authorization result. A useful record can include the task, rule and policy version, actor and subject references, a safe resource reference, the requested operation, and the outcome. Preserve provenance and access controls for those records. An audit channel may be highly sensitive even when it contains no raw credential.

The service can then hand an allowed action to an execution environment with its own credential and resource boundaries.

Summary

  • A model proposes an operation. A trusted service resolves the target and decides whether the user and workload may perform the operation.
  • Delegated scope, consent, workspace, resource, and validity answer different questions. A precise grant can permit reading a draft without permitting an effect on it.
  • Child grants in the fixture have connected endpoints and stay within parent scope, resource set, and time interval. The final grant still needs to cover the actual request.
  • The fixture distinguishes expiration, revocation, denial, and requests for additional approval. It applies a documented diagnostic order without turning any non-Allow result into permission.
  • An approval is specific to the trusted actor and subject, operation, resource, and time interval in the example. The service also evaluates its underlying authority rules.
  • Record enough trusted context to understand a decision and check the actual effect at the service boundary.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about identity, authorization, and least privilege in agent workflows.

Identity, Authorization, and Least Privilege

Question 1 of 80 of 8 completed
In the delegated workflow described in the chapter, why can't the language model itself serve as the authorization layer?
Join the discussionAsk a question or share what you learned.

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!

A different angle
All writing
Language AI Handbook · Vol. 19

Tool, Retrieval, and Memory Poisoning

Learn how tool schemas, retrieval snapshots, and durable memory lose integrity. Validate, authorize, and quarantine records across boundaries.

34 min read
Language AI Handbook · Vol. 19

Agent Supply Chains and Protocol Security

Build a release gate for agent tool supply chains. Verify artifacts, detect drift, and enforce revocation and least privilege.

35 min read
Language AI Handbook · Vol. 19

Audit, Detection, and Incident Response

Design tamper-evident audit trails, build layered detectors that survive base rates, and run incident response with kill switches and evidence preservation.

50 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026identityauthorization, author = {Michael Brenndoerfer}, title = {Identity, Authorization, and Least Privilege}, year = {2026}, url = {https://mbrenndoerfer.com/writing/identity-authorization-least-privilege-agents}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Identity, Authorization, and Least Privilege. Retrieved from https://mbrenndoerfer.com/writing/identity-authorization-least-privilege-agents
MLAAcademic
Michael Brenndoerfer. "Identity, Authorization, and Least Privilege." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/identity-authorization-least-privilege-agents>.
CHICAGOAcademic
Michael Brenndoerfer. "Identity, Authorization, and Least Privilege." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/identity-authorization-least-privilege-agents.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Identity, Authorization, and Least Privilege'. Available at: https://mbrenndoerfer.com/writing/identity-authorization-least-privilege-agents (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Identity, Authorization, and Least Privilege. https://mbrenndoerfer.com/writing/identity-authorization-least-privilege-agents
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy