diff --git a/.changeset/35812-org-delete-removes-units.md b/.changeset/35812-org-delete-removes-units.md new file mode 100644 index 00000000000..d20683ba8cf --- /dev/null +++ b/.changeset/35812-org-delete-removes-units.md @@ -0,0 +1,14 @@ +--- +'@objectstack/objectql': patch +'@objectstack/platform-objects': patch +'@objectstack/plugin-security': patch +--- + +fix(objectql): deleting an organization also deletes its units of measure, the one exemption from the `sys_unit` delete refusal + +Clause-②: yes (widening) +Metadata-protocol: none + +An organization that had ever created a unit of measure could not be deleted: the delete was refused with 409 `DELETE_RESTRICTED` naming `sys_unit`, and the units could not be removed first, because the engine refuses every delete of a unit (405 `ERR_UNIT_DELETE_REFUSED`). Now the organization delete's own cascade removes that organization's `sys_unit` rows, retired ones included, through the engine's delete path, after the delete has been admitted, so no unit row is left naming a deleted organization. `organizationOwnedRowCounts` (the question plugin-auth's organization delete asks first) and the engine's own refusal no longer count units as records the organization still owns. + +**Declared behaviour change.** A delete door widens, in one place only. A delete of an organization that holds units and no other record now succeeds and removes the units; before, it was refused. An organization that owns any other record is still refused, and none of its units is removed. Every other delete of a unit is still refused with 405 `ERR_UNIT_DELETE_REFUSED`, by id and batched, for a user, a system writer and an automation run, including a delete issued by a hook while the organization's delete is running: the exemption is recognised from the engine's own cascade, never from anything a caller passes. Retire a unit (`retired: true`) to stop its use, as before. diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index d941938d7c4..327c435f887 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -56,6 +56,7 @@ import { } from './engine-top-level.js'; import type { ReferentialClearOption } from './engine-top-level.js'; import { isExternalDriverFloor } from './external-driver-floor.js'; +import { ORGANIZATION_UNIT_OBJECT } from './validation/unit-code-membership.js'; import { forgetCollectedProbes, takeCollectedProbe } from './engine-delete-cascade.js'; import type { CascadeDeleteSet } from './engine-top-level.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; @@ -1213,6 +1214,13 @@ export class CascadePlanningFacet { } } } + // [ruling 7035627429, option B] An organization's delete removes its units, + // the one exemption from the `sys_unit` delete refusal. Last, once + // `refuseOrganizationDeleteWhileOwned` above has admitted the delete and + // every relation has been judged, so a refused delete removes no unit. + if (object === ORGANIZATION_OBJECT) { + for (const id of ids) await removeOrganizationUnits(this, id, context, objects, cascadeSet); + } } /** @@ -1348,7 +1356,9 @@ export class CascadePlanningFacet { /** * [#24948] The engine half of organization delete: refuse while any row * outside the cascade set still names the organization in its tenant column, - * a row that outlives the organization excepted ({@link outlivesOrganization}). + * a row that outlives the organization excepted ({@link outlivesOrganization}), + * and so is a unit of measure, which the walk removes with the organization + * once this admits the delete (`removeOrganizationUnits`). * * Runs before the walk touches the first relation, and reads every tenant * relation before it throws, so the one refusal names every table that holds @@ -1373,6 +1383,9 @@ export class CascadePlanningFacet { const fields = (child as any)?.fields as Record | undefined; // An append-only or engine-owned object's rows outlive the organization: not counted, kept as they are. if (!childName || !fields || ObjectQL.outlivesOrganization(child)) continue; + // [ruling 7035627429, option B] The organization's units are not counted: + // the walk removes them with it (`removeOrganizationUnits`). + if (childName === ORGANIZATION_UNIT_OBJECT) continue; for (const [fieldName, fdef] of Object.entries(fields)) { const behavior = this.cascadeRelationBehavior(ORGANIZATION_OBJECT, child, fieldName, fdef); if (!this.isTenantColumnSetNull(ORGANIZATION_OBJECT, child, fieldName, behavior)) continue; @@ -1415,6 +1428,8 @@ export class CascadePlanningFacet { const childName = (child as any)?.name as string | undefined; const fields = (child as any)?.fields as Record | undefined; if (!childName || !fields || exclude.has(childName) || ObjectQL.outlivesOrganization(child)) continue; + // [ruling 7035627429, option B] The organization's units go with its delete, as in the engine's refusal. + if (childName === ORGANIZATION_UNIT_OBJECT) continue; const tenantField = resolveTenantFieldName(child); if (!tenantField || !fields[tenantField]) continue; const fdef = fields[tenantField]; @@ -1517,6 +1532,79 @@ async function deleteCascadedChildren(host: Pick(); + +/** + * [ruling 7035627429, option B] Is `token`, the cascade token a `delete()` has + * just claimed, one an organization's delete issued to remove one of its + * units? The one exemption from `refuseOrganizationUnitDelete` + * (`validation/unit-code-membership.ts`): `delete()` asks it only for the token + * it claimed itself, so the answer reaches that one delete and no other. + */ +export function isOrganizationUnitRemoval(token: unknown): boolean { + return typeof token === 'object' && token !== null && organizationUnitRemovals.has(token); +} + +/** + * [ruling 7035627429, option B; ADR-0158 Open item 11] Remove the units of + * the organization `organizationId`, whose delete {@link + * CascadePlanningFacet.walkReferencingRelations} has admitted: a deleted + * organization can never create a code again, so its units, retired ones + * included, go with it and no `sys_unit` row is left naming it. + * + * The organization is named explicitly, twice, as the unit-code membership + * read names it (`organizationUnitRowsOf`): the read's predicate on the tenant + * column, and the `tenantId` of the context both the read and the deletes run + * under. That context is `sudo()`-shaped ({@link + * CascadePlanningFacet.referenceCheckContext}): the caller's transaction and + * user ride along, so the deletes join the organization delete's unit of work + * and the audit ledger records who triggered them, and system identity + * authorizes them, because no permission set grants a unit delete to anyone. + * The read is filed as a reference-check elevation, as the refusal's counts + * are. + * + * Each unit goes through the public `delete()` by id, inside a cascade token + * naming exactly that unit (as {@link deleteCascadedChildren} issues one per + * child), so its hooks run with `referentialCascadeDelete` set and its audit + * and events are a cascade child's. The token is recorded in + * {@link organizationUnitRemovals}, which is what admits the delete past the + * `sys_unit` refusal; a delete that does not claim it (a hook's own, another + * request's) is refused. A table never provisioned holds no unit. + */ +async function removeOrganizationUnits(host: Pick, organizationId: string | number, context: ExecutionContext | undefined, objects: ServiceObject[], cascadeSet: CascadeDeleteSet): Promise { + const unit = objects.find((o) => (o as { name?: unknown })?.name === ORGANIZATION_UNIT_OBJECT); + const tenantField = unit ? resolveTenantFieldName(unit) : null; + if (!unit || !tenantField) return; + host.fileReferenceCheckElevation(cascadeSet, ORGANIZATION_OBJECT, organizationId, ORGANIZATION_UNIT_OBJECT, tenantField, context); + const unitContext = { ...ObjectQL.referenceCheckContext(context), tenantId: String(organizationId) } as ExecutionContext; + let rows: unknown; + try { + rows = await host.find(ORGANIZATION_UNIT_OBJECT, { + where: { [tenantField]: organizationId }, + fields: ['id'], + context: unitContext, + }); + } catch (error) { + if (isMissingTableError(error, ORGANIZATION_UNIT_OBJECT)) return; + throw error; + } + for (const row of Array.isArray(rows) ? (rows as Array<{ id?: unknown }>) : []) { + const token = { object: ORGANIZATION_UNIT_OBJECT, id: String(row.id), claimed: false }; + organizationUnitRemovals.add(token); + await host.cascadeIssuedDeletes.run( + token, + () => host.delete(ORGANIZATION_UNIT_OBJECT, { where: { id: row.id }, context: unitContext } as any), + ); + } +} + /** * [ruling 6893104201 point 2] Does the caller's READ door return every child * of the chunk? Asked through the public `find()` under the walk's context, diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index ce9f53eb4ff..7aa8458e0e6 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -97,6 +97,7 @@ import { import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { ObjectQL as ObjectQLClass } from './engine.js'; import { refuseOrganizationUnitDelete } from './validation/unit-code-membership.js'; +import { isOrganizationUnitRemoval } from './engine-cascade-planning.js'; /** * The `ObjectQL` members the bodies of {@link DeleteAndAggregateFacet} read — every one of @@ -116,6 +117,7 @@ export interface DeleteAndAggregateHost { buildSession: ObjectQLClass['buildSession']; buildUser: ObjectQLClass['buildUser']; cascadeDeleteRelations: ObjectQLClass['cascadeDeleteRelations']; + readonly cascadeIssuedDeletes: ObjectQLClass['cascadeIssuedDeletes']; claimReferentialCascadeDelete: ObjectQLClass['claimReferentialCascadeDelete']; composeReadableIdsAtBoundary: ObjectQLClass['composeReadableIdsAtBoundary']; delete: ObjectQLClass['delete']; @@ -155,7 +157,7 @@ export interface DeleteAndAggregateHost { /** The bodies of the "Delete, count, aggregate and execute" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ export class DeleteAndAggregateFacet { /** The body of `ObjectQL#delete`; the method's docblock there is its contract. */ - static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { + static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. @@ -170,10 +172,6 @@ export class DeleteAndAggregateFacet { ownUnit ? () => this.inAfterAbortUnit(body) : body; this.logger.debug('Delete operation starting', { object }); this.assertWriteAllowed(object, 'delete'); - // [ADR-0158 Open item 11] A unit of measure is retired, never deleted: - // refused here, before any middleware or hook, so the refusal holds for a - // system writer and an automation run as for a user, single and batched. - refuseOrganizationUnitDelete(object); // [#8844] See the insert face — deleting the install's only organization // must not leave the memo answering with it. if (object === ORGANIZATION_OBJECT) this.invalidateOrganizationProbe(); @@ -223,6 +221,16 @@ export class DeleteAndAggregateFacet { // [ruling 6893661036, F1] A predicate delete hands its `where` instead: a // cascade batch is claimed by the exact id set it names. const referentialCascadeDelete = this.claimReferentialCascadeDelete(object, id ?? options?.where); + // [ADR-0158 Open item 11] A unit of measure is retired, never deleted on its + // own: refused here, before any middleware or hook, so the refusal holds for + // a system writer and an automation run as for a user, single and batched. + // [ruling 7035627429, option B] The one exemption is the organization + // delete's own removal of its units, recognised by the cascade token THIS + // call just claimed, never by anything the caller hands in. + refuseOrganizationUnitDelete( + object, + referentialCascadeDelete === true && isOrganizationUnitRemoval(this.cascadeIssuedDeletes.getStore()), + ); const opCtx: OperationContext = { object, diff --git a/packages/objectql/src/engine-organization-delete-refusal.test.ts b/packages/objectql/src/engine-organization-delete-refusal.test.ts index b00ecacd679..ab83e5f4a2e 100644 --- a/packages/objectql/src/engine-organization-delete-refusal.test.ts +++ b/packages/objectql/src/engine-organization-delete-refusal.test.ts @@ -494,3 +494,122 @@ describe('[#24948] organizationOwnedRowCounts: the question plugin-auth asks bef expect(await engine.organizationOwnedRowCounts(ORG_ID)).toEqual([]); }); }); + +/** An organization's units of measure (`sys_unit`, platform-objects'): the registry injects the tenant column. */ +const UNIT = { + name: 'sys_unit', + label: 'Unit of Measure', + fields: { + code: { name: 'code', label: 'Code', type: 'text' as const }, + retired: { name: 'retired', label: 'Retired', type: 'boolean' as const }, + }, +}; + +describe('[ruling 7035627429, option B] an organization delete removes its units, the one exemption from the sys_unit delete refusal', () => { + type Thrown = { code?: string; status?: number } | null; + const envelope = (e: Thrown) => e && { code: e.code, status: e.status }; + const refusalOf = (p: Promise): Promise => p.then(() => null, (e) => e as Thrown); + const REFUSED = { code: 'ERR_UNIT_DELETE_REFUSED', status: 405 }; + const seedUnits = (store: ReturnType) => { + store.seed('sys_unit', { id: 'u1', code: 'JIN1', retired: false, organization_id: ORG_ID }); + store.seed('sys_unit', { id: 'u2', code: 'SACK_50', retired: true, organization_id: ORG_ID }); + store.seed('sys_unit', { id: 'u3', code: 'TAEL_1', retired: false, organization_id: OTHER_ORG }); + }; + /** The callers a direct delete is refused for: a user, a system writer and a system automation run. */ + const CALLERS: Array<[string, Record]> = [ + ['a user', { userId: 'u_admin', tenantId: ORG_ID }], + ['a system writer', { isSystem: true, tenantId: ORG_ID }], + ['a system automation run', { isSystem: true, actor: 'svc:flow:units_cleanup', tenantId: ORG_ID }], + ]; + + it('deletes an organization whose only rows are its units, removing every one, retired included; another organization\'s unit stays', async () => { + const { engine, store } = await makeEngine([ORGANIZATION, ACCOUNT, UNIT]); + seedUnits(store); + const marked: unknown[] = []; + engine.registerHook('beforeDelete', async (ctx: any) => { marked.push(ctx.referentialCascadeDelete); }, { object: 'sys_unit' }); + + expect(await deleteOrg(engine)).toBeNull(); + + expect(store.rows('sys_organization').map((r) => r.id)).toEqual([OTHER_ORG]); + expect(store.rows('sys_unit').map((r) => [r.id, r.organization_id])).toEqual([['u3', OTHER_ORG]]); + // Each unit through the engine's delete, as a cascade child: its hooks carry the marker. + expect(store.writes).toEqual(['delete sys_unit/u1', 'delete sys_unit/u2', `delete sys_organization/${ORG_ID}`]); + expect(marked).toEqual([true, true]); + }); + + it('still refuses an organization that owns another record: 409 DELETE_RESTRICTED naming only that record, every unit kept', async () => { + const { engine, store } = await makeEngine([ORGANIZATION, ACCOUNT, UNIT]); + seedUnits(store); + store.seed('acct', { id: 'a1', organization_id: ORG_ID }); + + const err: any = await deleteOrg(engine); + + expect(envelope(err)).toEqual({ code: 'DELETE_RESTRICTED', status: 409 }); + expect(err?.dependents).toEqual([{ object: 'acct', count: 1 }]); + expect(store.writes).toEqual([]); + expect(store.rows('sys_unit').map((r) => r.id)).toEqual(['u1', 'u2', 'u3']); + expect(store.rows('sys_organization').map((r) => r.id)).toEqual([ORG_ID, OTHER_ORG]); + }); + + it('organizationOwnedRowCounts does not count units, and counts the record beside them', async () => { + const { engine, store } = await makeEngine([ORGANIZATION, ACCOUNT, UNIT]); + seedUnits(store); + expect(await engine.organizationOwnedRowCounts(ORG_ID)).toEqual([]); + store.seed('acct', { id: 'a1', organization_id: ORG_ID }); + expect(await engine.organizationOwnedRowCounts(ORG_ID)).toEqual([{ object: 'acct', count: 1 }]); + }); + + it.each(CALLERS)('refuses a direct delete of a unit by %s, by id and batched, nothing removed', async (_who, context) => { + const { engine, store } = await makeEngine([ORGANIZATION, UNIT]); + seedUnits(store); + expect(envelope(await refusalOf(engine.delete('sys_unit', { where: { id: 'u1' }, context } as any)))).toEqual(REFUSED); + expect(envelope(await refusalOf(engine.delete('sys_unit', { where: { id: { $in: ['u1', 'u2'] } }, multi: true, context } as any)))).toEqual(REFUSED); + expect(store.writes).toEqual([]); + }); + + it('refuses a delete inside a cascade token the organization delete did not issue', async () => { + const { engine, store } = await makeEngine([ORGANIZATION, UNIT]); + seedUnits(store); + // The engine's own token store, reached around its `private`: a generic + // cascade token for exactly this unit is not the organization's removal. + const issued = (engine as any).cascadeIssuedDeletes; + const forged = await refusalOf(issued.run( + { object: 'sys_unit', id: 'u1', claimed: false }, + () => engine.delete('sys_unit', { where: { id: 'u1' }, context: { isSystem: true, tenantId: ORG_ID } } as any), + )); + expect(envelope(forged)).toEqual(REFUSED); + expect(store.rows('sys_unit').map((r) => r.id)).toEqual(['u1', 'u2', 'u3']); + }); + + it('refuses every direct delete of a unit while its organization\'s delete is in flight, and the delete still removes them all', async () => { + const { engine, store } = await makeEngine([ORGANIZATION, UNIT]); + seedUnits(store); + const seen: Array<[string, Thrown]> = []; + const attempt = async (label: string, run: () => Promise) => { seen.push([label, await refusalOf(run())]); }; + // Before the walk: the organization's own hook, under each caller. + engine.registerHook('beforeDelete', async () => { + for (const [who, context] of CALLERS) { + await attempt(`org hook, ${who}, by id`, () => engine.delete('sys_unit', { where: { id: 'u1' }, context } as any)); + await attempt(`org hook, ${who}, batched`, () => engine.delete('sys_unit', { where: { id: { $in: ['u1', 'u2'] } }, multi: true, context } as any)); + } + }, { object: 'sys_organization' }); + // Inside the removal of a unit: that unit's own hook, on its sibling and on itself (once: a + // delete the refusal let through would re-enter this hook). + let entered = false; + engine.registerHook('beforeDelete', async (ctx: any) => { + if (ctx.input?.id !== 'u1' || entered) return; + entered = true; + const context = { isSystem: true, tenantId: ORG_ID }; + await attempt('unit hook, sibling by id', () => engine.delete('sys_unit', { where: { id: 'u2' }, context } as any)); + await attempt('unit hook, itself by id', () => engine.delete('sys_unit', { where: { id: 'u1' }, context } as any)); + await attempt('unit hook, batched', () => engine.delete('sys_unit', { where: { id: { $in: ['u2'] } }, multi: true, context } as any)); + }, { object: 'sys_unit' }); + + expect(await deleteOrg(engine)).toBeNull(); + + expect(seen).toHaveLength(9); + for (const [label, thrown] of seen) expect(envelope(thrown), label).toEqual(REFUSED); + expect(store.writes).toEqual(['delete sys_unit/u1', 'delete sys_unit/u2', `delete sys_organization/${ORG_ID}`]); + expect(store.rows('sys_unit').map((r) => r.id)).toEqual(['u3']); + }); +}); diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index aa42cfe1d51..382e6e1d264 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -5281,18 +5281,16 @@ export class ObjectQL implements IObjectQLEngine { * column: the question plugin-auth's organization delete asks before * anything is deleted. Only objects holding at least one row are listed. * - * The relations read are the ones {@link refuseOrganizationDeleteWhileOwned} - * judges, through the same reader ({@link cascadeRelationBehavior}: a - * federated object's unprovisioned injected column is no relation), widened - * to every behaviour: a tenant column its author declared `restrict` blocks - * the delete too, and one declared `cascade` would delete records, which is - * not the organization's own structure either. A count, never a row: the - * read is a system-identity `count`, and a table never provisioned holds no - * row. - * - * `exclude` names the objects the caller removes as part of the delete - * itself. An append-only or engine-owned object is never counted ({@link - * outlivesOrganization}), the same set the engine's own refusal leaves out. + * The relations read are the ones {@link refuseOrganizationDeleteWhileOwned} judges, through the same + * reader ({@link cascadeRelationBehavior}: a federated object's unprovisioned injected column is no + * relation), widened to every behaviour: a tenant column its author declared `restrict` blocks the delete + * too, and one declared `cascade` would delete records, which is not the organization's own structure + * either. A count, never a row: a system-identity `count`, and a table never provisioned holds no row. + * + * `exclude` names the objects the caller removes as part of the delete itself. An append-only or + * engine-owned object is never counted ({@link outlivesOrganization}), the same set the engine's own + * refusal leaves out, and neither is `sys_unit`: the engine's cascade removes the organization's units + * with it [ruling 7035627429, option B]. */ organizationOwnedRowCounts( organizationId: string, @@ -5864,6 +5862,7 @@ export class ObjectQL implements IObjectQLEngine { buildSession: (...a) => engine.buildSession(...a), buildUser: (...a) => engine.buildUser(...a), cascadeDeleteRelations: (...a) => engine.cascadeDeleteRelations(...a), + get cascadeIssuedDeletes() { return engine.cascadeIssuedDeletes; }, claimReferentialCascadeDelete: (...a) => engine.claimReferentialCascadeDelete(...a), composeReadableIdsAtBoundary: (...a) => engine.composeReadableIdsAtBoundary(...a), delete: (...a) => engine.delete(...a), diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 0888b2ba459..34dca84cd16 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -182,6 +182,11 @@ const READERS: Record = { via: 'cascadeRelationBehavior', why: "counts a tenant column only once the cascade's own relation reading admits it, so a federated object's unprovisioned injected column is never counted", }, + // [ruling 7035627429, option B] The organization delete removes its units. + 'engine-cascade-planning.ts#removeOrganizationUnits :: resolveTenantFieldName()': { + disposition: 'not-a-read', + why: "keys an organization's sys_unit rows, a platform table platform-objects owns (ADR-0158 U3), never a federated object's column", + }, 'engine-cascade-planning.ts#keepsOrganizationReference :: organization_id': { disposition: 'not-a-read', why: "names the attribution column a tenancy-disabled object keeps through an organization delete; the walk reads its relation through cascadeRelationBehavior; it reads no row", diff --git a/packages/objectql/src/validation/unit-code-membership.test.ts b/packages/objectql/src/validation/unit-code-membership.test.ts index 1d02c2a1c8a..681d5f6538f 100644 --- a/packages/objectql/src/validation/unit-code-membership.test.ts +++ b/packages/objectql/src/validation/unit-code-membership.test.ts @@ -318,17 +318,21 @@ describe('the organization read: once per organization per write, never for a st }); }); -describe('Requirement 1 (7030061316): a `sys_unit` row is never deleted', () => { +describe('Requirement 1 (7030061316): a `sys_unit` row is never deleted on its own', () => { it('refuses a delete of `sys_unit`, ERR_UNIT_DELETE_REFUSED / 405, and no other object', () => { let thrown: unknown; try { - refuseOrganizationUnitDelete('sys_unit'); + refuseOrganizationUnitDelete('sys_unit', false); } catch (e) { thrown = e; } expect(thrown).toMatchObject({ code: 'ERR_UNIT_DELETE_REFUSED', status: 405, httpStatus: 405 }); - expect(() => refuseOrganizationUnitDelete('sys_exchange_rate')).not.toThrow(); - expect(() => refuseOrganizationUnitDelete('material')).not.toThrow(); + expect(() => refuseOrganizationUnitDelete('sys_exchange_rate', false)).not.toThrow(); + expect(() => refuseOrganizationUnitDelete('material', false)).not.toThrow(); + }); + + it('[ruling 7035627429, option B] admits only the delete the engine recognised as its organization\'s removal', () => { + expect(() => refuseOrganizationUnitDelete('sys_unit', true)).not.toThrow(); }); }); diff --git a/packages/objectql/src/validation/unit-code-membership.ts b/packages/objectql/src/validation/unit-code-membership.ts index 7a5cb97a579..0d7604c4eff 100644 --- a/packages/objectql/src/validation/unit-code-membership.ts +++ b/packages/objectql/src/validation/unit-code-membership.ts @@ -472,12 +472,12 @@ export function organizationUnitRowsOf( export const UNIT_DELETE_REFUSED_CODE = 'ERR_UNIT_DELETE_REFUSED' as const; /** - * [ADR-0158 Open item 11; L1] A `sys_unit` row is never deleted, in any - * context. Retiring is the delete (the row's one-way `retired` flag): the row - * keeps holding its organization-scoped unique `code`, so the code can never - * be created again with another dimension, ratio or label, and a quantity - * resting on it never takes a stranger's meaning. A removed row would free - * that key. + * [ADR-0158 Open item 11; L1] A `sys_unit` row is never deleted on its own, + * in any context. Retiring is the delete (the row's one-way `retired` flag): + * the row keeps holding its organization-scoped unique `code`, so the code can + * never be created again with another dimension, ratio or label, and a + * quantity resting on it never takes a stranger's meaning. A removed row would + * free that key. * * The data API serves no `delete` on the object (`apiMethods`, 405 * `OBJECT_API_METHOD_NOT_ALLOWED`) and Setup offers none (`userActions`); this @@ -485,6 +485,12 @@ export const UNIT_DELETE_REFUSED_CODE = 'ERR_UNIT_DELETE_REFUSED' as const; * user, a system writer (`isSystem: true`, which the security middleware lets * through untouched) and an automation run. 405, the status the data door * answers the same verb on this object with. + * + * [ruling 7035627429, option B] The one exemption: an organization's own + * delete removes that organization's units, + * since a deleted organization can never create a code again. It is carried by + * the engine's cascade claim alone ({@link refuseOrganizationUnitDelete}), + * never by a caller's flag or a context bit. */ export class UnitDeleteRefusedError extends Error { readonly code = UNIT_DELETE_REFUSED_CODE; @@ -495,7 +501,7 @@ export class UnitDeleteRefusedError extends Error { constructor() { super( - `Delete on '${ORGANIZATION_UNIT_OBJECT}' was REFUSED: a unit of measure is never deleted. Retire it instead ` + + `Delete on '${ORGANIZATION_UNIT_OBJECT}' was REFUSED: a unit of measure is never deleted on its own, only with its organization. Retire it instead ` + '(set `retired: true`): a retired unit keeps its code, so the code is never created again with another ' + 'meaning, and records already in that unit keep it. Nothing was deleted.', ); @@ -508,7 +514,14 @@ export class UnitDeleteRefusedError extends Error { * {@link UnitDeleteRefusedError}. Called by the engine's `delete()` before any * middleware or hook runs, for a by-id, a predicate (`multi`) and a permanent * delete alike. + * + * `removedWithItsOrganization` is the engine's own answer, never a caller's: + * `true` only when THIS delete claimed the token the organization delete's + * cascade issued for exactly this unit (`isOrganizationUnitRemoval`, + * `engine-cascade-planning.ts`). A token is claimed once, so a delete a hook + * or a middleware issues inside that removal, or anyone else's delete while + * the organization's delete is in flight, is refused like every other. */ -export function refuseOrganizationUnitDelete(object: string): void { - if (object === ORGANIZATION_UNIT_OBJECT) throw new UnitDeleteRefusedError(); +export function refuseOrganizationUnitDelete(object: string, removedWithItsOrganization: boolean): void { + if (object === ORGANIZATION_UNIT_OBJECT && !removedWithItsOrganization) throw new UnitDeleteRefusedError(); } diff --git a/packages/platform-objects/src/system/sys-unit.object.ts b/packages/platform-objects/src/system/sys-unit.object.ts index dd939ddb88f..336ba25ef06 100644 --- a/packages/platform-objects/src/system/sys-unit.object.ts +++ b/packages/platform-objects/src/system/sys-unit.object.ts @@ -90,10 +90,12 @@ const DIMENSION_LABELS: Record<(typeof UNIT_DIMENSIONS)[number], string> = { * a retired row keeps its code, so the code can never be created again with * another dimension, ratio or label, and resting quantities never take a * stranger's meaning. A hard delete is not served (`apiMethods` has no - * `delete`) and the engine refuses one in every context, a system writer's - * and an automation run's included (`ERR_UNIT_DELETE_REFUSED`); a retired - * unit cannot be brought back, and a new save with a retired code is - * refused (`ERR_UNIT_CODE_RETIRED`). + * `delete`) and the engine refuses a direct one in every context, a system + * writer's and an automation run's included (`ERR_UNIT_DELETE_REFUSED`). The + * one exemption is the organization's own delete, whose cascade removes + * every unit of that organization (#35812). A retired unit cannot be + * brought back, and a new save with a retired code is refused + * (`ERR_UNIT_CODE_RETIRED`). * - **Tenancy** — no tenancy opt-out, so `organization_id` is injected and the * Layer 0 tenant wall (ADR-0095 D1) scopes every read and write. * - **Who reads, who writes** — every member READS it (`member_default` names diff --git a/packages/plugins/plugin-security/src/default-permission-sets.unit-of-measure.integration.test.ts b/packages/plugins/plugin-security/src/default-permission-sets.unit-of-measure.integration.test.ts index c49d3d271e5..f6c6848d958 100644 --- a/packages/plugins/plugin-security/src/default-permission-sets.unit-of-measure.integration.test.ts +++ b/packages/plugins/plugin-security/src/default-permission-sets.unit-of-measure.integration.test.ts @@ -381,4 +381,61 @@ describe('sys_unit on a real stack: member read, administrator write, and the ru expect((await materials({ id: resting!.id }))[0]).toMatchObject({ title: 'renamed-resting', uom: 'JIN1', weight: 2 }); }); }); + + // [ruling 7035627429, option B] Deleting an organization deletes its units: + // the one exemption from the delete refusal above, carried by the engine's + // own cascade, which names the organization explicitly, so a system writer + // acting in another organization removes every unit of the deleted one. + describe("an organization's delete removes its units, and only its delete does", () => { + const GONE = 'org_units_gone'; + const KEPT = 'org_units_kept'; + const inOrg = (organizationId: string) => ({ isSystem: true, tenantId: organizationId }) as const; + const unitsOf = async (organizationId: string) => + (await ql.find(OBJ, { where: { organization_id: organizationId }, context: inOrg(organizationId) } as never)) as Row[]; + const organizations = async (ids: string[]) => + ((await ql.find('sys_organization', { where: { id: { $in: ids } }, context: { isSystem: true } } as never)) as Row[]).map((r) => r.id); + + beforeAll(async () => { + for (const [id, slug] of [[GONE, 'units-gone'], [KEPT, 'units-kept']]) { + await ql.insert('sys_organization', { id, name: slug, slug }, { context: { isSystem: true } } as never); + await ql.insert(OBJ, { code: 'BALE_1', label: 'Bale', dimension: 'mass', ratio: 200 }, { context: inOrg(id) } as never); + const retired = (await ql.insert(OBJ, { code: 'DRUM_1', label: 'Drum', dimension: 'volume', ratio: 0.2 }, { context: inOrg(id) } as never)) as Row; + await ql.update(OBJ, { retired: true }, { where: { id: retired.id }, context: inOrg(id) } as never); + } + await ql.insert(MATERIAL, { title: 'owned', uom: 'BALE_1', weight: 1 }, { context: inOrg(KEPT) } as never); + }); + + it('an organization holding units, one retired, and no other record deletes, and no unit of it is left', async () => { + const others = (await stored({})).filter((r) => r.organization_id !== GONE).map((r) => r.id).sort(); + expect((await unitsOf(GONE)).map((r) => [r.code, r.retired])).toEqual([['BALE_1', false], ['DRUM_1', true]]); + + await expect(ql.delete('sys_organization', { where: { id: GONE }, context: SYS } as never)).resolves.toBe(true); + + expect(await organizations([GONE])).toEqual([]); + expect(await unitsOf(GONE)).toEqual([]); + expect((await stored({})).map((r) => r.id).sort()).toEqual(others); + }); + + it('an organization holding units and another record is refused 409 DELETE_RESTRICTED, and keeps every unit', async () => { + const err = await refusal(() => ql.delete('sys_organization', { where: { id: KEPT }, context: SYS } as never)); + expect(err).toEqual({ status: 409, code: 'DELETE_RESTRICTED' }); + expect(await organizations([KEPT])).toEqual([KEPT]); + expect((await unitsOf(KEPT)).map((r) => [r.code, r.retired])).toEqual([['BALE_1', false], ['DRUM_1', true]]); + }); + + for (const [who, ctx] of [['a system writer', () => inOrg(KEPT)], ['a system automation run', () => ({ ...AUTOMATION, tenantId: KEPT })]] as const) { + it(`${who} still deletes no unit of that organization directly: 405 ERR_UNIT_DELETE_REFUSED, by id and batched`, async () => { + const [unit] = await unitsOf(KEPT); + expect(await refusal(() => ql.delete(OBJ, { where: { id: unit!.id }, context: ctx() } as never))).toEqual({ + status: 405, + code: 'ERR_UNIT_DELETE_REFUSED', + }); + expect(await refusal(() => ql.delete(OBJ, { where: { code: 'BALE_1' }, multi: true, context: ctx() } as never))).toEqual({ + status: 405, + code: 'ERR_UNIT_DELETE_REFUSED', + }); + expect(await unitsOf(KEPT)).toHaveLength(2); + }); + } + }); }); diff --git a/packages/plugins/plugin-security/src/objects/default-permission-sets.ts b/packages/plugins/plugin-security/src/objects/default-permission-sets.ts index 512e7075aeb..30c0cafffaf 100644 --- a/packages/plugins/plugin-security/src/objects/default-permission-sets.ts +++ b/packages/plugins/plugin-security/src/objects/default-permission-sets.ts @@ -450,8 +450,9 @@ const baseDefaultPermissionSets: PermissionSet[] = [ // created, relabelled, re-rated and retired here, never deleted. // Retiring is the delete, and a removed row would free its code to be // created again with another meaning, so the effective map offers no - // delete, and the engine refuses one in every context - // (`ERR_UNIT_DELETE_REFUSED`, `@objectstack/objectql`). WITHOUT the + // delete, and the engine refuses a direct one in every context + // (`ERR_UNIT_DELETE_REFUSED`, `@objectstack/objectql`); only the + // organization's own delete removes its units (#35812). WITHOUT the // superuser bits: `modifyAllRecords` grants delete on its own, and the // derived no-bypass variant inherits this line. Units carry no owner // scope for an administrator (the owner-only floor binds `org_member`),