One AWS Session per Tenant: How to Isolate S3 Files by Organization or by Use
Most multi-tenant apps keep every customer's files in one S3 bucket, and read them with one IAM credential. That credential can read every file of every customer. The only thing between two customers is the code that bui
Most multi-tenant apps keep every customer's files in one S3 bucket, and read them with one IAM credential. That credential can read every file of every customer. The only thing between two customers is the code that builds the key.
That code is usually correct. But "usually correct" is a weak guarantee for a contract, a medical exam or a birth certificate. A bug that puts the wrong id in a key is not an error. It is a leak, and it returns 200 OK.
A leak of this kind has no attacker. Your own API hands the file to a paying customer, over TLS, with a valid session. No alarm fires. You learn about it when the other customer writes to you, or when a regulator does.
In this article I'll show a pattern that moves the isolation into AWS itself: every S3 call is signed with a session that belongs to one tenant, and AWS refuses a key of another tenant, whatever key your code builds. The tenant can be an organization, a user, a workspace, or both an organization and a user. I'll also show the second lock, in the application, that decides which tenant a request can name.
How to read this article: the pattern is generic, and every section starts with it. After each pattern, an "In my case" note shows how I applied it in production, with the real numbers. The policies are in JSON, so you can use them from Terraform, CDK, CloudFormation or the console.
The case: my example is Tranly, a document translation API that gives the file back in the layout of the original. Customers upload contracts, birth certificates and school transcripts, and download the translation. The gateway is Node.js (Fastify, MongoDB). The tenant is the organization. The files moved to S3 on November 30, 2026, with this pattern.
The Result
| Lock | Where | What it stops |
|---|---|---|
| One AWS session per tenant, with a session tag | IAM | A bug that builds the key of another tenant |
A policy that reads the tag (${aws:PrincipalTag/...}) |
IAM | A session reaching outside its prefix |
| A key check before the call | Your code | The same bug, before AWS sees it |
| A bucket policy that denies every other principal | S3 | A person, a CI user or another service reading an object |
| The tenant inside the database query | Your code | A request that names a file of another tenant |
The first four locks protect the bucket from your own code. The last one protects your code from the request. You need both. AWS can only refuse a session of the wrong tenant. It cannot know which tenant the request should have used.
Why a Cross-Tenant Leak Is the Worst Kind
Most security work assumes an outsider: a stolen password, an open port, a public bucket. A cross-tenant leak needs none of that. Three properties make it worse than it looks:
- The receiver is a third party with a legitimate account. You cannot revoke their access, because their access is correct. The file is already on their disk.
- Encryption does not help. The bucket encrypts at rest, and TLS encrypts in transit. Your API decrypts the file and sends it to the wrong customer, because it believes the request.
- A bug in a shared code path does not leak one file. It leaks every file that the path serves, for every request, until somebody notices.
The same risk exists between systems inside one company. When billing exports, analytics jobs and customer documents share one bucket and one credential, a data job can read a passport scan. The pattern in this article works for that case too: the tag names a system instead of a customer.
What the Law Says About It
If the files hold personal data, a leak to another customer is a security incident under every major privacy law. The deadlines are short, and the fines are calculated on revenue:
| Law | Where | Notify | Maximum fine |
|---|---|---|---|
| LGPD | Brazil | The ANPD and the data subjects, in 3 business days, when the incident can cause relevant risk (ResoluΓ§Γ£o CD/ANPD nΒΊ 15/2024) | 2% of the revenue in Brazil, up to R$ 50 million per infraction (Art. 52), plus the publication of the infraction and the suspension of the database |
| GDPR | European Union | The supervisory authority, in 72 hours (Art. 33) | β¬10 million or 2% of worldwide annual turnover for a failure of security (Art. 32 and 83(4)). β¬20 million or 4% for other infringements (Art. 83(5)) |
| HIPAA | United States, health data | The individuals, in 60 days at most. HHS too, and the media when 500 or more residents of a state are affected | More than $2 million a year for each provision violated, adjusted for inflation every year |
Three details matter for a SaaS:
- You are probably the processor, and the law still reaches you. Under the LGPD and the GDPR, a processor answers for its own security failures. Under HIPAA, a SaaS that stores health data for a hospital or a clinic is a business associate, and it is directly liable.
- Your customers' contracts add their own deadlines. A data processing agreement usually asks you to notify the customer in hours, and lets the customer terminate after a breach.
- "We did not know" is a weak defense. Every one of these laws asks for security measures that are appropriate to the risk. A single credential that reads every customer's files is hard to defend as appropriate for identity documents or health records.
I am not a lawyer, and this is not legal advice. But the numbers are enough to make the point: the cost of a cross-tenant leak is not the file. It is the fine, the notifications, the contracts and the customers who leave.
The Problem With One Credential
A typical setup looks like this:
const s3 = new S3Client({ region }); // one credential for the whole app
async function readResult(job: Job) {
const key = `tenants/${job.tenantId}/jobs/${job.id}/result`;
return s3.send(new GetObjectCommand({ Bucket: BUCKET, Key: key }));
}
The IAM policy of that credential allows s3:GetObject on arn:aws:s3:::bucket/*. So the isolation depends on three things being right every time:
- the
jobobject came from a query scoped to the caller; -
tenantIdis the field you think it is; - nobody writes a second function that builds the key in another way.
AWS cannot help, because from its point of view every read is allowed.
The Pattern: One Session per Tenant
The idea has three parts:
- Your app signs in with an identity that can do one thing: assume one role.
- Each time your app assumes the role, it attaches a session tag with the tenant id.
- The role's policy uses that tag as a variable in the resource ARN. A session reaches only the prefix of its own tenant.
You do not create one role per tenant. You create one role, and many sessions of it exist at the same time, one per active tenant.
Step 1: Choose the Tenant and the Key Layout
The tenant is the unit that must never see another unit's files. Pick it from the access rules of your product, not from your database schema:
| Product | Tenant tag | Key layout |
|---|---|---|
| B2B SaaS, files belong to the team | org |
orgs/<org>/... |
| Consumer app, files belong to a person | user |
users/<user>/... |
| Team files and private files |
org and user
|
orgs/<org>/shared/... and orgs/<org>/users/<user>/...
|
Two rules for the key:
- The tenant id is the first segment after a fixed prefix. The policy matches a prefix, so the tenant must come first.
-
The key holds ids only, never a filename. The S3 access log and CloudTrail record every key. A filename like
divorce-agreement-maria.pdfin a log is a leak of its own.
In my case: the tenant is the organization, because a team shares its documents. The tag is org, and the keys are orgs/<org>/jobs/<job>/source and orgs/<org>/jobs/<job>/result, and uploads/<org>/ holds the files that wait for a job.
Step 2: The Trust Policy Decides Which Sessions Can Exist
The trust policy of the role accepts only a session that carries exactly one tag, tenant, with a value:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "OneTenantPerSession",
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::<account>:user/app" },
"Action": ["sts:AssumeRole", "sts:TagSession"],
"Condition": {
"StringLike": { "aws:RequestTag/tenant": "?*" },
"ForAllValues:StringEquals": { "aws:TagKeys": ["tenant"] },
"Null": {
"aws:TagKeys": "false",
"sts:TransitiveTagKeys": "true"
}
}
}
]
}
Each condition closes one door:
-
"?*"refuses an empty value. An absent tag gives no match, so it is refused too. -
ForAllValues:StringEqualsrefuses a second tag, likeadmin: true. -
Nullonaws:TagKeysrefuses a request with no tag keys at all. Without it, an empty set passes aForAllValuestest. -
Nullonsts:TransitiveTagKeysrefuses transitive tags, because the app never chains this role.
STS also refuses * and ? in a tag value, so a tag cannot turn into a wildcard inside the policy.
For the "org and user" layout, allow both keys (["org", "user"]) and require both values.
Step 3: The Permission Policy Reads the Tag
AWS replaces ${aws:PrincipalTag/tenant} with the tag of the session on every call:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ObjectsOfTheSessionTenant",
"Effect": "Allow",
"Action": [
"s3:GetObject", "s3:GetObjectVersion", "s3:PutObject",
"s3:DeleteObject", "s3:DeleteObjectVersion",
"s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"
],
"Resource": "arn:aws:s3:::<bucket>/tenants/${aws:PrincipalTag/tenant}/*"
},
{
"Sid": "ListOnlyTheTenantPrefix",
"Effect": "Allow",
"Action": ["s3:ListBucket", "s3:ListBucketVersions"],
"Resource": "arn:aws:s3:::<bucket>",
"Condition": {
"StringLike": { "s3:prefix": "tenants/${aws:PrincipalTag/tenant}/*" }
}
}
]
}
For users inside organizations, the resource becomes:
arn:aws:s3:::<bucket>/orgs/${aws:PrincipalTag/org}/users/${aws:PrincipalTag/user}/*
arn:aws:s3:::<bucket>/orgs/${aws:PrincipalTag/org}/shared/*
In Terraform, write the variable as $${aws:PrincipalTag/tenant}, because HCL reads ${...} as its own interpolation.
Step 4: Assume the Role With the Tag
In Node.js:
import { AssumeRoleCommand, STSClient } from '@aws-sdk/client-sts';
const output = await sts.send(
new AssumeRoleCommand({
RoleArn: roleArn,
RoleSessionName: `tenant-${tenantId}`, // CloudTrail shows it
DurationSeconds: 3600,
Tags: [{ Key: 'tenant', Value: tenantId }],
}),
);
In Python, it is the same call:
creds = sts.assume_role(
RoleArn=role_arn,
RoleSessionName=f"tenant-{tenant_id}",
DurationSeconds=3600,
Tags=[{"Key": "tenant", "Value": tenant_id}],
)["Credentials"]
s3 = boto3.client(
"s3",
aws_access_key_id=creds["AccessKeyId"],
aws_secret_access_key=creds["SecretAccessKey"],
aws_session_token=creds["SessionToken"],
)
The session name has a limit of 64 characters, and a UUID with a short prefix fits. The tag value has a limit of 256 characters.
Where the app runs changes the first identity, not the pattern. Outside AWS, the app signs in as an IAM user whose only permission is sts:AssumeRole and sts:TagSession on this role. On ECS or Lambda, the task role or the execution role gets that permission instead, and you have no long-lived key. One difference: a role that assumes another role is role chaining, and AWS limits a chained session to one hour.
In my case: the API runs on a platform outside AWS, so it signs in as an IAM user. The key of that user can do nothing except assume the document role. If the key leaks, the thief still needs a tenant tag for every read, and each session reaches one organization.
Step 5: Keep the Sessions in a Cache
An AssumeRole per S3 call is slow and wasteful. Keep one client per tenant, and renew its credential before it ends:
export function tenantCredentials({ sts, roleArn, tenantId, now = Date.now }) {
let current: SessionCredentials | null = null;
let pending: Promise<SessionCredentials> | null = null;
return async () => {
// Renew 10 minutes before the end, so no call gets a credential that expires on the way.
if (current !== null && current.expiration.getTime() - now() > REFRESH_MARGIN_MS) {
return current;
}
// Two calls at the same instant share one AssumeRole.
pending ??= assume({ sts, roleArn, tenantId })
.then((fresh) => (current = fresh))
.finally(() => (pending = null));
return pending;
};
}
// The AWS SDK v3 accepts a function as `credentials` and calls it before each request.
const client = new S3Client({ region, credentials: tenantCredentials({ sts, roleArn, tenantId }) });
Put the clients in a map keyed by tenant, with a maximum size. When the map is full, drop the client used longest ago and call client.destroy() to release its sockets.
In my case: the cache holds 1,000 organizations. An active organization calls STS about once every 50 minutes. AssumeRole is free, and the STS quota is 600 requests a second for the account and the Region, shared with other STS calls.
Step 6: Check the Key in Your Code Too
AWS will refuse a wrong key. Refuse it first, in the one function that gives out clients:
export function keyBelongsTo({ tenantId, key }: { tenantId: string; key: string }): boolean {
const prefix = `tenants/${tenantId}/`;
return key.startsWith(prefix) && key.length > prefix.length;
}
function clientOf({ tenantId, key }: { tenantId: string; key: string }): S3Client {
if (!keyBelongsTo({ tenantId, key })) throw new AccessDeniedError();
return sessions.clientFor(tenantId);
}
Now a wrong key fails twice: in your code and in AWS. The check in code has a second use. Your in-memory store for tests can run the same check, so a unit test sees the refusal without an AWS account.
Also validate the tenant id before you put it in a key: no /, no .., no empty string. A tenant id of ../other must never become a prefix.
Step 7: Deny Every Other Principal
The role policy limits what the app can do. The bucket policy limits who else can touch an object. For a role session, aws:PrincipalArn is the ARN of the role, so one statement covers every tenant session:
{
"Sid": "OnlyTheAppRoleTouchesAnObject",
"Effect": "Deny",
"Principal": "*",
"Action": [
"s3:GetObject*", "s3:PutObject*", "s3:DeleteObject*",
"s3:ReplicateObject", "s3:RestoreObject"
],
"Resource": "arn:aws:s3:::<bucket>/*",
"Condition": {
"ArnNotEquals": { "aws:PrincipalArn": "arn:aws:iam::<account>:role/app-documents" }
}
}
An explicit deny wins over any allow. An admin of the account gets 403 on an object, and so does the CI user that applies your infrastructure. The lifecycle rules of the bucket still run, because a bucket policy does not reach S3's own lifecycle.
A person with full access can still remove this statement. That action is in CloudTrail. To empty the bucket by hand, remove the statement first.
In my case: the bucket policy also denies any request without TLS. The CI user that applies Terraform has its own explicit deny on every object.
Step 8: Prove That AWS Refuses
A mock that imitates the refusal proves your mock. Only a real bucket proves the policy. Write a small contract test that runs against a development account, never against production, and never in the normal test command:
it('AWS refuses the session of one tenant on the prefix of another', async () => {
const keyOfB = `tenants/${TENANT_B}/files/${randomUUID()}`;
await store.put({ tenantId: TENANT_B, key: keyOfB, body: Buffer.from('the file of B') });
// A raw client of A: no key check of ours in front of AWS.
const clientOfA = new S3Client({ region, credentials: tenantCredentials({ sts, roleArn, tenantId: TENANT_A }) });
await expect(clientOfA.send(new GetObjectCommand({ Bucket, Key: keyOfB })))
.rejects.toMatchObject({ name: 'AccessDenied' });
await expect(clientOfA.send(new PutObjectCommand({ Bucket, Key: keyOfB, Body: 'overwrite' })))
.rejects.toMatchObject({ name: 'AccessDenied' });
await expect(clientOfA.send(new ListObjectVersionsCommand({ Bucket, Prefix: 'tenants/' })))
.rejects.toMatchObject({ name: 'AccessDenied' });
});
it('AWS refuses a session without the tag, with a second tag, or with an empty tag', async () => {
for (const Tags of [undefined, [{ Key: 'tenant', Value: A }, { Key: 'admin', Value: 'true' }], [{ Key: 'tenant', Value: '' }]]) {
await expect(sts.send(new AssumeRoleCommand({ RoleArn, RoleSessionName: 'probe', Tags })))
.rejects.toMatchObject({ name: 'AccessDenied' });
}
});
Use random tenant ids, and delete every version you wrote, so the test leaves nothing behind.
In my case: the contract test proves these refusals against the development account. It never runs against production.
Serving the File: Proxy or Presigned URL
A customer still has to download the file. You have two options, and the pattern works with both.
Presigned URL. Sign the URL with the client of the tenant. A URL for another tenant's key fails at AWS when someone opens it. A URL signed with temporary credentials also stops working when the session ends, even if its own expiry is later. So a session of one hour gives a URL of one hour at most.
A link through your API. Your API serves GET /files/<token> and streams the object. This adds a hop, but you get a place to count downloads, refuse a suspended account, and keep the bucket name out of every answer.
In my case: I chose the proxy. The token is signed with HMAC-SHA256 and carries the organization, the job, the side (source or result) and the end time. A link works for 15 minutes, and the next read of the job gives a new one. The route checks, in order: the signature, the job (read with the organization from the token), the suspension, and a download counter (download 21 of the day gets 429). Then it streams the object through the session of that organization. Every refused token gets 404, never 401, so a probe learns nothing about which ids exist.
The Second Lock: The Tenant Inside the Query
The S3 locks answer one question: "can this session read this key?" They cannot answer "should this request use this session?" That decision lives in your code, in the database read that finds the file's pointer.
The weak shape reads by id and compares afterwards:
const job = await jobs.findById(jobId);
if (!job || job.organizationId !== organizationId) throw new NotFoundError();
This is correct. But each new caller must remember the comparison, and a test with one tenant never notices when somebody forgets it. The strong shape puts the tenant in the query:
async findForOrganization({ jobId, organizationId }: FindJobParams) {
// A query that cannot match another tenant's row is the isolation.
return this.col.findOne({ _id: jobId, organizationId });
}
Now there is no comparison to forget. A row of another tenant does not exist for this query. It answers null, exactly like an id that nobody holds. Make organizationId a required field of a named params type, so TypeScript refuses a call without it.
Some code paths have no request to scope to: a job runner, a queue worker, a webhook delivery. Keep an unscoped read for them, and give it a name that a reviewer cannot miss: findByIdAcrossTenants, not findById.
Then add a test that reads your src/ folder and counts the call sites:
const UNSCOPED_READ = 'findByIdAcrossTenants(';
const ALLOWED = [
'repositories/index.ts', // declares it
'repositories/mongo/repositories.ts', // implements it
'modules/translation/jobs.service.ts',
'modules/translation/webhooks/delivery.ts',
];
it('is spelled in exactly the files that may spell it', () => {
const spelled = sourceFiles.filter((f) => f.contents.includes(UNSCOPED_READ)).map((f) => f.path);
expect(spelled.sort()).toEqual([...ALLOWED].sort());
});
it('is never how a route reaches a row', () => {
const offenders = sourceFiles
.filter((f) => f.path.endsWith('.routes.ts'))
.filter((f) => f.contents.includes(UNSCOPED_READ) || f.contents.includes('getRepositories().jobs'));
expect(offenders).toEqual([]);
});
The list works in both directions. A new caller fails the test. A caller that stopped needing the read fails it too. A new exception is still possible, but now it is a line in a diff that a reviewer reads.
Finally, write the tests from the side that fails. Ask for a real row of tenant B with:
- the API key of tenant A;
- a person who belongs to both tenants, acting in A;
- a token whose membership was removed after the token was signed.
Each one must get the same 404 as an id that does not exist.
In my case: I measured the tests instead of trusting them. When I removed the organization from the query, 8 tests turned red, 3 of them HTTP crossings. When I put the old findById shape back, 2 of the 4 checks of the source test turned red. The unscoped read has exactly 3 callers.
What It Costs
| Item | Cost |
|---|---|
AssumeRole |
Free. The STS quota is 600 requests a second per account and Region |
| Sessions | One per active tenant, renewed about once an hour |
| Code | A session cache, a key check, and one function that gives out clients |
| Latency | One AssumeRole on the first call of a tenant, then none until renewal |
In my case: I measured the production key from a laptop with synthetic bytes. The first put took 1,092 ms, and that includes the AssumeRole. A get took 181 ms. The first customer job after the switch put a source of 221,392 bytes and a result of 65,666 bytes in S3. The dashboard downloaded them 4 times through the link, and every answer was 200.
Alternatives
- A bucket per tenant. Strong isolation, but an account has a quota of buckets, and every new tenant becomes an infrastructure change.
- S3 Access Points. One access point per tenant, each with its own policy. Better than a bucket per tenant, but you still create a resource for each tenant.
- S3 Access Grants. It maps identities from your directory to prefixes. It fits when your users already exist in IAM Identity Center or another directory. A SaaS whose users live in its own database usually has no such directory.
- Session tags, as in this article. One role, one policy, no resource per tenant. The tenant only exists in the tag and in the key.
The Limitations
- AWS checks the session, not the request. If your code assumes the session of the wrong tenant, AWS allows the read. The second lock, the tenant in the query, covers that.
- The source test matches strings. An alias or a wrapper with another name gets past it. It stops the honest mistake, not a determined one.
- The account owner can remove the deny statement. CloudTrail records it. A policy cannot stop the owner of the account.
- A person in the account can still list the keys, with their sizes and dates. The deny covers the objects, not the list. Keep ids in keys, never names.
- The contract test runs by hand in my setup. If somebody changes the IAM policy and does not run it, nothing catches the change until the next run.
- I did not measure the latency between my API's cluster and S3 in production, or the egress cost.
Conclusion
The isolation of tenant files should not depend on string concatenation being right every time. These are the rules I keep:
- Choose the tenant from the access rules. An organization, a user, or both. The tenant is the first segment of the key.
-
Give each tenant its own session. One role, one session tag, and
${aws:PrincipalTag/...}in the policy. A bug in your key code becomesAccessDenied. - Lock the trust policy. Exactly one tag key, never empty, never transitive.
- Check the key in code too. Fail before AWS, and let your test store fail the same way.
- Deny every other principal on the objects. Admins included.
- Prove the refusal on a real bucket. A mock proves the mock.
- Put the tenant inside the database query. Name the unscoped read honestly, and count its callers with a test.
AWS can refuse a session of the wrong tenant. Only your code can choose the right one. Build both locks, and a file has to pass two independent checks before it reaches anyone.
I built this for Tranly, where people send birth certificates, school transcripts and contracts, and get the translation back in the same layout. These are the documents a person least wants to see in somebody else's account. If you translate documents like these, I would like to hear how you handle them.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.