Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 2

Lab: Least-Privilege Tools and Per-User Authorization

Build a tool gateway that checks the verified user on every call, gives each tool its own narrow credential, refuses tokens issued for other services, and enforces rate and spend limits, then prove each check with negative tests in pytest.

Contentsand lesson path

What you will learn

  • Enforce least privilege: scoped credentials per tool, per-user authorization on every call, allowlists, and rate and spend limits.

Prerequisites: AI Security, Tool Calling

01. Goal and setup

In the threat-modelling lesson you found the paths by which untrusted text can push an agent towards an action. This lab removes the most common reason those paths are dangerous: tools that can do more than the current user is allowed to do.

The rule: the agent should never be able to do more than the person it is working for. The model chooses tools and arguments, and any text it reads can steer it, so the checks cannot live in the prompt. They live in code that runs on every call, between the model and the tool. Here that code is a gateway: the one function every tool call passes through.

You will build a small support system with two users. Alice is a customer who may list and read her own tickets. Bob is a support lead who may also refund orders. The gateway makes six checks on every call:

  1. The access token is genuine, was issued for this gateway, and has not expired.
  2. The user comes from the token, never from the model's arguments.
  3. The tool is on this user's allowlist, read fresh at the moment of the call.
  4. The token carries the scope the tool needs.
  5. The user's run is still inside its call and spend limits.
  6. The tool runs with its own narrow credential, not the user's token.

You need: Python 3.10 or later (tested with 3.12.13) and pytest 9.2.0 in a virtual environment. No API key and no network access: the model's tool calls are a fixed list, so every run prints the same output.

Files in this lab
toolgate/
├── tokens.py        step 1: signed access tokens with audience and expiry
├── backend.py       step 2: fake downstream services and their credentials
├── tools.py         step 3: tools, each with one narrow credential
├── gateway.py       step 4: the six checks, on every call
├── run_demo.py      step 5: replay the tool calls a model proposes
└── test_gateway.py  step 6: negative tests
Terminal
mkdir toolgate && cd toolgate
python3 -m venv .venv && . .venv/bin/activate
pip install pytest==9.2.0
python -m pytest --version
Expected output (last line; pip prints its progress first)
pytest 9.2.0

02. Step 1: Tokens that say who they are for

An access token is a string a client presents to prove that a request is allowed. A useful token carries claims: statements such as who the user is (sub, the subject), which service the token is meant for (aud, the audience), what it allows (scopes) and when it expires (exp). The issuer signs the claims, so nobody can change them without the signature failing.

Real systems use OAuth access tokens issued by an identity provider. This lab signs its own with HMAC-SHA256 from the standard library, with a key from LAB_SIGNING_KEY (the default is only for the lab). verify() does what a token library does: a constant-time signature comparison, then the audience, then the expiry.

The audience check is the one people skip, and it matters for agents. The MCP security best practices call accepting a token that was issued for some other service token passthrough, and say that an MCP server "MUST NOT accept any tokens that were not explicitly issued for the MCP server". If the gateway accepted any validly signed token, a token that a user gave to a calendar service could be replayed against your support tools.

Python · toolgate/tokens.py
"""Small signed access tokens, so the lab needs no identity provider.

Real systems use OAuth access tokens (often JWTs). The checks are the same:
signature, audience, expiry and scopes.
"""
import base64
import hashlib
import hmac
import json
import os
import time

KEY = os.environ.get("LAB_SIGNING_KEY", "lab-only-not-a-secret").encode()


class TokenError(Exception):
    pass


def _enc(raw):
    return base64.urlsafe_b64encode(raw).decode().rstrip("=")


def _dec(text):
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))


def issue(sub, aud, scopes, ttl=300, now=None):
    now = time.time() if now is None else now
    claims = {"sub": sub, "aud": aud, "scopes": sorted(scopes), "exp": int(now + ttl)}
    body = json.dumps(claims, sort_keys=True).encode()
    sig = hmac.new(KEY, body, hashlib.sha256).digest()
    return _enc(body) + "." + _enc(sig)


def verify(token, audience, now=None):
    now = time.time() if now is None else now
    try:
        body_part, sig_part = token.split(".")
        body, sig = _dec(body_part), _dec(sig_part)
    except ValueError:
        raise TokenError("malformed token") from None
    expected = hmac.new(KEY, body, hashlib.sha256).digest()
    if not hmac.compare_digest(sig, expected):
        raise TokenError("bad signature")
    claims = json.loads(body)
    if claims["aud"] != audience:
        raise TokenError(f"token was issued for {claims['aud']!r}, not this server")
    if claims["exp"] < now:
        raise TokenError("token expired")
    return claims
Terminal
python -c "import tokens as t; print(t.verify(t.issue('alice', 'gw', []), 'gw')['sub'])"
Expected output
alice

03. Step 2: Downstream services that check credentials

The tools in this lab call two fake downstream services: a ticket store and a payments service. backend.call() stands in for both. It refuses any action that the presented credential does not list, and it records every call it accepts in CALLS, so the tests can see exactly what reached the services and with which credential.

Alice owns ticket T-100 and order O-1; Bob owns T-200 and O-2. Amounts are in cents.

Python · toolgate/backend.py
"""Fake downstream services. Each call must present a credential that allows it."""
from dataclasses import dataclass

TICKETS = {
    "T-100": {"owner": "alice", "subject": "Late delivery", "order": "O-1"},
    "T-200": {"owner": "bob", "subject": "Broken charger", "order": "O-2"},
}
ORDERS = {
    "O-1": {"owner": "alice", "total": 4000},  # cents
    "O-2": {"owner": "bob", "total": 2500},
}
CALLS = []  # (credential name, action): what each downstream service received


@dataclass(frozen=True)
class Credential:
    name: str
    actions: frozenset


class Forbidden(Exception):
    pass


def call(credential, action, **kwargs):
    if action not in credential.actions:
        raise Forbidden(f"{credential.name} may not {action}")
    CALLS.append((credential.name, action))
    if action == "tickets:read":
        return TICKETS.get(kwargs["ticket_id"])
    if action == "tickets:list":
        return sorted(k for k, t in TICKETS.items() if t["owner"] == kwargs["owner"])
    if action == "orders:read":
        return ORDERS.get(kwargs["order_id"])
    if action == "payments:refund":
        return f"refunded {kwargs['amount']} cents on {kwargs['order_id']}"
    raise Forbidden(f"unknown action {action}")

04. Step 3: Tools with one narrow credential each

Least privilege means each part of a system gets only the access its job needs, so a part that is fooled or broken can do little harm. For agent tools this has two layers.

First, each tool has its own credential, scoped to its job. The ticket tools share tickets-reader, which can only read and list tickets; refund_order uses refunds-writer. A ticket tool that somehow attempted a refund would have its credential refused by the payments service.

Second, each tool checks the resource, not just the action. read_ticket fetches the ticket and then refuses it unless its owner is the current user. refund_order reads the order fresh, checks its owner, and checks that the amount is between 1 cent and the order total. The fresh read is deliberate: a decision made from data that the model saw earlier could be stale, so the check runs right before the side effect.

Notice what the tool functions do not take: the user's token. They get the user's name, which the gateway has already verified, and their own credential.

Python · toolgate/tools.py
"""Tools the model may call. Each has one narrow credential, a scope and a cost."""
from dataclasses import dataclass
from typing import Callable

import backend
from backend import Credential

TICKETS_RO = Credential("tickets-reader", frozenset({"tickets:read", "tickets:list"}))
REFUNDS = Credential("refunds-writer", frozenset({"orders:read", "payments:refund"}))


class NotAllowed(Exception):
    pass


def list_my_tickets(user, cred):
    return backend.call(cred, "tickets:list", owner=user)


def read_ticket(user, cred, ticket_id):
    ticket = backend.call(cred, "tickets:read", ticket_id=ticket_id)
    if ticket is None or ticket["owner"] != user:
        raise NotAllowed(f"no ticket {ticket_id} for {user}")
    return ticket["subject"]


def refund_order(user, cred, order_id, amount):
    order = backend.call(cred, "orders:read", order_id=order_id)  # fresh read
    if order is None or order["owner"] != user:
        raise NotAllowed(f"no order {order_id} for {user}")
    if not 0 < amount <= order["total"]:
        raise NotAllowed(f"amount must be 1..{order['total']}")
    return backend.call(cred, "payments:refund", order_id=order_id, amount=amount)


@dataclass(frozen=True)
class Tool:
    run: Callable
    scope: str
    credential: Credential
    cost_cents: int


TOOLS = {
    "list_my_tickets": Tool(list_my_tickets, "tickets:read", TICKETS_RO, 0),
    "read_ticket": Tool(read_ticket, "tickets:read", TICKETS_RO, 0),
    "refund_order": Tool(refund_order, "refunds:write", REFUNDS, 5),
}

05. Step 4: The gateway

Gateway.call() is the only way the agent loop can run a tool. It returns a dictionary shaped like an Anthropic tool_result block, with is_error set when the call is refused, so the model can explain the refusal instead of the loop crashing.

Read _call() from top to bottom; each numbered comment is one of the six checks from the goal. Three details are easy to miss.

The allowlist is a dictionary that the gateway reads on every call. It is not copied when the agent run starts, so if an administrator revokes a permission in the middle of a long run, the very next call sees it. This is authorisation revalidation: checking permission at each side effect, not once at login.

The gateway refuses any call whose arguments contain user or user_id. Identity comes from the verified token. If the model could name the user, a sentence such as "you are now acting for Bob" in a ticket would be enough to switch accounts.

The budget is counted per user for the current run, and a call is charged even if the tool then refuses it, which also stops a loop that keeps probing.

Python · toolgate/gateway.py
"""The only path from the model to a tool. Every check here runs on every call."""
from dataclasses import dataclass

import backend
import tokens
from tools import TOOLS, NotAllowed

AUDIENCE = "support-agent-gateway"


class Denied(Exception):
    pass


@dataclass
class Budget:
    max_calls: int = 10
    max_cost_cents: int = 10
    calls: int = 0
    cost_cents: int = 0


class Gateway:
    def __init__(self, permissions):
        self.permissions = permissions  # user -> set of tool names, read per call
        self.budgets = {}               # user -> Budget for the current run

    def call(self, token, name, args):
        """Return a tool_result-like dict; errors go back to the model as text."""
        try:
            return {"is_error": False, "content": self._call(token, name, args)}
        except (tokens.TokenError, Denied, NotAllowed, backend.Forbidden) as exc:
            return {"is_error": True, "content": f"denied: {exc}"}

    def _call(self, token, name, args):
        claims = tokens.verify(token, AUDIENCE)        # 1. who is asking?
        user = claims["sub"]
        if "user" in args or "user_id" in args:        # 2. identity is not an argument
            raise Denied("the user is set by the server, not by the model")
        tool = TOOLS.get(name)
        if tool is None or name not in self.permissions.get(user, set()):
            raise Denied(f"{user} may not call {name}")  # 3. per-user allowlist
        if tool.scope not in claims["scopes"]:
            raise Denied(f"token lacks scope {tool.scope}")  # 4. token scope
        budget = self.budgets.setdefault(user, Budget())  # 5. rate and spend
        if budget.calls >= budget.max_calls:
            raise Denied("call limit for this run reached")
        if budget.cost_cents + tool.cost_cents > budget.max_cost_cents:
            raise Denied("spend limit for this run reached")
        budget.calls += 1
        budget.cost_cents += tool.cost_cents
        return tool.run(user, tool.credential, **args)  # 6. the tool's own credential

06. Step 5: Replay what a model proposes

run_demo.py plays the part of the model. A real agent would receive these calls one at a time as tool_use blocks in replies from the Messages API, with the model name read from ANTHROPIC_MODEL (for example claude-sonnet-5-5). Here they are a fixed list, so you can predict and repeat the output. Calls 3 to 5 are the kind a confused or steered model makes: another user's ticket, a forged user_id, and a refund Alice is not allowed to issue, even though her token was signed correctly.

Python · toolgate/run_demo.py
"""Replay tool calls a model might propose for Alice, and print each decision.

The calls are fixed, in the shape of Anthropic `tool_use` blocks, so the output
is the same on every run. A real model would propose them one turn at a time.
"""
import os

import tokens
from gateway import Gateway

MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5-5")  # unused: no API call
PERMISSIONS = {
    "alice": {"list_my_tickets", "read_ticket"},
    "bob": {"list_my_tickets", "read_ticket", "refund_order"},
}
PROPOSED = [
    {"type": "tool_use", "id": "tu_1", "name": "list_my_tickets", "input": {}},
    {"type": "tool_use", "id": "tu_2", "name": "read_ticket",
     "input": {"ticket_id": "T-100"}},
    {"type": "tool_use", "id": "tu_3", "name": "read_ticket",
     "input": {"ticket_id": "T-200"}},
    {"type": "tool_use", "id": "tu_4", "name": "read_ticket",
     "input": {"ticket_id": "T-200", "user_id": "bob"}},
    {"type": "tool_use", "id": "tu_5", "name": "refund_order",
     "input": {"order_id": "O-1", "amount": 4000}},
]

gateway = Gateway(PERMISSIONS)
alice = tokens.issue("alice", "support-agent-gateway", {"tickets:read"})
for block in PROPOSED:
    result = gateway.call(alice, block["name"], block["input"])
    status = "ERROR" if result["is_error"] else "ok   "
    print(f"{block['id']} {block['name']:<15} {status} {result['content']}")
Terminal
python run_demo.py
Expected output
tu_1 list_my_tickets ok    ['T-100']
tu_2 read_ticket     ok    Late delivery
tu_3 read_ticket     ERROR denied: no ticket T-200 for alice
tu_4 read_ticket     ERROR denied: the user is set by the server, not by the model
tu_5 refund_order    ERROR denied: alice may not call refund_order

Each refusal comes from a different layer: tu_3 passed the gateway but the tool refused a ticket Alice does not own, tu_4 never reached the tool, and the allowlist stopped tu_5 before any credential was used.

07. Step 6: Negative tests

A negative test checks that something forbidden fails. Security code needs them more than anything else, because a missing check looks exactly like a working one when you only try allowed actions. Each test below tries one forbidden thing and asserts both the refusal and, where it matters, that nothing reached the downstream service.

The 15 tests cover every check from the goal, plus ownership and the refund amount: remove any one check and at least one test fails. One positive test makes sure a normal request still goes through, because a gateway that refused everything would pass every negative test.

Python · toolgate/test_gateway.py
"""Negative tests, plus one positive test: removing any check makes one fail."""
import pytest

import backend
import tokens
from gateway import AUDIENCE, Gateway
from tools import TICKETS_RO


@pytest.fixture
def gw():
    backend.CALLS.clear()
    return Gateway({
        "alice": {"list_my_tickets", "read_ticket"},
        "bob": {"list_my_tickets", "read_ticket", "refund_order"},
    })


def token(user, scopes=("tickets:read",), aud=AUDIENCE, ttl=300):
    return tokens.issue(user, aud, set(scopes), ttl=ttl)


BOB = ("tickets:read", "refunds:write")


def test_owner_reads_own_ticket(gw):
    assert gw.call(token("alice"), "read_ticket", {"ticket_id": "T-100"}) == {
        "is_error": False, "content": "Late delivery"}


def test_cannot_read_another_users_ticket(gw):
    result = gw.call(token("alice"), "read_ticket", {"ticket_id": "T-200"})
    assert result["is_error"] and "no ticket T-200" in result["content"]


def test_cannot_call_a_tool_outside_own_allowlist(gw):
    result = gw.call(token("alice", BOB), "refund_order",
                     {"order_id": "O-1", "amount": 100})
    assert result["is_error"] and "may not call refund_order" in result["content"]
    assert ("refunds-writer", "payments:refund") not in backend.CALLS


def test_model_cannot_choose_the_user(gw):
    result = gw.call(token("alice"), "read_ticket",
                     {"ticket_id": "T-200", "user_id": "bob"})
    assert result["is_error"] and "set by the server" in result["content"]


def test_token_for_another_service_is_rejected(gw):
    result = gw.call(token("bob", BOB, aud="calendar-api"), "list_my_tickets", {})
    assert result["is_error"] and "issued for 'calendar-api'" in result["content"]
    assert backend.CALLS == []


def test_tampered_token_is_rejected(gw):
    _, sig = token("alice").split(".")
    forged = tokens.issue("bob", AUDIENCE, set(BOB)).split(".")[0] + "." + sig
    result = gw.call(forged, "list_my_tickets", {})
    assert result["is_error"] and "bad signature" in result["content"]
    assert backend.CALLS == []


def test_token_without_the_scope_is_refused(gw):
    result = gw.call(token("bob"), "refund_order", {"order_id": "O-2", "amount": 1})
    assert result["is_error"] and "lacks scope refunds:write" in result["content"]


def test_expired_token_is_rejected(gw):
    result = gw.call(token("bob", BOB, ttl=-1), "list_my_tickets", {})
    assert result["is_error"] and "expired" in result["content"]


def test_user_token_is_not_forwarded_downstream(gw):
    bob = token("bob", BOB)
    result = gw.call(bob, "refund_order", {"order_id": "O-2", "amount": 500})
    assert not result["is_error"]
    assert backend.CALLS == [("refunds-writer", "orders:read"),
                             ("refunds-writer", "payments:refund")]
    assert bob not in repr(backend.CALLS)


def test_read_only_credential_cannot_refund():
    with pytest.raises(backend.Forbidden):
        backend.call(TICKETS_RO, "payments:refund", order_id="O-1", amount=1)


def test_revoked_permission_blocks_the_next_call(gw):
    bob = token("bob", BOB)
    args = {"order_id": "O-2", "amount": 100}
    assert not gw.call(bob, "refund_order", args)["is_error"]
    gw.permissions["bob"].discard("refund_order")  # an admin revokes it mid-run
    result = gw.call(bob, "refund_order", args)
    assert result["is_error"] and "may not call refund_order" in result["content"]
    assert backend.CALLS.count(("refunds-writer", "payments:refund")) == 1


def test_cannot_refund_another_users_order(gw):
    result = gw.call(token("bob", BOB), "refund_order",
                     {"order_id": "O-1", "amount": 1})
    assert result["is_error"] and "no order O-1 for bob" in result["content"]
    assert ("refunds-writer", "payments:refund") not in backend.CALLS


def test_refund_cannot_exceed_the_order_total(gw):
    result = gw.call(token("bob", BOB), "refund_order",
                     {"order_id": "O-2", "amount": 9999})
    assert result["is_error"] and "amount must be 1..2500" in result["content"]


def test_spend_limit_stops_repeated_refunds(gw):
    bob = token("bob", BOB)
    args = {"order_id": "O-2", "amount": 1}
    results = [gw.call(bob, "refund_order", args) for _ in range(3)]
    assert [r["is_error"] for r in results] == [False, False, True]
    assert "spend limit" in results[2]["content"]


def test_call_limit_stops_a_loop(gw):
    alice = token("alice")
    results = [gw.call(alice, "list_my_tickets", {}) for _ in range(11)]
    assert [r["is_error"] for r in results] == [False] * 10 + [True]
    assert "call limit" in results[10]["content"]
Terminal
python -m pytest -q
Illustrative output (the counts are exact; the time differs)
...............                                                          [100%]
15 passed in 0.11s

08. Step 7: Prove that the tests bite

A test suite is only useful if it fails when the protection is gone. Remove the allowlist check and run the tests again. Make a backup first, then open gateway.py and change the allowlist line from if tool is None or name not in self.permissions.get(user, set()): to if tool is None:.

Terminal
cp gateway.py gateway.py.bak
# edit gateway.py as described above, then:
python -m pytest -q --tb=no
mv gateway.py.bak gateway.py
python -m pytest -q
Illustrative output (the counts are exact; the time and line width differ)
..F.......F....                                                          [100%]
=========================== short test summary info ============================
FAILED test_gateway.py::test_cannot_call_a_tool_outside_own_allowlist - asser...
FAILED test_gateway.py::test_revoked_permission_blocks_the_next_call - assert...
2 failed, 13 passed in 0.17s
...............                                                          [100%]
15 passed in 0.11s

Two tests fail. The first is instructive: in that test Alice's token does carry the refunds:write scope, and order O-1 is hers, so without the allowlist the refund goes through. Token scopes describe what a client was granted; the allowlist describes what this user may do here. You need both. After you restore the file, all 15 tests pass again.

09. Troubleshooting

10. Check your understanding

Practice check · 3 questions

Least privilege in the gateway

Answer from the code in this lab.

Q1. In step 7, without the allowlist, why does Alice's refund of order `O-1` succeed?
Q2. An admin removes `refund_order` from Bob's permissions while his agent is in the middle of a run. When does the change take effect?
Q3. A teammate suggests passing the user's token to `backend.call()` so the payments service can check the user itself. What does the lab's design say?
Practice only: not graded, not saved, not evidence.

11. Apply it

For the practice project, put a gateway like this in front of every tool of your agent. Give each tool its own credential with the narrowest scope your provider supports, and write down why it needs each scope. Add a fixture for a revoked permission: start a run, revoke the permission after the first call, and assert that the next side effect is refused before any request leaves your process. Record the call and spend limits you chose per user and per run, and add one negative test per limit.

12. Review prompt

Without looking back: list the six checks the gateway makes, in order, and say which attack each one stops. Explain the difference between a token scope and a per-user allowlist, why the user must come from the token and not from the tool arguments, and what token passthrough is. Then say why a security test suite needs at least one positive test.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check