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, and 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.
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).
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 instaff-applicantthrough. The quote-mark exception is below.
The test: Signed in as a refused look-alike such as staff-applicant, 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 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 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")
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. For Carol, a demo user in staff and barista, trimmed:
| 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\"*"
};
| 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
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.
- Revocation may not help: AWS says revoked Cognito tokens are still valid to any library that only checks signature and expiry.
-
A
forbidrule 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, or in 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 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
allowedAudiencechecks 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, inallowedClients, 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_byargument. Tie that argument to the token, in the samepermitor in aforbid ... unless, because a secondpermitcannot narrow the first. For example:
principal.hasTag("username") &&
context.input.requested_by == principal.getTag("username")
Keep the hasTag guard. Cedar skips a policy whose condition errors, and reading a missing tag is an error, so a forbid without the guard lets the call through. 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,forbidrules, request interceptors and therequested_byrule. 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:groupsclaim, 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 # the 1 December 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 1 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.15
- 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 1 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
1. Test offline. The demo's own PASS and FAIL logic, with no AWS calls:
make test
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
140 seconds in total, 116 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
12 of 12 cases behaved as expected. The repo's transcript is from this run.
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
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:
Seven allowed, five denied.
Troubleshooting
-
Access denied while calling GetPolicyEnginewhen 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 needsGetPolicyEngine,AuthorizeActionandPartiallyAuthorizeActions(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-environmentfrommake deploy. Cause: your Python refuses a system-widepip install(PEP 668). Fix: the Makefile now installs boto3 into.venv. If you cloned before 1 December, pull. -
Insufficient permissions to call gatewaywhen you create a policy. Cause: policy authors needInvokeGatewayon 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
Beyond the rules and the test above, I make high-risk tools check the system of record before acting.
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)