Access Control
Each entity type says who may read and write its entities, with allow lines in its module. The same rules decide what the server returns and accepts, which entities reach each user's browser, and what can? answers in a template.
The conditions in the rules are written in the query language from Queries, the one filter uses, so there's no second language to learn. A condition you've written as a filter works in a rule as it is.
The examples use the entity types from Queries, where a project has an owner and tasks, and a task has a project and an optional assignee.
Deny by Default
Nobody may do anything that no line allows. No user can read or write an entity type with no allow lines, so reading it for a user returns nothing, and writing it raises a Hologram.AccessDeniedError. A live read of such a type could never show anything, so it fails the build, or raises a Hologram.MisuseError when the page renders if the build can't see the whole query.
The rules apply to code that runs for a user: actions and live reads in the browser, and init/3, middleware, commands and jobs on the server, as Reading Data and Writing Data describe. Seeds, Mix tasks, the console and your own plugs have no user, so they read and write past the rules.
allow Lines
An allow line names an operation, :create, :read, :update or :delete, followed by options that say who may do it and when:
defmodule MyApp.Project do
use Hologram.Entity
# ...the fields from Queries
role :member
allow :create, when: owner_id == user_id()
allow :read, when: owner_id == user_id()
allow :read, to: :member
allow :update, when: owner_id == user_id()
allow :update, to: :member, when: archived == false
allow :delete, when: owner_id == user_id() and none(tasks)
end
With these rules, a user may create a project only with themselves as its owner, and read the projects they own or are a member of. They may change the ones they own, and the ones they're a member of while they aren't archived. They may delete one they own once it has no tasks.
The options on one line must all hold at once, so the member's update line needs both the role and an unarchived project. When an operation has several lines, one that holds is enough. The owner's update line says nothing about archiving, so the owner may change a project even once it's archived. The order of the lines doesn't matter. A line with no options allows the operation to everyone, visitors included, so allow :read makes every entity of the type public.
Each operation checks a different version of the entity:
:readchecks each stored entity, and a user gets only the ones a line allows.:createchecks the new entity, with the values it's created with.:updatechecks the entity as stored, before the change. Rules About Changes below shows how to check the values after it.:deletechecks the entity as stored. Users can't be deleted yet, so a:deleteline on the user entity type fails the build, as The User Entity in Entities says.
Three more operations, :grant_role, :revoke_role and :read_roles, say who may hand out roles, which Roles covers. Job types have one more, :cancel, which checks the job as stored and says who may cancel it, as Jobs shows. On any other entity type, allow :cancel fails the build, and so does any other atom. A word of your app's own, like :archive, is a name on a line, which Named Lines below covers.
Who: to:
A role is a name your code grants a user, either app-wide or on one entity, like a member of a project. Roles covers declaring and granting them, and this section covers the rules that ask for one. to: says which role the user must hold, so a task's line names the relationship that leads to the role's entity:
allow :read, to: {:member, project}
allow :update, to: [{:member, project}, MyApp.Admin]
The members of a task's project may read the task, and they or an admin may change it. to: takes these forms:
- A role on the entity itself, like
:memberon a project, declared withrole :memberin its entity type. - A role on the entity a to-one leads to, as
{role, relationship}, like{:member, project}. A path of to-ones works too, like{:member, task.project}on a comment. - A role held on every entity of a type, as
{role, entity type}, like{:member, MyApp.Project}. - A global role, held app-wide, which is a module of its own.
- A list of any of them, where holding one is enough.
A global role is a module that uses Hologram.Role:
defmodule MyApp.Admin do
use Hologram.Role
end
A line without to: asks for no role. A visitor holds no role, so a line with to: never allows a visitor anything. Owning a project doesn't make its owner a member either, since a role is held only once it's granted. Your code can grant the role to the user who creates the entity, as Roles shows.
Conditions: when:
when: is a filter condition, in the same query language as Queries, with the same operators, paths and quantifiers. Rules add a few words a filter doesn't have, like new(), which Rules About Changes covers. A field is a bare name, and user_id() is the ID of the user acting. A value from the module, like a module attribute, is pinned with ^, as in ^@max_priority, and it's fixed when the module compiles:
allow :read, when: assignee_id == user_id() or project.owner_id == user_id()
allow :update, when: assignee_id == user_id() and project.archived == false
allow :delete, when: project.owner_id == user_id() and status != :done
A user may read a task assigned to them or one in a project they own. The assignee may change the task while its project isn't archived, and the project's owner may delete it until it's done.
user_id() is the ID of the signed-in user's entity, an entity of the type your app marks with user: true, as The User Entity in Entities shows. An app without that type has no user IDs, so a condition that names user_id() fails its build. A visitor has no user ID, so for a visitor every comparison with user_id() is false, != included, and owner_id != user_id() doesn't hold for a visitor either. That way a rule that names the user never matches a visitor by accident. It would if the ID were nil, since assignee_id == user_id() would then match every unassigned task. So in assignee_id == user_id() or project.archived == false, a visitor gets nothing from the first part, but the second can still hold for them.
A path through to-ones reads the related entities as stored, even ones the user may not read. A path that leads nowhere, like the assignee of a task that has none, reads as nil, so assignee.name != "Ann" holds for a task with no assignee. To require the related entity, check it first, as in assignee.id != nil and assignee.name != "Ann".
A to-many is read through any, none and all, as in a filter. none(tasks) in the first example holds while the project has no tasks. A derived field compares like an attribute, and one that reads a to-many can stand only inside a quantifier's condition.
Delegation: via:
via: hands the decision to the entity a to-one leads to. A task that anyone who may read its project may read, and so on for each operation, says so like this:
allow :read, via: project
allow :update, via: project
allow :delete, via: project
allow :create, via: {:update, project}
A bare relationship asks the related entity for the same operation, so allow :update, via: project lets the user change a task when they may change its project. {operation, relationship} asks for another operation. A new task's project already exists, but the project's own create rule says only who may create projects, so the create line asks whether the user may change the project instead. A path of to-ones works too, like via: task.project on a comment.
A delegation can lead through several entity types, but it can't lead back to the type it starts from, and a cycle fails the build. It needs a to-one, since a to-many has no single entity to ask.
Field Rules
An update line can cover only some fields. only: lists the fields it covers, and except: covers every field but the listed ones, fields you add later included:
allow :update, via: project
allow :update, only: [status, assignee], to: {:member, project}
Anyone who may change the project may change any field of its tasks, and the project's members may change a task's status and assignee. An update goes through when every field it changes is covered by some line that holds, so a member's update that also changes the title is refused. The refusal names the fields no line covered.
A field is an attribute or a relationship, and a to-one goes by its relationship name, assignee, not assignee_id. Fields are bare names, as in when: and the relationship in to:, so an atom written on an allow line is never a field. It's a role, an operation, a name or a value. A field list that comes from code, like one a macro or a for loop builds, is pinned, and it holds the fields as atoms.
only: and except: go on update lines only, and one line can't take both. A line that covers a relationship lets its holders point the entity at any entity of the related type, which Moving Entities Between Parents below covers.
Named Lines
as: gives a line a name of your app's own, so you can ask about it alone:
allow :update, as: :archive, only: [archived], when: owner_id == user_id()
can?(user, :archive, project) then asks whether this line holds, and another entity type can delegate to it with via: {:archive, project}. The name labels the line without limiting it, so it still allows every update its options allow. Several lines of one operation can share a name, and the name holds when any of them does. A name can't be one of the seven operations, like :update or :grant_role, or :cancel on a job type, since can? and via: ask for an operation by the same atom. One name also can't label lines of two operations.
Rules About Changes
An update line checks the entity as stored, so status == :doing is the status before the change. new() reads the entity as the change would leave it:
allow :update,
as: :finish,
only: [status],
to: {:member, project},
when: status == :doing and new(status) == :done
A member may change a task's status only from :doing to :done. A one-way change, like archiving a project for good, is only: [archived], when: new(archived) == true.
new() takes a field, a path through to-ones, like new(project.archived), which reads the project the task would point at, or a to-many as a quantifier's source. It works only in the when: of an update line, and anywhere else it fails the build.
When a change gives a field a value its attribute doesn't accept, new() reads the stored value instead. If a member sets a task's status to :finished, which isn't one of its values, new(status) in the example above reads :doing. The line doesn't hold, so the update raises a Hologram.AccessDeniedError, and its message says the value given for status is invalid. An entity holding an invalid value can never be saved, so the rule judges the value that will still be there.
Moving Entities Between Parents
An update rule checks the parent an entity points at before the change, not the one it would point at after it. A line that covers the relationship lets the user move the entity anywhere:
# A member can move the task into any project, even one they aren't a member of
allow :update, to: {:member, project}
# A member can move the task only into another project they're a member of
allow :update, except: [project], to: {:member, project}
allow :update,
as: :move,
only: [project],
to: {:member, project},
when: has_role(:member, new(project))
The first line lets a member of one project move its task into a project they've never joined. The two lines after it let a member change everything but the project, and move the task only when they're a member of the project it moves to as well. to: checks the stored project, and has_role(:member, new(project)) checks the new one. A role held on every project, as {:member, MyApp.Project}, doesn't count there.
To ask the rules of the new parent instead of a role, use can:
allow :update, only: [project], via: project, when: can(:update, new(project))
A user may move a task from a project they may change into another one they may change. has_role and can stand in the when: of an update line, on their own or in an or, and take new() of a to-one. They check the new parent as stored, and a rule they reach can't use new() itself, or the build fails.
Reusable Policies
Rules that several entity types share go in a policy, a module that uses Hologram.Policy and holds allow and role lines written as in an entity type:
defmodule MyApp.Policies.AdminManaged do
use Hologram.Policy
allow :read, to: MyApp.Admin
allow :update, to: MyApp.Admin
allow :delete, to: MyApp.Admin
end
An entity type takes it with policy and keeps its own lines beside it:
defmodule MyApp.Project do
use Hologram.Entity
# ...the fields from Queries
policy MyApp.Policies.AdminManaged
role :member
allow :read, to: :member
end
The policy's lines join the entity type's own as more alternatives, so an admin and a member can both read a project. A policy line can go anywhere in the module, since the order of the lines doesn't matter. A policy can take other policies with a policy line of its own, and an entity type that takes it gets all of their lines.
A policy's lines work as if they were written in each entity type that takes it. A role it declares is a role of each of those types, held separately on each, and a field its conditions name must be a field of each of them, or the build fails. A role declared both in a policy and in the entity type is one role, and Roles covers how the two declarations combine. Aliases, module attributes and functions in a policy mean what they mean in the policy's module.
Checking Permissions
can? asks whether a user may do an operation on an entity, for example to show a button only to the users who may press it. Pages and components import it, so a template can call it:
def template do
~HOLO"""
{%if can?(@current_user, :archive, @project)}
<button $click={:archive, project_id: @project.id}>Archive</button>
{/if}
"""
end
It takes the user entity, a user ID, or nil for a visitor, then an operation or a line's name, and the entity. @current_user here is the session user from Reading Data. It returns true or false, and an operation the entity type has no line for is false. A name no line carries raises a Hologram.MisuseError.
For updates, the bare :update counts only the lines that cover every field. {:update, :status} asks whether the user may change one field, and {:update, [:status, :assignee]} whether they may change all of them in one update. can? is an ordinary function, so it names fields with atoms, as put_attribute does.
A rule with new() depends on the change, and without values can? doesn't know it. So it answers whether some change would pass. can?(user, :finish, task) is true for a member while the task is :doing, since setting it to :done would pass. To ask about one change, pass its values as DB.update takes them. A picker that moves a task to another project can ask about each project it lists:
can?(current_user, :move, task, project_id: project.id)
can? only answers. The write is still checked, so a control that can? shows by mistake leads to a refusal, never to a write the rules don't allow.
can? works on the server too, in init/3 and commands, where you pass it server.user_id. Reads and writes there are checked already, so ask it about what the rules don't cover themselves, like whether to send an email or call another service for the user.
Browser and Server Checks
The server checks every read and every write, whatever the browser did. The browser uses the same rules to hold only the entities the user may read, to answer can? at once, and to refuse a write in an action that can't pass.
A rule can read other entities, through a path, a delegation, a role on a related entity or a quantifier. The browser holds the ones the user may read and answers from them, and a change to one of them changes the answer. A rule that reads through an entity the user may not read, or through an entity of a lazy type, gets its answer from the server, which sends it with each entity it sends. Some quantifiers, like none and all, need entities the browser may not hold, so the server answers those too, and keeps the answer current.
Where it can't tell, the browser's can? answers false while the server may say yes:
- for an entity built with
new, so for any create, and for one an action changed but hasn't written yet - for an entity the browser created that the server hasn't confirmed yet
- for a user other than the signed-in one, or for a visitor when someone is signed in
- while a write the server hasn't answered yet changes an entity type the rule reads
- for an entity the browser holds from before the rules changed, until sync sends it again, when the answer has to come from the server
A rule for any operation but :read that reads through an entity type with no allow :read line fails the build, since no browser would ever hold those entities and it would answer no where the server says yes.
An action's write is refused at once, with a Hologram.AccessDeniedError, only when its values can't pass whatever the server holds, like a member setting status: :todo when the :finish rule above is the only line covering the status. Everything else, like roles, delegations and related entities, the browser leaves to the server, since its copy can be out of date. It applies the write, and if the server refuses it, the browser undoes the batch, as Writing Data describes.
When a deploy changes only the rules, open tabs get the new ones from the server without reloading. Until they arrive, a tab checks by the rules it had, while the server always checks by the current ones.
Rules and Server-Only Data
A read rule can check a server-only attribute, which Entities describes:
attribute :flagged, :boolean, default: false, server_only: true
allow :read, when: flagged == false
allow :read, when: project.owner_id == user_id()
Users see the tasks that aren't flagged, and a project's owner sees all of its tasks. The browser never holds the flag, so the server decides each task's read rule and the browser takes its answer. A rule for any other operation that checks a server-only attribute, directly or through a path or a derived field, fails the build, since the browser would have to check a value it doesn't have. On the server, can? checks the stored server-only values, in a template too, so its answer can tell something about them. So can the entities a read rule lets through.
Reading and Writing Past the Rules
Server code can claim the server's own authority with trust(), on a query to read past the rules, or on an entity to write past them, as Reading Data and Writing Data show. Use it when the work has no user behind it, like recording what a payment provider reported, or when the server needs data no user may read to make a decision, like looking up an invite by its code. Keep the result on the server, since a trusted read can return entities the user may not see.
Don't use trust() to let a user do something the rules refuse. Add a line that allows it, so the browser and can? agree with the server. Browser code can't claim trust, and a query or a write there that tries raises a Hologram.MisuseError.