RolebookDocs

Fact schemas

Declare the facts your policy reads, catch mistyped fact paths and operand types before deployment, and check request facts before binding.

A policy reads facts by path, and Core accepts any well-formed path. A typo such as resource.stauts is a valid policy: no request has that fact, so the comparison is unknown and an allow that needs it never matches. A fact schema declares which facts exist and what JSON types they hold. The optional rolebook/authoring entry point checks a policy, or the facts of one request, against that schema.

rolebook never imports this entry point. If you do not use it, nothing changes.

What these checks prove, and what they do not

  • Validation checks shape only: that a fact is present and has a declared type. It cannot prove that a fact is fresh or where it came from. Load facts from your own authoritative, tenant-scoped records, exactly as before.
  • A passing result is never a grant. Nothing in rolebook/authoring makes a request more permitted.
  • Core’s decision does not change. check, enforce, and explain decide exactly as they would without a schema. A policy that definePolicy() accepts stays accepted by Core, even when the authoring checks reject it.

Use the checks to stop a bad policy at deployment and to notice a broken fact loader. Do not use them to decide who may do what.

Declare a fact schema

import { defineFactSchema } from "rolebook/authoring";

const projectFacts = defineFactSchema({
  format: "rolebook-fact-schema",
  version: 1,
  id: "projects",
  facts: {
    "subject.department": { types: ["string"], required: true },
    "subject.suspended": { types: ["boolean"] },
    "resource.ownerId": { types: ["string"], required: true },
    "resource.status": { types: ["string"] },
    "resource.tags": { types: [{ array: "string" }] },
    "resource.priority": { types: ["number", "null"] },
    "context.ipCountry": { types: ["string", "null"] },
  },
});

The schema is plain data, so it can live in a JSON file next to the policy. Each key is a fact path, and each declaration has:

  • types: one to six of "string", "number", "boolean", "null", "object", one array type such as { array: "string" }, or "json" on its own for any value;
  • required: optional, false by default. It means the fact must be present. A required fact may still be null when "null" is one of its types.

subject.type, subject.id, resource.type, and resource.id are always known, required strings. Do not declare them.

A path with dots means nested properties: resource.metadata.visibility is the visibility property of resource.metadata. When you declare both, the parent must allow "object" or "json", because nothing else can be traversed. Arrays are never traversed, even when their elements are objects. A parent may be optional while a child is required: when the parent is missing, the child is reported missing.

defineFactSchema() copies, checks, and freezes the schema, and throws a FactSchemaError when it is malformed. Its diagnostics point at each bad declaration, for example /facts/subject.id for a redeclared identity. The other functions accept only a schema that defineFactSchema() returned. A schema that went through JSON.stringify must be defined again.

Check a policy before you deploy it

compilePolicy() defines the policy with definePolicy() and checks every condition against the schema. This draft has a mistyped path, and it applies startsWith, a string operator, to an array:

import { compilePolicy } from "rolebook/authoring";

const draft = compilePolicy(
  {
    resources: { project: { actions: ["read", "update"] } },
    roles: {
      editor: {
        scope: "project",
        rules: [
          {
            effect: "allow",
            permission: "project:update",
            where: {
              all: [
                { fact: "resource.ownerId", operator: "equals", value: { fact: "subject.id" } },
                { fact: "resource.stauts", operator: "equals", value: "draft" },
                { fact: "resource.tags", operator: "startsWith", value: "eng-" },
              ],
            },
          },
        ],
      },
    },
  },
  projectFacts,
);
// draft.ok === false, and there is no draft.policy.
// draft.diagnostics, without their messages:
// { severity: "error", code: "UNKNOWN_FACT", pointer: "/roles/editor/rules/0/where/all/1/fact" }
// { severity: "error", code: "INCOMPATIBLE_OPERANDS", pointer: "/roles/editor/rules/0/where/all/2/operator" }

definePolicy() accepts this draft. Only the authoring check rejects it.

With the path fixed and contains in place of startsWith, the policy compiles. A warning does not stop it:

import { createAuthorizer } from "rolebook";

const compiled = compilePolicy(
  {
    resources: { project: { actions: ["read", "update"] } },
    roles: {
      editor: {
        scope: "project",
        rules: [
          {
            effect: "allow",
            permission: "project:update",
            where: {
              all: [
                { fact: "resource.ownerId", operator: "equals", value: { fact: "subject.id" } },
                { fact: "resource.status", operator: "equals", value: "draft" },
                { fact: "resource.tags", operator: "contains", value: "eng" },
              ],
            },
          },
          {
            effect: "allow",
            permission: "project:read",
            where: { fact: "resource.priority", operator: "greaterThan", value: 2 },
          },
        ],
      },
    },
  },
  projectFacts,
);
// compiled.ok === true
// compiled.diagnostics, without their messages:
// { severity: "warning", code: "POSSIBLY_UNSUPPORTED_OPERANDS", pointer: "/roles/editor/rules/1/where/operator" }

if (!compiled.ok) throw new Error("The policy failed its authoring checks");
const authorizer = createAuthorizer(compiled.policy);

resource.priority may be null, and greaterThan compares only numbers or strings, so some declared values cannot satisfy the comparison. That is a warning, not an error: at runtime such a comparison is unknown, and an allow does not match. compiled.policy is the object definePolicy() returns for the same input, with the same canonicalPolicyJson(). analyzePolicy() returns the same ok, diagnostics, and truncated without the policy.

The analysis checks:

  • Fact paths. The left fact of every comparison and every fact-reference operand must be declared or be a reserved identity. Every node is visited, including branches that a runtime short circuit would skip.
  • Operand types. For each operator, it compares every declared type of the fact with every type of the operand. When no pair can work, it reports INCOMPATIBLE_OPERANDS. When some pairs cannot work, or a pair needs a value the schema cannot describe (a non-empty string, a non-empty array, a non-negative integer), it warns with POSSIBLY_UNSUPPORTED_OPERANDS. equals, notEquals, and exists accept any declared type. A literal operand is already checked by definePolicy().
  • Duplicate rules. A direct rule whose canonical JSON equals an earlier rule of the same role is a DUPLICATE_RULE warning. The duplicate stays in the compiled policy.

This is compatibility analysis. It does not prove that a condition can be true, and it does not look for contradictions, shadowed rules, or unused rules.

Validate facts before you bind

validateFacts() checks the subject, the trusted resource, and the context you are about to bind. It performs no authorization. Decide in your own code what a failure means, and decide it before binding:

import type { Subject, TrustedResource } from "rolebook";
import { type Diagnostic, validateFacts } from "rolebook/authoring";

type Outcome = "allowed" | "denied" | "unavailable";

function updateProject(
  subject: Subject,
  project: TrustedResource,
  context: { readonly ipCountry: string | null },
  report: (diagnostics: readonly Diagnostic[]) => void,
): Outcome {
  const facts = validateFacts(projectFacts, { subject, resource: project, context });
  if (!facts.ok) {
    // This application treats malformed facts like a database outage. Answering "denied" is
    // the other safe choice. Either way, the request is not bound or checked.
    report(facts.diagnostics);
    return "unavailable";
  }
  const decision = authorizer
    .bind({
      subject,
      assignments: [
        {
          subject: { type: subject.type, id: subject.id },
          role: "editor",
          scope: { resource: project.ref, appliesTo: "self" },
        },
      ],
      context,
    })
    .check({ permission: "project:update", resource: project });
  return decision.allowed ? "allowed" : "denied";
}

The assignment here is inline to keep the example short. Load assignments as you always do.

Suppose a loader returns the priority as a string and drops the owner column:

import { trustedResource } from "rolebook";

const alice: Subject = { type: "user", id: "alice", attributes: { department: "eng" } };
const broken = trustedResource({ type: "project", id: "p2" }, [], {
  status: "draft",
  priority: "high",
});

const outcome = updateProject(alice, broken, { ipCountry: "DE" }, (diagnostics) => {
  for (const { severity, code, pointer } of diagnostics) console.log(severity, code, pointer);
});
// error MISSING_REQUIRED_FACT /resource/ownerId
// error FACT_TYPE_MISMATCH /resource/priority
// outcome === "unavailable"

Without the validation, Core would still fail closed: the owner comparison is unknown, so the allow does not match and the answer is "denied". Validation does not make that answer safer. It tells you that the loader is broken, and lets you choose an answer that says so.

Pointers here are logical: /resource/ownerId names the fact resource.ownerId, which Core reads from the resource’s attributes. They are not locations in your input. A structural problem, such as an undefined value anywhere in the facts, a malformed subject, or a value over Core’s limits, is one INVALID_FACTS error at the empty pointer instead of per-fact diagnostics.

What the checks deliberately do not do

  • An object or json fact does not declare its children. Declaring resource.metadata as "object" does not make resource.metadata.visibility known. Each path a policy references must be declared itself.
  • Undeclared properties are allowed at runtime. validateFacts() checks declared paths and ignores the rest, within Core’s structural limits. It removes nothing.
  • Missing optional facts are not warned about. A policy may reference an optional fact, and a request may omit it. Core already fails closed on a missing fact: an allow does not match, and a conditional deny does.
  • No rule is rewritten or removed. Duplicates are reported and kept. Branches are never simplified by type.
  • A policy Core accepts stays accepted by Core. The checks run only where you call them.
  • No duplicate-key detection. The functions take parsed objects. If your schema or policy comes from JSON text, duplicate keys are your parser’s concern.

Diagnostics

Every result has the same shape: ok, a frozen list of diagnostics, and truncated.

CodeSeverityReported byMeaning
INVALID_SCHEMAerrordefineFactSchema (thrown), the othersA malformed schema or declaration, or a schema that did not come from defineFactSchema.
INVALID_POLICYerroranalyzePolicy, compilePolicydefinePolicy() rejects the policy. The error’s text is not included.
UNKNOWN_FACTerroranalyzePolicy, compilePolicyA fact path, or a fact-reference operand, is not declared.
INCOMPATIBLE_OPERANDSerroranalyzePolicy, compilePolicyNo declared type pair can satisfy the operator.
POSSIBLY_UNSUPPORTED_OPERANDSwarninganalyzePolicy, compilePolicySome declared type pairs may not satisfy the operator.
DUPLICATE_RULEwarninganalyzePolicy, compilePolicyA direct rule repeats an earlier rule of the same role.
INVALID_FACTSerrorvalidateFactsThe facts are structurally invalid.
MISSING_REQUIRED_FACTerrorvalidateFactsA required fact does not resolve.
FACT_TYPE_MISMATCHerrorvalidateFactsA fact’s value matches none of its declared types.
  • ok is false when there is any error. Warnings never make it false.
  • An operation records at most 128 diagnostics. truncated is true when it had more to report. Errors past the cap still count, so a truncated result with only warnings showing can still have ok: false.
  • pointer is an RFC 6901 JSON Pointer, not a line and column. In a policy it follows the policy’s structure, such as /roles/editor/rules/0/where/all/1/fact. A comparison’s type problem points at its /operator, and a duplicate rule at the rule. A schema declaration error points at /facts/<path>, with the whole path as one segment. A structural failure uses the empty pointer.
  • The order is deterministic: schema paths and role names sorted by UTF-16 code unit, rules and conditions in declaration order.
  • message is a fixed sentence for each code. It never contains a path, a literal, or a value, so a diagnostic does not leak a fact. The wording is not a contract and may change: key your handling on code, severity, and pointer.

Diagnostics name fact paths and role names. Treat them as authoring metadata, and decide yourself whether to show them to end users.

Editor diagnostics

toEditorDiagnostics(diagnostics) returns a fresh frozen { pointer, severity, code, message } for each diagnostic, in order, ready to hand to an editor integration. It reads no file and throws TypeError("Invalid diagnostics") for anything that is not a list of at most 128 well-formed diagnostics. The pointer is still a JSON Pointer: mapping it to a line in your source file is the editor’s job.

See the rolebook/authoring API reference for every signature. A runnable version of this page is examples/authoring.ts in the repository: bun examples/authoring.ts.