|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#25522 cut 12] The driver-options and engine-posture bodies of `ObjectQL`, |
| 5 | + * moved out of `engine.ts` whole: `buildDriverOptions` (the `DriverOptions` |
| 6 | + * every driver call receives: the transaction handle, the tenant scope, the |
| 7 | + * timezone and the tenant-audit fill-ins), `driverReadScope` (the Layer 0 |
| 8 | + * verdict projected onto a read's driver scope), `engineLayer0Verdict` (that |
| 9 | + * verdict over the engine's own facts), `wallExemptedOperation` (did the |
| 10 | + * wall's exemption lift this operation's scope), `driverWriteTarget` (the |
| 11 | + * write target of an insert or upsert) and `resolveEnginePosture` (the |
| 12 | + * tenancy posture in force), with the one module helper only they use: |
| 13 | + * `accessibleOrganizationsOf`. |
| 14 | + * |
| 15 | + * A MOVE, not a redesign. Each exported function below is the body of the |
| 16 | + * `ObjectQL` method of the same name as it stood, re-indented one level and |
| 17 | + * otherwise unedited. Each method's docblock stays on the method in |
| 18 | + * `engine.ts`, which is still the contract. The helper moves with its |
| 19 | + * docblock, byte for byte, and is not exported. |
| 20 | + * |
| 21 | + * Nothing stays behind in this section: every member of it moved. |
| 22 | + * |
| 23 | + * ## The transaction seam's same-origin half (ADR-0119, ADR-0067) |
| 24 | + * |
| 25 | + * `buildDriverOptions` threads the open transaction handle only to the driver |
| 26 | + * that owns it (`transactionCoversDriverFor`, which stays in the class). The |
| 27 | + * ADR anchor entry for this file carries that half of the paragraph the |
| 28 | + * `engine.ts` entry carried; the `enforceTransactionOrigin` half stays there. |
| 29 | + * |
| 30 | + * ## How the moved bodies reach the class |
| 31 | + * |
| 32 | + * The shape #23050 set for `rest-server.ts`, applied per method as |
| 33 | + * `engine-file-reference-hydration.ts` applies it. The class keeps all six |
| 34 | + * methods with name, modifiers, signature, docblock and position, and each |
| 35 | + * body is one literal of exactly the {@link DriverOptionsHost} members that |
| 36 | + * method reads, plus a `.call`. The fields a body reads (`txStore`, |
| 37 | + * `_registry`, `tenancyPostureProvider`) go as GETTERS, so each read happens |
| 38 | + * when the body makes it, as it did. The methods they call |
| 39 | + * (`isClosedUnitHandle`, `transactionCoversDriverFor`, `driverWriteTarget`, |
| 40 | + * `driverReadScope`, `wallExemptedOperation`, `engineLayer0Verdict`, |
| 41 | + * `resolveEnginePosture`) go as late-bound closures over the instance, so a |
| 42 | + * double or spy set on the engine is still the one a call reaches. |
| 43 | + * |
| 44 | + * This module imports the engine only as a TYPE, so there is no module cycle |
| 45 | + * at run time, and nothing re-exports it, so the published surface does not |
| 46 | + * move. |
| 47 | + */ |
| 48 | + |
| 49 | +import { isTenancyDisabled } from '@objectstack/spec/data'; |
| 50 | +import type { ExecutionContext } from '@objectstack/spec/kernel'; |
| 51 | +import { |
| 52 | + // [ADR-0131 D8] The ONE tenant read predicate, shared with plugin-security's |
| 53 | + // Layer 0 — see {@link buildDriverOptions}. |
| 54 | + computeTenantLayer0Verdict, |
| 55 | +} from '@objectstack/core'; |
| 56 | +import { resolveTenantFieldName } from './tenancy/system-write-organization.js'; |
| 57 | +import { resolveTenancyPosture } from '@objectstack/types'; |
| 58 | +import { |
| 59 | + normalizeTenancyPosture, |
| 60 | + TenantLayer0VerdictSchema, |
| 61 | + type TenancyPosture, |
| 62 | + type TenantLayer0Verdict, |
| 63 | +} from '@objectstack/spec/security'; |
| 64 | +import { isFederatedObject } from './federated-object.js'; |
| 65 | +import type { ObjectQL } from './engine.js'; |
| 66 | + |
| 67 | +/** |
| 68 | + * The `ObjectQL` members the functions below read — every one of them, and no |
| 69 | + * other; each function's `this` is the `Pick` of the members IT reads. Each is |
| 70 | + * typed AS the class member (an indexed access on the class), so a change to a |
| 71 | + * member's type on the class is a change here too, and naming a member the |
| 72 | + * class does not have is a compile error. See the module header for which |
| 73 | + * members are getters. |
| 74 | + */ |
| 75 | +export interface DriverOptionsHost { |
| 76 | + readonly txStore: ObjectQL['txStore']; |
| 77 | + readonly _registry: ObjectQL['_registry']; |
| 78 | + readonly tenancyPostureProvider: ObjectQL['tenancyPostureProvider']; |
| 79 | + isClosedUnitHandle: ObjectQL['isClosedUnitHandle']; |
| 80 | + transactionCoversDriverFor: ObjectQL['transactionCoversDriverFor']; |
| 81 | + driverWriteTarget: ObjectQL['driverWriteTarget']; |
| 82 | + driverReadScope: ObjectQL['driverReadScope']; |
| 83 | + wallExemptedOperation: ObjectQL['wallExemptedOperation']; |
| 84 | + engineLayer0Verdict: ObjectQL['engineLayer0Verdict']; |
| 85 | + resolveEnginePosture: ObjectQL['resolveEnginePosture']; |
| 86 | +} |
| 87 | + |
| 88 | +/** |
| 89 | + * [ADR-0105 D2] The context's organization access set |
| 90 | + * (`ExecutionContext.accessible_org_ids`), stringified — `undefined` when |
| 91 | + * absent or empty, which the verdict reads as "no membership" under `group`. |
| 92 | + */ |
| 93 | +function accessibleOrganizationsOf(execCtx: ExecutionContext | undefined): string[] | undefined { |
| 94 | + const set = (execCtx as { accessible_org_ids?: unknown } | undefined)?.accessible_org_ids; |
| 95 | + return Array.isArray(set) && set.length > 0 ? set.map(String) : undefined; |
| 96 | +} |
| 97 | + |
| 98 | +/** The body of `ObjectQL#buildDriverOptions`; the method's docblock there is its contract. */ |
| 99 | +export function buildDriverOptions( |
| 100 | + this: Pick<DriverOptionsHost, 'isClosedUnitHandle' | 'txStore' | 'transactionCoversDriverFor' | '_registry' | 'driverWriteTarget' | 'driverReadScope' | 'wallExemptedOperation'>, |
| 101 | + object: string, |
| 102 | + execCtx?: ExecutionContext, |
| 103 | + base?: any, |
| 104 | + scope: { writeTarget?: boolean; recordedVerdict?: unknown } = {}, |
| 105 | +): any { |
| 106 | + // The open transaction may arrive explicitly via the context, or ambiently |
| 107 | + // via txStore when an internal query runs during a transactional write |
| 108 | + // (ADR-0034). Explicit wins; ambient is the safety net. [#22855] A handle |
| 109 | + // whose unit has closed is no handle: work the unit started and did not |
| 110 | + // await runs unenrolled (`runOpenedUnit`). |
| 111 | + const explicit = execCtx?.transaction; |
| 112 | + const tx = explicit !== undefined && !this.isClosedUnitHandle(explicit) |
| 113 | + ? explicit |
| 114 | + : this.txStore.getStore()?.transaction; |
| 115 | + // [#5351] SAME-ORIGIN GATE. A transaction handle is a property of ONE |
| 116 | + // driver's connection; handing it to a different driver does not put that |
| 117 | + // driver's statement inside the transaction, it executes the statement on |
| 118 | + // the WRONG CONNECTION — measured on knex/SQLite as `no such table` against |
| 119 | + // a database that never held the object. The write path's |
| 120 | + // `enforceTransactionOrigin` has already refused a business write by the |
| 121 | + // time we get here (and let a system ledger through by decision), so this |
| 122 | + // is the structural half: whatever survives to here, the handle only ever |
| 123 | + // reaches the driver that owns it. It covers READS too, which have no gate |
| 124 | + // of their own and were riding the same wrong connection. |
| 125 | + const hasTx = tx !== undefined && this.transactionCoversDriverFor(object, tx); |
| 126 | + const objectSchema = this._registry.getObject(object) as any; |
| 127 | + // `isFederatedObject` is the same predicate every schema-sync seam routes a |
| 128 | + // federated object by — one spelling of "this schema is the remote's", |
| 129 | + // not a second reading of it. |
| 130 | + const isFederated = isFederatedObject(objectSchema); |
| 131 | + const tenantObject = !isTenancyDisabled(objectSchema) && !isFederated; |
| 132 | + const tenantScope = tenantObject |
| 133 | + ? scope.writeTarget |
| 134 | + ? this.driverWriteTarget(execCtx) |
| 135 | + : this.driverReadScope(execCtx, scope.recordedVerdict) |
| 136 | + : undefined; |
| 137 | + const hasTenant = tenantScope !== undefined; |
| 138 | + const hasTz = execCtx?.timezone !== undefined; |
| 139 | + const isSystem = execCtx?.isSystem === true; |
| 140 | + // [ADR-0131 D9/D13] The tenant-audit's scope is the object's SCHEMA: a |
| 141 | + // tenant column (the registered schema's, as `resolveTenantFieldName` |
| 142 | + // reads it) on an object that is not federated. That is the same reading |
| 143 | + // the system-insert rule takes, and there is no second, per-table one — |
| 144 | + // the #13491 ledger that used to narrow this by name retired with D13. An |
| 145 | + // object is outside the audit only by declaring itself outside the |
| 146 | + // machinery (`tenancy.enabled: false`, `systemFields.tenant: false`, no |
| 147 | + // tenant field, `external`), which `scripts/platform-object-tenancy-census.json` |
| 148 | + // enumerates for the platform namespaces. |
| 149 | + const isTenantAuditInScope = |
| 150 | + resolveTenantFieldName(objectSchema) !== null && |
| 151 | + !isFederated; |
| 152 | + // [ADR-0131 D8 · 8c-1] The wall's exemption, declared to the driver. An |
| 153 | + // exempt platform admin's predicate write reaches the driver with no |
| 154 | + // `tenantId` because the wall lifted the scope on purpose, and the |
| 155 | + // driver's `[tenant-audit]` line tells such a write to declare |
| 156 | + // `bypassTenantAudit: true` — an option no REST caller can set. The |
| 157 | + // exemption is decided once, by `computeTenantLayer0Verdict`, and arrives |
| 158 | + // here as the recorded verdict; this reads it, it does not re-decide it |
| 159 | + // (see {@link wallExemptedOperation}). |
| 160 | + const wallExempt = |
| 161 | + tenantObject && isTenantAuditInScope && !scope.writeTarget && |
| 162 | + this.wallExemptedOperation(execCtx, scope.recordedVerdict); |
| 163 | + const preserveAudit = (execCtx as any)?.preserveAudit === true; |
| 164 | + if (!hasTx && !hasTenant && !isSystem && !hasTz && !preserveAudit && !wallExempt) return base; |
| 165 | + const opts: any = base && typeof base === 'object' ? { ...base } : {}; |
| 166 | + if (hasTx && opts.transaction === undefined) { |
| 167 | + opts.transaction = tx; |
| 168 | + } |
| 169 | + if (hasTenant && opts.tenantId === undefined) { |
| 170 | + opts.tenantId = tenantScope.tenantId; |
| 171 | + } |
| 172 | + if (hasTenant && opts.tenantIds === undefined && tenantScope.tenantIds !== undefined) { |
| 173 | + opts.tenantIds = tenantScope.tenantIds; |
| 174 | + } |
| 175 | + if (hasTz && opts.timezone === undefined) { |
| 176 | + // Thread the business timezone so date-dependent driver generation |
| 177 | + // (autonumber `{YYYYMMDD}` tokens) resolves the calendar day correctly. |
| 178 | + opts.timezone = execCtx!.timezone; |
| 179 | + } |
| 180 | + if (isSystem && opts.bypassTenantAudit === undefined && !isTenantAuditInScope) { |
| 181 | + // [#13491 → ADR-0131 D13] The isSystem mute, cut by the object's |
| 182 | + // schema alone (2026-08-31 ruling, execution point 1: the OBJECT decides, |
| 183 | + // never the caller's flag). |
| 184 | + // |
| 185 | + // It used to mute EVERY elevated write, whatever the object was. The |
| 186 | + // census cited in commit e49d98896's message measured what that cost: 135 of 175 write call sites |
| 187 | + // (77%) were silenced here — at the control's LARGEST gate, sitting |
| 188 | + // ahead of the condition the control is about — and the control has |
| 189 | + // never produced a finding, while all five known instances of the defect |
| 190 | + // were found by a person reading call sites. |
| 191 | + // |
| 192 | + // What still mutes: an object with no tenant field at all (nothing to be |
| 193 | + // unscoped from — the driver would exit at `resolveTenantField` anyway) |
| 194 | + // and a federated one. What does not: any object with a tenant column, |
| 195 | + // platform namespace or not — a name prefix, or a hand-kept list of |
| 196 | + // names, decides nothing here. A caller that means it still passes |
| 197 | + // `bypassTenantAudit: true` explicitly and is honoured above — this |
| 198 | + // branch only fills in a value nobody supplied. |
| 199 | + // |
| 200 | + // ⚠️ Direction, per execution point 3: what this ADDS is a driver WARN |
| 201 | + // line. It changes nothing about what any write touches. |
| 202 | + opts.bypassTenantAudit = true; |
| 203 | + } |
| 204 | + if (wallExempt && opts.bypassTenantAudit === undefined) { |
| 205 | + // The same fill-in-only rule as the isSystem mute above: a caller's own |
| 206 | + // value wins. Diagnostics only — the driver's scope is already the |
| 207 | + // verdict's (no `tenantId`), and this option silences a warning and |
| 208 | + // touches nothing else; on a read it is inert. |
| 209 | + opts.bypassTenantAudit = true; |
| 210 | + } |
| 211 | + if (preserveAudit && opts.preserveAudit === undefined) { |
| 212 | + // Historical import (#3493): let the driver keep a supplied `updated_at` |
| 213 | + // instead of force-stamping now on the update path. |
| 214 | + opts.preserveAudit = true; |
| 215 | + } |
| 216 | + return opts; |
| 217 | +} |
| 218 | + |
| 219 | +/** The body of `ObjectQL#driverReadScope`; the method's docblock there is its contract. */ |
| 220 | +export function driverReadScope( |
| 221 | + this: Pick<DriverOptionsHost, 'engineLayer0Verdict'>, |
| 222 | + execCtx: ExecutionContext | undefined, |
| 223 | + recordedVerdict: unknown, |
| 224 | +): { tenantId: string; tenantIds?: string[] } | undefined { |
| 225 | + const activeOrganization = |
| 226 | + execCtx?.tenantId !== undefined && execCtx.tenantId !== null && String(execCtx.tenantId) !== '' |
| 227 | + ? String(execCtx.tenantId) |
| 228 | + : undefined; |
| 229 | + const recorded = recordedVerdict === undefined ? undefined : TenantLayer0VerdictSchema.safeParse(recordedVerdict); |
| 230 | + const verdict = recorded?.success ? recorded.data : this.engineLayer0Verdict(execCtx, activeOrganization); |
| 231 | + switch (verdict.kind) { |
| 232 | + case 'none': |
| 233 | + return undefined; |
| 234 | + case 'organization': |
| 235 | + return { tenantId: verdict.organizationId }; |
| 236 | + case 'organizations': |
| 237 | + return { tenantId: activeOrganization ?? verdict.organizationIds[0], tenantIds: [...verdict.organizationIds] }; |
| 238 | + case 'deny': |
| 239 | + return activeOrganization !== undefined ? { tenantId: activeOrganization } : undefined; |
| 240 | + } |
| 241 | +} |
| 242 | + |
| 243 | +/** The body of `ObjectQL#engineLayer0Verdict`; the method's docblock there is its contract. */ |
| 244 | +export function engineLayer0Verdict( |
| 245 | + this: Pick<DriverOptionsHost, 'resolveEnginePosture'>, |
| 246 | + execCtx: ExecutionContext | undefined, |
| 247 | + activeOrganization: string | undefined, |
| 248 | +): TenantLayer0Verdict { |
| 249 | + return computeTenantLayer0Verdict({ |
| 250 | + tenancyPosture: this.resolveEnginePosture(), |
| 251 | + organizationId: activeOrganization, |
| 252 | + accessibleOrgIds: accessibleOrganizationsOf(execCtx), |
| 253 | + // Left to the driver, which resolves the tenant column from the |
| 254 | + // table it actually built (`resolveTenantField`): an object with no |
| 255 | + // such column is unscoped there whatever this says. `undefined` is |
| 256 | + // the verdict's "assume a tenant object", as Layer 0 reads an |
| 257 | + // unresolved field set. |
| 258 | + objectHasOrgIdField: undefined, |
| 259 | + tenancyDisabled: false, |
| 260 | + // The engine holds no permission sets: no exemption is ITS to grant. |
| 261 | + posturePermitsCrossTenant: false, |
| 262 | + isPlatformAdmin: false, |
| 263 | + }); |
| 264 | +} |
| 265 | + |
| 266 | +/** The body of `ObjectQL#wallExemptedOperation`; the method's docblock there is its contract. */ |
| 267 | +export function wallExemptedOperation( |
| 268 | + this: Pick<DriverOptionsHost, 'engineLayer0Verdict'>, |
| 269 | + execCtx: ExecutionContext | undefined, |
| 270 | + recordedVerdict: unknown, |
| 271 | +): boolean { |
| 272 | + if (recordedVerdict === undefined) return false; |
| 273 | + const recorded = TenantLayer0VerdictSchema.safeParse(recordedVerdict); |
| 274 | + if (!recorded.success || recorded.data.kind !== 'none') return false; |
| 275 | + const activeOrganization = |
| 276 | + execCtx?.tenantId !== undefined && execCtx.tenantId !== null && String(execCtx.tenantId) !== '' |
| 277 | + ? String(execCtx.tenantId) |
| 278 | + : undefined; |
| 279 | + return this.engineLayer0Verdict(execCtx, activeOrganization).kind !== 'none'; |
| 280 | +} |
| 281 | + |
| 282 | +/** The body of `ObjectQL#driverWriteTarget`; the method's docblock there is its contract. */ |
| 283 | +export function driverWriteTarget( |
| 284 | + this: Pick<DriverOptionsHost, 'resolveEnginePosture'>, |
| 285 | + execCtx: ExecutionContext | undefined, |
| 286 | +): { tenantId: string; tenantIds?: string[] } | undefined { |
| 287 | + if (execCtx?.tenantId === undefined) return undefined; |
| 288 | + const tenantIds = |
| 289 | + this.resolveEnginePosture() === 'group' ? accessibleOrganizationsOf(execCtx) : undefined; |
| 290 | + return { tenantId: execCtx.tenantId as string, ...(tenantIds ? { tenantIds: [...tenantIds] } : {}) }; |
| 291 | +} |
| 292 | + |
| 293 | +/** The body of `ObjectQL#resolveEnginePosture`; the method's docblock there is its contract. */ |
| 294 | +export function resolveEnginePosture( |
| 295 | + this: Pick<DriverOptionsHost, 'tenancyPostureProvider'>, |
| 296 | +): TenancyPosture { |
| 297 | + const injected = normalizeTenancyPosture(this.tenancyPostureProvider?.()); |
| 298 | + if (injected) return injected; |
| 299 | + try { |
| 300 | + return resolveTenancyPosture(); |
| 301 | + } catch { |
| 302 | + return 'isolated'; |
| 303 | + } |
| 304 | +} |
0 commit comments