Appearance
Authorization
166. What is authorization, and where should it be enforced?
The short answer
Authorization decides whether an authenticated identity may perform a specific action on a specific resource, such as "may Asha refund order 1043?". It must be enforced on the server, at every entry point, for every request, as close to the data as practical: in API middleware for coarse checks, and in the service or data layer for checks about the particular record. The front end may hide buttons for a nicer experience, but that is never security, because anyone can call the API directly. Deny by default.
Where checks belong:
| Layer | Checks | Example |
|---|---|---|
| Front end | Nothing, for security; only what to show | Hide "Refund" for customers |
| Gateway or middleware | Coarse: logged in, has a role or scope | /admin/* requires admin |
| Service or handler | This user, this record | Order belongs to the user's tenant and they are support staff |
| Database | Last line of defence | Row-level security by tenant (question 176) |
Ask the question in a fixed shape. Every check answers "may subject do action on resource, in this context?". Writing the code in that shape, can(user, 'refund', order), keeps rules in one place and makes them easy to audit.
167. What is role-based access control (RBAC)?
The short answer
RBAC grants permissions to roles, and assigns roles to users. Permissions are actions such as orders:read or orders:refund; roles bundle them, such as support with read and refund, or viewer with read only. Asha gets the support role, and so gets its permissions. Changing what support staff may do is one change to the role, not to hundreds of users. RBAC is simple to understand and audit, and fits most business apps. Its weakness is that it cannot easily express conditions like "only for orders in your own region" without an explosion of roles.
Check permissions in code, not role names:
ts
const ROLE_PERMISSIONS: Record<Role, Permission[]> = {
viewer: ['orders:read'],
support: ['orders:read', 'orders:refund'],
admin: ['orders:read', 'orders:refund', 'users:manage'],
}
export const hasPermission = (user: User, p: Permission) =>
user.roles.some((r) => ROLE_PERMISSIONS[r].includes(p))
if (!hasPermission(req.user, 'orders:refund')) throw new HttpError(403, 'Not allowed') // not: roles.includes('support')Checking orders:refund rather than role === 'support' means a new role, such as finance, can be given refund rights by changing the mapping, without finding every if in the code.
168. What is attribute-based access control (ABAC)?
The short answer
ABAC decides access by evaluating rules over attributes of the subject, such as department, clearance or country; the resource, such as its owner, region, sensitivity or status; the action; and the environment, such as time of day, network or device. A rule might say "support staff may refund orders under £500 in their own region, during working hours". It is far more expressive than roles alone and avoids creating a role for every combination. The cost is that rules are harder to understand, test and audit.
ts
type Ctx = { user: User; order: Order; now: Date }
export function canRefund({ user, order, now }: Ctx): boolean {
return (
user.department === 'support' && // (1)
user.region === order.region && // (2)
order.totalPence <= 50_000 && // (3)
order.status === 'delivered' &&
now.getUTCHours() >= 8 && now.getUTCHours() < 18 // (4)
)
}- A subject attribute: the user works in support.
- Subject and resource compared: same region as the order.
- Resource attributes: amount and status.
- An environment attribute: working hours.
With RBAC alone, covering these combinations would take roles like support-uk-under-500, which nobody can manage.
169. What are the differences between RBAC and ABAC?
The short answer
RBAC asks "does the user have a role that includes this permission?". It is simple, fast and easy to audit, but coarse. ABAC asks "do the attributes of the user, resource, action and environment satisfy the policy?". It is precise and handles context such as ownership, region and time, but rules are harder to reason about. Most real systems combine them: roles give the broad permission, and attribute checks narrow it, for example "has the support role and the order is in their region".
| RBAC | ABAC | |
|---|---|---|
| Decision based on | Roles held | Attributes and rules |
| Expresses ownership, region, time | Poorly | Well |
| Audit "who can do X?" | Easy: list role members | Hard: depends on data |
| Risk | Role explosion | Rules no one understands |
| Speed | Very fast | Depends on attribute lookups |
| Typical fit | Admin consoles, internal tools | Healthcare, finance, multi-region |
170. What is policy-based access control?
The short answer
Policy-based access control means writing authorization rules as policies, kept separately from application code, in a policy language, and evaluating them with a policy engine. The app asks the engine "may this user do this action on this resource?" and gets allow or deny. Policies can express RBAC, ABAC or both, can be reviewed and versioned like code, and can be shared by many services. Well-known engines include Open Policy Agent, which uses a language called Rego, and Cedar, an open-source policy language from AWS.
The idea in pictures, as an architecture:
| Part | Job |
|---|---|
| Policy enforcement point | Your middleware or service, which asks and then obeys |
| Policy decision point | The engine that evaluates policies |
| Policy administration | Where policies are written, reviewed and deployed |
| Policy information | Where the engine gets attributes, such as the user directory |
A Cedar policy, readable almost as English:
text
permit (
principal in Role::"support",
action == Action::"refund",
resource
) when { resource.region == principal.region && resource.total < 500 };Why separate policies from code. A security reviewer can read every rule in one place. A rule change does not need a code release. The same policy is applied identically by the Node API, the Python worker and the admin tool.
171. What is fine-grained authorization?
The short answer
Fine-grained authorization means deciding access at the level of individual objects and fields, not just whole features. Not "can edit documents" but "can edit this document", or "can see this customer's email but not their card details". The most popular model for it is relationship-based access control, ReBAC, as in Google Docs: access follows relationships, such as "Asha is an editor of folder X, and document Y is in folder X, so Asha can edit Y". Google's internal system for this, Zanzibar, inspired open-source engines such as OpenFGA and SpiceDB.
Relationships as data, the ReBAC idea:
text
document:q3-report#parent @ folder:finance
folder:finance#editor @ group:finance-team#member
group:finance-team#member @ user:ashaReading it bottom to top: Asha is a member of the finance team. The finance team are editors of the finance folder. The Q3 report is in the finance folder. The engine follows this chain, and answers "may user:asha edit document:q3-report?" with yes.
| Level | Example rule |
|---|---|
| Coarse | Support staff may view orders |
| Object | Asha may view order 1043 because it is her own |
| Field | Support may see the order's items, but not the full card number |
When you need it. Sharing features, such as "share this file with Ben", nested folders or teams, and per-record permissions. For a simple internal tool, roles plus ownership checks are enough.
172. What are permission inheritance and role hierarchies?
The short answer
A role hierarchy lets senior roles automatically include the permissions of junior ones: admin inherits everything editor can do, which inherits everything viewer can do. You then define each permission once, at the lowest role that needs it. Permission inheritance on resources means access given on a container flows down to what it contains: editing rights on a project apply to every document in it, as with folders on a file share. Both reduce repetition, but make it harder to see why someone has access, so tools must be able to explain the chain.
ts
const INHERITS: Record<Role, Role[]> = { viewer: [], editor: ['viewer'], admin: ['editor'] }
function effectiveRoles(role: Role, seen = new Set<Role>()): Set<Role> {
if (seen.has(role)) return seen // (1)
seen.add(role)
for (const parent of INHERITS[role]) effectiveRoles(parent, seen) // (2)
return seen
}
effectiveRoles('admin') // Set { 'admin', 'editor', 'viewer' }- Stop on a role already visited, so a mistaken loop in the configuration cannot recurse forever.
- Walk down to every role this one includes.
Watch out for:
| Problem | Fix |
|---|---|
| "Why does Ben have access?" is hard to answer | Log and show the inheritance path |
| Access added high in a tree reaches too far | Break inheritance for sensitive folders |
| Deep hierarchies nobody understands | Keep to a few levels |
173. What is authorization middleware?
The short answer
Authorization middleware is a function in the request pipeline, after authentication, that checks whether req.user may perform the requested action before the handler runs, and responds 403 if not. It is ideal for coarse checks that depend only on the route and the user, such as "requires the orders:refund permission" or "requires the admin role". Checks that depend on the specific record, such as "is this the user's own order?", need the record, so they run in the handler or service, often through a shared authorize function.
ts
export const requirePermission = (p: Permission) =>
(req: Request, res: Response, next: NextFunction) =>
hasPermission(req.user!, p) ? next() : next(new HttpError(403, 'Not allowed')) // (1)
export async function authorize<R>(user: User, action: Action, resource: R) {
if (!(await policy.can(user, action, resource))) throw new HttpError(403, 'Not allowed') // (2)
}
router.post('/orders/:id/refund',
requirePermission('orders:refund'), // (3)
async (req, res) => {
const order = await orders.findById(req.params.id)
if (!order || order.tenantId !== req.user!.tenantId) throw new HttpError(404, 'Not found') // (4)
await authorize(req.user!, 'refund', order) // (5)
res.json(await refunds.create(order))
})- Route-level check: does the user have the permission at all?
- A shared object-level check, used everywhere, so the rules live in one place.
- Coarse middleware runs before any database work.
- Tenant check first, answering
404so users cannot even learn that another tenant's order exists. - The record-level rule, such as region and amount limits.
174. How would you design a role and permission system?
The short answer
Start from permissions, named resource:action such as orders:refund, and have code check only permissions. Group them into roles that match real jobs. Assign roles to users per tenant, and optionally per resource scope such as a team or project. Add ownership and attribute checks for record-level rules. Keep a small set of built-in roles, and allow custom roles only if customers need them. Store role assignments in the database, cache each user's effective permissions, log every change, and let admins see why a user has access.
The tables:
| Table | Columns |
|---|---|
permissions | key such as orders:refund, description |
roles | id, tenant_id (null for built-in), name |
role_permissions | role_id, permission_key |
role_assignments | user_id, role_id, tenant_id, optional scope such as team:42, expires_at |
audit_log | Who changed which assignment, when |
Design decisions to talk through:
- Permissions in code, roles in data. Developers add permissions with features. Admins combine them into roles without a release.
- Per-tenant assignment. Asha is admin in Acme's workspace and viewer in Globex's.
- Scopes. "Admin of team 42" without being admin of the whole company.
- Time-limited assignments, for temporary elevated access that expires on its own.
- Caching. Compute effective permissions at login or on change, cache them, and clear the cache when assignments change.
- Separation of duties. The person who creates a payout may not approve it, enforced as a rule, not just a role.
- Explainability. An admin screen answering "why can Ben refund?" with the role and assignment that grant it.
175. How would you design centralized authorization for multiple services?
The short answer
Separate deciding from enforcing. A central authorization service, or a policy engine with centrally managed policies, holds the rules and the data they need, such as roles, relationships and attributes. Each service enforces by asking it "may this user do this action on this resource?", through an SDK or a sidecar. To keep latency low, run the decision engine next to each service with policies and data pushed to it, cache decisions briefly, and send coarse claims in tokens. Log every decision centrally for audit.
| Option | Good | Watch out |
|---|---|---|
| Each service writes its own checks | Simple at first | Rules drift apart; hard to audit |
| Central authorization API | One source of truth | A network call per check; must never go down |
| Policy engine beside each service | Fast, local, consistent | Distributing policies and data |
| Relationship engine, Zanzibar-style | Sharing and nested resources | Keeping relationship data in sync |
Keep the coarse parts in tokens. The token's scopes and tenant ID let the gateway reject obvious misses early. Object-level questions still go to the engine.
176. How would you implement tenant isolation in a multi-tenant SaaS application?
The short answer
Every piece of data belongs to a tenant, and no query may run without the tenant filter. Get the tenant from the authenticated token or session, never from a header the client chooses. Enforce it in layers: a data-access layer that adds tenant_id to every query automatically; database row-level security as a safety net, so even a forgotten filter returns nothing; tenant-prefixed keys in caches, queues and file storage; and per-tenant encryption keys or separate databases for customers who need stronger isolation. Write a check that fails the build if any table lacks a tenant_id.
The three common models:
| Model | Isolation | Cost | Fits |
|---|---|---|---|
Shared tables with a tenant_id column | Logical | Lowest | Most SaaS, many small tenants |
| A schema per tenant | Stronger | Medium | Hundreds of tenants |
| A database per tenant | Strongest | Highest | Large or regulated customers |
Row-level security in PostgreSQL, the safety net:
sql
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY; -- (1)
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id')::uuid); -- (2)ts
export async function withTenant<T>(tenantId: string, work: (tx: Tx) => Promise<T>) {
return db.transaction(async (tx) => {
await tx.query(`SELECT set_config('app.tenant_id', $1, true)`, [tenantId]) // (3)
return work(tx)
})
}
app.get('/api/orders', requireUser, async (req, res) => {
res.json(await withTenant(req.user!.tenantId, (tx) => tx.query('SELECT * FROM orders'))) // (4)
})- Apply the policy even to the table's owner. By default the owner bypasses row-level security, and the app's database user must also not be a superuser.
- Every row the app can see or touch must match the current tenant setting.
- Set the tenant for this transaction only; the
truemakes it local, so it cannot leak to the next request using the same pooled connection. - The query has no
WHERE tenant_id, yet returns only this tenant's orders. If a developer forgets the filter elsewhere, the database still enforces it.
Places tenant data leaks that are not the database:
| Place | Rule |
|---|---|
| Cache keys | tenant:{id}:orders:{orderId}, never just orders:{orderId} |
| File storage | Paths start with the tenant ID; signed URLs checked |
| Search indexes | Tenant filter on every query |
| Background jobs | Job carries the tenant ID; worker sets it before any query |
| Logs and analytics | Tenant ID on every record; no cross-tenant exports |
| IDs in URLs | Return 404, not 403, for other tenants' records (question 173) |