Writing policies
A policy is one class per resource with one method per action, and every action returns a boolean. This page covers how to write one that stays readable as the rules grow.
One class per resource
Extend Policy<TResource> once for each kind of thing your app guards: ArticlePolicy, InvoicePolicy, ProjectPolicy. The constructor takes the user first and the resource second and keeps them as this.user and this.resource. Both are protected, so code outside the policy cannot read them through it.
Keeping every rule for a resource in one class means one file answers "who can do what to an article", and a change to a rule is a change to one method.
One method per action
An action is a public method that returns a boolean, and you ask a policy by calling it: policy.update(). Name it after what the user wants to do: view, update, publish, archive. Because the question is a method call, TypeScript checks the name, and a misspelled action such as policy.udpate() is a compile error.
import { Policy } from '@blocks/policy'
export interface Article {
id: string
authorId: string
status: 'draft' | 'published'
archived: boolean
}
export class ArticlePolicy extends Policy<Article> {
view() {
if (this.resource.status === 'published') return true
return this.isAuthor() || this.isEditor()
}
update() {
if (this.resource.archived) return false
return this.isAuthor() || this.isEditor()
}
publish() {
if (this.resource.archived) return false
if (this.resource.status === 'published') return false
return this.isEditor()
}
archive() {
if (this.resource.archived) return false
return this.isEditor()
}
private isAuthor() {
return this.user.isOwner(this.resource.authorId)
}
private isEditor() {
return this.user.hasRole('editor', 'admin')
}
}Three habits keep this policy readable:
- Deny conditions come first.
update,publishandarchiveeach start withif (this.resource.archived) return false. The reasons to say no are at the top, one per line, and the rule that grants access is the last line. - Shared checks are private helpers.
isAuthorandisEditorgive a name to a check that several actions use. They are not actions: code outside the policy cannot call a private or protected method, sopolicy.isEditor()does not compile. - Actions can call each other. An action is an ordinary method. When one action requires everything another does, start it with that check, such as
if (!this.view()) return false.
An action takes no arguments. Everything it decides from is the user and the resource the policy was built with, so a call site asks the same question the same way everywhere. When a decision needs another value, make it part of the resource.
Decide from data you already have
Actions are synchronous. Load what the decision needs before you build the policy, and pass it in as the resource or on the user. An async action does not work: its result is a Promise, which is always truthy, so if (policy.view()) would allow everyone. Enforcing shows what goes wrong and the fix.
Sometimes the resource is not a database row but the answers to a few questions about one: did this user start the export, does the export belong to a team, does the user administer that team. Make those answers the resource. Each is a boolean or an id the server looked up, never a value taken from the request.
import { type CurrentUser, Policy } from '@blocks/policy'
/**
* What the server found out about one user and one file export. Every field
* comes from the database, never from the request.
*/
export interface DownloadFacts {
/** The user started the export. */
startedExport: boolean
/** The export belongs to a team. One that does not is a system export. */
belongsToTeam: boolean
/** The user administers the team the export belongs to. */
administersTeam: boolean
/** The user works in support. */
supportStaff: boolean
}
export class DownloadPolicy extends Policy<DownloadFacts> {
/**
* The user who started the export, an administrator of its team, and
* support. A system export is support's alone unless the user started it.
*/
download() {
const { startedExport, belongsToTeam, administersTeam, supportStaff } = this.resource
return startedExport || supportStaff || (belongsToTeam && administersTeam)
}
}
/** The lookups the server already has. */
export interface Lookups {
isTeamAdmin(userId: string, teamId: string): Promise<boolean>
isSupportStaff(userId: string): Promise<boolean>
}
export interface FileExport {
id: string
startedBy: string
teamId: string | null
}
/** Resolve the facts first, then build the policy, which decides synchronously. */
export async function downloadPolicyFor(user: CurrentUser, file: FileExport, lookups: Lookups) {
const { teamId } = file
const [administersTeam, supportStaff] = await Promise.all([
teamId === null ? false : lookups.isTeamAdmin(user.id, teamId),
lookups.isSupportStaff(user.id),
])
return new DownloadPolicy(user, {
startedExport: user.isOwner(file.startedBy),
belongsToTeam: teamId !== null,
administersTeam,
supportStaff,
})
}The policy holds the rule and nothing else. downloadPolicyFor does the lookups, in parallel, and skips the team lookup when there is no team. The policy can then be tested with plain objects, without the lookups.
When not to use a policy
A policy answers "can this user do this action to this resource". Other checks belong somewhere else:
- Authentication. Whether there is a signed-in user at all is decided before any policy runs. A policy needs a user to ask about.
- Route-level gating with no resource. "Only staff can open the admin area" has no resource to construct a policy with. Check it in middleware or the route itself.
- Quotas and billing limits. "This plan allows ten projects" is about counting, not about who the user is. Put the check next to the thing it counts.
These checks sit around your policies. Keep them out of the policy classes so each policy stays about one resource.