HTTP authorization
Protect application routes with the Hono adapter without revealing whether a document exists.
This recipe guards your application’s own document routes. It is not the
Sharing HTTP API. The adapter is the one documented on the
Hono page. The runnable program is examples/http-hono.ts:
bun examples/http-hono.ts It reuses the ACL recipe names: tenant A, documents, tenant_admin, and
document_reader. Examples are not published in the npm package.
| Route | Permission |
|---|---|
GET /api/tenants/:tenantId/documents/:id | document:read |
PATCH /api/tenants/:tenantId/documents/:id | document:update |
Those are ordinary Hono routes. Nothing new dispatches on the permission.
Request order
- Read the authenticated subject from the server session. No session returns 401 and does not load
a document.
getBindingreturnsundefinedonly for that case. - In
getBinding, decide whether that subject is a member of the tenant in the path, and load that tenant’s assignments. A member with no assignments still gets a binding, withassignments: []. A member of a different tenant throws the same 404 used for a missing document, before the document lookup. An unexpected eligibility failure is left to the server error handler. - Load the document by
(tenantId, documentId). Ancestry and facts come from that row. The path selects the lookup. It does not attest ownership. - Keep that row for both the check and the handler. A write still has to re-check its version inside the application’s transaction. The snapshot is not a lock.
- Install
app.onError(middleware.onError). LeavereuseBindingPerRequestoff: the binding depends on the tenant in the path.
The adapter’s default denial is 403. This recipe sets onForbidden so a denial, a missing document,
a document in another tenant, and an ineligible tenant all return the same plain-text 404. That
hides existence in the status and body. It does not make response timing identical. Keep
authorization traces on the server. Do not add a header or cookie that varies by which of those
cases it was.
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { definePolicy, trustedResource, type RoleAssignment } from "rolebook";
import { createRolebookMiddleware, type RolebookEnv } from "rolebook/middleware/hono";
const policy = definePolicy({
resources: {
tenant: { actions: ["read"] },
project: { parent: "tenant", actions: ["read"] },
document: { parent: "project", actions: ["read", "update"] },
},
roles: {
tenant_admin: {
scope: "tenant",
rules: [
{ effect: "allow", permission: "document:read" },
{ effect: "allow", permission: "document:update" },
],
},
document_reader: {
scope: "document",
rules: [{ effect: "allow", permission: "document:read" }],
},
},
});
const records = [
{ tenantId: "tenant_a", projectId: "project_a", id: "doc_a1", title: "Plan A1" },
] as const;
function unavailableResponse(): Response {
return new Response("Not Found", {
status: 404,
headers: { "content-type": "text/plain; charset=UTF-8" },
});
}
function unavailable(): HTTPException {
return new HTTPException(404, { res: unavailableResponse() });
}
function subjectFor(session: string) {
if (session === "alice") return { type: "user" as const, id: "alice" };
if (session === "bob") return { type: "user" as const, id: "bob" };
if (session === "carol") return { type: "user" as const, id: "carol" };
return undefined;
}
const members = new Map<string, ReadonlySet<string>>([["tenant_a", new Set(["alice", "bob", "carol"])]]);
function assignmentsFor(
subjectId: string,
tenantId: string,
): readonly RoleAssignment<"tenant_admin" | "document_reader">[] {
// Only the assignments stored for this tenant. Another tenant's grants never reach the binding.
if (tenantId !== "tenant_a") return [];
if (subjectId === "alice") {
return [
{
subject: { type: "user", id: "alice" },
role: "tenant_admin",
scope: { resource: { type: "tenant", id: "tenant_a" }, appliesTo: "descendants" },
},
];
}
if (subjectId === "bob") {
return [
{
subject: { type: "user", id: "bob" },
role: "document_reader",
scope: { resource: { type: "document", id: "doc_a1" }, appliesTo: "self" },
},
];
}
return [];
}
function loadDocument(tenantId: string, documentId: string) {
return records.find((record) => record.tenantId === tenantId && record.id === documentId);
}
type AppEnv = {
Variables: RolebookEnv<typeof policy>["Variables"] & { document: (typeof records)[number] };
};
const app = new Hono<AppEnv>();
const middleware = createRolebookMiddleware({
policy,
onForbidden: () => unavailableResponse(),
getBinding: (context) => {
const session = context.req.raw.headers.get("session");
if (session === null) return undefined;
const subject = subjectFor(session);
if (subject === undefined) return undefined;
const tenantId = context.req.param("tenantId");
if (tenantId === undefined || !members.get(tenantId)?.has(subject.id)) throw unavailable();
return { subject, assignments: assignmentsFor(subject.id, tenantId) };
},
});
app.onError(middleware.onError);
app.get("/health", (context) => context.text("ok"));
function openDocument(tenantId: string | undefined, documentId: string | undefined) {
if (tenantId === undefined || documentId === undefined) throw unavailable();
const record = loadDocument(tenantId, documentId);
if (record === undefined) throw unavailable();
return record;
}
function trustedDocument(record: (typeof records)[number]) {
return trustedResource({ type: "document", id: record.id }, [
{ type: "project", id: record.projectId },
{ type: "tenant", id: record.tenantId },
]);
}
app.get(
"/api/tenants/:tenantId/documents/:id",
middleware.requirePermission((context) => {
const record = openDocument(context.req.param("tenantId"), context.req.param("id"));
context.set("document", record);
return { permission: "document:read", resource: trustedDocument(record) };
}),
(context) => context.json({ id: context.get("document").id, title: context.get("document").title }),
);
app.patch(
"/api/tenants/:tenantId/documents/:id",
middleware.requirePermission((context) => {
const record = openDocument(context.req.param("tenantId"), context.req.param("id"));
context.set("document", record);
return { permission: "document:update", resource: trustedDocument(record) };
}),
(context) => context.json({ id: context.get("document").id, updated: true }),
); Hono 4 serves HEAD with the GET route and strips the body. The request method stays HEAD.
Prefer mapping the permission on the route. This sample has no CORS middleware and no OPTIONS
handler, so a preflight or an unsupported method is the framework’s ordinary 404. Configuring CORS
does not authorize the request that follows. GET /health is public because it does not use the
middleware.
Path and method conditions
The application above has no pathname or method conditions. A separate policy can require them on
every document:read and document:update allow. Read context.path from c.req.path and
context.method from c.req.method. Do not parse another copy of the URL, and do not copy either
fact from a client header or body. A query string is not part of c.req.path.
Each read allow requires context.path to start with /api/tenants/ and context.method to be
GET or HEAD. Each update allow requires the same prefix and context.method equal to PATCH.
Use those explicit permissions so a wildcard cannot skip the condition. The strings do not match
path parameters and do not establish the tenant. A binding that omits either fact cannot match the
allow. The main application is unchanged.