26 min read · Websites and web apps

A sales rep from the Chiang Mai branch logs in normally, then changes 1043 to 1044 in the URL. The screen shows an order from the Bangkok branch, with the customer's phone number and the cost price. In another case, the approve button is hidden from staff, but anyone can send the approval request directly. Both cases have the same root: the system checks who you are (authentication) but does not check whether you may do this to this record (authorization).
This article walks through building authorization correctly from the start. It uses TypeScript that Node 24 runs directly, with node:http and node:sqlite, which ship with Node, so nothing needs to be installed. There is code you can run yourself, real output, and a test suite. A manager can read the permission table and check the business rules. An engineer can run the code and follow along.
The real problem: being logged in does not mean you can do everything
Consider three hypothetical situations. They are not from any BT San customer project.
- A multi-branch sales order system: anyone who swaps the ID in the web address can see another branch's orders, because the endpoint only checks that the user is logged in (this flaw is called IDOR).
- An invoice system: an approved invoice should be locked against edits, but the edit button is hidden only on the screen. Anyone who calls the API directly can still change the amount.
- A back-office system shared by several companies: a front-desk employee opens a record and sees the cost price and customer phone fields. The screen does not show them, but the JSON the API sends contains every field.
These three cases are fixed with three layers, and all three are required: roles and actions (who can do what), record-level rules (whose record this is, which branch, what status), and field-level rules (which fields the user may see). All of it must be checked on the server on every request.
What the reference documents say
| Topic | What the document says | Effect on our code |
|---|---|---|
| Deny by default | The OWASP Authorization Cheat Sheet recommends deny-by-default and least privilege. OWASP Top 10 A01 says that, except for public resources, access should be denied by default. | can() must return false unless every condition passes. |
| Check every request | The Cheat Sheet says permissions must be validated correctly on every request, against the object or function actually being called. | Every endpoint calls can(). No shortcut because "the request came from our screen". |
| IDOR | OWASP says it occurs when an attacker can access or modify an object by changing an identifier, because authorization is not checked. Even when identifiers are complex, authorization checks are still required. | Changing the id to a UUID is not a fix. The owner must be checked. |
| Record owner | OWASP A01 says access control should enforce record ownership. | The rule that staff see only their own records. |
| Server side | OWASP A01 says access control is effective only in trusted server-side code, where the attacker cannot modify it. | Hiding a button is only a convenience, not a protection. |
| Logging and testing | A01 says to log access control failures and alert administrators when they repeat. The Logging Cheat Sheet lists authorization failures as events that should be logged. The Authorization Cheat Sheet says to write unit and integration tests for the permission logic. | There is a denied_log table, and a test suite that walks the whole table. |
| RBAC | NIST describes RBAC as assigning permissions at the role level: users are assigned roles, and roles hold privileges. | We use roles as the first layer, then add record conditions. |
Overview of the example
The code is in the folder examples/role-permission-resource-authorization-web-app/. It uses only Node 24 built-ins, with no npm install. TypeScript runs directly with node file.ts (Node only strips the types and does not type-check, so we do not use enum or namespace, and the .ts extension must be written in import statements). The current Node documentation lists the node:sqlite module as a release candidate (since v25.7.0); before that it was experimental. This example runs on Node 24, which still prints an ExperimentalWarning, so we run it with --no-warnings to hide that warning.
| File | Purpose |
|---|---|
| db.ts | In-memory database: 6 users, 2 companies, 3 branches, 4 roles, and 4 orders (sample data) |
| policy.ts | A single can(), filterFields(), and the permission table generator |
| server.ts | The vulnerable endpoint compared with the fixed endpoint, with denial logging |
| demo.ts / authz.test.ts | A script that sends real requests to the server, and a node:test suite |
| matrix.expected.txt | The reviewed permission table, used as a snapshot in the test suite |
The login in the example is simulated with the x-user-id header, so the focus stays on authorization. Anyone can forge this header. A real system needs a session issued by the server (see the related article on session lifetime and revocation).
Step 1: Design the permissions: roles, actions, and record rules
Start with a central table that a manager can read. It says which actions each role can perform in principle. Then add the conditions on the record.
// ชั้น (a): บทบาท -> การกระทำที่ทำได้ในหลักการ
const ROLE_ACTIONS: Record<Role, Action[]> = {
staff: ["read", "update"],
manager: ["read", "update", "approve"],
accountant: ["read", "export"],
admin: ["read", "update", "approve", "export"],
};
// ขอบเขตสาขา: บทบาทที่เห็นได้ทั้งบริษัท
const TENANT_WIDE: Role[] = ["accountant", "admin"];This layer only answers whether an accountant can approve (no). It does not yet know whose record it is, so the next layer is needed.
Step 2: A single can() function, deny by default
export function can(user: User, action: Action, o: Order): Decision {
if (!ROLE_ACTIONS[user.role]?.includes(action)) return no("role_lacks_action");
// ชั้น (b): กฎระดับทรัพยากร
if (o.tenant !== user.tenant) return no("other_tenant");
if (!TENANT_WIDE.includes(user.role) && o.branch !== user.branch) return no("other_branch");
const isOwner = o.ownerId === user.id;
if (user.role === "staff" && !isOwner) return no("not_owner");
if (action === "update" && o.status !== "draft") return no("locked_status");
if (action === "approve") {
if (o.status !== "submitted") return no("not_submitted");
if (isOwner) return no("self_approval");
}
if (action === "export" && o.status !== "approved") return no("not_approved");
return yes; // ไปถึงตรงนี้ได้เพราะผ่านทุกข้อด้านบนเท่านั้น
}- Every line returns a reason for denial. Only the last line allows the action. Someone writing a new rule who forgets a condition therefore fails toward denial, not toward opening access.
- An unknown role or action is denied because it is not in the ROLE_ACTIONS table.
- The tenant is always checked first. No role crosses companies, including the admin of that same company. Crossing companies is a separate system that needs its own careful design and heavy logging.
- The business rules are written in readable text: an invoice that is not a draft cannot be edited, only a submitted invoice can be approved, and the creator cannot approve their own invoice (separation of duties). Only an approved invoice can be exported.
- can() is a pure function. It does not touch the database or HTTP, so thousands of cases can be tested in milliseconds.
The third layer is fields. The table below defines which role sees which fields, and the filter function builds a new response from the allowed fields only (an allow list). It does not remove forbidden fields from the original, because a field added later is then hidden by default automatically.
const FIELD_ROLES: Record<string, Role[]> = {
id: ROLES, branch: ROLES, status: ROLES, customer: ROLES, total: ROLES,
phone: ["staff", "manager", "admin"],
costPrice: ["manager", "accountant", "admin"],
};
export function filterFields(user: User, o: Order): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [k, roles] of Object.entries(FIELD_ROLES)) {
if (roles.includes(user.role)) out[k] = (o as any)[k];
}
return out;
}Step 3: The IDOR flaw compared with the fixed endpoint
The two parts are in the same file so the difference is easy to see. The first is code that checks the login and then fetches directly by id. The second is the fixed code.
// แบบผิด: เช็กแค่ว่าล็อกอินแล้ว แล้วดึงตาม id (IDOR)
if (m[1]) {
const row = db.prepare("SELECT * FROM orders WHERE id = ?").get(id);
return row ? send(res, 200, row) : send(res, 404, { error: "not_found" });
} // แบบถูก: scope SQL ด้วย tenant ก่อน แล้วถาม can() ทุกครั้ง
const action: Action = m[4] ? "approve" : req.method === "GET" ? "read" : "update";
const row = db.prepare("SELECT * FROM orders WHERE id = ? AND tenant = ?").get(id, user.tenant);
if (!row) { // ไม่มีจริงหรืออยู่คนละบริษัท ตอบ 404 เหมือนกัน ไม่บอกว่ามีอยู่
if (db.prepare("SELECT 1 FROM orders WHERE id = ?").get(id)) deny(user, action, `order:${id}`, "other_tenant");
return send(res, 404, { error: "not_found" });
}
const order = rowToOrder(row);
const d = can(user, action, order);
if (!d.allow) {
deny(user, action, `order:${id}`, d.reason);
return send(res, 403, { error: "forbidden" }); // ไม่ส่งเหตุผลภายในให้ผู้เรียก
}
if (action === "read") return send(res, 200, filterFields(user, order));
if (action === "approve") db.prepare("UPDATE orders SET status = 'approved' WHERE id = ?").run(id);
else db.prepare("UPDATE orders SET customer = customer || ' (edited)' WHERE id = ?").run(id);- The SQL has AND tenant = ?, which is the first line of defense. Even if can() is edited wrongly in the future, data from another company is never fetched in the first place.
- A record from another company and a record that does not exist both return 404. An attacker cannot guess which ids exist. A record in the same company that the user has no right to returns 403.
- The denial returned to the caller says only forbidden. Detailed reasons such as self_approval go to denied_log on the server, so they do not help someone who is guessing.
- It uses prepared statements with parameters and does not concatenate SQL strings (this is covered in a separate article).
- Other functions that reach the same data, such as export, reports, and the mobile API, must go through can() and the same field filter. The channel that gets forgotten is where the flaw hides.
Running it: send real requests to the server and read the permission table
demo.ts starts the server on 127.0.0.1 with a random port and sends real requests using Node's fetch. All users and data are fictional.
async function call(who: string, uid: number | null, method: string, path: string) {
const res = await fetch(base + path, { method, headers: uid ? { "x-user-id": String(uid) } : {} });
console.log(` ${who.padEnd(18)} ${method.padEnd(4)} ${path.padEnd(22)} -> ${res.status} ${await res.text()}`);
}1) IDOR: Preecha (staff, cnx) ขอ order 1 ของสาขา bkk และ order 4 ของบริษัท zeta
unsafe Preecha GET /unsafe/orders/1 -> 200 {"id":1,"tenant":"acme","branch":"bkk","owner_id":1,"status":"draft","customer":"Customer A","phone":"081-000-0001","total":1200,"cost_price":800}
unsafe Preecha GET /unsafe/orders/4 -> 200 {"id":4,"tenant":"zeta","branch":"kkc","owner_id":6,"status":"draft","customer":"Customer D","phone":"081-000-0004","total":700,"cost_price":450}
2) endpoint ที่แก้แล้ว: คำขอเดียวกัน
fixed Preecha GET /orders/1 -> 403 {"error":"forbidden"}
fixed Preecha GET /orders/4 -> 404 {"error":"not_found"}
3) กรองฟิลด์: order 2 (ต้นทุน 3900, เบอร์โทร) ตามบทบาท
Malee manager GET /orders/2 -> 200 {"id":2,"branch":"bkk","status":"submitted","customer":"Customer B","total":5400,"phone":"081-000-0002","costPrice":3900}
Naree accountant GET /orders/2 -> 200 {"id":2,"branch":"bkk","status":"submitted","customer":"Customer B","total":5400,"costPrice":3900}
Somchai staff GET /orders/2 -> 403 {"error":"forbidden"}
Somchai own order 1 GET /orders/1 -> 200 {"id":1,"branch":"bkk","status":"draft","customer":"Customer A","total":1200,"phone":"081-000-0001"}
4) กฎสถานะและบทบาท
Preecha edit appr. PUT /orders/3 -> 403 {"error":"forbidden"}
Somchai approve POST /orders/2/approve -> 403 {"error":"forbidden"}
Malee approve own POST /orders/2/approve -> 403 {"error":"forbidden"}
Somchai edit draft PUT /orders/1 -> 200 {"id":1,"branch":"bkk","status":"draft","customer":"Customer A (edited)","total":1200,"phone":"081-000-0001"}
ไม่ล็อกอิน GET /orders/1 -> 401 {"error":"login_required"}
5) บันทึกการถูกปฏิเสธ (denied_log)
user=3 read order:1 reason=other_branch
user=3 read order:4 reason=other_tenant
user=1 read order:2 reason=not_owner
user=3 update order:3 reason=locked_status
user=1 approve order:2 reason=role_lacks_action
user=2 approve order:2 reason=self_approval
6) ตารางสิทธิ์จากนโยบาย (Y = อนุญาต)
role.action 1 2 3 4 5 6 7 8 9 10 11 12
staff.read Y Y Y - - - - - - - - -
staff.update Y - - - - - - - - - - -
staff.approve - - - - - - - - - - - -
staff.export - - - - - - - - - - - -
manager.read Y Y Y Y Y Y - - - - - -
manager.update Y - - Y - - - - - - - -
manager.approve - - - - Y - - - - - - -
manager.export - - - - - - - - - - - -
accountant.read Y Y Y Y Y Y Y Y Y - - -
accountant.update - - - - - - - - - - - -
accountant.approve - - - - - - - - - - - -
accountant.export - - Y - - Y - - Y - - -
admin.read Y Y Y Y Y Y Y Y Y - - -
admin.update Y - - Y - - Y - - - - -
admin.approve - - - - Y - - Y - - - -
admin.export - - Y - - Y - - Y - - -
columns: 1=own/draft 2=own/submitted 3=own/approved 4=branch/draft 5=branch/submitted 6=branch/approved 7=other_branch/draft 8=other_branch/submitted 9=other_branch/approved 10=other_tenant/draft 11=other_tenant/submitted 12=other_tenant/approvedReading the output item by item
- Item 1: the vulnerable endpoint returns order 1 from the Bangkok branch and order 4 from company zeta to the Chiang Mai employee, with every field including cost_price and tenant.
- Item 2: the same requests to the fixed endpoint get 403 (different branch) and 404 (different company). No data leaks.
- Item 3: for the same order 2, the manager sees both the phone number and the cost. The accountant sees the cost but not the phone number. A staff member who is not the owner gets 403. For their own order 1, the staff member sees the phone number but not the cost.
- Item 4: an approved invoice cannot be edited, staff cannot approve, and a manager cannot approve an invoice they created. A staff member can edit their own draft invoice, and a request without a login gets 401.
- Item 5: every denial has a line in denied_log with the user, the action, the record, and the internal reason. This is used for review after the fact and for alerts when attempts repeat.
- Item 6: the permission table is generated from the real can(), not written by hand. Each column is a relationship to the record (own, branch, other_branch, other_tenant) multiplied by a status (draft, submitted, approved). You can see at once that staff.update has only one allowed cell, their own draft records, and that other_tenant is a dash across the whole row.
The deliberately vulnerable endpoint (/unsafe) is used only with fictional data on localhost. Nothing here is used to attack any other system, and that pattern must not be copied into real use.
Test suite: walk the whole table so the policy cannot change unnoticed
authz.test.ts runs with node --no-warnings --test authz.test.ts and gives 4 passes across 4 cases.
// 1) ตารางสิทธิ์ต้องตรงกับไฟล์ที่ตรวจทานแล้ว: แก้นโยบายแล้วตารางเปลี่ยน test จะล้ม
// ต้องเปิดดู diff และแก้ matrix.expected.txt อย่างตั้งใจ
test("permission matrix equals the reviewed snapshot", () => {
assert.equal(buildMatrix() + "\n", readFileSync(new URL("./matrix.expected.txt", import.meta.url), "utf8"));
});// 2) กฎตายตัวที่ต้องไม่เปลี่ยน ตรวจเดินทุกช่องของตาราง ไม่ขึ้นกับ snapshot
test("invariants hold for every role x action x relation x status", () => {
for (const role of ROLES) for (const action of ACTIONS) for (const rel of RELATIONS) for (const st of STATUSES) {
const { user, order } = scenario(role, rel, st);
const d = can(user, action, order);
const where = `${role}.${action} ${rel}/${st}`;
if (rel === "other_tenant") assert.equal(d.allow, false, "tenant leak: " + where);
if (action === "update" && st !== "draft") assert.equal(d.allow, false, "edit locked: " + where);
if (action === "approve" && rel === "own") assert.equal(d.allow, false, "self approve: " + where);
if (role !== "accountant" && role !== "admin" && rel === "other_branch") assert.equal(d.allow, false, "branch leak: " + where);
if (role === "staff" && rel !== "own") assert.equal(d.allow, false, "staff sees others: " + where);
}
});- Snapshot: if someone edits the policy and any cell changes from a dash to Y, the test suite fails. A person must open the diff of matrix.expected.txt, read it, and confirm it. Granting a permission therefore becomes a decision visible in code review.
- Fixed rules: crossing companies must always be denied. An invoice that is not a draft cannot be edited. A creator cannot approve their own invoice. Staff see only their own records. A branch-level role cannot cross branches. These rules guard against the case where someone updates the snapshot to match without thinking.
- Defaults: an unknown role or action must be denied.
- Through real HTTP: confirms that IDOR is closed, the cost field does not reach staff, and denied_log has the two expected lines.
This test suite checks that the code follows the rules we wrote. It does not prove that the rules are correct for the business. That part needs the work owner to read the permission table and sign it off.
Why check on the server even when the screen hides the button
The browser is in the user's hands. A user can open developer tools, send requests with curl, or write a script that calls the API. Hiding a button keeps the menu clean and reduces confusion, but it is not a security measure. A practical approach is for the server to send the list of allowed actions (for example canUpdate and canApprove, computed from can()) along with the data, and for the screen to use it to show or hide buttons. The screen holds no copy of the rules, so it cannot drift, and the server still checks again when it receives the actual command.
Toward a real system: what the example does not do
- Authentication: use a session issued and verified on the server, an HttpOnly cookie, and a suitable session lifetime. Never trust a header sent by the user, as this example does.
- One place for the policy: make every entry point (web, API, background jobs, export) call a single function. Scattering if role === conditions across handlers is the source of flaws that disappear one spot at a time.
- The database as a second line of defense: PostgreSQL has row-level security, so the database can filter rows by tenant itself. Even if the application code forgets to scope, nothing leaks (the database roles and the per-connection tenant setting must be designed well; see the article on separating data for multiple companies).
- Permission caching and revocation: if roles are embedded in a long-lived token, a person who has been removed from a position keeps the old permissions until the token expires. Read permissions from the database or a short-lived cache, and have a way to cut a session immediately.
- Administrators and impersonation: if you need it, log who impersonated whom, when, and why, and limit the actions that must not be done on someone's behalf, such as approval.
- Personal data under the PDPA: phone numbers, ID numbers, and salaries should be visible only to the roles that need them for their duties, and access to sensitive data should be logged. Unneeded fields should never leave the API in the first place. The legal side needs review by a specialist for each case.
- Permission changes themselves need a history of who changed what for whom (see the article on audit trails).
- Multi-level approval and temporary delegation of authority are more complex rules than the example. They should be added to can() openly and tested.
Hypothetical examples: applying it to three businesses
A multi-branch quotation and sales order system
The key relationships are the record owner and the branch. A branch manager approves discounts above the limit, but may not approve their own records. Cost price and gross profit are fields hidden from sales staff by default. This example extends to approval-limit rules by adding a condition in can().
An accounting and invoice system
The document status determines the permissions. An issued invoice or a closed accounting period must be locked. A correction must be made by issuing a new credit note or amended document, not by overwriting the original. This matches locked_status in the example, and an audit trail should always go with it.
A customer portal on a system shared by several companies
External users have a single role but must see only their own company's data. Scoping every SQL statement by tenant, and returning 404 when an id belongs to the wrong company, matter most here. The tenant should be kept in the server-side session data and not accepted from request parameters.
Common mistakes and a checklist
- Checking only that the user is logged in, then fetching data by an id taken from a parameter.
- Hiding the button on the screen but not checking on the server, or checking only the main endpoint and forgetting export and the mobile API.
- Assuming a UUID cannot be guessed, so no authorization check is needed (OWASP says the check is still required).
- Accepting tenant or role from a body or query sent by the user, instead of reading it from the session.
- Sending every field of the database row to the screen and letting the screen choose what to show.
- Defaulting to allow, then banning case by case.
- Not logging denials, so you never learn that someone is trying to guess ids.
- Changing the policy without anyone seeing whose permissions changed, because there is no permission table and no test.
- Make a role x action x status table and have the work owner sign it off.
- Have a single authorization function that denies by default, and make every route to the data call it.
- Scope every SQL statement that reads business data by tenant (and by branch where relevant), and use parameters.
- Build responses from an allow list of fields per role.
- On denial, log it with the internal reason, but do not tell the caller that reason.
- Have a test suite that walks the whole table, with a snapshot that a person reads every time permissions change.
- Test by changing ids and calling the API directly with an account for each role in a test system, before going live and after every major change.
Cautions for this example: there is no real login system, no rate limit, no body size limit, and no row-level security in the database. It changes no real data except appending to a customer name. The roles and rules are hypothetical and do not match any particular business. Use it as a learning model, not as production-ready code, and it is not legal advice on the PDPA.
References
- OWASP — Authorization Cheat Sheet (deny by default, least privilege, validate every request, tests) (accessed 2026-11-21)
- OWASP Top 10 2021 — A01 Broken Access Control (deny by default, record ownership, server-side, logging) (accessed 2026-11-21)
- OWASP — Insecure Direct Object Reference Prevention Cheat Sheet (accessed 2026-11-21)
- OWASP — Logging Cheat Sheet (authorization failures as events to log) (accessed 2026-11-21)
- NIST CSRC — Role Based Access Control (project page, archived) (accessed 2026-11-21)
- Node.js — SQLite (node:sqlite) stability, prepared statements and parameter binding (accessed 2026-11-21)
- Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)




