Scope AWS AI Agent Access With STS and Guardrails
Authorize document reads in the worker using authenticated tenant context, then use a per-call STS session to scope S3 credentials to the requested object. Bedrock Guardrails screens retrieved text after the read; it does not authorize S3 requests.

Your AI agent is asked to summarize tenant A’s document, but its S3 credentials can also read tenant B’s files. A prompt filter can’t fix that permission. Make the tool worker authorize the request from authenticated tenant context, then give its S3 client credentials scoped to the requested object.
Choose where to enforce access
The model proposes a document ID. The worker checks the request and builds the key from a trusted tenant ID; S3 enforces the resulting session scope. Only after the read does Bedrock Guardrails evaluate the retrieved text. It does not authorize tools.
| Control | Use it when | Tradeoff |
|---|---|---|
| Fixed read-only role | A worker serves one tenant or one shared, approved dataset | Simpler; requests share the same IAM scope |
| Per-call STS session | A shared worker needs different object scopes | Adds an STS call and another failure path |
| Bedrock Guardrails | Retrieved text needs content screening | Adds a separate check; cannot compensate for broad IAM |
1. Set up staging roles and fixtures

Use an isolated bucket with synthetic UTF-8 files at documents/tenant-a/sample.txt and documents/tenant-b/sample.txt. Give the Lambda broker role sts:AssumeRole on the staging reader role and bedrock:ApplyGuardrail on your guardrail, but no S3 data access. Trust only the broker role in the reader role’s trust policy. Give the reader s3:GetObject on both fixture prefixes so you can test the same role with and without a session policy; grant no writes.
Lambda execution roles already use temporary credentials. The assumed session lasts until its configured expiration, not until the tool returns. The role’s identity permissions and the session policy intersect, and explicit denies still win. Review bucket and access-point policies too: a same-account resource policy granting access directly to a role session can bypass an implicit session-policy deny.
2. Wire the worker to the assumed credentials

Set DOC_BUCKET, READER_ROLE_ARN, GUARDRAIL_ID, and GUARDRAIL_VERSION to your staging values. Call fetch only after your application authenticates the caller and authorizes document reads for the tenant. Pass tenant from that trusted context and run_id as a server-generated UUID hex string per call; neither comes from the model. This example assumes all documents within the tenant are readable by that caller; enforce any narrower document ACL before calling STS.
import json
import logging
import os
import re
from contextlib import closing
import boto3
BUCKET = os.environ['DOC_BUCKET']
ROLE = os.environ['READER_ROLE_ARN']
LIMIT = 8192
sts = boto3.client('sts')
bedrock = boto3.client('bedrock-runtime')
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
def s3_client(session):
c = session['Credentials']
return boto3.client('s3', aws_access_key_id=c['AccessKeyId'],
aws_secret_access_key=c['SecretAccessKey'],
aws_session_token=c['SessionToken'])
def scoped_client(key, run_id):
policy = {'Version': '2012-10-17', 'Statement': [
{'Effect': 'Allow', 'Action': 's3:GetObject',
'Resource': f'arn:aws:s3:::{BUCKET}/{key}'},
{'Sid': 'DenyPutAndDeleteObject', 'Effect': 'Deny',
'Action': ['s3:PutObject', 's3:DeleteObject'], 'Resource': '*'}
]}
return s3_client(sts.assume_role(
RoleArn=ROLE, RoleSessionName=run_id, DurationSeconds=900,
Policy=json.dumps(policy)))
def fetch(payload, *, tenant, run_id):
if type(payload) is not dict or set(payload) != {'document_id'}:
raise ValueError('Expected only document_id')
doc = payload['document_id']
for value in (tenant, doc):
if type(value) is not str or not re.fullmatch(r'[a-z0-9-]{1,64}', value):
raise ValueError('Invalid identifier')
key = f'documents/{tenant}/{doc}.txt'
log.info('s3_read_attempt execution=%s', run_id)
obj = scoped_client(key, run_id).get_object(Bucket=BUCKET, Key=key)
with closing(obj['Body']) as body:
if obj['ContentLength'] > LIMIT:
raise ValueError('Document too large')
raw = body.read(LIMIT + 1)
if len(raw) > LIMIT:
raise ValueError('Document too large')
result = {'text': raw.decode('utf-8')}
if set(result) != {'text'} or type(result['text']) is not str:
raise ValueError('Invalid tool output')
text = result['text']
if re.search(r'ignore\s+previous\s+(directives|instructions)', text, re.I):
log.warning('text_heuristic_match execution=%s', run_id)
raise ValueError('Retrieved text rejected')
verdict = bedrock.apply_guardrail(
guardrailIdentifier=os.environ['GUARDRAIL_ID'],
guardrailVersion=os.environ['GUARDRAIL_VERSION'],
source='INPUT', content=[{'text': {'text': text}}])
if verdict['action'] != 'NONE':
log.warning('guardrail_intervened execution=%s', run_id)
raise ValueError('Retrieved text withheld')
return resultThe cap is in bytes, not tokens. The regex catches phrases like “Ignore previous directives” but misses paraphrases; treat it as a limited heuristic, not a sanitizer. Return a generic tool error for rejected content or service failures. Don’t retry with broader credentials.
3. Prove the policy change and verify the audit trail

Illustrative scenario. With the fixtures above, run these probes under the staging broker identity. They bypass the tool’s input checks to test what S3 itself permits. Never ship the unscoped probe in the worker.
from uuid import uuid4
from botocore.exceptions import ClientError
def denied(call, **args):
try:
call(**args)
except ClientError as exc:
if exc.response['Error']['Code'] == 'AccessDenied':
return
raise
raise AssertionError('Expected AccessDenied')
a = 'documents/tenant-a/sample.txt'
b = 'documents/tenant-b/sample.txt'
run_id = uuid4().hex
print('staging execution:', run_id)
baseline = s3_client(sts.assume_role(RoleArn=ROLE, RoleSessionName=uuid4().hex))
baseline.get_object(Bucket=BUCKET, Key=b)['Body'].close()
scoped = scoped_client(a, run_id)
scoped.get_object(Bucket=BUCKET, Key=a)['Body'].close()
denied(scoped.get_object, Bucket=BUCKET, Key=b)
denied(scoped.put_object, Bucket=BUCKET,
Key=f'documents/tenant-a/probe-{run_id}.txt', Body=b'test')The expected change is a successful tenant B read under the baseline and AccessDenied under the scoped session. For cost planning, 2,000 successful reads with no retries, session reuse, or filter blocks add 2,000 STS calls and 2,000 guardrail evaluations over a fixed-role worker with no screening. Measure content volume and check your bill rather than treating call counts as a quote.
Before probing, enable read and write CloudTrail S3 data events for the staging bucket’s object resources. Find the allowed read and look for denied probes using the role session name and trusted execution ID; keep application outcome logs rather than assuming every event includes session tags. For SQL writes, use database audit logs and database grants: rds-db:connect controls IAM database authentication, not SQL privileges.
4. Roll back without widening access
If STS or screening fails, pause the tool or switch to a pretested fixed read-only role dedicated to that tenant. Don’t fall back to the shared reader role without a session policy. For domain-based egress controls, route outbound traffic through an enforcing proxy or firewall and block bypass paths; security groups and VPC endpoints alone do not provide a general domain allowlist.
Release checklist: Confirm valid reads work, cross-tenant reads and writes are denied, oversized objects and blocked text stay out of model context, and the read can be traced in CloudTrail.
Related resources
Frequently Asked Questions
Do I need STS for every read?
No. A fixed read-only role can be enough when the worker serves one tenant or one approved shared dataset.
Does Bedrock Guardrails stop unauthorized S3 requests?
No. The worker authorizes the request, S3 enforces the credential scope, and Bedrock Guardrails screens text after retrieval.
How do I verify that the session policy blocks cross-tenant reads?
Try reading the same cross-tenant staging object with and without the session policy. The baseline read should succeed, and the scoped read should return AccessDenied.
What should the worker do if STS or screening fails?
Pause the tool or switch to a pretested fixed read-only role dedicated to that tenant. Do not fall back to the shared reader role without a session policy.
Get the Weekly SMB AI & SaaS Brief
Practical software benchmarks, prompt templates, and ROI breakdowns delivered every Tuesday. No fluff, unsubscribe anytime.