Rules and functions
The rules a permission is made of: named rules, the built-in ones, the functions a rule may call, and why every check terminates. Part of the schema language.
Named rules and built-in rules#
Put reusable rules under the schema's top-level :rules, in Datomic rule
syntax:
- Lang
- EDN
:rules [[(list-owner? ?l ?u) [?l :lists/owner ?u]] [(on-list? ?l ?u) [?l :lists/owner ?u]] [(on-list? ?l ?u) [?l :lists/members ?u]] [(on-item-list? ?i ?u) [?i :items/list ?l] (on-list? ?l ?u)]]
- Each rule is
[(name ?arg ...) clause ...]. - Two definitions with the same name are two branches: the rule holds if
either branch holds (
on-list?above means owner or member). All branches must take the same number of arguments. - A rule may call other rules.
- Names may not start with
october--, and may not redefine a built-in.
Built-in rules, available everywhere:
| Rule | Holds when |
|---|---|
(authenticated? ?u) |
?u is a signed-in user |
(self? ?e ?u) |
?e is the user ?u (for rules on $users) |
(created-by ?e ?u) |
?u made the write that created ?e |
(has-role? ?u :role) |
?u holds tenant-wide role :role (see Roles) |
(has-role-on? ?u :role ?s) |
?u holds scoped role :role on entity ?s |
When you plan a schema, october checks that every rule call names a known rule with the right number of arguments, and that every attribute in a pattern exists:
- Lang
- Text
Refused (400 bad-schema): Permission :view of :items calls unknown rule owner?. Built-ins: authenticated?, created-by, has-role-on?, has-role?, self?; define others under the schema's :rules (see /docs/schema-rules#named-rules-and-built-in-rules) Refused (400 bad-schema): Permission :view of :items uses unknown attribute :items/nme in [?e :items/nme "x"]
What a rule may read#
A rule may read only these attributes, in patterns and in missing? and
get-else:
- your own entities' attributes, private entities included;
$users/idand the attributes you add to$users;$users/emailof the caller only:[?user :$users/email ?email];:db/ident,:db/txInstant,:tx/user,:tx/originand:tx/reason.
Anything else is refused at plan (and at boot): the private system
entities ($magicCodes, $userRefreshTokens), other Datomic or october
attributes, and a variable in the attribute position ([?e ?a ?v], which
would read any attribute).
$users/email is for checks on the caller: [?user :$users/email ?m] [(ends-with? ?m "@example.com")] holds when the caller signed in with
an @example.com address.
- Lang
- EDN
{:rules [[(admin? ?u) [?a :admins/user ?u]] [(author? ?e ?u) [?e :posts/author ?u]]] :entities {:admins {:attrs {:user {:type :ref :to :$users :required? true :unique? true :reverse false}} :permissions {:view true :create [(authenticated? ?user) (or-join [?e ?user] ;; an admin other than this new row (which, ;; on the state after the create, is one) (and [?a :admins/user ?user] [(!= ?a ?e)]) ;; or the very first admin, adding themselves (and [?e :admins/user ?user] (not-join [?e] [?o :admins/user _] [(!= ?o ?e)])))] :delete [(admin? ?user)]}} :posts {:attrs {:body {:type :string :min 1 :max 2000} :author {:type :ref :to :$users :required? true :default :auth/user}} :permissions {:view true :create [(authenticated? ?user) (author? ?e ?user)] :delete [(or-join [?e ?user] (author? ?e ?user) (admin? ?user))]}}}}
(admin? ?user) holds when an admins row names the caller. These are the
app's admins, rows in its own admins etype: october's word for someone
who administers a tenant is tenant admin, and that person can push this
tenant's schema and set its origins without being able to read one row here.
The first app admin adds themselves (no other admins row exists); after
that only an admin adds admins. The create rule is checked on the state after the
write, where the new row already exists, so the admin branch asks for an
admin other than the new row ([(!= ?a ?e)]): with a plain
(admin? ?user) anyone could make themselves one. In demo mode, the
first one to call createAdmin wins, so create the first admin before
you share the tenant. Run against a live server:
- Lang
- Text
bob createAdmin(userId: ada) FORBIDDEN (only the first admin, for themselves) ada createAdmin(userId: ada) ok (the first) bob createAdmin(userId: bob) FORBIDDEN cy deletePost(bob's post) FORBIDDEN ada deletePost(bob's post) ok (an admin) ada createAdmin(userId: cy) ok
The pattern's entity must be ?user (not inside an or-join or
not-join that leaves ?user out), or, in a named rule, an argument
that every call passes ?user to. A rule that reads another user's
email would answer questions about it to every viewer ("does this
item's owner's email end in @corp.com?", "has anyone signed up as
ceo@example.com?"), so it is refused:
- Lang
- Text
Refused (400 bad-schema): Permission :view of :items reads :$users/email of ?o, which is not the caller: a rule may read the app's own attributes, ... in [?o :$users/email ?m] Refused (400 bad-schema): Permission :view of :items reads :$userRefreshTokens/user, which rules may not read: a rule may read the app's own attributes, ... in [?t :$userRefreshTokens/user ?user]
Plan also checks the variable rules Datomic imposes, which would otherwise fail every query on the entity:
- Every branch of an
ormust use the same variables. When they don't, useor-joinand name the variables the branches share. or-joinandnot-joindeclare their variables in a vector first.- A
notneeds its variables bound by another clause of the same rule (any clause, before or after it). A variable that appears only inside thenotis refused; usenot-join [?vars]to name the shared ones, and the others stay local to it. Anot-join's declared variables must be bound outside it. - An expression's arguments must be bound: in
[(> ?n 3)], some other clause must bind?n.
- Lang
- EDN
;; refused: the branches use different variables [(or [?e :items/name "public"] (created-by ?e ?user))] ;; accepted [(or-join [?e ?user] [?e :items/name "public"] (created-by ?e ?user))]
- Lang
- Text
Refused (400 bad-schema): Permission :view of :items: every branch of an or must use the same variables, but its branches use [?e], [?e ?user]. Use (or-join [?vars ...] ...) to name the ones the branches share, in (or [?e :items/name "public"] (created-by ?e ?user)) Refused (400 bad-schema): Permission :view of :items: ?t in (not [?e :items/name ?t]) is bound by no other clause of the rule. Datomic needs every variable of a not bound outside it; use (not-join [?vars ...] ...) to name the ones it shares, the rest stay local
Then plan runs every permission rule once with Datomic itself, on an empty
database, and refuses one that Datomic can't run, with Datomic's reason
(for example a function that doesn't exist:
Permission :view of :items can't run: a function doesn't compile: ...).
Some errors only show with data, for example a function that throws on a
stored value. A query that hits one gets a GraphQL error with code
RULE_ERROR and Datomic's reason in extensions.reason (see
api-errors.md), not an internal error. Fix the rule and push
again.
Functions you can use in rules#
An expression clause, [(name arg ...)] (a test) or
[(name arg ...) ?result] (binds ?result), may call only these names.
Write them as shown, without a namespace. Nothing else is allowed: no
other function, no namespaced name (clojure.string/lower-case), no Java
method or class (.toUpperCase, Class/forName, new), and no code as
an argument. Arguments are variables, $, or plain values (strings,
numbers, keywords, booleans).
| Name | Example |
|---|---|
= |
[(= ?status "open")] |
!=, not= |
[(!= ?a ?b)] |
<, <=, >, >= |
[(< ?n 10)] (numbers, strings, instants) |
+, -, * |
[(+ ?a ?b) ?sum] |
/ |
[(/ ?a ?b) ?q]: two whole numbers round toward zero; no result for a zero divisor |
mod |
[(mod ?n 2) ?r] (whole numbers) |
starts-with? |
[(starts-with? ?email "admin@")] |
ends-with? |
[(ends-with? ?email "@example.com")] |
includes? |
[(includes? ?title "draft")] |
lower |
[(lower ?name) ?l] |
upper |
[(upper ?code) ?u] |
length |
[(length ?title) ?n] (characters in a string) |
matches? |
[(matches? ?slug "^[a-z-]+$")]: the regex is a string in the schema; it holds when the regex matches part of the string, so anchor it with ^/$. Bounded, see below |
missing? |
[(missing? $ ?e :posts/deleted-at)]: the entity has no value for the attribute |
get-else |
[(get-else $ ?e :posts/rank 0) ?rank]: the value, or the default |
nil?, some? |
[(some? ?x)] |
before?, after? |
[(before? ?starts ?ends)] (instants) |
A wrong type never fails the query: a test is false and a transform gives no result, so the rule doesn't hold.
matches? is bounded. You write the regex, but your users write the
strings it tests, and some regexes take time exponential in the string
(^(a+)+$ on "aaaa...a!"). So:
- At plan, the regex is at most 200 characters and has no
backreference (
\1,\k<name>). - A string longer than 10,000 characters is not tested:
false. - A match may read at most 1,000,000 characters, backtracking included
(a few milliseconds). A match that needs more gives up:
false.
Every bound fails closed: the rule doesn't hold, the row is hidden or
the write is refused, and nothing else slows down. An ordinary regex
(^[a-z0-9-]+$, @example\.com$) never comes near the step bound, but
nested quantifiers like (a+)+ or (a|aa)* can; write ^a+$ instead. There is no now: a rule's answer
changes only when data changes, so live queries stay right.
Anything else is refused at plan:
- Lang
- Text
Refused (400 bad-schema): Permission :view of :items: clojure.java.shell/sh isn't a rule function in [(clojure.java.shell/sh "id")]. Rules may call only these functions: != * + - / < <= = > >= after? before? ends-with? get-else includes? length lower matches? missing? mod nil? not= some? starts-with? upper (see /docs/schema-rules#functions-you-can-use-in-rules); nothing else is allowedEvery check terminates#
Every permission check october runs finishes. A rule is Datalog over the
data: patterns that match datoms, rule calls, not/or and their -join
forms, and only the functions listed above,
which are pure and bounded. It reads only the attributes it is allowed to
read, and there is no now. Such a query can only combine values that
are already in the database or written in the schema, and there are
finitely many of those, so it reaches its answer.
Recursion keeps that guarantee in one shape only. A rule may call itself, directly or through other rules, when every rule on that cycle uses only patterns, comparisons and rule calls. A manager chain is fine:
- Lang
- EDN
:rules [[(manages? ?u ?e) [?e :people/manager ?m] [?m :people/user ?u]] [(manages? ?u ?e) [?e :people/manager ?m] (manages? ?u ?m)]]
Two shapes are refused when you plan the schema (and when the server boots with it):
- A recursive rule that makes values. A rule on a cycle may not use
a function that binds a variable (
[(+ ?n 1) ?m],[(lower ?s) ?l],[(length ?t) ?n],[(get-else $ ?e :a 0) ?v]), and may not call a rule off the cycle that hands such a value back through an argument. Each round of the recursion could make a value the last round didn't have, without end. Tests like[(> ?rank 0)]are fine, and so is a helper rule that makes a value and keeps it to itself ([(senior? ?m) [?m :people/rank ?r] [(+ ?r 1) ?s] [(> ?s 5)]]). - Recursion through negation. A rule may not depend on itself inside
notornot-join, directly or through other rules: whether it holds would depend on it not holding. Negating a rule that is not on the cycle is fine.
- Lang
- Text
Refused (400 bad-schema): Rule manages? is recursive (manages? -> manages?) and uses + to make a value: each round could make a value the last didn't have, so its check might never finish. ... Refused (400 bad-schema): Rule manages? depends on itself through a negation (manages? -> blocked? -> manages?, with blocked? called inside not): Datalog can't evaluate that, since whether manages? holds would depend on it not holding. ...
A rule outside every cycle runs once for each binding, so it may use any of the functions.