october

The schema language

An october schema is one EDN map. From it october builds the database schema, the GraphQL API, the validation of every write and the permission check on every read and write. This page describes every key the schema takes.

See api.md for what the schema generates, and cli.md for how to push it.

Shape

{:entities {<etype> {:attrs       {<label> <attr spec>, ...}
                     :permissions {:view <rule> :create <rule> :update <rule> :delete <rule>}
                     :order       [:created-at :desc] ; optional: lists' default sort
                     :private?    false            ; optional
                     :graphql/type "Name"}          ; optional
            ...}
 :rules    [<named Datalog rule> ...]}             ; optional

The map is closed at every level: an unknown key is an error. At the top level only :entities and :rules are allowed, so an entity written outside :entities ({:notes {:attrs ...}}) is refused with a hint to move it, not accepted as a schema with no entities. Your schema is merged over a built-in system schema, which defines $users (see below).

The smallest useful schema:

{:entities {:items {:attrs       {:name {:type :string :min 1 :max 100}}
                    :permissions {:view   true
                                  :create [(authenticated? ?user)]}}}}

Anyone may read items; anyone signed in may create one. Nobody may update or delete one, because those actions are not declared.

Entities and names

  • An etype (entity type) is a keyword, usually a plural noun in kebab-case: :lists, :items, :task-lists. Its GraphQL type is the singular in PascalCase (TaskList); see api.md.
  • A label (attribute name) is a keyword in kebab-case: :title, :owner-note. On the wire it is camelCase: ownerNote.
  • Names that start with $ are reserved for system entities. You may add attributes to $users, but you can't create other $ entities.
  • Every entity has a built-in id (a UUID). Don't declare :id yourself.
  • Every entity also gets the read-only fields createdBy and createdAt in GraphQL. If you declare your own :created-by or :created-at label, your field replaces the built-in one.

Data attributes

{:type <type> ...options}. The types:

:type Stored as GraphQL type JSON on the wire
:string string String string
:long 64-bit integer Long number; a decimal string beyond ±(2^53 − 1)
:double 64-bit float Float number
:boolean boolean Boolean true / false
:instant point in time Instant ISO-8601 string, "2026-10-20T09:00:00Z"
:uuid UUID UUID string
:json JSON text JSON any JSON value

Options on any data attribute:

Key Meaning
:optional? true makes the attribute optional. Data attributes are required by default.
:indexed? Index the attribute. An indexed attribute becomes a list filter, and, if it is also required, an orderBy field. See Indexes.
:unique? No two entities may hold the same value. See Unique values.
:immutable? true: set on create, never changed. See Immutable attributes.
:view A rule that hides the value from some viewers. See Field-level :view.
constraints See the next section.

A :json attribute takes any JSON value (object, array, string, number). It reads back as the same JSON value.

Constraints and sanitisers

Constraints are checked on every create and update. A value that fails gives a VALIDATION_FAILED error with a message per field (see api.md).

Key Types Meaning
:min :string minimum length (a whole number)
:max :string maximum length
:min :long, :double minimum value (an integer on :long)
:max :long, :double maximum value
:pattern :string a regular expression the whole value must match (Java syntax)
:format :string :email (loose: something@something.tld) or :url (http:// or https://)

Sanitisers change a string before it is validated and stored:

Key Effect
:trim? removes leading and trailing whitespace
:collapse-whitespace? turns each run of whitespace (newlines too) into one space, and trims
:lowercase? lower-cases the value

Only the sanitisers you declare run. For example, with :format :email :lowercase? true but no :trim?, the input " CY@Example.COM" fails with should be a valid email because the leading space stays.

Example:

:profiles {:attrs {:handle  {:type :string :unique? true :indexed? true
                             :pattern "^[a-z0-9_]{3,20}$" :trim? true :lowercase? true}
                   :website {:type :string :format :url :optional? true}
                   :bio     {:type :string :optional? true :max 200 :collapse-whitespace? true}
                   :rating  {:type :double :min 0 :max 5 :optional? true}}
           ...}

With this schema, handle: " Cy_L " is stored as "cy_l", and bio: "Counts things\n carefully" is stored as "Counts things carefully". Bad values give one message per field:

"errors": {
  "handle":  ["should match the pattern ^[a-z0-9_]{3,20}$"],
  "rating":  ["should be at most 5"],
  "website": ["should be a valid http(s) URL"]
}

october checks the constraint options when you plan the schema. Examples of refused options: a constraint the type doesn't take (:pattern on a :long), :min greater than :max, a :pattern that doesn't compile.

Required and optional

Kind of attribute Default Change it with
data attribute required :optional? true
enum required :optional? true
ref optional :required? true

A required attribute must be given on create and can't be cleared with null on update. Refs reject :optional? and enums reject :required?, so there is one way to say each.

Immutable attributes

:immutable? true means that the attribute is set when the entity is created and never changes afterwards. Data, enum and ref attributes take it.

Kind of attribute Default
a required one-target ref immutable
everything else (data, enums, optional refs, many-refs) mutable

So an answer's :question, an item's :list and a post's :author are immutable unless you say :immutable? false:

:answers {:attrs {:body     {:type :string}
                  :question {:type :ref :to :questions :required? true}            ; immutable
                  :author   {:type :ref :to :$users :required? true :default :auth/user}}} ; immutable
:bookmarks {:attrs {:question {:type :ref :to :questions :required? true
                               :immutable? false}}}                                ; may be moved

An immutable attribute:

  • is left out of the update input (AnswerUpdateInput has body and no questionId), so the GraphQL types rule out the change;
  • can't be cleared with null;
  • has no add/remove mutations when it is a many-ref;
  • is marked @immutable in /schema.graphql, and "x-immutable": true in /schema.json.

A request that sends questionId to updateAnswer fails GraphQL validation. Behind the types, the write path refuses the change too, as VALIDATION_FAILED {"questionId": ["can't be changed after it is created"]}.

Turning immutability on or off (with :immutable?, or by making a ref required or optional) is listed under API in the plan, and is never destructive. Turning it off loosens the schema: read the next warning first.

:update rules and create-only conditions. The :update rule is not the :create rule: a condition that only :create checks does not hold for updates. Take a Q&A app where answers can't be added to closed questions, and answers may move:

:answers {:attrs {:question {:type :ref :to :questions :required? true :immutable? false
                             :update [[?e :answers/question ?q] (not [?q :questions/closed true])]}
                  ...}
          :permissions {:create [(authenticated? ?user) (author? ?e ?user)
                                 [?e :answers/question ?q] (not [?q :questions/closed true])]
                        :update [(author? ?e ?user)]}}

Without the field's :update, an author could create an answer on an open question, then move it onto a closed one with updateAnswer: the entity's :update rule only asks for the author. The field rule runs whenever question changes, on the state before and after the move, so the answer moves only between open questions. Or keep :question immutable (the default). See Field :update rules.

Unique values

:unique? true on a data attribute or a ref means that no two entities hold the same value. A create or update that uses a taken value fails:

{"code": "VALIDATION_FAILED", "errors": {"handle": ["already taken"]}}

A unique attribute is also indexed, so it becomes a list filter (profiles(first: 5, handle: "ada_l")). On a ref, :unique? also makes the reverse side a single value instead of a list (see the next section).

Indexes

An index is exactly what the API filters and orders on: october indexes an attribute when, and only when, it is a list filter or an orderBy field. :indexed? true asks for both. It has no effect (no index, no filter, no order) on:

  • a :json attribute;
  • an attribute with a :view rule (a filter or an order would reveal the value the rule hides);
  • long text: a :string whose :max is over 256. Give a string you want to filter or sort on a :max of 256 or less. A :string with no :max is indexed, but the plan warns: one long value would bloat the index.

A :unique? attribute is always a filter (and, when required, an order field), whatever its length: uniqueness needs the index anyway. Refs and enums are always indexed by Datomic, so their filters (<ref>Id, an enum value) need nothing. Private entities have no API; their :indexed? attributes are indexed as declared.

october plan lists every index a change adds or drops:

Indexes:
  adds an index on Deal.stage
  drops the index on Deal.notes: the API no longer filters or orders on it

Adding an index to an attribute that already holds data is safe and needs no downtime. Datomic builds the index in the background (seconds for tens of thousands of values). Until it is built, an orderBy on that attribute sorts in memory, and a filter on it is checked entity by entity: slower, but the answers are the same.

Refs (relationships)

A ref points from one entity to another. You declare it on one side only; october derives the other side.

:items {:attrs {:list {:type :ref :to :lists :required? true :reverse :items}}}

This gives Item.list: List and, on the other side, List.items(...): a paginated connection of the list's items.

Key Meaning
:to the target etype (required)
:many? true: a set of targets (a many-to-many). Default: one target.
:required? true: must be set on create; can't be cleared. A required one-target ref is also immutable by default (see Immutable attributes).
:immutable? true: set on create, never changed. false: may change on update. Default: true for a required one-target ref, else false.
:unique? true: no two entities may point at the same target, so the reverse side is one entity, not a list. Use it for one-to-one.
:component? true: the target belongs to this entity. Deleting this entity deletes the target too.
:reverse the label of the reverse field on the target, or false for no reverse field. Default: the source etype's name without $ (:items here).
:default :auth/user: on create, fill the ref with the signed-in user when the input leaves it out, and pin it: a write may set it only to the signed-in user. Only on a one-target ref :to :$users. See :default :auth/user.
:pinned? false: a :default :auth/user ref is a default only, and a write may name any user. Default: true. Only with :default :auth/user.
:view a rule that hides the ref from some viewers (see Field-level :view).

Refs take no constraints and no :indexed? (refs are always indexed).

In mutation inputs a one-target ref is <label>Id (listId) and a many-ref is <singular label>Ids (members gives memberIds, tags gives tagIds). See api.md.

Reverse field names

Two refs to the same etype can't both use the default reverse name. If you declare :owner and :members on :lists, both pointing at :$users, both reverse fields would be User.lists. Plan refuses the schema and tells you to set :reverse:

Refused (400 bad-schema): Label :lists is declared more than once on :$users: [:reverse-of :lists/owner], [:reverse-of :lists/members]. Set :reverse <label> (or :reverse false) on the ref to rename its reverse field.

The fix:

:owner   {:type :ref :to :$users :required? true :default :auth/user :reverse :owned-lists}
:members {:type :ref :to :$users :many? true :reverse :shared-lists}

One-to-one

:profiles {:attrs {:user {:type :ref :to :$users :unique? true :required? true
                          :default :auth/user :reverse :profile}}
           ...}

This gives Profile.user: User and User.profile: Profile (user is nullable although required: users are closed by default, see below). A second profile for the same user fails with {"userId": ["already taken"]}.

Components

:news   {:attrs {:cover {:type :ref :to :images :component? true}} ...}
:images {:attrs {:url {:type :string :format :url}}
         :permissions {:view true :create [(authenticated? ?user)]
                       :update [(created-by ?e ?user)]}}

Deleting a news item also deletes its cover image. Two rules apply:

  • To set a component ref (on create, update or add), the caller needs the :update permission on the target. An etype with no :update rule can't be made a component through the API.
  • A delete fails if the caller may not delete every entity it removes, components included.

Deleting the target of a required ref

When an entity is deleted, every ref to it is removed. If that leaves another entity without a required ref, the delete is refused (october restricts; it doesn't cascade). With the shared lists schema below, deleting a list that still has items gives:

{"message": "List has 3 Items that require it; delete them first",
 "extensions": {"code": "VALIDATION_FAILED",
                "blockedBy": [{"type": "Item", "field": "list", "count": 3, "deletable": true}]}}

Only the blockers the caller can see are counted; others are mentioned without a number or a type (hiddenBlockers: true). Delete the items first (deleteItems(ids: [...]) takes them in one transaction, all or nothing; see api.md), or model the children as a :component? ref on the parent. A batch delete covers one etype, so the items and then the list are two calls. If the caller can't delete the blockers (no :delete rule on items, or it refuses them), the message says so: "List has 3 Items that require it, and they can't be deleted, so neither can this List", with deletable: false.

:default :auth/user

:author {:type :ref :to :$users :required? true :default :auth/user}

A create that leaves out authorId gets the signed-in user. The ref is also pinned: a create or an update may set it only to the signed-in user, so nobody can write a post "by" someone else, whatever the rules say. Naming another user is refused before any rule runs:

ada  createPost(body: "hi")                  ok, author ada
ada  createPost(body: "hi", authorId: ada)   ok
ada  createPost(body: "hi", authorId: bob)   VALIDATION_FAILED {"authorId": ["can only be the signed-in user"]}

A required ref is immutable too (see Immutable attributes), so authorId isn't in the update input. An optional pinned ref (an assignee that defaults to whoever creates the task) stays in the update input, and an update may set it to the caller ("assign it to me") or clear it, never to someone else. The input field's description in the GraphQL schema says so. /schema.json doesn't list the attribute as required.

To let a write name another user (a gift "for" someone, a task assigned to a teammate), opt out with :pinned? false:

:assignee {:type :ref :to :$users :default :auth/user :pinned? false}

Then the default only fills in a missing value, and the rules must say whom a caller may name: check it in :create, and in the attribute's own :update (see Field :update rules).

Changed (November 2026). Before, the ref was a default only: a write could name anyone unless a rule checked it. october plan shows the pin under Permissions for each such ref of a tenant last pushed before then ("now pinned: ...: the system default changed"), with how to opt out, until the next push (see Changing a schema). The pin applies from the first boot of the new server, not from the push.

:on-erase :excise

:user {:type :ref :to :$users :required? true :unique? true :default :auth/user :on-erase :excise}

When the user this ref points at is erased (see api.md), the entity goes with them: retracted, and excised from history. Use it for records that are about the person (a waitlist entry, a profile), not for what they made for others: a post or a deal stays, with its author an anonymous tombstone. Only on a ref to $users, and nothing may point at an entity that has it (the ref would be left pointing at nothing).

Enums

:stage {:type :enum :values [:draft :in-review :published]}
  • :values is a non-empty list of unqualified keywords, in kebab-case.
  • In GraphQL the enum type is <Type><Label> (NewsStage) and each value is UPPER_SNAKE_CASE: DRAFT, IN_REVIEW, PUBLISHED.
  • An enum is required unless :optional? true. Every enum attribute is a list filter (news(first: 5, stage: PUBLISHED)).
  • An enum takes no :many?, :unique?, :indexed?, :default or :required?.
  • In a permission rule, a value is the keyword :<etype>.<label>/<value>: [?e :news/stage :news.stage/published].
  • Adding a value is a safe change. Removing one is refused.
  • true, false and null are not allowed as values.
  • :transitions {:draft #{:in-review} :in-review #{:draft :published}} limits the moves an update may make; see :transitions on an enum.

The built-in $users entity

Users are created by sign-in (see api.md), never by mutations. Every tenant has its own users: the same email in two tenants is two users.

The system schema defines:

:$users {:permissions {:view [(self? ?e ?user)]}
         :attrs {:email {:type :string :unique? true :format :email
                         :view [(self? ?e ?user)]}}}
  • In GraphQL the type is User, with the roots users, user(id:) and me.
  • Users are closed by default. A signed-in user sees only themself (me, and themself in users and user(id:)); a signed-out caller sees no users. Wherever a user the caller can't see would appear, it is null: an author ref, createdBy, a member in a list of members. A <ref>Id filter naming such a user matches nothing, as for an id that doesn't exist. A write naming such a user (authorId, addListMembers) is NOT_FOUND, as for any target the caller can't see.
  • email is visible only to the user themself, whatever the rule on $users says.

You may add attributes and refs to $users:

:$users {:attrs {:display-name {:type :string :optional? true :min 1 :max 40
                                :trim? true :collapse-whitespace? true}}}

You may not redefine email or set :graphql/type on $users. When you add attributes, october generates updateUser(id:, input:), and a user may update only themself and only the attributes you added. A user's attributes are readable by whoever may see the user; put a :view rule on one that is for fewer people.

Who may see users

Declare :permissions {:view <rule>} on $users to show users to more people. It replaces the default (keep (self? ?e ?user) in it, or users won't see themselves), and :view is the only action you may set on $users: users come from sign-in, and updateUser is built in. Show people the users they have a reason to see:

;; authors of things I can see: myself, and anyone who wrote a post
;; (posts here are readable by everyone, so signed-out readers see authors too)
:$users {:permissions {:view [(or-join [?e ?user] (self? ?e ?user) [_ :posts/author ?e])]}}

;; teammates: myself, and anyone on a team with me
:$users {:permissions {:view [(or-join [?e ?user] (self? ?e ?user) (teammate? ?e ?user))]}}

When the things are not public, join them to their own rule, so a user is visible exactly when something they wrote is: (and [?p :posts/author ?e] (can-see-post? ?p ?user)).

Avoid true and [(authenticated? ?user)]: with either, anyone who signs up can list every user of your app (and their display names, and every attribute without its own :view). october plan warns when the rule lets every signed-in caller see every user: "anyone who signs up can list every user".

To let people share with someone they have nothing in common with yet (adding a list member, inviting to a team), that person must be visible to them first. One way is an opt-in the user sets on themself:

:$users {:attrs       {:findable {:type :boolean :optional? true}}
         :permissions {:view [(or-join [?e ?user]
                                       (self? ?e ?user)
                                       (shares-list? ?e ?user)
                                       (and (authenticated? ?user) [?e :$users/findable true]))]}}

Changed (October 2026). Before, $users was readable by anyone (:view true). A tenant whose schema declares no $users :view now gets the closed default; october plan shows it as a $users permission change ("view true -> [(self? ?e ?user)]: the system default changed") until the next push. To keep the old behaviour, declare a rule as above.

Refs from your entities to $users add reverse fields to User (for example User.ownedLists).

Who may erase a user

:$users {:permissions {:view  [(or-join [?e ?user] (self? ?e ?user) (has-role? ?user :operator))]
                       :erase [(has-role? ?user :operator)]}}

:erase (on $users only) adds eraseUser(id:): whoever passes the rule (?e is the user to erase) erases a user they can see, as eraseMe erases oneself (see api.md). Without it there is no eraseUser, and only the user (eraseMe) and the tenant's admins (october erase) can erase.

Permissions

Each entity's :permissions maps an action to a rule:

Action Checked when
:view on every read: list roots, by-id roots, nested fields, live queries
:create on the new entity, as it would be after the write
:update on the entity before and after the change, so a user can't hand an entity to someone else. A rule with (before ...) is instead checked once over both states. Not the :create rule: put create-only conditions on the attribute's own :update, or make it immutable (see Field :update rules and Immutable attributes)
:delete on the entity before the delete, and on every component the delete removes

A rule is one of:

  • true: anyone, signed in or not.
  • A vector of Datalog :where clauses, all of which must hold. Two variables are bound: ?e is the entity and ?user is the signed-in user. Any other variable is local to the rule.

An absent action is denied. If you leave out :delete, nobody can delete, and october generates no delete mutation.

In october, a missing rule means no access and no mutation — not a table open to anyone.

Defaults

What you get when you write nothing:

You leave out What happens
:view on an entity Nobody can read it. Its type and roots are still generated, but lists are always empty, by-id roots answer null, and a create or update succeeds but answers null with a NOT_VIEWABLE warning in extensions.warnings. october plan warns: "nobody can read Note", or "Note can be created but never read" when it has a write rule.
:create, :update or :delete Nobody can do it, and there is no mutation for it.
:permissions altogether Nobody can read or write the entity through the API.
:view on an attribute Anyone who can read the entity reads the attribute. october plan warns when you add such an attribute to an existing entity: "new field Employee.salary is readable by anyone who can read Employee, including signed-out users" (or, when only signed-in users can read the entity, a gentler note).
:update on an attribute Any update the entity's :update rule allows may change it.
:pinned? on a :default :auth/user ref It is pinned: a create or update may set it only to the signed-in user (see :default :auth/user).
:view on $users Each user sees only themself; signed-out callers see no users. Authors and createdBy that the caller can't see are null. email is always the user's own only. Widen it with your own $users :view (see Who may see users); october plan warns when that lets anyone who signs up list every user.

Anonymous callers: an anonymous caller never evaluates anything that mentions ?user (also inside not, or, or a rule call). true and rules that never mention ?user work for them as for anyone. A rule that mentions ?user is cut for them: each top-level or (or or-join) keeps only its branches that don't mention ?user, and the rule's other top-level clauses stay. If one of those other clauses mentions ?user, or an or has no such branch, the rule is denied to anonymous callers. Signed-in callers always get the whole rule. See Published or mine below.

The same applies to :create, :update and :delete: an anonymous write through a user-free branch is allowed, just as with true. An anonymous write that can't pass gets UNAUTHENTICATED.

A rule sees the database after the write for :create (so it can check the new entity's own values) and the entity's refs as stored. A write is decided on a snapshot; if anything a rule read changes before the write commits (a moderator role revoked, an answer added), october decides the write again on the new data, so a rule never passes on stale data. Patterns compare refs by entity, so [?e :lists/owner ?user] means "the owner of ?e is the caller".

Examples:

;; public read, signed-in write as yourself, edit and delete your own
:permissions {:view   true
              :create [(authenticated? ?user) (post-author? ?e ?user)]
              :update [(post-author? ?e ?user)]
              :delete [(post-author? ?e ?user)]}

;; private to the author
:permissions {:view   [(author? ?e ?user)]
              :create [(authenticated? ?user) (author? ?e ?user)]
              :update [(author? ?e ?user)]
              :delete [(author? ?e ?user)]}

;; public read of published items only (no ?user, so it works anonymously)
:permissions {:view [[?e :news/stage :news.stage/published]] ...}

;; a reply needs an unlocked thread
:create [(authenticated? ?user) (post-author? ?e ?user)
         [?e :posts/thread ?t] (not [?t :threads/locked true])]

;; using the built-in creator rule instead of an author attribute
:permissions {:view   true
              :create [(authenticated? ?user) (created-by ?e ?user)]
              :update [(created-by ?e ?user)]
              :delete [(created-by ?e ?user)]}

The check [(authenticated? ?user) (author? ?e ?user)] on create is what stops a caller from naming someone else as the author: the create would give FORBIDDEN.

Hidden and missing are the same to a client. An entity the caller can't view is left out of lists, is null from a by-id root, and gives NOT_FOUND to a mutation.

Field-level :view

Any attribute or ref may carry :view <rule>. When the rule fails for the viewer, the field reads as null. The field is nullable in GraphQL, and it is never a filter or an orderBy field, so a filter can't reveal the value.

:owner-note {:type :string :optional? true :max 500
             :view [(list-owner? ?e ?user)]}

Members of the list see ownerNote: null; the owner sees the value. A field with a :view rule can be written only by a caller for whom the rule holds.

createdBy is also guarded: if an entity has a :default :auth/user ref with a :view rule (an anonymous author, for example), createdBy is null unless that rule holds, because the creator is the person the rule hides.

Field :update rules, before and :transitions

An attribute may carry its own :update rule. It is checked only when a write changes that attribute, in addition to the entity's :update rule. Inside an :update rule (the entity's or an attribute's), (before clause ...) reads the entity as it was before the write; every other clause reads it as it is after. Together they say what a plain rule over one state can't: who may hand a record on, which way a flag may move, which moves a status may make.

Only the owner may hand a deal on

:deals {:attrs       {:title {:type :string :min 1 :max 200}
                      :owner {:type   :ref :to :$users
                              :update [(before [?e :deals/owner ?user])]}}
        :permissions {:view   true
                      :create [(authenticated? ?user)]
                      :update [(authenticated? ?user)]
                      :delete [[?e :deals/owner ?user]]}}

Any signed-in teammate may edit a deal, but only the caller who owned it before the write may change owner: give it to someone else, or clear it. Without the field rule, the owner-only :delete would not protect anything: a teammate could set owner to themselves, then delete.

mate   updateDeal(title: "Acme 2")            ok
mate   updateDeal(ownerId: <mate>)            FORBIDDEN, extensions.field "ownerId"
mate   updateDeal(ownerId: <owner>)           ok (the value it has: not a change)
mate   deleteDeal                             FORBIDDEN (not the owner)
owner  updateDeal(ownerId: <mate>)            ok
mate   deleteDeal                             ok (mate owns it now)

Published moves one way

:published {:type :boolean :update [(before [?e :articles/published false])]}

The rule runs only when published changes, so before false means the move is false to true. Unpublishing is FORBIDDEN with extensions.field "published".

The author may close but never reopen

:tickets {:attrs       {:title  {:type :string}
                        :closed {:type   :boolean
                                 :update [(before [?e :tickets/closed false])]}
                        :author {:type :ref :to :$users :required? true :default :auth/user}}
          :permissions {:view   true
                        :create [(authenticated? ?user) [?e :tickets/author ?user]]
                        :update [[?e :tickets/author ?user]]}}

The author edits the ticket and closes it; nobody reopens it. The title stays editable, because the field rule runs only when closed changes.

:transitions on an enum

:stage {:type        :enum :values [:open :won :lost :archived]
        :transitions {:open #{:won :lost} :won #{:archived} :lost #{:archived}}}

:transitions {from #{to ...}} lists the moves a write may make. It compiles to a field :update rule (ANDed with the attribute's own :update, when it has one):

  • a listed move passes; any other change of the value is FORBIDDEN with extensions.field "stage";
  • setting the value it already has is not a move, so it always passes;
  • a value that is not a key (:archived here) is terminal;
  • a create may set any declared value: the transitions govern updates only. To restrict where entities start, say so in :create ([?e :deals/stage :deals.stage/open]);
  • an optional enum with no value may be set to any value, as a create may; clearing it (null) is never a move, so it is refused.

Every value named must be in :values; :transitions on anything but an enum is refused.

How field rules and before work

  • When a field rule runs: the write's own changes decide it. A datom of that attribute on the entity asserted or retracted: setting, changing or clearing the value, and add<T><Ref>/remove<T><Ref> on a many-ref. Setting a value it already has (or adding a target that is already there) changes nothing, so the rule doesn't run. Creates and deletes don't run field :update rules.
  • A failure is FORBIDDEN with extensions.field, the input field (ownerId, tagIds, stage). For an anonymous caller, a rule that mentions ?user is UNAUTHENTICATED, as for the entity's rules.
  • before goes at the top level of an :update rule. Its clauses read the state before the write; patterns, rule calls, not, or and the -join forms inside it all do. (before (owner? ?e ?user)) calls a named rule on the state before. Variables join across: (before [?e :deals/owner ?old]) [?e :deals/owner ?new] [(!= ?old ?new)].
  • Without before an :update rule keeps its old meaning: it must hold on the entity before and after the write (so [[?e :tickets/closed true]] on its own would refuse closing: before the write it isn't closed). A rule with before is checked once, over both states.
  • Refused at plan: before in :view, :create, :delete or a field :view; before inside before, or inside an or/not (put the or inside before instead); before in a named rule under :rules; a before that shares no variable with the rest of the rule (?e and ?user count); a field :update or :transitions on an immutable attribute (it never changes).
  • Races: what a before clause read is watched like any other read of a rule, so if the owner changes between the check and the commit, the write is decided again on the new data.
  • /schema.graphql shows a field's rule as @auth(update: "...") on the field; the plan lists changes to it under Permissions.

Named rules and built-in rules

Put reusable rules under the schema's top-level :rules, in Datomic rule syntax:

: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:

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#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/id and the attributes you add to $users;
  • $users/email of the caller only: [?user :$users/email ?email];
  • :db/ident, :db/txInstant, :tx/user, :tx/origin and :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.

Warning: in demo mode anyone can sign in as any email. A tenant in demo mode hands out the sign-in code in the response (api.md), so a caller can be ceo@example.com by typing it. A rule keyed on the caller's email (an "admin?" by address, a company domain) then protects nothing. Even outside demo mode, an email check is only as strong as sign-in. Keep roles in your data instead, granted by someone who already holds one:

{: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:

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:

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 or must use the same variables. When they don't, use or-join and name the variables the branches share.
  • or-join and not-join declare their variables in a vector first.
  • A not needs its variables bound by another clause of the same rule (any clause, before or after it). A variable that appears only inside the not is refused; use not-join [?vars] to name the shared ones, and the others stay local to it. A not-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.
;; 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))]
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.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:

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#functions-you-can-use-in-rules); nothing else is allowed

Every 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:

: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 not or not-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.
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.

Writing rules: patterns that work

  • Owner plus members. Use a named rule with two branches, as on-list? above.
  • Children inherit from the parent. Follow the ref, then call the parent's rule: [(on-item-list? ?i ?u) [?i :items/list ?l] (on-list? ?l ?u)].
  • Write as yourself. :default :auth/user does it: the ref is pinned to the caller (see :default :auth/user). A create rule that checks the ref, such as (author? ?e ?user), is still a good second line, and the only one with :pinned? false.
  • Public, but only some rows. Use clauses that don't mention ?user, like [?e :news/stage :news.stage/published].
  • Public rows and private rows in one entity: a top-level or-join with a user-free branch. See Published or mine.
  • States and moves between them (closed, deleted, draft): see Patterns.
  • Joining by code or invitation: a user can't add themself to a list whose :update rule is owner-only. Model an invitation as its own etype that the invited user may create, or let the owner add members.

Published or mine

Posts that anyone may read once published, while each author also sees their own drafts:

{:rules    [[(author? ?e ?u) [?e :posts/author ?u]]]
 :entities {:$users {:permissions {:view [(or-join [?e ?user] (self? ?e ?user)
                                                   (and [?p :posts/author ?e] [?p :posts/published true]))]}}
            :posts {:attrs       {:title     {:type :string :min 1 :max 200}
                                  :published {:type :boolean}
                                  :author    {:type :ref :to :$users :required? true :default :auth/user
                                              :reverse :posts
                                              :view [(or-join [?e ?user] [?e :posts/published true] (author? ?e ?user))]}}
                    :permissions {:view   [(or-join [?e ?user] [?e :posts/published true] (author? ?e ?user))]
                                  :create [(authenticated? ?user) (author? ?e ?user)]
                                  :update [(author? ?e ?user)]
                                  :delete [(author? ?e ?user)]}}}}

The branches use different variables, so it is an or-join that names ?e ?user (a plain or is refused at plan). A signed-in caller gets the whole rule: published, or theirs. An anonymous caller gets only the branch without ?user: published. The :view on author follows the same rule, so the author of a draft (and its createdBy) stays hidden. :create starts with (authenticated? ?user) outside any or, so anonymous callers can't create posts. Users are closed by default (each sees only themself), so the $users rule opens the authors of published posts to everyone: without it, author would be null for everyone but the author.

Alice created "Hello world" (published) and "Draft". The query { posts(first: 10) { items { title published author { id } } } } gives:

anonymous: {"posts":{"items":[{"title":"Hello world","published":true,"author":{"id":"2bbb08a2-..."}}]}}
alice:     {"posts":{"items":[{"title":"Hello world","published":true,"author":{"id":"2bbb08a2-..."}},
                              {"title":"Draft","published":false,"author":{"id":"2bbb08a2-..."}}]}}
bob:       {"posts":{"items":[{"title":"Hello world","published":true,"author":{"id":"2bbb08a2-..."}}]}}

An anonymous createPost gets UNAUTHENTICATED. An anonymous live query on posts gets a push when Alice publishes her draft.

Anonymous callers never run a branch that mentions ?user, so a not or not-join over the user can't let them through: in (or-join [?e ?user] [?e :posts/published true] (not [?e :posts/author ?user])) an anonymous caller is held to [?e :posts/published true] only.

Roles and grants (RBAC)

A role is declared in the schema and granted to users as data, so changing who holds one — who runs the app, who edits a team, who owns a deal — is a write, not a schema push, and no email address goes in a schema.

An app names its roles what it likes. october reserves no word inside a tenant's schema, so :operator below is simply the october waitlist's name for the people who keep the list.

{:roles    {:operator {:doc "Runs the waitlist"}
            :owner    {:scope :teams :doc "Owns a team" :grant [(has-role? ?user :operator)]}
            :editor   {:scope :teams
                       :grant [(or-join [?scope ?user] (has-role-on? ?user :owner ?scope) (has-role? ?user :operator))]}}
 :entities {...}}
Key Meaning
:scope Absent: the role is tenant-wide. An app entity (:teams): the role is held on one entity of it (editor of a team).
:grant The rule saying who may grant and revoke the role: ?user is the granter, ?scope (scoped roles only) the entity the role is held on. Absent: only the tenant's admins (october roles, the admin API). true: anyone signed in.
:doc A description, shown by october roles.
:retired? true: the role's grants are kept, but no new grants are made and no rule may test it.

Rules test roles with two built-ins, plain Datalog over the grants:

[(has-role? ?user :operator)]                          ; tenant-wide
[[?e :docs/team ?t] (has-role-on? ?user :editor ?t)]   ; held on the doc's team

The role is a keyword literal naming a declared role, tenant-wide for has-role? and scoped for has-role-on?, or the plan refuses it. A rule that calls either mentions ?user, so it fails closed for signed-out callers (inside an or, the other branches still serve them: see Published or mine). Roles work inside or, not and named rules like any rule call, and a write's check watches the grants it read: a grant revoked between the check and the commit makes the write retry, and then it is refused.

Granting and revoking

  • The tenant's admins grant any role, whatever its :grant rule: october roles SLUG grant operator ada@example.com (see cli.md). That is how the first grant of every role is made.
  • Through the API, grantRole(role: OPERATOR, email: "...") or grantRole(role: EDITOR, userId: ..., scopeId: <team id>) and revokeRole(id: ...), checked against the role's :grant rule (see api.md). Granting what is already granted returns that grant. Grants are attributed writes like any other: grantedBy is the granter (null for an admin's), and the transaction is in history.
  • By email, a grant is held by whoever signs in with that address, from their first sign-in on (nothing to accept or claim). It shows its email, never a user, so a granter doesn't learn whether the address has an account. In demo mode anyone can sign in as any email, so grants by email are refused there (grants to a user id still work), and demo mode can't be turned on while a tenant has any.
  • By id, the granter must be able to see the user (users are closed by default: see Who may see users). The holder of a grant by id may revoke it themself (leave the role).
  • Deleting a scope entity deletes the grants held on it.

Who sees grants: each user their own (viewer { roles }), and whoever may grant a role (its :grant rule holds, on that scope) that role's grants (roleGrants(role:, scopeId:)). viewer { can { grantRole(role:, scopeId:) } } says whether you may grant one. Rules can't read grants directly ($roleGrants is a system entity), only through the two built-ins.

Changing roles

Plan lists added, removed and changed roles and :grant rules under Permissions, and warns about a role only the tenant's admins can grant (often what you want for the role that runs the app). Removing a role that has grants is destructive and refused, as removing an enum value is: revoke the grants, or keep the role with :retired? true. Making a tenant-wide role scoped, or scoping it to another entity, is refused while it has grants that don't fit.

Roles: patterns

{:roles    {:org-admin {:doc "Administers the organisation"}
            :owner     {:scope :teams :grant [(has-role? ?user :org-admin)]}
            :editor    {:scope :teams
                        :grant [(or-join [?scope ?user] (has-role-on? ?user :owner ?scope) (has-role? ?user :org-admin))]}}
 :entities {:teams {:attrs       {:name {:type :string :min 1 :max 100}}
                    :permissions {:view   [(authenticated? ?user)]
                                  :create [(has-role? ?user :org-admin)]
                                  :update [(or-join [?e ?user] (has-role-on? ?user :owner ?e) (has-role? ?user :org-admin))]
                                  :delete [(has-role? ?user :org-admin)]}}
            :docs  {:attrs       {:title  {:type :string :min 1 :max 200}
                                  :team   {:type :ref :to :teams :required? true}
                                  :author {:type :ref :to :$users :required? true :default :auth/user}}
                    :permissions {:view   [[?e :docs/team ?t]
                                           (or-join [?t ?user] (has-role-on? ?user :editor ?t)
                                                    (has-role-on? ?user :owner ?t) (has-role? ?user :org-admin))]
                                  :create [(authenticated? ?user) [?e :docs/author ?user] [?e :docs/team ?t]
                                           (or-join [?t ?user] (has-role-on? ?user :editor ?t) (has-role-on? ?user :owner ?t))]
                                  :update [[?e :docs/team ?t]
                                           (or-join [?t ?user] (has-role-on? ?user :editor ?t) (has-role-on? ?user :owner ?t))]
                                  :delete [[?e :docs/team ?t] (has-role-on? ?user :owner ?t)]}}}}
  • Org admin: tenant-wide, granted by the tenant's admins only (no :grant). Creates teams and makes their owners.
  • Owner of a team: granted by an org admin; edits the team, grants and revokes its editors, deletes its docs.
  • Editor of a team: granted by the team's owner (or an org admin); reads and writes the team's docs, nothing on other teams.

Patterns

An :update rule without before is checked on the entity before the change and again after it, so a rule over the state is also a rule over every move between states: a move is allowed only when both ends pass. With before (see Field :update rules) a rule can tell the two ends apart. These were run against a live server, as the author, as another user and anonymously.

A state that freezes the entity

A closed question can't be edited or reopened, and its author may close it:

{:rules    [[(author? ?e ?u) [?e :questions/author ?u]]]
 :entities {:questions {:attrs       {:title  {:type :string :min 1 :max 200}
                                      :closed {:type :boolean :optional? true}
                                      :author {:type :ref :to :$users :required? true :default :auth/user}}
                        :permissions {:view   true
                                      :create [(authenticated? ?user) (author? ?e ?user)
                                               (not [?e :questions/closed true])]
                                      :update [(author? ?e ?user)
                                               (before (not [?e :questions/closed true]))]}}}}

(before (not [?e :questions/closed true])) reads the question as it was before the write: every change, closing included, needs it open then. Once closed, editing and reopening both fail. The create rule keeps questions from being created closed.

alice  updateQuestion(title: "How, exactly?")   ok (open)
alice  updateQuestion(closed: true)             ok
alice  updateQuestion(title: "x")               FORBIDDEN (closed before)
alice  updateQuestion(closed: false)            FORBIDDEN (closed before)
bob    updateQuestion(title: "mine now")        FORBIDDEN (not the author)
anon   updateQuestion(closed: false)            UNAUTHENTICATED

To keep the rest editable and freeze only the flag, put the rule on the attribute instead: :closed {:type :boolean :optional? true :update [(before (not [?e :questions/closed true]))]}.

Soft delete, with no undelete

A deleted flag that hides the row from everyone, for good:

{:rules    [[(author? ?e ?u) [?e :notes/author ?u]]]
 :entities {:notes {:attrs       {:text    {:type :string :min 1 :max 500}
                                  :deleted {:type :boolean :optional? true}
                                  :author  {:type :ref :to :$users :required? true :default :auth/user}}
                    :permissions {:view   [(not [?e :notes/deleted true])]
                                  :create [(authenticated? ?user) (author? ?e ?user)
                                           (not [?e :notes/deleted true])]
                                  :update [(author? ?e ?user)]}}}}

The view rule hides deleted rows from lists, by-id roots and nested fields. It is also what refuses every later change: an update first looks the entity up as the caller sees it before the change, and a deleted note is not found. The :update rule must not test deleted without before: it is checked after the change too, so it would refuse the soft delete itself.

bob    updateNote(deleted: true)    FORBIDDEN (not the author)
alice  updateNote(deleted: true)    ok
alice  updateNote(deleted: false)   NOT_FOUND
alice  updateNote(text: "x")        NOT_FOUND
alice  note(id:)                    null
anon   notes(first: 5)              the other notes only

The rows stay in the database. When you don't need them, delete for real: delete<T> (a :delete rule), or delete<Plural>(ids:) for many at once, all or nothing (see api.md).

Children of a parent that can be hidden again

Answers on questions that may go back to draft. Drafts can't be answered, and a question can't return to draft once it has answers:

{:rules    [[(q-author? ?q ?u) [?q :questions/author ?u]]
            [(a-author? ?a ?u) [?a :answers/author ?u]]]
 :entities {:questions {:attrs       {:title     {:type :string :min 1 :max 200}
                                      :published {:type :boolean}
                                      :author    {:type :ref :to :$users :required? true :default :auth/user
                                                  :reverse :questions}}
                        :permissions {:view   [(or-join [?e ?user] [?e :questions/published true] (q-author? ?e ?user))]
                                      :create [(authenticated? ?user) (q-author? ?e ?user)]
                                      :update [(q-author? ?e ?user)
                                               (or-join [?e] [?e :questions/published true] (not [_ :answers/question ?e]))]}}
            :answers   {:attrs       {:body     {:type :string :min 1 :max 2000}
                                      :question {:type :ref :to :questions :required? true :reverse :answers}
                                      :author   {:type :ref :to :$users :required? true :default :auth/user
                                                 :reverse :answers}}
                        :permissions {:view   [(or-join [?e ?user]
                                                 (and [?e :answers/question ?q] [?q :questions/published true])
                                                 (a-author? ?e ?user))]
                                      :create [(authenticated? ?user) (a-author? ?e ?user)
                                               [?e :answers/question ?q] [?q :questions/published true]]
                                      :update [(a-author? ?e ?user)]}}}}

The question's :update holds while it is published, or while nothing answers it. Publishing a draft passes (no answers before, published after); editing a published question passes; unpublishing one with answers fails on the state after the change. The answer's view has a "mine" branch, so if a question is hidden anyway (by a schema that allowed it, or data from before this rule), each answer's author still sees their own answer, while everyone else doesn't.

bob    createAnswer on a draft                  NOT_FOUND
alice  updateQuestion(title:) on her draft      ok
alice  updateQuestion(published: true)          ok
bob    createAnswer                             ok
alice  updateQuestion(published: false)         FORBIDDEN (answered)
alice  updateQuestion(title:)                   ok (still published)
alice  unpublish a question with no answers     ok

With a looser :update ([(q-author? ?e ?user)]) the unpublish goes through; then me { answers } still gives Bob his answer (its question is null), and Carol and anonymous callers get none.

People join a team, and team members see the team's records and each other's display names. The membership is the permission, so who may create one is the whole security of the app: a membership is created only by the person joining, either the team's owner or someone a member invited.

{:rules    [[(member? ?t ?u) [?m :memberships/team ?t] [?m :memberships/user ?u]]
            [(teammate? ?a ?b) [?m :memberships/user ?a] [?m :memberships/team ?t] (member? ?t ?b)]
            [(invited? ?t ?u) [?i :invites/team ?t] [?i :invites/invitee ?u]]]
 :entities {:$users      {:attrs       {:display-name {:type :string :optional? true :max 40
                                                       :view [(or (self? ?e ?user) (teammate? ?e ?user))]}
                                        ;; set by the user, so members can find them to invite them
                                        :findable     {:type :boolean :optional? true}}
                          :permissions {:view [(or-join [?e ?user]
                                                 (self? ?e ?user)
                                                 (teammate? ?e ?user)
                                                 (and (authenticated? ?user) [?e :$users/findable true]))]}}
            :teams       {:attrs       {:name  {:type :string :min 1 :max 100}
                                        :owner {:type :ref :to :$users :required? true :default :auth/user}}
                          :permissions {:view   [(or [?e :teams/owner ?user] (member? ?e ?user) (invited? ?e ?user))]
                                        :create [(authenticated? ?user) [?e :teams/owner ?user]]
                                        :update [[?e :teams/owner ?user]]}}
            :invites     {:attrs       {:team    {:type :ref :to :teams :required? true}
                                        :invitee {:type :ref :to :$users :required? true :reverse :invites}
                                        :inviter {:type :ref :to :$users :required? true :default :auth/user :reverse false}}
                          :permissions {:view   [(or-join [?e ?user]
                                                   [?e :invites/invitee ?user]
                                                   (and [?e :invites/team ?t] (member? ?t ?user)))]
                                        :create [(authenticated? ?user) [?e :invites/inviter ?user]
                                                 [?e :invites/team ?t] (member? ?t ?user)]
                                        :delete [(or [?e :invites/invitee ?user] [?e :invites/inviter ?user])]}}
            :memberships {:attrs       {:team {:type :ref :to :teams :required? true :reverse :members}
                                        :user {:type :ref :to :$users :required? true :default :auth/user}}
                          :permissions {:view   [(or-join [?e ?user]
                                                   [?e :memberships/user ?user]
                                                   (and [?e :memberships/team ?t] (member? ?t ?user)))]
                                        :create [(authenticated? ?user) [?e :memberships/user ?user]
                                                 [?e :memberships/team ?t]
                                                 (or [?t :teams/owner ?user] (invited? ?t ?user))]
                                        :delete [[?e :memberships/user ?user]]}}
            :deals       {:attrs       {:title {:type :string :min 1 :max 200}
                                        :team  {:type :ref :to :teams :required? true}}
                          :permissions {:view   [[?e :deals/team ?t] (member? ?t ?user)]
                                        :create [(authenticated? ?user) [?e :deals/team ?t] (member? ?t ?user)]
                                        :update [[?e :deals/team ?t] (member? ?t ?user)]}}}}
  • An invite is created by a member of the team, naming the invitee. The invitee (and the team's members) can see it, and the invitee can see the team it is for.
  • A membership names the caller (:user defaults to the caller and is pinned to them; [?e :memberships/user ?user] says so again), and the team's owner or an invite for the caller to that team must exist. Nobody can put someone else on a team.
  • Records (deals) are visible to members of their team; display names to the user and their teammates.
  • Users are closed by default, so a member can name someone in an invite only once they can see them: a teammate, or a user who made themself findable (updateUser, which only they can do). Their display name stays hidden until they join.

Why consent. The tempting version lets any member add any user id: :create [[?e :memberships/team ?t] (member? ?t ?user)]. Then every rule that trusts membership trusts the attacker: Mallory creates a team, adds Alice to it, and a rule like "teammates see each other's display names" shows her Alice's name, or anything else gated on sharing a team. A review of a CRM built on october harvested users' display names exactly so, by force-adding them to its own team. With an invite that the invitee accepts, a membership is a statement by the member, and rules may rely on it.

alice    createMembership(Sales)                     ok (the owner joins)
alice    createInvite(Sales, bob)                    NOT_FOUND (bob is a stranger: users are closed)
bob      updateUser(bob, findable: true)             ok (bob lets people find him)
alice    createMembership(Sales, userId: bob)        VALIDATION_FAILED (not the caller: userId is pinned)
bob      createMembership(Sales)                     NOT_FOUND (no invite: the team is hidden)
mallory  createInvite(Sales, mallory)                NOT_FOUND (not a member)
alice    user(bob) { displayName }                   null
alice    createInvite(Sales, bob)                    ok
bob      me { invites { team { name } } }            Sales
bob      createMembership(Sales)                     ok (accepts)
alice    user(bob) { displayName }                   "Bob"
bob      deals(first: 5)                             the team's deals
mallory  createMembership(Mine, userId: alice)       VALIDATION_FAILED (pinned: anyone but the caller)
mallory  createInvite(Mine, bob)                     ok, but it means nothing until Bob accepts
mallory  user(bob) { displayName }                   null
mallory  users(first: 50)                            mallory and bob (findable), nobody else
anon     teams(first: 5)                             none

An invitee can accept an invite more than once; that makes duplicate memberships, which change nothing. Delete the invite after accepting if you want it gone (deleteInvite is allowed to the invitee and the inviter). Leaving a team is deleteMembership, by the member.

Other entity keys: :order, :private? and :graphql/type

:order [<label> :asc|:desc] sets how the entity's lists are sorted when a query passes no orderBy: its list root and every has-many field that lists it. The label is :created-at or an attribute that can be an orderBy field (required and indexed; see Indexes). Without :order, lists are oldest first ([:created-at :asc]). A query's orderBy always wins.

:messages {:attrs {...} :order [:created-at :desc]}   ; newest first

Changing it changes no data. The plan lists it under api, and cursors from the old default order stop working (Invalid cursor). The default shows in the orderBy argument's description ("Default: CREATED_AT DESC").

:private? true removes the entity from the API completely: no GraphQL type, no roots, no mutations, and refs into or out of it are not exposed. Nothing a client can call can read or write it, so in an app schema it is rarely useful.

:graphql/type "Name" sets the GraphQL type name. By default the name is the etype made singular in a simple way (ies becomes y, a final s is removed unless the name ends in ss) and capitalised: :lists gives List, :categories gives Category. Use :graphql/type when that is wrong:

:news {:graphql/type "News" ...}

If the by-id root would have the same name as the list root, it gets a ById suffix: news(first: ...) and newsById(id: ...).

Changing a schema

You push a new version of the whole schema with the CLI (see cli.md). october plan shows what would change without applying it; october push plans, asks, and applies.

$ october plan lists
Plan a0c43ec4d852 -> fd68405b15af
Add:
  $users/display-name
  items/done
  ...
  lists.color/grey
  october.spec/lists
Alter:
  october.spec/items
Destructive:
  :items/name is in the database but no longer in the schema [push with --allow-destructive to retire it]

The plan lists database-level names (<etype>/<label>) in Add, Alter and Destructive. Entries like lists.color/grey are enum values; october.spec/<etype> is the entity's set of required attributes. Two more groups list changes that touch no attribute, under Permissions and API.

Add (always applied):

  • a new entity or attribute (an optional one, or a required one on an entity that has no data yet)
  • a new enum value

Alter (applied):

  • a changed constraint, sanitiser or :indexed? (the plan lists each index it adds or drops under Indexes, see Indexes)
  • an attribute made optional, or made required when every stored entity already has it
  • the required attributes of an entity changed

Permissions (applied): an entity's permission for an action, an attribute's :view rule, a ref turning pinned or not (:pinned?, see :default :auth/user), or a named rule under :rules, added, changed or removed:

$ october plan shop
Plan 472eb30c5dac -> 939cfb76311f
Permissions:
  items: create [(authenticated? ?user)] -> true
  items/name: view added: [(named? ?e)]
  named?: rule added

API (applied): an entity's :graphql/type or :private?, an attribute's :reverse or :default, or an attribute turning immutable or mutable:

API:
  answers/question: now mutable: updates may change it, so check the :update rule allows only what :create would

These are never destructive: no data changes. The new rules are in force from the tenant's next request after the push.

Destructive (refused):

  • a changed :type (for example :string to :long or :json, or to or from :enum)

  • a changed :many?

  • a ref's :to, :component? or :unique? turned on or off

  • an enum value removed

  • an attribute made required (a new one, or an existing optional one) on an entity whose stored data lacks it:

    :items/owner would be required, but 4 existing items lack it; add it with :optional? true, backfill it, then make it required
    
  • a removed attribute. This one is retirable: october push --allow-destructive retires it. october stops serving and checking it, and its stored data stays. Declaring it again later with the same type brings it back.

The other destructive changes need a migration, which the CLI can't do. On a new app, the simple way out is a new attribute name or a new tenant.

Warnings do not block a push. A tightened constraint that stored values fail is a warning with the count:

Warnings:
  :items/name: 1 stored value(s) fail the new constraint; their entities refuse writes until those values are fixed

After the push, every write to such an entity fails until the bad value is replaced.

Plan also warns about the schema itself:

  • an entity nobody can read (no :view), more sharply when it can be created or updated (see Defaults);
  • a field added to an existing entity without a :view of its own, since whoever can read the entity can read it: "new field Employee.salary is readable by anyone who can read Employee, including signed-out users" (when :view is true, never mentions ?user, or has a signed-out variant), or "readable by every signed-in user who can read Review" otherwise;
  • :indexed? that indexes nothing, or an indexed string with no :max (see Indexes).

Plan also checks the whole schema, and refuses it with every error it finds:

Refused (400 bad-schema): Attr :items/name has :min 5 greater than :max 2
Refused (400 bad-schema): Ref attr :items/owner points at unknown entity :users
Refused (400 bad-schema): Invalid schema at [:entities :items :attrs :name :type]: should be either :boolean, :double, :instant, :json, :long, :string or :uuid
Refused (400 bad-schema): Schema EDN doesn't read: EOF while reading
Refused (400 bad-schema): 2 errors in the schema:
  Attr :items/name has :min 5 greater than :max 2
  Ref attr :items/owner points at unknown entity :users

october check gives the same errors before you push, with no tenant (see cli.md).

A complete example: shared lists

Each user owns lists, can share a list with other users, and everyone on a list can add, tick off and remove its items. Only the owner sees the list's private note, renames it, changes its members or deletes it.

;; Shared lists: each user owns lists, can share a list with other users,
;; and everyone on a list can add, tick off and remove its items.
{:entities
 {:$users {:attrs       {:display-name {:type :string :optional? true :min 1 :max 40
                                        :trim? true :collapse-whitespace? true}
                         ;; set by the user: lets people find them to share a list
                         :findable     {:type :boolean :optional? true}}
           ;; users are closed by default; here you see yourself, the people you
           ;; share a list with, and those who chose to be findable
           :permissions {:view [(or-join [?e ?user]
                                         (self? ?e ?user)
                                         (shares-list? ?e ?user)
                                         (and (authenticated? ?user) [?e :$users/findable true]))]}}

  :lists  {:attrs       {:title       {:type :string :min 1 :max 100 :trim? true :indexed? true}
                         :owner       {:type :ref :to :$users :required? true
                                       :default :auth/user :reverse :owned-lists}
                         :members     {:type :ref :to :$users :many? true :reverse :shared-lists}
                         :color       {:type :enum :values [:grey :red :green :blue] :optional? true}
                         ;; only the owner sees the note
                         :owner-note  {:type :string :optional? true :max 500
                                       :view [(list-owner? ?e ?user)]}}
           :permissions {:view   [(on-list? ?e ?user)]
                         :create [(authenticated? ?user) (list-owner? ?e ?user)]
                         :update [(list-owner? ?e ?user)]
                         :delete [(list-owner? ?e ?user)]}}

  :items  {:attrs       {:text  {:type :string :min 1 :max 500 :trim? true}
                         :done  {:type :boolean :optional? true}
                         :rank  {:type :long :optional? true :indexed? true :min 0}
                         :due   {:type :instant :optional? true}
                         :meta  {:type :json :optional? true}
                         :list  {:type :ref :to :lists :required? true :reverse :items}}
           :permissions {:view   [(on-item-list? ?e ?user)]
                         :create [(on-item-list? ?e ?user)]
                         :update [(on-item-list? ?e ?user)]
                         :delete [(on-item-list? ?e ?user)]}}}

 :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)]
         [(shares-list? ?a ?b) (on-list? ?l ?a) (on-list? ?l ?b)]]}

Part of what it generates (from GET /t/<slug>/schema.graphql):

type List @auth(view: "(on-list? ?e ?user)", create: "(authenticated? ?user) (list-owner? ?e ?user)", update: "(list-owner? ?e ?user)", delete: "(list-owner? ?e ?user)") {
  id: UUID!
  color: ListColor
  createdAt: Instant!
  createdBy: User
  history(first: Int!, after: String, field: [ListHistoryField!]): RevisionConnection!
  items(first: Int!, after: String, orderBy: ItemOrder, listId: UUID, rank: Long): ItemConnection!
  members(first: Int!, after: String, orderBy: UserOrder): UserConnection!
  owner: User @immutable
  ownerNote: String @constraint(maxLength: 500) @visible(rule: "(list-owner? ?e ?user)")
  revisionCount(field: [ListHistoryField!]): Int!
  title: String! @constraint(minLength: 1, maxLength: 100)
}

type User @auth(view: "(or-join [?e ?user] (self? ?e ?user) (shares-list? ?e ?user) (and (authenticated? ?user) [?e :$users/findable true]))") {
  id: UUID!
  createdAt: Instant!
  createdBy: User
  displayName: String @constraint(minLength: 1, maxLength: 40)
  email: String @constraint(format: "email") @visible(rule: "(self? ?e ?user)")
  findable: Boolean
  history(first: Int!, after: String, field: [UserHistoryField!]): RevisionConnection!
  ownedLists(first: Int!, after: String, orderBy: ListOrder, color: ListColor, ownerId: UUID, title: String): ListConnection!
  revisionCount(field: [UserHistoryField!]): Int!
  sharedLists(first: Int!, after: String, orderBy: ListOrder, color: ListColor, ownerId: UUID, title: String): ListConnection!
}

type Query {
  item(id: UUID!, asOf: Long): Item
  items(first: Int!, after: String, orderBy: ItemOrder, listId: UUID, rank: Long): ItemConnection!
  list(id: UUID!, asOf: Long): List
  lists(first: Int!, after: String, orderBy: ListOrder, color: ListColor, ownerId: UUID, title: String): ListConnection!
  me: User
  user(id: UUID!, asOf: Long): User
  users(first: Int!, after: String, orderBy: UserOrder): UserConnection!
}

type Mutation {
  addListMembers(id: UUID!, memberIds: [UUID!]!): List @auth(update: "(list-owner? ?e ?user)")
  createItem(input: ItemCreateInput!): Item @auth(create: "(on-item-list? ?e ?user)")
  createList(input: ListCreateInput!): List @auth(create: "(authenticated? ?user) (list-owner? ?e ?user)")
  deleteItem(id: UUID!): DeletePayload @auth(delete: "(on-item-list? ?e ?user)")
  deleteList(id: UUID!): DeletePayload @auth(delete: "(list-owner? ?e ?user)")
  removeListMembers(id: UUID!, memberIds: [UUID!]!): List @auth(update: "(list-owner? ?e ?user)")
  updateItem(id: UUID!, input: ItemUpdateInput!): Item @auth(update: "(on-item-list? ?e ?user)")
  updateList(id: UUID!, input: ListUpdateInput!): List @auth(update: "(list-owner? ?e ?user)")
  updateUser(id: UUID!, input: UserUpdateInput!): User @auth(update: "(self? ?e ?user)")
}

Things to notice:

  • Item.list is nullable (List, not List!) although the ref is required, because the list has a :view rule; so is List.owner, because users have one too.
  • To add a member, the owner must see them: someone already on one of their lists, or a user who set findable on themself.
  • owner and Item.list are @immutable: they are required refs, so an item can't be moved to another list and a list can't be given away. ListUpdateInput has color, ownerNote and title only.
  • ItemOrderField is only CREATED_AT: rank is indexed but optional, so it is a filter (items(first: 10, rank: 2)) but not an order field. title is required and indexed, so ListOrderField has TITLE.
  • done is not indexed, so there is no done filter. Add :indexed? true to filter by it.
  • No :view on display-name, so anyone can list users and their display names.