The policy language
A policy is one or more .authz files. This one uses most of the language; the list after it says what each part does.
app role app_user -- the role the policies apply to
include "roles.authz" -- split big policies into files
type user = app.users where {active} -- suspended users hold nothing
type team = app.teams
member : user = app.team_members(team_id -> user_id)
member : team#member = app.teams(parent_id -> id) -- declared twice: two sources;
-- sub-teams' members count too
type folder = app.folders where {not archived}
org : org = org_id -- from a column you already have
parent : folder, project = (parent_type, parent_id) -- inside a folder or a project
linked_into : folder = app.folder_links(folder_id -> parent_id) -- from a table you have
owner : user = owner_id
viewer : user, team#member, user:*, anyone, link shared by edit -- authz.share()
editor : user, team#member shared if {subject_type <> 'user' or subject_id in (select id::text from app.users where active)}
roles : user, team#member from org -- custom roles, defined at runtime by the org
can share = owner or org.admin or (parent.share and {inherit})
can edit = share or editor or roles or (parent.edit and {inherit and not locked})
can view = edit or viewer or roles or parent.view or linked_into.view -- roles: one that includes view
can break_glass = org.member -- may use authz.break_glass here
caveat business_hours = {authz.ctx('mode') = 'business'} -- conditions attached to single shares
caveat from_ip = {authz.ctx('ip') = arg('ip')}
scope read = select, view -- what a token may do (API keys, JWTs)
scope files = app.files.select, app.files.update, file.view, file.edit
rules app.files view app.files_visible -- also make a view with masked columns
select : view
insert : folder.edit and owner -- the new row names you as its owner
update : edit
update folder_id after : folder.edit -- checked on the row after the change
update id, owner_id, confidential : share -- only when these columns change
mask body : edit -- NULL in the view unless you may edit
delete : edit
invariants
never folder: share and not org.member -- checked by the tests and authz.check_invariants(); rowstile prove
-- finds a folder owner outside the org: the policy doesn't forbid it
test
user 3 can view file 11 -- against the data already there
user 3 cannot edit file 11
test "a folder's owner edits what is inside" -- brings its own data, rolled back after
given ann = {INSERT INTO app.users (id, name) VALUES (9001, 'Ann') RETURNING id}
given top = {INSERT INTO app.folders (org_id, owner_id, name) VALUES (1, $ann, 'Top') RETURNING id}
given f = {INSERT INTO app.files (folder_id, name) VALUES ($top, 'plan.txt') RETURNING id}
user $ann can edit file $f
as user $ann allowed {UPDATE app.files SET name = 'plan-2.txt' WHERE id = $f} -- as the app role
as user 7 refused {DELETE FROM app.files WHERE id = $f}
as user 7 sees 0 {SELECT FROM app.files WHERE id = $f}- The app role is the Postgres role the rules apply to, the one your app connects as. Its name is read as written, like a table's:
app role AppUseris the roleCREATE ROLE "AppUser"makes, whileCREATE ROLE AppUsermakesappuser. - Files:
include "roles.authz"reads another file, named from the folder of the file that includes it. The command reads included files from disk, and applying stores them with the policy. A file outside the policy's folder (above it, an absolute path, a path with a backslash or a drive) is refused (AZ108), and so is a file included twice. Each file's blocks are its own: a block ends at an include line and at the end of its file, so an included file starts with a line at the left margin. Its name may hold an apostrophe or a%, never a dollar quote's tag ($f$), which would end a generated function that names the file. - Keys: a type's key is
id bigintunless the type line says otherwise:(gid),(id uuid), or several columns for a composite key:type folder = app.folders (org_id, id). The type is the column's own: a 32-bit key, as Prisma'sIntor aserialmakes, is(id int).rowstile initwrites it, and applying says so when it is missing (AZ602). A key can't be a date, a time, an interval or money (AZ206): ids are kept as text, and these write theirs by the session's settings. Nor can it be anumeric, a float or abytea(AZ206): these write one value several ways, as2and2.0are one numeric. Nor can its text be compared by a collation that isn't deterministic (a case-insensitive one): two texts are one key there, and applying refuses it (AZ630). Its type is one of Postgres's own: applying refuses a key of an extension's type (citext), of a domain or of an enum (AZ629). After a key changes type, applying refuses while shares name ids the new type can't read (AZ627: delete them, then apply again). A relation points at such an object with its columns in square brackets:parent : folder = [org_id, parent_id],app.folder_teams([org_id, folder_id] -> user_id),(parent_type, [org_id, parent_id]). The user type's key is one column. - Rows that count:
where {...}on a type line says which rows do. A row that fails it holds nothing and passes nothing on: a suspended user, an archived folder and what is inside it, a disbanded team's members (also through the team that holds it). No rule allows anything on it either: the app role can't read, change or delete an archived folder, so it can't un-archive one. An invariant isn't asked of it either:never folder: not ownerholds on no archived folder. Leave such rows to a job that runs as the owner, or say it in permissions instead (can edit = ... and {not archived}). - Relations link rows to users or groups: from a column, from another table (
app.team_members(team_id -> user_id), or with the columns named:app.team_members(object: team_id, subject: user_id); optionallywhere {...}), from a polymorphic pair of columns(type_col, id_col), in the type's table or in a link table (app.backings(project_id -> (backer_type, backer_id))), or from shares people make (shared). Intable(this_col -> subject_col), the left column names this row and the right one what it links to: on a team,app.team_members(team_id -> user_id)reads the rows whoseteam_idis this team's id, each linking it to auser_id; andapp.teams(parent_id -> id), a table that links to itself, reads the teams whoseparent_idis this team's id, the teams inside it. Declare a relation again to add a source, of another type too (watcher : userandwatcher : doc). Named alone, a relation gives the users and groups it links to; the objects it links to give something when it is followed by one of their permissions (parent.view), and a relation that links to objects alone must be followed (AZ301). The type column of a polymorphic pair holds the policy's type names ('folder','project'): renaming a type changes what the rows link to, and a row naming a type the relation doesn't list links to nothing. - Shares: a
sharedrelation is given withauthz.share()by whoever holdsshareon the object, so the type needs acan share, or the relation names another permission:shared by edit. The giver must also hold each permission the relation feeds on the object (view, forcan view = ... or viewer): a share can't give what its giver doesn't hold.shared if {...}is a condition on the share being made (object_id,subject_type,subject_id,subject_relation), whichauthz.sharechecks: "only to active users". A relation may have severalsharedlines, each with its ownshared byandshared if, and compiling refuses a subject named on two of them with another permission or another condition (AZ212).authz.break_glasschecks it too, for whoever breaks the glass, and refuses them a relation it doesn't let them hold. Shares may expire or start later:authz.share's seventh argument is when it ends, its eighth when it starts. A share counts from its start, that instant included, until its end, that instant not included. A share goes with its object: deleting the object deletes its shares, so an object made again with the same id starts with none. A caveat is a condition that goes with one share and is checked at each request:authz.share('folder', 3, 'viewer', 'user', 4, '', NULL, NULL, 'from_ip', '{"ip": "10.0.0.1"}')givesviewerwhilecaveat from_ipholds,arg('ip')being what the share was made with. - Subjects:
user, a group such asteam#member(nested to any depth, loops are fine; after the#, any relation or permission of the group's type:team#manageis whoever holdsmanageon the team),user:*(any signed-in user),anyone(also signed out) andlink(anyone holding a share link's token). A share withuser:*oranyonenames no row: its id is*, as inauthz.share('folder', 3, 'viewer', 'anyone', '*'), and foranyoneany id given is read as*, with no relation after it. - Principals: services, API clients and agents can sign in as themselves:
type service = app.services principal. Relations name them like users (bot : service = bot_id,reader : user, service shared), andservice:*means any signed-in service.signed_inanduser:*stay about users. - Permissions combine relations with
or,and,notand parentheses, which say what goes first whereandandormeet:owner or (parent.edit and {inherit})(without them it is refused). Parentheses that change nothing,owner or (parent.edit or editor)or((owner or parent.edit) and {inherit}) and not hidden, are read as if they weren't there.rel.permfollows a relation (parent.edit,org.admin, or to a user's own:manager.oversee,author.has_blocked),signed_inmeans any user signed in,anyoneanyone at all, signed in or not (for rules on directories), andnobodynobody (update id : nobody),{...}is any SQL condition on the row (columns, subqueries,now(),authz.uid(), request context withauthz.ctx('mfa'), which the app sets in the transaction:SET LOCAL authz_ctx.mfa = 'yes'). A key the transaction didn't set is NULL, whatever an earlier transaction on the connection set, and so is a key set to''. Being SQL, a condition names a column as SQL does: one with capital letters, as Prisma makes them, takes double quotes there ({"parentId" is null}), while a relation's source is the bare name (parent : folder = parentId). A column may have any name, one that PL/pgSQL or rowstile calls something of its own by too (found,new,p_id): in a condition it is the column. - Conditions name their row
this: a bare column is the row's, unless a table the condition reads has one by that name, as most have anid. In a subquery, writethis.:{exists (select 1 from app.memberships m where m.project_id = this.id)}(withidalone, that would be the membership's id, and applying warns).thisis the object in a permission, a rule or an invariant, the type's row in itswhere, the link table's row in a link table'swhere, and the share being made inshared if. A caveat has no row.this.names the row whatever a subquery of the condition calls its tables, even by the name rowstile gives the row where it is checked. Names that start withauthz__are rowstile's own: a condition that writes one is refused (AZ113), and so is a table called so. A string, a quoted name or a dollar quote in a condition ends on the line it starts on (AZ114): a line break in a string isE'\n'. In a named test's statements, a quote may go on over several lines, and holds them as written. - Conditions read with the policy's rights, wherever they are checked (a rule, a permission, a caveat,
authz.can, another type's rule throughrel.perm), as relations do: a subquery sees every row of the tables it reads, not only those the signed-in user may. A function of the app's is called by its name, with parentheses:{app.is_member(this.org_id)}. One that Postgres calls without the condition's text showing it (a function of the row written as a column of it,{this.blocked}; a cast;OPERATOR(app.=)) would run with the app role's rights where a rule is checked, so applying refuses it (AZ628), unless it is IMMUTABLE and so reads nothing. In a write rule, they see the tables as the statement found them, without the other rows it writes: a count in a rule is no limit on how many rows there may be (Limits). A condition that is NULL holds nothing:{not archived}is false wherearchivedis NULL,not {archived}is true there. Where a relation says the same, write the relation:insert : folder.edit and ownerrather than{owner_id = authz.uid()}, whichrowstile proveand the review read as a fact about the row; your own row is a relation too (self : user = id, thencan edit = self). - Inheritance:
or rel.permback to the same type (or across types, like projects and folders inside each other) inherits as deep as it goes, through any mix of sources;and {condition}says where it stops. What inheritance holds is worked out once and stored, so a condition that limits it (and a link table's or a type'swherethat decides it) must give the same answer for everyone at any time. It can't read the clock (now(),current_timestamp,current_date,current_time,localtime,localtimestamp,clock_timestamp(),statement_timestamp(),transaction_timestamp(),timeofday(),age(x)with one argument, a date or time written'now','today','tomorrow'or'yesterday'), chance (random(),random_normal(),gen_random_uuid(),uuidv4(),uuidv7()), who asks or the session (authz.uid(),authz.ctx(),authz.principal(),current_user,current_role,session_user,user,system_user,current_setting(),current_schema,current_catalog,current_database(),pg_backend_pid(),txid_current(),pg_current_xact_id(),current_schemas(),pg_my_temp_schema(),pg_trigger_depth(),pg_has_role(),has_*_privilege()(has_table_privilege()and the others),row_security_active(),inet_client_addr(),inet_client_port(),inet_server_addr(),inet_server_port(),nextval(),currval(),lastval()): that is refused (AZ305). Applying then asks Postgres, which refuses a function of the app's that isn't IMMUTABLE and, in a condition that reads no other table, anything else that isn't (a cast that depends on the time zone) (AZ603). - Denies:
can view = (viewer or parent.view) and not hiddentakesviewaway on a hidden folder and everything below it, even from people who hold it higher up. The deny must inherit the same way (can hidden = blocked or parent.hidden), so it covers everything below; a deny on one object that only cuts inheritance there is refused, with a message saying so. Where the inheritance stops at conditions (parent.view and {inherit}), the deny's may stop at the same ones, in any order, or at fewer; with other conditions it is refused, and the message shows both. A deny can't inherit through a relation that also points at another type (parent : folder, project: give the projects a relation of their own), nor through another type's permission that comes back to it (aproject.viewthat inherits from folders): both are refused (AZ306). Another type's permission beside the deny is fine: in(viewer or parent.view or project.view) and not hidden,project.viewgivesviewlikeviewerdoes, andhiddentakes it away. A deny made of conditions on the row (can hidden = {hidden} or parent.hidden) is held by everyone on the rows it marks, as any permission of conditions alone is.authz.can,authz.listandauthz.permsanswer for the rows you may select, so on a table with a select rule they tell nobody which rows those are: a row you can't see reads as a missing one (App code). A condition joined the same way holds at every level:(viewer or parent.view) and {not archived}stops at an archived folder. - Custom roles:
roles : user, team#membersays who may hold roles people create at runtime (authz.create_role('org', 1, 'folder', 'reviewer', ARRAY['view'])) and share like relations. A permission writesroleswhere a role that includes it gives it, and a role may include the permissions that write it:can view = (viewer or roles or parent.view) and not hiddengivesviewto holders of a role that includes it, and the deny holds for them too, as it is written. Creating a role needsmanage_roleson its owner (can manage_roles = adminon the org type), and gives the role's id: the role is shared as the relationrole:<id>(authz.share('folder', 3, 'role:12', 'user', 7)), by someone who holdsshareon the object and everything the role grants. Changing what a role gives (authz.set_role_permissions(12, ARRAY['view', 'edit'])) needsmanage_rolestoo, and a permission it adds must be one the caller holds on each object the role is given on, as giving it there asks: else it is refused, asauthz.sharerefuses it (AZ705), naming the object, unless the caller can't see it. Taking a permission out needs nothing more, and a role given to nobody gives nothing, whatever it holds.from orgsays whose roles count on an object: only those of the org itsorgrelation links it to now (a column or a table, to one type).authz.sharerefuses another owner's role (with an error, AZ706: offering it is the app's mistake), an assignment of one grants nothing, and a folder moved to another org stops honouring the first org's roles. Withoutfrom, any role for the type counts wherever it is given, so an app must offer only the owner's roles. - Rules say what each command needs, per table, with column-level variants and masks. The plain
updaterule must hold on the row before and after the change (as Postgres checks both), unlessupdate after : ...says what must hold after it. A column rule checks the row before the change (update owner_id : share, orupdate owner_id before : share) or after it (update folder_id after : folder.edit: where a row moves to). A rule on the row after the change reads the columns Postgres works out itself too (a generated column): on a table that has one it is checked once the row is written (Limits).authz.lint()warns about a move in a tree (a column that links a row to another of its own type) that nothing checks the destination of, and about any column that gives a relation and that whoever may update the row may change, with no rule on it. A rule on the row before the change (update org_id : share) says who may move a row to another organisation, not to which:update org_id after : org.memberorupdate org_id : nobodysays that. An update two column rules both refuse is refused in the words of a rule on the row before the change first (update id, owner_idbeforeupdate folder_id after), then of the one whose columns come first in name order, whatever order the policy writes them in. A foreign key that deletes or changes a governed table's rows (ON DELETE CASCADE,SET NULLorSET DEFAULT,ON UPDATE SET NULLorSET DEFAULT) does so without the rules, and applying warns of it.cascade from app.folders, underrules app.files, says the key of files to folders does so as meant, and applying no longer warns of it. Where several keys of the table to that table act, the line says which by its columns:cascade from app.users (owner_id). Applying refuses a line that names no such key, or several (AZ625). Invariants state what must never be true, for everyone who can sign in (each user, each service or other principal) and for nobody. - The sync index (a preview):
sync role sync_enginenames a sync engine's Postgres role, andsync app.files : viewkeeps, for each row of a type's table, the keys that may read it (sync app.filesalone: those its select rule lets read it), for engines such as Electric to replicate (The sync index). What a synced permission reads can't depend on the clock, on who asks, or on other rows than its own: that is refused (AZ804, AZ805, AZ806).sync app.files : view by folderkeys each file's readers by its folder, rather than copying in the readers of each folder above: the file's readers name the folder's key (folder#view:7), and the index says whose own keys that key inherits, and what each folder gives itself.bynames a type with a permission that inherits (parent.view), which the synced permission reaches; another is refused (AZ810).sync after commithas a worker keep the index after each change commits, so writers don't wait for it.sync app.files : view mirroredkeeps a copy of the table for PowerSync, every column but the masked ones and each row's readers; withby, it is refused (AZ811). - Tests: the unnamed
testsection checks the data already in the database, with linesuser|<principal type> X can|cannot PERM TYPE ID(oranyone ...). Such a line checks the permission itself, whether X may select the row or not; whatauthz.cananswers X is asked withas user X sees 1 {SELECT WHERE authz.can(...)}. A named test,test "...", brings its own:given name = {SQL ... RETURNING id}rows (as whoever applies policies;$nameis what it returned, a key of several columns as its row text), then the same checks, andas user X allowed|refused {SQL}oras user X sees N {SELECT ...}, which run as the app role signed in as X. A write is refused if a rule or a missing privilege stops it, or if it changes no row (the rows it meant are hidden from X). An id is written as it is (11, a uuid) or in single quotes ('a b','it''s'):$annis what a given line returned, and'$ann'is that text. In a line's SQL,$annis the name where it is code, and text in a string or a comment:VALUES ($ann, 'Ann $smith'). Any other error, a unique key say, fails the check whichever was expected. Each named test runs in a transaction that is rolled back. What a line sets for its transaction (set_config(..., true), such as a share link's token inauthz_ctx.links) holds for the test's later lines, unless the line ends in an error. After who a line is about,with scope read(or several:with scope read, files) checks it as a key or a token limited to those scopes would be:user 3 with scope read cannot edit file 11,as user 3 with scope read refused {UPDATE ...}. A scope the policy doesn't have is a mistake (AZ503). A scope's name may go on with-or:(scope files:write = ...), and a test names it the same way:with scope files:write. Named tests may live in their own files (onlytest "..."blocks);rowstile testandrowstile devrun them, neverapply. A failing check explains itself.
Permissions the runtime asks for
Permission names are yours to choose, but six are asked for by name. The compiler refuses one of the first five declared where nothing would ask for it (AZ307).
| permission | on | lets its holders |
|---|---|---|
share | a type with shared relations | share them (unless shared by names another), see who has access (authz.who, authz.list_shares), decide access requests |
break_glass | a type with a relation shared with users | give themselves that relation for a while with authz.break_glass: audited, announced; a user, not a service (AZ715) |
impersonate | the user type | view the app as that user with authz.view_as: read-only, audited; a user, not a service (AZ715) |
manage_keys | a type that signs in | make and revoke its API keys (authz.create_api_key(..., 'service', '7')) |
manage_roles | the type that owns custom roles (roles : user from org) | create, change and delete those roles (a permission added held on each object the role is given on); a user, not a service (AZ715) |
view | the type that owns custom roles | list those roles with authz.roles_of, as holders of manage_roles may: each one's name and what it gives (the choices of a share dialog); a user, not a service (AZ715) |
Masked columns
rules app.files view app.files_visible plus mask body : edit creates a view with the rows select allows, where body is NULL unless the rule holds. The app role loses SELECT on body in the table itself (the other columns stay), so the view is the only way to read it. Applying refuses to go on if the column would still be readable through PUBLIC or another Postgres role. A later GRANT that makes it readable again isn't refused (that would need an event trigger, and so a superuser): authz.lint() reports it, and applying again takes it back. Removing the mask gives back what it took: the table-wide SELECT, or the SELECT of its own the column had (GRANT SELECT (id, body)), by applying, by a migration or by rowstile remove.
The view is the app's to build on: a view of your own over it, or a function that reads it. Applying and migrations replace it in place, so those go on working when the policy changes. Two things can't be done in place, and are refused with what is built on the view named (AZ617): taking the masked view out of the policy, and a change of the table's columns that the view can't follow (a column renamed; a new column is fine). Drop what you built, apply, and make it again.