Architecture
Roles are not enough
Admin, moderator, viewer. Then somebody needs to refund orders but not touch pricing, and your three roles become five, then nine. A permission map of eight modules by six actions, and the escalation hole I found writing this up.
Every internal tool starts with three roles. Admin can do everything, moderator can do most things, viewer can look. It is enough for the first year and it is enough right up until the first request that does not fit.
Somebody in accounts needs to issue refunds but must not be able to change device prices. A support hire needs to read customer records and reply to tickets but not delete anything. A contractor needs to upload device data for two weeks and then needs that access gone. None of these people is a moderator, and none of them is an admin.
The usual response is to add roles. Support moderator, finance moderator, content moderator. That works twice and then you have nine roles, most of which exist for one person, and no way to answer what can this account actually do without reading the source.
The grid
The alternative is to stop treating a role as a bundle and store the grid directly. Eight modules by six actions:
modules: admin_management, agent_management, analytics, device_management,
logs, order_management, support, user_management
actions: view, create, edit, delete, assign, replyThat last point matters more than it looks. A dense grid of forty eight checkboxes would be unusable, so the actions available per module are a property of the module, not of the grid. Assign exists because orders are assigned to agents. Reply exists because support tickets are replied to. Modelling them as universal actions and then disabling most of them would be a worse interface and a worse data model.
The permissions themselves are a JSON column on the admin record, parsed once at authentication:
const [adminUsers] = await db.query(
'SELECT id, name, email, role, is_active, permissions FROM admins WHERE id = ? AND is_active = 1',
[decoded.adminId]
)
const admin = adminUsers[0]
admin.permissions = admin.permissions ? JSON.parse(admin.permissions) : null
req.admin = adminTwo things about that query are deliberate. The permissions are read from the database on every request rather than carried in the JWT, so revoking access takes effect immediately instead of whenever the token happens to expire. And `is_active = 1` is part of the lookup, so a deactivated admin is rejected at the same moment for the same reason, without a separate check anybody can forget.
Putting permissions in the token is the performance optimisation everyone reaches for and the one that makes revocation impossible. One indexed primary key lookup per request is not your bottleneck.
The check is a middleware factory
Each route declares what it needs, in the route definition, where somebody reading it will see it:
router.post('/specs',
adminAuth,
checkPermission('device_management', 'create'),
async (req, res) => { /* ... */ })And the factory:
const checkPermission = (module, action) => (req, res, next) => {
const admin = req.admin
if (admin.role === 'developer' || admin.role === 'admin') return next()
if (!admin.permissions) {
return res.status(403).json({ message: 'No permissions configured' })
}
const modulePerms = admin.permissions[module]
if (!modulePerms) {
return res.status(403).json({ message: `No access to ${module}` })
}
if (modulePerms === true || (typeof modulePerms === 'object' && modulePerms[action] === true)) {
return next()
}
res.status(403).json({ message: `Permission denied: ${module}.${action}` })
}Note that a module's value can be either the literal true or an object of actions. That shorthand means give this person everything in this module without enumerating six keys, which is what you actually want for the person who owns support. It is a small accommodation to how permissions are really assigned, and it costs one extra branch.
The error messages name the exact permission that was missing. That is a deliberate trade: it leaks the shape of the permission model to an authenticated admin, which is fine, and it turns every access problem into a self-diagnosing one. Without it, every 403 becomes a message to a developer.
One action per route is not always enough
Two real cases broke the single action assumption, and both are worth knowing about because they will happen to you too.
A bulk device upload inserts new records and updates existing ones in the same commit. Guarding it with create alone would let somebody with only create silently modify existing devices. Guarding it with edit alone has the mirror problem. It genuinely needs both:
const checkAllPermissions = (module, actions) => (req, res, next) => {
// ...
const missing = actions.filter((action) => !hasPermission(admin, module, action))
if (missing.length === 0) return next()
res.status(403).json({
message: `Permission denied: ${module}.${missing.join(' + ' + module + '.')}`,
})
}The other direction: uploading a device image happens from both the create flow and the edit flow, so either permission should allow it. Requiring both would block somebody who is legitimately only editing.
So there are three guards: all of these, any of these, and exactly this one. The reason to build the combinators rather than write bespoke checks inside the handlers is that a check inside a handler is invisible from the route table, and the route table is where anybody auditing the system will look.
The escalation hole
I went looking for the guard that stops an admin creating an account more powerful than themselves, because I remembered writing one. What is actually there is narrower than I remembered.
if (requestedRole === 'developer' && currentRole !== 'developer') {
return res.status(403).json({ message: 'Only developers can create developer accounts' })
}The role escalation is blocked: you cannot mint a developer unless you are one, and the edit route separately refuses to let a non-developer touch a developer account or promote anyone into that role. That is the right set of role guards.
What is missing is the equivalent for permissions. An admin holding `admin_management.create` can create a moderator with any permission map at all, including modules they themselves cannot touch. Someone with support access and the ability to create admins can create an account with device management and log in as it.
The fix is not complicated. Granted permissions have to be a subset of the granter's:
function isSubsetOfGranter(requested, granter) {
if (granter.role === 'developer' || granter.role === 'admin') return true
for (const [module, perms] of Object.entries(requested ?? {})) {
const held = granter.permissions?.[module]
if (!held) return false
if (perms === true && held !== true) return false
if (typeof perms === 'object') {
for (const [action, wanted] of Object.entries(perms)) {
if (wanted === true && !hasPermission(granter, module, action)) return false
}
}
}
return true
}It belongs on both the create and the edit route, because otherwise you can create a legal account and then escalate it. That is the sort of two-step hole that is easy to leave when you only guard creation.
Any system where a permission grants the ability to grant permissions needs an explicit subset check. Guarding the role is not the same thing, and the gap between the two is invisible until someone goes looking.
I am including this because a write-up that only shows the parts that went well is not much use to anyone. The permission model is good. This hole is real, it is exploitable only by someone you already trusted with admin creation, and it should still be closed.
Permissions without logging are half a system
Granular permissions tell you what somebody could do. They tell you nothing about what they did, and the second question is the one you get asked in an incident.
await db.query(
`INSERT INTO activity_logs
(admin_id, user_id, action, level, message, details, ip_address, user_agent, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())`,
[adminId, userId, action, level, message, detailsJson, ipAddress, userAgent]
)Who, what, against whom, with what payload, from where, on what client, when. The one design decision worth copying is that the action is a namespaced string, and the categories used for filtering are derived from prefixes rather than stored separately:
const CATEGORY_FILTERS = {
security: `(action LIKE 'admin_%' OR action LIKE '%login%')`,
orders: `(action LIKE 'order_%')`,
devices: `(action LIKE 'brand_%' OR action LIKE 'model_%' OR action LIKE 'spec_%')`,
bans: `(action LIKE 'ban_%')`,
}That means a new action gets categorised for free if it follows the naming convention, and there is no second field to keep in step. The cost is that the filters are prefix matches rather than indexed equality, which is fine at the volumes an admin panel produces and would not be at application log volumes.
One more detail: the whole logging call is wrapped in a try/catch that swallows errors. A failure to write an audit entry must not fail the operation the admin was performing. That is the correct trade for an internal tool and the wrong one for a regulated system, where an unloggable action is an action you must refuse. Know which you are building.
What to take from this
- When roles start multiplying to serve one person each, store the grid instead of the bundle.
- Let each module define which actions are meaningful. A dense matrix of every action against every module is a worse interface and a worse model.
- Read permissions from the database per request, not from the token, or you cannot revoke anything.
- Fold the active check into the same lookup so it cannot be forgotten separately.
- Declare the requirement in the route definition, where an auditor will see it.
- Build all-of and any-of combinators. Real routes need both, and a check hidden in a handler is invisible.
- Name the missing permission in the error. It costs nothing and stops every 403 becoming a support ticket.
- If a permission lets someone grant permissions, enforce a subset check, on create and on edit.
- Log every privileged action with actor, target, payload and origin, and derive categories from a naming convention.
The underlying shift is from asking who is this person to asking what is this person allowed to do here. Roles answer the first question and only approximate the second, which is why they keep multiplying. The admin panel this belongs to, including the review queue and abuse tooling that sit behind the same guards, is described in the SellPrime case study.