Authentication and authorisation for a multi-tenant SaaS and its public API
Name every identity that can call you, check function, object and property on every request, and make the tenant boundary something the database and the tests enforce, not something each handler remembers
A researcher reports that with her own Wrenpost API key she can read delivery reports for messages sent by another business. Her key is valid and the authentication middleware passed. What is the most likely cause?
A business SaaS with a public API has more kinds of caller than its engineers usually list, and each kind has its own credential, its own lifetime and its own favourite bug. Your job is to know all of them, to make the checks that apply to each one happen in one place, and to prove with tests that one customer cannot reach another’s data. This chapter is that job, at the level of the code.
It assumes the mechanisms. The OAuth lesson walks the authorisation code flow, CSRF and harden-login cover the browser side, and the lessons IDOR, SSRF, tenant isolation and JWT pitfalls cover the bug classes one at a time. Staff identity, MFA and service secrets belong to identity, access and secrets. This chapter is the customer-facing side.
The model: five callers and one boundary
Start a review by listing who can call the system. In a messaging API like Wrenpost’s there are five.
| Caller | What proves it | What it should reach | The bug it attracts |
|---|---|---|---|
| A user in the dashboard | Session cookie after password, MFA or SSO | Workspaces they are a member of, within their role | Session not rotated or revoked; role checked in the UI only |
| A workspace (the tenant) | Not a caller itself: the boundary every other identity sits inside | Its own messages, contacts, keys, webhooks, exports | A query without the workspace condition |
| An API client of the customer | API key issued to one workspace | That workspace’s API surface, perhaps limited by key scope | Key treated as global; key in logs; no rotation |
| A connected third-party app | OAuth access token, granted by a user for a workspace | The scopes the user consented to, in that workspace | Token for one workspace accepted on another; scopes not enforced |
| Internal staff | Staff SSO, then an impersonation session | One customer’s view, for a ticket, logged and time-limited | Impersonation that is silent, unlimited or able to change billing |
The tenant is the row that matters. Every request ends up as “this actor, acting in this workspace, wants this action on this object”. If any of the three parts comes from the request body instead of the credential, you have a bug. Write that sentence on the wall.
Wrenpost’s 2,400 or so business customers each have at least one workspace. Some agencies run several. A user can belong to more than one workspace, which is why “the user’s tenant” is not a thing: the tenant comes from the credential (a key is issued to one workspace) or, for a session, from a workspace the user selected and is confirmed to belong to.
Tokens: OAuth 2.0 for the public API and its apps
A connected app, such as a CRM that sends SMS through a customer’s Wrenpost account, should never hold the customer’s password or a copy of their API key. It holds an OAuth access token a user granted it. RFC 9700, the OAuth 2.0 Security Best Current Practice published in January 2025, is the current rulebook, and most of it is a list of things the original RFC 6749 allowed that you should now refuse.
- Authorisation code with PKCE. RFC 9700 says “Public clients MUST use PKCE” and recommends it for confidential clients too. The implicit grant should not be used, and the resource owner password grant must not be.
- Exact redirect URIs. The authorisation server must compare redirect URIs with exact string matching. A wildcard on a subdomain is how codes get stolen.
- Scopes the resource server enforces.
messages:send,messages:read,contacts:read,webhooks:write. A scope listed on the consent screen and never checked in the handler is decoration. - Audience. Access tokens should be restricted to one resource server, and the API must reject tokens meant for anything else. A token for Wrenpost’s analytics service should not open the send API.
- Refresh tokens. For public clients they must be sender-constrained or rotated. With rotation, each refresh returns a new refresh token and invalidates the old one. If the old one is presented again, either the client or a thief is replaying it, and RFC 9700 says the server revokes the active token.
The tenant part is yours, not the RFC’s. A grant is made by a user for one workspace. Store the workspace id on the grant and in the token, and take it from there in the API. The bug to look for is the app sending a workspace_id header and the API believing it.
API keys or OAuth tokens
| API key | OAuth access token | |
|---|---|---|
| Who holds it | The customer’s own servers | A third party acting for the customer |
| Lifetime | Long; until rotated | Short, renewed with a refresh token |
| Granted by | An admin in the dashboard | A user’s consent, per app |
| Revocation | Delete the key | Revoke the grant: every token for that app and workspace |
| Right for | Server-to-server use by the customer | Integrations, marketplaces, anything acting for many customers |
Keep both, and make keys behave well. Give them a visible prefix that marks live and test (so leaked keys are findable by secret scanners), store only a hash, show the full key once, allow two active keys during a rotation, and record last-used time so dead keys can be removed. Comparing a presented key against a stored value with ordinary string equality leaks timing; the timing-attack lesson shows why you compare hashes in constant time.
Login: OIDC, SSO and the account-linking trap
OpenID Connect adds an ID token to OAuth. The two tokens are not interchangeable. The ID token tells your app who logged in and is addressed to your app as its audience. The access token is for calling an API. Accepting an ID token as an API credential, or an access token as proof of login, is a common bug.
OpenID Connect Core 1.0 lists the checks on an ID token: the issuer must match exactly, the audience must contain your client id, the signature must verify with the issuer’s keys, the token must not have expired, and if you sent a nonce it must come back unchanged. The nonce ties the ID token to the login your browser started, which stops an old token being replayed into a new session. Use a maintained library and read its configuration; the JWT pitfalls lesson covers the algorithm and key-confusion mistakes.
Then the trap from the Why. Section 5.7 of the same specification says the combination of iss and sub is “the only guaranteed unique identifier” for a user, and that email, phone number, username and name “MUST NOT be used as unique identifiers”. Enterprise SSO multiplies the risk, because each customer brings its own identity provider and the email domain inside a token proves nothing about who controls that domain.
Rules that close it:
- Key external identities on the pair (issuer, subject). Store it in a table of linked identities.
- Link a new external identity to an existing account only after the user proves they own the existing account, for example by logging in to it first.
- Bind each SSO connection to the workspace that configured it, and to email domains that workspace has verified by DNS. An identity provider configured by workspace A cannot log anyone into workspace B.
- Decide what just-in-time provisioning may create: a member with the default role in the connected workspace, never an admin, never in another workspace.
- When SSO is enforced for a workspace, password login and old sessions for its members stop.
Sessions
The dashboard session is a cookie, and the OWASP Session Management Cheat Sheet settles most choices. Set Secure, HttpOnly and SameSite (Strict preferred, Lax acceptable), leave Domain unset, and use the __Host- prefix so a sibling subdomain cannot plant or read it. Regenerate the session id at login and at any privilege change, or an attacker who planted an id before login inherits the logged-in session. Keep sessions on the server, so logout, a password change, an SSO deprovisioning and an admin’s “sign out everywhere” can delete them. The cheat sheet gives idle timeouts of 15 to 30 minutes for low-risk applications and 2 to 5 for high-value ones; a dashboard that can read message content and create API keys is nearer the second, and adding an absolute timeout caps a stolen cookie’s life.
Staff impersonation is a session too, and the riskiest one. Make it a separate session type: started from the staff tool with a ticket reference, read-only by default, time-limited, shown to the customer in their audit log, and unable to create keys, change SSO or touch billing.
Authorisation: three checks on every request
Every request needs three answers, and OWASP’s API Security Top 10 2023 names the failure of each.
- Function level (API5, BFLA). May this caller use this operation at all? A member calling
DELETE /v2/workspaces/:id/keys/:keyId, a token withmessages:readcalling send. - Object level (API1, BOLA). Does this object belong to the caller’s workspace, and may they touch it?
- Property level (API3, BOPLA). Which fields may they read or write? A
PATCHthat copies the whole body into the row lets a member setrole: "owner"orcredit_balance. That is mass assignment.
Here is the bug from the Predict, in the shape you will meet it:
// Before: authenticated, not authorised
app.get('/v2/messages/:id', requireApiKey, async (req, res) => {
const msg = await db.message.findUnique({ where: { id: req.params.id } });
if (!msg) return res.status(404).end();
res.json(msg);
});
// After: the workspace comes from the credential, never the request
app.get('/v2/messages/:id', requireApiKey, async (req, res) => {
const { workspaceId } = req.auth; // set by middleware from the key
const msg = await db.message.findFirst({
where: { id: req.params.id, workspaceId },
select: publicMessageFields, // property-level: an allowlist
});
if (!msg) return res.status(404).end(); // 404, not 403: do not confirm it exists
res.json(msg);
});
The fix in one handler is easy. The finding that matters is that 112 handlers each had to remember it. The OWASP Authorization Cheat Sheet says deny by default and validate permissions on every request, preferably in central middleware. In practice that means one policy function and a data layer that cannot be called without a tenant:
type Actor = { kind: 'user' | 'apiKey' | 'app' | 'staff'; workspaceId: string; role?: Role; scopes: string[] };
export function can(actor: Actor, action: Action, resource?: { workspaceId: string }): boolean {
if (resource && resource.workspaceId !== actor.workspaceId) return false;
return POLICY[action](actor); // one table: action -> roles and scopes allowed
}
// The repository takes the actor, so a handler cannot forget the tenant
export const messages = (actor: Actor) => ({
get: (id: string) => db.message.findFirst({ where: { id, workspaceId: actor.workspaceId } }),
});
Role-based access inside a workspace (owner, admin, developer, member, billing) is enough for most products. The cheat sheet prefers attribute or relationship-based models as rules multiply; move when your roles start to split by team or sub-account, not before.
Tenant isolation, and the places it leaks
There are three ways to keep tenants apart, and the Decide below asks you to choose.
| Option | How it works | What it buys | What it costs |
|---|---|---|---|
| Application scoping | Every query carries workspaceId, through a scoped repository |
Simple, one database, cheap | One forgotten condition is a cross-tenant leak |
| Postgres row-level security | A policy on each table compares workspace_id to a per-transaction setting |
The database refuses rows from other tenants even when the code forgets | Setup discipline; owner and BYPASSRLS roles skip it |
| Schema or database per tenant | Each workspace gets its own schema or database | Strongest separation; per-tenant restore and residency | 2,400 migrations per release, connection counts, cost |
Row-level security has three traps the PostgreSQL documentation states plainly. Table owners bypass it unless the table has FORCE ROW LEVEL SECURITY. Superusers and roles with BYPASSRLS always bypass it. And a table with RLS enabled and no policy denies everything, which is the safe failure. The fourth trap is yours: if the app sets the tenant for the whole connection, the next request on that pooled connection inherits it. Set it per transaction:
await db.$transaction(async (tx) => {
await tx.$executeRaw`select set_config('app.workspace_id', ${actor.workspaceId}, true)`; // true = this transaction only
return tx.message.findMany({ where: { status: 'failed' } });
});
// policy: USING (workspace_id = current_setting('app.workspace_id')::uuid)
Run the application as a role that owns nothing and lacks BYPASSRLS, and keep migrations on a separate role.
Then look past the database. Tenant data leaks most often through shared things that were built later:
- Caches. A key of
msg:${id}serves whichever tenant asked first. Put the workspace in every cache key. - Search indexes. A shared index of message logs needs a workspace filter the query builder adds, not one the caller passes.
- Queues and jobs. A job carries a workspace id written by the producer; the worker must re-check that the objects belong to it.
- Exports. A CSV in object storage with a guessable path, or a download link with no expiry, is a public file.
- Webhooks. A delivery report sent to the wrong workspace’s URL, or signed with the wrong secret, leaks message content. The webhook delivery lesson covers signing and retries.
SSRF from webhooks and import-from-URL
Wrenpost lets each workspace set a webhook URL for delivery reports, and lets users import contacts from a URL. Both make your server send a request to an address the customer chose, from inside your network. Without checks, http://169.254.169.254/ reaches the cloud metadata service and http://10.0.3.7:9200/ reaches an internal search cluster. OWASP lists this as API7:2023.
The OWASP SSRF Prevention Cheat Sheet admits an allowlist is rarely possible when the customer picks the URL, so the defence has layers. Resolve the hostname, check every A and AAAA record against private, loopback, link-local and metadata ranges, then connect to the address you checked rather than resolving again, since a second lookup can be rebound. Turn off redirects. Send these requests from a separate egress path whose firewall cannot reach internal networks. On AWS, require IMDSv2, which cloud and infrastructure security covers. Validating the URL when it is saved and not when it is called is the usual gap, because DNS can change in between: that is TOCTOU again, and the SSRF lesson walks the bypasses.
Finding these bugs in a TypeScript codebase
You will not read 112 handlers line by line every quarter. Search for the shapes instead.
| Search for | What it usually means |
|---|---|
findUnique(, findById(, .where('id' with a route param |
Object lookup that may lack the workspace condition |
req.body.workspaceId, req.query.workspace, headers['x-workspace |
Tenant taken from the request instead of the credential |
...req.body or data: req.body in an update |
Mass assignment (BOPLA) |
Routes with no can( or policy middleware |
Missing function-level check |
fetch(, axios(, got( with a URL from a model or request |
SSRF candidate |
jwt.decode( without verify; algorithms unset |
Token not validated |
| Cache keys and index queries without the workspace | Shared-resource leak |
Grep finds candidates; tests prove the boundary. Write one test that every route must pass, generated from the route table: create two workspaces, create an object in B, then call every route with A’s credentials and B’s object id, and assert a 403 or 404 (404 is better, since it does not confirm the object exists). Add a route and the test fails until it is covered.
for (const route of listRoutes(app)) {
test(`${route.method} ${route.path} refuses another workspace's object`, async () => {
const res = await call(route, { as: tenantA.key, ids: tenantB.ids });
expect([403, 404]).toContain(res.status);
});
}
A Semgrep or ESLint rule that flags direct db. calls outside the repository layer keeps the policy central. Add the test to CI as a blocking check, and treat a researcher’s BOLA report as a missing test as well as a missing condition; triage of those reports is in triaging researcher reports.
Where practitioners disagree
| Question | One view | The other view |
|---|---|---|
| Where tenant isolation lives | In application code, which you can test and read | In the database too, because code forgets and RLS does not |
| Authorisation model | RBAC is understandable and auditable | ABAC or ReBAC fits multi-workspace agencies and sub-accounts |
| Session or token for the dashboard | Server sessions in a cookie, revocable at once | Short JWTs, stateless, with refresh; revocation becomes a list you must check anyway |
| 403 or 404 on another tenant’s object | 403 is honest and easier to debug | 404 does not confirm that the id exists |
Day to day
Design reviews, two or three a month. Any change that adds a caller type, a scope, a route family, a shared store or an outbound fetch gets a short review using the five-caller table and the three checks. These are cheap at design time and expensive afterwards.
Pull requests, daily. Review diffs that touch auth middleware, the policy table, the repository layer, SSO configuration and webhook code. A CODEOWNERS rule routes them to you or a trained champion.
Weekly. Read the grep report for new direct db. calls and unprotected routes. Check that the cross-tenant test suite covers every route in the table.
Monthly. Review impersonation sessions against tickets, keys unused for 90 days (a rule of thumb), OAuth apps with the widest scopes, and SSO connections without a verified domain.
Quarterly. Re-run the authorisation model review on one API surface, and bring the findings to the engineering managers’ meeting with owners and dates. Feed the pentest scope from pentests, bug bounties and vendor risk with the areas the tests do not reach.
The meetings that matter are the design review, the weekly API team stand-up when a new route family is planned, and the incident review after any cross-tenant report, however small.
There is no security engineer and one database. The cheapest controls are structural: a repository layer that takes the workspace from the credential, a policy function every route calls, and the cross-tenant test generated from the route table. Use a hosted identity provider for login and SSO instead of writing your own, and copy its settings into a short document. Keys get a prefix and a hash from the first day. Row-level security can wait until a second team writes queries, but not much longer.
Several teams write routes, and connected apps and enterprise SSO arrive because sales needs them. This is the stage to centralise: one policy table, RLS as a backstop under the application checks, a lint rule against direct database calls, and the review template in the design-doc process. Enterprise customers’ security questionnaires ask about tenant isolation and SSO, and auditors ask how access is enforced, so the tests double as evidence. Train a champion in each team that owns routes.
The surface is many APIs, several identity providers and years of routes written by people who have left. The work is inventory and consistency: a catalogue of every API and its owner, an authorisation service or policy engine shared across services, standard token formats and audiences, and isolation tiers sold as a product, with dedicated databases for the customers who pay for them. Politics arrive with each exception: a team that wants its own token format, or a big customer that wants staff access turned off.
Template
# Authorisation model review: <API or surface>
Author · Reviewed with: <tech leads, EMs> · Date · Routes in scope: <n>
Status: draft | reviewed | fixes in progress | closed
## 1. Callers
| Caller | Credential | Lifetime and revocation | Where the workspace comes from | Logged as |
|---|---|---|---|---|
## 2. Tokens and login
| Token | Issuer | Audience | Checks done (sig, exp, iss, aud, nonce, scopes) | Refresh handling |
|---|---|---|---|---|
Account linking rule: <keyed on iss + sub; how a new identity is linked>
SSO: <how a connection is bound to a workspace and verified domains; JIT role>
Sessions: <cookie flags, rotation, idle/absolute timeout, server-side revocation>
## 3. Authorisation
Policy: <where the central check lives; roles and scopes table>
| Route family | Function check | Object check | Property check | Gap (BOLA/BFLA/BOPLA) |
|---|---|---|---|---|
## 4. Tenant boundary
Primary enforcement: <scoped repository / RLS / per-tenant store>
Backstop: <...>
| Shared store | Tenant in key or filter? | Control | Gap |
|---|---|---|---|
## 5. Outbound fetches (SSRF)
| Feature | URL chosen by | Address checked when | Redirects | Egress path |
|---|---|---|---|---|
## 6. Findings
| ID | Finding | Class | Severity | Owner | Ticket | Test that proves the fix |
|---|---|---|---|---|---|---|
## 7. Residual risk and next review
<what is accepted, by whom, until when> WORKED EXAMPLE
Wrenpost, about 180 staff and 55 engineers in seven teams. The security team is two people: the security lead and Habib, a security engineer. Habib reviewed the public API v2, 112 routes, with Oge, the Dashboard team’s engineering manager, and the Delivery Reports tech lead.
Callers. Dashboard users (session cookie, SSO for about 90 workspaces); API keys per workspace with live_ and test_ prefixes, stored hashed; about 40 connected apps on OAuth; support staff through a “view as” tool.
Findings.
| ID | Finding | Class | Owner | Test |
|---|---|---|---|---|
| AUTHZ-1 | GET /v2/messages/:id and two siblings look up by id alone |
BOLA | Delivery Reports | Generated cross-tenant test, all 112 routes |
| AUTHZ-2 | PATCH /v2/members/:id spreads the body, so a member can set role |
BOPLA | Dashboard | Member sets role, expect 400 |
| AUTHZ-3 | SSO login links accounts on email when the address exists | Account takeover | Dashboard | IdP of workspace A asserts B’s admin email, expect no link |
| AUTHZ-4 | Message-log search cache key omits the workspace | Shared-store leak | Delivery Reports | Same query from two workspaces returns different results |
| AUTHZ-5 | Webhook URL checked at save time only, redirects followed | SSRF | Delivery Reports | URL that resolves to 169.254.169.254 at send time is refused |
| AUTHZ-6 | Refresh tokens for apps never rotate | Token theft | Dashboard | Reused refresh token revokes the grant |
| AUTHZ-7 | “View as” sessions can create API keys and last until logout | Staff impersonation | Dashboard | Impersonation session cannot call key routes; expires in 60 min |
Tenant boundary. Primary: a scoped repository taking the actor. Backstop: RLS on the six tables holding message content, with FORCE ROW LEVEL SECURITY, the app role without BYPASSRLS, and the setting made per transaction. AUTHZ-1 and AUTHZ-3 were fixed within the week; the rest were scheduled into the next two sprints.
Now you
You are the security engineer at Wrenpost (about 180 staff, 55 engineers, about 2,400 business customers). Sales wants partner access by the WhatsApp launch in Q3 2027: agencies that manage many customer workspaces will use one OAuth app and one login to act across all their clients. Product proposes that the partner app sends an X-Workspace-Id header to choose the client on each call. Complications: some agency staff log in with their agency’s identity provider, and some of their client workspaces enforce their own SSO; the export feature writes CSVs to a shared bucket with paths made from a timestamp; partner apps want long-lived tokens because their jobs run overnight; the cross-tenant test covers only routes that take a single object id; and support wants to see what an agency did in a client’s workspace. Write the authorisation model review for partner access: the callers, how the workspace is chosen and checked on every call, tokens and refresh, the SSO interaction, the shared stores, and your findings with tests.
Self-check
You are Habib, the security engineer at Wrenpost. After AUTHZ-1, Oge asks how tenant isolation should be enforced from now on. Wrenpost has one Postgres cluster with shared tables keyed by workspace_id, about 2,400 business customers, seven teams writing queries, and a few enterprise prospects asking about dedicated infrastructure. What do you recommend?
- DOC RFC 9700: Best Current Practice for OAuth 2.0 Security IETF, 2025
The current rules for OAuth: PKCE, exact redirect matching, audience-restricted tokens, refresh-token rotation, and the grants to stop using. Read sections 2 and 4.14 before reviewing any OAuth server.
- DOC OpenID Connect Core 1.0 OpenID Foundation
Section 3.1.3.7 lists the ID token checks and section 5.7 says why only issuer plus subject identifies a user. The two sections that prevent most SSO account takeovers.
- DOC OWASP API Security Top 10 2023 OWASP, 2023
The shared vocabulary for API flaws: BOLA, BOPLA, BFLA and SSRF each have a page with attack scenarios and prevention. Cite risks by number and edition in findings.
- DOC Authorization Cheat Sheet OWASP
Deny by default, check on every request, centralise the logic and test it. The case for one policy function instead of checks scattered through handlers.
- DOC Session Management Cheat Sheet OWASP
Cookie attributes, the __Host- prefix, session id renewal at login, timeouts and server-side invalidation. The checklist for the dashboard session.
- DOC Row Security Policies PostgreSQL Global Development Group
How RLS policies work, and the exceptions that matter for tenant isolation: owners, superusers, BYPASSRLS, FORCE and referential integrity checks.
- DOC Server Side Request Forgery Prevention Cheat Sheet OWASP
What to do when customers choose the URL, as with webhooks: check resolved addresses, pin the connection, disable redirects and segregate egress.
- POST nOAuth: How Microsoft OAuth Misconfiguration Can Lead to Full Account Takeover Descope, 2023
The disclosure behind the Why: apps merged accounts on a mutable, unverified email claim. The clearest public case for keying identities on issuer and subject.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.