Skip to content

Authorization Starts with Denial

The Course
•
18 min study

The decision

A session identifies a caller; authorization decides which operation that caller may perform on this record. The Review Queue makes that decision in a server-side policy used by every transport.

Read, predict, run

The inputs are explicit test fixtures, not real sessions. A matching owner can read a record, while an absent actor is denied. On a real server, load the actor from a verified session; never accept an owner id from the submitted form as proof:

JavaScript
export function run({ actor, record }) {
  return Boolean(
    actor &&
    record &&
    typeof actor.id === "string" &&
    actor.id.length > 0 &&
    actor.id === record.ownerId,
  );
}

Before pressing Run, predict what run returns for {"actor": null, "record": {"ownerId": "ada"}} and {"actor": {"id": "ada"}, "record": {"ownerId": "ada"}}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Authorization Starts with Denial Next.js · 9 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import ApiProbe from "./ApiProbe.jsx"; import Cases from "./Cases.jsx"; import Compare from "./Compare.jsx"; export default function Page() { return ( <main> <h1>Authorization Starts with Denial</h1> <p> app/api/records/[id]/route.js calls run from lib/contract.js. Add ?as=ada to act as Ada; without it the session is an empty object. </p> <Compare /> <ApiProbe /> <Cases /> </main> ); } "use client"; import { useState } from "react"; export default function ApiProbe() { const [path, setPath] = useState("/api/records/2"); const [result, setResult] = useState(""); async function send() { const response = await fetch(path); setResult(`${response.status} ${JSON.stringify(await response.json())}`); } return ( <section> <label> Path <input value={path} onChange={(event) => setPath(event.target.value)} /> </label>{" "} <button onClick={send}>Send GET</button> <p role="status">{result}</p> </section> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } import { run } from "@/lib/contract.js"; import { naiveCanRead } from "@/lib/records.js"; const inputs = [ { actor: { id: "ada" }, record: { ownerId: "ada" } }, { actor: { id: "grace" }, record: { ownerId: "ada" } }, { actor: {}, record: {} }, ]; export default function Compare() { return ( <table aria-label="Naive check and run"> <thead> <tr> <th>Input</th> <th>Naive one-liner</th> <th>run</th> </tr> </thead> <tbody> {inputs.map((input) => ( <tr key={JSON.stringify(input)}> <td> <code>{JSON.stringify(input)}</code> </td> <td>{String(naiveCanRead(input))}</td> <td>{String(run(input))}</td> </tr> ))} </tbody> </table> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } import { run } from "@/lib/contract.js"; import { actorFrom, findRecord } from "@/lib/records.js"; export async function GET(request, { params }) { const { id } = await params; const record = findRecord(id); const actor = actorFrom(request); // Same 404 for "missing" and "not yours", so ids can't be probed. if (!record || !run({ actor, record })) { return Response.json({ code: "not_found" }, { status: 404 }); } return Response.json({ id: record.id, title: record.title }); } export function run({ actor, record }) { return Boolean( actor && record && typeof actor.id === "string" && actor.id.length > 0 && actor.id === record.ownerId, ); } export const examples = [ [{ actor: null, record: { ownerId: "ada" } }, false], [{ actor: { id: "ada" }, record: { ownerId: "ada" } }, true], ]; // Record 2 came from an old import and never got an owner. const records = [ { id: "1", ownerId: "ada", title: "Ada's draft review" }, { id: "2", title: "Imported review with no owner" }, ]; export function findRecord(id) { return records.find((record) => record.id === id) ?? null; } // The session lookup returns an empty object, not null, when the cookie is // missing: a realistic shape that the naive check below trips over. export function actorFrom(request) { const as = new URL(request.url).searchParams.get("as"); return as ? { id: as } : {}; } // The obvious one-liner, kept here only to compare with run. export function naiveCanRead({ actor, record }) { return actor?.id === record?.ownerId; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"actor": null, "record": {"ownerId": "ada"}} → false.
  • Input {"actor": {"id": "ada"}, "record": {"ownerId": "ada"}} → true.

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The failure to avoid

Hiding a button does not protect an endpoint. A route handler and a Server Action must both enforce the policy, even when the UI never offers the forbidden operation.

Why so many guards? Compare run with the obvious one-liner, return actor?.id === record?.ownerId;, on {"actor": {}, "record": {}}. The one-liner compares undefined === undefined and returns true. That input isn't far-fetched: a session lookup that returns {} for a missing cookie meets a record imported without an owner.

The lab has both. lib/records.js holds record 2, which has no ownerId, and a session that is {} unless the URL says ?as=ada. app/api/records/[id]/route.js checks access with run:

JavaScript
const record = findRecord(id);
const actor = actorFrom(request);
if (!record || !run({ actor, record })) {
  return Response.json({ code: "not_found" }, { status: 404 });
}
return Response.json({ id: record.id, title: record.title });

Run it and read the comparison table. Press Send GET for /api/records/2. Then, in the route, replace run({ actor, record }) with naiveCanRead({ actor, record }) (import it from @/lib/records.js), and predict what the same request returns.

The naive check, wired into a route Next.js · 9 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import ApiProbe from "./ApiProbe.jsx"; import Cases from "./Cases.jsx"; import Compare from "./Compare.jsx"; export default function Page() { return ( <main> <h1>Authorization Starts with Denial</h1> <p> app/api/records/[id]/route.js calls run from lib/contract.js. Add ?as=ada to act as Ada; without it the session is an empty object. </p> <Compare /> <ApiProbe /> <Cases /> </main> ); } "use client"; import { useState } from "react"; export default function ApiProbe() { const [path, setPath] = useState("/api/records/2"); const [result, setResult] = useState(""); async function send() { const response = await fetch(path); setResult(`${response.status} ${JSON.stringify(await response.json())}`); } return ( <section> <label> Path <input value={path} onChange={(event) => setPath(event.target.value)} /> </label>{" "} <button onClick={send}>Send GET</button> <p role="status">{result}</p> </section> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } import { run } from "@/lib/contract.js"; import { naiveCanRead } from "@/lib/records.js"; const inputs = [ { actor: { id: "ada" }, record: { ownerId: "ada" } }, { actor: { id: "grace" }, record: { ownerId: "ada" } }, { actor: {}, record: {} }, ]; export default function Compare() { return ( <table aria-label="Naive check and run"> <thead> <tr> <th>Input</th> <th>Naive one-liner</th> <th>run</th> </tr> </thead> <tbody> {inputs.map((input) => ( <tr key={JSON.stringify(input)}> <td> <code>{JSON.stringify(input)}</code> </td> <td>{String(naiveCanRead(input))}</td> <td>{String(run(input))}</td> </tr> ))} </tbody> </table> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } import { run } from "@/lib/contract.js"; import { actorFrom, findRecord } from "@/lib/records.js"; export async function GET(request, { params }) { const { id } = await params; const record = findRecord(id); const actor = actorFrom(request); // Same 404 for "missing" and "not yours", so ids can't be probed. if (!record || !run({ actor, record })) { return Response.json({ code: "not_found" }, { status: 404 }); } return Response.json({ id: record.id, title: record.title }); } export function run({ actor, record }) { return Boolean( actor && record && typeof actor.id === "string" && actor.id.length > 0 && actor.id === record.ownerId, ); } export const examples = [ [{ actor: null, record: { ownerId: "ada" } }, false], [{ actor: { id: "ada" }, record: { ownerId: "ada" } }, true], ]; // Record 2 came from an old import and never got an owner. const records = [ { id: "1", ownerId: "ada", title: "Ada's draft review" }, { id: "2", title: "Imported review with no owner" }, ]; export function findRecord(id) { return records.find((record) => record.id === id) ?? null; } // The session lookup returns an empty object, not null, when the cookie is // missing: a realistic shape that the naive check below trips over. export function actorFrom(request) { const as = new URL(request.url).searchParams.get("as"); return as ? { id: as } : {}; } // The obvious one-liner, kept here only to compare with run. export function naiveCanRead({ actor, record }) { return actor?.id === record?.ownerId; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction

The table shows the naive check returning true for {"actor": {}, "record": {}}, where run returns false. With run, the request gets 404 {"code":"not_found"}. With the naive check it gets 200 {"id":"2","title":"Imported review with no owner"}: an anonymous caller reads a record that belongs to nobody. Put run back.

Deny by default means access needs every identity field to be present and to match, so anything missing denies.

Exercise

Extend the contract

Allow a reviewer to read a record only when the reviewer and record also have the same tenantId. Owners must still match the tenant. Give the original valid actor and record a tenantId before rerunning that case; missing identity fields must be denied.

Start by finding a failure. Write one input of your own that the current run gets wrong under the new rule (a reviewer, or an owner in another tenant), with the result it should give, and add it to examples. Watch it fail before you change anything.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"actor": {"id": "grace", "role": "reviewer", "tenantId": "a"}, "record": {"ownerId": "ada", "tenantId": "a"}} must return true.
  • Input {"actor": {"id": "ada", "tenantId": "a"}, "record": {"ownerId": "ada", "tenantId": "b"}} must return false.
Your working space Next.js · 9 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import ApiProbe from "./ApiProbe.jsx"; import Cases from "./Cases.jsx"; import Compare from "./Compare.jsx"; export default function Page() { return ( <main> <h1>Authorization Starts with Denial</h1> <p> app/api/records/[id]/route.js calls run from lib/contract.js. Add ?as=ada to act as Ada; without it the session is an empty object. </p> <Compare /> <ApiProbe /> <Cases /> </main> ); } "use client"; import { useState } from "react"; export default function ApiProbe() { const [path, setPath] = useState("/api/records/2"); const [result, setResult] = useState(""); async function send() { const response = await fetch(path); setResult(`${response.status} ${JSON.stringify(await response.json())}`); } return ( <section> <label> Path <input value={path} onChange={(event) => setPath(event.target.value)} /> </label>{" "} <button onClick={send}>Send GET</button> <p role="status">{result}</p> </section> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } import { run } from "@/lib/contract.js"; import { naiveCanRead } from "@/lib/records.js"; const inputs = [ { actor: { id: "ada" }, record: { ownerId: "ada" } }, { actor: { id: "grace" }, record: { ownerId: "ada" } }, { actor: {}, record: {} }, ]; export default function Compare() { return ( <table aria-label="Naive check and run"> <thead> <tr> <th>Input</th> <th>Naive one-liner</th> <th>run</th> </tr> </thead> <tbody> {inputs.map((input) => ( <tr key={JSON.stringify(input)}> <td> <code>{JSON.stringify(input)}</code> </td> <td>{String(naiveCanRead(input))}</td> <td>{String(run(input))}</td> </tr> ))} </tbody> </table> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } import { run } from "@/lib/contract.js"; import { actorFrom, findRecord } from "@/lib/records.js"; export async function GET(request, { params }) { const { id } = await params; const record = findRecord(id); const actor = actorFrom(request); // Same 404 for "missing" and "not yours", so ids can't be probed. if (!record || !run({ actor, record })) { return Response.json({ code: "not_found" }, { status: 404 }); } return Response.json({ id: record.id, title: record.title }); } export function run({ actor, record }) { return Boolean( actor && record && typeof actor.id === "string" && actor.id.length > 0 && actor.id === record.ownerId, ); } export const examples = [ [{ actor: null, record: { ownerId: "ada" } }, false], [{ actor: { id: "ada" }, record: { ownerId: "ada" } }, true], ]; // Record 2 came from an old import and never got an owner. const records = [ { id: "1", ownerId: "ada", title: "Ada's draft review" }, { id: "2", title: "Imported review with no owner" }, ]; export function findRecord(id) { return records.find((record) => record.id === id) ?? null; } // The session lookup returns an empty object, not null, when the cookie is // missing: a realistic shape that the naive check below trips over. export function actorFrom(request) { const as = new URL(request.url).searchParams.get("as"); return as ? { id: as } : {}; } // The obvious one-liner, kept here only to compare with run. export function naiveCanRead({ actor, record }) { return actor?.id === record?.ownerId; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

Tenancy is an outer boundary: a record in another organization is out of reach for everyone, owner or reviewer. Inside it, either relationship can grant access. And like the id, the tenant must be present before it can match.

Hint 2: a first step

Check the tenant boundary before either ownership or the reviewer role.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ actor, record }) {
  return Boolean(
    actor &&
    record &&
    typeof actor.id === "string" &&
    actor.id.length > 0 &&
    typeof actor.tenantId === "string" &&
    actor.tenantId.length > 0 &&
    actor.tenantId === record.tenantId &&
    (actor.id === record.ownerId || actor.role === "reviewer"),
  );
}

Each new comparison has its own presence guard. Without typeof actor.tenantId === "string" && actor.tenantId.length > 0, an actor and a record that both lack a tenant would match on undefined === undefined, the same hole as before. The tenant check sits outside the parentheses, so it applies to owners and reviewers alike. The original owner case now needs a tenantId on both sides; without one it's denied, which is the point.

Explain it without the code

Write the smallest input that would wrongly return true if you removed one of the presence guards, and say which guard.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.