← Notebook

Server-enforced authorization

Hiding a button is not authorization. Permissions belong where protected data leaves the system.

authorizationpermissionsaccess control

You hide the Approve button from anyone who is not a reviewer. Requests stop arriving from the wrong people, nobody reports a problem, and it feels like security.

It is not. The button never approved anything — the request it sends does. Anyone can send that request without the button: from a script, from the browser's developer tools, or from a tab opened yesterday before their role was taken away. Hiding the button changes what most people see. It changes nothing about what anyone can do.

This note is about putting that decision somewhere it can actually be enforced. It assumes you have built a web application with a login and a role or two, and nothing more.

Two questions that are easy to blur#

Every protected request asks two separate questions.

Authentication asks who are you? Login answers it: a session cookie or a token the server can verify was issued to a particular person.

Authorization asks what may you do? It is answered by rules about that person, the action they are attempting, and the thing they are attempting it on.

Most applications get the first right, because a library does it for them. The second tends to end up scattered: a role check in one route, a hidden button in a component, an extra condition in one query. This note is about the second.

Why the browser cannot be the one to decide#

Anything the browser does, the person using it can change. The interface is a convenience the server offers, not a gatekeeper the server can rely on.

Concretely, the Approve button sends a request like this one, which works just as well typed into a terminal with a session cookie copied from the user's own logged-in browser:

sh
curl -X POST https://app.example.com/api/changes/42/approve \
  --cookie "session=…"

So the server has to ask the authorization question itself, on every request, using only what it can trust: the identity from the verified session, and that person's current roles and the record's current state, both read from its own database for this request. Never a role the client sent, never a role copied into the session when they signed in, never a flag in the request body.

A policy is just a function#

The clearest home for an authorization rule is a plain function. Given who is acting, what they are trying to do, and what they are doing it to, it returns yes or no. That function is called a policy.

Start with the shapes involved:

ts
type Actor = { id: string; roles: string[] };

type Change = {
  id: string;
  authorId: string;
  status: "draft" | "awaiting_review" | "approved";
  amount: number;
};

type Action = "view" | "edit" | "submit" | "approve";

Why a role is not enough#

The tempting policy is one line: reviewers may approve. Real rules are rarely that simple. A reviewer may approve a change only while it is awaiting review, only up to the approval limit, and never one they wrote themselves.

Roles are still useful; they are one input among several. Who is asking matters too, and so does the record: you can always see your own changes, a reviewer can also see anything that has been submitted, and a draft stays private to its author until then. The policy is where all the inputs meet:

ts
const APPROVAL_LIMIT = 10_000;

export function can(
  actor: Actor,
  action: Action,
  change: Change
): boolean {
  const isAuthor = change.authorId === actor.id;
  const isReviewer = actor.roles.includes("reviewer");

  switch (action) {
    case "view":
      // Your own changes, and anything submitted if you review.
      return isAuthor || (isReviewer && change.status !== "draft");
    case "edit":
    case "submit":
      return isAuthor && change.status === "draft";
    case "approve":
      return (
        isReviewer &&
        change.status === "awaiting_review" &&
        change.amount <= APPROVAL_LIMIT &&
        !isAuthor
      );
    default:
      // An action this policy does not know is denied, never allowed.
      return false;
  }
}

Two things about this function matter more than its details.

It is readable as a specification. Someone who has never seen the codebase can check it against the business rule, line by line. Rules spread across routes, components and queries cannot be checked that way, because nobody can see them all at once.

It fails closed. The default branch denies anything it does not recognise. For typed callers that branch can never run — inside it, TypeScript narrows action to never, its type for a value that cannot exist — but the action usually arrives from a URL, and a URL can say anything. When someone adds a new action and forgets its rule, failing closed produces a refused request and a bug report. Failing open, where anything unhandled is allowed, turns every forgotten rule into a hole.

Put the check at the boundary#

The boundary is the point where a request enters your server and is about to read or change something. Every route to the data passes through it, which makes it the one place a check cannot be walked around.

Load the record, ask the policy, and only then act:

ts
type Store = {
  findChange(id: string): Promise<Change | undefined>;
  markApproved(id: string, approverId: string): Promise<void>;
};

type Result = { status: number; body: unknown };

export async function approveChange(
  store: Store,
  actor: Actor,
  changeId: string
): Promise<Result> {
  const change = await store.findChange(changeId);

  // "Not found" and "not yours to see" must look the same from outside.
  if (!change || !can(actor, "view", change)) {
    return { status: 404, body: { error: "not_found" } };
  }
  if (!can(actor, "approve", change)) {
    return { status: 403, body: { error: "not_permitted" } };
  }

  await store.markApproved(change.id, actor.id);
  return { status: 200, body: { id: change.id, status: "approved" } };
}

Notice the two different refusals. 403 Forbidden says "this exists, and you may not do that". 404 Not Found says "there is nothing here" — and it is also the right answer when there is something, but this person is not allowed to see it, such as someone else's unsubmitted draft. Returning 403 there would confirm the record exists, and that confirmation is itself a leak.

Reads need the rule too#

It is common to protect the routes that change things and forget the ones that list them. A search, an export or a dashboard count can reveal changes someone may not see just as surely as opening one can.

Put the view rule into the query itself, so rows this person may not see are never fetched at all:

ts
type Db = {
  query<T>(sql: string, params: unknown[]): Promise<{ rows: T[] }>;
};

export async function listChanges(db: Db, actor: Actor) {
  const { rows } = await db.query<{ id: string; status: string }>(
    `SELECT id, status
       FROM changes
      WHERE author_id = $1
         OR ($2 AND status <> 'draft')
      ORDER BY created_at DESC`,
    [actor.id, actor.roles.includes("reviewer")]
  );
  return rows;
}

$1 and $2 are parameters: the database receives the values separately from the SQL text, so a value can never be mistaken for part of the query. The WHERE clause is the view rule from can, written a second time in the database's language.

Fetching everything and filtering in your own code afterwards looks equivalent, and is not. Anything computed before the filter — a total count, a page number, an error message — still describes rows the user was never meant to know existed.

Tell the interface, but do not let it decide#

The interface still needs to know whether to show the Approve button, or it will offer actions that fail. Let the server tell it, using the same policy:

ts
export function capabilities(actor: Actor, change: Change) {
  return {
    edit: can(actor, "edit", change),
    submit: can(actor, "submit", change),
    approve: can(actor, "approve", change)
  };
}

Send this alongside the record and have the interface render from it. The button and the rule can no longer disagree, because both come from one function.

This answer can go stale. A user can load the page, lose their reviewer role, and click Approve an hour later. That is fine, because approveChange asks the policy again when the request arrives, with the roles the user has now. This is why roles are read on each request: a role copied into a session cookie or a token at sign-in stays valid until it expires, so the re-check would approve with a role that is already gone. Capabilities keep the interface honest; the boundary keeps the data safe.

Test the denials, not the button#

A test that clicks the button only proves the button works. What matters is whether the server refuses what it should, including requests that never came from your interface. A table keeps the cases readable and makes a missing one obvious:

ts
import assert from "node:assert/strict";

const reviewer: Actor = { id: "r1", roles: ["reviewer"] };
const change: Change = {
  id: "c1",
  authorId: "a1",
  status: "awaiting_review",
  amount: 5_000
};

type Case = [string, Partial<Actor>, Partial<Change>, boolean];

// Each denial differs from the allowed request in exactly one way.
const cases: Case[] = [
  ["a reviewer approves", {}, {}, true],
  ["approving their own change", { id: "a1" }, {}, false],
  ["the role was removed", { roles: [] }, {}, false],
  ["still a draft", {}, { status: "draft" }, false],
  ["already approved", {}, { status: "approved" }, false],
  ["over the approval limit", {}, { amount: 50_000 }, false]
];

for (const [name, actorDiff, changeDiff, expected] of cases) {
  const actor = { ...reviewer, ...actorDiff };
  const target = { ...change, ...changeDiff };
  assert.equal(can(actor, "approve", target), expected, name);
}

// An action that arrived from a URL rather than from the type system.
const fromUrl: string = "delete";
assert.equal(can(reviewer, fromUrl as Action, change), false);

// Someone else's draft is hidden, not refused.
const draft: Change = { ...change, id: "d1", status: "draft" };
const store: Store = {
  findChange: async (id) => [change, draft].find((c) => c.id === id),
  markApproved: async () => {}
};
const author = { ...reviewer, id: "a1" };
assert.equal((await approveChange(store, reviewer, "d1")).status, 404);
assert.equal((await approveChange(store, author, "c1")).status, 403);
assert.equal((await approveChange(store, reviewer, "c1")).status, 200);

Every row is a request someone could send directly. If the policy allows a single row that should be denied, it is not a policy — it is a suggestion.

What it costs#

A policy function is one more thing to keep in step with the business. Every new action needs a rule, and every rule needs its denied cases tested. That is more work than hiding a button, and it never stops.

It also puts a decision that used to be spread out into one place, so a mistake in it is a mistake everywhere at once. That is the point. One place to get wrong is also one place to review, test and get right.

It centralises the rule, not the call to it. Every route still has to ask the policy, and a list query cannot ask it row by row, so its view rule is written again in each WHERE clause. A route that skips either fails as quietly as any scattered check, which is why the denial tests belong at the routes as well as on the function. Scattered checks fail one at a time, quietly, and usually in the route nobody remembered; with a policy, at least the rule that route forgot is written down where someone can review it.

The interface describes permission. The server enforces it.