Skip to main content

Row rules

Give every table one rule. Every row an operation reads or writes is checked against it, so a forgotten filter fails instead of leaking data.

A row rule says who may read and write the rows of one table. You give one rule per table in defineFunctions. Inside an operation, ctx.db checks every row the handler reads or writes against the rule of its table, however the handler reads it: get, withIndex, paginate, search, first, unique, or a loop.

convex/schema.ts
import { libraryTables } from '@lupinum/better-convex-functions'
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'

export const role = v.union(v.literal('owner'), v.literal('member'), v.literal('viewer'))

export default defineSchema({
  users: defineTable({ authId: v.string(), name: v.string() }).index('by_auth_id', ['authId']),
  organizations: defineTable({ name: v.string() }),
  memberships: defineTable({
    organizationId: v.id('organizations'),
    userId: v.id('users'),
    role,
  })
    .index('by_org_user', ['organizationId', 'userId'])
    .index('by_org', ['organizationId']),
  // A client of an agency: a tenant inside the organization.
  clients: defineTable({ organizationId: v.id('organizations'), name: v.string() }).index(
    'by_org',
    ['organizationId'],
  ),
  projects: defineTable({
    organizationId: v.id('organizations'),
    name: v.string(),
    status: v.union(v.literal('active'), v.literal('archived')),
    summary: v.optional(v.string()),
    archivedAt: v.optional(v.number()),
  })
    .index('by_org_status', ['organizationId', 'status'])
    .index('by_status_archived', ['status', 'archivedAt']),
  // Public once published; drafts belong to the organization.
  pages: defineTable({
    organizationId: v.id('organizations'),
    slug: v.string(),
    title: v.string(),
    body: v.string(),
    status: v.union(v.literal('draft'), v.literal('published')),
  }).index('by_org_status_slug', ['organizationId', 'status', 'slug']),
  // Private to its author, or shared with an organization.
  notes: defineTable({
    authorId: v.id('users'),
    organizationId: v.optional(v.id('organizations')),
    text: v.string(),
  })
    .index('by_author', ['authorId'])
    .index('by_org', ['organizationId']),
  ...libraryTables,
})
convex/functions.ts
import {
  anyOf,
  custom,
  defineFunctions,
  owner,
  publicRead,
  tenant,
} from '@lupinum/better-convex-functions'

import { internal } from './_generated/api'
import type { Doc, Id } from './_generated/dataModel'
import { auth } from './auth'
import { policy } from './policy'

export const fns = defineFunctions({
  auth,
  policy,
  user: (ctx, authId) =>
    ctx.db
      .query('users')
      .withIndex('by_auth_id', (q) => q.eq('authId', authId))
      .unique(),
  roleOf: async (ctx, user, tenant) => {
    // A call that names no organization gets no role. What every signed-in person may do is a
    // role too (see Policy and roles: signedIn).
    if (tenant === null) return null
    let organizationId: Id<'organizations'> | undefined
    if (tenant.table === 'organizations') organizationId = tenant.id
    // A client inherits the roles of its organization.
    if (tenant.table === 'clients') organizationId = (await ctx.db.get(tenant.id))?.organizationId
    if (!organizationId) return null
    const membership = await ctx.db
      .query('memberships')
      .withIndex('by_org_user', (q) =>
        q.eq('organizationId', organizationId).eq('userId', user._id),
      )
      .unique()
    return membership?.role ?? null
  },
  rules: {
    users: owner('_id'),
    organizations: tenant('_id'),
    // Every membership of an organization where your role allows the action, inside the
    // organization the call names (as tenant() does). Not owner('userId'): that would let a
    // member change their own role or add themselves to another organization.
    memberships: custom<Doc<'memberships'>>(
      (ctx, membership) =>
        (ctx.tenant === undefined || ctx.tenant.id === membership.organizationId) &&
        ctx.allows({ table: 'organizations', id: membership.organizationId }),
    ),
    clients: tenant('_id', { parent: 'organizationId', createdBy: 'clients.create' }),
    projects: tenant('organizationId'),
    pages: anyOf(
      publicRead((page: Doc<'pages'>) => page.status === 'published'),
      tenant('organizationId'),
    ),
    notes: anyOf(owner('authorId'), tenant('organizationId')),
  },
})

export const {
  query,
  mutation,
  internalQuery,
  internalMutation,
  internalAction,
  job,
  authorizeAction,
} = fns
// Public actions run `authorizeAction` before their handler: see Internal operations.
export const action = fns.action(internal.functions.authorizeAction)

The rules

RuleA row passes when
tenant('organizationId')the caller's role in the organization in this field allows the call's action
tenant('_id', { createdBy })the same, for the tenant table itself. Only the createdBy action may insert one (none without it)
tenant('_id', { parent, createdBy })a tenant inside a tenant: a call in the parent also reaches it; only createdBy may insert one
owner('authorId')the field holds the caller's user ID ('_id' on the users table)
publicRead(where)anyone reads it, signed-out visitors too, when where returns exactly true (not a Promise). It never allows a write
anyOf(rule, …)one of the rules passes
allOf(rule, …)every rule passes
custom(check)check(ctx, row) returns exactly true; any other value hides the row. ctx.db only reads
unchecked(reason)always. Write why, so a reviewer can find and judge every one

The field of tenant(field) must hold the ID of a tenant: a row of a table whose rule is tenant('_id'). A field that holds no ID is a type error. A field that holds an ID of another table, such as tasks: tenant('projectId') when projects is not a tenant, fails at the first row with a message that names the field. Make that table a tenant with tenant('_id', { parent }), or name the field that holds the tenant.

A write that moves a tenant under another parent (a client to another organization) is checked like a new tenant there: the new parent must be in the call, and the caller's role in it must allow the action. Otherwise the write fails with NOT_FOUND, or FORBIDDEN when the role does not allow it.

The rule is the same for every operation. The action decides the rest: a viewer of an organization reads its projects with projects.list, but projects.archive fails, because the viewer role does not allow that action.

Conditions on the row's state

Put a condition such as "only drafts change" in the rule, not in the handlers. A check in a handler protects only that handler: the next operation that writes the table can forget it. allOf adds the condition to the tenant rule. In the rules of defineFunctions:

ts
pages: anyOf(
  publicRead((page: Doc<'pages'>) => page.status === 'published'),
  allOf(
    tenant('organizationId'),
    // A published page changes only through pages.editLive.
    custom<Doc<'pages'>>(
      (ctx, page) =>
        ctx.mode === 'read' || page.status === 'draft' || ctx.action === 'pages.editLive',
    ),
  ),
),

A write is checked on the row before and after the change, so this rule also stops an operation other than pages.editLive from publishing a draft. When one part hides the row, the row does not exist for the caller; when one part refuses the write, the write fails with FORBIDDEN.

What a refused row does

The handlerResult
reads one row with getnull, as for a row that does not exist
runs a query that returns such a rowthe call fails: the query is missing a filter
writes a row the caller cannot seeNOT_FOUND
writes a row the caller may only readFORBIDDEN

Rules check rows. They do not filter them. A query that would skip rows makes pages short and counts wrong without a sign, so it fails instead.

Narrow every query by an index on the field its rule checks: the tenant field, the owner field, or the publicRead condition. For pages, query by_org_status_slug with the organization and status: 'published'. A query over the whole table fails as soon as it meets a row of another tenant.

How a call finds its tenant

The call's tenant is where its role comes from. The library finds it in the arguments before the handler runs:

  • An ID of a table with a tenant rule names a tenant: projectId names the project's organization, organizationId names the organization. A tenant rule inside allOf counts too, as every row must pass it.
  • An ID of an anyOf table does not, because its rows may be private, public or shared. An operation on pages or notes names its tenant in its own arguments (organizationId).
  • All IDs of one call must come from one place: one tenant and the tenants above it. IDs from two organizations fail with FORBIDDEN. An operation that moves rows between tenants sets crossTenant: true; the caller's role must then allow the action in every tenant the call names.
  • An ID of a tenant where the caller has no role fails with NOT_FOUND, not FORBIDDEN, so a caller cannot learn that a foreign ID exists.

A call with no tenant ID needs the role outside any tenant (roleOf(ctx, user, null)) to allow its action, unless the action is public. Its rows are then checked each in its own tenant.

Custom rules

custom receives the call and the row. ctx.actor is the caller, ctx.action the call's action, ctx.mode is 'read' or 'write', and ctx.db reads without rules, for lookups. Type the row: custom<Doc<'memberships'>>(…). Without the type, the row is unknown. The row is a frozen copy: a rule that changes it throws, and the call fails.

Call ctx.allows(tenant) to apply the role layer. A custom rule that checks membership alone lets a viewer write.

A custom rule is not limited to the call's tenant, the way tenant(field) is. ctx.tenant is the tenant the call names, or undefined for a call that names none. The memberships rule above checks it, so an operation in one organization cannot change a membership of another organization where the caller has the same role.

What ctx.db refuses

  • System tables (ctx.db.system): scheduled-function arguments and file metadata belong to every user at once.
  • Query methods the library does not know. A method that Convex adds later fails until the library checks it too.

A system job (job) gets the database without rules. See Internal operations.

Files are not rows

ctx.storage is Convex's own, without rules: a storage ID gives whoever holds it the file. Read the storage ID from a row the call may read ((await ctx.db.get(documentId))?.fileId), never from the input, before you call ctx.storage.getUrl or ctx.storage.delete. See What is not protected.