Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/35812-org-delete-removes-units.md
Original file line number Diff line number Diff line change
@@ -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.
90 changes: 89 additions & 1 deletion packages/objectql/src/engine-cascade-planning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
}
}

/**
Expand Down Expand Up @@ -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
Expand All @@ -1373,6 +1383,9 @@ export class CascadePlanningFacet {
const fields = (child as any)?.fields as Record<string, any> | 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;
Expand Down Expand Up @@ -1415,6 +1428,8 @@ export class CascadePlanningFacet {
const childName = (child as any)?.name as string | undefined;
const fields = (child as any)?.fields as Record<string, any> | 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];
Expand Down Expand Up @@ -1517,6 +1532,79 @@ async function deleteCascadedChildren(host: Pick<CascadePlanningHost, 'cascadeIs
}
}

/**
* The tokens {@link removeOrganizationUnits} issued, and no other: the
* provenance `delete()` reads ({@link isOrganizationUnitRemoval}) to admit an
* organization's unit delete. Module-private, so nothing outside this module
* can enter a token into it, a holder of the engine's own `cascadeIssuedDeletes`
* store included.
*/
const organizationUnitRemovals = new WeakSet<object>();

/**
* [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<CascadePlanningHost, 'cascadeIssuedDeletes' | 'delete' | 'fileReferenceCheckElevation' | 'find'>, organizationId: string | number, context: ExecutionContext | undefined, objects: ServiceObject[], cascadeSet: CascadeDeleteSet): Promise<void> {
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,
Expand Down
18 changes: 13 additions & 5 deletions packages/objectql/src/engine-delete-and-aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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'];
Expand Down Expand Up @@ -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<DeleteAndAggregateHost, '_registry' | 'assertBulkPerRowHookBudget' | 'assertWriteAllowed' | 'buildDriverOptions' | 'buildHookApi' | 'buildPerRowAfterContexts' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'cascadeDeleteRelations' | 'claimReferentialCascadeDelete' | 'dispatchPerRowBeforeHooks' | 'dispatchUnscopedMultiWriteHooks' | 'enforceTransactionOrigin' | 'executeWithMiddleware' | 'facade' | 'getDriver' | 'getSummaryDescriptors' | 'hasHooksFor' | 'inAfterAbortUnit' | 'invalidateOrganizationProbe' | 'logger' | 'openRecycleBinCapture' | 'opensAfterAbortUnit' | 'planCascadeAtomicity' | 'publishBulkDataEvent' | 'publishDataEvent' | 'realtimeService' | 'recomputeSummaries' | 'relatedSchemaOf' | 'releaseSecretHandles' | 'resolveObjectName' | 'summaryForeignKeyColumns' | 'transaction' | 'triggerHooks' | 'warnCascadeNotAtomic' | 'withResolvedWhere'>, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise<boolean | number> {
static async delete(this: Pick<DeleteAndAggregateHost, '_registry' | 'assertBulkPerRowHookBudget' | 'assertWriteAllowed' | 'buildDriverOptions' | 'buildHookApi' | 'buildPerRowAfterContexts' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'cascadeDeleteRelations' | 'cascadeIssuedDeletes' | 'claimReferentialCascadeDelete' | 'dispatchPerRowBeforeHooks' | 'dispatchUnscopedMultiWriteHooks' | 'enforceTransactionOrigin' | 'executeWithMiddleware' | 'facade' | 'getDriver' | 'getSummaryDescriptors' | 'hasHooksFor' | 'inAfterAbortUnit' | 'invalidateOrganizationProbe' | 'logger' | 'openRecycleBinCapture' | 'opensAfterAbortUnit' | 'planCascadeAtomicity' | 'publishBulkDataEvent' | 'publishDataEvent' | 'realtimeService' | 'recomputeSummaries' | 'relatedSchemaOf' | 'releaseSecretHandles' | 'resolveObjectName' | 'summaryForeignKeyColumns' | 'transaction' | 'triggerHooks' | 'warnCascadeNotAtomic' | 'withResolvedWhere'>, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise<boolean | number> {
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`.
Expand All @@ -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();
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading