Q16 of 24 · Security

How do you design an API security test suite that validates authorisation on every endpoint?

SecuritySeniorsecurityauthorisationapirbacidoropenapitestingsenior

Short answer

Short answer: Build a matrix of all API endpoints × role types. For each cell, assert the expected HTTP status (200 for permitted, 403 for forbidden) and verify the response body does not leak data the role should not see. Generate the endpoint list from the OpenAPI spec to ensure coverage keeps pace with development.

Detail

The matrix approach: identify all roles (unauthenticated, user, admin, service account) and all API endpoints. For each combination, document the expected outcome: allowed (200) or forbidden (403). Automated tests assert the actual response matches the expected.

const scenarios = [
  { endpoint: '/api/admin/users',    method: 'GET',    role: 'user',  expected: 403 },
  { endpoint: '/api/admin/users',    method: 'GET',    role: 'admin', expected: 200 },
  { endpoint: '/api/orders/me',      method: 'GET',    role: 'user',  expected: 200 },
  { endpoint: '/api/orders/me',      method: 'GET',    role: 'anon',  expected: 401 },
];

for (const { endpoint, method, role, expected } of scenarios) {
  const token = getTokenForRole(role);
  const response = await request[method.toLowerCase()](endpoint, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
  expect(response.status(), `${role} on ${method} ${endpoint}`).toBe(expected);
}

Automating endpoint discovery: parse the OpenAPI spec (Swagger JSON) to generate the endpoint list. Any endpoint not in the test matrix is a gap. Configure CI to fail if new endpoints appear in the spec without a corresponding test.

Beyond status codes: a 403 response is correct but you must also verify the response body doesn't include partial data. Some implementations return 403 with the resource data in the body — the client is expected to honour the status, but the data is still transmitted and visible to a determined attacker.

Cross-user data leakage: for GET endpoints that return user-specific data, verify that User B's token cannot retrieve User A's resources. Create two test accounts, capture User A's resource IDs, and assert they're inaccessible under User B's token.

// WHAT INTERVIEWERS LOOK FOR

Matrix approach with programmatic generation from OpenAPI spec. Tests response body for data leakage — not just HTTP status. Covers horizontal (IDOR) and vertical (role) privilege checks.