A Permission Checked but Never Granted Is a Silent 403

A Permission Checked but Never Granted Is a Silent 403

#rbac#authorization#nestjs#typescript#compliance

Sixth post from the compliance-ready backend kit. The last one was database-per-tenant, and this one depends on it.

Start with an admission. The kit seeds three permissions into every tenant: users:read, users:write and roles:manage. Its admin role holds all three. Only one of them is checked anywhere. There is one permission-protected route, GET /api/users, and it requires users:read. No route requires the other two, because the routes they would guard do not exist yet.

That is not a security hole. Nothing is reachable that should not be. But read the grants table in an access review and you would conclude the kit gates user writes and role management behind specific permissions. It gates nothing; there is nothing there. A permission granted but never checked is a control on paper.

The kit’s docs say so for roles:manage. I am saying it for both here, because the opposite drift is the one that hurts, and it is much harder to see.

Two ways the catalogue drifts

Role-based access control has two halves that live in different places. The check lives in code, on a route. The grant lives in data, in a role_permissions table. Nothing in most stacks forces them to agree.

DriftWhat users seeWhat a reviewer sees
Checked, never granteda permanent 403 that looks like the caller’s bugnothing, the denial says only “forbidden”
Granted, never checkednothing at alla capability that does not exist

The first is a support ticket that nobody can close. The second is an overclaim. Both are exactly what an access-control review under HIPAA 164.312(a)(1), PCI DSS Requirement 7 or SOC 2 CC6.3 is meant to surface, so it is worth not letting them happen quietly.

One list in code

The kit’s first defence is boring and effective. Every permission string is declared once, in a framework-free package that both sides import:

// packages/common/src/index.ts
export const PERMISSION_KEYS = {
  usersRead: "users:read",
  usersWrite: "users:write",
  rolesManage: "roles:manage",
} as const;

export type PermissionKey = (typeof PERMISSION_KEYS)[keyof typeof PERMISSION_KEYS];

The route uses the constant:

@Get()
@TenantAuthenticated(PERMISSION_KEYS.usersRead)
list() {
  return this.users.list();
}

And provisioning seeds from a list built on the same constants, so a route checking "user:read" while the seed inserts "users:read" cannot happen. The typo class is gone.

What the list does not catch

Here is the gap in the kit as it stands. The seed list is typed as an array:

export const DEFAULT_PERMISSIONS: readonly PermissionDefinition[] = [
  { key: PERMISSION_KEYS.usersRead, description: "List and view users in this tenant" },
  // ...
];

Add a fourth key to PERMISSION_KEYS, use it on a route, and forget to add it here. It compiles. Every element is a valid PermissionDefinition; an array has no idea which keys it is supposed to contain.

An object keyed by permission does, if you ask with satisfies:

const PERMISSION_DESCRIPTIONS = {
  "users:read": "List and view users in this tenant",
  "users:write": "Create, modify, and disable users in this tenant",
  "roles:manage": "Create roles and change their permission grants",
} as const satisfies Record<PermissionKey, string>;

export const DEFAULT_PERMISSIONS = (Object.keys(PERMISSION_DESCRIPTIONS) as PermissionKey[]).map(
  (key) => ({ key, description: PERMISSION_DESCRIPTIONS[key] }),
);

I checked both failure cases against tsc before writing this. Drop roles:manage and the build fails with Property '"roles:manage"' is missing. Misspell it as role:manage and it fails with Object literal may only specify known properties. The compiler now enforces the step people forget.

The 403 that every test passes

Now the drift the catalogue cannot see, and the reason this post follows the database-per-tenant one.

Provisioning seeds the catalogue into a new tenant’s database and grants the admin role every permission that exists at that moment:

INSERT INTO role_permissions (role_id, permission_id) SELECT $1, id FROM permissions

“At that moment” is the problem. The kit has no per-tenant migration runner yet, so existing tenant databases never see a change to the seed list. Walk through adding a feature:

  1. Add reports:read to the catalogue, with its description.
  2. Put @TenantAuthenticated(PERMISSION_KEYS.reportsRead) on the new route.
  3. Run the tests. They pass, because every test provisions a fresh tenant, and a fresh tenant gets the new permission.
  4. Deploy. New customers can read reports. Every customer who signed up before today gets a 403 from the new route, forever.

The type system is satisfied, the tests are green, and the bug exists only in databases that were created before the change. That is a hard place for a bug to live, because nothing you run in CI was created before the change.

It gets one notch worse. Fix the data by hand and the affected users still get a 403, because the kit bakes permissions into the access token at login. Their current token was minted without reports:read. The kit has no refresh tokens, so the fix takes effect when they next log in. The mirror image is documented in the kit too: a revoked grant stays usable until the token expires, 15 minutes by default.

Until a migration runner exists, the honest procedure is to grant the new permission to existing tenants yourself, in every tenant database:

INSERT INTO permissions (key, description)
VALUES ('reports:read', 'View reports in this tenant')
ON CONFLICT (key) DO NOTHING;

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM roles r, permissions p
WHERE r.name = 'tenant-admin' AND p.key = 'reports:read'
ON CONFLICT DO NOTHING;

Both statements are safe to re-run: permissions.key and roles.name are unique, and role_permissions has a composite primary key.

If you take one design lesson from this: a test suite that only ever provisions fresh state cannot see drift in old state. Keep one long-lived fixture tenant that is created by the previous release and upgraded by the current one, and run the protected-route tests against it.

Order is part of the control

The decorator on that route is not cosmetic. It expands to three guards and the permission requirement:

export function TenantAuthenticated(...permissions: PermissionKey[]) {
  return applyDecorators(
    UseGuards(TenantGuard, AccessTokenGuard, PermissionsGuard),
    RequirePermissions(...permissions),
  );
}

The order is load-bearing. TenantGuard resolves which database this request may touch. AccessTokenGuard verifies the token and refuses one issued for a different tenant. Only then does PermissionsGuard compare required against held. Drop the first and there is no tenant to bind the token to. Assemble the three by hand on each controller and somebody, eventually, will assemble them in the wrong order. One decorator removes that option.

Multiple permissions passed to it are all required, not any.

A denial is evidence

PermissionsGuard records every refusal to the tenant’s audit chain before it throws:

await this.audit.tenantEvent({
  action: "authz.denied",
  actorType: actorId === null ? "anonymous" : "user",
  actorId,
  sourceIp: req.ip,
  metadata: {
    reason,
    method: req.method,
    route: req.routeOptions?.url ?? req.url.split("?")[0],
    required: required.join(","),
    missing: missing.join(","),
  },
});

A refused attempt is the event an access review actually asks for. Not “who holds which role”, which the database answers already, but who tried to do something they were not entitled to. The response deliberately says only “Missing required permission”, so this record is the only place that information exists.

Three choices in those few lines are deliberate:

  • Both required and missing. required is what an integrator needs to fix their grant. missing tells an investigator whether someone was one permission short of a legitimate action or nowhere near it.
  • The route pattern, not the URL. /api/users/:id groups in a query. /api/users/8f2c... fragments into thousands of distinct values that nobody can aggregate.
  • anonymous means a wiring bug. If this guard runs with no authenticated user, authentication was not in front of it. That is the developer’s mistake, not the caller’s, and the audit table’s actor constraint requires an anonymous event to carry no actor id.

It also makes the drift above visible. A run of authz.denied events from admin users with missing: reports:read is the silent 403 announcing itself, in a place you can query. Every one of them would look like a user problem anywhere else.

The cost is a database write on the denial path. That is fine because it is the denial path: an allowed request pays nothing, and a caller producing enough denials for the write to matter is precisely the caller this record exists to document. The audit service fails open, so an unwritable chain slows the rejection rather than turning it into a 500. How that chain resists tampering is the subject of the audit log post.

What the kit does not do

Stated as the kit states it:

  • Permissions are baked into the token at login, so revocation is not immediate.
  • There is no role-management API. Roles and grants change by writing to the tenant database.
  • No hierarchical roles, no wildcards, no resource-scoped permissions. A permission applies to a route, not to a record. “Edit your own profile but nobody else’s” is not expressible.
  • Three permissions and one role is a starting point for least privilege, not a role model. Anything real needs more, which is exactly when the catalogue starts earning its keep.

The part worth taking with you

  1. Checks live in code and grants live in data. Nothing makes them agree unless you build the thing that does.
  2. Declare permission keys once and import them on both sides. Then make the seed an object that satisfies Record<PermissionKey, string>, so omission fails the build.
  3. Fresh-state tests cannot see old-state drift. Upgrade a fixture tenant from the previous release and test against it.
  4. Record denials with what was required and what was missing. It is the evidence an access review wants and the first place a silent 403 shows up.

The code is in services/auth/src/rbac/ and packages/common/src/index.ts in the kit repo. Next in this series: rate limiting in production, and the one setting with no safe default.

Get new posts by email

Backend, auth, and shipping compliant systems. No spam, unsubscribe anytime.