|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#25522 cut 10] Two referential-integrity bodies of `ObjectQL`, moved out |
| 5 | + * of `engine.ts` whole: `assertReferencesResolve` (the write path's #4441 |
| 6 | + * reference check: a caller-supplied id in a reference field must name a row |
| 7 | + * of its target) and `masterDetailHeadersCallerReads` (#22519: which |
| 8 | + * master-detail headers the caller's own read door returns), with |
| 9 | + * `isEmptyReferenceValue`, the module helper only the first of them calls. |
| 10 | + * |
| 11 | + * A MOVE, not a redesign. Each exported function below is the body of the |
| 12 | + * `ObjectQL` method of the same name as it stood, re-indented one level and |
| 13 | + * otherwise unedited: the same system-caller exit, the same `readonly` and |
| 14 | + * caller-supplied skips, the same master-detail branch, the same one-`find` |
| 15 | + * read door and the same warning when that read fails. Each method's |
| 16 | + * docblock stays on the method in `engine.ts`, which is still the contract. |
| 17 | + * `isEmptyReferenceValue` moves with its docblock, byte for byte, and is not |
| 18 | + * exported. |
| 19 | + * |
| 20 | + * What stays in the class: `referenceExists`, `resolveMasterDetailParent` and |
| 21 | + * `resolveMasterDetailParents`, which read the private static |
| 22 | + * `referenceCheckContext` and hold an erased query-options site; the bodies |
| 23 | + * that call a module helper `engine.ts` still needs elsewhere |
| 24 | + * (`settleMasterDetailLanding`, `resolvePreviewParents`, |
| 25 | + * `resolvePredicateRelated`, `resolveOneHopRelated`); and |
| 26 | + * `masterDetailHeaderExists`, `materializeParentHeader` and |
| 27 | + * `masterDeclaredFields`, whose bodies are no longer than the host literal |
| 28 | + * moving them would cost. |
| 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-compatibility-api.ts` applies it. The class keeps both methods with |
| 34 | + * name, modifiers, signature, docblock and position, and each body is one |
| 35 | + * literal of exactly the {@link ReferentialIntegrityHost} members that method |
| 36 | + * reads, plus a `.call`. The one field a body reads (`logger`) goes as a |
| 37 | + * GETTER, so the read happens when the body makes it, as it did. The methods |
| 38 | + * they call (`find`, `masterDetailHeaderExists`, `referenceExists`) go as |
| 39 | + * late-bound closures over the instance, so a double or spy set on the engine |
| 40 | + * is still the one a call reaches. |
| 41 | + * |
| 42 | + * This module imports the engine only as a TYPE, so there is no module cycle |
| 43 | + * at run time, and nothing re-exports it, so the published surface does not |
| 44 | + * move. |
| 45 | + */ |
| 46 | + |
| 47 | +import { referenceTargetOf, type EngineQueryOptions } from '@objectstack/spec/data'; |
| 48 | +import type { ExecutionContext } from '@objectstack/spec/kernel'; |
| 49 | +import { ValidationError, buildFieldError } from './validation/record-validator.js'; |
| 50 | +import type { ObjectQL } from './engine.js'; |
| 51 | + |
| 52 | +/** |
| 53 | + * The `ObjectQL` members the functions below read — every one of them, and no |
| 54 | + * other; each function's `this` is the `Pick` of the members IT reads. Each is |
| 55 | + * typed AS the class member (an indexed access on the class), so a change to a |
| 56 | + * member's type on the class is a change here too, and naming a member the |
| 57 | + * class does not have is a compile error. See the module header for which |
| 58 | + * member is a getter. |
| 59 | + */ |
| 60 | +export interface ReferentialIntegrityHost { |
| 61 | + readonly logger: ObjectQL['logger']; |
| 62 | + find: ObjectQL['find']; |
| 63 | + masterDetailHeaderExists: ObjectQL['masterDetailHeaderExists']; |
| 64 | + referenceExists: ObjectQL['referenceExists']; |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * [#4441] "The caller did not name a record here." |
| 69 | + * |
| 70 | + * `null` / `undefined` / `''` mean NO LINK — exactly what |
| 71 | + * `deleteBehavior: 'set_null'` writes — and an empty array is the multi-value |
| 72 | + * spelling of the same thing. None of them is an id to resolve. |
| 73 | + */ |
| 74 | +function isEmptyReferenceValue(v: unknown): boolean { |
| 75 | + if (v === null || v === undefined || v === '') return true; |
| 76 | + if (Array.isArray(v)) return v.length === 0 || v.every((e) => e === null || e === undefined || e === ''); |
| 77 | + return false; |
| 78 | +} |
| 79 | + |
| 80 | +/** The body of `ObjectQL#assertReferencesResolve`; the method's docblock there is its contract. */ |
| 81 | +export async function assertReferencesResolve( |
| 82 | + this: Pick<ReferentialIntegrityHost, 'masterDetailHeaderExists' | 'referenceExists'>, |
| 83 | + schema: any, |
| 84 | + data: Record<string, unknown> | null | undefined, |
| 85 | + supplied: Record<string, unknown> | null | undefined, |
| 86 | + context: any, |
| 87 | + msgCtx?: { locale?: string; translate?: any; objectName?: string }, |
| 88 | +): Promise<void> { |
| 89 | + if (context?.isSystem) return; |
| 90 | + const fields = schema?.fields; |
| 91 | + if (!fields || !data) return; |
| 92 | + |
| 93 | + const failures: any[] = []; |
| 94 | + for (const name of Object.keys(fields)) { |
| 95 | + // [#4441, narrowing kept by #4743] A `readonly` field is never the |
| 96 | + // caller's to answer for — BY CONSTRUCTION, not by exemption. |
| 97 | + // |
| 98 | + // This check answers for exactly one thing: "the reference the CALLER |
| 99 | + // named". `stripReadonlyFields` removes a non-system caller's value from |
| 100 | + // a readonly field before the write — on BOTH write paths since #14147 |
| 101 | + // moved the create-side strip into this engine and deleted the boundary |
| 102 | + // copy it used to live in. So a value still sitting in one at |
| 103 | + // this point was minted by the PLATFORM — outside this check's own stated |
| 104 | + // scope, whatever it happens to hold. That argument stands on its own and |
| 105 | + // depends on no particular field: deleting the `continue` would start |
| 106 | + // rejecting the platform's own writes, which is why it is recorded here |
| 107 | + // (AGENTS.md PD #13) rather than left to be re-derived. |
| 108 | + // |
| 109 | + // Historical note, kept because it is how the narrowing was FOUND (the |
| 110 | + // dogfood gate, not reasoning) and because the audit next door re-scoped |
| 111 | + // itself on its removal: `sys_metadata_history.recorded_by` is a |
| 112 | + // `Field.lookup('sys_user', { readonly: true })` that the metadata |
| 113 | + // repository once filled with `actor ?? 'system'` — a SENTINEL STRING, |
| 114 | + // not a user id, on a write carrying no `isSystem`; checking it rejected |
| 115 | + // ordinary metadata authoring (package create / publish / clone). #4556 |
| 116 | + // replaced that sentinel with NULL, so no platform write puts a non-id in |
| 117 | + // a reference column any more. The narrowing survives it unchanged |
| 118 | + // because it never rested on it — but #4551's blanket audit skip did, and |
| 119 | + // #4743/#5719 duly re-scoped that one (see `inspectDanglingReferences`). |
| 120 | + // |
| 121 | + // This does NOT weaken #4441: the fields the issue names — |
| 122 | + // `sys_position_permission_set.permission_set_id` and |
| 123 | + // `showcase_task.project` — are ordinary author-facing lookups with no |
| 124 | + // `readonly`, and both stay enforced (pinned in the unit suite). |
| 125 | + if (fields[name]?.readonly === true) continue; |
| 126 | + // Only a value the CALLER actually supplied is theirs to answer for. |
| 127 | + // |
| 128 | + // Key presence is not enough: a form serializes an unpicked control as |
| 129 | + // an explicit `null`, and `applyFieldDefaults` then fills it from |
| 130 | + // `defaultValue` — including the `current_user` token (#2706). The key is |
| 131 | + // in the payload, but the ID that lands is the PLATFORM's, so validating |
| 132 | + // it would report a server-derived value as the caller's bad reference |
| 133 | + // (and reject a perfectly ordinary insert against a driver that has no |
| 134 | + // `sys_user` row for the acting principal). |
| 135 | + // |
| 136 | + // So the value read for the check comes from the post-normalization |
| 137 | + // `data` (multi-value strings are already split by then), while WHETHER |
| 138 | + // to check is decided by the caller's own raw value being non-empty. |
| 139 | + if (!supplied || isEmptyReferenceValue((supplied as Record<string, unknown>)[name])) continue; |
| 140 | + if (!(name in data)) continue; |
| 141 | + const def = fields[name]; |
| 142 | + const target = referenceTargetOf(def); |
| 143 | + if (!target) continue; |
| 144 | + const raw = (data as Record<string, unknown>)[name]; |
| 145 | + const values = Array.isArray(raw) ? raw : [raw]; |
| 146 | + for (const v of values) { |
| 147 | + if (v === null || v === undefined || v === '') continue; |
| 148 | + if (typeof v === 'object') continue; |
| 149 | + // [#22519] A master-detail header must also be one the caller can read. |
| 150 | + const resolved = def?.type === 'master_detail' |
| 151 | + ? await this.masterDetailHeaderExists(target, v, context) |
| 152 | + : await this.referenceExists(target, v, context); |
| 153 | + if (resolved === false) { |
| 154 | + failures.push(buildFieldError( |
| 155 | + { |
| 156 | + field: name, |
| 157 | + code: 'reference_not_found', |
| 158 | + def, |
| 159 | + value: String(v), |
| 160 | + constraint: { target }, |
| 161 | + }, |
| 162 | + msgCtx as any, |
| 163 | + )); |
| 164 | + } |
| 165 | + } |
| 166 | + } |
| 167 | + if (failures.length > 0) throw new ValidationError(failures); |
| 168 | +} |
| 169 | + |
| 170 | +/** The body of `ObjectQL#masterDetailHeadersCallerReads`; the method's docblock there is its contract. */ |
| 171 | +export async function masterDetailHeadersCallerReads( |
| 172 | + this: Pick<ReferentialIntegrityHost, 'find' | 'logger'>, |
| 173 | + master: string, |
| 174 | + ids: ReadonlyArray<unknown>, |
| 175 | + context: ExecutionContext | undefined, |
| 176 | +): Promise<ReadonlySet<string>> { |
| 177 | + const asked = new Map<string, unknown>(); |
| 178 | + for (const id of ids) if (id != null) asked.set(String(id), id); |
| 179 | + if (context?.isSystem || asked.size === 0) return new Set(asked.keys()); |
| 180 | + // One id is asked by equality, the predicate shape the elevated probe |
| 181 | + // already sends; a batch by `$in`, as read 2 of the batch reads it. |
| 182 | + const values = [...asked.values()]; |
| 183 | + try { |
| 184 | + const rows = await this.find(master, { |
| 185 | + where: { id: values.length === 1 ? values[0] : { $in: values } }, |
| 186 | + fields: ['id'], |
| 187 | + context, |
| 188 | + } as EngineQueryOptions) as Array<Record<string, unknown>>; |
| 189 | + const served = new Set<string>(); |
| 190 | + for (const row of Array.isArray(rows) ? rows : []) { |
| 191 | + if (row?.id != null && asked.has(String(row.id))) served.add(String(row.id)); |
| 192 | + } |
| 193 | + return served; |
| 194 | + } catch (err) { |
| 195 | + this.logger?.warn?.('the caller\'s read of the master-detail header failed — the header binds as a missing header', { |
| 196 | + object: master, error: err, |
| 197 | + }); |
| 198 | + return new Set(); |
| 199 | + } |
| 200 | +} |
0 commit comments