Repository navigation
Expand file tree
/
Copy pathsql-driver-internal-helpers.ts
More file actions
194 lines (183 loc) · 11.2 KB
/
Copy pathsql-driver-internal-helpers.ts
File metadata and controls
194 lines (183 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [#29520 codemod] The "Internal helpers" section of `SqlDriver`: the bodies of
* `getKnex`, `getBuilder`, `resolveTenantField`, `isMultiTenantMode`,
* `applyTenantScope`, `readableIdsSubquery`, `injectTenantOnInsert`,
* `auditMissingTenant` moved out of `sql-driver.ts` whole (split
* by #29598 and #30249).
*
* A MOVE, not a redesign. {@link InternalHelpersFacet} is a stateless facet of `SqlDriver`
* (ruling 6624345766): each static method of it is the body of the `SqlDriver`
* method of the same name exactly as it stood: not re-indented, not
* formatted, not edited. The method stays on the class as a one-call stub with
* its signature, so the published surface, an instance spy and a subclass
* override are what they were. A public or protected method keeps its
* docblock on the class, the contract; a private method's docblock moved here
* with its body. The state stays on `SqlDriver`.
*
* The bodies reach the class through {@link InternalHelpersHost}: exactly the
* `SqlDriver` members they read, private ones included. Every stub hands its
* body, by a `.call`, the same host: `internalHelpersHost` in
* `sql-driver-facet-hosts.ts`, built once per driver by the class's static
* block. Methods go as closures that call them on the driver at call time, so a
* subclass override or an instance spy is still the one reached; fields and
* accessors go as GETTERS, read when the body reads them, as they were on the
* class, and a field a body assigns goes with a SETTER that assigns it on the
* driver.
*
* The module imports `sql-driver.ts` for types only, so the two modules form no
* evaluation cycle. `index.ts` re-exports nothing from this module.
*/
import type { ComposedReadableIds, DriverOptions } from '@objectstack/spec/data';
import { StorageNameMapping } from '@objectstack/spec/system';
import { resolveTenancyPosture } from '@objectstack/types';
import { postureEnforcesWall } from '@objectstack/spec/security';
import type { Knex } from 'knex';
import type { SqlDriver } from './sql-driver.js';
/**
* The `SqlDriver` members the bodies of {@link InternalHelpersFacet} read — every one of
* them, and no other. Each is typed AS the class member (an indexed access on
* the class), so a change to a member's signature on the class is a change
* here too. `readonly` members are the getters; the others are fields a body
* assigns.
*/
export interface InternalHelpersHost {
applyFilters: SqlDriver['applyFilters'];
applyTenantScope: SqlDriver['applyTenantScope'];
getBuilder: SqlDriver['getBuilder'];
isMultiTenantMode: SqlDriver['isMultiTenantMode'];
readonly knex: SqlDriver['knex'];
readonly logger: SqlDriver['logger'];
readonly physicalSchemaByObject: SqlDriver['physicalSchemaByObject'];
readonly physicalTableByObject: SqlDriver['physicalTableByObject'];
remoteColumn: SqlDriver['remoteColumn'];
resolveTenantField: SqlDriver['resolveTenantField'];
readonly tenantAuditWarned: SqlDriver['tenantAuditWarned'];
readonly tenantFieldByTable: SqlDriver['tenantFieldByTable'];
}
/** The bodies of the "Internal helpers" section of `SqlDriver`: a stateless facet, called by the class's stubs. */
export class InternalHelpersFacet {
/** The body of `SqlDriver#getKnex`; the method's docblock there is its contract. */
static getKnex(this: Pick<InternalHelpersHost, 'knex'>): Knex {
return this.knex;
}
/** The body of `SqlDriver#getBuilder`; the method's docblock there is its contract. */
static getBuilder(this: Pick<InternalHelpersHost, 'knex' | 'physicalSchemaByObject' | 'physicalTableByObject'>, object: string, options?: DriverOptions) {
// Federation (ADR-0015): an external object resolves to its remote table
// (`external.remoteName`, optionally schema-qualified). Managed objects miss
// both maps, so this is `this.knex(object)` — unchanged. `.withSchema()` is
// applied on the builder (not via `knex.withSchema().from()`) so the builder
// type is identical to the managed path for every downstream caller.
const physical = this.physicalTableByObject[object] ?? object;
let builder = this.knex(physical);
const remoteSchema = this.physicalSchemaByObject[object];
if (remoteSchema) {
builder = builder.withSchema(remoteSchema);
}
if (options?.transaction) {
builder = builder.transacting(options.transaction as Knex.Transaction);
}
return builder;
}
/** The body of `SqlDriver#resolveTenantField`; the method's docblock there is its contract. */
static resolveTenantField(this: Pick<InternalHelpersHost, 'tenantFieldByTable'>, object: string): string | null {
const tableName = StorageNameMapping.resolveTableName({ name: object } as any);
const cached =
this.tenantFieldByTable[tableName] ?? this.tenantFieldByTable[object];
return cached ?? null;
}
/** The body of `SqlDriver#isMultiTenantMode`; the method's docblock there is its contract. */
static isMultiTenantMode(): boolean {
return postureEnforcesWall(resolveTenancyPosture());
}
/** The body of `SqlDriver#applyTenantScope`; the method's docblock there is its contract. */
static applyTenantScope(this: Pick<InternalHelpersHost, 'resolveTenantField'>, builder: Knex.QueryBuilder, object: string, options?: DriverOptions): Knex.QueryBuilder {
const tenantId = options?.tenantId;
if (tenantId === undefined || tenantId === null || tenantId === '') return builder;
const field = this.resolveTenantField(object);
if (!field) return builder;
// [ADR-0105 D2 / #3623] Union tenant scope: under the `group` posture the
// engine threads the caller's whole membership set as `tenantIds`, and the
// native wall widens to `IN (...)` — the SAME union the Layer 0
// authorization wall enforces above. Equality here would AND under that
// union and collapse group reads to active-org reach. A malformed or
// empty set falls through to the equality path: fail toward isolation,
// never toward exposure. Insert-side injection (injectTenantOnInsert)
// deliberately keeps `tenantId` — the active org is the write target (D5).
const rawIds = options?.tenantIds;
const tenantIds = Array.isArray(rawIds)
? rawIds.filter((v: unknown) => typeof v === 'string' && v !== '')
: [];
if (tenantIds.length > 0) {
return builder.whereIn(field, tenantIds.map(String));
}
// `field = :tenantId`, and nothing else. [ADR-0131 D1, D14] NULL is not an
// owner: an organization-less row is no tenant's, so no tenant scope reaches
// it. The v17 reading (#2734) added an `OR field IS NULL` arm here, under
// which such a row stood for platform state; ADR-0131 replaced that reading
// (D2, D6, D7) and the 18.x upgrade ceremony retired the rows it served: a
// certified database holds no NULL organization, a fresh install never
// writes one, and a v17 database is refused at boot until it is certified.
// A composition that registers no organization object can still write
// organization-less rows, and it never reaches this line with a tenant: no
// session, guest or system write there carries an organization.
return builder.where(field, String(tenantId));
}
/** The body of `SqlDriver#readableIdsSubquery`; the method's docblock there is its contract. */
static readableIdsSubquery(this: Pick<InternalHelpersHost, 'applyFilters' | 'applyTenantScope' | 'getBuilder' | 'remoteColumn'>, leaf: ComposedReadableIds, options?: DriverOptions): Knex.QueryBuilder {
const parent = leaf.object;
const sub = this.getBuilder(parent).select(this.remoteColumn(parent, 'id', 'id'));
this.applyTenantScope(sub, parent, options);
if (leaf.scope !== undefined) this.applyFilters(sub, leaf.scope, options);
return sub;
}
/** The body of `SqlDriver#injectTenantOnInsert`; the method's docblock there is its contract. */
static injectTenantOnInsert(this: Pick<InternalHelpersHost, 'resolveTenantField'>, object: string, row: Record<string, any>, options?: DriverOptions): void {
const tenantId = options?.tenantId;
if (tenantId === undefined || tenantId === null || tenantId === '') return;
const field = this.resolveTenantField(object);
if (!field) return;
if (row[field] === undefined || row[field] === null || row[field] === '') {
row[field] = String(tenantId);
}
}
/** The body of `SqlDriver#auditMissingTenant`; the method's docblock there is its contract. */
static auditMissingTenant(this: Pick<InternalHelpersHost, 'isMultiTenantMode' | 'logger' | 'resolveTenantField' | 'tenantAuditWarned'>, object: string, op: 'create' | 'update' | 'delete' | 'bulkCreate' | 'bulkDelete' | 'updateMany' | 'deleteMany' | 'upsert', options?: DriverOptions, insertRows?: readonly unknown[]): void {
if (process.env.OS_TENANT_AUDIT === '0') return;
if (options?.bypassTenantAudit === true) return;
// A write that DID carry its tenant is the case this audit has nothing to
// say about, and it is the overwhelmingly common one — so it exits here,
// before the posture read below. Ordering only (both guards are pure
// predicates over independent facts); it is what makes `isMultiTenantMode()`
// affordable as a live read now that it no longer memoises (#5262).
const tenantId = options?.tenantId;
if (tenantId !== undefined && tenantId !== null && tenantId !== '') return;
// Only meaningful in multi-tenant deployments. Single-tenant stacks have no
// tenant isolation, yet the kernel now ALWAYS provisions an `organization_id`
// column (its existence is decoupled from the tenant flag). Column presence
// alone therefore no longer implies "tenant-scoped" — without this gate every
// system/sudo write (e.g. the notification/http delivery dispatchers' claim
// updates) would spam a meaningless warning on single-tenant boots.
if (!this.isMultiTenantMode()) return;
const field = this.resolveTenantField(object);
if (!field) return;
// Empty is spelled as `injectTenantOnInsert` spells it: a row it would
// stamp is a row that does not carry its organization.
const carriesTenant = (row: unknown): boolean => {
const value = row && typeof row === 'object' ? (row as Record<string, unknown>)[field] : undefined;
return value !== undefined && value !== null && value !== '';
};
if (insertRows !== undefined && insertRows.length > 0 && insertRows.every(carriesTenant)) return;
const key = `${object}:${op}`;
if (this.tenantAuditWarned.has(key)) return;
this.tenantAuditWarned.add(key);
this.logger.warn(
`[tenant-audit] ${op} on tenant-scoped object "${object}" without options.tenantId — the statement is not confined to one organization. `
+ 'If the write belongs to one organization, run it in that organization\'s context (an ExecutionContext carrying its organization); '
+ 'the row\'s own organization column does not scope an update or a delete. '
+ 'If it crosses organizations on purpose (a platform admin the organization wall exempts, or a system job over every organization), '
+ 'nothing needs fixing: the caller declares it with bypassTenantAudit:true, which also silences this line.',
{ object, op, tenantField: field },
);
}
}