Guard / foldkit-guard

Serving writes

A declared write (Mutation.write) runs through RemoteServer.write (see the declared writes guide). Wrap its writer with GuardServer.writer to enforce write rules before any row changes:

ts
import { Write } from 'foldkit-entity'
import { Mutation } from 'foldkit-remote'
import { writer } from 'foldkit-remote-drizzle'

const EditTodo = Mutation.write(
  'EditTodo',
  Write.update(Entity.input(Todo, Schema.Struct({ id: Schema.String, title: Schema.String })), {
    id: 'id',
  }),
)
RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))

How writes and cascades are checked

  • Reads before writing: updates and deletes load the row under the writer's visibility. Hidden rows fail updates as Forbidden and answer deletes as already deleted.
  • Row rules: Create checks proposed values (fields left unset fail any guard reading them). Update checks the row both before and after the write so writers can move rows only within their own visibility. Delete checks the existing row.
  • Member and link rules: each set or incremented member requires its Create or Update rule, and changed relations require Unlink on the old target and Link on the new one. Updates evaluate each member/link rule against the new row with that one change reverted, preventing multi-field bypasses while letting transition rules like "update status only while draft" pass.
  • Refusals and readback: signed-in failures return Forbidden (with Guards.explain text); visitors (Option.none()) return Unauthenticated so clients prompt for sign-in and outbox writes retry cleanly. Accepted writes return only fields and relations the writer may read, reporting rows that left the writer's visibility in deleted.
  • Cascades and link clearing: for onDelete: 'cascade' and onDelete: 'setNull' relations, pass { children: [Like] } to GuardServer.writer. Cascades check every child's Delete rule (unless authorizedBy: 'parent') and setNull checks each child's Update and Unlink rules in the same statement/batch, refusing the whole delete on any failure without leaking child IDs.

A revision closes the gap between the check and the write

Because loading a row and writing it are separate statements, another write can land in between. Add a numeric revision field and pass { revision: 'revision' } to GuardServer.writer so every update and delete pins the revision it checked:

ts
GuardServer.writer(Todo, Policy, writer(Db.Todo), { revision: 'revision' })

If another write moves the row first, the guard reloads and re-evaluates up to three times before failing with an Internal error (ServerDefect logged as "changed while it was written"). Client inputs with stale expect revisions fail immediately with Conflict. GuardServer.validate emits an UnpinnedWrites diagnostic for updates or deletes on Entities without a revision pin.

Preconditions, increments and invariants

  • Preconditions (when): the writer checks when after guards pass, in the order: hidden row (Forbidden), stale expected revision (Conflict), failed guard (Forbidden), unmet precondition (Unmet). GuardServer.validate and the writer reject preconditions or expect over fields with Read rules to prevent oracle leaks.
  • Increments and computed assignments: increments require the member's Update rule and check row rules over the resulting sum; computed assignments run through Write.apply with your operators table (emitting ComputeRefused on operator errors) and reject reads from Read-guarded members. Both require either expect or a writer revision pin.
  • Invariants (Entity.invariant): invariants run after guards pass and fail with Invalid. Invariants reading a Read-guarded member still run, reporting a generic "The row would be invalid" message without naming hidden values.

Retries

When a writer uses a ledger (writer(binding, { ledger })), retries of an already-applied operation replay from the ledger immediately, while failed or first-time requests evaluate against the current principal and row.

The writer's binding

Give GuardServer.writer the same binding (Db.Todo) used by the Entity's Source so its visible filter matches GuardDrizzle.visible.

Fields the server sets

Use Entity.sets (Expr.viewer, Expr.now) in foldkit-entity for fields such as ownerId so RemoteServer.write populates them before guards run. Inputs attempting to set those fields fail declaration checks, and visitors fail with Unauthenticated. Duplicate creates return Refusal.taken uniformly, while ledger retries replay the original row to the same creator.

Handlers

Custom mutation handlers (RemoteServer.mutation) use GuardServer.mutation to check one interaction rule before executing:

ts
const ArchiveTodo = Mutation.make('ArchiveTodo', { Input: { id: Schema.String }, Output: {} })

GuardServer.mutation(
  ArchiveTodo,
  { entity: Todo, policy: Policy, interaction: Archive.key, id: input => input.id, source: TodoSource },
  ({ input, row }) => Effect.succeed({ output: {} }), // `row`: the todo, as its writer sees it
)
  • id loads the target row through source (rejecting hidden rows); omitting id checks principal/create rules, and returning an Option handles both create (Option.none()) and edit (Option.some(id)).
  • Pass fields to select extra columns for your handler; returned Entity rows pass back through source's authorize and filter, marking newly hidden rows as deleted.

Rules that read another row

Read, Update, and Delete row guards can traverse relations (Expr.path, Expr.exists, or viewer paths). Read rules compile into SQL subqueries, while Update and Delete rules pass remaining cross-row conditions to remote-drizzle's writer via requires (update … where … and <rule>) so they evaluate atomically at write time on SQLite and Postgres (Postgres apps call postgres() from foldkit-remote-drizzle/pg at startup).

  • Cross-row Update/Delete rules read the stored row, blocking writes that would move a row out of reach (such as moving a note to another team).
  • may leaves cross-row interactions undecided (May.answer returns an Unknown Verdict). Keep forms editable and hide controls with May.refused rather than !May.can, letting the server render the final decision.
  • GuardServer.writer throws if given a writer without requires support; single-row seams (GuardServer.mutation, GuardSync.document, GuardServer.memory) reject cross-row rules on those surfaces by name.