Quickback Docs
Errors

Errors by Security Layer

The status code, error code and body each security layer returns — authentication, firewall, access, guards, validation, masking, database, legacy forwards, claimed tables, tenancy.

The status code, stable error code and body each layer of the generated API returns when it refuses a request. The response format and where the full reason goes are on Errors.

Errors by Security Layer

Authentication (401)

Missing or invalid authentication tokens.

{
  "detail": "Authentication required",
  "layer": "authentication",
  "code": "AUTH_MISSING",
  "hint": "Include Authorization header with Bearer token"
}

Error codes:

CodeDescription
AUTH_MISSINGNo Authorization header provided
AUTH_INVALID_TOKENToken is malformed or invalid — including a Quickback-minted JWT that no longer verifies (rotated key, tampered, revoked). Presented-and-bad is always 401, never treated as no credential. An API key whose owner is banned answers with details.reason: "owner_banned"; one whose stored scopes are malformed, "malformed_scopes"
AUTH_EXPIREDToken has expired
AUTH_RATE_LIMITEDToo many auth attempts, or an API key over its per-key limit (429)
AUTH_REVOCATION_UNAVAILABLE503, retryable. Only with revocationCheck: 'kv': the bearer's signature verified, but its revocation state could not be read (KV binding missing or unreachable), so it was not trusted. Retry, or authenticate with a session cookie

Firewall (403)

Records outside the user's firewall scope return 403 Forbidden by default — firewallErrorMode defaults to 'reveal':

{
  "detail": "Not found, or not visible to you",
  "layer": "firewall",
  "code": "FIREWALL_NOT_FOUND",
  "hint": "If you expected this record, check your active organization. The server log line for this requestId (x-request-id) records the exact reason."
}

Firewall filtering is transparent — the query is scoped by WHERE organizationId = ? so inaccessible records simply don't appear in results.

The body is identical whether the id does not exist or exists outside your scope — GET/PATCH/PUT/DELETE /:id, record actions, batch items, and views by root id all answer it the same way, so an id cannot be probed for existence. The message is true in both cases. The reason is not lost: on the miss path the route runs one unscoped primary-key probe and writes its diagnosis to the request.refused log line — whether the row exists, and which scope column excluded it (or that it is soft-deleted, or that the caller holds no such claim). Dev bodies carry the same details.diagnosis. Batch items get the same per item: one log line for each item the batch processes, keyed by batch.index, capped per request with one summary line for the rest (Batch Operations). On Postgres (caller-scoped RLS) and tenant Durable Object tables the probe is skipped (exists: "unknown"): an unscoped lookup there would not see other tenants' rows.

Record in another of your organizations (409)

One case is answered truthfully instead: the record exists, the only thing excluding it is its organization column, and the caller is a member of that organization. Then the answer is 409 RECORD_IN_OTHER_ORGANIZATION, naming the organization and the fix:

{
  "detail": "This record belongs to another organization you are a member of",
  "layer": "firewall",
  "code": "RECORD_IN_OTHER_ORGANIZATION",
  "details": { "organizationId": "org_01H...", "organizationSlug": "acme", "organizationName": "Acme Talent" },
  "hint": "Switch your active organization to \"Acme Talent\" (org_01H...) to open it (POST /auth/v1/organization/set-active { organizationId })."
}

It reveals nothing the caller could not see by switching. It is answered only when every condition holds:

  • The caller signed in interactively and can switch organizations: a session (cookie or session bearer) or a JWT minted from one. API keys (pinned to their own organization), OAuth tokens, service principals, scoped callers and link/share callers get the uniform miss, even when the key's owner is a member of the record's organization.
  • Membership is read server-side from the auth member table (one indexed lookup joined to organization), never from the request.
  • The caller's role in that organization (expanded through auth.roleHierarchy) passes the route's own pre-record access gate. The pre-record gate in the current organization still runs first, so a caller whose role cannot use the route gets ACCESS_ROLE_REQUIRED, not this.
  • The table's firewall is only column = ctx.activeOrgId and column = ctx.userId scopes plus isNull checks, with an organization scope on ctx.activeOrgId. Every such predicate counts, so a table may scope two owner columns, two null-check columns (deletedAt, archivedAt) or two organization columns. Switching to the record's organization must satisfy all of them: every ctx.activeOrgId column holds that organization, every owner column already matches, and no null-check column is set. A team scope (ctx.activeTeamId, which an organization switch resets), any: groups, in:, via:/permission arms and optional arms keep the uniform miss for the whole table.
  • Shared D1 only. Postgres (caller-scoped RLS) and tenant Durable Object tables keep the uniform miss.
  • The lookup runs only on the miss path, never on a hit. Routes without a declarative pre-record access gate, and audited unsafe actions, keep the uniform miss.
  • On a route wired for the hint, every miss runs the same queries: the probe plus one membership lookup, against a placeholder organization when there is no candidate. An absent id and a record in an organization you do not belong to take the same work. PUT reuses its own unscoped id probe, so a miss there runs one primary-key lookup, not two.
  • Batch items (PATCH, DELETE, PUT /batch) follow the same rule per item, gated by the batch route's own access, with one probe and one membership lookup per batch rather than per item. The lookup's query count depends only on the route's maxBatchSize (Batch Operations).

A non-member gets the uniform miss — the same body as for an id that does not exist.

Error codes:

CodeDescription
FIREWALL_NOT_FOUNDRecord not found behind firewall (wrong org, soft-deleted, or doesn't exist)
FIREWALL_ORG_ISOLATIONRecord belongs to a different organization
FIREWALL_USER_ISOLATIONRecord belongs to another user
FIREWALL_SOFT_DELETEDRecord has been soft deleted
FIREWALL_WRITE_DENIEDA create would land a row outside the caller's firewall (see Firewall on write); also a Postgres RLS refusal (42501)
RECORD_IN_OTHER_ORGANIZATION409. The record is in another organization the caller is a member of. details: { organizationId, organizationSlug?, organizationName? }; switch the active organization to open it (above)

An action that throws new ActionError(message, code, status) answers with that status as Problem Details too: detail is the message, code and layer: "action" are extension members, and details / hint ride along when set. Generated clients read the message from detail like every other error.

Inside an action, any statement through the scoped db on a table whose firewall needs a claim the caller does not carry (no activeOrgId for an org-scoped table, say — a PUBLIC or AUTHENTICATED action, or a scope principal on a table with no arm for its kind) fails with 403 FIREWALL_CLAIM_MISSING, layer: "action", and details: { table, claims } (the claim sets the firewall accepts) — the statement never runs, so a read cannot silently return [] and a row is never written into whatever tenant the body named. An INSERT whose conjunctive claim is missing reports details: { table, column, claim }.

An INSERT through the scoped db whose row would land outside the table's firewall (a project the caller has no relationship to) fails with 403 FIREWALL_WRITE_DENIED, layer: "firewall" — the same Problem the CRUD create paths return, and the one a Postgres RLS refusal (42501) inside an action maps to. A .prepare()d insert into such a table is refused with 400 FIREWALL_WRITE_CHECK_UNSUPPORTED.

For security-hardened deployments, set firewallErrorMode: 'hide' at the top level of the resource definition (not inside firewall: — it was lifted off when firewall became a predicate array) to return opaque 404 Not Found responses with NOT_FOUND instead — the same message and hint as the 403. Both modes are uniform: neither lets a caller distinguish "record exists but you can't access it" from "record doesn't exist". hide additionally keeps the status from saying "forbidden".

quickback/features/candidates/candidates.ts
import { feature, q } from "@quickback/compiler";

export default feature("candidates", {
  columns: {
    id:             q.id(),
    name:           q.text({ maxLength: 200 }).required(),
    organizationId: q.text({ maxLength: 64 }).required(),
    ...q.audit(),
    ...q.softDelete(),
  },
  firewallErrorMode: 'hide',   // top level — default: 'reveal' (403)
  firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
});

Access (403)

Access violations return 403 Forbidden when the user's role doesn't match the required roles for the operation.

{
  "detail": "Insufficient permissions",
  "layer": "access",
  "code": "ACCESS_ROLE_REQUIRED",
  "details": {
    "required": ["hiring-manager"],
    "current": ["interviewer"],
    "operation": "update",
    "rule": "crud.update.access",
    "failed": "role"
  },
  "hint": "crud.update.access admits roles [hiring-manager]; the caller has roles [interviewer]. Grant a listed role, or change crud.update.access."
}

details names the refusal: operation, the rule that refused it (read.access, crud.<op>.access, actions.<name>.access) and the gate that failed — role, userRole, principal, or record. Alongside: required / current (org roles), userRoleRequired / userRoleCurrent, principals, and requires (relationship / FGA arms the rule offers). When the role passed but the record did not (failed: "record"), the detail is "Access denied for this record" and details.conditions lists the rule's declared record: conditions — config, never the record's values. The code stays ACCESS_ROLE_REQUIRED in every case, so clients keep switching on it. A caller with no active organization is told so in the hint.

Error codes:

CodeDescription
ACCESS_ROLE_REQUIREDUser doesn't have the required role
ACCESS_CONDITION_FAILEDRecord-level access condition not met
ACCESS_OWNERSHIP_REQUIREDUser must own the record
ACCESS_NO_ORGNo active organization set
ACCESS_KEY_SCOPE_REQUIREDA scoped API key does not cover this route and method. details.required lists the scope that would admit it (empty outside the API base, which scoped keys never reach); details.current is the key's scopes
ACCESS_DENIEDA token bound to one instance was used for another (namespace, tenant and realtime ticket routes), or the caller's credential does not admit an operator surface
ENTITLEMENT_REQUIREDAn action's requires: JSON key did not hold for the record. details: { column, key }. Checked before execute
ACCESS_NO_ARMThe action declares access.arms and no arm's when matches the validated input

Guards (400)

Guard violations return 400 Bad Request when the request body contains fields that aren't allowed.

{
  "detail": "Field cannot be set during creation",
  "layer": "guards",
  "code": "GUARD_FIELD_NOT_CREATEABLE",
  "details": {
    "fields": { "stage": "cannot be set on create" },
    "allowed": ["name", "email", "phone"]
  },
  "pointer": "/stage",
  "hint": "stage not in guards.createable. Fields a create may set: name, email, phone. Omit the others, or add them to guards.createable."
}

GUARD_FIELD_NOT_CREATEABLE and GUARD_FIELD_NOT_UPDATABLE list the fields the operation accepts in details.allowed.

GUARD_FIELD_PROTECTED also carries details.actions — the actions that may change the field.

Guards judge the raw body before body validation, so a guarded field always answers its GUARD_* code — never VALIDATION_ERROR. A key that names no column at all is not a guard matter: it is VALIDATION_ERROR with "Unrecognized field" (see Validation). In a batch, a guard failure is reported per record (207, or BATCH_FAIL_FAST_STOPPED under failFast) rather than failing the whole request.

Error codes:

CodeDescription
GUARD_FIELD_NOT_CREATEABLEField not in createable list
GUARD_FIELD_NOT_UPDATABLEField not in updatable list
GUARD_FIELD_PROTECTEDField is action-only (protected)
GUARD_FIELD_IMMUTABLEField cannot be modified after creation
GUARD_SYSTEM_MANAGEDSystem field (createdAt, modifiedAt, etc.)

Platform-managed JSON keys (422)

A body that sets a platform key of a q.json(schema, { keys }) column answers 422 JSON_KEY_RESTRICTED (layer: "guards"). details.fields names each key as <column>.<key>. The response is the same on POST, PATCH, PUT, the batch routes (the whole request is refused), and changeset ops. An action whose write changes a platform key without a grant gets the same code and status, with details: { table, column, keys }.

{
  "status": 422,
  "code": "JSON_KEY_RESTRICTED",
  "layer": "guards",
  "details": { "fields": { "settings.beta": "is platform-managed — not writable through settings on this route" } }
}

Malformed record id (400)

Record routes (GET/PATCH/PUT/DELETE /:id, the changeset PATCH, and record actions at /:id/<action>) check :id against the table's id format and answer 400 before any database work when it can't be an id — a UUID route given job_123, a serial route given abc:

{
  "type": "https://quickback.dev/problems/invalid-id",
  "title": "Invalid id",
  "status": 400,
  "detail": "Malformed \"id\" path parameter",
  "layer": "validation",
  "code": "INVALID_ID",
  "details": { "param": "id", "expected": "a UUID" },
  "hint": "\"id\" must be a UUID. No record was looked up."
}
CodeDescription
INVALID_ID:id isn't shaped like the table's ids — see Malformed ids for the per-strategy shapes, what is never checked, and the validateIdParams: false opt-out

It is its own code, not a VALIDATION_* one: those describe the request body, and carry a JSON pointer into it. A bad path segment has no pointer, and "that's not an id" (400) versus "no such row" (403/404) is the distinction a client wants to branch on.

Validation (400)

A body that fails the column or action-input schema returns 400 with layer: "validation": VALIDATION_ERROR for CRUD bodies, VALIDATION_INVALID_INPUT for action input and query parameters (which also carries the raw Zod details.issues), VALIDATION_FAILED inside a changeset. details.fields maps each offending field to its message; an unknown key is reported under its own name:

{
  "detail": "Invalid input",
  "layer": "validation",
  "code": "VALIDATION_INVALID_INPUT",
  "details": {
    "issues": [ … ],
    "fields": { "name": "Required", "status": "Unrecognized field" }
  },
  "pointer": "/name"
}

Field errors — one shape

details.fields has one shape on every layer that names fields — guards, body and action-input validation, FK_NOT_FOUND: an object mapping the field name (a dotted path for nested input) to a human-readable message. A form can render each message under its input without knowing which layer rejected the request; the generated client exposes it as QuickbackError.fields. pointer names the first entry.

Masking

Masking doesn't produce errors — it silently transforms field values in the response.

Database

Surfaced when a SQL write fails post-validation — most often a NOT NULL or UNIQUE constraint hit at the storage layer (e.g. an FK target was deleted concurrently, or a unique column collided with another tenant's row). All four codes share the same layer: "database" so consumers can switch on the layer alone and treat the rest as one bucket.

{
  "detail": "Duplicate value",
  "layer": "database",
  "code": "DB_UNIQUE_VIOLATION",
  "details": {
    "column": "organizationId",
    "columns": ["organizationId", "email"],
    "fields": { "organizationId": "Already taken", "email": "Already taken" }
  },
  "hint": "A record with this \"organizationId\" + \"email\" already exists"
}

A unique violation names every column of the constraint (a composite unique lists all of them) as API field names, and marks each in details.fields so a form can show the conflict inline. details.column is the first of them.

Error codes:

CodeStatusDescription
DB_NOT_NULL_VIOLATION400Required column was null at write time
DB_UNIQUE_VIOLATION409Unique constraint hit
DB_RELATIONSHIP_MISMATCH400A referenced row does not match the required parent column
DB_INSERT_FAILED500INSERT failed for an unrecognized reason
DB_UPDATE_FAILED500UPDATE failed for an unrecognized reason
DB_DELETE_FAILED500DELETE (or soft-delete UPDATE) failed for an unrecognized reason
DB_TIMEOUT503Retryable. A read passed queryTimeoutMs (D1 only). The read had no side effects; retry. details: { binding }
DB_WRITE_OUTCOME_UNKNOWN500A write passed queryTimeoutMs. D1 does not cancel the statement, so it may still commit after the response. Re-read the record before retrying — a blind retry can double-apply. details: { binding, outcome: 'unknown' }
ENCRYPTION_UNREADABLE422A stored .encrypted() value will not decrypt
TRIGGER_REJECTED422 / 403A before-trigger refused the write; nothing was persisted. layer: "trigger", details.code for a prefixed sql: rejection or an invariant. An invariant also sets details.table, rule, fields, field and id (what a refusal says)

The details.column field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).

The same classification applies to every write path — single-record create, update, PUT and delete, the batch endpoints (including DELETE /batch, which reports these DB_* codes per id, or as the failFast response), bulk actions, and changesets.

DB_INSERT_FAILED, DB_UPDATE_FAILED and DB_DELETE_FAILED are the fallback for a failure that matches no known constraint. The driver message (D1 or Postgres text, which can name tables, columns, and SQL fragments) is always logged with console.error — with bound values redacted (see Bound values never leave the database) — and the production body carries no details:

{
  "detail": "Update failed",
  "layer": "database",
  "code": "DB_UPDATE_FAILED",
  "hint": "Database rejected the update. Check server logs for the underlying error."
}

The (redacted) message appears as details.reason only when the worker runs with EXPOSE_ERROR_STACK set.

Bound values never leave the database

A database error can carry the row it was writing: drizzle reports every driver failure as Failed query: <sql> followed by params: <values>, and Postgres inlines values into its own text (Key (email)=(…) already exists, Failing row contains (…)). Every place the generated API records an error — console.error in CRUD, batch, changeset and action catches, the global onError, queue consumers, webhook event and delivery rows, afterCommit failures, the error_message column of audit_events, and the EXPOSE_ERROR_STACK bodies, and Better Auth's own logger (the generated betterAuth({ logger }), which covers endpoint failures and the database adapter) — passes it through redactError in the generated src/lib/errors.ts first. Only the values are removed:

Driver textLogged / stored as
Failed query: insert into "account" ("id", "user_id", "password") values (?, ?, ?)
params: acc_1,usr_1,$argon2id$…
Failed query: insert into "account" ("id", "user_id", "password") values (?, ?, ?)
params: [string(5), string(5), string(97)]
UNIQUE constraint failed: account.user_id (D1, libsql)unchanged
duplicate key value violates unique constraint "users_email_key", detail: Key (email)=(x@y.com) already exists. (Postgres)message unchanged; detail: Key (email)=(<redacted>) already exists.
Failing row contains (r1, x@y.com, …)Failing row contains (<redacted>)
invalid input syntax for type uuid: "…"invalid input syntax for type uuid: "<redacted>"
Key (lower(email::text))=(…) (expression index), conflicts with existing key (…)=(…) (exclusion constraint)=(<redacted>)
value "…" is out of range for type integer, date/time field value out of range: "…", malformed array literal: "…", Token "…" is invalid.the quoted literal becomes "<redacted>"; quoted constraint, relation, column and table names stay

The SQL with its placeholders, table, column and constraint names, the driver code (SQLITE_CONSTRAINT_UNIQUE, 23505), the parameter count and each parameter's type and length stay, so the log line still tells you which statement failed and why; the requestId correlates it with the response, and the global error log line also carries the driver code and causeCode. Driver text past 16 KB is cut and marked [truncated], so a hostile value can't make redaction slow. Classification is unaffected — the DB_* codes above are computed from the original error. Your own code can call redactError(error) from src/lib/errors before logging a caught error.

ENCRYPTION_UNREADABLE always carries details: { table, column, id } — the row whose stored ciphertext is malformed, was not written under the caller's organization key, was copied from another column or table, or names a key version the organization does not have. Rewriting the field repairs the row.

Legacy forwards

A legacy forward answers these itself, before it dispatches; every other response is the successor route's. Each carries the Deprecation, Sunset and Link headers.

CodeStatusMeaning
LEGACY_ORG_REQUIRED403The caller has no active organization, is an instance-bound OAuth token, or (database per tenant) its active organization is not the tenant. Call the successor URL in Link.
LEGACY_INSTANCE_REQUIRED400The request names no instance: no ?C= (or a repeated / ?C.<op>= one) on a collection, no C in the body, or an id that is not a valid instance id.
LEGACY_INSTANCE_MISMATCH400The request names more than one instance (a batch spanning instances, or a body C that disagrees with ?C=).

An instance outside the caller's organization answers the namespace gate's 403 ACCESS_ROLE_REQUIRED; a row outside it answers the table's firewall miss (403 FIREWALL_NOT_FOUND, or 404 with firewallErrorMode: 'hide').

Claimed tables

A table a namespace claims is pinned to the URL instance.

CodeStatusMeaning
INSTANCE_MISMATCH400A create body (or a batch record) sends the instance column with a value other than the instance in the URL. layer: "validation", details: { field, param } (plus index for a batch record). Omit the column: it is taken from the URL.

Tenancy (database per tenant)

With tenancy.isolation: 'durable-object', responses about an organization's own database carry layer: "tenancy" and one of these codes. See Database per Tenant.

CodeMeaning
TENANT_REQUIREDThe route reads an organization's own database but the request names no organization (or names an invalid id)
TENANT_MISMATCHThe principal does not belong to the tenant object it reached
TENANT_SCOPE_MISMATCHA scope claim names a different tenant than the request
TENANT_AMBIGUOUSThe instance resolves to more than one organization; set an active organization
TENANT_UNAVAILABLEThe organization database or directory is unavailable; retry (Retry-After)
TENANT_OVERLOADEDThe organization database is overloaded; retry after Retry-After
TENANT_DEPTH_EXCEEDEDSubrequest depth limit exceeded calling the organization database (508)
TENANT_ADMISSION_UNAVAILABLEScope admission could not be checked right now; retry
TENANT_LOOKUP_UNAVAILABLEThe tenant lookup index could not be read; retry
TENANT_LOOKUP_PENDINGThe instance is not indexed to a tenant yet; retry
TENANT_NOT_PROVISIONEDThe organization has no tenant database registered (operator routes other than archive refuse it)
TENANT_ARCHIVEDThe organization is archived (423); an operator can unarchive it
TENANT_PURGEDThe organization's data was purged (410)
TENANT_MIGRATION_FAILEDThe organization database failed to migrate (503); details names the migration
TENANT_JURISDICTION_MISMATCHThe registry row was written under another jurisdiction
TENANT_RPC_VERSION_MISMATCHThe edge and tenant Workers disagree on the RPC contract; deploy the tenant Worker first
TENANT_AUTHORIZATION_EPOCH_CHANGEDA restore advanced the tenant's authorization epoch; credentials issued before it are refused
TENANT_RESTORE_PENDINGA restore is pending or unreconciled; sync or cancel it first
STORAGE_FILE_NOT_READYA tenant upload is not verified (or is unavailable after a restore); details.status says which (409)
STORAGE_FILE_BRIDGE_EDGE_OUTDATED / STORAGE_FILE_BRIDGE_UNAVAILABLEThe tenant file bridge cannot sign here: the edge Worker is older than the object, or the call is not a forwarded request (a job or alarm) (503)
TENANT_FILE_GRANT_FAILED / TENANT_FILES_PURGING / TENANT_BRIDGE_* / TENANT_FILE_*The edge refused (or could not sign) a tenant file grant: a forged or malformed envelope, a reused key, a stale generation, or a purge cleanup in progress
TENANT_RESTORE_TOO_LARGEOperator restore: the dump exceeds the restore limit (413)
TENANT_OPERATION_FAILEDOperator route refused or failed (409); detail says why
TENANT_COMMAND_INVALIDA tenant command request failed its schema
TENANT_COMMAND_FINGERPRINT_MISMATCHA tenant command was compiled against a different contract
TENANT_COMMAND_REPLY_INVALIDThe tenant object answered a command with a malformed reply
TENANT_JOB_INVALIDA tenant job message is invalid
TENANT_JOB_CALL_ONLYA result job was delivered instead of called (callTenantJob)
TENANT_JOB_PLACEMENTA tenant job was sent to an object of the wrong placement (a partition job outside its partition, an organization job in a partition), or its message names another partition
TENANT_JOB_STALE_GENERATIONA queued tenant job was delivered under a restore generation the object no longer has; it is dropped, never run
TENANT_JOB_FAILEDA called tenant job failed
TENANT_JOB_REPLY_INVALIDThe tenant object answered a job call with a malformed reply
TENANT_JOB_RESULT_INVALIDA tenant job result is not serializable
TENANT_JOB_RESULT_TOO_LARGEA tenant job result exceeds the size limit
TENANT_TABLE_ON_EDGEEdge code queried a tenant table (500, a compile-placement bug)

On this page