iamops.dev
Argo on X RSS feed
ENEnglish

Labs Practitioner · 25 min

Permit.io behind AuthZEN: deciding which MCP tool calls an agent may make

I put a Permit.io PDP behind a small MCP enforcement point that speaks AuthZEN. A $90 payment was refused, $45 was allowed, and errors failed closed.

Redacted Permit.io console screenshots from my lab: the Policy Editor with the payments_reader and payments_writer roles, and the Audit Log with two permitted and four denied tool calls.
TL;DRI rebuilt the OPA (Open Policy Agent) lab with Permit.io on the free…
Repeat this lab 7 steps

I wrote this lab so you can run it yourself. Each step has the commands to copy and the output I got, and you can tick it as done. Your ticks stay in this browser only.

Go to the steps

How this works

Copies a ready-made prompt for Claude Code, Cursor, Codex or any coding agent. For test environments only.

Show prompt
I want to run a hands-on lab from iamops.dev, and I would like your help to do it safely.

Lab: Permit.io behind AuthZEN: deciding which MCP tool calls an agent may make
Read the whole lab here (Markdown): https://iamops.dev/permit-authzen-mcp-tool-call-policy.md

What the lab needs before the first step:
- A free Permit.io account; the API key of its Development environment typed at the env.sh prompt
- Linux with Podman 5 or Docker, curl, jq and Python 3.10 or newer

How I want you to work:
1. Read the lab from start to finish first (each step lists its own prerequisites). Then check that the prerequisites are in place and that the tool versions match what the lab expects. Tell me what is missing before you run anything.
2. Run one step at a time. Before each command, show it to me and say in a sentence what it does.
3. Ask me before anything that costs money, creates cloud resources, touches a real tenant or account, or deletes anything. Wait for my answer.
4. Use the placeholders from the lab. Never paste real secrets, tokens or production identities into a command, a file or this chat. If a value is needed, tell me where to set it myself.
5. After each step, compare the output with the expected output in the lab. If it does not match, stop and tell me what differs. Do not carry on or invent a fix without asking me.
6. At the end, report what passed, what failed and which cleanup you did. Then offer to tick the steps off for me. The lab page keeps ticks only in my browser, so if you cannot do that, list the steps I should tick.

This lab is for test environments only. Do not run it against production, or against a tenant or account that holds real data or real users.

You may answer in my language.

Earlier this month I built a policy decision point for MCP tool calls with OPA: an agent proposes a tools/call, something in front of the MCP server asks a policy engine, and the engine answers yes or no through AuthZEN. This time the engine is Permit.io.

Permit.io is a good fit for the comparison for two reasons. Its PDP speaks AuthZEN 1.0 out of the box, and in March the team shipped Permit MCP Gateway, a proxy that sits in front of MCP servers and checks every tool call against Permit. Their post on the six layers every MCP gateway must enforce is a useful short list of what such a gateway has to do beyond routing.

I used only what the free Community plan includes. New accounts start with a 14-day Pro trial, but nothing in this lab needs it: RBAC, ABAC, the Edge PDP and the audit log are all in the free plan.

How Permit models MCP tool calls#

The gateway architecture docs describe the mapping. Each MCP server becomes a Permit resource type, keyed by the server key. Each tool becomes an action on that resource type. For a tool call the gateway runs a permit.check() with the agent as the user, the tool name as the action and the server as the resource, plus a second check for the person when an admin imported the server. Both must allow.

On top of that sit trust levels (low for reads, medium for writes, high for deletes) and a ceiling: the agent never gets more than the admin gave the person. Permit builds that ceiling as ReBAC rules. The docs also say that if the PDP does not answer, the gateway refuses the request, with JSON-RPC (remote procedure calls in JavaScript Object Notation) error -32005. A plain denial is -32004. I reused -32004 in my own enforcement point.

The PDP is the part I tested. Permit runs three kinds. The Cloud PDP is hosted at cloudpdp.api.permit.io and covers RBAC and ReBAC. The Edge PDP is an open-source container (permitio/pdp-v2) that bundles OPA and the OPAL (Open Policy Administration Layer) client and also covers ABAC. Nexus PDP is a newer container with an on-disk store. All three serve the AuthZEN endpoints: evaluation, batch evaluations, the three search APIs (application programming interfaces) and the discovery document.

Sequence diagram: the Permit control plane sends policy and data to the Edge PDP. An AI agent sends an MCP tools/call to pep.py, which takes the subject from the session and sends an AuthZEN evaluation to the PDP. For 9000 cents against a 5000 limit the PDP answers decision false and pep.py returns error -32004. For 4500 cents with confirmation it answers decision true and the tool runs. With no key in the PEP or the PDP stopped, pep.py denies and fails closed. The PDP sends decision logs to the Permit audit log.
The flow I ran. The enforcement point builds the AuthZEN request from the session, not from what the model wrote. The PDP decides from the policy it pulled from Permit, and errors end in a deny.

Setup#

I used Podman 5.4.2 on Debian 13 to run the Edge PDP image permitio/pdp-v2:0.9.17, Python 3.13, the Permit Python SDK (software development kit) 3.0.1 (the package on the Python Package Index is permit), curl and jq. Everything listens on localhost: 7766 for the PDP and 8383 for the enforcement point. Docker works the same way: replace podman with docker.

You need a free Permit.io account. Sign up at app.permit.io, open the Development environment of the default project and copy its API key from Settings, API Keys. The lab reads the key at a hidden prompt into one shell variable. It never goes into a file, a log or a screenshot, and the PDP container gets it as PDP_API_KEY.

The scenario is the one from the OPA lab. An agent called support-bot may read the balance and the transactions, and may send payments up to 5000 cents, $50, when the user confirmed. read-bot may only read. The tools are get_balance, list_transactions and send_payment on one MCP server, payments_mcp. delete_account does not exist.

The policy#

setup_permit.py creates the policy through the Permit API, so you can rebuild it in any environment and remove it with cleanup_permit.py:

  • Resource type payments_mcp with the three tools as actions, and two attributes, amount_cents and user_confirmed.
  • A user attribute limit_cents, set to 5000 for both agents.
  • Two roles that stand in for the scopes: payments_reader with the two read tools (RBAC), and payments_writer with no plain permissions.
  • An ABAC resource set, payment_within_limit: resource.amount_cents less than or equal to user.limit_cents, compared by reference, and resource.user_confirmed equals true. payments_writer gets send_payment only on that set.
Permit.io console, Policy, Resources tab: resource type Payments MCP server with key payments_mcp, attributes amount_cents: number and user_confirmed: bool, and the actions get_balance, list_transactions and send_payment.
The MCP server as a resource. One resource type, one action per tool, and the two attributes the ABAC rule reads.
Permit.io console, Policy Editor: role payments.read (payments_reader) has get_balance and list_transactions ticked on the Payments MCP server column and nothing in the Payment within limit column; role payments.write (payments_writer) has only send_payment ticked, in the Payment within limit column.
Roles in the policy editor. The reader gets the two read tools. The writer gets send_payment only in the resource set column, not on the server itself.
Permit.io console, edit view of the ABAC dynamic resource Payment within limit and confirmed, key payment_within_limit, resource type payments_mcp, with two conditions: resource.amount_cents less-than-equals (ref) user.limit_cents, and resource.user_confirmed equals True.
The ABAC rule. Opened in the edit panel; nothing was changed. The amount is compared with the agent's own limit attribute, not with a fixed number.
Permit.io console, Directory, Default Tenant, Users: support-bot with top level access payments_writer and payments_reader, and read-bot with payments_reader.
The two agents. Both agents are users in the default tenant; only support-bot holds the writer role.
Terminal output: a Python virtual environment gets the permit package 3.0.1, setup_permit.py prints policy created with payments_mcp, 2 roles, 1 resource set and 2 agents, podman starts permit-pdp from pdp-v2 0.9.17 with PDP_API_KEY taken from a shell variable, and the healthy endpoint reports status ok for OPA and horizon.
Policy in, PDP healthy. The key is passed as a variable and never shown. After 30 seconds both parts of the PDP report ok.

The PDP pulled the policy within the 30 seconds I gave it, and /healthy reported both of its parts as ok.

The enforcement point#

pep.py takes a JSON-RPC tools/call, looks up the agent from the session header, and sends Permit an AuthZEN Access Evaluation. The shape follows the gateway mapping: the subject is the agent, the action is the tool name, the resource is the MCP server. The amount and the confirmation go into resource.properties, because the Permit docs say the PDP reads tenant from there and passes the other keys to the policy as resource attributes.

python
body = {
    "subject": {"type": "user", "id": agent},
    "action": {"name": tool},
    "resource": {"type": "payments_mcp", "id": "payments_mcp", "properties": {
        "tenant": "default",
        "amount_cents": args.get("amount_cents", 0),
        "user_confirmed": bool(args.get("user_confirmed", False)),
    }},
}

The important lines are the ones after the call. Only HTTP (Hypertext Transfer Protocol) 200 with "decision": true allows. Any HTTP error, a timeout, a refused connection or a body without a boolean is a deny, and the log says which one it was.

Permit answers with more than the decision. The context field carries the reasoning, including the agent’s roles and its limit_cents. pep.py keeps the short reason codes for its own log and tells the agent only denied: policy. An agent that can read the limit can learn to split a payment under it.

Run 1: AuthZEN with a key#

First I checked the AuthZEN endpoints directly, with the key in the bearer header: the discovery document, one evaluation for get_balance, a batch of four payments in one request, and a subject search for who may call get_balance.

Terminal output: the AuthZEN discovery document lists six entries, an evaluation for get_balance answers decision true with the role payments_reader, a batch of four send_payment evaluations answers false, true, false, false with rbac and abac codes, and a subject search returns read-bot and support-bot.
Four payments, one yes. Only the confirmed $45 payment passes, through the ABAC rule. $90, the unconfirmed $45 and read-bot are refused.

The batch is the policy in four lines. $90 against the $50 limit: false. $45 confirmed: true, allowed by the ABAC rule. $45 not confirmed: false. The same $45 by read-bot, set as a per-item subject inside the batch: false. The subject search found both agents, because both hold payments_reader. The action search returned an empty list for both agents in my run. I did not dig into why, so I do not rely on it here.

Run 2: six tool calls through the enforcement point#

Then I started pep.py and sent the six calls from the OPA lab: a balance read, a $90 payment, a $45 payment with and without confirmation, a payment by read-bot, and the unknown delete_account.

Terminal output: six JSON-RPC responses from pep.py, two results for get_balance and send_payment and four errors -32004 denied: policy, then the pep.log lines: get_balance ALLOW by rbac, the $90 send_payment DENY, the confirmed $45 send_payment ALLOW by abac, the unconfirmed one DENY, read-bot DENY, and delete_account DENY with rbac no_such_action.
Two allowed, four denied. The same outcome as the OPA lab. The agent only sees denied: policy; the reason codes stay in the log.

The results match the OPA lab. Two calls ran: the balance read, allowed by the role, and the confirmed $45 payment, allowed by the ABAC rule. Four were denied by the policy. For delete_account the PDP said no_such_action: the tool is not an action on payments_mcp, so no role can grant it.

Each decision also reached the Permit audit log. I counted them through the audit log API: user, action, resource type and decision for every call in this run, including the ones from the Cloud PDP in run 4.

Permit.io console, Audit Log, Check view: rows from 11:23:53 to 11:25:17 AM on 22 Nov 2026, all on payments_mcp in tenant default. The six rows at 11:25:17 are delete_account denied, read-bot send_payment denied, support-bot send_payment denied, permitted and denied, and get_balance permitted.
Decisions in the audit log. The six rows at 11:25:17 are one run of the six calls: two permitted, four denied. The rows below are from earlier runs.
Permit.io console, Audit Event for read-bot send_payment on payments_mcp at 11:25:17 AM, decision denied, with debug JSON showing abac allow false, code no_matching_rules, and the reason that read-bot does not match any rule that grants the send_payment permission on payments_mcp.
Why read-bot was refused. The audit entry keeps the reasoning the PDP returned: no matching rule.

Run 3: fail closed with a live policy#

A working policy does not make the error path go away. I restarted pep.py with an empty key against the same healthy PDP, and then stopped the PDP container and sent the $45 payment again.

Terminal output: pep.py restarted with an empty key returns error -32004 denied: pdp error HTTP 403, fail closed for the confirmed $45 payment; after podman stops permit-pdp the same call returns denied: pdp unreachable (URLError), fail closed, and pep.log shows both reasons.
An allowed call, refused twice. The policy says yes, but without a key or a PDP the enforcement point says no, and the log says why.

Both times the confirmed $45 payment, which the policy allows, was refused. The log line says why: pdp error HTTP 403 and pdp unreachable, not decision false. That difference is what an alert should watch.

Run 4: the Cloud PDP does not evaluate ABAC#

The Cloud PDP accepted the same key and the same batch, and answered false four times. The reason was in the context: ABAC is not supported yet in the Cloud PDP. With pep.py pointed at the Cloud PDP, the balance read still ran on the role, but the confirmed $45 payment was refused.

Terminal output: the same batch sent to cloudpdp.api.permit.io answers decision false four times with ABAC is not supported yet in the Cloud PDP; pep.py pointed at the Cloud PDP allows get_balance and denies both send_payment calls, and the log shows abac NOT_SUPPORTED.
The Cloud PDP skips ABAC. The role still works, the limit rule does not, so even the confirmed $45 payment is refused.

This fails closed, which is the safe direction, but it would read as a broken policy if you did not know. Limits like this one need the Edge PDP, or a policy that does not depend on ABAC.

Before the key: what a PDP without a key does#

Before the account existed I ran the same lab without a key. I keep these results because they show what a misconfigured PDP looks like from the enforcement point.

The container started without PDP_API_KEY and did not exit. Its watchdog kept restarting the internal API server, and /healthy reported an error.

Terminal output: podman starts permit-pdp from pdp-v2 0.9.17, the container is up, the log says Failed to get Environment API Key with ApiKeyError No API key specified, and the healthy endpoint reports status error with the message that the PDP has no API key yet.
Up, but not healthy. The container runs, and the PDP says plainly that it has no API key.

AuthZEN requests got status codes and never a decision: 401 without a header, 403 with an empty bearer token, and 503 with a wrong key. The container also wanted a token for the discovery document.

Terminal output: healthy answers HTTP 503, an AuthZEN evaluation without an Authorization header answers Missing Authorization header with HTTP 401, and the same request with an empty bearer token answers that the caller is not authorized, with HTTP 403.
No decision, only status codes. 503 on health, 401 without a header, 403 with an empty key.

All six tool calls through pep.py were denied, each with pdp error HTTP 403. The right result for the wrong reason. To the agent, a PDP that lost its key looks the same as a strict policy, so only the log can tell them apart.

Terminal output: six JSON-RPC responses, each an error with code -32004 and the message denied, pdp error HTTP 403, fail closed, followed by the enforcement point log with one DENY line per call for support-bot and read-bot.
Six calls, six denials. Even the harmless balance read is refused, because the PDP gave no decision.

The Cloud PDP served its discovery document without a token and answered 401 to an evaluation without one. Error bodies differ: JSON on the Cloud PDP, plain text on the container.

Terminal output: the Cloud PDP discovery document lists the evaluation, batch evaluations and three search endpoints, an evaluation without a token answers Unauthorized with HTTP 401, and the enforcement point pointed at the Cloud PDP denies two calls with pdp error HTTP 401, fail closed.
Discovery is public, decisions are not. All five AuthZEN endpoints are listed, and the enforcement point fails closed on the 401.

Gotchas#

  • The Cloud PDP ignores ABAC. It answers false with NOT_SUPPORTED in the context. Use the Edge PDP for attribute rules. It also sends no CORS (cross-origin resource sharing) headers, so a browser cannot read its answers; call it from a server.
  • The decision context says a lot. Roles, attributes and rule names come back with every answer. Log the codes, do not forward them to the agent.
  • A missing key is not a policy. The container stays up and answers 401, 403 or 503 depending on what you send. Only the PEP can turn that into a safe deny.
  • The subject comes from the session. pep.py ignores any agent name in the arguments. The same rule applies to user_confirmed: in a real gateway it must come from a confirmation step the model cannot fake.
  • Tool lists are not filtered. The Permit gateway docs say tools/list returns every upstream tool and enforcement happens on each call. An agent can see a tool it cannot use.
  • The gateway uses the SDK check, not AuthZEN. AuthZEN is how another PEP, like mine, talks to the same PDP.

What I would do with this#

  1. Make the enforcement point fail closed and log why, then stop the PDP in a test and check the log line.
  2. Alert when denials come from PDP errors instead of policy decisions.
  3. Keep the PDP key on the server side, in the gateway or a sidecar, never in a browser or an agent prompt.
  4. Pick the PDP type by the policy model: ABAC limits like this one need the Edge PDP.
  5. Strip the decision context before anything goes back to the agent.

What was not run#

This lab runs its own small enforcement point instead of the hosted Permit MCP Gateway. It only uses features of the free Community plan.

Terminal images are renders of the saved output from 22 November 2026; console screenshots are from the same day. The key never appears.

Repeat this lab#

This lab needs a free Permit.io account, Linux with Podman or Docker, curl, jq and Python 3.10 or newer. Plan for about 25 minutes. env.sh asks for the API key of your Development environment at a hidden prompt; keep it out of files, chats and screenshots. Open each step, copy the blocks and compare the output with mine.

Every value in angle brackets is a placeholder for your own test environment. Nothing on this page is a real identifier or secret.

Set your variables once

bash · env.sh
# Paste into every terminal you use for this lab.
export PDP_IMAGE="docker.io/permitio/pdp-v2:0.9.17"
export PDP_URL="http://localhost:7766"
# The API key of your Permit.io Development environment (Settings, API Keys). Type it at the prompt;
# it stays in this shell only. Never put it in a file you commit, a chat or a screenshot.
read -rsp "Permit API key: " PERMIT_API_KEY; echo; export PERMIT_API_KEY
# Headers for every AuthZEN call to the PDP.
AUTHZ=(-H "authorization: Bearer $PERMIT_API_KEY" -H "content-type: application/json")
Step 1Load the policy into your Permit environment

Goal. Install the Permit Python SDK in a virtual environment and run setup_permit.py to create the resource, roles, ABAC resource set and two agents.

Prerequisites

  • A free Permit.io account; the API key of its Development environment typed at the env.sh prompt
  • Linux with Podman 5 or Docker, curl, jq and Python 3.10 or newer
bash · setup_permit.py
cat > setup_permit.py <<'EOF'
"""Create the lab policy in a Permit.io environment (free Community plan).
Reads PERMIT_API_KEY from the environment. Run once; cleanup_permit.py removes it.
Model: one resource type per MCP server, one action per tool (the way Permit MCP Gateway maps servers and tools)."""
import asyncio, inspect, os
from permit import Permit

permit = Permit(token=os.environ["PERMIT_API_KEY"], pdp=os.environ.get("PDP_URL", "http://localhost:7766"))
api = permit.api


async def call(result):
    return await result if inspect.isawaitable(result) else result


async def main():
    # The MCP server "payments_mcp" and its three tools. Payment calls carry the amount and the confirmation.
    await call(api.resources.create({
        "key": "payments_mcp", "name": "Payments MCP server",
        "actions": {"get_balance": {}, "list_transactions": {}, "send_payment": {}},
        "attributes": {"amount_cents": {"type": "number"}, "user_confirmed": {"type": "bool"}},
    }))
    # The agent's delegated limit is a user attribute.
    await call(api.resource_attributes.create("__user", {"key": "limit_cents", "type": "number"}))
    # Scopes become roles. The reader can call the two read tools on every call.
    await call(api.roles.create({"key": "payments_reader", "name": "payments.read",
                                 "permissions": ["payments_mcp:get_balance", "payments_mcp:list_transactions"]}))
    # The writer gets send_payment only on calls inside the limit and confirmed by the user.
    await call(api.roles.create({"key": "payments_writer", "name": "payments.write"}))
    await call(api.condition_sets.create({
        "key": "payment_within_limit", "name": "Payment within limit and confirmed",
        "type": "resourceset", "resource_id": "payments_mcp",
        "conditions": {"allOf": [
            {"resource.amount_cents": {"less-than-equals": {"ref": "user.limit_cents"}}},
            {"resource.user_confirmed": {"equals": True}},
        ]},
    }))
    await call(api.condition_set_rules.create({
        "user_set": "payments_writer", "is_role": True,
        "permission": "payments_mcp:send_payment", "resource_set": "payment_within_limit",
    }))
    # Two agents: support-bot holds both scopes and a 5000-cent limit, read-bot only reads.
    for key, roles in (("support-bot", ["payments_reader", "payments_writer"]), ("read-bot", ["payments_reader"])):
        await call(api.users.sync({"key": key, "attributes": {"limit_cents": 5000}}))
        for role in roles:
            await call(api.users.assign_role({"user": key, "role": role, "tenant": "default"}))
    print("policy created: payments_mcp, 2 roles, 1 resource set, 2 agents")

asyncio.run(main())
EOF
bash · setup-policy.sh
python3 -m venv .venv && .venv/bin/pip install -q permit==3.0.1
.venv/bin/python setup_permit.py

Expected output

output
policy created: payments_mcp, 2 roles, 1 resource set, 2 agents
Step 2Start the Permit Edge PDP with the key

Goal. Start the pinned Edge PDP image with PDP_API_KEY from the shell variable, wait for it to pull the policy and read its health endpoint.

Prerequisites

  • The policy from the previous step exists
  • Ports 7766 and 8383 free
bash · start-pdp.sh
podman pull -q $PDP_IMAGE > /dev/null
podman run -d --name permit-pdp -p 7766:7000 -e PDP_API_KEY=$PERMIT_API_KEY $PDP_IMAGE | cut -c1-12
sleep 30
podman ps --format "{{.Names}} {{.Image}} {{.Status}}"
curl -s $PDP_URL/healthy | jq -c '{status, opa: .components.opa.status, horizon: .components.horizon.status}'

Expected output

output
<container-id>
permit-pdp docker.io/permitio/pdp-v2:0.9.17 Up 30 seconds
{"status":"ok","opa":"ok","horizon":"ok"}
Step 3Ask the PDP over AuthZEN

Goal. Read the discovery document, send one evaluation, a batch of four payments and a subject search, and compare the decisions.

Prerequisites

  • The PDP is healthy
bash · authzen.sh
cat > get_balance.json <<'EOF'
{"subject": {"type": "user", "id": "support-bot"},
 "action": {"name": "get_balance"},
 "resource": {"type": "payments_mcp", "id": "payments_mcp", "properties": {"tenant": "default"}}}
EOF
cat > batch.json <<'EOF'
{"subject": {"type": "user", "id": "support-bot"},
 "action": {"name": "send_payment"},
 "evaluations": [
  {"resource": {"type": "payments_mcp", "id": "payments_mcp", "properties": {"tenant": "default", "amount_cents": 9000, "user_confirmed": true}}},
  {"resource": {"type": "payments_mcp", "id": "payments_mcp", "properties": {"tenant": "default", "amount_cents": 4500, "user_confirmed": true}}},
  {"resource": {"type": "payments_mcp", "id": "payments_mcp", "properties": {"tenant": "default", "amount_cents": 4500, "user_confirmed": false}}},
  {"subject": {"type": "user", "id": "read-bot"}, "resource": {"type": "payments_mcp", "id": "payments_mcp", "properties": {"tenant": "default", "amount_cents": 4500, "user_confirmed": true}}}
 ]}
EOF
cat > search.json <<'EOF'
{"subject": {"type": "user"},
 "action": {"name": "get_balance"},
 "resource": {"type": "payments_mcp", "id": "payments_mcp", "properties": {"tenant": "default"}}}
EOF
curl -s $PDP_URL/.well-known/authzen-configuration "${AUTHZ[@]}" | jq -c '[keys[] | sub("_endpoint$"; "")]'
curl -s -X POST $PDP_URL/access/v1/evaluation "${AUTHZ[@]}" -d @get_balance.json \
  | jq -c '{decision, roles: .context.rbac.allowing_roles}'
curl -s -X POST $PDP_URL/access/v1/evaluations "${AUTHZ[@]}" -d @batch.json \
  | jq -c '.evaluations[] | {decision, rbac: .context.rbac.code, abac: .context.abac.code}'
curl -s -X POST $PDP_URL/access/v1/search/subject "${AUTHZ[@]}" -d @search.json | jq -c '.results'

Expected output

output
["access_evaluation","access_evaluations","policy_decision_point","search_action","search_resource","search_subject"]
{"decision":true,"roles":["payments_reader"]}
{"decision":false,"rbac":"no_permission","abac":"no_matching_rules"}
{"decision":true,"rbac":null,"abac":"allow"}
{"decision":false,"rbac":"no_permission","abac":"no_matching_rules"}
{"decision":false,"rbac":"no_permission","abac":"no_matching_rules"}
[{"type":"user","id":"support-bot"},{"type":"user","id":"read-bot"}]
Step 4Run six tool calls through the enforcement point

Goal. Write pep.py and calls.sh, start the enforcement point and send the six MCP tool calls from the OPA lab.

Prerequisites

  • The PDP is healthy
  • Port 8383 free
bash · pep.py
cat > pep.py <<'EOF'
"""A tiny enforcement point in front of an MCP server, for the lab only.
It takes an MCP JSON-RPC tools/call, builds an AuthZEN Access Evaluation from what the
gateway knows (the session), not from what the model wrote, and asks the PDP.
Anything other than HTTP 200 with "decision": true is a deny. Standard library only."""
import json, os, urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer

PDP = os.environ.get("PDP_URL", "http://localhost:7766") + "/access/v1/evaluation"
KEY = os.environ.get("PERMIT_API_KEY", "")
# Stand-in for a verified session: in a real gateway this comes from the token and the delegation record.
SESSIONS = {"s-support": "support-bot", "s-read": "read-bot"}


def ask_pdp(agent, tool, args):
    body = {
        "subject": {"type": "user", "id": agent},
        "action": {"name": tool},
        "resource": {"type": "payments_mcp", "id": "payments_mcp", "properties": {
            "tenant": "default",
            "amount_cents": args.get("amount_cents", 0),
            "user_confirmed": bool(args.get("user_confirmed", False)),
        }},
    }
    req = urllib.request.Request(PDP, data=json.dumps(body).encode(), method="POST", headers={
        "content-type": "application/json", "authorization": f"Bearer {KEY}"})
    try:
        with urllib.request.urlopen(req, timeout=3) as r:
            answer = json.load(r)
    except urllib.error.HTTPError as e:
        return False, f"pdp error HTTP {e.code}, fail closed"
    except Exception as e:
        return False, f"pdp unreachable ({type(e).__name__}), fail closed"
    if not isinstance(answer, dict):
        return False, "pdp sent no decision, fail closed"
    # Permit puts its reasoning in "context". Keep the codes for our log, never send them to the agent.
    ctx = answer.get("context") or {}
    codes = ", ".join(f"{k} {ctx[k]['code']}" for k in ("rbac", "abac", "rebac")
                      if isinstance(ctx.get(k), dict) and "code" in ctx[k])
    return answer.get("decision") is True, f"decision {json.dumps(answer.get('decision'))} ({codes or 'no context'})"


class Gateway(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def do_POST(self):
        msg = json.loads(self.rfile.read(int(self.headers["content-length"])))
        agent = SESSIONS.get(self.headers.get("x-session", ""))
        params = msg.get("params", {})
        if msg.get("method") != "tools/call" or not agent:
            allowed, why = False, "no session or not a tools/call"
        else:
            allowed, why = ask_pdp(agent, params.get("name", ""), params.get("arguments", {}))
        print(f"{agent} {params.get('name')} -> {'ALLOW' if allowed else 'DENY'}: {why}", flush=True)
        if allowed:
            out = {"jsonrpc": "2.0", "id": msg.get("id"),
                   "result": {"content": [{"type": "text", "text": f"called {params['name']} (stub)"}]}}
        else:
            # The agent learns that it was denied and whether the PDP failed, not the policy details.
            reason = "policy" if why.startswith("decision") else why
            out = {"jsonrpc": "2.0", "id": msg.get("id"), "error": {"code": -32004, "message": f"denied: {reason}"}}
        data = json.dumps(out).encode()
        self.send_response(200)
        self.send_header("content-type", "application/json")
        self.end_headers()
        self.wfile.write(data)


HTTPServer(("127.0.0.1", 8383), Gateway).serve_forever()
EOF
bash · calls.sh
cat > calls.sh <<'EOF'
# Six MCP tool calls through the enforcement point on :8383.
call() { # session tool arguments-json
  curl -s localhost:8383/mcp -H 'content-type: application/json' -H "x-session: $1" \
    -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"'"$2"'","arguments":'"$3"'}}'; echo; }
call s-support get_balance '{}'
call s-support send_payment '{"amount_cents":9000,"user_confirmed":true}'
call s-support send_payment '{"amount_cents":4500,"user_confirmed":true}'
call s-support send_payment '{"amount_cents":4500,"user_confirmed":false}'
call s-read    send_payment '{"amount_cents":4500,"user_confirmed":true}'
call s-support delete_account '{}'
EOF
python3 pep.py > pep.log &
sleep 1
bash calls.sh
cat pep.log

Expected output

output
{"jsonrpc": "2.0", "id": 1, "result": {"content": [{"type": "text", "text": "called get_balance (stub)"}]}}
{"jsonrpc": "2.0", "id": 1, "error": {"code": -32004, "message": "denied: policy"}}
{"jsonrpc": "2.0", "id": 1, "result": {"content": [{"type": "text", "text": "called send_payment (stub)"}]}}
{"jsonrpc": "2.0", "id": 1, "error": {"code": -32004, "message": "denied: policy"}}
{"jsonrpc": "2.0", "id": 1, "error": {"code": -32004, "message": "denied: policy"}}
{"jsonrpc": "2.0", "id": 1, "error": {"code": -32004, "message": "denied: policy"}}
support-bot get_balance -> ALLOW: decision true (rbac allow)
support-bot send_payment -> DENY: decision false (rbac no_permission, abac no_matching_rules)
support-bot send_payment -> ALLOW: decision true (abac allow)
support-bot send_payment -> DENY: decision false (rbac no_permission, abac no_matching_rules)
read-bot send_payment -> DENY: decision false (rbac no_permission, abac no_matching_rules)
support-bot delete_account -> DENY: decision false (rbac no_such_action, abac no_matching_rules)
Step 5Break the key, then stop the PDP

Goal. Restart the enforcement point with an empty key, then stop the PDP container, and send the allowed $45 payment each time.

Prerequisites

  • pep.py and calls.sh from the previous step
bash · fail-closed.sh
pkill -f "python3 pep.py"; sleep 1
env -u PERMIT_API_KEY python3 pep.py > pep.log &
sleep 1
bash calls.sh | sed -n 3p
pkill -f "python3 pep.py"; sleep 1
python3 pep.py >> pep.log &
podman stop permit-pdp > /dev/null && podman ps -a --format "{{.Names}} {{.Status}}"
sleep 1
bash calls.sh | sed -n 3p
cat pep.log | sed -n '3p;9p'
podman start permit-pdp > /dev/null

Expected output

output
{"jsonrpc": "2.0", "id": 1, "error": {"code": -32004, "message": "denied: pdp error HTTP 403, fail closed"}}
permit-pdp Exited (0) Less than a second ago
{"jsonrpc": "2.0", "id": 1, "error": {"code": -32004, "message": "denied: pdp unreachable (URLError), fail closed"}}
support-bot send_payment -> DENY: pdp error HTTP 403, fail closed
support-bot send_payment -> DENY: pdp unreachable (URLError), fail closed
Step 6Send the same batch to the Cloud PDP

Goal. Send the batch to the Permit Cloud PDP with the same key, then point the enforcement point at it and send the first three calls.

Prerequisites

  • Outbound HTTPS to cloudpdp.api.permit.io
bash · cloud-pdp.sh
curl -s -X POST https://cloudpdp.api.permit.io/access/v1/evaluations "${AUTHZ[@]}" -d @batch.json \
  | jq -c '.evaluations[] | {decision, abac: .context.abac.reason}'
pkill -f "python3 pep.py"; sleep 1
PDP_URL=https://cloudpdp.api.permit.io python3 pep.py > pep.log &
sleep 1
bash calls.sh | head -3
cat pep.log | head -3

Expected output

output
{"decision":false,"abac":"ABAC is not supported yet in the Cloud PDP"}
{"decision":false,"abac":"ABAC is not supported yet in the Cloud PDP"}
{"decision":false,"abac":"ABAC is not supported yet in the Cloud PDP"}
{"decision":false,"abac":"ABAC is not supported yet in the Cloud PDP"}
{"jsonrpc": "2.0", "id": 1, "result": {"content": [{"type": "text", "text": "called get_balance (stub)"}]}}
{"jsonrpc": "2.0", "id": 1, "error": {"code": -32004, "message": "denied: policy"}}
{"jsonrpc": "2.0", "id": 1, "error": {"code": -32004, "message": "denied: policy"}}
support-bot get_balance -> ALLOW: decision true (abac ABAC_EARLY_EXIT, rebac EARLY_EXIT)
support-bot send_payment -> DENY: decision false (rbac NO_PERMISSION, abac NOT_SUPPORTED, rebac NO_PERMISSION)
support-bot send_payment -> DENY: decision false (rbac NO_PERMISSION, abac NOT_SUPPORTED, rebac NO_PERMISSION)
Step 7Clean up

Goal. Stop the enforcement point, remove the container, delete the policy from your Permit environment and delete the files.

Prerequisites

  • Nothing else uses ports 7766 and 8383
bash · cleanup.sh
cat > cleanup_permit.py <<'EOF'
"""Remove what setup_permit.py created. Reads PERMIT_API_KEY from the environment."""
import asyncio, inspect, os
from permit import Permit

api = Permit(token=os.environ["PERMIT_API_KEY"]).api


async def call(result):
    return await result if inspect.isawaitable(result) else result


async def main():
    for step in (lambda: api.users.delete("support-bot"), lambda: api.users.delete("read-bot"),
                 lambda: api.condition_sets.delete("payment_within_limit"),
                 lambda: api.roles.delete("payments_writer"), lambda: api.roles.delete("payments_reader"),
                 lambda: api.resource_attributes.delete("__user", "limit_cents"),
                 lambda: api.resources.delete("payments_mcp")):
        try:
            await call(step())
        except Exception as e:  # keep going, report what is left
            print("cleanup:", type(e).__name__, str(e)[:120])
    print("cleanup done")

asyncio.run(main())
EOF
pkill -f "python3 pep.py"
podman rm -f permit-pdp > /dev/null
.venv/bin/python cleanup_permit.py
rm -rf .venv setup_permit.py cleanup_permit.py pep.py calls.sh get_balance.json batch.json search.json pep.log
podman ps -a --format "{{.Names}}" | grep -c permit-pdp
curl -s -o /dev/null -w "%{http_code}\n" localhost:8383 ; curl -s -o /dev/null -w "%{http_code}\n" localhost:7766/healthy

Expected output

output
cleanup done
0
000
000

Sources#

Discuss this on X or LinkedIn

Follow on X

New posts by email

One email a week with new posts and labs. Unsubscribe anytime.

Your address is stored with Kit, which sends the emails. Details

Related posts and labs