We Replaced 85 Brittle RBAC UI Tests With One 60-Line Permission Matrix

We Replaced 85 Brittle RBAC UI Tests With One 60-Line Permission Matrix

"Finding #2 (High): A read-only Viewer user can export full Stripe invoice PDFs and trigger webhook rotations by calling POST /api/v1/webhooks/rotate directly." Reading that line in our Q2 pentest PDF was humbling, mostly because we already had 85 Playwright tests dedicated to role-based access control. Those 85 tests took 18 minutes to run in CI. Every time a frontend developer renamed a sidebar tab from Billing to Plan & Usage, 14 of them turned red. And yet, they missed a High-severity authorization bypass on the very routes they were supposed to guard. Why? Because UI tests check what React renders, not what Express allows. The 18-Minute Login-Logout Loop Nobody Wanted to Maintain When our SaaS platform grew from two roles (Admin, Member) to five (Owner, Admin, Billing, Member, Viewer), someone on the team did what most teams do: copied a Playwright spec, parameterized the login email, and asserted await expect(page.getByRole('button', { name: 'Rotate Secret' })).toBeHidden(). Multiply 17 sensitive actions by 5 roles and you get 85 browser tests. Each test booted a Chromium context, loaded the React bundle, waited for /api/v1/me to hydrate, navigated to /settings/webhooks, and checked that a button was missing from the DOM. It felt thorough. On paper, every role had 100% UI test coverage. In reality, two things happened: Frontend hiding masked backend neglect. A developer added if (user.role === 'Admin') around the component in React, saw the Playwright test pass, and forgot to add requireRole('Admin') on POST /api/v1/webhooks/rotate in the Node API. Nobody tested new endpoints across all five roles. When a new GET /api/v1/invoices/:id/pdf route shipped in a rush before a customer demo, the PR author wrote one happy-path test as Owner and called it a day. Hiding a button in React is UX. Returning 403 Forbidden on the server is security. Our 85 Playwright tests were only testing UX. One Declarative Matrix That Drives Both the API and the Tests Instead of maintaining 85 browser specs and hoping backend engineers remembered to copy-paste middleware onto every new route, we flipped the setup upside down. We created a single source of truth—src/auth/permissionMatrix.ts—that maps every API route (METHOD /path) to the exact list of roles allowed to call it. Two things consume that exact same file: The Express/Fastify route guard middleware — If a route is not listed in permissionMatrix.ts, the server refuses to start in CI (FAIL-CLOSED by default). No more "forgot to attach auth middleware" bugs. A single data-driven Vitest/Playwright API test — It loops over every row in permissionMatrix.ts and fires real HTTP requests with five pre-minted JWTs (Owner, Admin, Billing, Member, Viewer), asserting 403 for every disallowed role and non-403 for allowed roles. Here is the declarative matrix (src/auth/permissionMatrix.ts): export type Role = 'owner' | 'admin' | 'billing' | 'member' | 'viewer'; export interface RoutePolicy { method: 'GET' | 'POST' | 'PATCH' | 'DELETE'; path: string; // Express/Fastify route pattern allowedRoles: readonly Role[]; tenantScoped: boolean; } export const PERMISSION_MATRIX: readonly RoutePolicy[] = [ { method: 'GET', path: '/api/v1/projects', allowedRoles: ['owner', 'admin', 'billing', 'member', 'viewer'], tenantScoped: true, }, { method: 'POST', path: '/api/v1/projects', allowedRoles: ['owner', 'admin', 'member'], tenantScoped: true, }, { method: 'GET', path: '/api/v1/billing/invoices/:invoiceId/pdf', allowedRoles: ['owner', 'admin', 'billing'], tenantScoped: true, }, { method: 'DELETE', path: '/api/v1/billing/cards/:cardId', allowedRoles: ['owner', 'billing'], tenantScoped: true, }, { method: 'POST', path: '/api/v1/webhooks/rotate', allowedRoles: ['owner', 'admin'], tenantScoped: true, }, ]; And here is the fail-closed middleware (src/auth/enforcePolicy.ts) that guarantees no engineer can ever ship an unprotected endpoint by accident: import type { Request, Response, NextFunction } from 'express'; import { PERMISSION_MATRIX, type Role } from './permissionMatrix'; export function enforcePermissionMatrix(req: Request, res: Response, next: NextFunction) { // Normalize matched Express route pattern, e.g. /api/v1/billing/cards/:cardId const routePath = req.route?.path ? `${req.baseUrl}${req.route.path}` : req.path; const policy = PERMISSION_MATRIX.find( (p) => p.method === req.method && p.path === routePath ); if (!policy) { // Fail closed: any route missing from the matrix is blocked everywhere return res.status(403).json({ error: 'ROUTE_NOT_IN_PERMISSION_MATRIX' }); } const userRole = req.auth?.role as Role | undefined; if (!userRole || !policy.allowedRoles.includes(userRole)) { return res.status(403).json({ error: 'FORBIDDEN', required: policy.allowedRoles, }); } return next(); } Think about what that if (!policy) branch does. If someone adds POST /api/v1/admin/impersonate and forgets to update permissionMatrix.ts, their very first happy-path test fails with 403 ROUTE_NOT_IN_PERMISSION_MATRIX. They literally cannot merge the PR without explicitly declaring which roles are allowed to call it—which puts the role list right in the GitHub PR diff for security and QA reviewers to see. Testing Every (Role × Route) and Cross-Tenant IDOR in 1.9 Seconds Once PERMISSION_MATRIX existed, replacing those 85 slow Playwright UI tests took one 65-line API test (tests/security/rbac-matrix.test.ts). Better yet, we added horizontal tenant isolation (IDOR / BOLA) to the exact same loop. Whenever policy.tenantScoped is true, the test also fires a request using Tenant B's Owner token against Tenant A's resource ID—proving that even an Owner cannot read or delete another customer's invoice or card. Here is the test file: import { describe, it, expect, beforeAll } from 'vitest'; import { PERMISSION_MATRIX, type Role } from '../../src/auth/permissionMatrix'; const API_URL = process.env.API_URL || 'http://127.0.0.1:4000'; const ALL_ROLES: Role[] = ['owner', 'admin', 'billing', 'member', 'viewer']; let tenantATokens: Record; let tenantBOwnerToken: string; let tenantAFixtures: { invoiceId: string; cardId: string }; beforeAll(async () => { // Helper endpoint or seed helper that returns valid JWTs for test tenants tenantATokens = await mintTestTokens('tenant_a'); tenantBOwnerToken = (await mintTestTokens('tenant_b')).owner; tenantAFixtures = await seedTenantAResources(); }); function resolveTestPath(pattern: string): string { return pattern .replace(':invoiceId', tenantAFixtures.invoiceId) .replace(':cardId', tenantAFixtures.cardId); } describe('RBAC & Cross-Tenant Authorization Matrix', () => { for (const policy of PERMISSION_MATRIX) { const url = `${API_URL}${resolveTestPath(policy.path)}`; // 1. Vertical privilege escalation checks (all 5 roles) for (const role of ALL_ROLES) { const shouldAllow = policy.allowedRoles.includes(role); it(`${policy.method} ${policy.path} as [${role}] -> ${shouldAllow ? 'ALLOW' : '403'}`, async () => { const res = await fetch(url, { method: policy.method, headers: { Authorization: `Bearer ${tenantATokens[role]}`, 'Content-Type': 'application/json', }, body: policy.method === 'POST' || policy.method === 'PATCH' ? '{}' : undefined, }); if (shouldAllow) { // Allowed roles may get 200/201/400/422 depending on payload, NEVER 401/403 expect([401, 403]).not.toContain(res.status); } else { expect(res.status).toBe(403); } }); } // 2. Horizontal tenant isolation (IDOR) check if (policy.tenantScoped) { it(`${policy.method} ${policy.path} blocks cross-tenant access (Tenant B Owner -> Tenant A)`, async () => { const res = await fetch(url, { method: policy.method, headers: { Authorization: `Bearer ${tenantBOwnerToken}`, 'Content-Type': 'application/json', }, body: policy.method === 'POST' || policy.method === 'PATCH' ? '{}' : undefined, }); // Must return 403 or 404 (never 200/201/204) expect([403, 404]).toContain(res.status); }); } } }); Notice one subtle detail in the shouldAllow assertion: we assert expect([401, 403]).not.toContain(res.status) instead of expect(res.status).toBe(200). Why? Because sending an empty {} body to POST /api/v1/projects as an Admin should hit your Zod/payload validation (400 or 422), after passing the authorization middleware. That keeps the matrix test decoupled from business payload setup while still proving the auth gate let Admin through and slammed the door on Viewer with 403. Checking for Unregistered Express Routes at Startup Wait: what if someone creates a brand-new Express router file and forgets to attach enforcePermissionMatrix to that router at all? We caught that gap with a 25-line startup audit (scripts/verify-route-coverage.ts) that introspects Express's app._router.stack in CI and compares every mounted (method, path) against PERMISSION_MATRIX: import { app } from '../src/app'; import { PERMISSION_MATRIX } from '../src/auth/permissionMatrix'; const PUBLIC_ALLOWLIST = new Set(['GET /healthz', 'POST /api/v1/auth/login']); function listMountedRoutes(expressApp: typeof app): string[] { const routes: string[] = []; for (const layer of expressApp._router?.stack || []) { if (layer.route) { for (const method of Object.keys(layer.route.methods)) { routes.push(`${method.toUpperCase()} ${layer.route.path}`); } } } return routes; } const matrixSet = new Set(PERMISSION_MATRIX.map((p) => `${p.method} ${p.path}`)); const missing = listMountedRoutes(app).filter( (r) => !PUBLIC_ALLOWLIST.has(r) && !matrixSet.has(r) ); if (missing.length > 0) { console.error('UNPROTECTED ROUTES DETECTED (missing from permissionMatrix.ts):'); for (const r of missing) console.error(` - ${r}`); process.exit(1); } console.log('All mounted Express routes are covered by PERMISSION_MATRIX.'); Run npx tsx scripts/verify-route-coverage.ts in CI and it is physically impossible to mount an API route without either adding it to PUBLIC_ALLOWLIST or assigning its roles in PERMISSION_MATRIX. Three Edge Cases That Bit Us After Rollout Even with the matrix in place, three authorization edge cases popped up over the next couple of months: Trailing slashes and case differences. When enforcePermissionMatrix fell back to req.path on unmatched sub-routers, POST /api/v1/webhooks/rotate/ (with a trailing slash) didn't match '/api/v1/webhooks/rotate'. It failed closed (403), which was safe, but broke a legitimate webhook client. Normalizing routePath.replace(/\/+$/, '') and enabling Express's strict routing: false fixed it cleanly. Field-level leaks inside allowed GET routes. A Member is allowed to call GET /api/v1/workspace/settings, so the matrix test returned 200. What the matrix alone didn't check was whether that 200 JSON accidentally included stripeCustomerId or webhookSigningSecret. We added a simple expect(JSON.stringify(body)).not.toContain('whsec_') assertion for non-admin roles on settings endpoints. Batch and RPC-style endpoints. If you have a POST /api/v1/batch endpoint that takes { action: "deleteInvoice", ... }, route-level RBAC sees every action as the same URL. Keep those endpoints split into explicit REST routes, or key your permission matrix by action name inside the batch dispatcher. Nested resource IDs (:projectId + :webhookId). One tricky IDOR pattern happens when a route has two IDs in the URL: DELETE /api/v1/projects/:projectId/webhooks/:webhookId. If the handler checks that projectId belongs to Tenant A, then runs DELETE FROM webhooks WHERE id = $1 without also scoping AND project_id = $2 AND tenant_id = $3, an attacker can pass their own projectId paired with someone else's webhookId. We enforce tenant scoping directly inside every database query wrapper rather than checking it in a separate if (record.tenantId !== req.auth.tenantId) branch after the fetch: // Enforce tenant ownership in the SQL predicate itself, not after fetching const deleted = await db.query( `DELETE FROM webhooks WHERE id = $1 AND project_id = $2 AND tenant_id = $3 RETURNING id`, [webhookId, projectId, req.auth.tenantId] ); if (deleted.rowCount === 0) { return res.status(404).json({ error: 'NOT_FOUND' }); } Why Deleting 85 Playwright RBAC Specs Made Us Safer We kept four Playwright UI tests for navigation UX (just enough to verify the sidebar hides Billing for Member and Viewer so users don't click dead links). The other 81 browser-based role tests went straight into git rm. Here is what changed after that cleanup: RBAC test runtime: Dropped from 18 minutes (85 Playwright specs) to 1.9 seconds (one Vitest API matrix running 150+ role and IDOR assertions). Maintenance: Zero UI selector breakage when frontend engineers restyle settings pages. Security coverage: Every single mounted Express route is checked against all five roles and cross-tenant IDOR on every commit—not just the buttons QA happened to write Playwright specs for. If you are still spinning up headless Chromium to prove a Viewer cannot click a hidden button, stop. Check the backend routes with a 60-line matrix instead—because attackers do not use your React sidebar.

Original Source

Read the full article at Hackernoon →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.