Appearance
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
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 fromdispatch/dispatch_json(unknown name) and the doors never generate a GraphQL field, MCP tool or CLI verb for it. It is listed underpublishedonly (never also underqueries), registered withModule::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 asorbit_piifields checked per field (redacted when denied), like any query.Consuming. The caller declares the owning module in
requiresoroptionaland 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 includesoptional(RegistryError::DependencyCycle).API.
ctx.query::<Q>(input).await -> Result<Q::Output, QueryError>, whereQis the owning module's handler type, exported from its crate underpublished(payroll already depends onorbit-corefor id types, as leave does).QueryErrorisNotEnabled { module }orDomain(DomainError);From<QueryError> for DomainErrormapsNotEnabledtoConflictwith reasonmodule_not_enabled. A published handler may not callctx.queryitself (one level only); that, and a query missing from the caller'sconsumes, returnDomain(Invalid). Anoptionalowner that is not compiled into the build isNotEnabled.What the call does, inside the caller's transaction (same tenant, same actor, door, request id and
confirmed):SAVEPOINT.- Gate: Cedar with the human actor as principal, the published action,
resource is Tenant, andcontext.via = "<calling module>". - Enablement: the owning module must be enabled for the tenant, else
NotEnabled(payroll treats a disabled optionaltax-benefitsas "no profile"; a disabled requiredcorecannot happen, since enabling payroll needs core and disabling core is refused while payroll is enabled).NotEnabledis not audited: it is the expected answer for a disabled optional owner, not a denial. SET LOCAL ROLE orbit_mod_<owner>; run the handler on aCtxwhose op is the published handler's (so row and field checks use its action), withresource_checkedand the revealed-field set reset; the bus's rule applies (it must callctx.authorizeor beTENANT_SCOPED).- Tripwire:
still_scoped_as(tenant, owner), else the whole request fails (BusError::TenantChanged). ROLLBACK TO SAVEPOINT, thenRELEASE. This discards any write the published handler made (it is a read; core's outbox trigger never sees a row) and, becauseSET LOCALis undone by a rollback to an earlier savepoint, restores the caller's role without a secondSET ROLEstatement. The output is already in memory.- Tripwire again:
still_scoped_as(tenant, caller).
Cedar. The context gains
via: String, empty for anything a door dispatched. The loader requires everypermiton a published action to have a conditioncontext.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 (theviaclause) 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 byupsert_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 aUser(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 awhenclause counts as theviacondition (not one inside||orunless). Avianaming 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.Personal fields: how the two permissions combine. For each personal field the published handler reveals,
orbit_piimakes its usualFieldcheck with the published action. It is allowed only when a single owning-module permit matches bothcontext.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.lockfor a payroll admin) are a third precondition, since the call happens only inside it. Example in core'spolicies.cedar:cedarpermit (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'srun.calculatetherefore sees national IDs but bank fields come back redacted; a payroll admin'srun.lockwrites the bank file. An agent never matches: agents hold noModuleRole.Audit. Each published call that revealed a field writes its own
readentry: the published action, the human actor, door, request id, the columns revealed (never values) and the newviacolumn (the calling module). A gate or resource denial of the call writes adeniedentry withvia. 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.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.
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_storageblob whose download is an audited read.
Implementation notes
Ctx::queryswaps 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 aDomain(Invalid)error, and the bus then fails the whole request withHandlerPanicked,ResourceUncheckedorTenantChanged(auditedfailed) 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.queryfuture mid-flight (a timeout, aselect!), 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-levelwhenconjunct of such tests (a disjunction of them counts);principal is Useralone is refused. - References to modules not compiled into the build (an inert
viaorModuleRole) 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_detailschecks 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.queryfor a query not in the caller'sconsumesfails. - 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
readentry per call naming the columns andvia = payroll; a denied call writesdeniedwithvia; a failed outer command still has thereadentry. - Roles: inside the call
current_setting('role')isorbit_mod_core, after itorbit_mod_payroll; a published handler that runsRESET ROLEfails 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 DEFINERfunction per consumer. Bypasses Cedar, field checks and audit. Rejected. - Nested
SET ROLEwithout 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.