Skip to content

Interview PrepAuthorization · Advanced

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:

LayerChecksExample
Front endNothing, for security; only what to showHide "Refund" for customers
Gateway or middlewareCoarse: logged in, has a role or scope/admin/* requires admin
Service or handlerThis user, this recordOrder belongs to the user's tenant and they are support staff
DatabaseLast line of defenceRow-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.

usersrolespermissionsAshaBensupportviewerorders:readorders:refund
Users get roles, roles get permissions. Asha's support role gives her both permissions. Ben's viewer role gives only read. To let all support staff do something new, you change one role, not every user.

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)
  )
}
  1. A subject attribute: the user works in support.
  2. Subject and resource compared: same region as the order.
  3. Resource attributes: amount and status.
  4. 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".

RBACABAC
Decision based onRoles heldAttributes and rules
Expresses ownership, region, timePoorlyWell
Audit "who can do X?"Easy: list role membersHard: depends on data
RiskRole explosionRules no one understands
SpeedVery fastDepends on attribute lookups
Typical fitAdmin consoles, internal toolsHealthcare, 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:

PartJob
Policy enforcement pointYour middleware or service, which asks and then obeys
Policy decision pointThe engine that evaluates policies
Policy administrationWhere policies are written, reviewed and deployed
Policy informationWhere 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:asha

Reading 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.

LevelExample rule
CoarseSupport staff may view orders
ObjectAsha may view order 1043 because it is her own
FieldSupport 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' }
  1. Stop on a role already visited, so a mistaken loop in the configuration cannot recurse forever.
  2. Walk down to every role this one includes.

Watch out for:

ProblemFix
"Why does Ben have access?" is hard to answerLog and show the inheritance path
Access added high in a tree reaches too farBreak inheritance for sensitive folders
Deep hierarchies nobody understandsKeep 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))
  })
  1. Route-level check: does the user have the permission at all?
  2. A shared object-level check, used everywhere, so the rules live in one place.
  3. Coarse middleware runs before any database work.
  4. Tenant check first, answering 404 so users cannot even learn that another tenant's order exists.
  5. 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:

TableColumns
permissionskey such as orders:refund, description
rolesid, tenant_id (null for built-in), name
role_permissionsrole_id, permission_key
role_assignmentsuser_id, role_id, tenant_id, optional scope such as team:42, expires_at
audit_logWho changed which assignment, when

Design decisions to talk through:

  1. Permissions in code, roles in data. Developers add permissions with features. Admins combine them into roles without a release.
  2. Per-tenant assignment. Asha is admin in Acme's workspace and viewer in Globex's.
  3. Scopes. "Admin of team 42" without being admin of the whole company.
  4. Time-limited assignments, for temporary elevated access that expires on its own.
  5. Caching. Compute effective permissions at login or on change, cache them, and clear the cache when assignments change.
  6. Separation of duties. The person who creates a payout may not approve it, enforced as a rule, not just a role.
  7. 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.

policy managementpolicies + data, reviewed, versionedordersenforcesenginedecidesbillingenforcesenginedecidesreportsenforcesenginedecides
Decide locally, manage centrally. The rules are written and reviewed in one place, then copied to an engine next to every service. A decision is a local call, so it is fast and still works if the central service is briefly down.
OptionGoodWatch out
Each service writes its own checksSimple at firstRules drift apart; hard to audit
Central authorization APIOne source of truthA network call per check; must never go down
Policy engine beside each serviceFast, local, consistentDistributing policies and data
Relationship engine, Zanzibar-styleSharing and nested resourcesKeeping 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:

ModelIsolationCostFits
Shared tables with a tenant_id columnLogicalLowestMost SaaS, many small tenants
A schema per tenantStrongerMediumHundreds of tenants
A database per tenantStrongestHighestLarge 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)
})
  1. 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.
  2. Every row the app can see or touch must match the current tenant setting.
  3. Set the tenant for this transaction only; the true makes it local, so it cannot leak to the next request using the same pooled connection.
  4. 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:

PlaceRule
Cache keystenant:{id}:orders:{orderId}, never just orders:{orderId}
File storagePaths start with the tenant ID; signed URLs checked
Search indexesTenant filter on every query
Background jobsJob carries the tenant ID; worker sets it before any query
Logs and analyticsTenant ID on every record; no cross-tenant exports
IDs in URLsReturn 404, not 403, for other tenants' records (question 173)

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Authentication & Identity
Cookies & sessions
Authentication
Tokens
OAuth & OIDC
Enterprise SSO
Directories
Authorization
Other topics
Nothing picked yet