Skip to content

Commit adab62a

Browse files
fix(service-datasource)!: the datasource admin door asks the walled-catalog verdict on every row-writing verb, as the /meta door does (#31005)
security#1 · os-tesla · session_01L9qibvynRbCtMndW8EHNGc Clause-②: no (narrowing) — under the `isolated` and `group` tenancy postures, creating, changing or removing a datasource at the datasource admin routes (`POST /api/v1/datasources`, `PATCH` and `DELETE /api/v1/datasources/:name`, `POST /api/v1/datasources/:name/migrate-credential`) is a write to the environment's metadata catalog, and it is the platform operator's, as every other write to that catalog is. Metadata-protocol: none Skills-docs: none — no `skills/**` text teaches the datasource admin routes or who may call them (0 hits for `api/v1/datasources` and `migrate-credential` under `skills/`; `datasource` itself is named there, the positive control); the rule is stated in the docs this diff updates (`content/docs/deployment/tenancy-modes.mdx`, `content/docs/data-modeling/external-datasources.mdx`). ## 维护者速读 - 改了什么:数据源管理路由中写数据源记录的四个动作(创建、修改、删除、迁移凭据),在 `isolated` / `group` 租户姿态下,与 `/meta` 写入门问同一个“围墙目录写入”裁决(`walledCatalogWriteVerdict`,类型 `datasource`)。 - 为什么改:数据源是环境元数据目录里的一个 `datasource` 条目,与 `PUT /meta/datasource/:name` 写的是同一条记录;围墙姿态下这个目录只归平台运营方(与引擎自身)写,所以这道门与 `/meta` 门读同一条裁决、给同一个状态码与同一句话。 - 风险与回滚:围墙姿态下,平台运营方以下、持有 `manage_platform_settings` 的调用方(包括组织内的 `admin_full_access` 持有人)写数据源改为 `403 PERMISSION_DENIED`,什么都不存、不封存凭据、不重建连接池;`single` 与未注册租户服务的部署不变;列表、读取、驱动目录、两种连接测试、远程表列表与对象草稿不变;回滚即还原本 PR,已存的数据源不受影响。 - 先看:`packages/services/service-datasource/src/admin-routes.ts`(`requireDatasourceAdmin` 的 `catalogWrite` 段与 `walledVerdictTenancyPosture`,以及四条写路由的调用)、`packages/services/service-datasource/src/__tests__/admin-routes-tenancy-posture-admission.test.ts`(§1 改用运营方作写入对照,§8 / §8b 新矩阵)、`packages/services/service-datasource/src/__tests__/datasource-update-kept-pool-stores-nothing.test.ts`(被拒的 PATCH 不动存储与连接池)。 - 两分钟验证:`pnpm --filter @objectstack/service-datasource exec vitest run src/__tests__/admin-routes-tenancy-posture-admission.test.ts src/__tests__/datasource-update-kept-pool-stores-nothing.test.ts`,预期 2 个文件 73 个用例全部通过。 - 需要你做的:无,席位落地。 ## What changes - **The rule.** Under `isolated` and `group` every organization shares the environment's metadata catalog, and a write to it is admitted only for the platform operator and for the engine's own writes (ADR-0131 D3, D12 items 7–8, D11). A datasource is a `datasource` item of that catalog, the record `PUT /api/v1/meta/datasource/:name` writes. The datasource admin door now asks the walled-catalog verdict on every row-writing verb, as the `/meta` door does: create, update, remove and migrate-credential each ask `walledCatalogWriteVerdict` (`@objectstack/metadata-core`) for the type `datasource`, after the `manage_platform_settings` capability gate and before the datasource service is looked up. The verdict is reused, not restated. - **The answer.** A refused call answers `403 PERMISSION_DENIED` with the verdict's sentence for a `datasource` item, the sentence the `/meta` write doors answer for the same record, naming the posture. Nothing is stored, no secret is sealed or removed, and no pool is rebuilt or evicted. - **The posture judged.** On a host whose kernel has the async service accessor, the verdict judges the same effective posture the door's admission already resolved, so one read of the `tenancy` service decides both. On a host without that accessor, where the admission does not read the posture, the verdict reads a registered `tenancy` service synchronously; a service that is not registered reads as the no-`tenancy` composition, inert as `single` is. - **Unchanged.** The platform operator writes datasources under a wall as before. Under `single`, and with no `tenancy` service, every caller holding `manage_platform_settings` writes datasources as before. Listing, reading, the driver catalog, the draft probe (`POST /datasources/test`), the saved-datasource probe (`POST /datasources/:name/test`), the remote-table listing and the object draft write no datasource record and do not ask the verdict; the object draft hands back a definition the caller saves through the `/meta` doors, which ask it themselves. The capability gate still answers first. - **Docs and doc comments.** The admin routes' docblock states the rule in place of the old "no posture arm" note. `deployment/tenancy-modes` and `data-modeling/external-datasources` state who writes a datasource under a wall. The `walledCatalogWriteVerdict` doc comment and its ADR anchor name the datasource admin routes among the doors that ask it, and a new ADR-0131 anchor holds the rule on `admin-routes.ts`. ## Tests - `admin-routes-tenancy-posture-admission.test.ts` (real `ObjectKernel`, real `resolveAuthzContext`, API keys over the shipped permission-store shapes): - §1's write controls under `isolated` are now the platform operator's key (declared in `OS_PLATFORM_OWNER_EMAIL` over a verified row); they previously pinned a member's create and delete landing under `isolated`. - §8, for `isolated` and for `group`, each of the four verbs: refused for a current member holding `manage_platform_settings` (`403`, `PERMISSION_DENIED`, the message equal to the verdict's message for `datasource` on that posture, the service method never called, the store unchanged); refused for an organization's `admin_full_access` holder; allowed for the platform operator, and the write lands. The capability refusal still answers first for a caller without the capability. The seven routes that write no record still answer `200` for the member. - §8b, under `single` and with no `tenancy` service: each of the four verbs is served for the member and the write lands. - `datasource-update-kept-pool-stores-nothing.test.ts` (the real `DatasourceAdminServicePlugin` and `ExternalDatasourceServicePlugin` behind the real routes, the real secret binder, a driver factory that records every pool it builds): under `isolated` and `group` a PATCH carrying a new secret and a new host by the entitled caller is refused with the verdict's status, code and sentence; the stored record and the `sys_secret` ids are byte-equal to before, no pool is built, and the serving pool still answers its test. Control: the same PATCH under `single` stores the new host and builds one new pool. This rig has no `getKernel`, so it also covers the synchronous posture read. ## Acceptance notes - **Where the rule sits.** At the door, beside the capability gate, before `resolve()`: the service below receives the record, not the caller's rung, and the door is where this family's admission already lives. One option on the shared floor (`catalogWrite`) is passed by exactly the four row-writing routes. - **Which verbs write.** Decided from the code: the service's write seams (`putDatasourceRecord`, `deleteDatasourceRecord`, the secret writes and the pool seams) are reached only from `createDatasource`, `updateDatasource`, `removeDatasource` and `migrateCredential`. `testConnection` (draft and saved), `listRemoteTables`, `generateObjectDraft`, `listDatasources` and `getDatasource` reach none of them. - **The code.** `PERMISSION_DENIED`, the standard-catalog member this family already answers for a 403, and the code the dispatcher `/meta` door answers; the REST `/meta` door answers its grandfathered synonym (`STANDARD_SYNONYM_WAIVERS`, ADR-0112 D3), which is not endorsed for new code. - **`isSystem`.** Not passed to the verdict: this family's resolution never carries it from inbound HTTP, so the verdict's engine admission is unreachable here, as before. - **Breaking, patch.** An accept-set narrowing under a walled posture only; no key of any schema moves and nothing stored changes, so the package takes a patch with a BREAKING banner (ADR-0087 marker `not-required (no-migration-prescription)`). - **The metadata-core edit is comments only** (the verdict's door list), so it publishes no behaviour and carries no changeset of its own. ## Verification All readings below are at head `b99ce15091cc324f14293a091741c641936cd413`, after `origin/main` was merged in at `e304cae63f` (no conflicts; `main` had moved `core/security`, `metadata-core`, `tenancy-modes` and a `service-datasource` test), the closure rebuilt and every build and test run under the shared verify lock. `main` has moved since by 14 commits, none touching `service-datasource`, `metadata-core`, the authorization resolver or the two docs pages (one `core/security` pin test). <details><summary>Package tests and typecheck</summary> - `pnpm --filter @objectstack/service-datasource exec vitest run`: Test Files 72 passed (72), Tests 1279 passed (1279). - `pnpm --filter @objectstack/metadata-core exec vitest run`: Test Files 23 passed (23), Tests 911 passed (911). - The two edited pin files hold 73 of those tests (65 in the admission matrix, 8 in the PATCH rig). - `typecheck` for `service-datasource`, `metadata-core` and the direct consumers of `service-datasource` (`rest`, `runtime`, `cli`, `verify`, `dogfood`, `example-showcase`): `VERDICT command-exit 0`, every package `Done`, 0 `error TS` lines. The package's typecheck compiles both edited test files (`tsc --listFiles`). - `pnpm --filter @objectstack/spec check:generated` after the merge: all 14 generated artifacts up to date. </details> <details><summary>Ablations</summary> Each through `scripts/ablation-replace.mjs` (anchor hit once, blob changed, restored blob-equal to HEAD with `git diff HEAD` empty), on the committed tree. The pins import `../admin-routes.js` from source, so no rebuild sits between the mutation and the run. The four route ablations were read at `56a424acf3` (blob `c44ff35c97f1`); `admin-routes.ts` has since changed only in a doc comment (blob `bf51f83b0cbc`). The posture-read ablation was read at the head. | subject | ablation | reading (73 pins) | | --- | --- | --- | | create | the route stops naming the type it writes | 4 failed: the member and `admin_full_access` refusals, under `isolated` and `group` | | update | the same, on `PATCH /:name` | 6 failed: the same four, and the PATCH rig's refusal under `isolated` and `group` | | remove | the same, on `DELETE /:name` | 4 failed: the member and `admin_full_access` refusals, both postures | | migrate-credential | the same, on `POST /:name/migrate-credential` | 4 failed: the member and `admin_full_access` refusals, both postures | | the synchronous posture read | the verdict judges the admission posture on every host | 2 failed: the PATCH rig's refusal under `isolated` and `group` | After each restore the blob equals `HEAD`'s and `git diff HEAD` is empty; `git status --porcelain` empty after the last. </details> <details><summary>Derived gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` (no paths) at `b99ce15091`: 102 commands, each run as printed with stdin from `/dev/null` and its exit code recorded. `--ran`: 102 derived, 102 run, 0 NOT-MEASURED, 0 UNRUN; every recorded exit is 0. Before the merge, at `f2dc54d5ea`, two first answered exit 3 (`check:skill-examples`, `check:dual-build-cjs-loads`: prerequisite packages outside this diff unbuilt) and answered 0 once those were built; they were built before the run at the head. `pnpm check:adr-anchors`: exit 0 with the new anchor. </details> <details><summary>Full dogfood battery at the head</summary> `b99ce15091cc324f14293a091741c641936cd413`, the closure built at that head, then under the lock `pnpm --filter @objectstack/dogfood test` with no shard and no path: - `os-verify-lock: VERDICT command-exit 0` - Test Files 427 passed | 3 skipped (430) - Tests 3556 passed | 41 skipped (3597) - no failures </details> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d9f8f7f commit adab62a

10 files changed

Lines changed: 405 additions & 21 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/service-datasource': patch
3+
---
4+
5+
fix(service-datasource)!: the datasource admin door asks the walled-catalog verdict on every row-writing verb, as the /meta door does
6+
7+
Clause-②: no (narrowing) — under the `isolated` and `group` tenancy postures, creating, changing or removing a datasource at the datasource admin routes (`POST /api/v1/datasources`, `PATCH` and `DELETE /api/v1/datasources/:name`, `POST /api/v1/datasources/:name/migrate-credential`) is a write to the environment's metadata catalog, and it is the platform operator's, as every other write to that catalog is.
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped and nothing at rest changes: which caller the datasource admin routes admit to a datasource write under a walled tenancy posture is all that moves, and every stored datasource stays as it is. -->
11+
12+
**BREAKING** accept-set narrowing at the datasource admin routes (`@objectstack/service-datasource`) under a walled tenancy posture.
13+
14+
- **The rule.** Under `isolated` and `group` every organization shares the environment's metadata catalog, and a write to it is admitted only for the platform operator and for the engine's own writes (ADR-0131 D3, D12 items 7–8, D11). A datasource is a `datasource` item of that catalog, the same record `PUT /api/v1/meta/datasource/:name` writes. So each datasource admin route that writes a datasource record (create, update, remove, migrate-credential) asks the walled-catalog verdict the `/meta` write doors ask (`walledCatalogWriteVerdict`, `@objectstack/metadata-core`) for the type `datasource`, after the `manage_platform_settings` capability gate and before the datasource service is looked up.
15+
- **The answer.** A refused call answers `403 PERMISSION_DENIED` with the verdict's sentence for a `datasource` item, the one the `/meta` write doors answer, naming the posture. Nothing is stored, no secret is sealed or removed, and no pool is rebuilt or evicted.
16+
- **Unchanged.** The platform operator writes datasources under a wall as before. Under `single`, and on a deployment with no `tenancy` service, every caller holding `manage_platform_settings` writes datasources as before. Listing, reading, the driver catalog, both connection tests, the remote-table listing and the object draft are unchanged, and the capability gate answers first, as before.
17+
- **Who moves.** On a walled deployment, a datasource create, update, removal or credential migration by a caller below the platform operator, an organization's `admin_full_access` holder included, is refused; the platform operator performs it.

‎content/docs/data-modeling/external-datasources.mdx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,12 @@ Datasources** (stamped `origin: code`, read-only in the UI) and via
157157
`GET /api/v1/datasources` and `GET /api/v1/meta/datasource`, where an admin can
158158
run the "Sync objects" wizard.
159159

160+
A datasource created in Setup (`POST /api/v1/datasources`) is a `datasource`
161+
item of the environment's metadata. Under the `group` and `isolated` tenancy
162+
postures only the platform operator creates, changes or removes one, or migrates
163+
its credential; any other caller is refused `403`, naming the posture, whatever
164+
it holds, as at the `/meta` doors ([tenancy modes](/docs/deployment/tenancy-modes)).
165+
160166
### When auto-connect fails
161167

162168
An object that binds explicitly via `datasource: '…'` has **no fallback** — it

‎content/docs/deployment/tenancy-modes.mdx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,13 @@ caller `403`, naming the posture.
8383
- **An organization that needs metadata of its own** is given an environment of
8484
its own.
8585

86+
A datasource is metadata of this kind. Under `group` and `isolated` the
87+
datasource admin routes that write one (`POST /datasources`, `PATCH` and
88+
`DELETE /datasources/:name`, and `POST /datasources/:name/migrate-credential`)
89+
are the platform operator's too: a caller holding `manage_platform_settings`
90+
inside an organization is refused `403`, naming the posture. Listing, reading
91+
and testing a datasource are unchanged.
92+
8693
Under `single` the organization is the environment, and every `manage_metadata`
8794
holder writes as before.
8895

‎packages/metadata-core/src/meta-write-capability.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,9 @@
4646
* predicate after their capability gate, {@link walledCatalogWriteVerdict}:
4747
* the `/meta` item write doors, `POST /meta/_migrate-stored`, the `/packages`
4848
* write doors, the `/automation` definition writes, `install-local`, the
49-
* external-table import (the REST route and the MCP `import_object` tool) and
50-
* the federated catalog refresh.
49+
* external-table import (the REST route and the MCP `import_object` tool),
50+
* the federated catalog refresh and the datasource admin routes that write a
51+
* datasource record (`@objectstack/service-datasource`).
5152
*
5253
* ── Refusal messages (#7450) ──────────────────────────────────────────────
5354
*
@@ -186,7 +187,9 @@ export const PLATFORM_OPERATOR_POSTURE = 'PLATFORM_ADMIN';
186187
* `install-local` (install, upgrade, uninstall), the permission-set clone
187188
* door, the external-table import on both of its doors (the REST route and
188189
* the MCP `import_object` tool, which save an `object` into the catalog), and
189-
* the federated catalog refresh (which saves an `external_catalog`). (The
190+
* the federated catalog refresh (which saves an `external_catalog`), and the
191+
* datasource admin routes that write a datasource record (create, update,
192+
* remove, migrate-credential: a `datasource` item). (The
190193
* security plugin's data door on the catalog objects asked it too,
191194
* until those objects retired — ADR-0131 D3, C3 stage 8: no `sys_position`,
192195
* `sys_permission_set` or `sys_capability` write reaches the engine, so a

‎packages/services/service-datasource/src/__tests__/admin-routes-tenancy-posture-admission.test.ts‎

Lines changed: 180 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,19 +53,33 @@
5353
* at all, which is byte-identically what the other suites in this package
5454
* still mount. Remove the fix's input and the ex-member is admitted again,
5555
* writes and all. A pin that cannot go red has measured nothing.
56+
*
57+
* §8 adds the walled-catalog rule (ADR-0131 D3, D12 items 7–8, D11): under
58+
* `isolated` and `group` a route that writes a datasource record admits only
59+
* the platform operator, whom this file declares in `OS_PLATFORM_OWNER_EMAIL`.
60+
* The write controls of §1 are therefore the operator's key.
5661
*/
5762

5863
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
5964
import { ObjectKernel, hashApiKey } from '@objectstack/core';
65+
import { walledCatalogWriteVerdict } from '@objectstack/metadata-core';
6066
import type { PluginContext } from '@objectstack/core';
6167
import { HonoHttpServer } from '@objectstack/plugin-hono-server';
6268
import { registerDatasourceAdminRoutes, DATASOURCE_ADMIN_CAPABILITY } from '../admin-routes.js';
6369
import { bindCatalogFromTables } from './security-catalog.testkit.js';
70+
// Pay the first transform of the dist-resolved driver at module load, not
71+
// inside a clocked `it()` (see `scripts/check-test-source-alias.mjs`).
72+
import '@objectstack/driver-sql';
6473

6574
const RAW_MEMBER_KEY = 'osk_15350_member';
6675
const RAW_EXMEMBER_KEY = 'osk_15350_exmember';
6776
const RAW_ORGLESS_KEY = 'osk_15350_orgless';
6877
const RAW_UNENTITLED_KEY = 'osk_15350_unentitled';
78+
/** The platform operator: declared in `OS_PLATFORM_OWNER_EMAIL` (§8). */
79+
const RAW_OPERATOR_KEY = 'osk_walled_operator';
80+
/** An organization's administrator: holds `admin_full_access` in `org_alpha` (§8). */
81+
const RAW_ORG_ADMIN_KEY = 'osk_walled_org_admin';
82+
const OPERATOR_EMAIL = 'u_operator@example.com';
6983

7084
const ORG_ALPHA = 'org_alpha';
7185
const ORG_BETA = 'org_beta';
@@ -118,17 +132,25 @@ function makeQl() {
118132
{ id: 'key_exmember', key: hashApiKey(RAW_EXMEMBER_KEY), user_id: 'u_exmember', active_organization_id: ORG_ALPHA, revoked: false },
119133
{ id: 'key_orgless', key: hashApiKey(RAW_ORGLESS_KEY), user_id: 'u_orgless', revoked: false },
120134
{ id: 'key_unentitled', key: hashApiKey(RAW_UNENTITLED_KEY), user_id: 'u_plain', active_organization_id: ORG_ALPHA, revoked: false },
135+
{ id: 'key_operator', key: hashApiKey(RAW_OPERATOR_KEY), user_id: 'u_operator', active_organization_id: ORG_ALPHA, revoked: false },
136+
{ id: 'key_org_admin', key: hashApiKey(RAW_ORG_ADMIN_KEY), user_id: 'u_org_admin', active_organization_id: ORG_ALPHA, revoked: false },
121137
],
122138
sys_member: [
123139
{ user_id: 'u_member', organization_id: ORG_ALPHA },
124140
{ user_id: 'u_exmember', organization_id: ORG_BETA },
125141
{ user_id: 'u_plain', organization_id: ORG_ALPHA },
142+
{ user_id: 'u_operator', organization_id: ORG_ALPHA },
143+
{ user_id: 'u_org_admin', organization_id: ORG_ALPHA },
126144
],
127145
sys_user: [
128146
{ id: 'u_member', email: 'u_member@example.com' },
129147
{ id: 'u_exmember', email: 'u_exmember@example.com' },
130148
{ id: 'u_orgless', email: 'u_orgless@example.com' },
131149
{ id: 'u_plain', email: 'u_plain@example.com' },
150+
// The platform operator's standing is the deployment's declaration
151+
// (`OS_PLATFORM_OWNER_EMAIL`, stubbed for this file) over a VERIFIED row.
152+
{ id: 'u_operator', email: OPERATOR_EMAIL, email_verified: true },
153+
{ id: 'u_org_admin', email: 'u_org_admin@example.com', email_verified: true },
132154
],
133155
// The grant, SYMMETRIC across the three subject principals (note 2), and
134156
// owned by the organization the stamped keys name: an organization-less
@@ -139,6 +161,9 @@ function makeQl() {
139161
{ user_id: 'u_member', permission_set_id: SHARED_SET, permission_set: 'datasource_operator', organization_id: ORG_ALPHA },
140162
{ user_id: 'u_exmember', permission_set_id: SHARED_SET, permission_set: 'datasource_operator', organization_id: ORG_ALPHA },
141163
{ user_id: 'u_orgless', permission_set_id: SHARED_SET, permission_set: 'datasource_operator', organization_id: ORG_ALPHA },
164+
// §8: the platform set, held inside one organization. It carries the
165+
// capability; under a wall it confers no platform-operator rung.
166+
{ user_id: 'u_org_admin', permission_set_id: 'ps_admin_full_access', permission_set: 'admin_full_access', organization_id: ORG_ALPHA },
142167
],
143168
sys_permission_set: [
144169
{
@@ -150,6 +175,12 @@ function makeQl() {
150175
system_permissions: JSON.stringify([DATASOURCE_ADMIN_CAPABILITY]),
151176
object_permissions: '{}',
152177
},
178+
{
179+
id: 'ps_admin_full_access',
180+
name: 'admin_full_access',
181+
system_permissions: JSON.stringify(['manage_metadata', DATASOURCE_ADMIN_CAPABILITY]),
182+
object_permissions: '{}',
183+
},
153184
],
154185
};
155186
return bindCatalogFromTables({
@@ -313,16 +344,22 @@ const listOf = (h: Harness, raw?: string) => call(h, 'GET', '/api/v1/datasources
313344
const createOf = (h: Harness, raw: string | undefined, name: string) =>
314345
call(h, 'POST', '/api/v1/datasources', raw, { name, driver: 'sqlite' });
315346
const removeOf = (h: Harness, raw?: string) => call(h, 'DELETE', '/api/v1/datasources/pg', raw);
347+
const patchOf = (h: Harness, raw?: string) => call(h, 'PATCH', '/api/v1/datasources/pg', raw, { driver: 'postgres' });
348+
const migrateOf = (h: Harness, raw?: string) => call(h, 'POST', '/api/v1/datasources/pg/migrate-credential', raw);
316349

317350
let warnSpy: ReturnType<typeof vi.spyOn>;
318351
let errorSpy: ReturnType<typeof vi.spyOn>;
319352
beforeEach(() => {
320353
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
321354
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
355+
// The deployment declares one platform operator. Only `u_operator`'s
356+
// verified row matches, so every other principal resolves as before.
357+
vi.stubEnv('OS_PLATFORM_OWNER_EMAIL', OPERATOR_EMAIL);
322358
});
323359
afterEach(() => {
324360
warnSpy.mockRestore();
325361
errorSpy.mockRestore();
362+
vi.unstubAllEnvs();
326363
});
327364

328365
const ISOLATED: Wiring = { kind: 'posture', posture: 'isolated' };
@@ -339,16 +376,18 @@ describe('[#15350] §1 — the door can serve, and the door can refuse', () => {
339376
expect(res.body?.data?.datasources?.map((d: DatasourceRow) => d.name)).toEqual(['pg']);
340377
});
341378

342-
it('CONTROL · writes REACH: a CURRENT member\'s POST lands, read back FROM THE STORE', async () => {
379+
// Under `isolated` a datasource write is the platform operator's (§8), so
380+
// the write controls are the operator's key; the member's writes are §8's.
381+
it('CONTROL · writes REACH: the platform operator\'s POST lands, read back FROM THE STORE', async () => {
343382
const h = mount(ISOLATED);
344-
const res = await createOf(h, RAW_MEMBER_KEY, 'ds_member');
383+
const res = await createOf(h, RAW_OPERATOR_KEY, 'ds_operator');
345384
expect(res.status).toBe(201);
346-
expect(h.store().filter((r) => r.name === 'ds_member')).toHaveLength(1);
385+
expect(h.store().filter((r) => r.name === 'ds_operator')).toHaveLength(1);
347386
});
348387

349-
it('CONTROL · deletes REACH: a CURRENT member\'s DELETE removes the row FROM THE STORE', async () => {
388+
it('CONTROL · deletes REACH: the platform operator\'s DELETE removes the row FROM THE STORE', async () => {
350389
const h = mount(ISOLATED);
351-
const res = await removeOf(h, RAW_MEMBER_KEY);
390+
const res = await removeOf(h, RAW_OPERATOR_KEY);
352391
expect(res.status).toBe(204);
353392
expect(h.store().filter((r) => r.name === 'pg')).toHaveLength(0);
354393
});
@@ -655,3 +694,139 @@ describe('[#15350] §7 — under `single` nothing changes', () => {
655694
expect((await listOf(h, RAW_UNENTITLED_KEY)).status).toBe(403);
656695
});
657696
});
697+
698+
// ---------------------------------------------------------------------------
699+
// §8 — [ADR-0131 D3 · D12 items 7–8 · D11] Under a wall, a datasource WRITE is
700+
// the platform operator's.
701+
//
702+
// A datasource is a `datasource` metadata item in the environment's catalog,
703+
// which every organization shares under `isolated` and `group`. Each route that
704+
// writes a datasource record asks the walled-catalog verdict for that type, the
705+
// verdict the `/meta` write doors ask for the same record. The member holds
706+
// `manage_platform_settings` and is a current member: the capability gate and
707+
// the API-key admission both pass it, so only the verdict can refuse it.
708+
// ---------------------------------------------------------------------------
709+
710+
interface WriteVerb {
711+
readonly verb: string;
712+
readonly send: (h: Harness, raw?: string) => ReturnType<typeof call>;
713+
readonly served: number;
714+
readonly method: 'createDatasource' | 'updateDatasource' | 'removeDatasource' | 'migrateCredential';
715+
/** Did the write reach the store? Read off the fixture's store, not the answer. */
716+
readonly landed: (h: Harness) => boolean;
717+
}
718+
719+
const WRITE_VERBS: readonly WriteVerb[] = [
720+
{
721+
verb: 'POST /datasources',
722+
send: (h, raw) => createOf(h, raw, 'ds_new'),
723+
served: 201,
724+
method: 'createDatasource',
725+
landed: (h) => h.store().some((r) => r.name === 'ds_new'),
726+
},
727+
{
728+
verb: 'PATCH /datasources/:name',
729+
send: patchOf,
730+
served: 200,
731+
method: 'updateDatasource',
732+
landed: (h) => h.store().find((r) => r.name === 'pg')?.driver === 'postgres',
733+
},
734+
{
735+
verb: 'DELETE /datasources/:name',
736+
send: removeOf,
737+
served: 204,
738+
method: 'removeDatasource',
739+
landed: (h) => !h.store().some((r) => r.name === 'pg'),
740+
},
741+
{
742+
verb: 'POST /datasources/:name/migrate-credential',
743+
send: migrateOf,
744+
served: 200,
745+
method: 'migrateCredential',
746+
landed: (h) => h.service.migrateCredential.mock.calls.length === 1,
747+
},
748+
];
749+
750+
/** What the `/meta` write doors answer for the same record on this posture. */
751+
const metaDoorRefusal = (posture: 'group' | 'isolated') => {
752+
const verdict = walledCatalogWriteVerdict({ type: 'datasource', tenancyPosture: posture });
753+
if (verdict.allowed) throw new Error('fixture: the verdict admits an anonymous caller under a wall');
754+
return verdict.message;
755+
};
756+
757+
describe.each(['isolated', 'group'] as const)(
758+
'[ADR-0131 D3] §8 — under `%s` every route that writes a datasource record asks the walled-catalog verdict',
759+
(posture) => {
760+
const WALLED: Wiring = { kind: 'posture', posture };
761+
// The requested posture matches the one in force, as on a real walled
762+
// deployment: no stored grant then anchors platform standing.
763+
beforeEach(() => {
764+
vi.stubEnv('OS_TENANCY_POSTURE', posture);
765+
});
766+
767+
it.each(WRITE_VERBS)('$verb: refused for a member holding the capability, and nothing is written', async (v) => {
768+
const h = mount(WALLED);
769+
const res = await v.send(h, RAW_MEMBER_KEY);
770+
expect(res.status).toBe(403);
771+
expect(res.body?.error?.code).toBe('PERMISSION_DENIED');
772+
expect(res.body?.error?.message).toBe(metaDoorRefusal(posture));
773+
expect(h.service[v.method]).not.toHaveBeenCalled();
774+
expect(v.landed(h)).toBe(false);
775+
expect(h.store()).toEqual(SEED);
776+
});
777+
778+
it.each(WRITE_VERBS)('$verb: refused for an organization\'s `admin_full_access` holder too', async (v) => {
779+
const h = mount(WALLED);
780+
const res = await v.send(h, RAW_ORG_ADMIN_KEY);
781+
expect(res.status).toBe(403);
782+
expect(res.body?.error?.code).toBe('PERMISSION_DENIED');
783+
expect(res.body?.error?.message).toBe(metaDoorRefusal(posture));
784+
expect(h.service[v.method]).not.toHaveBeenCalled();
785+
expect(h.store()).toEqual(SEED);
786+
});
787+
788+
it.each(WRITE_VERBS)('$verb: allowed for the platform operator, and the write lands', async (v) => {
789+
const h = mount(WALLED);
790+
const res = await v.send(h, RAW_OPERATOR_KEY);
791+
expect(res.status).toBe(v.served);
792+
expect(h.service[v.method]).toHaveBeenCalledTimes(1);
793+
expect(v.landed(h)).toBe(true);
794+
});
795+
796+
it('the capability gate still answers first: a caller without it gets the capability refusal', async () => {
797+
const h = mount(WALLED);
798+
const res = await createOf(h, RAW_UNENTITLED_KEY, 'ds_unentitled');
799+
expect(res.status).toBe(403);
800+
expect(res.body?.error?.code).toBe('PERMISSION_DENIED');
801+
expect(res.body?.error?.message).not.toBe(metaDoorRefusal(posture));
802+
expect(res.body?.error?.message).toContain(DATASOURCE_ADMIN_CAPABILITY);
803+
});
804+
805+
it('the routes that write no record are unchanged for the member', async () => {
806+
const h = mount(WALLED);
807+
expect((await listOf(h, RAW_MEMBER_KEY)).status).toBe(200);
808+
expect((await call(h, 'GET', '/api/v1/datasources/pg', RAW_MEMBER_KEY)).status).toBe(200);
809+
expect((await call(h, 'GET', '/api/v1/datasources/drivers', RAW_MEMBER_KEY)).status).toBe(200);
810+
expect((await call(h, 'POST', '/api/v1/datasources/test', RAW_MEMBER_KEY, { driver: 'sqlite' })).status).toBe(200);
811+
expect((await call(h, 'POST', '/api/v1/datasources/pg/test', RAW_MEMBER_KEY)).status).toBe(200);
812+
expect((await call(h, 'GET', '/api/v1/datasources/pg/remote-tables', RAW_MEMBER_KEY)).status).toBe(200);
813+
expect(
814+
(await call(h, 'POST', '/api/v1/datasources/pg/object-draft', RAW_MEMBER_KEY, { table: 'customers' })).status,
815+
).toBe(200);
816+
expect(h.store()).toEqual(SEED);
817+
});
818+
},
819+
);
820+
821+
describe.each([
822+
['single', { kind: 'posture', posture: 'single' }],
823+
['no tenancy service', { kind: 'unregistered' }],
824+
] as const)('[ADR-0131 D11] §8b — under %s the verdict is inert', (_label, wiring) => {
825+
it.each(WRITE_VERBS)('$verb: the member holding the capability writes, as before', async (v) => {
826+
const h = mount(wiring as Wiring);
827+
const res = await v.send(h, RAW_MEMBER_KEY);
828+
expect(res.status).toBe(v.served);
829+
expect(h.service[v.method]).toHaveBeenCalledTimes(1);
830+
expect(v.landed(h)).toBe(true);
831+
});
832+
});

0 commit comments

Comments
 (0)