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) and 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 worked. 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 the asking user's token, not the agent's. A token here means an ID badge: the policy reads what the badge says, never who is holding it.
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 the tool's record of calls stayed empty.
- The policy knows only what the token says. 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 the agent has no way to create one.
- Match group names on the quoted element,
"staff"with its quotes. A bare*staff*let a user instaff-applicantthrough. This holds only while no group name contains a quote mark.
The test: Make the same tool call twice, once with the agent's credential and once as a user who should be refused. If both are allowed, the policy is not seeing the user.
This is the managed-service version of The LLM is not a security boundary, and where it stops.
The setup
An AgentCore Gateway is the endpoint an agent calls to use tools, here over MCP (the Model Context Protocol). Policy in AgentCore attaches a policy engine, a set of rules in the Cedar policy language, to a Gateway; "the policy" means that. 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 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. Cognito 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.
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 second row is the point. 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, trimmed:
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). 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 |
The principal is Cedar's name for who is asking. The token's claims become string tags on it, read with principal.getTag(...), so the groups array arrives as its JSON text (a null claim gets no tag). The rule for the staff perk, where shop___free_smoothie is the target name, 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 ledger shows no new row. The check happened before your code.
A group name that matches too much
My first policy matched the group name with only a wildcard on each side. It worked on the first run, which is the dangerous kind of working. 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 element. That is exact only while no group name contains a quote mark, which Cognito allows, 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. AWS's principal policy examples give the same warning, though the page's own scope example, *insurance:claim*, does not match the delimiters.
The limit: a stale claim
These policies know what the token says. Nothing else.
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 |
The old token still carried the staff claim. In the demo an access token lasts an hour, and that is the window.
Short token lifetimes narrow it. Revocation may not: 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, works in the Gateway but needs a policy change for every removal. For anything high risk, check the system of record at the moment of the action: 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, which can refuse the call (it sees the caller's token only with passRequestHeaders). An hour of stale entitlement may be fine for a free smoothie. For "merge to the infrastructure repo" it is not.
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. All three of mine accept tokens from the same Cognito app client, while the MCP specification says a server must accept only tokens issued for it (2026-07-28 revision). The Gateway's
allowedAudiencechecks this, but Cognito adds an audience to an access token only when the app requests a resource binding through Cognito's OAuth sign-in endpoints, not in this demo's API sign-in. One app client per Gateway, inallowedClients, also works, 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 (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.
-
The tool never sees the verified user. The Gateway calls it with its own IAM role, so my Lambda gets only the
requested_byargument. Tie that argument to the token inside the samepermitor aforbid ... unless(permits never narrow each other), for exampleprincipal.hasTag("username") && context.input.requested_by == principal.getTag("username"), withcontext.input has requested_byif it is optional. Or remove the argument. -
Policy authors need
InvokeGatewayon the Gateway a policy names (permissions docs). I deployed as an admin and never hit this.
For the pull request agent, an open_pr rule must also check the repository in context.input, and a group in your identity provider is not 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, because enforcement must not depend on the model.
- 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. I forwarded a raw Cognito access token.
- 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 group 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). Read that as "I could not find it", not "nobody has".
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.
The repo on 30 November: the CDK stack in cdk, the scripted agent in demo, the mock shop in lambda.
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_REGIONunset orus-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:
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. Two Lambda log groups are left behind; delete them by hand if you want them 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. Three chips carry the lessons: the agent's token allowed, the customer's own token denied, and the old token allowed after removal. A fourth, staff-applicant under the bare wildcard, is why the rule matches the quoted name.
Troubleshooting
-
Access denied while calling GetPolicyEnginewhen CloudFormation creates the guarded Gateway: with CDK the role's permissions are a separate IAM policy resource, and in September CloudFormation created the Gateway before it. The role needsGetPolicyEngine,AuthorizeActionandPartiallyAuthorizeActions(permissions docs). The repo gives the Gateway an explicit dependency on that policy; keep it if you adapt the stack. -
error: externally-managed-environmentfrommake deploy: your Python refuses a system-widepip install(PEP 668). The Makefile now installs boto3 into.venv; pull the latest repo.
On 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, not a measured bill, and leaves out the small Cognito, DynamoDB and Lambda charges.
An earlier pull-request version of the demo is tagged pull-request-demo.
What I do now
Beyond the rules and the test above:
- I keep one test user in a look-alike group such as
staff-applicant, next to the quoted-element match. - I set access tokens to the shortest lifetime the app tolerates, and make high-risk tools check the system of record before acting.
The question I would like to hear answers to: for the actions your agents take, where is the line between "a token that is 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)