Skip to content

0007. Cross-module reads through published queries ​

Status: accepted. Applies to crates/kernel (manifest, registry, Ctx, bus), crates/authz (schema, loader, audit), the doors (GraphQL, MCP, CLI generation) and every module that publishes or consumes a query. First users: payroll reading core (national ID, bank details) and tax-benefits (TIN, previous employer's year-to-date figures).

Context ​

Contract rule 2.3 lets a module read another module's data only through that module's published query interface. Events carry ids, dates, flags and versions only (no personal values: ADR 0005 refuses redacted values in payloads), so payroll cannot learn an employee's bank account from core.employee.joined. Today no module calls another module's handler in-process, and every handler runs as its own database role (ADR 0005), so payroll's role cannot select from core.*.

Decision ​

  1. Publishing. The owning module lists the queries other modules may call under [provides] published = ["core.employee.pay_details"]. A published query is an ordinary registered query handler (Kind::Query) with its own Cedar action, but it is only callable in-process: the bus refuses it from dispatch/dispatch_json (unknown name) and the doors never generate a GraphQL field, MCP tool or CLI verb for it. It is listed under published only (never also under queries), registered with Module::published::<H>() and kept apart in the registry: Registry::handlers(), which every door iterates, never yields it; Registry::published() does. Its output carries personal values only as orbit_pii fields checked per field (redacted when denied), like any query.

  2. Consuming. The caller declares the owning module in requires or optional and the query under [consumes] queries = [...]. At startup the registry refuses a consumed query that is not published by a declared dependency. Cycles are already refused by the dependency graph, which includes optional (RegistryError::DependencyCycle).

  3. API. ctx.query::<Q>(input).await -> Result<Q::Output, QueryError>, where Q is the owning module's handler type, exported from its crate under published (payroll already depends on orbit-core for id types, as leave does). QueryError is NotEnabled { module } or Domain(DomainError); From<QueryError> for DomainError maps NotEnabled to Conflict with reason module_not_enabled. A published handler may not call ctx.query itself (one level only); that, and a query missing from the caller's consumes, return Domain(Invalid). An optional owner that is not compiled into the build is NotEnabled.

  4. What the call does, inside the caller's transaction (same tenant, same actor, door, request id and confirmed):

    1. SAVEPOINT.
    2. Gate: Cedar with the human actor as principal, the published action, resource is Tenant, and context.via = "<calling module>".
    3. Enablement: the owning module must be enabled for the tenant, else NotEnabled (payroll treats a disabled optional tax-benefits as "no profile"; a disabled required core cannot happen, since enabling payroll needs core and disabling core is refused while payroll is enabled). NotEnabled is not audited: it is the expected answer for a disabled optional owner, not a denial.
    4. SET LOCAL ROLE orbit_mod_<owner>; run the handler on a Ctx whose op is the published handler's (so row and field checks use its action), with resource_checked and the revealed-field set reset; the bus's rule applies (it must call ctx.authorize or be TENANT_SCOPED).
    5. Tripwire: still_scoped_as(tenant, owner), else the whole request fails (BusError::TenantChanged).
    6. ROLLBACK TO SAVEPOINT, then RELEASE. This discards any write the published handler made (it is a read; core's outbox trigger never sees a row) and, because SET LOCAL is undone by a rollback to an earlier savepoint, restores the caller's role without a second SET ROLE statement. The output is already in memory.
    7. Tripwire again: still_scoped_as(tenant, caller).
  5. Cedar. The context gains via: String, empty for anything a door dispatched. The loader requires every permit on a published action to have a condition context.via == "<module>" naming a module that consumes it, and a scoped principal (as today). There is no other way to allow a published action, so the module grant (the via clause) and the human's permission (the principal clause) are always both required, in one policy written and owned by the owning module. Base policies are unchanged: an API client or agent still needs the published action in its grants (the ceiling of ADR 0001). Grants are written by upsert_membership, which has no registry at hand, so instead of refusing a grant for a published action when it is issued, a base policy forbids every published call for a principal that is not a User (context.via != "" && !(principal is User)): an API client, an agent or the system never passes, whatever it was granted. Only a top-level conjunct of a when clause counts as the via condition (not one inside || or unless). A via naming a module that is not compiled into the build is accepted and stays inert (that module never calls); one naming a compiled-in module that does not consume the action is refused.

  6. Personal fields: how the two permissions combine. For each personal field the published handler reveals, orbit_pii makes its usual Field check with the published action. It is allowed only when a single owning-module permit matches both context.via == "payroll" and the human's payroll grant (ADR 0008). The human's own permission on core's door queries (core.employee.get) is not consulted: a payroll admin who is not an HR admin still gets bank details for a run, and an HR admin without a payroll grant gets none through payroll. The calling command's own gate and resource check (e.g. payroll.run.lock for a payroll admin) are a third precondition, since the call happens only inside it. Example in core's policies.cedar:

    cedar
    permit (principal in ModuleRole::"payroll.payroll_admin",
            action == Action::"core.employee.pay_details", resource is Field)
    when { context.via == "payroll" && resource.row_kind == "core.employee" &&
           ["national_id", "bank_name", "bank_account"].contains(resource.name) };
    permit (principal in ModuleRole::"payroll.preparer",
            action == Action::"core.employee.pay_details", resource is Field)
    when { context.via == "payroll" && resource.row_kind == "core.employee" &&
           resource.name == "national_id" };

    (plus the matching gate and row permits, and the same for owners with principal is User in Role::"owner"). A preparer's run.calculate therefore sees national IDs but bank fields come back redacted; a payroll admin's run.lock writes the bank file. An agent never matches: agents hold no ModuleRole.

  7. Audit. Each published call that revealed a field writes its own read entry: the published action, the human actor, door, request id, the columns revealed (never values) and the new via column (the calling module). A gate or resource denial of the call writes a denied entry with via. These entries are written with the outer attempt: in its transaction when it is a command that commits, otherwise on the sink's own connection (as rejections are today), so a failed outer command still records what was read. The outer entry names only the caller's own fields.

  8. What the caller does with the values. A consumer must not put values it read through a published query into its own query outputs, events or tables, except where its own field permissions allow the reader to see them (e.g. a payroll admin's bank file). Its own field policies decide who sees them again, not the owner's; the payroll review checks this for every published read.

  9. Events do not change. Personal values never travel in events or job payloads, and the caller never stores them in its own tables. The one exception is a document the caller generates for its purpose (a bank file, a statutory return), stored as an encrypted orbit_storage blob whose download is an audited read.

Implementation notes ​

  • Ctx::query swaps the caller's op, resource-check flag, before/after hashes, revealed fields and flags out for the call and back in after it, so the caller's own audit entry names only its own fields.
  • A published handler that breaks a bus rule (panics, never runs a resource check while not TENANT_SCOPED, or leaves the transaction on another role or tenant) gets the caller a Domain(Invalid) error, and the bus then fails the whole request with HandlerPanicked, ResourceUnchecked or TenantChanged (audited failed) even if the caller swallowed that error.
  • The savepoint name is unique per call (orbit_published_<uuid>), so a savepoint the published handler opens itself can never shadow it and keep a write.
  • The call is cancel-safe: if the caller drops the ctx.query future mid-flight (a timeout, a select!), a drop guard puts the caller's frame back and marks the request failed (TenantChanged), since the savepoint was never rolled back; the bus also refuses to finish a request while a published call is still marked in flight. The caller's own audit entry stays its own.
  • Every permit on a published action must also scope the person by membership: principal in Role::.../ModuleRole::... in its scope, or a top-level when conjunct of such tests (a disjunction of them counts); principal is User alone is refused.
  • References to modules not compiled into the build (an inert via or ModuleRole) are logged at startup; the build with every module fails a test on any, except modules listed as pending (none since payroll landed).
  • The published calls' audit entries are written before the outer command's own entry, in its transaction when it commits; for a query, or a request that fails, each on the sink's own connection.
  • core.employee.pay_details checks the batch as a whole (core.employees) before each row (core.employee), so a call whose ids all miss is still authorised.

Consequences ​

  • One more role switch per call, inside the request's transaction; a published query should take a list of ids so a run makes one call per employee batch, not one per employee.
  • Values read are as of the caller's transaction snapshot, consistent with its own reads.
  • The owning module decides, in its own policy file, which caller modules and which of their grants may see which of its fields; a new consumer is a policy change in the owner, reviewed there (contract 7.5: raised as an issue on the owning module).
  • Like ADR 0005, this guards against bugs, not hostile in-process code.
  • The doors' generators and the registry's handler iteration must skip published actions.

Tests required ​

  • Registry: a consumed query not published by a declared dependency, or published by an undeclared module, is refused at startup; ctx.query for a query not in the caller's consumes fails.
  • Bus: a published action dispatched from any door is UnknownName.
  • Loader: a permit on a published action without context.via == "<consumer>", or naming a module that does not consume it, is refused.
  • Allow/deny: payroll admin gets bank fields via payroll; preparer gets national ID only; HR admin without a payroll grant, manager, member, API client and agent get nothing; the same person calling a door query gets core's normal result.
  • Audit: one read entry per call naming the columns and via = payroll; a denied call writes denied with via; a failed outer command still has the read entry.
  • Roles: inside the call current_setting('role') is orbit_mod_core, after it orbit_mod_payroll; a published handler that runs RESET ROLE fails the request, and one that writes a row leaves no row (nor an outbox event) after the call.
  • Tenancy: the call never returns another tenant's row (tenants_never_see_each_other).
  • A disabled optional owner returns NotEnabled.

Alternatives considered ​

  • Copies in the caller (payroll keeps its own sealed copy of bank details, fed by events). Two sources of truth for personal data, a second place to erase, and events would need to carry the values. Rejected.
  • Sealed values in events (encrypted for the consumer). Personal values in the outbox and dead-letter tables, key distribution between modules, and replay of stale values. Rejected.
  • A read-only cross-schema view or SECURITY DEFINER function per consumer. Bypasses Cedar, field checks and audit. Rejected.
  • Nested SET ROLE without a savepoint. Needs an explicit switch back and cannot undo a stray write by the published handler. Rejected in favour of the savepoint.

Amendment (Phase 3, with ADR 0009) ​

The system may call a published query when the owning module names it explicitly: a permit (principal == System::"system", ...) with the same context.via == "<consumer>" condition. The loader accepts that principal scope for published permits, and the base policy now forbids published calls for API clients and agents only (!(principal is User || principal is System)), so without such a permit the system is still refused (no policy allows it). First use: core.employee.payslip_header, which payroll's payslip renderer (payroll.payslip.render, run as the system) reads for the company's and employee's names and the employee number.

Orbit by SkySync Tech. Licensed under AGPL-3.0.