Skip to content

Commit 420499a

Browse files
committed
Merge remote-tracking branch 'origin/claude/issue-24583-7b0-tenant-not-null-ddl' into claude/issue-24583-7b12-index-plain-form
# Conflicts: # packages/drivers/driver-sql/src/sql-driver-tenant-scope-read-doors.test.ts # packages/drivers/driver-sql/src/sql-driver-tenant-scope.test.ts
2 parents abd5acd + 582989e commit 420499a

337 files changed

Lines changed: 3061 additions & 56 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/driver-sql': minor
3+
'@objectstack/driver-turso': minor
4+
'@objectstack/spec': patch
5+
---
6+
7+
feat(driver-sql,driver-turso)!: a table the driver creates carries its tenant column NOT NULL, so a write that names no organization is refused at the database
8+
9+
Clause-②: yes (narrowing)
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) A storage constraint at CREATE TABLE: no key of any metadata schema is removed, renamed or re-shaped, so there is nothing for `objectstack migrate meta` to rewrite and no tombstone. No export, type or error code is removed or renamed; `TENANT_SCOPE_FIELD_DEF` keeps its shape and only its description text is corrected. The remedy is a run-time one, stated below. -->
12+
13+
**BREAKING** accept-set narrowing at the database, shipped as `minor` under the repo's launch-window convention for breaking changes (ADR-0131 D1: "There is no nullable tenant column anywhere").
14+
15+
- **Before.** The SQL driver created a table's tenant column (`organization_id`, or a declared `tenancy.tenantField`) nullable, as the injected field's declaration says (`required: false`, no `storage`). A write that reached the driver without an organization landed a row no organization owns.
16+
- **Now.** Every table the driver CREATES takes its tenant column `NOT NULL`, with no metadata change: the plain managed table (`initObjects`), every newly rotated shard (asked of the base table's declaration), and a table the Turso remote face creates (`syncSchema`, `syncSchemasBatch`, `initObjects`). A write with no organization on such a table is refused by the database (`NOT NULL constraint failed: <table>.organization_id`, `violates not-null constraint`, or `cannot be null`). That includes an `upsert` whose payload omits the organization: the database checks the proposed row before it resolves the conflict.
17+
- **Unchanged.** A tenant column ADDED to a table that already exists stays nullable, and so does an existing shard or an existing remote table: a table that already holds rows is the organization-ownership ceremony's to tighten (`os migrate organization-ownership`), which reports a shard and the Turso remote face as unable to. The schema differ reports no drift over the tenant column's nullability either way. An object with no tenant column (`tenancy: { enabled: false }`, `systemFields: { tenant: false }`) is untouched, even when it carries a field named `organization_id`.
18+
- **Who sees it.** A composed `os serve` / `os dev` / `os start` with auth stamps every write with its organization, so nothing changes there. A production `os serve` whose `AuthPlugin` did not compose (no `OS_AUTH_SECRET`) and a lean embedding (`@objectstack/objectql/core` or `createStandaloneStack` over a SQL driver, with no organization object) used to write those rows with a NULL organization; now each such write fails, loudly.
19+
20+
**The remedy.** Carry the organization on the write: `ql.insert(object, { ...row, organization_id: orgId })`, or `{ context: { tenantId: orgId } }`. Compose authentication (set `OS_AUTH_SECRET`) so the platform derives it. If the object's rows legitimately belong to no organization, declare it so and it has no tenant column: `systemFields: { tenant: false }` or `tenancy: { enabled: false }`.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Give a lean test engine what every real `single` install has: an
5+
* organization object holding its Default Organization.
6+
*
7+
* ADR-0131 D1: a table the SQL driver creates carries its tenant column NOT
8+
* NULL. The engine stamps an organization-less system write with the derived
9+
* organization under `single` (D9) — but only where the composition registers
10+
* the organization object; a bare `ObjectQL` + `SqlDriver` registers none, so
11+
* the write reaches the database with no organization and is refused there.
12+
* A suite whose subject is not tenancy (claims, acks, idle cost, at-rest
13+
* shapes) calls this once its own objects are registered, so its system
14+
* writes land the way they do on a real install.
15+
*
16+
* The object mirrors the platform's: managed by better-auth, so it carries no
17+
* tenant column of its own.
18+
*/
19+
export const DEFAULT_ORGANIZATION_ID = 'org_default';
20+
21+
export async function installDefaultOrganization(engine: {
22+
registry: { registerObject(def: unknown, owner: string): unknown };
23+
getSchema(object: string): unknown;
24+
syncSchemas(): Promise<unknown>;
25+
getDriverForObject(object: string):
26+
| {
27+
create(object: string, data: Record<string, unknown>): Promise<unknown>;
28+
findOne(object: string, query: unknown): Promise<unknown>;
29+
}
30+
| undefined;
31+
}): Promise<void> {
32+
// Idempotent: a suite that syncs one engine more than once may call it each time.
33+
if (!engine.getSchema('sys_organization')) {
34+
engine.registry.registerObject(
35+
{ name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: { type: 'text', label: 'Name' } } },
36+
'@objectstack/example-crm',
37+
);
38+
}
39+
await engine.syncSchemas();
40+
// Seeded through the driver: the organization is data at rest, not a write
41+
// the suite under test should observe (an audit or activity mirror would).
42+
const driver = engine.getDriverForObject('sys_organization')!;
43+
if (await driver.findOne('sys_organization', { where: { id: DEFAULT_ORGANIZATION_ID } })) return;
44+
await driver.create('sys_organization', { id: DEFAULT_ORGANIZATION_ID, name: 'Default' });
45+
}

‎examples/app-crm/test/opportunity-stage-hook.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import { SqlDriver } from '@objectstack/driver-sql';
5656
import { Account, Opportunity, OpportunityLineItem } from '../src/objects/index.js';
5757
import { allHooks } from '../src/hooks/index.js';
5858
import { OpportunityStageHook } from '../src/hooks/opportunity.hook.js';
59+
import { installDefaultOrganization } from './default-organization.testkit.js';
5960

6061
/** The app id `AppPlugin` derives its `packageId` from. */
6162
const PACKAGE_ID = 'app:com.example.crm';
@@ -96,6 +97,9 @@ async function bootCrm(hooks: unknown[] = allHooks): Promise<ObjectQL> {
9697
engine.registry.registerObject(def as never, PACKAGE_ID, 'crm');
9798
}
9899
await engine.syncSchemas();
100+
// A real `single` install's Default Organization: the system writes below
101+
// derive it (ADR-0131 D9), as a fresh NOT NULL tenant column requires (D1).
102+
await installDefaultOrganization(engine);
99103

100104
// Exactly the AppPlugin call, minus the sandbox body runner this app has no
101105
// use for (its single hook is an inline code handler).

‎examples/app-showcase/test/approval-resume-relation-expand.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ import {
5858
TaskDoneNotifyOwnerFlow,
5959
NotifyOwnerSubflow,
6060
} from '../src/automation/flows/index.js';
61+
import { installDefaultOrganization } from './default-organization.testkit.js';
6162

6263
/** Everything the approvals service treats as an unconditional actor. */
6364
const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as any;
@@ -128,6 +129,9 @@ async function bootShowcaseApprovals(
128129
objectql.registry.registerObject(obj, 'showcase', 'showcase');
129130
}
130131
await objectql.syncSchemas();
132+
// A real `single` install's Default Organization: the system writes below
133+
// derive it (ADR-0131 D9), as a fresh NOT NULL tenant column requires (D1).
134+
await installDefaultOrganization(objectql);
131135

132136
for (const flow of flows) automation.registerFlow(flow.name, flow);
133137

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Give a lean test engine what every real `single` install has: an
5+
* organization object holding its Default Organization.
6+
*
7+
* ADR-0131 D1: a table the SQL driver creates carries its tenant column NOT
8+
* NULL. The engine stamps an organization-less system write with the derived
9+
* organization under `single` (D9) — but only where the composition registers
10+
* the organization object; a bare `ObjectQL` + `SqlDriver` registers none, so
11+
* the write reaches the database with no organization and is refused there.
12+
* A suite whose subject is not tenancy (claims, acks, idle cost, at-rest
13+
* shapes) calls this once its own objects are registered, so its system
14+
* writes land the way they do on a real install.
15+
*
16+
* The object mirrors the platform's: managed by better-auth, so it carries no
17+
* tenant column of its own.
18+
*/
19+
export const DEFAULT_ORGANIZATION_ID = 'org_default';
20+
21+
export async function installDefaultOrganization(engine: {
22+
registry: { registerObject(def: unknown, owner: string): unknown };
23+
getSchema(object: string): unknown;
24+
syncSchemas(): Promise<unknown>;
25+
getDriverForObject(object: string):
26+
| {
27+
create(object: string, data: Record<string, unknown>): Promise<unknown>;
28+
findOne(object: string, query: unknown): Promise<unknown>;
29+
}
30+
| undefined;
31+
}): Promise<void> {
32+
// Idempotent: a suite that syncs one engine more than once may call it each time.
33+
if (!engine.getSchema('sys_organization')) {
34+
engine.registry.registerObject(
35+
{ name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: { type: 'text', label: 'Name' } } },
36+
'@objectstack/example-showcase',
37+
);
38+
}
39+
await engine.syncSchemas();
40+
// Seeded through the driver: the organization is data at rest, not a write
41+
// the suite under test should observe (an audit or activity mirror would).
42+
const driver = engine.getDriverForObject('sys_organization')!;
43+
if (await driver.findOne('sys_organization', { where: { id: DEFAULT_ORGANIZATION_ID } })) return;
44+
await driver.create('sys_organization', { id: DEFAULT_ORGANIZATION_ID, name: 'Default' });
45+
}

‎examples/app-showcase/test/hook-body-persisted-writes.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import { QuickJSScriptRunner, hookBodyRunnerFactory } from '@objectstack/runtime
4949

5050
import { Account, Project, Task, Inquiry } from '../src/data/objects/index.js';
5151
import { allHooks } from '../src/data/hooks/index.js';
52+
import { installDefaultOrganization } from './default-organization.testkit.js';
5253

5354
/** The app id `AppPlugin` derives its `packageId` from. */
5455
const APP_ID = 'com.objectstack.showcase';
@@ -87,6 +88,9 @@ async function bootShowcase(hooks: unknown[] = allHooks): Promise<ObjectQL> {
8788
engine.registry.registerObject(def as never, PACKAGE_ID, 'showcase');
8889
}
8990
await engine.syncSchemas();
91+
// A real `single` install's Default Organization: the system writes below
92+
// derive it (ADR-0131 D9), as a fresh NOT NULL tenant column requires (D1).
93+
await installDefaultOrganization(engine);
9094

9195
engine.bindHooks(hooks as never[], {
9296
packageId: PACKAGE_ID,

‎examples/app-showcase/test/new-project-wizard-initial-status.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import { SqlDriver } from '@objectstack/driver-sql';
3737
import stack from '../objectstack.config.js';
3838
import { Account, Project } from '../src/data/objects/index.js';
3939
import { NewProjectWizardPage } from '../src/ui/pages/new-project-wizard.page.js';
40+
import { installDefaultOrganization } from './default-organization.testkit.js';
4041

4142
type Rule = {
4243
type?: string;
@@ -82,6 +83,9 @@ async function bootShowcase(): Promise<ObjectQL> {
8283
engine.registry.registerObject(def as never, PACKAGE_ID, 'showcase');
8384
}
8485
await engine.syncSchemas();
86+
// A real `single` install's Default Organization: the system writes below
87+
// derive it (ADR-0131 D9), as a fresh NOT NULL tenant column requires (D1).
88+
await installDefaultOrganization(engine);
8589
return engine;
8690
}
8791

‎examples/app-showcase/test/paid-invoice-line-lock.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
PAID_INVOICE_LINE_REMOVE_REFUSAL,
3535
PAID_INVOICE_LINE_MOVE_REFUSAL,
3636
} from '../src/data/hooks/index.js';
37+
import { installDefaultOrganization } from './default-organization.testkit.js';
3738

3839
const APP_ID = 'com.objectstack.showcase';
3940
const PACKAGE_ID = `app:${APP_ID}`;
@@ -61,6 +62,9 @@ async function bootShowcase(hooks: unknown[] = allHooks): Promise<ObjectQL> {
6162
engine.registry.registerObject(def as never, PACKAGE_ID, 'showcase');
6263
}
6364
await engine.syncSchemas();
65+
// A real `single` install's Default Organization: the system writes below
66+
// derive it (ADR-0131 D9), as a fresh NOT NULL tenant column requires (D1).
67+
await installDefaultOrganization(engine);
6468
engine.bindHooks(hooks as never[], {
6569
packageId: PACKAGE_ID,
6670
bodyRunner: hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: engine, appId: APP_ID }),

‎examples/app-showcase/test/task-reopen-hook-refusal.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
import { Account, Project, Task } from '../src/data/objects/index.js';
3939
import { allHooks, TASK_REOPEN_REFUSAL } from '../src/data/hooks/index.js';
4040
import { ReopenTaskAction } from '../src/ui/actions/index.js';
41+
import { installDefaultOrganization } from './default-organization.testkit.js';
4142

4243
const APP_ID = 'com.objectstack.showcase';
4344
const PACKAGE_ID = `app:${APP_ID}`;
@@ -65,6 +66,9 @@ async function bootShowcase(hooks: unknown[] = allHooks): Promise<ObjectQL> {
6566
engine.registry.registerObject(def as never, PACKAGE_ID, 'showcase');
6667
}
6768
await engine.syncSchemas();
69+
// A real `single` install's Default Organization: the system writes below
70+
// derive it (ADR-0131 D9), as a fresh NOT NULL tenant column requires (D1).
71+
await installDefaultOrganization(engine);
6872
engine.bindHooks(hooks as never[], {
6973
packageId: PACKAGE_ID,
7074
bodyRunner: hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: engine, appId: APP_ID }),
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Give a lean test engine what every real `single` install has: an
5+
* organization object holding its Default Organization.
6+
*
7+
* ADR-0131 D1: a table the SQL driver creates carries its tenant column NOT
8+
* NULL. The engine stamps an organization-less system write with the derived
9+
* organization under `single` (D9) — but only where the composition registers
10+
* the organization object; a bare `ObjectQL` + `SqlDriver` registers none, so
11+
* the write reaches the database with no organization and is refused there.
12+
* A suite whose subject is not tenancy (claims, acks, idle cost, at-rest
13+
* shapes) calls this once its own objects are registered, so its system
14+
* writes land the way they do on a real install.
15+
*
16+
* The object mirrors the platform's: managed by better-auth, so it carries no
17+
* tenant column of its own.
18+
*/
19+
export const DEFAULT_ORGANIZATION_ID = 'org_default';
20+
21+
export async function installDefaultOrganization(engine: {
22+
registry: { registerObject(def: unknown, owner: string): unknown };
23+
getSchema(object: string): unknown;
24+
syncSchemas(): Promise<unknown>;
25+
getDriverForObject(object: string):
26+
| {
27+
create(object: string, data: Record<string, unknown>): Promise<unknown>;
28+
findOne(object: string, query: unknown): Promise<unknown>;
29+
}
30+
| undefined;
31+
}): Promise<void> {
32+
// Idempotent: a suite that syncs one engine more than once may call it each time.
33+
if (!engine.getSchema('sys_organization')) {
34+
engine.registry.registerObject(
35+
{ name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: { type: 'text', label: 'Name' } } },
36+
'@objectstack/example-todo',
37+
);
38+
}
39+
await engine.syncSchemas();
40+
// Seeded through the driver: the organization is data at rest, not a write
41+
// the suite under test should observe (an audit or activity mirror would).
42+
const driver = engine.getDriverForObject('sys_organization')!;
43+
if (await driver.findOne('sys_organization', { where: { id: DEFAULT_ORGANIZATION_ID } })) return;
44+
await driver.create('sys_organization', { id: DEFAULT_ORGANIZATION_ID, name: 'Default' });
45+
}

0 commit comments

Comments
 (0)