24 min read · Websites and web apps

A user at one company opens an invoice and sees another company's customer name. Or they change the last digits of a URL from 111 to 211 and open a document that is not theirs. This happens in systems that several organizations share (multi-tenant), when a single query forgets to filter by organization ID. The damage is worse than an ordinary bug, because it hits the data of several companies at once.
This article builds data isolation one layer at a time, in TypeScript that Node 24 runs directly with nothing to install. It uses node:sqlite as the test database. It includes code you can run, real output, a test suite, and a PostgreSQL Row-Level Security SQL file for a real system. A manager can read the explanations and tables and get the picture. An engineer can run the code and follow along.
The real problem: many organizations in one table, and care alone is not enough
Keeping every organization in the same database and the same tables, with a tenant_id column saying who owns each row, is the cheapest and easiest to maintain. But all the security then depends on whether every line of code that touches data remembers WHERE tenant_id = .... People slip in the search menu, in exports, in file downloads, and in background jobs written later.
Consider three made-up situations. They are not projects of any BT San customer.
- An invoicing system for several accounting offices: the list page filters correctly, but the CSV export button, added later, forgot to filter. The downloaded file holds the invoices of every office.
- An inventory system for several shops with different owners: a user changes the id number in the URL of a product image and can load another shop's file. The download endpoint only checks that the user is logged in. It does not check which organization the file belongs to.
- A booking system for several clinics: the background job that sends appointment reminders receives only the appointment ID and does not know which organization it belongs to. It loads the data and picks the message template of the wrong organization.
All three are fixed by the same principle: do not rely only on the developer's memory. Make the database help reject bad access, make the data access layer force the filter every time, and have a test suite that attacks through every route.
What the documentation says: what we know, and what we must not assume
| Topic | What the documentation says | Effect on our code |
|---|---|---|
| Where the tenant comes from | The OWASP Multi-Tenant Security Cheat Sheet says to find the tenant from an identity the server has verified, not from client-side data. If a tenant ID arrives in a header or a parameter, treat it only as a hint the server must check. | Bind the tenant to the server-side session. Do not read it from the body, the URL or a hidden field. |
| Object-level checks | The OWASP Authorization Cheat Sheet says to check permission on every request against the object actually being accessed, and to deny by default. | Every method that takes an id must also filter by tenant. |
| 404 instead of 403 | The OWASP Multi-Tenant Security Cheat Sheet says to answer 404 instead of 403 when someone reaches for another tenant's object, so the response does not reveal that the object exists. | Another tenant's object and a nonexistent object must get the same response. |
| Row-Level Security | PostgreSQL: when RLS is enabled and there is no policy, the system denies every row by default. Superusers and roles with BYPASSRLS always bypass RLS. The table owner can bypass it unless you run FORCE ROW LEVEL SECURITY. | The app must not connect with a role that can bypass RLS, and must use FORCE. |
| USING and WITH CHECK | PostgreSQL: USING filters existing rows (rows that fail are silently filtered out). WITH CHECK validates new rows or rows after an update, and raises an error if they fail. | Write both conditions explicitly. |
| Tenant value per transaction | PostgreSQL: set_config with is_local set to true lasts until the end of the transaction. current_setting with missing_ok set to true returns NULL instead of an error when the value has not been set. OWASP recommends setting it per transaction so the value does not carry over between requests on a pooled connection, and failing closed. | Set the tenant in every transaction. If it is missing, the query must see no rows at all. |
| Composite keys in SQLite | SQLite: foreign keys are off by default. You must run PRAGMA foreign_keys = ON on every connection, and a composite foreign key must reference exactly the same set of columns that form a PRIMARY KEY or UNIQUE constraint. | Parent tables need PRIMARY KEY (tenant_id, id), and child tables reference both columns. |
| Schemas in PostgreSQL | PostgreSQL: a schema is a namespace within one database. A user can reach objects in other schemas if they have permission. Role names are shared across the whole cluster. | A schema per tenant is not a wall by itself. You must also set permissions. |
The latest Node.js documentation we read lists node:sqlite as a release candidate and treats the name DatabaseSync as an old alias of Database. This example was tested on Node 24.21, where DatabaseSync works normally. If you use another Node version and the name does not match, adjust it according to the documentation for that version.
Overview of the example
The example has two made-up organizations in one database. A user from organization A tries to guess the ids of organization B through every route. Everything runs on one machine with no network.
| File | Role |
|---|---|
| schema.ts | The schema: tenant_id on every table, composite keys, composite FKs, and bill numbers that are unique per organization |
| seed.ts | Made-up data for two organizations. The bill number INV-0001 can repeat across organizations |
| repo.ts | TenantRepo, the data access layer, which filters every query by the tenant from the session |
| api.ts | A simulated handler that ignores the tenant value in the body and gives the same 404 in every case |
| extras.ts | Cache keys, background jobs, webhooks, and exporting and deleting a whole organization's data |
| rls.sql | PostgreSQL Row-Level Security (not yet run) |
| demo.ts | The cross-organization attack scenarios, which print the results |
| isolation.test.ts | The node:test suite |
| output.txt | Real output of the demo |
Step 1: composite keys, so the database rejects references across organizations
The principle is that the primary key of every table is (tenant_id, id), and child tables reference their parent with both columns. An invoice for tenant 1 cannot point to a customer of tenant 2, because there is no row (1, the id of tenant 2's customer) to reference. Even if someone writes an INSERT directly, the database refuses it. UNIQUE (tenant_id, number) lets the bill number INV-0001 repeat across organizations but not within one organization.
CREATE TABLE invoices (
tenant_id INTEGER NOT NULL REFERENCES tenants(id),
id INTEGER NOT NULL,
seq INTEGER NOT NULL,
number TEXT NOT NULL,
customer_id INTEGER NOT NULL,
total_satang INTEGER NOT NULL CHECK (total_satang >= 0),
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, seq),
UNIQUE (tenant_id, number),
FOREIGN KEY (tenant_id, customer_id) REFERENCES customers(tenant_id, id)
);A common slip with SQLite is that foreign keys are off by default. You must run PRAGMA foreign_keys = ON on every connection. schema.ts runs it on its first line. If you skip it, all the composite keys are only decoration.
Step 2: a data access layer that accepts no tenant from outside
TenantRepo is built from a session that the server itself issued, and no method takes tenantId as a parameter. The caller therefore cannot pass the wrong tenant by mistake. The session itself is bound to the user with a composite FK, so the tenant in a session always comes from the database.
// tenant มาจาก session ที่เซิร์ฟเวอร์ออกเอง ไม่รับจาก body, URL หรือ hidden field
export function sessionFromToken(db: DatabaseSync, token: string | undefined): Session | null {
const row = db.prepare("SELECT tenant_id, user_id FROM sessions WHERE token = ?").get(token ?? "") as
{ tenant_id: number; user_id: number } | undefined;
return row ? { tenantId: row.tenant_id, userId: row.user_id } : null;
} get(id: number): Invoice {
const row = this.db.prepare(
"SELECT id, number, customer_id, total_satang FROM invoices WHERE tenant_id = ? AND id = ?",
).get(this.tenantId, id) as Invoice | undefined;
if (!row) throw new NotFoundError("invoice");
return row;
}Creating a new invoice also uses only the repo's own tenant. If a customer id from another organization is passed in, the composite FK rejects it, and the code turns that into a NotFoundError, the same as the other cases. This stops an attacker from telling whether a customer with that id exists.
// simplified: MAX(seq)+1 ปลอดภัยเพราะ SQLite เขียนทีละคน; PostgreSQL ใช้ตารางตัวนับต่อ tenant (UPDATE ... RETURNING) หรือ retry เมื่อชน UNIQUE
create(customerId: number, totalSatang: number): Invoice {
const seq = (this.db.prepare("SELECT COALESCE(MAX(seq),0)+1 AS n FROM invoices WHERE tenant_id = ?")
.get(this.tenantId) as { n: number }).n;
// simplified: id = ช่วงของ tenant + ลำดับ เพื่อให้ id ของสององค์กรไม่ซ้ำกันในตัวอย่าง; ของจริงใช้ identity/UUID
const id = (this.db.prepare("SELECT COALESCE(MAX(id),0)+1 AS n FROM invoices WHERE tenant_id = ?")
.get(this.tenantId) as { n: number }).n + this.tenantId * 1000;
const number = "INV-" + String(seq).padStart(4, "0");
try {
this.db.prepare("INSERT INTO invoices (tenant_id,id,seq,number,customer_id,total_satang) VALUES (?,?,?,?,?,?)")
.run(this.tenantId, id, seq, number, customerId, totalSatang);
} catch (e) {
// FK ผสมปฏิเสธลูกค้าของอีกองค์กร: แปลงเป็น not found เหมือนกรณีอื่น
if (String(e).includes("FOREIGN KEY")) throw new NotFoundError("customer");
throw e;
}
this.audit("invoice.create", String(id));
return this.get(id);
}Step 3: the same 404 every time, and ignore the tenant from the client
The handler only reads the session from the token and builds a repo. If the body sends a tenant_id, it is never read. Every kind of NotFoundError is turned into a 404 whose content is identical character for character. Answering 403 sounds correct, but it tells an attacker that this id really exists in another organization.
export function handle(db: DatabaseSync, req: Req): Res {
const s = sessionFromToken(db, req.token);
if (!s) return { status: 401, body: { error: "unauthenticated" } };
const repo = new TenantRepo(db, s.tenantId, s.userId);
const [path, query = ""] = req.path.split("?");
const m = path.match(/^\/(invoices|files)\/(\d+)$/);
const id = m ? Number(m[2]) : 0;
try {
if (req.method === "GET" && path === "/invoices") return { status: 200, body: repo.list() };
if (req.method === "GET" && path === "/search") return { status: 200, body: repo.search(new URLSearchParams(query).get("q") ?? "") };
if (req.method === "GET" && path === "/export") return { status: 200, body: repo.exportCsv() };
if (req.method === "POST" && path === "/invoices")
return { status: 201, body: repo.create(Number(req.body?.customer_id), Number(req.body?.total_satang)) };
if (m?.[1] === "invoices" && req.method === "GET") return { status: 200, body: repo.get(id) };
if (m?.[1] === "invoices" && req.method === "PATCH") return { status: 200, body: repo.update(id, Number(req.body?.total_satang)) };
if (m?.[1] === "invoices" && req.method === "DELETE") { repo.remove(id); return { status: 204, body: null }; }
if (m?.[1] === "files" && req.method === "GET") return { status: 200, body: repo.downloadFile(id) };
return { status: 404, body: { error: "not found" } };
} catch (e) {
// ของคนอื่นกับของที่ไม่มีอยู่ ตอบเหมือนกันทุกตัวอักษร (404 ไม่ใช่ 403)
if (e instanceof NotFoundError) return { status: 404, body: { error: "not found" } };
throw e;
}
}Step 4: cache, background jobs, webhooks and exports
Data isolation can leak outside the tables. Examples are a cache that uses the same invoice-list key for every organization, a background job that does not know whom it works for, or a webhook that trusts the tenant named inside the message body. The example covers all of them. The cache key leads with the tenant, and the API forces you to pass a tenant every time. A background job carries the tenantId that the server set when it queued the job, and the worker opens the repo from that value, so it cannot call another organization's id. A webhook finds the tenant from a key in the URL that we issue to each organization, not from the payload.
export function runJob(db: DatabaseSync, job: Job): string {
const ok = db.prepare("SELECT 1 FROM tenants WHERE id = ?").get(job.tenantId);
if (!ok) throw new Error("job has unknown tenant");
const repo = new TenantRepo(db, job.tenantId, null);
const inv = repo.get(job.invoiceId); // ถ้า id เป็นของอีกองค์กรจะ throw NotFoundError
repo.audit("job.recalc-total", String(inv.id));
return `ok invoice ${inv.number}`;
}OWASP stresses that a tenant ID in a queue message is not proof of permission. The receiving side must check permission again, and the tenant ID must come from a trusted path or from a payload whose integrity is protected. This example does not yet sign the job payload. A real system must add that.
A real run: a user from organization A tries to touch the data of organization B
== ผู้ใช้องค์กร ก (tenant 1) ลองแตะข้อมูลองค์กร ข ==
list 200 [{"id":111,"number":"INV-0001","customer_id":101,"total_satang":150000},{"id":112,"number":"INV-0002","customer_id":101,"total_satang":275000}]
read invoice 211 (ของ ข) 404 {"error":"not found"}
read invoice 999 (ไม่มีจริง) 404 {"error":"not found"}
update invoice 211 404 {"error":"not found"}
delete invoice 211 404 {"error":"not found"}
download file 221 (ของ ข) 404 {"error":"not found"}
search INV-0001 200 [{"id":111,"number":"INV-0001","customer_id":101,"total_satang":150000}]
export CSV 200 "number,customer_id,total_baht\nINV-0001,101,1500\nINV-0002,101,2750"
create ด้วยลูกค้า 201 (ของ ข) 404 {"error":"not found"}
create + body.tenant_id=2 (ถูกเมิน) 201 {"id":1113,"number":"INV-0003","customer_id":101,"total_satang":100}
ไม่มี token 401 {"error":"unauthenticated"}
== ผู้ใช้องค์กร ข เห็นบิลของตัวเอง เลขเริ่มใหม่ ==
list (tok-b) 200 [{"id":211,"number":"INV-0001","customer_id":201,"total_satang":990000},{"id":212,"number":"INV-0002","customer_id":201,"total_satang":45000}]
== คีย์ผสม: ใครเขียน SQL ตรง ๆ ก็ผูกข้ามองค์กรไม่ได้ ==
ฐานข้อมูลปฏิเสธ: FOREIGN KEY constraint failed
== cache / job / webhook ==
cache tenant 1: ["ของ ก"] | tenant 2: undefined
job ของ tenant 1 บิล 111: ok invoice INV-0001
job tenant 1 บิล 211: NotFoundError
webhook key whk_b -> tenant 2 | key ปลอม -> null
== audit ต่อ tenant ==
{"tenant_id":1,"action":"invoice.create","n":1}
{"tenant_id":1,"action":"invoice.export","n":1}
{"tenant_id":1,"action":"job.recalc-total","n":1}
== ส่งออกและลบทั้งองค์กร ก (PDPA) ==
export แถวต่อตาราง: {"customers":1,"invoices":3,"files":1,"audit_log":3,"users":1}
ลบ: {"files":1,"invoices":3,"customers":1,"audit_log":3,"users":1}
tenant 2 ยังอยู่ครบ 200 [{"id":211,"number":"INV-0001","customer_id":201,"total_satang":990000},{"id":212,"number":"INV-0002","customer_id":201,"total_satang":45000}]- A's list has only A's INV-0001 and INV-0002. B's bills, which have the same bill numbers, do not appear.
- Reading, editing and deleting B's bill 211, and downloading B's file 221, each get 404 {"error":"not found"}, identical character for character to the nonexistent bill 999. The attacker cannot tell which ids exist.
- Searching for INV-0001 finds only A's. The CSV has 2 lines, both A's, with no amounts from B.
- Creating a bill with B's customer 201 gets 404. Sending tenant_id=2 in the body is ignored. The new bill goes to A as INV-0003.
- A direct SQL statement that tries to link A's bill to B's customer is rejected by the database with FOREIGN KEY constraint failed.
- Tenant 2's cache cannot read tenant 1's values. Tenant 1's job that points at bill 211 fails with NotFoundError, and a fake webhook key gets no tenant.
- The per-tenant audit log shows who did what in which organization. All of organization A's data can be exported in full before deletion, and after the deletion organization B is still fully intact.
The test suite
The test suite does what the attacker does, then confirms that every route answers the same as for a nonexistent id, and that B's data is not touched. Tie a test like this to CI. When you add a new endpoint, always add a cross-organization case too.
test("ทุกช่องทางที่แตะข้อมูลของ tenant B ตอบ 404 แบบเดียวกับ id ที่ไม่มีอยู่", () => {
const db = makeDb();
const missing = handle(db, a("GET", "/invoices/999"));
for (const [m, p, b] of [
["GET", "/invoices/211"], ["PATCH", "/invoices/211", { total_satang: 1 }],
["DELETE", "/invoices/211"], ["GET", "/files/221"],
] as const) {
assert.deepEqual(handle(db, a(m, p, b)), missing, `${m} ${p}`);
}
assert.equal(missing.status, 404);
// ข้อมูลของ B ไม่ถูกแตะ
assert.equal(handle(db, { token: "tok-b", method: "GET", path: "/invoices/211" }).status, 200);
});A real database: PostgreSQL Row-Level Security (not run here)
A production system on PostgreSQL should add a third layer, RLS, so the database filters by tenant itself even if the app code forgets to filter. The rls.sql file is written from the PostgreSQL documentation. To be direct about it, the environment where this article was written has no PostgreSQL, so this file has never been run. You must try it on your own test database.
-- 2) เปิด RLS และบังคับกับเจ้าของตารางด้วย (เจ้าของตารางข้าม RLS โดยปกติ)
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
-- 3) policy: USING กรองแถวที่เห็น/แก้/ลบ, WITH CHECK คุมแถวที่เขียนเข้าไป
-- current_setting(..., true) คืน NULL ถ้ายังไม่ตั้งค่า -> เงื่อนไขไม่เป็นจริง -> ไม่เห็นแถวเลย (fail closed)
CREATE POLICY tenant_isolation ON invoices
FOR ALL TO app_user
USING (tenant_id = nullif(current_setting('app.tenant_id', true), '')::bigint)
WITH CHECK (tenant_id = nullif(current_setting('app.tenant_id', true), '')::bigint);- The role the app uses to connect to the database must not be a superuser, must not have BYPASSRLS, and must not own the tables, because all of these bypass RLS. FORCE ROW LEVEL SECURITY covers the table-owner case.
- Set the tenant with set_config('app.tenant_id', ..., true) in the same transaction as the query, so the value does not linger on a pooled connection.
- current_setting with missing_ok set to true returns NULL when nothing was set, so the query sees no rows at all (fail closed). That is better than seeing every row.
- The PostgreSQL documentation warns that unique and foreign key checks bypass RLS, so data can leak through error messages. You still need composite keys and a uniform error response in the app.
- The test suite should also check that the app's role has neither rolsuper nor rolbypassrls, and that every table with a tenant_id has RLS enabled.
Permissions inside an organization, and the change record
Separating organizations is only the first gate. Inside one organization you still have to decide who can edit, who approves and who can view. That is a topic for other articles in this series. Every change should also have an audit record that names the tenant and the actor, as the example does in audit_log. Password hashing and identity verification are in the article on SSO and MFA. A cache that should not hold personal data is in the article on caching.
Exporting and deleting a whole organization's data (PDPA requests)
When an organization stops using the service, or a request arrives to send or delete personal data, you must be able to do it for the whole organization without affecting anyone else. The example writes exportTenant and deleteTenant so that every statement carries tenant_id, and the delete runs in one transaction, going from child tables to parents. A real system must also think about files in file storage, backup copies, logs, and the retention periods the law sets, for example for accounting documents. Ask a legal adviser about these. This example is not legal advice.
export function deleteTenant(db: DatabaseSync, tenantId: number): Record<string, number> {
const counts: Record<string, number> = {};
db.exec("BEGIN");
try {
// ลำดับ: ลูกก่อนแม่ (files -> invoices -> customers)
for (const t of ["files", "invoices", "customers", "audit_log"]) {
counts[t] = Number(db.prepare(`DELETE FROM ${t} WHERE tenant_id = ?`).run(tenantId).changes);
}
db.prepare("DELETE FROM sessions WHERE tenant_id = ?").run(tenantId);
counts.users = Number(db.prepare("DELETE FROM users WHERE tenant_id = ?").run(tenantId).changes);
db.prepare("DELETE FROM tenants WHERE id = ?").run(tenantId);
db.exec("COMMIT");
} catch (e) {
db.exec("ROLLBACK");
throw e;
}
return counts;
}When to separate by schema or by database per organization
| Approach | Fits when | The trade-off |
|---|---|---|
| Shared tables + tenant_id + RLS | There are many organizations and each has a small amount of data. You want to maintain and migrate in one place. | You need discipline about policies and the test suite. One bug affects every tenant. |
| Schema per organization | You want separate table names and per-tenant backups, and the number of tenants is still manageable. | Migrations must run on every schema, and a schema is not a permission wall by itself. |
| Database per organization | A contract or regulation requires real separation, or a large customer wants its own keys or its own data location. | Operating cost, connections and migrations grow with the number of tenants. OWASP says a separate database gives a stronger boundary when you also separate permissions, network and backups. |
Made-up cases: applying this to three businesses
An invoicing system for accounting offices
Each office is a tenant. Document numbers are counted per office. Every export button must go through the repo, and there must be cross-office test cases for exports, PDF printing and email sending.
A management system for several branches with different owners
Image and document files need a tenant_id in the file table, and the download endpoint must go through the same checks as any other data. If you use external file storage, put the tenant in the path, and do not hand out permanent URLs.
A clinic appointment system
The reminder job carries the tenantId and checks it again before it runs. Health data is sensitive. Consider RLS and logs that do not store raw data content, as advised by a legal expert.
Common mistakes and a checklist
- Reading the tenant from the body, query string, header or a hidden field, and trusting it.
- Filtering by tenant on the list page but forgetting it in export, search, file download, reports and background jobs.
- Answering 403 for someone else's object, which tells the attacker the id exists.
- Making the bill number unique across the whole table, so one organization collides with another's number and learns that the number exists.
- Enabling RLS but connecting the app as the table owner or a superuser, which bypasses RLS entirely.
- Setting the tenant at session level on a pooled connection, so the value carries over between requests.
- A cache key with no tenant in it.
- No tenant in logs and the audit record, so an incident cannot be investigated.
- Every customer table has tenant_id NOT NULL and a composite primary key or unique constraint that includes tenant_id.
- Foreign keys between tenant tables use composite keys on both sides, and the database's FK enforcement is turned on.
- The tenant comes only from the server-side session, and no data method takes a tenant from the caller.
- Someone else's object and a nonexistent object get the same response.
- Cache keys, background jobs and webhooks carry a trusted tenant, and the receiving side checks it again.
- Logs and the audit record contain the tenant and the actor.
- There is a procedure to export and delete data per organization, which also covers files and backup copies.
- If you use PostgreSQL, enable RLS with FORCE and a role that cannot bypass it, then test it on a real database.
- A cross-organization test suite covers every endpoint and runs in CI.
Cautions for the example: it uses in-memory SQLite, has no connection pool, and has not tried RLS for real. The id numbers in the example are generated in a simple way. Job payloads are not signed, files are not encrypted, and there is no handling for one user belonging to several organizations (multi-organization membership). There is no rate limit, and it does not cover every requirement of the PDPA. All data is made up. Adapt it and test it with your real system before using it.
References
- OWASP — Multi-Tenant Security Cheat Sheet (accessed 2026-11-21)
- OWASP — Authorization Cheat Sheet (accessed 2026-11-21)
- PostgreSQL — Row security policies (accessed 2026-11-21)
- PostgreSQL — CREATE POLICY (accessed 2026-11-21)
- PostgreSQL — System administration functions (set_config, current_setting) (accessed 2026-11-21)
- PostgreSQL — Schemas (accessed 2026-11-21)
- SQLite — Foreign key support (accessed 2026-11-21)
- Node.js — SQLite (node:sqlite) (accessed 2026-11-21)




