diff --git a/.changeset/39398-setup-datasource-create-names-package.md b/.changeset/39398-setup-datasource-create-names-package.md new file mode 100644 index 00000000000..3ed116436eb --- /dev/null +++ b/.changeset/39398-setup-datasource-create-names-package.md @@ -0,0 +1,33 @@ +--- +'@objectstack/service-datasource': minor +'@objectstack/metadata-protocol': minor +'@objectstack/spec': minor +'@object-ui/app-shell': minor +--- + +fix(service-datasource): a datasource created in Setup is saved through the kernel save, into a named package, and a create naming none is refused `422 WRITABLE_PACKAGE_REQUIRED` + +Clause-②: yes (narrowing) — narrowed: a Setup datasource create naming no package is refused, and an edit of a datasource whose stored config or pool the schema refuses is refused until it sends the block corrected; widened in the same change: the `@objectstack/spec/kernel` exports `getMetadataTypeCarryForwardRetirement` and `MetadataCarryForwardRetirement` +Metadata-protocol: narrowed +Skills-docs: updated here — content/docs/data-modeling/external-datasources.mdx (a datasource created in Setup is saved into the writable package the request names; skills/** teach no Setup datasource create) + + + +**BREAKING** accept-set narrowing (ADR-0070 D1; ruling record 7408558495). + +- **Before:** `POST /api/v1/datasources` (the Setup "Datasources" create) inserted its row straight into the metadata table, bound to no package, so it was the one create door the kernel's package-less create judgment never saw. +- **Now:** the door's create, edit (`PATCH /api/v1/datasources/{name}`) and credential migration (`POST /api/v1/datasources/{name}/migrate-credential`) are saved through the kernel save, and every judge of that save answers them. A create names its package with `package` in the request body; naming none answers `422 WRITABLE_PACKAGE_REQUIRED` in this door's words, the writable packages on `error.details.writablePackages`, nothing stored and the secret sealed for the request removed again. An empty or non-string `package` answers `400 VALIDATION_ERROR`. An edit and a migration are saved in the package the row is stored in. No new exemption: the reference to the secret the door has just sealed is stated to the save by server code only (never by any HTTP or MCP door), and passes the own-reference rule only when it is the body's reference and no other stored datasource row holds it. A host with no metadata save answers `503 SERVICE_UNAVAILABLE` instead of writing the row itself. +- **Imports land with their datasource.** An object imported from a datasource added in Setup is saved in the package that datasource is stored in; from a package-less one it still lands loose. +- **Console:** the Setup datasource editor shows the refusal in the server's words with one button per writable package, and picking one sends the create again into that package. +- **Not touched:** the door's delete (`DELETE /api/v1/datasources/{name}`) still removes the row directly. + +## FROM → TO + +| FROM | TO | +|:---|:---| +| `POST /api/v1/datasources` `{ "name": "wh", "driver": "postgres", … }` | `POST /api/v1/datasources` `{ "name": "wh", "driver": "postgres", …, "package": "my_pkg" }` | +| `PATCH /api/v1/datasources/{name}` `{ "active": false }` on a datasource whose stored `config` or `pool` the schema refuses for anything but an inline credential (answered `400 DATASOURCE_ADMIN_ERROR`, naming the key) | `PATCH /api/v1/datasources/{name}` `{ "active": false, "config": { …the stored config without the key the refusal names } }` | + +One-line fix: name the writable package the new datasource belongs to; on the second arm, send the corrected `config` (or `pool`) with the edit. An edit of an existing datasource is saved in place on the body a read serves: the credentials a row stored before inline credentials were refused still holds in `config` are carried forward by the save, so its `label` and `active: false` edits keep saving, and a row whose stored config or pool the schema now refuses for any other reason is refused until the edit sends it corrected. + +- **A bound reference retires the inline credential, on every door.** A datasource save whose body binds `external.credentialsRef` no longer carries the driver's inline credential slot (`config.password`; turso's `config.authToken`) forward from the stored row: the row is written without it, and the save names each dropped position on its answer (`advisories`, rule `withheld-key-dropped`; the admin door's update answer as `droppedWithheldKeys`). With a reference bound the connect path never reads that slot. The credential migration (`POST /api/v1/datasources/{name}/migrate-credential`) therefore leaves the reference and no inline password at rest, after a restart too. Former alias spellings and a URL-embedded password are still carried forward, and the migration still reports them as `remaining`. diff --git a/content/docs/data-modeling/external-datasources.mdx b/content/docs/data-modeling/external-datasources.mdx index 47f44f7457a..e72333d99f4 100644 --- a/content/docs/data-modeling/external-datasources.mdx +++ b/content/docs/data-modeling/external-datasources.mdx @@ -158,7 +158,9 @@ Datasources** (stamped `origin: code`, read-only in the UI) and via run the "Sync objects" wizard. A datasource created in Setup (`POST /api/v1/datasources`) is a `datasource` -item of the environment's metadata. Under the `group` and `isolated` tenancy +item saved into the writable package the request names (`package` in the body); +a create naming none is refused `422 WRITABLE_PACKAGE_REQUIRED`, listing the +writable packages. Under the `group` and `isolated` tenancy postures only the platform operator creates, changes or removes one, or migrates its credential; any other caller is refused `403`, naming the posture, whatever it holds, as at the `/meta` doors ([tenancy modes](/docs/deployment/tenancy-modes)). diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-datasource.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-datasource.md index 5c6b571c681..93817b04cda 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-datasource.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-datasource.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 6 | -| Object name statically decidable | 6 | +| Write call sites | 4 | +| Object name statically decidable | 4 | | Object name chosen at run time | 0 | | Object name spelled inline | 2 | -| Object name spelled through a `const` | 4 | +| Object name spelled through a `const` | 2 | | Object name is an `object: string` parameter | 0 | | Object name is some other run-time expression | 0 | -| Against a tenancy-enabled object | 6 | +| Against a tenancy-enabled object | 4 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 6 | +| Threading a tenant context | 4 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | -| Threading a decidably elevated (`isSystem`) context | 6 | +| Threading a decidably elevated (`isSystem`) context | 4 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 0 | -| Receiver carried a readable engine type | 6 | +| Receiver carried a readable engine type | 4 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -48,7 +48,6 @@ a row or a number here — fix the code, or the census, and regenerate. | file | verb | object | tenancy | tenant context | n | |---|---|---|---|---|---:| | `packages/services/service-datasource/src/datasource-admin-plugin.ts` | `delete` | `sys_metadata` | enabled | elevated | 1 | -| `packages/services/service-datasource/src/datasource-admin-plugin.ts` | `insert` | `sys_metadata` | enabled | elevated | 1 | -| `packages/services/service-datasource/src/datasource-admin-plugin.ts` | `update` | `sys_metadata` | enabled | elevated | 2 | +| `packages/services/service-datasource/src/datasource-admin-plugin.ts` | `update` | `sys_metadata` | enabled | elevated | 1 | | `packages/services/service-datasource/src/datasource-secret-binder.ts` | `delete` | `sys_secret` | enabled | elevated | 1 | | `packages/services/service-datasource/src/datasource-secret-binder.ts` | `insert` | `sys_secret` | enabled | elevated | 1 | diff --git a/packages/metadata-protocol/src/metadata-redaction.ts b/packages/metadata-protocol/src/metadata-redaction.ts index a7e8415e90d..25e33690c24 100644 --- a/packages/metadata-protocol/src/metadata-redaction.ts +++ b/packages/metadata-protocol/src/metadata-redaction.ts @@ -49,11 +49,15 @@ * ⛔ It does NOT create cleartext, and does not migrate it out either: it * preserves what is already at rest. Getting stored cleartext OUT of the store * is #8081 item 3's migration and is deliberately not attempted here — with - * ONE exception the redactor itself declares. A position it names in - * `notCarriedForwardKeys` (#28640 ②B, ruling 6566912252: a connector's - * undeclared `auth` keys, which no door accepts and nothing reads) is never - * re-grafted, so a save of the served form drops it from the row, and the - * save names each dropped position on its answer + * TWO exceptions, both declared in `@objectstack/spec/kernel`, never named + * here. A position the redactor names in `notCarriedForwardKeys` (#28640 ②B, + * ruling 6566912252: a connector's undeclared `auth` keys, which no door + * accepts and nothing reads), and a position the type's carry-forward + * retirement names for the INCOMING body (`getMetadataTypeCarryForwardRetirement`, + * ruling record 7416154891: a datasource's inline credential slot once the + * body binds `external.credentialsRef`, which the connect path then never + * reads), are never re-grafted, so a save of the served form drops them from + * the row, and the save names each dropped position on its answer * ({@link carryForwardRedactedValuesReportingDrops}). * * ## Why nothing is stamped on the wire @@ -73,7 +77,7 @@ */ import { createHmac, randomBytes } from 'node:crypto'; -import { getMetadataTypeRedactor } from '@objectstack/spec/kernel'; +import { getMetadataTypeCarryForwardRetirement, getMetadataTypeRedactor } from '@objectstack/spec/kernel'; import type { MetadataTypeRedactor } from '@objectstack/spec/kernel'; // [#21120] The family-wide stored-metadata-body primitives — the object set, // the object predicate, the column names and the body redactor — live in @@ -105,6 +109,11 @@ function redactorFor(type: string): MetadataTypeRedactor | undefined { return getMetadataTypeRedactor(PLURAL_TO_SINGULAR[type] ?? type); } +/** The type's carry-forward retirement, resolved through the same spelling as {@link redactorFor}. */ +function carryForwardRetirementFor(type: string) { + return getMetadataTypeCarryForwardRetirement(PLURAL_TO_SINGULAR[type] ?? type); +} + /** * Whether any redactor is registered for `type`. * @@ -617,7 +626,11 @@ function planCarryForward(type: string, incoming: T, stored: unknown): { out: // [#28640 ②B] The withheld positions the redactor marks NOT carried // forward: never re-grafted, so the save drops each one the stored row // holds and the incoming body does not — and reports it (`dropped`). - const notCarriedForward = new Set(served.notCarriedForwardKeys ?? []); + // [ruling record 7416154891] …and the ones the type's retirement names for + // what the INCOMING body declares (a bound credentials reference), which + // the stored body alone cannot say on a first bind. + const retiredByIncoming = carryForwardRetirementFor(type)?.(incoming as Record) ?? []; + const notCarriedForward = new Set([...(served.notCarriedForwardKeys ?? []), ...retiredByIncoming]); const dropped: string[] = []; const unchanged = { out: incoming, landed: [] as string[], dropped }; diff --git a/packages/metadata-protocol/src/protocol-datasource-credentials-ref.ts b/packages/metadata-protocol/src/protocol-datasource-credentials-ref.ts index 244a4d11467..2af09dfea2e 100644 --- a/packages/metadata-protocol/src/protocol-datasource-credentials-ref.ts +++ b/packages/metadata-protocol/src/protocol-datasource-credentials-ref.ts @@ -9,13 +9,16 @@ * seal a new value or keep its own record's stored reference.** A credentials * reference is minted by the platform when a secret is bound (the datasource * admin door's `secret`), and the readers of a stored datasource act on - * whatever reference its row holds. This door seals nothing, so the one - * reference a save through it may name is the one its own stored row already - * holds: + * whatever reference its row holds. A save through this door seals nothing + * of its own, so the one reference it may name is the one its own stored row + * already holds, or the one reference the admin door has just sealed for this + * very write (below): * - * - a create (no stored row) naming any reference is refused; + * - a create (no stored row) naming any reference is refused, unless it is + * the server-stated minted reference; * - an edit naming a reference other than its row's, or naming one where its - * row holds none, is refused; + * row holds none, is refused, unless it is the server-stated minted + * reference; * - an edit sending back its row's own reference — the GET → edit → PUT * round trip, since the read serves the reference — keeps it, and so does a * first draft sending back the reference of the active row it overlays; @@ -41,6 +44,20 @@ * already holds (`source` set: the stored-metadata migration) keep their * pass-through, as the system principal does under the #27582 rule. * + * [ADR-0070 D1, ruling record 7408558495 (A2)] The datasource admin door, the + * one sealer of datasource credentials, writes through this save too: it seals + * the secret, then saves the record naming the new reference, and states that + * reference as `mintedCredentialsRef`, a request member server code alone sets + * (no HTTP or MCP door forwards it). That is the parent rule's "seal a new + * value" arm, at the place the sealer now saves. The body's reference passes + * only when it EQUALS the stated one and NO stored `datasource` row other than + * the one this save writes holds it (a newly minted reference is held by none), + * so the statement can never point a datasource at a reference another one + * holds. A stated reference the body does not name changes nothing: the body + * is judged as it would be without it. Only this judge reads the member; every + * other judge, the package-less create judgment included, runs as before, and + * `source` stays unset. + * * [#27818] The doors that make a STORED body the active row ask the same * judge, as `door: 'restore'` and `door: 'publish'`: the restore doors * (`rollbackMetaItem` and `revertCommit`'s restore limb, through the restore @@ -65,6 +82,44 @@ function namedCredentialsRef(body: unknown): unknown { return (external as { credentialsRef?: unknown }).credentialsRef; } +/** + * [ruling record 7408558495 (A2)] Whether a stored `datasource` row other than + * the one this save writes (`name` in `packageId`'s layer) names `credentialsRef`. + * Every state is read, drafts included: a reference a draft names is held. A + * host with no store to read answers "held", and a read that fails throws: the + * pass is never granted on a read that did not happen. + * + * The reference is compared here, not pushed into the query: it lives inside + * the serialized `metadata` body, which has no column of its own and no + * predicate that is portable across the drivers. The rows read are this + * environment's datasource rows only, and the read runs only on the + * server-stated path, when the body names the stated reference. + */ +async function heldByAnotherDatasourceRow( + engine: { find(object: string, query: Record): Promise } | undefined, + credentialsRef: string, + name: string, + packageId: string | null, +): Promise { + if (typeof engine?.find !== 'function') return true; + // A read that fails throws to the save, which answers it: never a pass. + const rows = await engine.find('sys_metadata', { where: { type: 'datasource' }, context: { isSystem: true } }); + if (!Array.isArray(rows)) return true; + for (const row of rows as Array>) { + if (row?.name === name && ((row.package_id as string | null | undefined) ?? null) === packageId) continue; + let body: unknown = row?.metadata; + if (typeof body === 'string') { + try { + body = JSON.parse(body); + } catch { + return true; + } + } + if (namedCredentialsRef(body) === credentialsRef) return true; + } + return false; +} + /** * The refusal a `datasource` save owes when its body names an * `external.credentialsRef` its own stored row does not hold, else `undefined`. @@ -87,6 +142,17 @@ export async function datasourceCredentialsRefSaveRefusal(args: { * refusal's words, never what is judged. */ door?: 'restore' | 'publish'; + /** + * [ruling record 7408558495 (A2)] The reference the datasource admin door + * has just minted for this write (`mintedCredentialsRef` on the save + * request), stated by server code only. See the module header. + */ + mintedCredentialsRef?: string; + /** + * The store, read only when a minted reference is stated and the body + * names it: the "no other row holds it" half of the pass. + */ + engine?: { find(object: string, query: Record): Promise }; }): Promise<(Error & { code: 'VALIDATION_ERROR'; status: 400 }) | undefined> { if (args.type !== 'datasource' || args.source !== undefined) return undefined; const named = namedCredentialsRef(args.item); @@ -101,6 +167,14 @@ export async function datasourceCredentialsRefSaveRefusal(args: { } const own = namedCredentialsRef(head?.body); if (typeof own === 'string' && own === named) return undefined; + if ( + typeof args.mintedCredentialsRef === 'string' + && args.mintedCredentialsRef !== '' + && named === args.mintedCredentialsRef + && !(await heldByAnotherDatasourceRow(args.engine, named, args.name, target.packageId ?? null)) + ) { + return undefined; + } const adminDoor = `To bind a credential, send the secret to the datasource admin door instead (Setup → Datasources, ` + `\`POST /api/v1/datasources\` or \`PATCH /api/v1/datasources/${args.name}\`).`; const why = 'because a reference is minted by the platform when a secret is bound.'; diff --git a/packages/metadata-protocol/src/protocol-door-requests.ts b/packages/metadata-protocol/src/protocol-door-requests.ts index 424385e68d2..547bafc7e82 100644 --- a/packages/metadata-protocol/src/protocol-door-requests.ts +++ b/packages/metadata-protocol/src/protocol-door-requests.ts @@ -28,6 +28,18 @@ type SaveMetaItemRequest = { * already holds. Set by server code only; no HTTP door forwards it. */ inheritedGrantObjects?: readonly string[], + /** + * [ADR-0070 D1, ruling record 7408558495 (A2)] The `external.credentialsRef` + * the datasource admin door has just minted for this write by sealing a + * secret (`POST /api/v1/datasources`, its `PATCH` with a secret, and the + * credential migration). Read by the own-reference judge alone + * ({@link datasourceCredentialsRefSaveRefusal}): a `datasource` body naming + * exactly this reference passes when no other stored datasource row holds + * it. Every other judge still runs, the package-less create judgment + * included, and `source` stays unset. Set by server code only; no HTTP or + * MCP door forwards it. + */ + mintedCredentialsRef?: string, /** * [#38174, ruling 7380917604 (A)] The fifth named exemption from the * package-less create refusal: a create the organization-ownership diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 41868d9be9d..a355c0fa25d 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -1952,7 +1952,7 @@ export class ProtocolSaveFacet { const repo = host.getOverlayRepo(); const credentialsRefRefusal = await datasourceCredentialsRefSaveRefusal({ headAt: (...a) => repo.headAt(...a), type: singularType, name: request.name, item: request.item, - mode, packageId: request.packageId, source: request.source, + mode, packageId: request.packageId, source: request.source, mintedCredentialsRef: request.mintedCredentialsRef, engine: host.engine, }); if (credentialsRefRefusal) throw credentialsRefRefusal; } diff --git a/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts b/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts index 212da097cf3..ddd8a166855 100644 --- a/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts +++ b/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts @@ -29,6 +29,7 @@ import { describe, expect, it } from 'vitest'; // [#5619] The producer's own dispatch decisions, so the stub cannot accept a call ObjectQL refuses. import { assertEngineFindOnePredicate, assertEngineUpdateDispatch, hashSpec } from '@objectstack/metadata-core'; +import { getMetadataTypeRedactor } from '@objectstack/spec/kernel'; import { ObjectStackProtocolImplementation } from './protocol.js'; import type { MetadataWriteFace } from './protocol.js'; // Pays these dist-resolved deps' first load at collection, never inside a clocked case. @@ -276,3 +277,239 @@ describe('[#27762] datasource `external.credentialsRef`: a non-system save may o }); }); }); + +/** A reference the datasource admin door has just minted: no stored row holds it. */ +const MINTED_REF = 'sys_secret:minted_39398'; + +describe('[ADR-0070 D1, ruling record 7408558495 (A2)] the admin door\'s minted reference, stated by server code', () => { + describe('accepted: the body names exactly the stated reference and no other stored row holds it', () => { + it('a create into a package stores the minted reference with the row', async () => { + const s = session(); + await s.protocol.saveMetaItem({ + type: 'datasource', name: 'fresh', packageId: TEST_PKG, parentVersion: null, + item: { ...datasourceBody('fresh', 'Fresh', MINTED_REF), origin: 'runtime' }, mintedCredentialsRef: MINTED_REF, + }); + expect(rowOf(s.rows, 'fresh')?.package_id).toBe(TEST_PKG); + expect(storedRefOf(s.rows, 'fresh')).toBe(MINTED_REF); + expect(JSON.parse(rowOf(s.rows, 'fresh')!.metadata).origin).toBe('runtime'); + }); + + it('an edit of a row holding its old reference, and a first bind on a row holding none', async () => { + const s = session(); + await s.protocol.saveMetaItem({ + type: 'datasource', name: 'ledger', item: datasourceBody('ledger', 'Ledger', MINTED_REF), mintedCredentialsRef: MINTED_REF, + }); + expect(storedRefOf(s.rows, 'ledger')).toBe(MINTED_REF); + const second = 'sys_secret:minted_39398_b'; + await s.protocol.saveMetaItem({ + type: 'datasource', name: 'plain', item: datasourceBody('plain', 'Plain', second), mintedCredentialsRef: second, + }); + expect(storedRefOf(s.rows, 'plain')).toBe(second); + }); + }); + + describe('every other judge still runs, and nothing is written', () => { + it('a create naming no package is still 422 WRITABLE_PACKAGE_REQUIRED', async () => { + const s = session(); + const r = await refused(s, { + type: 'datasource', name: 'fresh', parentVersion: null, + item: datasourceBody('fresh', 'Fresh', MINTED_REF), mintedCredentialsRef: MINTED_REF, + }); + expect({ code: r.code, status: r.status }, r.message).toEqual({ code: 'WRITABLE_PACKAGE_REQUIRED', status: 422 }); + }); + + it('a body reference other than the stated one is still 400', async () => { + const s = session(); + expectRuleRefusal(await refused(s, { + type: 'datasource', name: 'fresh', packageId: TEST_PKG, + item: datasourceBody('fresh', 'Fresh', UNHELD_REF), mintedCredentialsRef: MINTED_REF, + })); + expectRuleRefusal(await refused(s, { + type: 'datasource', name: 'ledger', item: datasourceBody('ledger', 'Ledger', OTHER_REF), mintedCredentialsRef: MINTED_REF, + })); + }); + + it('(A2) a stated reference another stored datasource row holds is refused 400, as an unstated one is', async () => { + const s = session(); + expectRuleRefusal(await refused(s, { + type: 'datasource', name: 'fresh', packageId: TEST_PKG, + item: datasourceBody('fresh', 'Fresh', OTHER_REF), mintedCredentialsRef: OTHER_REF, + })); + expectRuleRefusal(await refused(s, { + type: 'datasource', name: 'plain', item: datasourceBody('plain', 'Plain', OWN_REF), mintedCredentialsRef: OWN_REF, + })); + }); + + it('the reference written into the body, not stated by the caller, passes nothing', async () => { + const s = session(); + const before = snapshot(s.rows); + const caught: any = await s.protocol.saveMetaItem({ + type: 'datasource', name: 'fresh', packageId: TEST_PKG, + item: { ...datasourceBody('fresh', 'Fresh', UNHELD_REF), mintedCredentialsRef: UNHELD_REF }, + }).then(() => undefined, (err: unknown) => err); + expect(caught, 'the save was accepted').toBeDefined(); + expect([caught.code, caught.status], String(caught.message)).toEqual(['INVALID_METADATA', 422]); + expect(snapshot(s.rows)).toBe(before); + }); + + it('(A2) a reference only a draft row holds is held', async () => { + const s = session(); + const draftRef = 'sys_secret:held_by_a_draft_39398'; + await s.protocol.saveMetaItem({ + type: 'datasource', name: 'vault', mode: 'draft', item: datasourceBody('vault', 'Vault', draftRef), mintedCredentialsRef: draftRef, + }); + expect(storedRefOf(s.rows, 'vault', 'draft')).toBe(draftRef); + expectRuleRefusal(await refused(s, { + type: 'datasource', name: 'fresh', packageId: TEST_PKG, + item: datasourceBody('fresh', 'Fresh', draftRef), mintedCredentialsRef: draftRef, + })); + }); + }); +}); + +/** + * A row stored before #8078: cleartext in `config` under the canonical key, a + * former alias spelling and a URL userinfo password, each refused by the + * datasource schema today. + */ +const LEGACY_CONFIG = { + host: 'db.internal', + database: 'legacy', + username: 'app', + password: 'hunter2', + passwd: 'alias-secret', + url: 'postgresql://app:url-secret@db.internal/legacy', +}; +const legacyBody = () => ({ name: 'legacy', label: 'Legacy', driver: 'postgres', origin: 'runtime', config: { ...LEGACY_CONFIG } }); + +function legacySession() { + const s = session(); + const where = { type: 'datasource', name: 'legacy', organization_id: null, package_id: null, state: 'active' }; + const body = legacyBody(); + s.rows.set(keyOf(where), { id: 'r_seed_legacy', ...where, metadata: JSON.stringify(body), checksum: hashSpec(body), version: 1 }); + return s; +} + +const storedBodyOf = (rows: Map, name: string) => JSON.parse(rowOf(rows, name)!.metadata); + +describe('[#39398 M1] the admin door\'s edit of a legacy row: the served form, saved on the real save', () => { + it('control: the at-rest body itself, with a new label, is refused 422 INVALID_METADATA and nothing is written', async () => { + const s = legacySession(); + const before = snapshot(s.rows); + const caught: any = await s.protocol.saveMetaItem({ + type: 'datasource', name: 'legacy', item: { ...legacyBody(), label: 'Legacy (edited)' }, + }).then(() => undefined, (err: unknown) => err); + expect(caught, 'the save was accepted').toBeDefined(); + expect([caught.code, caught.status], String(caught.message)).toEqual(['INVALID_METADATA', 422]); + expect(snapshot(s.rows)).toBe(before); + }); + + it('the door\'s served form is what a read serves for the row', async () => { + const s = legacySession(); + const { _diagnostics, ...served }: any = (await s.protocol.getMetaItem({ type: 'datasource', name: 'legacy' })).item; + expect(getMetadataTypeRedactor('datasource')!(legacyBody()).item).toEqual(served); + expect(Object.keys(served.config).sort()).toEqual(['database', 'host', 'url', 'username']); + }); + + const edits: Array<[string, Record]> = [ + ['a label edit', { label: 'Legacy (edited)' }], + ['`active: false`', { active: false }], + ]; + for (const [edit, patch] of edits) { + it(`${edit} saves, and every credential the row holds is carried forward`, async () => { + const s = legacySession(); + const servedForm = getMetadataTypeRedactor('datasource')!(legacyBody()).item; + await s.protocol.saveMetaItem({ type: 'datasource', name: 'legacy', item: { ...servedForm, ...patch } }); + const stored = storedBodyOf(s.rows, 'legacy'); + expect(stored).toMatchObject(patch); + expect(stored.config).toEqual(LEGACY_CONFIG); + }); + } +}); + +/** Seeds one package-less runtime row under `name` with exactly `body`. */ +function seedBody(rows: Map, name: string, body: Record) { + const where = { type: 'datasource', name, organization_id: null, package_id: null, state: 'active' }; + rows.set(keyOf(where), { id: `r_seed_${name}`, ...where, metadata: JSON.stringify(body), checksum: hashSpec(body), version: 1 }); +} + +/** The positions an answer names as dropped (`withheld-key-dropped`), in the advisory's own path spelling. */ +const droppedOn = (answer: unknown) => + (((answer as { advisories?: Array<{ rule?: string; path?: string }> })?.advisories) ?? []) + .filter((a) => a.rule === 'withheld-key-dropped') + .map((a) => a.path); + +const servedFormOf = (body: Record) => getMetadataTypeRedactor('datasource')!(body).item; + +describe('[ruling record 7416154891, F1 A] a body that binds a credentials reference does not get the inline credential slot carried forward', () => { + const bothBody = () => ({ ...legacyBody(), name: 'both', external: { credentialsRef: OWN_REF } }); + + it('/meta GET → edit → PUT of a row holding a reference and an inline copy: the copy is dropped and named; the aliases and the URL password are carried', async () => { + const s = session(); + seedBody(s.rows, 'both', bothBody()); + const served: any = (await s.protocol.getMetaItem({ type: 'datasource', name: 'both' })).item; + const { _diagnostics, ...item } = served; + + const answer = await s.protocol.saveMetaItem({ type: 'datasource', name: 'both', item: { ...item, label: 'Both (edited)' } }); + + const stored = storedBodyOf(s.rows, 'both'); + const { password: _dropped, ...kept } = LEGACY_CONFIG; + expect(stored.config).toEqual(kept); + expect(stored.external).toEqual({ credentialsRef: OWN_REF }); + expect(rowOf(s.rows, 'both')!.metadata).not.toContain('hunter2'); + expect(droppedOn(answer)).toEqual(['datasources[0].config.password']); + }); + + it('the credential migration\'s body (served form, the minted reference bound and stated): the stored row holds the reference and no inline password', async () => { + const s = legacySession(); + const { password: _bound, ...rest } = LEGACY_CONFIG; + const migrated = { ...legacyBody(), config: rest, external: { credentialsRef: MINTED_REF } }; + + const answer = await s.protocol.saveMetaItem({ + type: 'datasource', name: 'legacy', item: servedFormOf(migrated), mintedCredentialsRef: MINTED_REF, + }); + + const stored = storedBodyOf(s.rows, 'legacy'); + expect(stored.config).toEqual(rest); + expect(stored.external).toEqual({ credentialsRef: MINTED_REF }); + expect(rowOf(s.rows, 'legacy')!.metadata).not.toContain('hunter2'); + expect(droppedOn(answer)).toEqual(['datasources[0].config.password']); + + // A restart reads the row at rest: a fresh save door serves it clean. + const restarted = new ObjectStackProtocolImplementation(s.engine); + const { _diagnostics, ...reread }: any = (await restarted.getMetaItem({ type: 'datasource', name: 'legacy' })).item; + expect(reread).toEqual(servedFormOf(stored)); + expect(reread.external).toEqual({ credentialsRef: MINTED_REF }); + }); + + it('control: the same body with no reference bound keeps the inline credential, and names no drop', async () => { + const s = legacySession(); + const answer = await s.protocol.saveMetaItem({ type: 'datasource', name: 'legacy', item: { ...servedFormOf(legacyBody()), label: 'Legacy (edited)' } }); + expect(storedBodyOf(s.rows, 'legacy').config).toEqual(LEGACY_CONFIG); + expect(droppedOn(answer)).toEqual([]); + }); +}); + +describe('[ruling record 7416154891, F2 A] a row the schema refuses for a non-credential key saves once the edit sends the config corrected', () => { + const residueBody = () => ({ ...legacyBody(), name: 'residue', config: { ...LEGACY_CONFIG, legacyOption: 'x' } }); + + it('`active: false` alone is refused; with the config sent without the refused key it saves, and the credentials are carried forward', async () => { + const s = session(); + seedBody(s.rows, 'residue', residueBody()); + const served = servedFormOf(residueBody()) as { config: Record }; + + const before = snapshot(s.rows); + const caught: any = await s.protocol.saveMetaItem({ type: 'datasource', name: 'residue', item: { ...served, active: false } }) + .then(() => undefined, (err: unknown) => err); + expect([caught?.code, caught?.status], String(caught?.message)).toEqual(['INVALID_METADATA', 422]); + expect(String(caught.message)).toContain('legacyOption'); + expect(snapshot(s.rows)).toBe(before); + + const { legacyOption: _refused, ...corrected } = served.config; + await s.protocol.saveMetaItem({ type: 'datasource', name: 'residue', item: { ...served, config: corrected, active: false } }); + + const stored = storedBodyOf(s.rows, 'residue'); + expect(stored.active).toBe(false); + expect(stored.config).toEqual(LEGACY_CONFIG); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.minted-credentials-ref-wire-39398.test.ts b/packages/metadata-protocol/src/protocol.minted-credentials-ref-wire-39398.test.ts new file mode 100644 index 00000000000..1990881f56a --- /dev/null +++ b/packages/metadata-protocol/src/protocol.minted-credentials-ref-wire-39398.test.ts @@ -0,0 +1,53 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#39398, ADR-0070 D1, ruling record 7408558495 (A2), premise 2] The wire's + * save request has no `mintedCredentialsRef`. + * + * The own-reference judge (`protocol-datasource-credentials-ref.ts`) lets a + * datasource body's `external.credentialsRef` through when it equals the + * reference the caller states as `mintedCredentialsRef` and no other stored + * datasource row holds it. The pass is sound only while that statement comes + * from server code that has just sealed the secret: the datasource admin door + * (`@objectstack/service-datasource`). The member is declared on this + * package's own request type (`protocol-door-requests.ts`) and nowhere on the + * published one, `SaveMetaItemRequestSchema` in `@objectstack/spec/api`, which + * is the shape the REST `/meta` route builds its request against, field by + * field, so an undeclared member there is a compile error. + * + * What is pinned: + * - (a) the published request type refuses the member: a request literal + * naming it does not compile (the `@ts-expect-error` below fails the + * package's typecheck the day the member is published); + * - (b) the published schema drops it: a parsed request carries no + * `mintedCredentialsRef`, whatever the client sent; + * - (c) the body is no channel for it either: an `item` that carries the + * member is refused on the real save, beside the minted pass, in + * `protocol.datasource-credentials-ref-own-reference.test.ts`. + */ + +import { describe, expect, it } from 'vitest'; +import { SaveMetaItemRequestSchema, type SaveMetaItemRequest as PublishedSaveMetaItemRequest } from '@objectstack/spec/api'; + +const MEMBER = 'mintedCredentialsRef'; + +describe('[#39398, ruling record 7408558495 (A2)] the published save request has no `mintedCredentialsRef`', () => { + it('(a) the published request type refuses a literal naming it', () => { + const request: PublishedSaveMetaItemRequest = { + type: 'datasource', + name: 'warehouse', + item: {}, + // @ts-expect-error -- the published save request declares no minted reference (ruling record 7408558495). + mintedCredentialsRef: 'sys_secret:from_the_wire', + }; + expect(request.type).toBe('datasource'); + }); + + it('(b) the published schema drops it from a parsed request', () => { + const parsed = SaveMetaItemRequestSchema.parse({ + type: 'datasource', name: 'warehouse', item: {}, [MEMBER]: 'sys_secret:from_the_wire', + }) as Record; + expect(MEMBER in parsed).toBe(false); + expect(Object.keys(SaveMetaItemRequestSchema.shape)).not.toContain(MEMBER); + }); +}); diff --git a/packages/metadata-protocol/src/registry-question.ts b/packages/metadata-protocol/src/registry-question.ts index d5085eb8467..567cce4f00b 100644 --- a/packages/metadata-protocol/src/registry-question.ts +++ b/packages/metadata-protocol/src/registry-question.ts @@ -112,6 +112,7 @@ export const REGISTRY_QUESTION_PRODUCERS: readonly RegistryQuestionProducer[] = { file: 'packages/runtime/src/domains/packages.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a package publish/unpublish flips each of its apps\' visibility: writes an app, never an object.' }, { file: 'packages/runtime/src/domains/permission-set-clone.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a permission-set clone writes a permission set, never an object.' }, { file: 'packages/services/service-datasource/src/plugin.ts', callee: 'saveMetaItem', calls: 1, question: 'by-face', why: 'face `external-import`: one datasource table imported as one object, its refusal relayed to the caller: against the registry.' }, + { file: 'packages/services/service-datasource/src/datasource-record-save.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'the Setup datasource door (create, edit, credential migration) writes a datasource record, never an object, and states no face.' }, { file: 'packages/services/service-automation/src/flow-credential-migration.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a stored-flow migration pass writes flows, never an object.' }, { file: 'packages/metadata-protocol/src/protocol-package-commits.ts', callee: 'saveMetaItem', calls: 2, question: 'body-only', why: 'faces `package-duplicate` and `package-unmanaged-import`: a package copied or imported row by row (batch); its objects are judged as one unit after the loop.' }, { file: 'packages/metadata-protocol/src/protocol-packageless-overlay-migration.ts', callee: 'saveMetaItem', calls: 2, question: 'body-only', why: 'the packageless overlay migration rewrites stored rows (batch).' }, diff --git a/packages/qa/dogfood/test/datasource-meta-door-reaches-admin-door.dogfood.test.ts b/packages/qa/dogfood/test/datasource-meta-door-reaches-admin-door.dogfood.test.ts index d92b67c762b..be87284cd53 100644 --- a/packages/qa/dogfood/test/datasource-meta-door-reaches-admin-door.dogfood.test.ts +++ b/packages/qa/dogfood/test/datasource-meta-door-reaches-admin-door.dogfood.test.ts @@ -46,6 +46,9 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { ensurePair } from './customization-pair.js'; +import { DatasourceAdminServicePlugin } from '@objectstack/service-datasource'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { assertEngineFindOnePredicate, assertEngineUpdateDispatch, hashSpec } from '@objectstack/metadata-core'; /** [#38174] The writable package this file's new items are created in. */ const PAIR_PKG = 'com.example.showcase.custom'; @@ -192,7 +195,8 @@ describe('[#21923] the metadata door and the admin door agree on a runtime datas }); it('a datasource the admin door creates is edited and removed through the metadata door, and the removal leaves the admin door', async () => { - const created = await call('POST', '/datasources', sqliteBody(ADMIN_RT, 'Admin Runtime 21923')); + // [#39398, ADR-0070 D1] A create names the package it is saved in. + const created = await call('POST', '/datasources', { ...sqliteBody(ADMIN_RT, 'Admin Runtime 21923'), package: PAIR_PKG }); expect(created.status, JSON.stringify(created.json)).toBe(201); expect(connectVerdict(ADMIN_RT)).toBe('connected'); @@ -242,3 +246,223 @@ describe('[#21923] the metadata door and the admin door agree on a runtime datas expect(await adminEntry(EXTERNAL)).toMatchObject({ origin: 'code' }); }); }); + +// [#39398, ruling record 7416154891 (F1 A, F2 A)] The admin door's credential +// migration and edits over the REAL kernel save (`ObjectStackProtocolImplementation`), +// read at the STORED ROW and again after a restart. The showcase composition +// wires no secret binder, so these cases compose the door in-process: the real +// save over one `sys_metadata` table, the admin plugin with a readable binder. +describe('[#39398, ruling 7416154891] the admin door over the real kernel save: the row at rest', () => { + type Row = Record; + const keyOf = (r: Row) => `${r.type}|${r.name}|${r.state ?? 'active'}|${r.package_id ?? ''}`; + const matches = (r: Row, where: Row = {}) => Object.entries(where).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`stub engine: no '${k}' combinator`); + return v === undefined || (v !== null && typeof v === 'object' && Array.isArray((v as { $in?: unknown }).$in) + ? (v as { $in: unknown[] }).$in.includes(r[k]) + : r[k] === v); + }); + + /** One `sys_metadata` table both the save and the door read, kept across restarts. */ + function table() { + const rows = new Map(); + const drivers = new Map(); + let nextId = 0; + const findRow = (where: Row) => [...rows.entries()].find(([, r]) => matches(r, where)); + const engine: any = { + async findOne(object: string, opts: { where: Row }) { + assertEngineFindOnePredicate(object, opts); + return object === 'sys_metadata' ? (findRow(opts.where)?.[1] ?? null) : null; + }, + async find(object: string, opts: { where?: Row; limit?: number }) { + if (object !== 'sys_metadata') return []; + const hits = [...rows.values()].filter((r) => matches(r, opts?.where)); + return typeof opts?.limit === 'number' ? hits.slice(0, opts.limit) : hits; + }, + async insert(object: string, data: Row) { + if (object !== 'sys_metadata') return { id: 'side_table' }; + const row = { id: `r_${++nextId}`, ...data }; + rows.set(keyOf(row), row); + return { id: row.id }; + }, + async update(object: string, data: Row, opts: { where: Row }) { + assertEngineUpdateDispatch(data, opts); + if (object !== 'sys_metadata') return { id: null }; + const found = findRow(opts.where); + if (!found) return { id: null }; + const merged = { ...found[1], ...data }; + rows.delete(found[0]); + rows.set(keyOf(merged), merged); + return { id: found[1].id }; + }, + async transaction(cb: (ctx: unknown, info: { owned: boolean }) => Promise): Promise { + return cb(undefined, { owned: true }); + }, + async syncObjectSchema() { /* no DDL */ }, + registerDriver: (driver: { name: string }) => void drivers.set(driver.name, driver), + unregisterDriver: (name: string) => drivers.delete(name), + getDriverByName: (name: string) => drivers.get(name), + registerDatasourceDef() {}, + markDatasourceUnavailable() {}, + clearDatasourceUnavailable() {}, + registry: { + listItems: () => [], + isPackageDisabled: () => false, + getItem: () => undefined, + registerItem: () => {}, + registerObject: () => {}, + getPackage: () => undefined, + }, + }; + return { rows, engine }; + } + + /** A binder whose sealed values outlive a restart, so a second run can read the reference back. */ + function binder() { + const live = new Map(); + let seq = 0; + return { + live, + bind: async (input: { value: string }, hint: { name: string }) => { + const ref = `sys_secret:${hint.name}_${++seq}`; + live.set(ref, input.value); + return ref; + }, + unbind: async (ref: string) => void live.delete(ref), + resolve: async (ref: string) => live.get(ref), + }; + } + + /** A factory that builds an inert driver for every datasource, so a boot's pools open. */ + const factory = { + supports: () => true, + create: async (spec: { name: string }) => ({ driver: { name: spec.name } as never, connect: async () => {}, disconnect: async () => {} }), + }; + + interface AdminDoor { + migrateCredential(name: string): Promise>; + updateDatasource(name: string, patch: Row, secret?: { value: string }): Promise>; + getDatasource(name: string): Promise | undefined>; + } + + /** One boot (and a restart is another): the real save and the admin plugin over `store`. */ + async function boot(store: ReturnType, secrets: ReturnType) { + const registry = new Map(); + const metadata = { + get: async (_t: string, n: string) => registry.get(n), + list: async () => [...registry.values()], + register: async (_t: string, n: string, d: unknown) => void registry.set(n, d), + unregister: async (_t: string, n: string) => void registry.delete(n), + }; + const services: Record = { + metadata, + data: store.engine, + protocol: new ObjectStackProtocolImplementation(store.engine), + }; + const ctx: any = { + getService: (name: string) => { + if (name in services) return services[name]; + throw new Error(`no service ${name}`); + }, + registerService: (name: string, svc: unknown) => void (services[name] = svc), + trigger: async () => {}, + logger: { warn() {}, info() {}, error() {}, debug() {} }, + }; + const plugin = new DatasourceAdminServicePlugin({ driverFactory: factory as never, secrets }); + await plugin.init(ctx); + await plugin.start(ctx); + return { door: services['datasource-admin'] as AdminDoor, registry }; + } + + /** A row stored before inline credentials were refused: cleartext under the slot and under a former alias. */ + const legacy = (name: string, extra: Row = {}) => ({ + name, label: name, origin: 'runtime', driver: 'postgres', + config: { host: 'db.internal', database: name, username: 'app', password: 'hunter2', passwd: 'alias-secret', ...extra }, + }); + function seed(store: ReturnType, body: Row) { + const row = { id: `seed_${body.name}`, type: 'datasource', name: body.name, organization_id: null, package_id: null, state: 'active', version: 1, metadata: JSON.stringify(body), checksum: hashSpec(body) }; + store.rows.set(keyOf(row), row); + } + const atRest = (store: ReturnType, name: string) => { + const row = [...store.rows.values()].find((r) => r.type === 'datasource' && r.name === name && r.state === 'active'); + return { text: String(row?.metadata), body: JSON.parse(String(row?.metadata)) }; + }; + + it('a credential migration leaves the reference and no inline password at rest; a restart serves the clean row; a second run answers already-bound', async () => { + const store = table(); + const secrets = binder(); + const { passwd: _alias, ...config } = legacy('legacy_ds').config; + seed(store, { ...legacy('legacy_ds'), config }); + const first = await boot(store, secrets); + + const result = await first.door.migrateCredential('legacy_ds'); + + expect(result).toMatchObject({ status: 'migrated', migratedKey: 'password', reusedExistingSecret: false }); + const row = atRest(store, 'legacy_ds'); + expect(row.text).not.toContain('hunter2'); + expect(row.body.config).toEqual({ host: 'db.internal', database: 'legacy_ds', username: 'app' }); + expect(secrets.live.get(row.body.external.credentialsRef)).toBe('hunter2'); + + const second = await boot(store, secrets); + expect(await second.door.getDatasource('legacy_ds')).toMatchObject({ hasSecret: true, redactedConfigKeys: [] }); + expect((second.registry.get('legacy_ds') as { config: Row }).config).not.toHaveProperty('password'); + expect(await second.door.migrateCredential('legacy_ds')).toMatchObject({ status: 'already-bound' }); + expect(atRest(store, 'legacy_ds').text).toBe(row.text); + }); + + it('a migration of a row that also holds a former alias: the alias is carried forward at rest and reported remaining', async () => { + const store = table(); + seed(store, legacy('alias_ds')); + const { door } = await boot(store, binder()); + + expect(await door.migrateCredential('alias_ds')).toMatchObject({ status: 'migrated', migratedKey: 'password', remaining: ['passwd'] }); + const row = atRest(store, 'alias_ds'); + expect(row.body.config).toEqual({ host: 'db.internal', database: 'alias_ds', username: 'app', passwd: 'alias-secret' }); + expect(row.text).not.toContain('hunter2'); + }); + + it('a label edit of a row holding a reference and an inline copy drops the copy at rest and names it on its answer', async () => { + const store = table(); + const secrets = binder(); + const ref = await secrets.bind({ value: 'bound-secret' }, { name: 'edited_ds' }); + seed(store, { ...legacy('edited_ds'), external: { credentialsRef: ref } }); + const { door, registry } = await boot(store, secrets); + + const summary = await door.updateDatasource('edited_ds', { label: 'Edited' }); + + expect(summary).toMatchObject({ label: 'Edited', droppedWithheldKeys: ['config.password'] }); + const row = atRest(store, 'edited_ds'); + expect(row.text).not.toContain('hunter2'); + expect(row.body.config).toHaveProperty('passwd', 'alias-secret'); + expect(row.body.external).toEqual({ credentialsRef: ref }); + expect((registry.get('edited_ds') as { config: Row }).config).not.toHaveProperty('password'); + }); + + it('control: a label edit on a row with no reference keeps the inline credential at rest and names no drop', async () => { + const store = table(); + seed(store, legacy('kept_ds')); + const { door } = await boot(store, binder()); + + const summary = await door.updateDatasource('kept_ds', { label: 'Kept' }); + + expect(summary).not.toHaveProperty('droppedWithheldKeys'); + expect(atRest(store, 'kept_ds').body).toMatchObject({ label: 'Kept', config: { password: 'hunter2', passwd: 'alias-secret' } }); + }); + + it('(F2) `active: false` on a row whose config holds a key the schema refuses is refused; sent with the config corrected, it saves', async () => { + const store = table(); + seed(store, legacy('residue_ds', { legacyOption: 'x' })); + const { door } = await boot(store, binder()); + + const refused = await door.updateDatasource('residue_ds', { active: false }).then(() => undefined, (err: unknown) => err as { code?: string; message?: string }); + expect(refused?.code, refused?.message).toBe('INVALID_METADATA'); + expect(String(refused?.message)).toContain('legacyOption'); + expect(atRest(store, 'residue_ds').body.active).toBeUndefined(); + + const corrected = { host: 'db.internal', database: 'residue_ds', username: 'app' }; + await door.updateDatasource('residue_ds', { active: false, config: corrected }); + + const row = atRest(store, 'residue_ds').body; + expect(row.active).toBe(false); + expect(row.config).toEqual({ ...corrected, password: 'hunter2', passwd: 'alias-secret' }); + }); +}); diff --git a/packages/qa/dogfood/test/datasource-restore-code-wins.dogfood.test.ts b/packages/qa/dogfood/test/datasource-restore-code-wins.dogfood.test.ts index 99b9e1ed511..eb3ddabf572 100644 --- a/packages/qa/dogfood/test/datasource-restore-code-wins.dogfood.test.ts +++ b/packages/qa/dogfood/test/datasource-restore-code-wins.dogfood.test.ts @@ -213,8 +213,10 @@ describe('[#21922 / #21944] a stored datasource row never displaces a code datas it('after a restart over a stored row under each code name: the admin door serves code, refuses the edit, and no pool opens from a row', async () => { // A runtime datasource with no code twin, created before the restart. + // [#39398, ADR-0070 D1] A create names the package it is saved in. const created = await call('POST', '/datasources', { name: RUNTIME, label: 'Runtime 21922', driver: 'sqlite', config: { filename: join(dir, 'rt.db') }, + package: await ensurePair(stack, token, 'com.example.showcase'), }); expect(created.status, JSON.stringify(created.json)).toBe(201); diff --git a/packages/qa/dogfood/test/datasource-restore-environment-rows.dogfood.test.ts b/packages/qa/dogfood/test/datasource-restore-environment-rows.dogfood.test.ts index 54900ddca05..a3c5687ed55 100644 --- a/packages/qa/dogfood/test/datasource-restore-environment-rows.dogfood.test.ts +++ b/packages/qa/dogfood/test/datasource-restore-environment-rows.dogfood.test.ts @@ -137,8 +137,9 @@ describe('[#22835] the datasource-admin plugin reads environment rows only (show it('the writes\' by-name reads address the environment\'s rows', async () => { // An admin create writes an environment row; its remove takes that row // away again. + // [#39398, ADR-0070 D1] A create names the package it is saved in. const created = await call('POST', '/datasources', { - name: FRESH, label: 'Admin create 22835', driver: 'sqlite', config: { filename: join(dir, 'admin.db') }, + name: FRESH, label: 'Admin create 22835', driver: 'sqlite', config: { filename: join(dir, 'admin.db') }, package: PAIR_PKG, }); expect(created.status, JSON.stringify(created.json)).toBe(201); expect(await environmentRows(FRESH)).toHaveLength(1); diff --git a/packages/qa/dogfood/test/meta-door-code-datasource.dogfood.test.ts b/packages/qa/dogfood/test/meta-door-code-datasource.dogfood.test.ts index 244644a7c34..0edec905760 100644 --- a/packages/qa/dogfood/test/meta-door-code-datasource.dogfood.test.ts +++ b/packages/qa/dogfood/test/meta-door-code-datasource.dogfood.test.ts @@ -188,9 +188,10 @@ describe('[#21899] the metadata door answers a code-defined datasource as read-o }); it('control: a runtime datasource still saves and deletes through the door that created it', async () => { - // The admin door. + // The admin door. [#39398, ADR-0070 D1] A create names the package it is saved in. + const pkg = await ensurePair(stack, token, 'com.example.showcase'); const created = await call('POST', '/datasources', { - name: ADMIN_RUNTIME, label: 'Admin Runtime 21899', driver: 'sqlite', config: { filename: join(dir, 'admin-rt.db') }, + name: ADMIN_RUNTIME, label: 'Admin Runtime 21899', driver: 'sqlite', config: { filename: join(dir, 'admin-rt.db') }, package: pkg, }); expect(created.status, JSON.stringify(created.json)).toBe(201); expect(created.json.data?.datasource).toMatchObject({ name: ADMIN_RUNTIME, origin: 'runtime' }); @@ -204,7 +205,6 @@ describe('[#21899] the metadata door answers a code-defined datasource as read-o name: META_RUNTIME, label, driver: 'sqlite', config: { filename: join(dir, 'meta-rt.db') }, }); // [#38174] A new item is created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. - const pkg = await ensurePair(stack, token, 'com.example.showcase'); const saved = await call('PUT', `/meta/datasource/${META_RUNTIME}?package=${pkg}`, runtimeBody('Meta Runtime 21899')); expect(saved.status, JSON.stringify(saved.json)).toBe(200); const updated = await call('PUT', `/meta/datasource/${META_RUNTIME}`, runtimeBody('Meta Runtime 21899 (edited)')); diff --git a/packages/services/service-datasource/src/__tests__/datasource-admin-plugin.test.ts b/packages/services/service-datasource/src/__tests__/datasource-admin-plugin.test.ts index 0123ea78632..cc5cb9331ac 100644 --- a/packages/services/service-datasource/src/__tests__/datasource-admin-plugin.test.ts +++ b/packages/services/service-datasource/src/__tests__/datasource-admin-plugin.test.ts @@ -36,6 +36,7 @@ import { assertEngineFindOnePredicate, hashSpec } from '@objectstack/metadata-co // which is what guards this file now rather than the position of the line below. import '@objectstack/spec/kernel'; import { refusalAccount } from './refusal-account.js'; +import { kernelSaveFixture, TEST_PACKAGE } from './kernel-save.fixture.js'; /** * Minimal PluginContext + in-memory metadata service. Boots the plugin and @@ -59,7 +60,12 @@ async function boot(opts: DatasourceAdminServicePluginOptions & { listObjects: async () => [...(registry.get('object')?.values() ?? [])], }; - const services: Record = { metadata, ...(opts.services ?? {}) }; + // [ADR-0070 D1] The kernel save every datasource write goes through. + const services: Record = { + metadata, + protocol: kernelSaveFixture(opts.services?.data as never), + ...(opts.services ?? {}), + }; let registered: IDatasourceAdminService | undefined; const ctx: any = { getService: (name: string) => { @@ -152,7 +158,7 @@ describe('DatasourceAdminServicePlugin: secret fail-closed', () => { expect(await refusalAccount( service.createDatasource( { name: 'reporting', driver: 'postgres', config: { database: 'analytics' } }, - { value: 'pw' }, + { value: 'pw' }, { package: TEST_PACKAGE }, ), )).toMatch(/no secret store configured/i); // nothing persisted @@ -172,7 +178,7 @@ describe('DatasourceAdminServicePlugin: secret fail-closed', () => { }); await service.createDatasource( { name: 'reporting', driver: 'postgres', config: { database: 'analytics' } }, - { value: 'pw' }, + { value: 'pw' }, { package: TEST_PACKAGE }, ); const rec = registry.get('datasource')?.get('reporting') as any; expect(rec.origin).toBe('runtime'); @@ -184,17 +190,28 @@ describe('DatasourceAdminServicePlugin: secret fail-closed', () => { describe('DatasourceAdminServicePlugin: credential re-homing wiring (#8155)', () => { /** Seed a legacy row straight into the registry — post-#8078 no door writes one. */ - const seedLegacy = async (metadata: { register: (t: string, n: string, d: unknown) => Promise }) => - metadata.register('datasource', 'warehouse', { - name: 'warehouse', - driver: 'postgres', - origin: 'runtime', - config: { host: 'db.internal', database: 'app', username: 'app', password: 'hunter2' }, + const LEGACY_ROW = { + name: 'warehouse', + driver: 'postgres', + origin: 'runtime', + config: { host: 'db.internal', database: 'app', username: 'app', password: 'hunter2' }, + }; + const seedLegacy = async ( + metadata: { register: (t: string, n: string, d: unknown) => Promise }, + ctx?: { getService: (name: string) => unknown }, + ) => { + // [ADR-0070 D1] The stored row too, where the kernel save looks for it: + // a migration rewrites an existing row, it creates none. + (ctx?.getService('protocol') as ReturnType | undefined)?.memory.set('warehouse', { + id: 'legacy_warehouse', name: 'warehouse', type: 'datasource', state: 'active', version: 1, package_id: null, + metadata: JSON.stringify(LEGACY_ROW), }); + await metadata.register('datasource', 'warehouse', LEGACY_ROW); + }; it('re-homes through the host binder when it can bind AND resolve', async () => { const store = new Map(); - const { service, metadata, registry } = await boot({ + const { service, metadata, registry, ctx } = await boot({ driverFactory: fakeFactory(), secrets: { bind: async (input, hint) => { @@ -205,7 +222,7 @@ describe('DatasourceAdminServicePlugin: credential re-homing wiring (#8155)', () resolve: async (ref) => store.get(ref), }, }); - await seedLegacy(metadata); + await seedLegacy(metadata, ctx); const result = await service.migrateCredential('warehouse'); @@ -348,7 +365,7 @@ describe('DatasourceAdminServicePlugin: persistence + bound count', () => { // seed an object bound to a runtime datasource registry.set('object', new Map([['lead', { name: 'lead', datasource: 'reporting' }]])); - await service.createDatasource({ name: 'reporting', driver: 'postgres', config: { database: 'analytics' } }); + await service.createDatasource({ name: 'reporting', driver: 'postgres', config: { database: 'analytics' } }, undefined, { package: TEST_PACKAGE }); const list = await service.listDatasources(); expect(list.find((d) => d.name === 'crm_primary')?.origin).toBe('code'); @@ -408,7 +425,7 @@ describe('DatasourceAdminServicePlugin: runtime datasource durability', () => { // Boot #1: create a runtime sqlite datasource (no secret needed). const b1 = await boot({ services: { data } }); - await b1.service.createDatasource({ name: 'demo_ext', driver: 'sqlite', config: { filename: '/tmp/x.db' } }); + await b1.service.createDatasource({ name: 'demo_ext', driver: 'sqlite', config: { filename: '/tmp/x.db' } }, undefined, { package: TEST_PACKAGE }); // It is durably written to sys_metadata (not just the in-memory registry). expect(data.rows.filter((r) => r.type === 'datasource' && r.name === 'demo_ext')).toHaveLength(1); @@ -477,7 +494,7 @@ describe('DatasourceAdminServicePlugin: runtime datasource durability', () => { it('removes the durable sys_metadata row when a datasource is deleted', async () => { const data = fakeSysMetadataEngine(); const b = await boot({ services: { data } }); - await b.service.createDatasource({ name: 'gone', driver: 'sqlite', config: { filename: '/tmp/y.db' } }); + await b.service.createDatasource({ name: 'gone', driver: 'sqlite', config: { filename: '/tmp/y.db' } }, undefined, { package: TEST_PACKAGE }); expect(data.rows.some((r) => r.name === 'gone')).toBe(true); await b.service.removeDatasource('gone'); expect(data.rows.some((r) => r.name === 'gone')).toBe(false); @@ -642,12 +659,9 @@ describe('DatasourceAdminServicePlugin: runtime datasource durability', () => { return { connect: async () => {}, disconnect: async () => {} }; }, }; - const projectors = new Map Promise>(); - const protocol = { - registerMutationProjector: (type: string, projector: (evt: unknown) => Promise) => { - projectors.set(type, projector); - }, - }; + // [ADR-0070 D1] The kernel save, whose projector slot the plugin fills. + const protocol = kernelSaveFixture(data as never); + const projectors = protocol.projectors as Map Promise>; const b = await boot({ driverFactory: factory, services: { data, protocol, ...(opts.codeNames ? { [CODE_NAMES]: opts.codeNames } : {}) }, @@ -659,7 +673,7 @@ describe('DatasourceAdminServicePlugin: runtime datasource durability', () => { projectors.get('datasource')!({ type: 'datasource', name, state, organizationId: null }); const listed = async (name: string) => (await b.service.listDatasources()).find((d) => d.name === name); const builtFor = (name: string) => built.filter((s) => s.name === name); - return { ...b, data, built, builtFor, projectors, metaDoorWrote, listed }; + return { ...b, data, built, builtFor, projectors, metaDoorWrote, listed, protocol }; }; it('serves code only for a name in the code-datasource set, and runtime for every other, whatever the record says', async () => { @@ -667,6 +681,9 @@ describe('DatasourceAdminServicePlugin: runtime datasource durability', () => { await b.metadata.register('datasource', 'crm_wh', { ...CODE, origin: 'runtime' }); await b.metadata.register('datasource', 'rt_none', { name: 'rt_none', label: 'No origin', ...pg('a') }); await b.metadata.register('datasource', 'rt_code', { name: 'rt_code', label: 'Asserts code', origin: 'code', ...pg('b') }); + // [ADR-0070 D1] Their stored rows, which the edits below rewrite in place. + b.data.rows.push(metaRow('rt_none', { label: 'No origin', ...pg('a') })); + b.data.rows.push(metaRow('rt_code', { label: 'Asserts code', origin: 'code', ...pg('b') })); expect((await b.listed('crm_wh'))?.origin).toBe('code'); expect((await b.listed('rt_none'))?.origin).toBe('runtime'); @@ -758,13 +775,16 @@ describe('DatasourceAdminServicePlugin: runtime datasource durability', () => { it('an admin-written row carries the checksum the /meta door\'s repository stamps on the body it stores', async () => { const b = await host(); - await b.service.createDatasource({ name: 'ck_ds', label: 'v1', driver: 'postgres', config: { host: 'h', database: 'db' } }); + await b.service.createDatasource({ name: 'ck_ds', label: 'v1', driver: 'postgres', config: { host: 'h', database: 'db' } }, undefined, { package: TEST_PACKAGE }); const row = () => b.data.rows.find((r) => r.name === 'ck_ds')!; expect(row().checksum).toBe(hashSpec(JSON.parse(row().metadata as string), 'datasource')); await b.service.updateDatasource('ck_ds', { label: 'v2' }); expect(JSON.parse(row().metadata as string).label).toBe('v2'); expect(row().checksum).toBe(hashSpec(JSON.parse(row().metadata as string), 'datasource')); + // [ADR-0070 D1] The row is the kernel save's: both writes reached it, and + // the door wrote none of its own. + expect(b.protocol.saves.map((s) => [s.name, s.packageId ?? null])).toEqual([['ck_ds', TEST_PACKAGE], ['ck_ds', TEST_PACKAGE]]); }); }); @@ -789,8 +809,9 @@ describe('DatasourceAdminServicePlugin: runtime datasource durability', () => { supports: (id: string) => id === 'postgres', create: async (spec) => { built.push(spec); return { connect: async () => {}, disconnect: async () => {} }; }, }; - const projectors = new Map Promise>(); - const protocol = { registerMutationProjector: (t: string, p: (evt: unknown) => Promise) => projectors.set(t, p) }; + // [ADR-0070 D1] The kernel save, whose projector slot the plugin fills. + const protocol = kernelSaveFixture(data as never); + const projectors = protocol.projectors as Map Promise>; const b = await boot({ driverFactory: factory, services: { data, protocol } }); await b.plugin.start(b.ctx); const metaDoorWrote = (name: string) => projectors.get('datasource')!({ type: 'datasource', name, state: 'active' }); @@ -818,7 +839,7 @@ describe('DatasourceAdminServicePlugin: runtime datasource durability', () => { expect(JSON.parse(String(b.data.rows.find((r) => r.id === 'meta_dup_env')!.metadata)).label).toBe('edited'); await b.service.removeDatasource('dup'); expect(b.data.rows.some((r) => r.id === 'meta_dup_env')).toBe(false); - await b.service.createDatasource({ name: 'dup', driver: 'postgres', config: { host: 'new-host', database: 'db' } }); + await b.service.createDatasource({ name: 'dup', driver: 'postgres', config: { host: 'new-host', database: 'db' } }, undefined, { package: TEST_PACKAGE }); expect(b.data.rows.filter((r) => r.name === 'dup' && r.organization_id == null)).toHaveLength(1); expect(b.data.rows.find((r) => r.id === LEGACY.id)).toEqual(LEGACY); }); @@ -838,7 +859,7 @@ describe('DatasourceAdminServicePlugin: objects bound external are read from the const { service, registry } = await boot({ services: { objectql: objectql([ORDERS]) } }); expect(await refusalAccount( - service.createDatasource({ name: 'wh', driver: 'postgres', config: { database: 'analytics' } }), + service.createDatasource({ name: 'wh', driver: 'postgres', config: { database: 'analytics' } }, undefined, { package: TEST_PACKAGE }), )).toMatch(/Object 'wh_orders' declares `external` on datasource 'wh', whose `schemaMode` is 'managed'/); expect(registry.get('datasource')?.has('wh') ?? false).toBe(false); }); @@ -851,7 +872,7 @@ describe('DatasourceAdminServicePlugin: objects bound external are read from the schemaMode: 'external', config: { database: 'analytics' }, external: {}, - }); + }, undefined, { package: TEST_PACKAGE }); expect(await refusalAccount(service.updateDatasource('wh', { schemaMode: 'managed' }))).toMatch(/'wh_orders'/); expect((registry.get('datasource')?.get('wh') as { schemaMode?: string }).schemaMode).toBe('external'); @@ -862,7 +883,7 @@ describe('DatasourceAdminServicePlugin: objects bound external are read from the services: { objectql: objectql([{ name: 'wh_local', datasource: 'wh' }]) }, }); - await service.createDatasource({ name: 'wh', driver: 'postgres', config: { database: 'analytics' } }); + await service.createDatasource({ name: 'wh', driver: 'postgres', config: { database: 'analytics' } }, undefined, { package: TEST_PACKAGE }); expect(registry.get('datasource')?.has('wh')).toBe(true); }); }); diff --git a/packages/services/service-datasource/src/__tests__/datasource-cluster-convergence.test.ts b/packages/services/service-datasource/src/__tests__/datasource-cluster-convergence.test.ts index 819d59fc458..f7c5821935e 100644 --- a/packages/services/service-datasource/src/__tests__/datasource-cluster-convergence.test.ts +++ b/packages/services/service-datasource/src/__tests__/datasource-cluster-convergence.test.ts @@ -60,6 +60,7 @@ import type { DatasourceConnectionSpec, } from '../contracts/datasource-driver-factory.js'; import type { DatasourceDraft } from '../contracts/index.js'; +import { kernelSaveFixture, TEST_PACKAGE } from './kernel-save.fixture.js'; type Row = Record; @@ -243,11 +244,14 @@ async function makeReplica( }; const logger = { warn: vi.fn(), info: vi.fn(), debug: vi.fn() }; + const protocol = kernelSaveFixture(engine as never); let service: DatasourceAdminService | undefined; const ctx: any = { getService: (name: string) => { if (name === 'data') return engine; if (name === 'metadata') return metadata; + // [ADR-0070 D1] The kernel save, over this replica's view of the shared rows. + if (name === 'protocol') return protocol; throw new Error(`no service ${name}`); }, registerService: (name: string, svc: unknown) => { @@ -344,7 +348,7 @@ describe('[#13805] ⭐ two-arm: the peer’s driver registry converges because o const c = await makeCluster(); expect(c.peer.drivers.size).toBe(0); - await c.writer.service.createDatasource(draft()); + await c.writer.service.createDatasource(draft(), undefined, { package: TEST_PACKAGE }); expect(c.writer.drivers.get('analytics')!.connected).toBe(true); await vi.waitFor(() => expect(c.peer.drivers.has('analytics')).toBe(true)); @@ -361,7 +365,7 @@ describe('[#13805] ⭐ two-arm: the peer’s driver registry converges because o it('Arm A — CONTROL: the identical create with no bridge leaves the peer pool-less', async () => { const c = await makeCluster({ attach: false }); - await c.writer.service.createDatasource(draft()); + await c.writer.service.createDatasource(draft(), undefined, { package: TEST_PACKAGE }); await settle(); expect(c.writer.drivers.has('analytics')).toBe(true); @@ -401,7 +405,7 @@ describe('[#13805] the signal is an address, and receipt is convergence', () => it('publishes name + originNode only, on datasource.mutated, for create, update AND delete — symmetric', async () => { const c = await makeCluster(); - await c.writer.service.createDatasource(draft()); + await c.writer.service.createDatasource(draft(), undefined, { package: TEST_PACKAGE }); await c.writer.service.updateDatasource('analytics', { label: 'Renamed' }); await c.writer.service.removeDatasource('analytics'); await settle(); @@ -418,7 +422,7 @@ describe('[#13805] the signal is an address, and receipt is convergence', () => it('a duplicate delivery is a no-op — same driver instance on the peer, no rebuild', async () => { const c = await makeCluster(); - await c.writer.service.createDatasource(draft()); + await c.writer.service.createDatasource(draft(), undefined, { package: TEST_PACKAGE }); await vi.waitFor(() => expect(c.peer.drivers.has('analytics')).toBe(true)); const peerDriver = c.peer.drivers.get('analytics')!; const last = c.published[c.published.length - 1]; @@ -455,7 +459,7 @@ describe('[#13805] the signal is an address, and receipt is convergence', () => // Not awaited in between: the peer sees both deliveries before its first // convergence finishes reading. Ordered receipt is what keeps this from // opening two pools for one name. - const create = c.writer.service.createDatasource(draft()); + const create = c.writer.service.createDatasource(draft(), undefined, { package: TEST_PACKAGE }); const update = create.then(() => c.writer.service.updateDatasource('analytics', { config: { filename: '/tmp/new.db' } }), ); @@ -544,7 +548,7 @@ describe('[#13805] the signal is an address, and receipt is convergence', () => throw new Error('bus down'); }; - const summary = await c.writer.service.createDatasource(draft()); + const summary = await c.writer.service.createDatasource(draft(), undefined, { package: TEST_PACKAGE }); await settle(); expect(summary.name).toBe('analytics'); @@ -560,7 +564,7 @@ describe('[#13805] the signal is an address, and receipt is convergence', () => for (const d of c.detachers) d(); expect(c.subscriptionCount()).toBe(0); - await c.writer.service.createDatasource(draft()); + await c.writer.service.createDatasource(draft(), undefined, { package: TEST_PACKAGE }); await settle(); expect(c.published).toHaveLength(0); @@ -569,7 +573,7 @@ describe('[#13805] the signal is an address, and receipt is convergence', () => it('a replica that boots AFTER the write still converges the old way — boot rehydration is the loss bound', async () => { const c = await makeCluster(); - await c.writer.service.createDatasource(draft()); + await c.writer.service.createDatasource(draft(), undefined, { package: TEST_PACKAGE }); await settle(); // A third replica that was down at publish time: it never heard the @@ -658,7 +662,7 @@ describe('[#13805] the attach seam — loopback, idempotency, the missing conver expect(logger.debug).toHaveBeenCalledTimes(1); expect(logger.debug.mock.calls[0][0]).toContain('no convergePool seam wired'); - await service.createDatasource(draft()); + await service.createDatasource(draft(), undefined, { package: TEST_PACKAGE }); expect(published).toEqual([ { channel: DATASOURCE_MUTATION_CLUSTER_CHANNEL, payload: { originNode: 'node-a', name: 'analytics' } }, ]); @@ -731,7 +735,7 @@ describe('resyncDatasourceMutationPubSub() — signals lost in a cluster outage const c = await makeCluster(); const outage = lossy(c); outage.down = true; - await c.writer.service.createDatasource(draft()); + await c.writer.service.createDatasource(draft(), undefined, { package: TEST_PACKAGE }); outage.down = false; await settle(); expect(c.peer.drivers.has('analytics')).toBe(false); diff --git a/packages/services/service-datasource/src/__tests__/datasource-create-packageless-39398.test.ts b/packages/services/service-datasource/src/__tests__/datasource-create-packageless-39398.test.ts new file mode 100644 index 00000000000..7f028fff48a --- /dev/null +++ b/packages/services/service-datasource/src/__tests__/datasource-create-packageless-39398.test.ts @@ -0,0 +1,357 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0070 D1, ruling record 7408558495] The Setup datasource door saves + * through the kernel save, into a named package. + * + * `POST /api/v1/datasources` used to insert a package-less `datasource` row + * straight into `sys_metadata`, so the one new item the kernel's create + * judgment never saw was a datasource an admin added in Setup. Now every write + * of the door (create, update, credential migration) goes through + * `saveMetaItem`, and: + * + * - a create naming no package is the kernel's `422 WRITABLE_PACKAGE_REQUIRED`, + * answered in this door's words (the body's `package`), the writable + * packages on `details`; nothing is stored and the secret minted for it is + * removed again (premise 4 of the record); + * - a create naming one is saved there, create-only, with the reference it + * minted stated as `mintedCredentialsRef`; + * - an update is saved where its row is stored, and a refused one keeps the + * secret it replaces and drops the one it minted; so does a migration; + * - an edit sends the body a read serves, so a row holding cleartext stored + * before #8078 is judged on what the author wrote (the real save's carry- + * forward is pinned in `@objectstack/metadata-protocol`); + * - a refused update after the door rebuilt the pool puts the pool back on + * the stored record; + * - the save's projector registers the stored row and leaves the pool to the + * door, whose own verdict is the one recorded: one connect per create, + * `connected`, and one rebuild per connection change; + * - with no save to write through, the door refuses `503`: no direct write. + * + * The kernel save is `kernel-save.fixture.ts`: this package does not depend on + * the metadata protocol. The own-reference judge itself, minted pass included, + * is pinned on the real save in `@objectstack/metadata-protocol`. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; +import { HonoHttpServer } from '@objectstack/plugin-hono-server'; +import { DatasourceAdminServicePlugin } from '../datasource-admin-plugin.js'; +import { registerDatasourceAdminRoutes } from '../admin-routes.js'; +import type { IDatasourceDriverFactory } from '../contracts/index.js'; +import { ENTITLED_CREDENTIAL, createSessionAuthService, createGrantsEngine } from './entitled-caller.fixture.js'; +import { kernelSaveFixture, TEST_PACKAGE } from './kernel-save.fixture.js'; +// Paid at module load, so the dist-resolved spec subpath's first transform is +// never inside a clocked case (`check-test-source-alias`, clocked-window rule). +import { getMetadataTypeRedactor } from '@objectstack/spec/kernel'; +// Pay the source's dynamic `@objectstack/driver-sql` load at collection, not inside a +// clocked case (`check-test-source-alias`). +import '@objectstack/driver-sql'; + +type Row = Record; + +/** An engine over one `sys_metadata` table and a driver registry. */ +function store() { + const rows: Row[] = []; + const drivers = new Map(); + const match = (r: Row, w: Row = {}) => Object.entries(w).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`store double: no '${k}' combinator`); + return r[k] === v; + }); + return { + rows, + async find(_object: string, query: { where?: Row; limit?: number }) { + const hits = rows.filter((r) => match(r, query?.where)); + return typeof query?.limit === 'number' ? hits.slice(0, query.limit) : hits; + }, + async insert(_object: string, row: Row) { + rows.push({ ...row }); + return row; + }, + async update(_object: string, patch: Row, options: { where: Row }) { + assertEngineUpdateDispatch(patch, options); + for (const r of rows) if (match(r, options.where)) Object.assign(r, patch); + return 1; + }, + async delete(_object: string, options: { where: Row }) { + assertEngineDeleteDispatch(options); + const i = rows.findIndex((r) => match(r, options.where)); + if (i >= 0) rows.splice(i, 1); + return true; + }, + registerDriver: (driver: { name: string }) => void drivers.set(driver.name, driver), + unregisterDriver: (name: string) => drivers.delete(name), + getDriverByName: (name: string) => drivers.get(name), + registerDatasourceDef() {}, + markDatasourceUnavailable() {}, + clearDatasourceUnavailable() {}, + }; +} + +/** A secret store whose live handles are readable, so "nothing left behind" is a reading. */ +function secretStore() { + const live = new Map(); + let seq = 0; + return { + live, + bind: vi.fn(async (input: { value: string }, hint: { name: string }) => { + const ref = `sys_secret:${hint.name}_${++seq}`; + live.set(ref, input.value); + return ref; + }), + unbind: vi.fn(async (ref: string) => void live.delete(ref)), + resolve: async (ref: string) => live.get(ref), + }; +} + +/** A factory that counts the drivers it builds, per datasource, and the host each was built for. */ +function countingFactory(): IDatasourceDriverFactory & { built: string[]; hosts: unknown[] } { + const built: string[] = []; + const hosts: unknown[] = []; + return { + built, + hosts, + supports: (id: string) => id === 'postgres', + create: async (spec) => { + built.push(String(spec.name)); + hosts.push((spec.config as { host?: unknown } | undefined)?.host); + return { driver: { name: spec.name } as never, connect: async () => {}, disconnect: async () => {} }; + }, + }; +} + +async function boot(opts: { protocol?: boolean; start?: boolean; refuseUpdates?: boolean } = {}) { + const data = store(); + const secrets = secretStore(); + const factory = countingFactory(); + const kernel = kernelSaveFixture(data as never, { writablePackages: [TEST_PACKAGE] }); + const saveMetaItem = kernel.saveMetaItem; + if (opts.refuseUpdates) { + kernel.saveMetaItem = async (request) => { + if (request.parentVersion !== null) { + kernel.saves.push(request); + throw Object.assign(new Error('refused by the kernel save'), { code: 'INVALID_METADATA', status: 422 }); + } + return saveMetaItem(request); + }; + } + const registry = new Map(); + const metadata = { + get: async (_t: string, n: string) => registry.get(n), + list: async () => [...registry.values()], + register: async (_t: string, n: string, d: unknown) => void registry.set(n, d), + unregister: async (_t: string, n: string) => void registry.delete(n), + }; + const services: Record = { metadata, data, ...(opts.protocol === false ? {} : { protocol: kernel }) }; + const ctx: any = { + getService: (name: string) => { + if (name in services) return services[name]; + throw new Error(`no service ${name}`); + }, + registerService: (name: string, svc: unknown) => void (services[name] = svc), + trigger: async () => {}, + logger: { warn() {}, info() {}, error() {}, debug() {} }, + }; + const plugin = new DatasourceAdminServicePlugin({ driverFactory: factory, secrets }); + await plugin.init(ctx); + if (opts.start) await plugin.start(ctx); + + const server = new HonoHttpServer(0); + const authService = createSessionAuthService(); + const grantsEngine = createGrantsEngine(); + registerDatasourceAdminRoutes(server, { + getService: (name: string) => + name === 'auth' ? authService : name === 'objectql' || name === 'data' ? grantsEngine : services[name], + } as never, '/api/v1'); + const send = async (method: string, path: string, body?: unknown) => { + const res = await server.getRawApp().fetch(new Request(`http://local/api/v1${path}`, { + method, + headers: { 'content-type': 'application/json', authorization: ENTITLED_CREDENTIAL }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + })); + return { status: res.status, body: (await res.json()) as any }; + }; + return { data, secrets, factory, kernel, registry, services, send }; +} + +/** The pool verdict the connection service records for `name`. */ +const connectionStatus = (b: { services: Record }, name: string) => + (b.services['datasource-connection'] as { listConnectionStates(): Array<{ name: string; status: string }> }) + .listConnectionStates().find((s) => s.name === name)?.status; + +const PG = { driver: 'postgres', config: { host: 'db.internal', database: 'app', username: 'app' } }; +const storedBody = (row: Row | undefined) => (row ? JSON.parse(String(row.metadata)) : undefined); + +describe('[ADR-0070 D1] POST /api/v1/datasources names a writable package', () => { + it('no package: 422 WRITABLE_PACKAGE_REQUIRED in this door\'s words, nothing stored, the minted secret removed', async () => { + const b = await boot(); + const res = await b.send('POST', '/datasources', { name: 'loose_ds', ...PG, secret: 'pw' }); + + expect({ status: res.status, code: res.body.error?.code }).toEqual({ status: 422, code: 'WRITABLE_PACKAGE_REQUIRED' }); + expect(String(res.body.error?.message).startsWith("Cannot create datasource 'loose_ds' with no package")).toBe(true); + expect(res.body.error?.details).toEqual({ writablePackages: [TEST_PACKAGE] }); + // The kernel was asked, with the reference this write minted… + expect(b.kernel.saves).toHaveLength(1); + expect(b.kernel.saves[0].mintedCredentialsRef).toMatch(/^sys_secret:loose_ds_/); + // …and refused it, so nothing is stored and the secret has no referrer left. + expect(b.data.rows).toEqual([]); + expect(b.registry.has('loose_ds')).toBe(false); + expect(b.secrets.unbind).toHaveBeenCalledWith(b.kernel.saves[0].mintedCredentialsRef); + expect([...b.secrets.live.keys()]).toEqual([]); + }); + + it('a package: 201, saved create-only into it, the minted reference stated and stored with the row', async () => { + const b = await boot(); + const res = await b.send('POST', '/datasources', { name: 'wh', ...PG, secret: 'pw', package: TEST_PACKAGE }); + + expect(res.status).toBe(201); + const [save] = b.kernel.saves; + expect({ type: save.type, name: save.name, packageId: save.packageId, parentVersion: save.parentVersion }) + .toEqual({ type: 'datasource', name: 'wh', packageId: TEST_PACKAGE, parentVersion: null }); + const row = b.data.rows.find((r) => r.name === 'wh'); + expect(row?.package_id).toBe(TEST_PACKAGE); + expect(storedBody(row).external.credentialsRef).toBe(save.mintedCredentialsRef); + expect(storedBody(row).origin).toBe('runtime'); + expect([...b.secrets.live.keys()]).toEqual([save.mintedCredentialsRef]); + // `package` lands the row; it is never a key of the record. + expect('package' in storedBody(row)).toBe(false); + }); + + it('control: a create with no secret states no minted reference', async () => { + const b = await boot(); + expect((await b.send('POST', '/datasources', { name: 'wh', ...PG, package: TEST_PACKAGE })).status).toBe(201); + expect('mintedCredentialsRef' in b.kernel.saves[0]).toBe(false); + }); + + it('an empty `package` is a malformed request: 400, nothing saved, no secret minted', async () => { + const b = await boot(); + const res = await b.send('POST', '/datasources', { name: 'wh', ...PG, secret: 'pw', package: '' }); + + expect({ status: res.status, code: res.body.error?.code }).toEqual({ status: 400, code: 'VALIDATION_ERROR' }); + expect(b.kernel.saves).toEqual([]); + expect(b.secrets.bind).not.toHaveBeenCalled(); + }); + + it('no metadata save on the host: 503, and no row is written any other way', async () => { + const b = await boot({ protocol: false }); + const res = await b.send('POST', '/datasources', { name: 'wh', ...PG, secret: 'pw', package: TEST_PACKAGE }); + + expect({ status: res.status, code: res.body.error?.code }).toEqual({ status: 503, code: 'SERVICE_UNAVAILABLE' }); + expect(b.data.rows).toEqual([]); + expect([...b.secrets.live.keys()]).toEqual([]); + }); +}); + +describe('[ADR-0070 D1] the door\'s other writes go through the same save', () => { + it('an update is saved in the package its row is stored in, stating the reference it minted', async () => { + const b = await boot(); + await b.send('POST', '/datasources', { name: 'wh', ...PG, secret: 'pw', package: TEST_PACKAGE }); + const first = b.kernel.saves[0].mintedCredentialsRef; + + const res = await b.send('PATCH', '/datasources/wh', { label: 'Warehouse', secret: 'pw2' }); + + expect(res.status).toBe(200); + const update = b.kernel.saves[1]; + expect({ packageId: update.packageId, parentVersion: update.parentVersion }).toEqual({ packageId: TEST_PACKAGE, parentVersion: undefined }); + expect(update.mintedCredentialsRef).toMatch(/^sys_secret:wh_/); + expect(update.mintedCredentialsRef).not.toBe(first); + expect(storedBody(b.data.rows.find((r) => r.name === 'wh')).external.credentialsRef).toBe(update.mintedCredentialsRef); + // The secret it replaced is retired once the new one is stored. + expect([...b.secrets.live.keys()]).toEqual([update.mintedCredentialsRef]); + }); + + it('an update the kernel refuses keeps the stored secret and removes the one minted for it', async () => { + const b = await boot({ refuseUpdates: true }); + await b.send('POST', '/datasources', { name: 'wh', ...PG, secret: 'pw', package: TEST_PACKAGE }); + const kept = b.kernel.saves[0].mintedCredentialsRef; + + const res = await b.send('PATCH', '/datasources/wh', { secret: 'pw2' }); + + expect(res.status).toBe(400); + expect(b.kernel.saves[1].mintedCredentialsRef).not.toBe(kept); + expect(storedBody(b.data.rows.find((r) => r.name === 'wh')).external.credentialsRef).toBe(kept); + expect([...b.secrets.live.keys()]).toEqual([kept]); + }); + + it('a credential migration the kernel refuses keeps the inline credential and removes the minted secret', async () => { + const b = await boot({ refuseUpdates: true }); + const legacy = { name: 'legacy', origin: 'runtime', driver: 'postgres', config: { ...PG.config, password: 'hunter2' } }; + b.data.rows.push({ id: 'legacy_row', type: 'datasource', name: 'legacy', state: 'active', version: 1, package_id: null, metadata: JSON.stringify(legacy) }); + b.registry.set('legacy', legacy); + + const res = await b.send('POST', '/datasources/legacy/migrate-credential'); + + expect(res.status).toBe(400); + expect(b.kernel.saves.map((s) => [s.name, typeof s.mintedCredentialsRef])).toEqual([['legacy', 'string']]); + expect(storedBody(b.data.rows[0]).config.password).toBe('hunter2'); + expect([...b.secrets.live.keys()]).toEqual([]); + }); +}); + +describe('[#39398 M1] an edit of a legacy row sends the kernel save the body a read serves', () => { + // Stored before #8078: cleartext under the canonical key and a former alias. + const legacy = { name: 'legacy', label: 'Legacy', origin: 'runtime', driver: 'postgres', config: { ...PG.config, password: 'hunter2', passwd: 'alias-secret' } }; + const edits: Array<[string, Row]> = [['a label edit', { label: 'Legacy (edited)' }], ['`active: false`', { active: false }]]; + for (const [edit, patch] of edits) { + it(`${edit}: the saved body is the served form, no stored cleartext in it (the real save carries it forward)`, async () => { + const b = await boot(); + b.data.rows.push({ id: 'legacy_row', type: 'datasource', name: 'legacy', state: 'active', version: 1, package_id: null, metadata: JSON.stringify(legacy) }); + b.registry.set('legacy', legacy); + + const res = await b.send('PATCH', '/datasources/legacy', patch); + + expect(res.status).toBe(200); + const [save] = b.kernel.saves; + expect(save.item).toEqual(getMetadataTypeRedactor('datasource')!({ ...legacy, ...patch }).item); + expect(Object.keys((save.item as { config: Row }).config).sort()).toEqual(['database', 'host', 'username']); + }); + } +}); + +describe('[ADR-0070 D1] the save\'s projector and the door\'s pool', () => { + it('a create connects once and records the door\'s own verdict, `connected`: the projector registers the stored row and leaves the pool to the door', async () => { + const b = await boot({ start: true }); + expect(b.kernel.projectors.has('datasource')).toBe(true); + + expect((await b.send('POST', '/datasources', { name: 'wh', ...PG, package: TEST_PACKAGE })).status).toBe(201); + + expect(b.factory.built).toEqual(['wh']); + // A convergence inside the save would open the pool first, and the door's + // own open would then record `already-registered` (dogfood #21923). + expect(connectionStatus(b, 'wh')).toBe('connected'); + expect(b.registry.get('wh')).toMatchObject({ name: 'wh', origin: 'runtime' }); + }); + + it('an update that changes the connection reconnects once: the door rebuilds before it stores, the projector adds no second rebuild', async () => { + const b = await boot({ start: true }); + await b.send('POST', '/datasources', { name: 'wh', ...PG, secret: 'pw', package: TEST_PACKAGE }); + + const res = await b.send('PATCH', '/datasources/wh', { config: { ...PG.config, host: 'db2.internal' }, secret: 'pw2' }); + + expect(res.status).toBe(200); + expect(b.factory.built).toEqual(['wh', 'wh']); + }); + + it('an update the kernel refuses after the rebuild puts the pool back on the stored record', async () => { + const b = await boot({ start: true, refuseUpdates: true }); + await b.send('POST', '/datasources', { name: 'wh', ...PG, secret: 'pw', package: TEST_PACKAGE }); + const kept = b.kernel.saves[0].mintedCredentialsRef; + + const res = await b.send('PATCH', '/datasources/wh', { config: { ...PG.config, host: 'db2.internal' }, secret: 'pw2' }); + + expect(res.status).toBe(400); + // The create, the rebuild onto the refused configuration, and the rebuild back. + expect(b.factory.built).toEqual(['wh', 'wh', 'wh']); + expect(b.factory.hosts[b.factory.hosts.length - 1]).toBe('db.internal'); + expect(connectionStatus(b, 'wh')).toBe('connected'); + expect(storedBody(b.data.rows.find((r) => r.name === 'wh')).external.credentialsRef).toBe(kept); + expect([...b.secrets.live.keys()]).toEqual([kept]); + }); + + it('control: a /meta save of a datasource, not the door\'s, still gets its pool from the projector', async () => { + const b = await boot({ start: true }); + await b.kernel.saveMetaItem({ type: 'datasource', name: 'meta_wh', item: { name: 'meta_wh', ...PG }, packageId: TEST_PACKAGE }); + + expect(b.factory.built).toEqual(['meta_wh']); + }); +}); diff --git a/packages/services/service-datasource/src/__tests__/datasource-system-context.pin.test.ts b/packages/services/service-datasource/src/__tests__/datasource-system-context.pin.test.ts index 1ac6d8a5d44..2fc216370a9 100644 --- a/packages/services/service-datasource/src/__tests__/datasource-system-context.pin.test.ts +++ b/packages/services/service-datasource/src/__tests__/datasource-system-context.pin.test.ts @@ -32,6 +32,10 @@ import { // Pay the dist-resolved spec subpath's first transform at module load, as the // sibling plugin suite does (`check-test-source-alias`, clocked-window rule). import '@objectstack/spec/kernel'; +import { kernelSaveFixture, TEST_PACKAGE } from './kernel-save.fixture.js'; +// Pay the source's dynamic `@objectstack/driver-sql` load at collection, not inside a +// clocked case (`check-test-source-alias`). +import '@objectstack/driver-sql'; type Call = { verb: string; object: string; context: unknown }; @@ -101,7 +105,8 @@ async function boot(data: ReturnType) { unregister: async (t: string, n: string) => { registry.get(t)?.delete(n); }, listObjects: async () => [...(registry.get('object')?.values() ?? [])], }; - const services: Record = { metadata, data }; + // [ADR-0070 D1] The kernel save every datasource write goes through. + const services: Record = { metadata, data, protocol: kernelSaveFixture(data as never) }; let service: any; const ctx: any = { getService: (name: string) => { @@ -121,7 +126,7 @@ describe('[#21913] runtime-datasource sys_metadata helpers carry the explicit sy it('persist (insert and update branches), boot restore, convergence read and delete', async () => { const data = recordingStore(); const first = await boot(data); - await first.service.createDatasource({ name: 'pin_ds', driver: 'sqlite', active: false, config: { filename: '/tmp/pin.db' } }); + await first.service.createDatasource({ name: 'pin_ds', driver: 'sqlite', active: false, config: { filename: '/tmp/pin.db' } }, undefined, { package: TEST_PACKAGE }); await first.service.updateDatasource('pin_ds', { label: 'Pin' }); // A "restart" over the same store: start() restores runtime rows from it. diff --git a/packages/services/service-datasource/src/__tests__/datasource-update-kept-pool-stores-nothing.test.ts b/packages/services/service-datasource/src/__tests__/datasource-update-kept-pool-stores-nothing.test.ts index 8376da0cd8a..d0317741e85 100644 --- a/packages/services/service-datasource/src/__tests__/datasource-update-kept-pool-stores-nothing.test.ts +++ b/packages/services/service-datasource/src/__tests__/datasource-update-kept-pool-stores-nothing.test.ts @@ -40,6 +40,7 @@ import { ENTITLED_CREDENTIAL, createSessionAuthService, createGrantsEngine } fro // Pay the first transform of the dist-resolved driver at module load, not // inside a clocked `it()` (see `scripts/check-test-source-alias.mjs`). import '@objectstack/driver-sql'; +import { kernelSaveFixture, TEST_PACKAGE } from './kernel-save.fixture.js'; // This suite hands the admin plugin its own driver factory, so the default // factory's `memory` arm is never called. The mock answers its static reach // without loading the in-memory driver (scripts/driver-memory-census.ledger.json). @@ -191,6 +192,8 @@ async function boot(store: Store, options: { tenancy?: 'single' | 'group' | 'iso const services = new Map([ ['data', data], ['metadata', metadata], + // [ADR-0070 D1] The kernel save every datasource write goes through. + ['protocol', kernelSaveFixture(data as never)], ['auth', createSessionAuthService()], // The routes resolve the caller's grants from `objectql` first. ['objectql', createGrantsEngine()], @@ -253,7 +256,7 @@ function atRest(store: Store) { async function created(store: Store) { const first = await boot(store); - const res = await first.send('POST', '/datasources', { ...CREATE, secret: REAL_PASSWORD }); + const res = await first.send('POST', '/datasources', { ...CREATE, secret: REAL_PASSWORD, package: TEST_PACKAGE }); expect({ status: res.status, dsStatus: res.body.data?.datasource?.status }).toEqual({ status: 201, dsStatus: 'ok' }); return first; } diff --git a/packages/services/service-datasource/src/__tests__/external-namespace-reads-engine-registry.test.ts b/packages/services/service-datasource/src/__tests__/external-namespace-reads-engine-registry.test.ts index c5deb309561..8c691531f1b 100644 --- a/packages/services/service-datasource/src/__tests__/external-namespace-reads-engine-registry.test.ts +++ b/packages/services/service-datasource/src/__tests__/external-namespace-reads-engine-registry.test.ts @@ -41,6 +41,9 @@ import type { PluginContext } from '@objectstack/core'; import type { IntrospectedSchema, IExternalDatasourceService } from '@objectstack/spec/contracts'; import { validateObjectNamespacePrefix } from '@objectstack/spec/kernel'; import { ExternalDatasourceServicePlugin } from '../plugin.js'; +// Pay the source's dynamic `@objectstack/driver-sql` load at collection, not inside a +// clocked case (`check-test-source-alias`). +import '@objectstack/driver-sql'; const remoteSchema = (): IntrospectedSchema => ({ @@ -462,3 +465,64 @@ describe('[#30469 item 2] an import lands in the package of its datasource', () expect(ensureCustomizationPackage).not.toHaveBeenCalled(); }); }); + +describe('[ruling 6660988968 item 1, ADR-0070 D1] an import from a datasource added in Setup lands in the package its row is stored in', () => { + /** A datasource the admin door saved through the kernel save: its copy carries no `_packageId`. */ + const SETUP_DATASOURCE = { name: 'warehouse', schemaMode: 'external', origin: 'runtime' }; + + /** The `'data'` service: introspection, plus the stored `sys_metadata` rows a `find` answers. */ + function storedRows(rows: Array>) { + const find = vi.fn(async (object: string, query: { where?: Record }) => + object !== 'sys_metadata' + ? [] + : rows.filter((r) => Object.entries(query.where ?? {}).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`storedRows double: no '${k}' combinator`); + return r[k] === v; + }))); + return { introspectDatasource: vi.fn(async () => remoteSchema()), find }; + } + const row = (packageId: string | null, state = 'active') => + ({ type: 'datasource', name: 'warehouse', state, package_id: packageId, metadata: JSON.stringify(SETUP_DATASOURCE) }); + + async function compose(rows: Array>) { + const h = harness(); + const saveMetaItem = vi.fn(async () => ({ success: true })); + const service = await federation(h); + h.services.set('data', storedRows(rows)); + h.services.set('metadata', metadataService(SETUP_DATASOURCE)); + h.services.set('objectql', engine(WAREHOUSE).service); + h.services.set('protocol', writableProtocol(saveMetaItem)); + return { service, saveMetaItem }; + } + + it('a row stored in a writable package: the import is saved into it, named in its namespace', async () => { + const { service, saveMetaItem } = await compose([row(PACKAGE_ID)]); + + const result = await service.importObject('warehouse', 'customers'); + + expect(result.name).toBe('wh_customers'); + expect(saveMetaItem).toHaveBeenCalledWith(expect.objectContaining({ name: 'wh_customers', packageId: PACKAGE_ID })); + }); + + it('control: a row stored with no package lands package-less, as before', async () => { + const { service, saveMetaItem } = await compose([row(null), row(PACKAGE_ID, 'draft')]); + + const result = await service.importObject('warehouse', 'customers'); + + expect(result.name).toBe('customers'); + expect('packageId' in ((saveMetaItem.mock.calls[0] as unknown[])[0] as object)).toBe(false); + }); + + it('active rows in two packages are no one landing: refused, and nothing is saved', async () => { + const { service, saveMetaItem } = await compose([row(PACKAGE_ID), row('other_pkg')]); + + const refusal = await service.importObject('warehouse', 'customers').then( + () => undefined, + (err: { code?: unknown; status?: unknown; message?: unknown }) => ({ code: err.code, status: err.status, message: String(err.message) }), + ); + + expect({ code: refusal?.code, status: refusal?.status }).toEqual({ code: 'EXTERNAL_IMPORT_ERROR', status: 400 }); + expect(refusal?.message).toContain('more than one package'); + expect(saveMetaItem).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/services/service-datasource/src/__tests__/kernel-save.fixture.ts b/packages/services/service-datasource/src/__tests__/kernel-save.fixture.ts new file mode 100644 index 00000000000..8dfd02fbe68 --- /dev/null +++ b/packages/services/service-datasource/src/__tests__/kernel-save.fixture.ts @@ -0,0 +1,123 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0070 D1] A stand-in for the kernel's metadata save (`saveMetaItem` on + * the `protocol` service), for the plugin-level suites of this package. + * + * The datasource admin door stores every record through that save + * (`datasource-record-save.ts`); this package does not depend on + * `@objectstack/metadata-protocol`, so a suite that drives the door end to end + * wires this fixture as its `protocol` service. It does what those suites rely + * on and no more: + * + * - a create (no active row of the name) naming no package is refused + * `422 WRITABLE_PACKAGE_REQUIRED` (with `writablePackages` when given), + * nothing written, the kernel's verdict; + * - a create-only save (`parentVersion: null`) over an existing row is + * refused `409 METADATA_CONFLICT`; + * - otherwise the row is written into the engine's `sys_metadata` (or kept in + * memory when the engine has no durable store), with the checksum the + * kernel's repository stamps and the package in `package_id`; + * - after a durable write, the projector a plugin registered for the type + * runs, as the kernel's awaited mutation projector does. + * + * ⛔ It judges no credentials reference. The own-reference rule and the + * minted-reference pass are pinned on the real save + * (`@objectstack/metadata-protocol`, `protocol.datasource-credentials-ref-own-reference.test.ts`). + */ + +import { hashSpec, readLegacyOrganizationRows } from '@objectstack/metadata-core'; + +/** The package suites save into: a package the fixture treats as installed and writable. */ +export const TEST_PACKAGE = 'test_pkg'; + +type Projector = (evt: { name: string; state: string }) => Promise; + +interface EngineLike { + find?: (object: string, query: any, options?: any) => Promise; + insert?: (object: string, row: Record, options?: any) => Promise; + update?: (object: string, row: Record, options?: any) => Promise; + getDriverForObject?: (object: string) => unknown; +} + +export interface KernelSaveRequest { + type: string; + name: string; + item: unknown; + parentVersion?: string | null; + packageId?: string; + mintedCredentialsRef?: string; +} + +export function kernelSaveFixture(engine?: EngineLike, opts: { writablePackages?: readonly string[] } = {}) { + const saves: KernelSaveRequest[] = []; + const projectors = new Map(); + const memory = new Map>(); + const durable = typeof engine?.insert === 'function' && typeof engine?.find === 'function'; + const context = { isSystem: true } as const; + let nextId = 0; + + return { + saves, + memory, + projectors, + registerMutationProjector(type: string, projector: Projector): void { + projectors.set(type, projector); + }, + async saveMetaItem(request: KernelSaveRequest): Promise<{ success: true }> { + saves.push(request); + const where = { type: request.type, name: request.name, state: 'active' }; + // The environment's row: a legacy organization's row (ADR-0131 D6) is + // never the one a save writes. + let existing: Record | undefined; + if (durable) { + const rows = ((await engine!.find!('sys_metadata', { where }, { context })) ?? []) as Array>; + const legacy = await readLegacyOrganizationRows(engine!.getDriverForObject?.('sys_metadata') as never); + existing = rows.find((row) => !legacy.has(String(row.id))); + } else { + existing = memory.get(request.name); + } + if (!existing && !request.packageId) { + throw Object.assign(new Error(`Cannot create ${request.type}/${request.name} with no package (kernel save fixture).`), { + code: 'WRITABLE_PACKAGE_REQUIRED', + status: 422, + ...(opts.writablePackages ? { writablePackages: [...opts.writablePackages] } : {}), + }); + } + if (existing && request.parentVersion === null) { + throw Object.assign(new Error(`${request.type}/${request.name} already exists (kernel save fixture).`), { + code: 'METADATA_CONFLICT', + status: 409, + }); + } + const now = new Date().toISOString(); + const metadata = JSON.stringify(request.item); + const checksum = hashSpec(request.item as Record, request.type); + if (existing) { + const patch = { metadata, checksum, updated_at: now, version: ((existing.version as number) || 0) + 1, state: 'active' }; + if (durable) await engine!.update?.('sys_metadata', patch, { where: { id: existing.id }, context }); + else memory.set(request.name, { ...existing, ...patch }); + } else { + const row = { + id: `ksf_${++nextId}`, + name: request.name, + type: request.type, + scope: 'platform', + metadata, + checksum, + state: 'active', + version: 1, + package_id: request.packageId ?? null, + created_at: now, + updated_at: now, + }; + if (durable) await engine!.insert!('sys_metadata', row, { context }); + else memory.set(request.name, row); + } + // The kernel's projector reads the stored row back, so it runs only over + // a durable store: an in-memory row is one no projector could read. + if (durable) await projectors.get(request.type)?.({ name: request.name, state: 'active' }); + return { success: true }; + }, + }; +} diff --git a/packages/services/service-datasource/src/__tests__/runtime-datasource-bound-object-storage.test.ts b/packages/services/service-datasource/src/__tests__/runtime-datasource-bound-object-storage.test.ts index 1f3e7e24dd7..b8cc701702f 100644 --- a/packages/services/service-datasource/src/__tests__/runtime-datasource-bound-object-storage.test.ts +++ b/packages/services/service-datasource/src/__tests__/runtime-datasource-bound-object-storage.test.ts @@ -47,6 +47,10 @@ import type { IDataDriver } from '@objectstack/spec/contracts'; import type { IDatasourceAdminService } from '../contracts/index.js'; import { DatasourceAdminServicePlugin } from '../datasource-admin-plugin.js'; import { createDefaultDatasourceDriverFactory } from '../default-datasource-driver-factory.js'; +import { kernelSaveFixture, TEST_PACKAGE } from './kernel-save.fixture.js'; +// Pay the source's dynamic `@objectstack/driver-sql` load at collection, not inside a +// clocked case (`check-test-source-alias`). +import '@objectstack/driver-sql'; const teardowns: Array<() => Promise | void> = []; afterEach(async () => { @@ -104,6 +108,8 @@ async function boot(opts: { objects: Array>; stored?: Ar ['objectql', ql], ['data', data], ['metadata', metadata], + // [ADR-0070 D1] The kernel save every datasource write goes through. + ['protocol', kernelSaveFixture(data as never)], ]); const ctx = { getService: (n: string) => { @@ -136,7 +142,7 @@ describe('a code object bound to a runtime managed datasource gets its table', ( name: 'warehouse', driver: 'sqlite', config: { filename: join(dir, 'warehouse.db') }, - }); + }, undefined, { package: TEST_PACKAGE }); expect(created.status).toBe('ok'); expect(await knexOf('warehouse').schema.hasTable('wh_note')).toBe(true); @@ -153,7 +159,7 @@ describe('a code object bound to a runtime managed datasource gets its table', ( config: { filename: join(dir, 'warehouse.db') }, }; const first = await boot({ objects: [boundTo('wh_note', 'warehouse')] }); - await first.admin.createDatasource({ name: record.name, driver: record.driver, config: record.config }); + await first.admin.createDatasource({ name: record.name, driver: record.driver, config: record.config }, undefined, { package: TEST_PACKAGE }); // The state an install that created the datasource before this fix is in. await first.knexOf('warehouse').schema.dropTableIfExists('wh_note'); await (first.ql.getDriverByName('warehouse') as IDataDriver).disconnect?.(); @@ -170,7 +176,7 @@ describe('a code object bound to a runtime managed datasource gets its table', ( objects: [boundTo('wh_note', 'warehouse'), boundTo('crm_note', 'crm')], }); - await admin.createDatasource({ name: 'warehouse', driver: 'sqlite', config: { filename: join(dir, 'warehouse.db') } }); + await admin.createDatasource({ name: 'warehouse', driver: 'sqlite', config: { filename: join(dir, 'warehouse.db') } }, undefined, { package: TEST_PACKAGE }); expect(synced.mock.calls.map(([name]) => name)).toEqual(['wh_note']); }); @@ -180,7 +186,7 @@ describe('[#27750] an update that rebuilds the pool gives the bound managed obje it('a changed config: the table exists on the NEW database, and the object reads', async () => { const dir = scratch(); const { admin, knexOf, read } = await boot({ objects: [boundTo('wh_note', 'warehouse')] }); - await admin.createDatasource({ name: 'warehouse', driver: 'sqlite', config: { filename: join(dir, 'a.db') } }); + await admin.createDatasource({ name: 'warehouse', driver: 'sqlite', config: { filename: join(dir, 'a.db') } }, undefined, { package: TEST_PACKAGE }); const updated = await admin.updateDatasource('warehouse', { config: { filename: join(dir, 'b.db') } }); @@ -200,7 +206,7 @@ describe('[#27750] an update that rebuilds the pool gives the bound managed obje schemaMode, external: { validation: { onMismatch: 'warn' } }, config: { filename: join(dir, 'a.db') }, - } as never); + } as never, undefined, { package: TEST_PACKAGE }); const updated = await admin.updateDatasource('lake', { config: { filename: join(dir, 'b.db') } }); @@ -229,7 +235,7 @@ describe('⛔ an external or federated datasource never gets DDL', () => { schemaMode, external: { validation: { onMismatch: 'warn' } }, config: { filename: join(dir, 'lake.db') }, - } as never); + } as never, undefined, { package: TEST_PACKAGE }); expect(created.status).toBe('ok'); expect(synced).not.toHaveBeenCalled(); diff --git a/packages/services/service-datasource/src/__tests__/sqlite-filename-neither-memory-nor-path.test.ts b/packages/services/service-datasource/src/__tests__/sqlite-filename-neither-memory-nor-path.test.ts index de2518220bd..83dfc782443 100644 --- a/packages/services/service-datasource/src/__tests__/sqlite-filename-neither-memory-nor-path.test.ts +++ b/packages/services/service-datasource/src/__tests__/sqlite-filename-neither-memory-nor-path.test.ts @@ -15,6 +15,7 @@ import { ENTITLED_CREDENTIAL, createSessionAuthService, createGrantsEngine } fro // load, not inside a clocked `it()` (see `scripts/check-test-source-alias.mjs`). import '@objectstack/spec/kernel'; import '@objectstack/driver-sql'; +import { kernelSaveFixture, TEST_PACKAGE } from './kernel-save.fixture.js'; /** * [#30331] A SQLite `config.filename` that is neither exactly `:memory:` nor a @@ -40,6 +41,7 @@ const grantsEngine = createGrantsEngine(); async function mountDoor() { let admin: IDatasourceAdminService | undefined; const rows = new Map(); + const protocol = kernelSaveFixture(); const metadata = { get: async (_type: string, name: string) => rows.get(name), list: async () => [...rows.values()], @@ -53,6 +55,8 @@ async function mountDoor() { const ctx: any = { getService: (name: string) => { if (name === 'metadata') return metadata; + // [ADR-0070 D1] The kernel save every datasource write goes through. + if (name === 'protocol') return protocol; throw new Error(`no service ${name}`); }, registerService: (name: string, svc: unknown) => { @@ -97,7 +101,7 @@ async function mountDoor() { expect(res.status).toBe(200); return res.body.data.result as { ok: boolean; error?: string }; }, - create: (draft: Record) => send('POST', '', draft), + create: (draft: Record) => send('POST', '', { ...draft, package: TEST_PACKAGE }), update: (name: string, patch: Record) => send('PATCH', `/${name}`, patch), }; } diff --git a/packages/services/service-datasource/src/admin-routes.ts b/packages/services/service-datasource/src/admin-routes.ts index 51bacafe7ea..e5bb3a75b29 100644 --- a/packages/services/service-datasource/src/admin-routes.ts +++ b/packages/services/service-datasource/src/admin-routes.ts @@ -107,7 +107,7 @@ const SERVICE_ERROR_CODE: Record = { * GET /datasources → listDatasources (provenance + health) * GET /datasources/:name → getDatasource (config credential-redacted) * POST /datasources/test → testConnection (no persistence) - * POST /datasources → createDatasource (origin: 'runtime') + * POST /datasources → createDatasource (origin: 'runtime'; body `package`, ADR-0070 D1) * PATCH /datasources/:name → updateDatasource (runtime only) * DELETE /datasources/:name → removeDatasource (runtime only) * POST /datasources/:name/migrate-credential @@ -771,6 +771,20 @@ export function registerDatasourceAdminRoutes( if (envelope?.status === 404 && envelope?.code === 'RESOURCE_NOT_FOUND') { return sendError(res, 404, 'RESOURCE_NOT_FOUND', (err as Error).message); } + // [ADR-0070 D1] The kernel save's package refusal, relayed with its own + // status and code: a create naming no package, or a package that is not + // installed and writable. The writable packages it lists ride on + // `details`, so the Setup form can offer them. + if (envelope?.status === 422 && envelope?.code === 'WRITABLE_PACKAGE_REQUIRED') { + const relayed = (err as { details?: unknown } | null | undefined)?.details; + return sendError( + res, + 422, + envelope.code, + (err as Error).message, + relayed !== null && typeof relayed === 'object' && !Array.isArray(relayed) ? { details: relayed as Record } : undefined, + ); + } // [#30444] A refusal that declared this route's own 400 envelope may carry // `details` (the bound-object refusal of `removeDatasource`: its reason and // the objects' names), relayed as thrown. All three must hold, so a driver @@ -963,9 +977,22 @@ export function registerDatasourceAdminRoutes( if (await requireDatasourceAdmin(req, res, { catalogWrite: DATASOURCE_METADATA_TYPE })) return; const svc = resolve(res, 'datasource-admin', 'createDatasource'); if (!svc) return; - const { draft, secret } = splitSecret(req.body); + const { draft: body, secret } = splitSecret(req.body); + // [ADR-0070 D1] The package the new datasource is saved into: the body's + // `package`, read here and never part of the record. Omitted ⇒ the kernel + // save refuses the create `422 WRITABLE_PACKAGE_REQUIRED`. + const { package: landing, ...draft } = (body ?? {}) as Record; + if (landing !== undefined && (typeof landing !== 'string' || landing.trim() === '')) { + sendError( + res, + 400, + 'VALIDATION_ERROR', + '`package` names the installed, writable package the new datasource is saved in — a non-empty package id.', + ); + return; + } try { - const datasource = await svc.createDatasource(draft, secret); + const datasource = await svc.createDatasource(draft, secret, landing === undefined ? undefined : { package: landing }); sendOk(res, { datasource }, 201); } catch (err) { badRequest(res, 'datasource-admin', err); diff --git a/packages/services/service-datasource/src/contracts/datasource-admin-service.ts b/packages/services/service-datasource/src/contracts/datasource-admin-service.ts index a4daad68b41..0a5bdea2d9a 100644 --- a/packages/services/service-datasource/src/contracts/datasource-admin-service.ts +++ b/packages/services/service-datasource/src/contracts/datasource-admin-service.ts @@ -111,6 +111,13 @@ export interface DatasourceSummary { definedIn?: string; /** True when a runtime row is shadowed by a code definition of the same name. */ conflictsWithCode?: boolean; + /** + * [ruling record 7416154891] On an update's answer only: the withheld + * positions the save did not carry forward and so removed from the stored + * row, dotted (`config.password`): the driver's inline credential slot once + * the record binds a credentials reference. Absent when it removed none. + */ + droppedWithheldKeys?: string[]; } /** @@ -173,8 +180,13 @@ export interface IDatasourceAdminService { * Rejects when a code-defined datasource of the same name exists, and rejects * a draft that names `external.credentialsRef`: the only reference a create * stores is the one a supplied `secret` is bound under. + * + * [ADR-0070 D1, #39398] Saved through the kernel save into `landing.package`, + * a writable package; with none named the save refuses `422 + * WRITABLE_PACKAGE_REQUIRED`, nothing stored, and the secret bound for it is + * removed again. */ - createDatasource(input: DatasourceDraft, secret?: SecretInput): Promise; + createDatasource(input: DatasourceDraft, secret?: SecretInput, landing?: { package?: string }): Promise; /** * Patch an existing runtime datasource. Rejects for code-defined datasources. diff --git a/packages/services/service-datasource/src/datasource-admin-plugin.ts b/packages/services/service-datasource/src/datasource-admin-plugin.ts index 93b2e36c978..58dcc8e7852 100644 --- a/packages/services/service-datasource/src/datasource-admin-plugin.ts +++ b/packages/services/service-datasource/src/datasource-admin-plugin.ts @@ -1,7 +1,7 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import type { Plugin, PluginContext } from '@objectstack/core'; -import { hashSpec, readLegacyOrganizationRows } from '@objectstack/metadata-core'; +import { readLegacyOrganizationRows } from '@objectstack/metadata-core'; import { applyConversionsToStoredItem } from '@objectstack/spec'; import { registerMetadataTypeActions } from '@objectstack/spec/kernel'; import { resolveDriverId } from '@objectstack/spec/data'; @@ -28,6 +28,7 @@ import type { IDataEngine, IObjectQLEngine } from '@objectstack/spec/contracts'; import { CONNECTOR_CREDENTIAL_SOURCE_SERVICE, type IConnectorCredentialSource } from '@objectstack/types'; import { borrowConnectorCredential, borrowedConnectorOf } from './datasource-connector-credential.js'; import { resolveDatasourceEnvCredentialsSwitch } from './datasource-env-credential.js'; +import { saveDatasourceRecord, withoutPositions, type MetadataSaveDoorLike } from './datasource-record-save.js'; /** * Minimal metadata-service surface used for datasource persistence + the @@ -89,13 +90,14 @@ interface MetadataDoorMutation { } /** - * Durable persistence for runtime datasource records via the `sys_metadata` - * table — the same store runtime objects use (the protocol writes objects there - * directly). `MetadataManager.register()` alone is in-memory unless a writable - * `datasource:` loader is wired, which standalone `serve` does not do; so a - * UI-created datasource vanished on restart. These helpers persist on write and - * the plugin restores them into the registry on boot before rehydrating pools. - * Credential cleartext is never stored — only the opaque `external.credentialsRef`. + * Durable runtime datasource records live in the `sys_metadata` table, the + * store runtime objects use. `MetadataManager.register()` alone is in-memory + * unless a writable `datasource:` loader is wired, which standalone `serve` + * does not do, so the plugin restores the stored rows into the registry on + * boot before rehydrating pools. [ADR-0070 D1] A record is WRITTEN through the + * kernel save alone (`datasource-record-save.ts`); the helpers below read the + * rows, and delete one. Credential cleartext is never stored — only the opaque + * `external.credentialsRef`. */ const DS_META_TYPE = 'datasource'; const SYS_METADATA = 'sys_metadata'; @@ -111,12 +113,6 @@ const SYS_METADATA = 'sys_metadata'; */ const SYSTEM_CTX = { isSystem: true } as const; -function newMetaId(): string { - return typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' - ? crypto.randomUUID() - : `meta_${Date.now()}_${Math.random().toString(36).slice(2)}`; -} - /** * [#22835 · ADR-0131 D6] The environment's active `datasource` rows — every * one, or one name's. EVERY read below of a stored datasource row goes through @@ -144,44 +140,6 @@ async function findEnvironmentRows( return rows.filter((row) => !legacy.has(String(row.id))); } -/** - * [#21923] Write a runtime datasource's durable row — WITH the `checksum` the - * metadata door's repository stamps on every row it writes - * (`SysMetadataRepository.put`: `hashSpec(body, ref.type)`, the one - * computation, imported rather than re-spelled). That column is the `/meta` - * door's optimistic lock: its reads hand out the row's checksum as the version - * a `PUT` / `DELETE` names as its parent, and its writes compare that parent - * against the stored column. A row written here without one could never be - * matched, so every `/meta` edit or removal of an admin-created datasource - * answered `409 METADATA_CONFLICT` — the two doors disagreeing on one record. - */ -async function persistDatasourceRow(engine: DataEngineLike | undefined, record: { name: string }): Promise { - if (!engine?.insert || !engine.find) return; // no durable store — in-memory only - const now = new Date().toISOString(); - const checksum = hashSpec(record, DS_META_TYPE); - const [existing] = await findEnvironmentRows(engine, record.name); - if (existing) { - await engine.update?.( - SYS_METADATA, - { metadata: JSON.stringify(record), checksum, updated_at: now, version: ((existing.version as number) || 0) + 1, state: 'active' }, - { where: { id: existing.id }, context: SYSTEM_CTX }, - ); - } else { - await engine.insert(SYS_METADATA, { - id: newMetaId(), - name: record.name, - type: DS_META_TYPE, - scope: 'platform', - metadata: JSON.stringify(record), - checksum, - state: 'active', - version: 1, - created_at: now, - updated_at: now, - }, { context: SYSTEM_CTX }); - } -} - async function deleteDatasourceRow(engine: DataEngineLike | undefined, name: string): Promise { if (!engine?.find) return; const [existing] = await findEnvironmentRows(engine, name); @@ -314,6 +272,15 @@ export class DatasourceAdminServicePlugin implements Plugin { optionalDependencies: string[] = ['com.objectstack.engine.objectql']; private service?: DatasourceAdminService; + /** + * [ADR-0070 D1] The names this door is saving right now through the kernel + * save. The save's projector ({@link applyMetadataDoorWrite}) registers + * their metadata slot and leaves their pool to this door, which opens or + * rebuilds it around the save as before: a convergence inside the save would + * open it first, and the door's own open would then read `already-registered` + * for the pool its write just opened. + */ + private readonly doorWritesInFlight = new Set(); private config?: DatasourceAdminServiceConfig; /** Shared "definition → live driver" path (ADR-0062 D1); also exposed as the `'datasource-connection'` service. */ private connection?: DatasourceConnectionService; @@ -490,15 +457,41 @@ export class DatasourceAdminServicePlugin implements Plugin { return row ? { ...row, origin: servedOrigin(ctx, name) } : undefined; }, - putDatasourceRecord: async (record) => { + // [ADR-0070 D1, ruling record 7408558495] One write, through the kernel + // save (`saveDatasourceRecord`): never a row written here directly. The + // save runs the datasource mutation projector + // ({@link applyMetadataDoorWrite}), which registers the stored row; while + // this write is in flight it leaves the pool to this door + // (`doorWritesInFlight`), which settles it around the save as before, so + // the door's own pool verdict is the one recorded (`connected` for a + // create, pinned in `datasource-create-packageless-39398.test.ts`). The + // slot is registered here too, as before, for a save that ran no + // projector. + putDatasourceRecord: async (record, write) => { const metadata = metadataOf(); if (!metadata?.register) { throw new Error('Metadata service is unavailable; cannot persist datasource.'); } - // In-memory registry (immediate visibility) + durable sys_metadata row - // (survives restart; restored on boot by restoreRuntimeDatasources). - await metadata.register('datasource', record.name, record); - await persistDatasourceRow(engineOf(), record); + this.doorWritesInFlight.add(record.name); + let saved: Awaited>; + try { + saved = await saveDatasourceRecord({ + protocol: safeGetService>(ctx, 'protocol'), + storedPackageOf: async (name) => { + const [row] = await findEnvironmentRows(engineOf(), name); + const packageId = (row as { package_id?: unknown } | undefined)?.package_id; + return typeof packageId === 'string' && packageId !== '' ? packageId : undefined; + }, + record, + write, + }); + } finally { + this.doorWritesInFlight.delete(record.name); + } + // The slot holds what the row holds: a position the save dropped is + // not registered back from the record in hand. + await metadata.register('datasource', record.name, withoutPositions(record, saved.droppedWithheldKeys)); + return saved; }, deleteDatasourceRecord: async (name) => { @@ -803,6 +796,9 @@ export class DatasourceAdminServicePlugin implements Plugin { if (row) await metadata.register(DS_META_TYPE, name, row); else await metadata.unregister(DS_META_TYPE, name); } + // [ADR-0070 D1] This door's own write: the door settles the pool itself, + // around the save (an update rebuilds BEFORE it stores, #29879). + if (this.doorWritesInFlight.has(name)) return; await this.convergePool(ctx, name, engineOf); } diff --git a/packages/services/service-datasource/src/datasource-admin-service.ts b/packages/services/service-datasource/src/datasource-admin-service.ts index 93e76ac1d47..907bcd967a5 100644 --- a/packages/services/service-datasource/src/datasource-admin-service.ts +++ b/packages/services/service-datasource/src/datasource-admin-service.ts @@ -99,6 +99,14 @@ const PROBE_DRAFT_NAME = 'connection_test_draft'; * it out of service (`active: false`) must stay possible on a row stored before * a gate landed. Every other patched key, and any supplied secret, is a change * to what the record binds, and the record is judged whole. + * + * That exemption is this door's own judgement. The kernel save every edit is + * stored through judges the body a read serves (`servedForm`), so the + * credential material a read withholds never reaches its schema and is carried + * forward after it (#8154); any OTHER at-rest content that schema refuses is + * refused there, whatever the patch touches — the narrowing's second arm + * (ruling record 7416154891, F2 A): the refusal names the key, and the same + * edit sending the corrected block saves. */ const RECORD_JUDGE_EXEMPT_PATCH_KEYS: ReadonlySet = new Set(['label', 'active']); @@ -306,6 +314,52 @@ export interface ReregisterPoolOutcome { previousPoolKept: boolean; } +/** + * [ADR-0070 D1] What a datasource write states beside the record it stores. + */ +export interface DatasourceRecordWrite { + /** + * The installed, writable package a CREATE is saved into: the request's + * `package`. Absent on a create, the kernel save refuses it + * (`422 WRITABLE_PACKAGE_REQUIRED`). Never stated on an update, which saves + * the row where it is stored. + */ + packageId?: string; + /** True for a create: the save may write only where no row of the name exists. */ + create?: boolean; + /** + * [ruling record 7408558495 (A2)] The `external.credentialsRef` this write + * has just minted by sealing a secret, stated to the kernel save so its + * own-reference judge lets exactly this reference through. + */ + mintedCredentialsRef?: string; + /** + * Send the kernel save the body a READ serves, not the record at rest: the + * kernel's credential carry-forward (#8154) restores the withheld material + * after its gates. Stated by an edit, so a row holding cleartext stored + * before #8078 is judged on what the author wrote and keeps its credential, + * and by the credential migration, whose bound reference retires the inline + * slot at the save instead (ruling record 7416154891). + */ + servedForm?: boolean; +} + +/** + * [ruling record 7416154891] What one record save reports back: the withheld + * positions the kernel save did not carry forward, dotted (`config.password`), + * sorted; `[]` when it dropped none. + */ +export interface DatasourceRecordSaved { + droppedWithheldKeys: string[]; +} + +/** + * [ADR-0070 D1] Where a create lands: the request's `package`. + */ +export interface DatasourceCreateLanding { + package?: string; +} + /** * Injected dependencies. The plugin supplies real implementations backed by the * driver registry, `IMetadataService` (runtime store), and the secret store; @@ -318,8 +372,17 @@ export interface DatasourceAdminServiceConfig { listDatasourceRecords: () => Promise; /** Read one datasource record by name. */ getDatasourceRecord: (name: string) => Promise; - /** Persist a runtime datasource record into the runtime metadata store. */ - putDatasourceRecord: (record: StoredDatasource) => Promise; + /** + * Persist a runtime datasource record into the runtime metadata store. + * + * [ADR-0070 D1, ruling record 7408558495] The plugin's implementation saves + * through the kernel's metadata save (`saveMetaItem`), so every judge of that + * save answers this write: a create naming no writable package is refused + * `422 WRITABLE_PACKAGE_REQUIRED` with nothing stored. `write` carries what + * the door states beside the record: the package a CREATE lands in, and the + * credentials reference this very write has just minted. + */ + putDatasourceRecord: (record: StoredDatasource, write?: DatasourceRecordWrite) => Promise; /** Remove a runtime datasource record from the runtime metadata store. */ deleteDatasourceRecord: (name: string) => Promise; /** Encrypt + store a secret, returning an opaque `credentialsRef`. */ @@ -949,7 +1012,11 @@ export class DatasourceAdminService implements IDatasourceAdminService { } } - async createDatasource(input: DatasourceDraft, secret?: SecretInput): Promise { + async createDatasource( + input: DatasourceDraft, + secret?: SecretInput, + landing?: DatasourceCreateLanding, + ): Promise { this.assertValidName(input?.name); assertSecretNotEmpty(`Invalid datasource '${input.name}'.`, secret); this.assertNoDraftCredentialsRef(input); @@ -991,12 +1058,27 @@ export class DatasourceAdminService implements IDatasourceAdminService { // source can lend leaves nothing behind. await this.assertConnectorLendable(record); + let mintedRef: string | undefined; if (secret) { - const credentialsRef = await this.config.writeSecret(secret, { name: input.name }); - record.external = { ...(record.external ?? {}), credentialsRef }; + mintedRef = await this.config.writeSecret(secret, { name: input.name }); + record.external = { ...(record.external ?? {}), credentialsRef: mintedRef }; } - await this.config.putDatasourceRecord(record); + // [ADR-0070 D1, ruling record 7408558495] One write through the kernel + // save, in the package the request names, stating the reference just + // minted. A save it refuses (no package named, a package that is not + // writable, a name taken meanwhile) stores nothing, so the secret sealed + // for it has no referrer and is taken back out rather than orphaned. + try { + await this.config.putDatasourceRecord(record, { + create: true, + ...(landing?.package !== undefined ? { packageId: landing.package } : {}), + ...(mintedRef !== undefined ? { mintedCredentialsRef: mintedRef } : {}), + }); + } catch (err) { + if (mintedRef !== undefined) await this.tryRemoveSecret(mintedRef); + throw err; + } // [#13804] A record born `active: false` gets no live pool. Every other // lifecycle path already reads the flag this way — `connectDeclared` skips // `active === false` at boot, and boot rehydration filters on @@ -1123,6 +1205,12 @@ export class DatasourceAdminService implements IDatasourceAdminService { // (scope item 3) and is deliberately not attempted here — a write path that // quietly dropped a credential the operator still depends on would be the // destructive sweep that decision is reserved for. + // + // The same split holds at the kernel save the record is stored through: + // it is sent the body a read serves (`servedForm`, below), so its schema + // judges what the author wrote and its own carry-forward puts the withheld + // material back after every gate. This restore is what the POOL is built + // from; the kernel's is what is stored. if (patch.config !== undefined && merged.driver === existing.driver) { merged.config = restoreRedactedConfig(existing.driver, merged.config, existing.config); } @@ -1172,6 +1260,7 @@ export class DatasourceAdminService implements IDatasourceAdminService { // write path: the record is stored once, after the pool settles, and the // working secret is retired only after that write. const rebuildNeeded = secret !== undefined || datasourceConnectivityChanged(existing, merged); + let rebuilt = false; if (merged.active !== false && rebuildNeeded) { const { previousPoolKept } = await this.tryReregisterPool(existing, merged); if (previousPoolKept) { @@ -1179,11 +1268,27 @@ export class DatasourceAdminService implements IDatasourceAdminService { // Nothing was stored, so there is nothing for a peer to converge on. return this.toSummary(existing); } + rebuilt = true; } + let dropped: string[] = []; try { - await this.config.putDatasourceRecord(merged); + // The body a read serves, so the kernel save judges what the author + // wrote and carries the withheld credential material forward after its + // gates (#8154); `merged`, credential included, is what the pool above + // was built from. [ruling record 7416154891] A body binding a credentials + // reference has the driver's inline credential slot dropped instead, and + // the save names it, so this answer does too. + const saved = await this.config.putDatasourceRecord(merged, { + servedForm: true, + ...(newRef !== undefined ? { mintedCredentialsRef: newRef } : {}), + }); + dropped = saved?.droppedWithheldKeys ?? []; } catch (err) { + // [#29879] The stored record is still `existing`, so the pool serves it + // again: a pool left on the configuration the save refused would serve + // what no record declares, on a secret removed just below. + if (rebuilt) await this.convergePoolToStored(existing, merged); // The stored record still names the working secret; the one sealed for // this write has no referrer, so take it back out rather than orphan it. if (newRef && newRef !== prevRef) await this.tryRemoveSecret(newRef); @@ -1200,7 +1305,8 @@ export class DatasourceAdminService implements IDatasourceAdminService { // signal, decides whether anything connectivity-bearing changed, by the // same `datasourceConnectivityChanged` reading this door just applied. this.publishDatasourceMutation(name); - return this.toSummary(merged); + const summary = this.toSummary(merged); + return dropped.length > 0 ? { ...summary, droppedWithheldKeys: dropped } : summary; } /** @@ -1396,7 +1502,10 @@ export class DatasourceAdminService implements IDatasourceAdminService { + 'replaces the unresolvable reference; the inline copy can then be removed.', ); } - await this.config.putDatasourceRecord(withoutConfigKey(existing, plan.key)); + // [ruling record 7416154891] The served form: the bound reference + // retires the inline slot at the kernel save, and every other withheld + // key (the `remaining` aliases) is carried forward after its gates. + await this.config.putDatasourceRecord(withoutConfigKey(existing, plan.key), { servedForm: true }); this.logger?.info?.( `datasource '${name}': dropped inline 'config.${plan.key}' — the credential is already bound`, ); @@ -1431,7 +1540,7 @@ export class DatasourceAdminService implements IDatasourceAdminService { external: { ...(existing.external ?? {}), credentialsRef }, }; try { - await this.config.putDatasourceRecord(migrated); + await this.config.putDatasourceRecord(migrated, { servedForm: true, mintedCredentialsRef: credentialsRef }); } catch (err) { // The record still holds the cleartext and still works; the secret we // just minted has no referrer, so remove it rather than orphan it. @@ -1744,6 +1853,24 @@ export class DatasourceAdminService implements IDatasourceAdminService { } } + /** + * Put the live pool back on the stored record after a save refused the one + * it was just rebuilt from. Through the host's `convergePool`, which reads + * the stored row (still `stored`) and rebuilds, keeps or evicts by the same + * decision table a peer's write converges with; a host without that seam + * gets the same answer from the record in hand. Degrade-not-throw: the + * refusal is what the caller rethrows. + */ + private async convergePoolToStored(stored: StoredDatasource, refused: StoredDatasource): Promise { + try { + if (this.config.convergePool) await this.config.convergePool(stored.name); + else if (stored.active === false) await this.tryUnregisterPool(stored.name); + else await this.tryReregisterPool(refused, stored); + } catch (err) { + this.logger?.warn(`convergePool('${stored.name}') after a refused save failed`, err); + } + } + /** * [#13804] The in-place rebuild, degrade-not-throw like its siblings. A host * without the `reregisterPool` seam falls back to the plain register: its diff --git a/packages/services/service-datasource/src/datasource-record-save.ts b/packages/services/service-datasource/src/datasource-record-save.ts new file mode 100644 index 00000000000..77193c55071 --- /dev/null +++ b/packages/services/service-datasource/src/datasource-record-save.ts @@ -0,0 +1,187 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0070 D1, ruling record 7408558495] The datasource admin door's one write + * of a runtime datasource record: the kernel's metadata save (`saveMetaItem` on + * the `protocol` service), never a row written into `sys_metadata` directly. + * + * The door used to insert its row itself, with no package, so a datasource an + * admin added in Setup was the one new item the kernel's create judgment never + * saw. Saved through the kernel, every judge of that save answers this door's + * write too: the schema, the package-less create judgment (a create names a + * writable package, else `422 WRITABLE_PACKAGE_REQUIRED` and nothing stored), + * the read-only-base and code-datasource refusals, and the own-reference rule + * for `external.credentialsRef`. The save writes the row (with the checksum the + * `/meta` door's optimistic lock reads) and runs the datasource mutation + * projector, which registers the stored row in the metadata service. + * + * - **create**: create-only (`parentVersion: null`), into the package the + * request names. No package named ⇒ the kernel's refusal, answered in this + * door's words ({@link inThisDoorsWords}). No exemption is + * added for this door (ruling 7184753035, question 2 A). + * - **update** (an edit, a credential migration): saved where its row is + * stored, the row's own package stated, so the save never moves it. + * - **an edit and a credential migration** send the body a read serves ({@link servedFormOf}), never + * the record at rest: the kernel's schema judges what the author wrote, + * and its credential carry-forward (#8154) puts back what the read + * withheld, after every gate, exactly as on the `/meta` door's GET → edit + * → PUT. A row stored before #8078 with cleartext in `config` therefore + * keeps its `label` and `active: false` edits, and keeps the credential. + * - **what the save dropped**: a withheld position the save did not carry + * forward (ruling record 7416154891: a datasource's inline credential slot + * once the body binds `external.credentialsRef`) is read off the answer's + * notices and handed back, so the door names it too. + * - **a reference this write minted**: stated as `mintedCredentialsRef`, + * server-side only, so the own-reference judge lets exactly that reference + * through, when no other stored datasource row holds it (ruling record + * 7408558495, A2). + * + * ⛔ No host without the save is served by a direct write instead: the door + * refuses with `503 SERVICE_UNAVAILABLE`, nothing stored. + */ + +import { getMetadataTypeRedactor } from '@objectstack/spec/kernel'; +import type { DatasourceRecordSaved, DatasourceRecordWrite, StoredDatasource } from './datasource-admin-service.js'; + +/** The metadata type a datasource record is saved as. */ +const DATASOURCE_TYPE = 'datasource'; + +/** + * The slice of the kernel save this door calls, read structurally: this + * package does not depend on `@objectstack/metadata-protocol`. + */ +export interface MetadataSaveDoorLike { + saveMetaItem(request: { + type: string; + name: string; + item: unknown; + parentVersion?: string | null; + packageId?: string; + mintedCredentialsRef?: string; + }): Promise; +} + +/** + * What a read serves for `record`: the type's own read-path redactor, the one + * the kernel's carry-forward compares an incoming body against. Sent as an + * edit's body, every withheld position equals what the read served, so the + * kernel restores the stored value there after its gates; nothing this door + * holds is lost and no stored cleartext reaches the schema gate. + */ +function servedFormOf(record: StoredDatasource): StoredDatasource { + const redactor = getMetadataTypeRedactor(DATASOURCE_TYPE); + return redactor ? (redactor(record as unknown as Record).item as unknown as StoredDatasource) : record; +} + +/** + * [ruling record 7416154891] The rule id of the save's notice for a withheld + * position it did not carry forward (`withheld-key-dropped` on the answer's + * `advisories`), read structurally like the rest of this answer. + */ +const WITHHELD_KEY_DROPPED_RULE = 'withheld-key-dropped'; + +/** + * The positions the save's answer names as dropped, in the redactor's dotted + * spelling (`config.password`): the advisory path is the item's position in + * its collection (`datasources[0].config.password`), so that root comes off. + * A path that does not carry the root is kept as written, never left out. + */ +function droppedPositionsOf(answer: unknown): string[] { + const advisories = (answer as { advisories?: unknown } | null | undefined)?.advisories; + if (!Array.isArray(advisories)) return []; + return advisories + .filter((a): a is { rule: string; path: string } => a?.rule === WITHHELD_KEY_DROPPED_RULE && typeof a?.path === 'string') + .map((a) => a.path.replace(/^datasources\[0\]\./, '')) + .sort(); +} + +/** Remove each dotted position (`config.password`) from a copy of `record`. */ +export function withoutPositions(record: StoredDatasource, positions: readonly string[]): StoredDatasource { + if (positions.length === 0) return record; + const copy: Record = structuredClone(record as unknown as Record); + for (const position of positions) { + const segments = position.split('.'); + let node: unknown = copy; + for (const segment of segments.slice(0, -1)) { + node = node && typeof node === 'object' ? (node as Record)[segment] : undefined; + } + if (node && typeof node === 'object') delete (node as Record)[segments[segments.length - 1]]; + } + return copy as unknown as StoredDatasource; +} + +/** How many writable packages this door's refusal names before it counts the rest. */ +const NAMED_PACKAGES_CAP = 5; + +/** The kernel's package-less create refusal (ADR-0070 D1's code, with no package named). */ +type PackagelessCreateRefusal = Error & { writablePackages?: readonly string[]; details?: unknown }; +function isPackagelessCreateRefusal(err: unknown): err is PackagelessCreateRefusal { + const e = err as { code?: unknown; status?: unknown; packageId?: unknown } | null | undefined; + return err instanceof Error && e?.code === 'WRITABLE_PACKAGE_REQUIRED' && e.status === 422 && e.packageId === undefined; +} + +/** + * The kernel's refusal of a datasource create that names no package, relayed + * in this door's words: the same error, its code and status the kernel's + * (this door stamps no code of its own), its sentence prescribing the request + * body's `package`, which this door reads (the kernel's own sentence names the + * `/meta` door's `?package=`). The writable packages ride on `details` too, so + * a console can offer them. + */ +function inThisDoorsWords(err: PackagelessCreateRefusal, name: string): PackagelessCreateRefusal { + const writable = err.writablePackages; + const listed = writable === undefined + ? '' + : writable.length === 0 + ? ' No package in this environment is writable: create one first.' + : ` Writable packages here: ${writable.slice(0, NAMED_PACKAGES_CAP).join(', ')}` + + `${writable.length > NAMED_PACKAGES_CAP ? `, and ${writable.length - NAMED_PACKAGES_CAP} more` : ''}.`; + err.message = `Cannot create datasource '${name}' with no package: a new datasource is saved into a writable package ` + + `(ADR-0070), so it travels with that package. Name one with \`package\` in the request body. ` + + `Nothing was saved.${listed}`; + const kept = typeof err.details === 'object' && err.details !== null ? err.details : {}; + err.details = writable === undefined ? kept : { ...kept, writablePackages: [...writable] }; + return err; +} + +/** `503 SERVICE_UNAVAILABLE`: the host composes no metadata save. */ +function noSaveDoorError(name: string): Error { + return Object.assign( + new Error( + `Cannot store datasource '${name}': this host registers no metadata save (the 'protocol' service), ` + + 'which every datasource write goes through. Nothing was saved.', + ), + { code: 'SERVICE_UNAVAILABLE', status: 503 }, + ); +} + +/** + * Store one runtime datasource record through the kernel save. `storedPackageOf` + * reads the package an existing row is stored in, asked for an update only. + */ +export async function saveDatasourceRecord(args: { + protocol: Partial | undefined; + storedPackageOf: (name: string) => Promise; + record: StoredDatasource; + write?: DatasourceRecordWrite; +}): Promise { + const { protocol, record, write } = args; + if (typeof protocol?.saveMetaItem !== 'function') throw noSaveDoorError(record.name); + const packageId = write?.create ? write.packageId : await args.storedPackageOf(record.name); + try { + const answer = await protocol.saveMetaItem({ + type: DATASOURCE_TYPE, + name: record.name, + item: write?.servedForm ? servedFormOf(record) : record, + ...(write?.create ? { parentVersion: null } : {}), + ...(packageId !== undefined ? { packageId } : {}), + ...(write?.mintedCredentialsRef !== undefined ? { mintedCredentialsRef: write.mintedCredentialsRef } : {}), + }); + return { droppedWithheldKeys: droppedPositionsOf(answer) }; + } catch (err) { + if (write?.create && isPackagelessCreateRefusal(err)) { + throw inThisDoorsWords(err, record.name); + } + throw err; + } +} diff --git a/packages/services/service-datasource/src/plugin.ts b/packages/services/service-datasource/src/plugin.ts index 2c6493e4eb2..eda4c1c3ba7 100644 --- a/packages/services/service-datasource/src/plugin.ts +++ b/packages/services/service-datasource/src/plugin.ts @@ -208,16 +208,58 @@ export class ExternalDatasourceServicePlugin implements Plugin { * The package that declared a datasource: its stamped `_packageId`, or * `undefined` for a datasource no package declares, the `'sys_metadata'` * rehydration sentinel, and a datasource that cannot be read. See - * `getNamespace` below for why the stamp is the one source. + * `getNamespace` below for why the stamp is the first source. A datasource + * whose copy carries no stamp is answered by its stored row's package + * ({@link storedDatasourcePackageId}). */ const datasourcePackageId = async (datasource: string): Promise => { + let pkgId: string | undefined; try { const ds = (await metadata()?.get('datasource', datasource)) as { _packageId?: unknown } | undefined; - const pkgId = typeof ds?._packageId === 'string' ? ds._packageId : undefined; - return !pkgId || pkgId === 'sys_metadata' ? undefined : pkgId; + pkgId = typeof ds?._packageId === 'string' ? ds._packageId : undefined; } catch { return undefined; } + if (pkgId && pkgId !== 'sys_metadata') return pkgId; + return storedDatasourcePackageId(datasource); + }; + + /** + * [ADR-0070 D1 · ruling 6660988968 item 1, ruling record 7408558495 Q2] The + * package a STORED datasource row is saved in: its `package_id` column. A + * datasource added in Setup is saved through the kernel save into a + * package, which the row holds in that column and never in its body, so + * the metadata service's copy (registered from the body) carries no + * `_packageId`. Read only when that copy names none; a row stored with no + * package, and a store that cannot be read, answer `undefined`, as before + * (ruling 6660988968 item 1: unreadable → package-less). Several active + * rows naming different packages are no single answer, and are refused. + */ + const storedDatasourcePackageId = async (datasource: string): Promise => { + const data = safeGetService>>(ctx, 'data'); + if (typeof data?.find !== 'function') return undefined; + let rows: Array<{ package_id?: unknown }> | undefined; + try { + rows = (await data.find('sys_metadata', { + where: { type: 'datasource', name: datasource, state: 'active' }, + context: { isSystem: true }, + } as never)) as Array<{ package_id?: unknown }> | undefined; + } catch { + // Ruling 6660988968 item 1: a datasource whose package cannot be read + // lands package-less, as one with an unreadable `_packageId` does. + return undefined; + } + const packages = new Set(); + for (const row of rows ?? []) { + if (typeof row?.package_id === 'string' && row.package_id !== '') packages.add(row.package_id); + } + if (packages.size > 1) { + throw importLandingRefusal( + `Datasource '${datasource}' is stored in more than one package (${[...packages].sort().join(', ')}), ` + + 'so an object imported from it has no one package to be saved into. The import is not saved anywhere.', + ); + } + return packages.values().next().value; }; /** The engine registry `installPackage` stores package records in, read where it is used. */ @@ -338,7 +380,8 @@ export class ExternalDatasourceServicePlugin implements Plugin { * [#30469 item 2] Where an import is saved — ruling B (recorded as * 6660988968), the module of `resolveImportLanding` in * `external-datasource-service.ts` stating the three rows. Decided by - * the datasource's `_packageId` alone: + * the datasource's package (`datasourcePackageId`: its `_packageId`, or, + * for a datasource saved in Setup, its stored row's `package_id`): * * - none → package-less (ADR-0146 D11 environment metadata); * - writable (the save door's own ADR-0070 predicate) → that package; diff --git a/packages/spec/api-surface/kernel.json b/packages/spec/api-surface/kernel.json index e5070d67eaa..85653b97820 100644 --- a/packages/spec/api-surface/kernel.json +++ b/packages/spec/api-surface/kernel.json @@ -180,6 +180,7 @@ "ManifestSchema (const)", "MetadataBulkResult (type)", "MetadataBulkResultSchema (const)", + "MetadataCarryForwardRetirement (type)", "MetadataCategory (type)", "MetadataCategoryEnum (const)", "MetadataDependency (type)", @@ -497,6 +498,7 @@ "findNamespaceObjectNameClashes (function)", "getMetadataCreateSeed (function)", "getMetadataTypeActions (function)", + "getMetadataTypeCarryForwardRetirement (function)", "getMetadataTypeRedactor (function)", "getMetadataTypeSchema (function)", "getOverrideTypeClassification (function)", diff --git a/packages/spec/export-origins/kernel.json b/packages/spec/export-origins/kernel.json index 564af4b06e4..d69466a341f 100644 --- a/packages/spec/export-origins/kernel.json +++ b/packages/spec/export-origins/kernel.json @@ -179,6 +179,7 @@ "ManifestSchema": "src/kernel/manifest.zod.ts#ManifestSchema (const)", "MetadataBulkResult": "src/kernel/metadata-plugin.zod.ts#MetadataBulkResult (type)", "MetadataBulkResultSchema": "src/kernel/metadata-plugin.zod.ts#MetadataBulkResultSchema (const)", + "MetadataCarryForwardRetirement": "src/kernel/metadata-type-redaction.ts#MetadataCarryForwardRetirement (type)", "MetadataCategory": "src/kernel/package-artifact.zod.ts#MetadataCategory (type)", "MetadataCategoryEnum": "src/kernel/package-artifact.zod.ts#MetadataCategoryEnum (const)", "MetadataDependency": "src/kernel/metadata-plugin.zod.ts#MetadataDependency (type)", @@ -493,6 +494,7 @@ "findNamespaceObjectNameClashes": "src/kernel/namespace-prefix.ts#findNamespaceObjectNameClashes (function)", "getMetadataCreateSeed": "src/kernel/metadata-create-seeds.ts#getMetadataCreateSeed (function)", "getMetadataTypeActions": "src/kernel/metadata-type-schemas.ts#getMetadataTypeActions (function)", + "getMetadataTypeCarryForwardRetirement": "src/kernel/metadata-type-redaction.ts#getMetadataTypeCarryForwardRetirement (function)", "getMetadataTypeRedactor": "src/kernel/metadata-type-redaction.ts#getMetadataTypeRedactor (function)", "getMetadataTypeSchema": "src/kernel/metadata-type-schemas.ts#getMetadataTypeSchema (function)", "getOverrideTypeClassification": "src/kernel/customization-package.ts#getOverrideTypeClassification (function)", diff --git a/packages/spec/src/kernel/metadata-type-redaction.ts b/packages/spec/src/kernel/metadata-type-redaction.ts index 2b2a8021459..3475450b0b3 100644 --- a/packages/spec/src/kernel/metadata-type-redaction.ts +++ b/packages/spec/src/kernel/metadata-type-redaction.ts @@ -69,7 +69,7 @@ * regions, write-path strip) keep their explicit redactors. */ -import { redactDatasourceConfig } from '../data/datasource-credential-redaction'; +import { redactDatasourceConfig, refusedCredentialKeys } from '../data/datasource-credential-redaction'; import { redactConnectorItem } from '../integration/connector-credential-redaction'; import { derivedCredentialRedactorFor } from './metadata-credential-fields'; import { @@ -242,6 +242,50 @@ export function registerMetadataTypeRedactor(type: string, redactor: MetadataTyp EXTRA_METADATA_TYPE_REDACTORS.set(type, redactor); } +/** + * [ruling record 7416154891, F1 A] A per-type rule naming withheld positions + * that a save does NOT carry forward because of what the INCOMING body + * declares, as {@link MetadataRedactionResult.notCarriedForwardKeys} names + * them from the stored body alone. The positions use the redactor's dotted + * spelling; a save of the served form drops the stored value at each one the + * incoming body leaves empty, and names every drop on its answer. + * + * MUST be pure: no mutation of the input, no I/O. + */ +export type MetadataCarryForwardRetirement = (incoming: Record) => string[]; + +/** + * `datasource`: a body that binds `external.credentialsRef` retires the + * driver's inline credential slot (`refusedCredentialKeys` of the body's + * driver: `config.password`, turso's `config.authToken`). With a reference + * bound, the connect path resolves it fail-closed (ADR-0062 D3) and every + * driver arm prefers the injected secret over that slot ("The resolved secret + * is injected at connect time and always wins over anything embedded in + * `config`"), so nothing reads the stored copy, and no door accepts it. The + * former alias spellings and a URL-embedded password are not that slot: they + * stay carried forward. + */ +function datasourceInlineCredentialsRetiredByBinding(incoming: Record): string[] { + const external = incoming.external; + if (!external || typeof external !== 'object' || Array.isArray(external)) return []; + const ref = (external as { credentialsRef?: unknown }).credentialsRef; + if (typeof ref !== 'string' || ref === '') return []; + return refusedCredentialKeys(incoming.driver).map((key) => `config.${key}`).sort(); +} + +const BUILTIN_CARRY_FORWARD_RETIREMENTS: Record = { + datasource: datasourceInlineCredentialsRetiredByBinding, +}; + +/** + * The type's {@link MetadataCarryForwardRetirement}, or `undefined` for a type + * whose withheld positions the incoming body never retires (every type but + * `datasource` today). + */ +export function getMetadataTypeCarryForwardRetirement(type: string): MetadataCarryForwardRetirement | undefined { + return BUILTIN_CARRY_FORWARD_RETIREMENTS[type]; +} + /** * Snapshot of every type that currently has a redactor (built-in, extras, and * the types whose schema derives one), sorted. diff --git a/packages/spec/src/migrations/entries/semantic/19.setup-datasource-create-names-package.ts b/packages/spec/src/migrations/entries/semantic/19.setup-datasource-create-names-package.ts new file mode 100644 index 00000000000..b149a8cc1a6 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.setup-datasource-create-names-package.ts @@ -0,0 +1,51 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #39398 (ADR-0070 D1; ruling record 7408558495) — the Setup datasource door +// saves through the kernel save, so a create there names a writable package +// like every other create. A runtime HTTP verdict: no authored source spells +// anything that moves, so there is no D2 conversion. +export const entry: SemanticMigration = { + id: 'setup-datasource-create-names-package', + surface: + 'POST /api/v1/datasources (the Setup "Datasources" create, and any script that calls it) with no `package` ' + + 'in the request body. FROM `201`, storing a new datasource row bound to no package, written straight into ' + + 'the metadata table, TO `422 WRITABLE_PACKAGE_REQUIRED` naming the writable packages (also on ' + + '`error.details.writablePackages`), nothing stored and the secret sealed for the request removed again. An ' + + 'empty or non-string `package` answers `400 VALIDATION_ERROR`. The door\'s edit (`PATCH ' + + '/api/v1/datasources/{name}`) and credential migration (`POST /api/v1/datasources/{name}/migrate-credential`) ' + + 'are saved through the same kernel save, in the package the row is stored in, so every judge of that save ' + + 'answers them too. Second arm: on an existing datasource whose stored `config` (or `pool`) the schema ' + + 'refuses for a reason other than an inline credential (a key it no longer recognises), an edit that ' + + 'leaves that block as stored, a `label` or `active: false` alone included, moves FROM `200` TO `400 ' + + 'DATASOURCE_ADMIN_ERROR` carrying the kernel\'s sentence, which names the key; nothing is stored', + replacement: + 'name the package the new datasource belongs to: `"package": "PKG"` in the body of `POST ' + + '/api/v1/datasources`, or choose a package in the Console\'s Setup datasource form, which offers the ' + + 'writable packages when the server refuses a create without one. For the second arm, send the corrected ' + + 'block with the edit: `{ "active": false, "config": { ...the stored config without the key the refusal ' + + 'names } }` saves. An edit of an existing datasource is otherwise saved in place on the body a read ' + + 'serves, its stored credentials carried forward; once the record binds `external.credentialsRef`, the ' + + 'driver\'s inline credential slot is dropped from the row and named on the answer. An object imported ' + + 'from a datasource now ' + + 'lands in the package that datasource is stored in', + reason: + 'ADR-0070 D1: a runtime create resolves to a writable package, judged at the kernel save. The Setup ' + + 'datasource door wrote its row itself, so it was the one create door that judgment never saw, and every ' + + 'datasource added in Setup became a loose item no package could version, publish, move or delete. The ' + + 'door now writes through the kernel save with no new exemption; the reference to the secret it has just ' + + 'sealed for the write is stated to the save by server code only, and passes when no other stored ' + + 'datasource holds it.', + acceptanceCriteria: + '`POST /api/v1/datasources` with no `package` answers 422 `WRITABLE_PACKAGE_REQUIRED` with ' + + '`details.writablePackages`, and no datasource row and no sealed secret remain; with `package` naming a ' + + 'writable package it answers 201 and the row is stored in that package. On a datasource whose stored ' + + '`config` holds a key the schema no longer recognises, `PATCH` with `{ "active": false }` alone answers 400 ' + + '`DATASOURCE_ADMIN_ERROR` naming the key and stores nothing, and the same `PATCH` with the config sent ' + + 'without that key answers 200 and stores both. A credential migration leaves the reference and no inline ' + + 'credential slot in the stored row, after a restart too, and a second run answers `already-bound`. ' + + 'Verify UNAFFECTED: a `label` or `active: false` edit of an existing datasource whose only refused stored ' + + 'content is an inline credential (the credential is kept), testing and deleting an existing package-less ' + + 'datasource; an object import from a package-less datasource, which still lands loose.', +}; diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index dbd0936dbc1..54fc6a99a92 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -5256,6 +5256,16 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/qa/dogfood/test/datasource-meta-door-reaches-admin-door.dogfood.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/qa/dogfood/test/datasource-meta-door-reaches-admin-door.dogfood.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/qa/dogfood/test/flow-hook-per-slot.dogfood.test.ts", "verb": "delete", @@ -6196,6 +6206,16 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/services/service-datasource/src/__tests__/datasource-create-packageless-39398.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/services/service-datasource/src/__tests__/datasource-create-packageless-39398.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/services/service-datasource/src/__tests__/datasource-system-context.pin.test.ts", "verb": "delete", diff --git a/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceLandingPick.tsx b/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceLandingPick.tsx new file mode 100644 index 00000000000..1bfa910b7de --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceLandingPick.tsx @@ -0,0 +1,69 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#39398 (ADR-0070 D1) — the package a new datasource is saved in. + * + * `POST /api/v1/datasources` saves through the kernel save, so a create naming + * no package is refused `422 WRITABLE_PACKAGE_REQUIRED`, nothing stored, with + * the writable packages on the envelope's `details.writablePackages`. The + * editor shows that refusal in the server's words with one button per package + * the server named, and choosing one sends the create again with that package + * as the body's `package` (the permission-set clone dialog's pick, objectstack#38174). + * ⛔ Nothing is chosen for the administrator, and with no writable package the + * server's sentence (which says to create one) stands alone. + */ + +import * as React from 'react'; +import { Button } from '@object-ui/components'; +import { tFormat, type SupportedLocale } from '../i18n.js'; + +/** A create refused for want of a package: the server's sentence and the packages it named. */ +export interface DatasourceLanding { + message: string; + packages: string[]; +} + +/** The landing refusal a failed create carries, or `undefined` for any other failure. */ +export function datasourceLandingRefusal(err: unknown): DatasourceLanding | undefined { + const e = err as { status?: unknown; code?: unknown; message?: unknown; details?: { writablePackages?: unknown } } | null | undefined; + if (e?.status !== 422 || e.code !== 'WRITABLE_PACKAGE_REQUIRED') return undefined; + const listed = e.details?.writablePackages; + const packages = Array.isArray(listed) ? listed.filter((p): p is string => typeof p === 'string' && p !== '') : []; + return { message: typeof e.message === 'string' ? e.message : '', packages: [...new Set(packages)].sort() }; +} + +/** The refusal's sentence, with one button per package the server named. */ +export function DatasourceLandingPick({ + landing, + locale, + busy, + onPick, +}: { + landing: DatasourceLanding; + locale: SupportedLocale; + busy: boolean; + onPick: (packageId: string) => void; +}) { + return ( +
+

{landing.message}

+ {landing.packages.length > 0 && ( +
+ {landing.packages.map((id) => ( + + ))} +
+ )} +
+ ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.newDatasourceModes-30327.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.newDatasourceModes-30327.test.tsx index 2e23c35a490..8fac5c599c8 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.newDatasourceModes-30327.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.newDatasourceModes-30327.test.tsx @@ -36,6 +36,15 @@ * driver is chosen; * - (j) CONTROL: an unmarked driver (PostgreSQL) still offers all three modes * and shows no reason sentence. + * + * objectstack#39398 (ADR-0070 D1) — a create naming no package is refused + * `422 WRITABLE_PACKAGE_REQUIRED` with `details.writablePackages`: + * - (k) the dialog shows the server's sentence with one button per package + * it named, raises no toast, and stays open; + * - (l) picking one sends the same create again with that `package`, and the + * created datasource is reported; + * - (m) no writable package: the sentence stands alone, nothing is chosen; + * - (n) CONTROL: another refusal of the create is the toast it was. */ import * as React from 'react'; @@ -134,7 +143,13 @@ const MSSQL = { interface Seen { method: string; url: string; body?: Record } -function renderPage(opts: { rows?: unknown[]; stored?: Record; language?: string } = {}) { +function renderPage(opts: { + rows?: unknown[]; + stored?: Record; + language?: string; + /** Answers a create in place of the default `201` (objectstack#39398). */ + post?: (body: Record | undefined) => Reply | undefined; +} = {}) { const seen: Seen[] = []; state.fetch = (async (url: string, init?: RequestInit) => { const method = (init?.method ?? 'GET').toUpperCase(); @@ -142,7 +157,7 @@ function renderPage(opts: { rows?: unknown[]; stored?: Record; seen.push({ method, url, body }); if (url === '/api/v1/datasources/drivers') return ok({ drivers: [SQLITE, POSTGRES, ORACLE, MSSQL] }); if (url === '/api/v1/datasources' && method === 'GET') return ok({ datasources: opts.rows ?? [] }); - if (url === '/api/v1/datasources' && method === 'POST') return ok({ datasource: { name: body?.name } }, 201); + if (url === '/api/v1/datasources' && method === 'POST') return opts.post?.(body) ?? ok({ datasource: { name: body?.name } }, 201); if (url === '/api/v1/datasources/test') return ok({ result: { ok: true } }); if (opts.stored && url === `/api/v1/datasources/${String(opts.stored.name)}` && method === 'GET') { return ok({ datasource: opts.stored }); @@ -377,3 +392,61 @@ describe('A federation-only driver is offered the federation modes alone (object expect(t(key, ZH)).not.toBe(t(key, EN)); }); }); + +describe('New datasource — the package it is saved in (objectstack#39398, ADR-0070 D1)', () => { + const SENTENCE = "Cannot create datasource 'parts_db' with no package: name one with `package` in the request body. Nothing was saved."; + const landingRefusal = (writablePackages: string[]) => + reply(422, { success: false, error: { code: 'WRITABLE_PACKAGE_REQUIRED', message: SENTENCE, details: { writablePackages } } }); + /** Refuses a create naming no package; saves one naming a package. */ + const landingDoor = (writablePackages: string[]) => (body: Record | undefined) => + body?.package === undefined ? landingRefusal(writablePackages) : ok({ datasource: { name: body?.name } }, 201); + + async function createParts() { + const dialog = await openNew(); + fireEvent.change(controlUnder('Name *'), { target: { value: 'parts_db' } }); + fireEvent.click(within(dialog).getByRole('button', { name: /Create datasource/ })); + return dialog; + } + + it('(k) a create naming no package shows the server\'s sentence with one button per writable package', async () => { + const seen = renderPage({ post: landingDoor(['sales_pkg', 'ops_pkg']) }); + const dialog = await createParts(); + const pick = await within(dialog).findByTestId('datasource-landing-pick'); + + expect(within(pick).getByRole('alert').textContent).toBe(SENTENCE); + expect(within(pick).getAllByRole('button').map((b) => b.getAttribute('data-testid'))) + .toEqual(['datasource-landing-ops_pkg', 'datasource-landing-sales_pkg']); + expect(toast.error).not.toHaveBeenCalled(); + expect(toast.success).not.toHaveBeenCalled(); + expect(lastWrite(seen, 'POST', '/api/v1/datasources').package).toBeUndefined(); + }); + + it('(l) picking a package sends the same create again into it', async () => { + const seen = renderPage({ post: landingDoor(['sales_pkg', 'ops_pkg']) }); + const dialog = await createParts(); + fireEvent.click(await within(dialog).findByTestId('datasource-landing-sales_pkg')); + + await waitFor(() => expect(toast.success).toHaveBeenCalled()); + const posts = seen.filter((r) => r.method === 'POST' && r.url === '/api/v1/datasources'); + expect(posts.map((p) => p.body?.package)).toEqual([undefined, 'sales_pkg']); + expect({ ...posts[1].body, package: undefined }).toEqual({ ...posts[0].body, package: undefined }); + }); + + it('(m) no writable package: the sentence stands alone and nothing is chosen', async () => { + const seen = renderPage({ post: landingDoor([]) }); + const dialog = await createParts(); + const pick = await within(dialog).findByTestId('datasource-landing-pick'); + + expect(within(pick).getByRole('alert').textContent).toBe(SENTENCE); + expect(within(pick).queryAllByRole('button')).toEqual([]); + expect(seen.filter((r) => r.method === 'POST' && r.url === '/api/v1/datasources')).toHaveLength(1); + }); + + it('(n) CONTROL: another refusal of the create is a toast, with no package pick', async () => { + renderPage({ post: () => reply(400, { success: false, error: { code: 'VALIDATION_ERROR', message: 'bad config' } }) }); + const dialog = await createParts(); + + await waitFor(() => expect(toast.error).toHaveBeenCalled()); + expect(within(dialog).queryByTestId('datasource-landing-pick')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.tsx b/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.tsx index 8ab5ab48fc7..aa93f73a62b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.tsx @@ -98,6 +98,7 @@ import { createAuthenticatedFetch } from '@object-ui/auth'; import { useMetadataClient } from '../useMetadata.js'; import { t, tFormat, useMetadataLocale, type SupportedLocale } from '../i18n.js'; import { humanizeKey } from '../inspectors/json-schema-to-fields.js'; +import { DatasourceLandingPick, datasourceLandingRefusal, type DatasourceLanding } from './DatasourceLandingPick.js'; // objectui#7265 — this page used to re-describe the introspection row as a // module-local `interface RemoteTable { name; schema?; columnCount? }`. It is // the SAME wire shape `GET /datasources/:name/remote-tables` returns, and the @@ -598,6 +599,8 @@ export function DatasourceResourcePage(_props: { type?: string }): React.ReactEl const [savingEditor, setSavingEditor] = React.useState(false); const [testMsg, setTestMsg] = React.useState<({ ok: boolean } & InlineRefusal) | null>(null); const [testingDraft, setTestingDraft] = React.useState(false); + /** A create refused for want of a package (objectstack#39398), shown as a pick of the writable packages. */ + const [landing, setLanding] = React.useState(null); const ensureDrivers = React.useCallback(async (): Promise => { if (drivers.length) return drivers; @@ -626,6 +629,7 @@ export function DatasourceResourcePage(_props: { type?: string }): React.ReactEl setEditing(null); setHasSecret(false); setTestMsg(null); + setLanding(null); setForm({ name: '', label: '', @@ -647,6 +651,7 @@ export function DatasourceResourcePage(_props: { type?: string }): React.ReactEl setEditing(row.name); setHasSecret(Boolean(ds.hasSecret)); setTestMsg(null); + setLanding(null); setForm({ name: ds.name ?? row.name, label: ds.label ?? '', @@ -737,21 +742,28 @@ export function DatasourceResourcePage(_props: { type?: string }): React.ReactEl } }; - const saveEditor = async () => { + /** Save the editor; a create is saved in `intoPackage` when the administrator picked one (objectstack#39398). */ + const saveEditor = async (intoPackage?: string) => { if (!form) return; setSavingEditor(true); + setLanding(null); try { if (editing) { await api(`/api/v1/datasources/${encodeURIComponent(editing)}`, { method: 'PATCH', body: JSON.stringify(draftBody(form)) }); toast.success(tFormat('engine.datasource.updated', locale, { name: editing })); } else { - await api('/api/v1/datasources', { method: 'POST', body: JSON.stringify({ name: form.name, ...draftBody(form) }) }); + await api('/api/v1/datasources', { + method: 'POST', + body: JSON.stringify({ name: form.name, ...draftBody(form), ...(intoPackage ? { package: intoPackage } : {}) }), + }); toast.success(tFormat('engine.datasource.created', locale, { name: form.name })); } setEditorOpen(false); void load(); } catch (err) { - refusalToast(tFormat('engine.datasource.saveFailed', locale, { error: (err as Error).message }), err); + const refusedLanding = editing ? undefined : datasourceLandingRefusal(err); + if (refusedLanding) setLanding(refusedLanding); + else refusalToast(tFormat('engine.datasource.saveFailed', locale, { error: (err as Error).message }), err); } finally { setSavingEditor(false); } @@ -1058,6 +1070,10 @@ export function DatasourceResourcePage(_props: { type?: string }): React.ReactEl )} + + {landing && ( + void saveEditor(id)} /> + )} )}