Justine Acosta
JUSTINE ACOSTA · GMT+8 ·
All articles
BLOG / ARTICLE

Authorization Is Where Apps Leak

Authentication is a solved problem you can buy. Authorization is bespoke to your product, and it's where most real data exposure comes from.

5 min readSecurityArchitectureAuthorization

Authentication, proving who someone is, is genuinely solved. Use a managed provider, don't store passwords, move on. It's a morning of work and the hard parts are somebody else's problem.

Authorization is what happens next: given that we know who you are, what are you allowed to see and do? Nobody can sell you that, because it's specific to your data model. It's also where the great majority of real-world data exposure comes from, and it tends to be assembled incidentally rather than designed.

The distinction worth holding onto

Authentication is a property of the session. Authorization is a property of the request, and it depends on the specific resource being touched.

That difference explains the most common bug in the category. A logged-in user requests /api/invoices/4821. The session is valid, so the request proceeds, but nobody checked whether invoice 4821 belongs to that user's organization. The authentication was perfect and the data still leaked.

This has a name, insecure direct object reference, and it accounts for a large share of the breaches that get written up. It's rarely exotic. It's usually one handler that queried by ID without also filtering by owner.

Decide it on the server, once

Hiding a button is a user experience improvement, not a security control. If the only thing preventing a non-admin from deleting a record is that the delete button isn't rendered, the API will happily accept the request from anyone who sends it.

The reliable structure is a single place where the decision is made, called by every route:

export function can(actor: Actor, action: Action, resource: Resource): boolean {
  if (actor.orgId !== resource.orgId) return false; // tenant boundary first
  switch (action) {
    case "invoice:read":
      return actor.role !== "guest";
    case "invoice:void":
      return actor.role === "owner" || actor.role === "admin";
    default:
      return false; // unknown action is a denial
  }
}

Two properties matter more than the specific shape. The tenant check comes first and applies to everything, so cross-organization access fails before any role logic runs. And the default is denial: a new action nobody has written a rule for is refused rather than allowed, which means forgetting to update this file breaks a feature instead of opening a hole.

Scattering if (user.role === "admin") through route handlers produces the opposite default. Every new endpoint is open until someone remembers.

Filter in the query, not after it

Loading a record and then checking ownership works, but it's fragile: it relies on every handler remembering the second step. Pushing the constraint into the query makes the safe version the natural one:

// The tenant is part of the lookup, so there is no unscoped read.
const invoice = await db.invoice.findFirst({
  where: { id, orgId: actor.orgId },
});

A wrong-tenant ID now returns nothing, which your existing not-found path already handles. This also gives you a better security property incidentally: an attacker probing for valid IDs can't distinguish "doesn't exist" from "exists but isn't yours."

Row-level security in the database is the strongest version of this idea, since the constraint holds even for code that forgets. It's worth the setup cost on anything holding data belonging to more than one customer.

The four leaks worth checking for today

In rough order of how often I find them:

Object references without an ownership filter. Any handler that takes an ID from the request and queries by it alone. Search your codebase for lookups by primary key and confirm each one is scoped.

List endpoints that filter in the application. Fetching all records and filtering in JavaScript is a leak waiting for a pagination bug, and it's usually slow as well.

Nested resources checked one level up. /projects/9/documents/3 where the code verifies access to project 9 but never confirms document 3 belongs to project 9. Check the leaf, not just the parent.

Mass assignment. Accepting a request body and spreading it into an update lets a user set role, orgId, or isAdmin on themselves. Allow-list the fields a given actor may write, per action.

Testing it is easier than it sounds

Authorization is unusually testable, because the interesting cases are enumerable. For each protected resource, there are only a few actors that matter: the owner, a teammate, a member of another organization, and an unauthenticated request.

A single parameterized test over that matrix catches the whole category:

for (const [actor, expected] of [
  [owner, 200],
  [teammate, 200],
  [otherOrgUser, 404],
  [anonymous, 401],
] as const) {
  it(`${actor.label} gets ${expected}`, async () => {
    const res = await request(app).get(`/api/invoices/${invoice.id}`).set(auth(actor));
    expect(res.status).toBe(expected);
  });
}

Note that the other-organization case expects 404 rather than 403. Returning "forbidden" confirms the resource exists, which is a small disclosure worth avoiding.

Write this once per resource type and the coverage compounds: every new endpoint on that resource inherits the pattern.

Log the decisions you'll be asked about later

Keep a record of sensitive reads and every write: who, what, when, and from where. This is unglamorous and it earns its place in three situations that all eventually arrive: a customer asking who accessed their data, an incident where you need to establish scope, and a compliance review.

Append-only, outside the application database if you can manage it, and never containing the sensitive values themselves. You want to know that user 12 read invoice 4821, not what the invoice said.

A reasonable sequence

If you're retrofitting this onto something already running:

  1. Establish the tenant boundary. One check, applied everywhere, before anything else.
  2. Move scattered role checks into a single can() function that denies by default.
  3. Push ownership into queries rather than post-load checks.
  4. Write the actor-matrix test for your two or three most sensitive resources.
  5. Add audit logging on writes.

That's a week or so on a typical codebase, and it converts authorization from something that depends on every developer remembering into something the structure enforces.