Skip to the content

Lesson 203 of 296

Roles, ownership checks and multi-tenant isolation

What you will learn

  • Authorisation models: RBAC, permissions, ABAC
  • Ownership checks and IDOR
  • Where to put authorisation checks
  • Multi-tenancy and keeping tenants' data apart
  • Row-Level Security
  • Testing authorisation
On this page

Authorisation models

RBAC (role-based access control): users have roles; roles have permissions.

RolePermissions
viewerinvoice:read
staffinvoice:read, invoice:create
adminall of the above, invoice:delete, user:manage

Check permissions, not role names, in code: can(user, "invoice:delete") rather than user.role === "admin". Then adding a "finance-manager" role does not mean changing code everywhere.

ABAC (attribute-based access control): decisions use attributes of the user, the resource and the context: "staff can edit an invoice if it belongs to their branch and it is not yet paid and it is during working hours". More flexible; more complex. Real systems mix RBAC with a few attribute rules. Policy engines such as Open Policy Agent, Cedar and CASL help for complex cases.

Ownership checks and IDOR

The most common serious API bug (number one in the OWASP Top 10 as Broken Access Control, Lesson 259):

GET /api/invoices/1043      (user A's own invoice: fine)
GET /api/invoices/1044      (user B's invoice: user A just changes the number)

If the server only checks "is the user logged in?" and not "does this invoice belong to them?", any user can read everyone's invoices. This is an IDOR (Insecure Direct Object Reference).

Fix: check ownership on every request, ideally inside the query itself:

TypeScript
type Invoice = { id: string; tenantId: string; ownerId: string; totalPence: number; status: "draft" | "paid" };
type Actor = { userId: string; tenantId: string; permissions: Set<string> };

export class ForbiddenError extends Error {}
export class NotFoundError extends Error {}

export class InvoiceService {
  constructor(private readonly invoices: Invoice[]) {}

  getForActor(actor: Actor, invoiceId: string): Invoice {
    const invoice = this.invoices.find((i) => i.id === invoiceId && i.tenantId === actor.tenantId);
    if (!invoice) throw new NotFoundError("Invoice not found");
    const canReadAll = actor.permissions.has("invoice:read:any");
    if (!canReadAll && invoice.ownerId !== actor.userId) throw new NotFoundError("Invoice not found");
    return invoice;
  }

  deleteForActor(actor: Actor, invoiceId: string): void {
    const invoice = this.getForActor(actor, invoiceId);
    if (!actor.permissions.has("invoice:delete")) throw new ForbiddenError("Not allowed to delete invoices");
    if (invoice.status === "paid") throw new ForbiddenError("Paid invoices cannot be deleted");
    this.invoices.splice(this.invoices.indexOf(invoice), 1);
  }
}
  • The tenant filter is part of the lookup itself: another tenant's invoice is simply "not found".
  • Not-owned resources also return 404, not 403, so attackers cannot discover which IDs exist (Lesson 194).
  • Permission and attribute rules ("paid invoices cannot be deleted") are checked in one service, which every route, server action, job and GraphQL resolver calls.
  • In SQL the same idea: SELECT ... FROM invoices WHERE id = $1 AND tenant_id = $2 AND (owner_id = $3 OR $4).

Random IDs (UUIDs) instead of counting numbers make guessing harder, but they are not a substitute for checks.

Where to check

  • Authentication at the edge: middleware or guards (Lesson 209) confirm who the user is.
  • Authorisation close to the data: in the service or data access layer, so every entry point is covered.
  • The front end hides buttons the user cannot use, but that is only for user experience. Never trust the client.
  • Deny by default: a new endpoint without a rule should refuse access, not allow it.

Multi-tenancy

A multi-tenant system serves many customer organisations (tenants) from one application. Examples: a CRM used by 500 law firms, or a booking SaaS for many restaurants. The most important rule: one tenant must never see another tenant's data.

ModelHowIsolationCost and effort
Shared tables with a tenant_id columnAll tenants in the same tablesLogical: every query must filter by tenantCheapest; easiest to run; most common
Schema per tenantOne database, one schema per tenantStrongerMigrations run per schema; harder with many tenants
Database per tenantSeparate databasesStrongest; per-tenant backup, restore and data locationMost expensive; for large or regulated customers

Making shared-table isolation safe

  • Put tenant_id on every tenant-owned table, and include it in indexes and unique constraints (UNIQUE (tenant_id, email)).
  • Take the tenant from the authenticated session or token, never from a request parameter or header the client controls.
  • Apply the filter automatically: a repository that always adds tenant_id, or a Prisma client extension or query middleware (Lesson 230).
  • Use Row-Level Security (RLS) in PostgreSQL as a safety net: the database itself refuses rows from other tenants.
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.tenant_id')::uuid);

The application sets app.tenant_id at the start of each transaction. Even if a developer forgets a WHERE, the database returns nothing from other tenants. (The application's database user must not be the table owner or a superuser, which bypass RLS by default.)

  • Include the tenant in cache keys (tenant:42:dashboard), file storage paths, search indexes, queue job payloads and logs.
  • Background jobs must carry and check the tenant ID too.

Testing authorisation

Write tests for the forbidden paths, not just the happy path:

  • User A cannot read, update or delete user B's resource (expect 404 or 403).
  • A user from tenant 1 cannot access tenant 2's data through any endpoint, filter or search.
  • A role without a permission gets 403.
  • Changing your own role or tenant ID in the request body is ignored.

How to say it in an interview

"I model authorisation with role-based permissions, checking permissions rather than role names, plus attribute rules where needed. The biggest risk is broken access control such as IDOR, so every request checks ownership and tenant inside the data access layer, ideally as part of the query, returning 404 for records the user may not see, and the front end is never trusted. For multi-tenant SaaS I usually use shared tables with a tenant ID taken from the session, applied automatically by a repository or ORM extension, with PostgreSQL row-level security as a safety net, tenant-scoped unique constraints, cache keys and jobs, and tests for cross-tenant access. Higher-isolation schema or database per tenant suits large or regulated clients."

Key words

WordMeaning
RBACRole-based access control
ABACAttribute-based access control
PermissionA specific allowed action, like invoice:delete
IDORAccessing others' records by changing an ID
Ownership checkConfirming a resource belongs to the user
TenantOne customer organisation in a shared system
Multi-tenancyServing many tenants from one application
Row-Level SecurityDatabase rules that filter rows per user or tenant
Deny by defaultRefusing access unless a rule allows it

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.