DEV Community

Cover image for Field Notes: The Gateway policy saw the agent, not the user
Raj Murugan
Raj Murugan

Posted on Edited on Originally published at rajmurugan.com

Field Notes: The Gateway policy saw the agent, not the user

An agent that calls its tools with its own token is the easy default, and the wrong one once a policy has to tell users apart. This post puts a staff-only policy on an Amazon Bedrock AgentCore Gateway (the managed endpoint an agent calls its tools through). It shows three things. The agent's token let a customer past the rule. The customer's own token was refused before the tool ran. A stale token kept working after the customer was removed from the staff group. Every result came from scripted calls against a mock shop in one AWS account, in us-east-1.

The use case

A smoothie shop gives its staff free drinks. It puts an ordering agent on the counter, and because the agent makes staff drinks, it signs in with a staff account. The shop adds one rule to the free smoothie tool: staff only. A customer asks the agent for a free smoothie and gets one. The rule ran as written. Swap the smoothie for a pull request and it is the shape of an AWS re:Post question: an ops agent that opens pull requests for people who are not allowed to push to the repo.

Three callers appear throughout. The customer is not staff and must not get free drinks. Alice works at the shop and is in the staff group. The agent signs in as agent-svc, a service user that is also in staff. A later case adds Carol, a test user in both staff and barista, to show how a list of groups reaches the policy.

In a regulated business the free smoothie is a fee waiver, a limit override or access to a customer's records, and the staff-only rule is the control an auditor expects to see enforced. If it holds only when the agent happens to use the right token, you cannot show that it holds.

The core idea: A Gateway policy judges the token it is shown, so your code must send a token for the asking user. This demo forwards the user's access token as a shortcut. In production, send one issued for that Gateway that names the user (untested here). That fix has one limit: even the user's own token is a snapshot of their groups, and it can go stale (see "The limit: a stale claim" below). It does not stop prompt injection or other routes to the tool, and the tool's own record does not show who asked.

The lessons:

  • The agent's own token got a customer the staff-only free smoothie, because the agent was in the staff group.
  • The customer's own token was denied before the tool ran, and added no row to the tool's record of calls.
  • The policy knows only what the token says about the user. A token taken while the customer was briefly staff still worked after they were removed; a fresh one was denied.

The rules:

  • Your code picks the token for each tool call, from the asking user's own sign-in. The model never sees or chooses it, and in production the agent must have no way to create one.
  • Match the group name with its quote marks, "staff". A bare *staff* let a user in staff-applicant through. This fails if group names can contain quote marks (see below).

The test: sign in as a user who should be refused, such as one in staff-applicant, and ask your agent for the action. The Gateway must deny it, and an allowed user must succeed. If not, suspect the token or the rule.

This post applies The LLM is not a security boundary to a managed service, and shows where that protection ends.

The same rule at an airline desk

This part is the demo's rule mapped onto an airline. I did not run it, and the demo has no airline tools.

Take a disruption desk where an agent rebooks passengers after a cancellation. Airline staff at the desk, such as a supervisor, are in the staff group. The agent signs in as a service account that is also in staff, because it has to waive change fees. The shop has three tools: a free smoothie, a paid order and a refund. Waiving a fee is the free smoothie: staff only. Rebooking is the paid order: anyone signed in. A real desk would also check that a passenger owns the booking, and this rule does not. A refund over a set limit is the refund: no rule permits it, so it is denied. An approval path would be separate, and this sketch does not build one.

Say a passenger asks the agent to waive a fee. With the agent's token the rule would see staff and permit it. With the passenger's token it would refuse before the tool runs. A supervisor asking with their own token would be allowed. Now an auditor asks you to show that only staff can waive a fee. Only the second design lets the policy test the asker's group, as it stood when the token was issued. That alone is not audit evidence. A supervisor removed from the group ten minutes ago may still waive fees on an older token until it expires. I infer that from the stale claim further down.

The smoothie shop rule at an airline disruption desk, an illustration that was not run. Rule: only staff may waive a fee, and the agent's account is in staff. Waive a change fee: a passenger asking with the agent's token is allowed, which is wrong; a passenger with their own token is denied; airline staff with their own token are allowed. Rebook a passenger: allowed in all three. Refund over the limit: denied in all three.

The setup

An AgentCore Gateway is the endpoint an agent calls to use tools, here over MCP (the Model Context Protocol). Policy in AgentCore lets you attach a set of rules, written in the Cedar policy language, to a Gateway. In this post, "the policy" means those rules. In ENFORCE mode a call is blocked if no rule permits it or a forbid rule matches.

The demo is a shop with three tools: free_smoothie, paid_order and refund. Free smoothies are a staff perk, anyone signed in can place a paid order, and no rule permits a refund. All three sit behind a mock Lambda that records each call to DynamoDB. Nothing is made or charged.

The same target (the Gateway's name for the mock Lambda) sits behind three AgentCore Gateways: one with no policy, one with a staff-only policy in ENFORCE mode, and one with a deliberately wrong rule. Amazon Cognito, the AWS sign-in service, issues the tokens. The person asking is a customer. Alice works at the shop. The agent signs in as agent-svc, a password-based Cognito user standing in for its service credential, and that user is in the staff group.

To get each user's token, the script signs in as them with admin credentials and one throwaway password. That is a demo shortcut: a real agent must receive the user's token from that user's own sign-in, and have no way to create one.

The deployed smoothie shop demo. Rule: only staff can call the free smoothie tool. A scripted agent gets tokens from Amazon Cognito and makes three calls. Call 1, the agent's token to an open Gateway with no policy: the free smoothie is given. Call 2, the agent's token to the guarded Gateway, which permits group staff: still given. Call 3, the customer's token to the same guarded Gateway: denied before the AWS Lambda function runs. Allowed calls reach the function, which records them in DynamoDB.

The third Gateway is not drawn. The "agent" is a script standing in for the model's tool calls, because enforcement must not depend on what the model decides. All twelve case results are in the transcript.

Cases 1 and 2: the agent's token

Case Result
No policy, agent's own token, the customer asks for a free smoothie Allowed
Staff-only policy, agent's own token, same request Allowed

The working policy changed nothing, because it judges the token, and the token was the agent's. I put agent-svc in staff, as someone might for an agent that makes staff drinks. Default deny still applied (nobody can refund), but the rule could not tell one asker from another. The customer's name travelled only as a requested_by argument, which my policy did not read and should not trust.

Case 3: send the asking user's token

In the script, the only difference is which token goes in the request header: the customer's instead of the agent's. From demo/demo.py, condensed:

def call(gateway_url, tok, tool, requested_by):
    body = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
            "params": {"name": f"shop___{tool}", "arguments": {"drink": "mango", "requested_by": requested_by}}}  # refund sends order_id instead
    req = urllib.request.Request(gateway_url, data=json.dumps(body).encode(), method="POST",
                                 headers={"Authorization": f"Bearer {tok}"})  # plus content headers

# case 2: the agent's token, asked by the customer
run("guarded gateway, agent credential, asked by customer -> free_smoothie", GUARD, tok["agent-svc"], FREE, "customer", "ALLOWED")
# case 3: the customer's own token
run("guarded, customer's token -> free_smoothie", GUARD, tok["customer"], FREE, "customer", "DENIED")
Enter fullscreen mode Exit fullscreen mode

The token is a JWT, a signed set of claims. The Gateway turns the token and the tool call into the Cedar request the policy judges (authorisation flow). In Cedar, the principal is who is asking. Here is what the policy receives for Carol, who is in two groups. The table is trimmed, and <Carol's user ID> stands in for the long unique ID Cognito gives her:

In the token or the call What Cedar sees
"sub": "<Carol's user ID>" principal AgentCore::OAuthUser::"<Carol's user ID>"
"cognito:groups": ["staff","barista"] principal tag cognito:groups, the string ["staff","barista"]
"username": "carol" principal tag username, the string carol
tool shop___free_smoothie action AgentCore::Action::"shop___free_smoothie"
the Gateway called resource AgentCore::Gateway::"<guarded gateway arn>"
arguments {"drink": "mango", "requested_by": "carol"} context.input, as typed JSON: the caller's values, not proved by the token

Each claim in the token becomes a string tag on the principal, read with principal.getTag(...). So the groups array arrives as one string of JSON text, such as ["staff","barista"]. A null claim gets no tag. The rule for the staff perk follows. Its action name is the target name, shop, then three underscores and the tool name:

permit(
  principal is AgentCore::OAuthUser,
  action == AgentCore::Action::"shop___free_smoothie",
  resource == AgentCore::Gateway::"<guarded gateway arn>"
) when {
  principal.hasTag("cognito:groups") &&
  principal.getTag("cognito:groups") like "*\"staff\"*"
};
Enter fullscreen mode Exit fullscreen mode
Case Result
Customer's token, free smoothie Denied, target never invoked
Alice's token (staff), free smoothie Allowed
Alice's token, refund Denied (no permit)
Customer's token, paid order Allowed

The denial comes back as JSON-RPC error -32002: "Tool Execution Denied: Tool call not allowed due to policy enforcement [No policy applies to the request (denied by default).]". The DynamoDB table of calls shows no new row.

A group name that matches too much

A rule that matches the group name with only a wildcard on each side looks right until you try a look-alike group. The cognito:groups claim reaches Cedar as a string that looks like ["staff","barista"], quotes and brackets included, so like "*staff*" also matches staff-applicant. The repo keeps that wrong rule on the third Gateway:

Token Rule Result
User in staff-applicant like "*staff*" (wrong) Allowed
User with no group like "*staff*" (wrong) Denied
User in staff-applicant like "*\"staff\"*" Denied
User in staff and barista like "*\"staff\"*" Allowed

Match the quoted name. It is exact only while no group name contains a quote mark. Cognito allows quote marks in group names, so control who can create groups. For a truly exact match, compare a single-valued claim with ==, such as one added by a pre token generation trigger (a Cognito Lambda function; for access tokens, on Essentials or Plus). AWS's principal policy examples give the same warning, though the page's own scope example, *insurance:claim*, leaves out the surrounding quote marks.

The limit: a stale claim

Sending the user's own token fixes the agent problem. It does not make the token fresh. These policies know only what the token says about the user.

I briefly put the customer in staff, took a token, then removed them from the group, and called the guarded Gateway with the old token and then a fresh one:

Customer's token Groups in it Result
Old staff Allowed
Fresh none Denied

In the demo an access token lasts an hour (set in config; I did not time the cut-off), and that is the window.

Ways to shrink that window:

  • Short token lifetimes shrink the window. Cognito allows 5 minutes to 1 day, and AWS advises at least an hour with managed login (Cognito's hosted sign-in pages).
  • Revocation may not help: AWS says revoked Cognito tokens are still valid to any library that only checks signature and expiry.
  • A forbid rule on a username, from AWS's principal examples, should work (untested) but needs a policy change for every removal.
  • For anything high risk, check the system of record (here, the user's current groups) at the moment of the action. Do it in the tool itself, as the asker in the re:Post thread did with an open-source library. The tool first needs a trustworthy identity, such as the requested_by tie below (untested). Or use a Gateway request interceptor: a Lambda function the Gateway calls first that can refuse the call. It sees the caller's token only with passRequestHeaders.

An hour of stale access is fine for a free smoothie. On an infrastructure repo, it gives someone removed from the group up to an hour to keep merging.

Before you copy that header

Forwarding the user's token is the demo's shortcut, and riskier than it looks:

  • The token is not issued for one Gateway. A token that works on one of my Gateways works on all three, because they all accept tokens from the same Cognito app client (the registration an application signs in through). The MCP specification says a server must accept only tokens issued for it (2026-07-28 revision).
  • Check who a token was issued for. A token's audience says who it was issued for, and the Gateway's allowedAudience checks it. This demo's API sign-in token has no audience. Cognito can add a Gateway-specific one through resource binding in managed login (Essentials or Plus), or through token exchange. One app client per Gateway, in allowedClients, should also work (untested), at the cost of a sign-in per Gateway.
  • The token does more than call tools. One from Cognito's API sign-in carries aws.cognito.signin.user.admin, which can read and change that user's attributes (as the app client allows) and MFA settings, and delete the account (access token docs). Keep it away from the model and out of logs.
  • No side door. The agent must have no other route to the same tool. My unguarded Gateway accepts the same token.
  • By default the tool does not see the verified user. The Gateway calls it with its own IAM role, so my Lambda has only the unverified requested_by argument. Tie that argument to the token, in the same permit or in a forbid ... unless, because a second permit cannot narrow the first. For example:
  principal.hasTag("username") &&
  context.input.requested_by == principal.getTag("username")
Enter fullscreen mode Exit fullscreen mode

Keep the hasTag guard. Cedar skips a policy whose condition errors, and reading a missing tag is an error, so by Cedar's rules a forbid without the guard lets the call through (not tested on the Gateway). If requested_by is optional, guard it with context.input has requested_by first. Or remove the argument.

  • It does not stop injection. Forwarding the user's token stops a user borrowing the agent's permissions. It does not stop a prompt injection that gets the model to call a tool the user is already allowed to call; a high-impact tool still needs a confirmation step the model cannot complete.

If you build the pull request agent from the opening, its open_pr rule must also check the repository in context.input. A group in your identity provider does not grant push permission on GitHub.

For a real system, look for a token issued for the Gateway receiving it: AgentCore Identity's on-behalf-of token exchange, or Cognito's OAuth token exchange (12 November 2026, Essentials and Plus plans). Check the new token still carries the claims your policy reads.

What I did not test

  • An LLM. The agent is a script.
  • Policy features beyond these rules, such as temporal conditions and Amazon Bedrock Guardrails, or identity carried across a Gateway, Runtime, Gateway chain.
  • Where a real agent gets the user's token.
  • What the Gateway's logs record when the user's token is forwarded: whether the agent appears at all, or only the user.
  • Any production route above: allowedAudience, per-Gateway app clients, token exchange, forbid rules, request interceptors and the requested_by rule. Nor a group name containing a quote mark, or what the Gateway does with a revoked token.
  • A real agent identity. Cognito machine-to-machine tokens carry no cognito:groups claim, so a password user stands in for it.

Others, AWS included, have written up forwarding the user's token to Policy in AgentCore. When I searched in September I found no run comparing the agent's token with the user's under one policy, or showing the stale claim (one AWS Builder article would not open). That is the limit of my search; someone may well have done it.

Run it yourself

The repo is rajmurugan01/agentcore-acts-as-the-user. It deploys everything above into one AWS account in us-east-1, runs the cases and removes it again.

What is in it:

```text showLineNumbers=false
agentcore-acts-as-the-user/
├── cdk/
│ ├── bin/app.ts # the CDK app
│ └── lib/stack.ts # Cognito, Gateways, policies, Lambda, DynamoDB
├── demo/
│ ├── demo.py # the scripted agent and the twelve cases
│ └── test_demo.py # nine offline tests, no AWS
├── lambda/shop.py # the mock shop: records each call
├── docs/transcript.txt # an earlier run, 12 of 12
├── Makefile # install, test, deploy, demo, destroy
└── README.md




`cdk/lib/stack.ts` holds the three Cedar rules; `demo/demo.py` decides which token each call sends. An earlier version, built around the pull request case from the opening, is tagged [`pull-request-demo`](https://github.com/rajmurugan01/agentcore-acts-as-the-user/tree/pull-request-demo).

### Prerequisites

Versions from the run on 3 December 2026:

- An AWS account with CDK bootstrapped in us-east-1, and permission to create Cognito, Lambda, DynamoDB, IAM and AgentCore resources
- Node.js 22.22.2, AWS CDK CLI 2.1143.0 and aws-cdk-lib 2.271.0
- Python 3.14.6 with boto3 1.44.17
- AWS CLI 2.36.6
- Credentials for that account in your shell, with `AWS_REGION` unset or `us-east-1`

### Steps

The screenshots are from a run from a fresh clone on 3 December 2026.

Clone the repo and work from its folder:



```bash
git clone https://github.com/rajmurugan01/agentcore-acts-as-the-user.git
cd agentcore-acts-as-the-user
Enter fullscreen mode Exit fullscreen mode

1. Test offline. The demo's own PASS and FAIL logic, with no AWS calls:

make test
Enter fullscreen mode Exit fullscreen mode

Terminal output of make test: nine unit tests of the demo's verdict logic, each reported ok

Nine tests pass, including the ones that make a broken call fail instead of passing as a denial.

2. Deploy. Creates a Python virtual environment for boto3, then the stack:

make deploy
Enter fullscreen mode Exit fullscreen mode

Terminal output of make deploy, filtered to its result lines: AgentcoreActsAsUser deployed, deployment time and total time

130 seconds in total, 109 of them deploying. The output is filtered to these lines because the full log prints the account ID.

3. Run the twelve cases. Writes docs/transcript.txt:

make demo
Enter fullscreen mode Exit fullscreen mode

Terminal output of make demo, filtered to its PASS lines: twelve cases each marked PASS, ending with 12/12 cases behaved as expected

12 of 12 cases behaved as expected. The screen shows the PASS lines; the repo's transcript has every line from an earlier run of the same twelve cases.

4. Clean up. The demo users and password are throwaway and go with the stack. Each deploy leaves the Lambda function's log group behind; delete it by hand if you want it gone:

make destroy
Enter fullscreen mode Exit fullscreen mode

Terminal output of make destroy, filtered: the AgentcoreActsAsUser stack destroying and then destroyed

The stack destroyed. I checked that no stack resource remained.

What it produced

The run deployed the stack drawn under The setup. This is what each case did against it:

Four of twelve cases let the wrong caller in. Rule: only staff get the free smoothie. The agent's own token: the open Gateway and the staff-only Gateway both allowed the free smoothie, a bug shown on purpose. The asking user's token: the customer's free smoothie denied, Alice's free smoothie allowed, Alice's refund denied, the customer's paid order allowed. Group names: staff-applicant with the quoted match denied, Carol in staff and barista allowed, staff-applicant with the bare wildcard allowed, a bug shown on purpose, no group on the bare rule denied. A stale claim: the customer's old token allowed after removal, a limit shown on purpose, and a fresh token denied.

Seven allowed, five denied. Four of the seven allowed results are the failures this post is about: the agent's token with no policy and with the staff-only policy, the bare wildcard, and the stale token.

Trace: the shop's table of calls holds one row for each of the seven allowed calls and none for the five denied, so the record matches the verdicts. The table shows what the tool did. It cannot show who asked: the tool saw only the agent's role and the unverified requested_by argument. I did not check what the Gateway's own logs record for the forwarded token.

Troubleshooting

  • Access denied while calling GetPolicyEngine when CloudFormation creates the guarded Gateway. Cause: with CDK the role's permissions are a separate IAM policy resource, and in September CloudFormation created the Gateway before it. Fix: the role needs GetPolicyEngine, AuthorizeAction and PartiallyAuthorizeActions (permissions docs), and the Gateway needs an explicit dependency on that policy. The repo does both; keep the dependency if you adapt the stack. It scopes the actions to any policy engine in the account, so in production name your one engine's ARN.
  • error: externally-managed-environment from make deploy. Cause: your Python refuses a system-wide pip install (PEP 668). Fix: the Makefile now installs boto3 into .venv. If you cloned before 1 December, pull.
  • Insufficient permissions to call gateway when you create a policy. Cause: policy authors need InvokeGateway on the Gateway the policy names. Fix: grant it (permissions docs). I deployed as admin and never hit this.

Cost

A full run makes twelve tool calls. At list prices, $5 per million Gateway calls and $25 per million policy decisions (AgentCore pricing), the AgentCore side is well under a cent. That is an estimate from list prices; I did not measure the bill. It leaves out the small Cognito, DynamoDB and Lambda charges.

What I do now

  • On every tool call, my code sends a token for the asking user. For production that means one issued for that Gateway, which I have not tested yet.
  • For a risky action such as a refund or a merge, the tool also looks up the user's current groups at that moment, because even their own token can be up to an hour out of date. The demo does not build this check.

For the actions your agents take, where do you draw the line between "a token up to an hour stale is fine" and "the tool must ask the system of record every time"?

Part 7 of **Production AI, Honestly, a postscript to the series that closed with Part 6, Your LLM security diagram defends the wrong layer.

Top comments (0)