Database.Security

Database

Policies that decide which rows a token may touch.

Every [Database.Table] carries a `Policy`. Pass the token into `access` / `insert` / `update` / `remove` (often `Server.cookies req` or a user id). The compiler only accepts equality checks it can enforce as SQL; anything else fails compilation (fail-closed).

Security.policy
    { access = \user todo -> todo.owner == user
    , insert = \user todo -> todo.owner == user
    , update =
        \user before after ->
            before.owner == user && after.owner == user
    , remove = \user todo -> todo.owner == user
    }

For tables anyone may read or write in-process, use unrestricted and pass Security.Unrestricted as the token. On Postgres, secured tables also get FORCE ROW LEVEL SECURITY policies bound to selm.token per query. See examples/03_todo_app (Todos.selm, Users.selm).

Types

Unrestricted

type Unrestricted = Unrestricted

Token type for tables with no row-level restrictions.

Examples

access logs Security.Unrestricted
    |> map (\row -> { id = row.id })
    |> selectAll

Policy

type Policy token row = Policy

Row-level security predicates parameterized by token and row.

Examples

security =
    Security.policy
        { access = \user todo -> todo.owner == user
        , insert = \user todo -> todo.owner == user
        , update = \user before after -> before.owner == user && after.owner == user
        , remove = \user todo -> todo.owner == user
        }

Values

unrestricted

unrestricted : Policy Unrestricted row

Allow every operation without a user token. Pass Unrestricted to access / insert / and the other table ops.

Examples

table
    { primary = .id
    , security = Security.unrestricted
    , indexes = []
    , constraints = []
    }

policy

policy : { access : token -> row -> Bool , insert : token -> row -> Bool , update : token -> row -> row -> Bool , remove : token -> row -> Bool } -> Policy token row

Define row-level security predicates.

Codegen only accepts conjunctions of equalities it can enforce:

- access / insert / remove: row.field == token (or field of token) - update: before.field == token, after.field == token (required so ownership cannot be reassigned), and optional before.field == after.field

Any other clause fails compilation. A policy must yield an owner column; unrecognized policies never become unrestricted.

Examples

Security.policy
    { access = \user todo -> todo.owner == user
    , insert = \user todo -> todo.owner == user
    , update =
        \user before after ->
            before.owner == user && after.owner == user
    , remove = \user todo -> todo.owner == user
    }