Skip to content

Authorization

Authentication answers who is asking. Authorization answers what that person may do. You write the rules as small policy files, and hamur server checks them on the server, before your handler runs.

The policy language is Cedar. You do not need to know it first: this page starts with one policy and adds one need at a time. The parts of Cedar that hamur server supports, and the few it does not, are on Cedar support.

How a decision is made

Every check asks one question: may this principal (the signed-in user) do this action (update) to this resource (document 42)? Three rules answer it.

  • Nothing is allowed by default. A request is allowed only when at least one permit policy matches it.
  • A forbid wins. One matching forbid denies the request, whatever the permits say.
  • Order never matters. Policies are not tried in sequence, so you can move one between files without changing a decision.

A policy that fails while it runs, for example by reading an attribute the entity does not have, counts as not matching. It is logged once as a warning with the entity that caused it.

A thing the policies talk about is an entity: a type and an id, written Document::"42". The schema lists the types, their attributes and the actions. The policies say who may do what. A small piece of your own code, the entity sources, tells the policies what is true about a user or a document right now.

Start with one policy

The first app has one rule: the owner of a document may view and rename it. It takes four files.

The schema declares the entity types and the actions. Each action says which types may do it and to what:

cedarschema
entity User;
entity Document { owner: User, title: String };

action view, update appliesTo { principal: [User], resource: [Document] };

The policy says who is allowed. Read it aloud: permit a user to view or update a document when the document's owner is that user.

cedar
@id("owner")
permit (principal is User, action in [Action::"view", Action::"update"], resource is Document)
when { resource.owner == principal };

@id("owner") names the policy. The name shows up in logs, in the devtools and in tests. Without it the name is the file and line, such as documents.cedar:2.

entities.ts answers two questions the policies cannot: who is signed in, and what is true about a document. Read the session in principal, and return null when no one is signed in. A tableEntities source loads documents from your table, one column for each attribute of the schema:

ts
import { getUserSession } from "@hamur/auth/server"
import { tableEntities } from "@hamur/db/server"
import { defineEntities } from "hamur/server"

export default defineEntities({
  async principal(event) {
    const { user } = await getUserSession(event)
    return user ? { type: "User", id: user.id } : null
  },
  sources: {
    Document: tableEntities({
      table: "documents",
      attributes: { owner: { column: "owner_id", entity: "User" }, title: "title" },
    }),
  },
})

Last, the handler asks for the check with the authorize key:

ts
import { defineHandler } from "hamur/server"
import { useDatabase } from "@hamur/db/server"
import { schema } from "./schema.ts"

export const renameDocument = defineHandler({
  input: schema<{ id: string; title: string }>(),
  authorize: {
    action: "update",
    resource: (input) => ({ type: "Document", id: input.id }),
  },
  async handler({ id, title }) {
    await useDatabase().run`update documents set title = ${title} where id = ${id}`
  },
})

The check runs after the handler's middleware and after input is validated, and before handler. action is a string literal, because the build reads it. resource gets the validated input and returns the entity the action is done to.

That is the whole setup. renameDocument now runs only for the owner of the document.

The policy files are read at build time, and a mistake fails the build with its place. A misspelled attribute gives server/policies/documents.cedar:3:8: HAMUR_E1257 policy "owner": Document has no attribute "ownr" (it has: owner, title).

The same goes for an action that is not in the schema, in a policy or in an authorize key. Typegen writes the action and entity names from the schema, so authorize: { action: "updat" } also fails tsc. The policies never reach the browser: no client output holds a policy, a policy id or the schema.

What a denied request sees

CaseAnswer
no one is signed in (principal is null)401 Unauthorized; no policy runs
the resource does not exist404 Not Found
no permit matches, or a forbid does403 Forbidden, or 404 with denyStatus: 404

The error body holds the status and nothing else: no policy id and no reason, so a caller learns nothing about your rules. Add denyStatus: 404 to the authorize key when even the existence of a document is private, because a denied document then looks like one that is not there.

Every deny is logged at debug with the request id, for example authz deny User::"7" update Document::"42" (no permit), or (forbid "locked") when a forbid decided. To see the reason of one decision while you work, use explain or the Explain form of the devtools tab.

Add a role

Roles are entities too. A user is in a role, and a policy can ask principal in Role::"admin".

Change the schema in two places: add entity Role;, and change entity User; to entity User in [Role];. A Role has no attributes, so it needs no source: any id of it exists. A User now has a parent, so it needs a source. The role is a column of your users table, and tableEntities can read a column as a parent: add User: tableEntities({ table: "users", attributes: {}, parents: { role: "Role" } }) to sources in entities.ts. Then one more file lets admins do everything to a document:

cedar
@id("admin")
permit (principal in Role::"admin", action, resource is Document);

action with no condition means every action. in is true when the user is that role or has it as a parent.

A rule that nothing overrides

Say a locked document may be changed by an admin only. A forbid is the tool, since it beats every permit, the owner's included:

cedar
@id("locked")
forbid (principal, action == Action::"update", resource is Document)
when { resource.locked }
unless { principal in Role::"admin" };

when and unless are conditions. The forbid applies when the document is locked, unless the user is an admin. Add locked: Bool to Document in the schema and a locked attribute to its source ({ column: "locked", boolean: true }; boolean: true reads 0 and 1 as a boolean on sqlite and mysql).

A list page

A list must show only what the user may see. Loading every row and dropping some afterwards breaks paging and loads what the caller must never receive. authorizedWhere turns the policies into a SQL condition for the database to apply:

ts
import { defineHandler, authorizedWhere } from "hamur/server"
import { useDatabase, type Row } from "@hamur/db/server"

export const listDocuments = defineHandler({
  method: "GET",
  async handler(_input, { event }) {
    const allowed = await authorizedWhere(event, "view", "Document", { alias: "d" })
    return useDatabase().sql<Row<"documents">>`
      select d.id, d.title from documents d
      where ${allowed}
      order by d.id
      limit ${50}`
  },
})

authorizedWhere(event, "view", "Document") returns a fragment that you put in the query like any other value; the connection fills in its own placeholders. alias is the name of the table in your query, and it defaults to the table's own name. With no one signed in, or when no policy can permit, the condition selects nothing.

Add one more rule, which lets any signed-in user view a public document. It reads a new attribute: add public: Bool to the schema and public: { column: "is_public", boolean: true } to the source.

cedar
@id("public")
permit (principal is User, action == Action::"view", resource is Document)
when { resource.public };

The list now holds the user's own documents and the public ones, and every document for an admin, in one query.

Each limit is met where you hit it:

  • Only a tableEntities source can become SQL. A function source fails the call with authorizedWhere("view", "Document") needs a tableEntities source for Document; a function source cannot become SQL.
  • Only some conditions have a SQL form. A policy may compare an attribute of the resource with a value, test a set with contains, containsAny or isEmpty, and test the resource with ==, in and is. Arithmetic on an attribute, an extension type such as decimal on an attribute, containsAll, record attributes and tags have none. authorizedWhere lists them.
  • The build checks the call. When the action and the type are string literals, a policy with no SQL form fails the build with HAMUR_E1264, … uses resource.labels.containsAll(…), which has no SQL form; list with canEach instead. Load the rows and filter them with canEach, or rewrite the policy.
  • Index what you filter on. The condition is not served by an index. An index for the where and order by of your own query is.

Share one document with one person

The owner shares a document with Bob. The rule is the same for every document, but the fact is one row of data. A template is a policy with a placeholder for the person and the document, and a link fills the placeholders from your data.

The template sits in the same file as the policy that lets owners share:

cedar
@id("owner-may-share")
permit (principal is User, action == Action::"share", resource is Document)
when { resource.owner == principal };

@id("shared")
permit (principal == ?principal, action == Action::"view", resource == ?resource);

A template decides nothing alone. It applies only for the links you return. Your links function reads the shares table:

ts
import { useDatabase, type Row } from "@hamur/db/server"
import type { LinkSource } from "hamur/server"

export const shareLinks: LinkSource = async ({ principal, resourceType }) => {
  if (resourceType !== "Document") return []
  const rows = await useDatabase().sql<Row<"shares">>`select document_id from shares where user_id = ${principal.id}`
  return rows.map((row) => ({
    template: "shared",
    principal,
    resource: { type: "Document", id: row.document_id },
  }))
}

template is the template's id, its @id. A link gives exactly the placeholders its template has, here both. links runs once for each check. For a list, authorizedWhere calls it once without resource, so it must return the links of every document of resourceType, or the list shows fewer rows than canEach allows.

Pass it to defineEntities as links, as the finished entities.ts below does. The handler that adds a row is an ordinary handler with its own action, share, so only the owner can call it:

ts
import { defineHandler } from "hamur/server"
import { useDatabase } from "@hamur/db/server"
import { schema } from "./schema.ts"

export const shareDocument = defineHandler({
  input: schema<{ id: string; userId: string }>(),
  authorize: {
    action: "share",
    resource: (input) => ({ type: "Document", id: input.id }),
  },
  async handler({ id, userId }) {
    await useDatabase().run`insert into shares (document_id, user_id) values (${id}, ${userId})`
  },
})

Add share to the schema's action list. When the shared people are a few and live on the document itself, a set attribute does the same without templates: editors: Set<User> and when { principal in resource.editors }. Use links when the shares are many, or when they carry their own data.

Hide a button

The page can show a Rename button only to people who may rename. The server sends its decisions along with the data, and can reads them in the browser.

A hidden button is not protection. can only decides what the page shows. Anyone can call a handler without your page, so the server checks again on every call, with authorize or the authorize key. Never rely on can for security.

Call exposeDecisions in the handler that loads the data, with the actions and the resources the page will ask about:

ts
import { createError, defineHandler, exposeDecisions } from "hamur/server"
import { useDatabase, type Row } from "@hamur/db/server"
import { schema } from "./schema.ts"

export const getDocument = defineHandler({
  method: "GET",
  input: schema<{ id: string }>(),
  authorize: {
    action: "view",
    resource: (input) => ({ type: "Document", id: input.id }),
    denyStatus: 404,
  },
  async handler({ id }, { event }) {
    await exposeDecisions(event, ["update", "share"], [{ type: "Document", id }])
    const document = await useDatabase().first<Row<"documents">>`select id, title from documents where id = ${id}`
    if (!document) throw createError({ status: 404 })
    return document
  },
})

authorize still guards getDocument itself, and denyStatus: 404 hides a document the caller may not view. Then use can from hamur/app in the component:

tsx
import { useAsyncData } from "@hamur/adapter-react"
import { can } from "hamur/app"
import { getDocument } from "#server"

export function DocumentActions({ id }: { id: string }) {
  const { data: doc } = useAsyncData(getDocument, { id })
  if (!doc) return null
  const resource = { type: "Document", id } as const
  return (
    <>
      <h1>{doc.title}</h1>
      {can("update", resource) && <button>Rename</button>}
      {can("share", resource) && <button>Share</button>}
    </>
  )
}

What can does:

  • It returns false when the server sent no decision, because the default is deny. In dev, the browser console warns once for each missing one: can("update", Document::"42") has no decision from the server; call exposeDecisions(event, ["update"], …) in the handler that loads it.
  • It is not reactive. A component that calls it renders again when the data it came with changes.
  • The browser gets decisions, never policies: 1 or 0 for an action on an entity. A page or an answer that carries decisions is private, no-store, so no shared cache keeps one.
  • An answer carries at most 1000 decisions. More than that fails with exposeDecisions: an answer carries at most 1000 decisions (got 1500); expose fewer actions or page the list.
  • The decisions of one user are dropped when an answer names another, so a login or a logout never leaves the old user's buttons on the page. For that, principal must read the session itself, not something a middleware put on event.context.
  • In a handler that writes, call exposeDecisions after the write, so it decides on what was written.

A prerendered page and a handler with cache carry no decisions, since a stored answer would be shown to everyone.

Hide a field

Cedar has no rules for single fields. Give each guarded field an action of its own, then drop the field with redact when the action is denied. The note of a document is guarded by viewNote; add that action to the schema's list, and this policy:

cedar
@id("owner-notes")
permit (principal is User, action == Action::"viewNote", resource is Document)
when { resource.owner == principal };
ts
import { createError, defineHandler, redact } from "hamur/server"
import { useDatabase, type Row } from "@hamur/db/server"
import { schema } from "./schema.ts"

export const getDetails = defineHandler({
  method: "GET",
  input: schema<{ id: string }>(),
  authorize: { action: "view", resource: (input) => ({ type: "Document", id: input.id }) },
  async handler({ id }, { event }) {
    const row = await useDatabase().first<Row<"documents">>`select id, title, note from documents where id = ${id}`
    if (!row) throw createError({ status: 404 })
    return redact(event, row, { type: "Document", id }, { note: "viewNote" })
  },
})

redact returns a copy of the row without note when viewNote is denied on that document, when the document does not exist, and when no one is signed in. If the handler has an output schema, it must make note optional, or it refuses the copy with a 500.

Check in your own code

The authorize key covers a handler. For everything else, import the functions from hamur/server and pass the event:

ts
import { canEach, defineHandler } from "hamur/server"
import { useDatabase } from "@hamur/db/server"
import { schema } from "./schema.ts"

export const lockDocuments = defineHandler({
  input: schema<{ ids: string[] }>(),
  async handler({ ids }, { event }) {
    const allowed = await canEach(
      event,
      "update",
      ids.map((id) => ({ type: "Document" as const, id })),
    )
    const mine = ids.filter((_, index) => allowed[index])
    for (const id of mine) await useDatabase().run`update documents set locked = ${1} where id = ${id}`
    return { locked: mine.length, skipped: ids.length - mine.length }
  },
})
FunctionResult
authorize(event, …)returns, or throws 401, 404 or 403 as the key does
can(event, …)true or false; never throws for a denial
canEach(event, action, …)one boolean for each resource, in order; the entities of one type load in one call
explain(event, …)the decision with the policies that made it, the errors, the entities loaded and the time
getPrincipal(event)the principal, or null

Log what explain returns and never send it to the browser: it names your policies.

can is false when no one is signed in and when the resource does not exist. A decision is made once for each request, and entities are loaded once for each request. A mutation drops them, so a check after a write sees the new state. An entity source that throws, or an entity that does not match the schema, is a 500 and not a denial; a denial is never a way to hide a bug.

Never call a check inside principal, an entity source or links. It would wait for itself, and fails with an error that says so.

Test the policies

createAuthorizer from hamur/test reads the policies of server/policies/ with the build's own code and checks one request at a time. It runs with no server, no database and no entity sources. You pass the entities yourself, in the shape a source returns:

ts
import { expect, test } from "bun:test"
import { createAuthorizer } from "hamur/test"
import type { EntityRef } from "hamur/server"

const authz = await createAuthorizer()

type Entities = Parameters<typeof authz.check>[0]["entities"]

const user = (id: string, role?: string) => ({
  uid: { type: "User", id } as EntityRef<"User">,
  attrs: {},
  parents: role ? [{ type: "Role", id: role }] : [],
})

const documentOf = (owner: string, locked = false) => ({
  uid: { type: "Document", id: "42" } as EntityRef<"Document">,
  attrs: {
    owner: { type: "User", id: owner } as EntityRef<"User">,
    title: "Plan",
    public: false,
    locked,
  },
})

const check = (who: string, action: "view" | "update", entities: Entities) =>
  authz.check({
    principal: { type: "User", id: who },
    action,
    resource: { type: "Document", id: "42" },
    entities,
  })

test("the owner may update a document", () => {
  const result = check("ada", "update", [user("ada"), documentOf("ada")])
  expect(result.decision).toBe("allow")
  expect(result.determining).toEqual(["owner"])
})

test("someone else may not, since no policy permits it", () => {
  expect(check("bob", "update", [user("bob"), documentOf("ada")]).decision).toBe("deny")
})

test("a locked document needs an admin", () => {
  const locked = check("ada", "update", [user("ada"), documentOf("ada", true)])
  expect(locked.decision).toBe("deny")
  expect(locked.determining).toEqual(["locked"])
  expect(check("eve", "update", [user("eve", "admin"), documentOf("ada", true)]).decision).toBe("allow")
})

test("a link shares a document with one person", () => {
  const entities = [user("bob"), documentOf("ada")]
  const request = {
    principal: { type: "User", id: "bob" },
    action: "view",
    resource: { type: "Document", id: "42" },
  } as const
  expect(authz.check({ ...request, entities }).decision).toBe("deny")
  const links = [{ template: "shared", principal: request.principal, resource: request.resource }]
  expect(authz.check({ ...request, entities, links }).decision).toBe("allow")
})

determining holds the ids of the policies that decided: the matching forbids on a deny, the matching permits on an allow. An entity a policy needs and the test did not give is missing, so the policy fails and is listed in errors. That makes a forgotten entity a visible mistake, not a silent denial.

A policy that does not parse or validate throws the build's message with hamur/test: in front. A wrong action, or a principal or resource type the action does not apply to, throws instead of denying, for example hamur/test: check.action "mov" is not an action of the authorization schema (did you mean "move"?). The signatures are in the test API reference.

Keep these tests next to the policies: they are fast, and a changed policy should change a test with it.

See decisions in the devtools

An app with a server/policies/ folder gets an Authorization tab in the devtools, in the Server group.

PartShows
Policieseach policy with its effect, id, scope and file:line that opens in your editor; templates are marked
Schemathe entity types with their attributes and parents, and the actions with what they apply to
Decisionsthe last 200 checks of the dev server: time, principal, action, resource, the decision, the policies that decided, the ones that failed, entities and time
Explaina form: a principal such as User::"7", an action, a resource and a context as JSON; it answers why, with the text of each policy that decided

Decisions arrive live while you click through the app. Explain runs without a session, as the principal you type.

The finished files

The schema and entities.ts of the finished app, with the roles, the extra attributes, the actions and the links of the steps above:

cedarschema
entity Role;
entity User in [Role];
entity Document { owner: User, title: String, public: Bool, locked: Bool };

action view, update, share, viewNote appliesTo { principal: [User], resource: [Document] };
ts
import { getUserSession } from "@hamur/auth/server"
import { tableEntities } from "@hamur/db/server"
import { defineEntities } from "hamur/server"
import { shareLinks } from "../shares.ts"

export default defineEntities({
  async principal(event) {
    const { user } = await getUserSession(event)
    return user ? { type: "User", id: user.id } : null
  },
  sources: {
    User: tableEntities({ table: "users", attributes: {}, parents: { role: "Role" } }),
    Document: tableEntities({
      table: "documents",
      attributes: {
        owner: { column: "owner_id", entity: "User" },
        title: "title",
        public: { column: "is_public", boolean: true },
        locked: { column: "locked", boolean: true },
      },
    }),
  },
  links: shareLinks,
})

Where the check runs

The key runs on every way into a handler: its endpoint, its route, a form post, a call on the server during rendering, a socket upgrade, every connection and reconnect of a live handler, a JSON-RPC method and an MCP tool call. A handler with the key cannot run unchecked.

A page is protected by the data it reads: its load and its components call handlers, and a handler with authorize answers 401, 403 or 404 there as anywhere else. A route middleware may call can to steer a navigation, but that protects nothing.

Things to know:

  • No stored answers. A stored answer is not checked, so authorize with cache or prerender is refused: authorize cannot be used with cache or prerender: a stored answer is not checked. A path that such a handler answers cannot be prerendered, and a build that would do it fails.
  • Nothing is kept between requests. A role taken away applies at the next request. A stream that is already open is not closed by it; the next connection is refused.
  • Signed-out visitors. A request with no principal is stopped with 401 before any policy runs. A handler that anyone, signed in or not, may call has no authorize key.
  • Limits. One request loads at most 10 000 entities, and an entity's parent chain is at most 32 deep. Past that the check fails with a 500 and a log line.
  • Entity sources are checked. An entity whose attributes do not match the schema fails the check that loaded it with a 500 and a line such as entity source Document returned Document::"42" with attribute "public" = "yes"; the schema declares Bool.

Build errors

CodeWhat failed
HAMUR_E1255a Cedar file does not parse
HAMUR_E1256the schema is invalid, for example a type declared twice
HAMUR_E1257a policy does not validate against the schema
HAMUR_E1258policies, and no schema
HAMUR_E1259one policy id used twice
HAMUR_E1260server/policies/entities.ts does not default-export defineEntities
HAMUR_E1261a source names an entity type the schema does not have
HAMUR_E1262an entity type with attributes or parents has no source
HAMUR_E1263policies, and no entities.ts
HAMUR_E1264a policy of an authorizedWhere call has no SQL form

In hamur dev the message shows in the overlay and the server keeps the last good set of policies until the file is fixed. For the signatures of every function on this page see the server API reference and can. Coming from Laravel or CASL: Migrating from Laravel and CASL.