diff --git a/.changeset/28549-datasource-top-level-credential.md b/.changeset/28549-datasource-top-level-credential.md new file mode 100644 index 00000000000..43f657f50d6 --- /dev/null +++ b/.changeset/28549-datasource-top-level-credential.md @@ -0,0 +1,18 @@ +--- +'@objectstack/service-datasource': patch +--- + +fix(service-datasource)!: `POST /api/v1/datasources` and `PATCH /api/v1/datasources/:name` refuse a top-level `password` or `connectionString` by name, with the build door's prescription, instead of dropping it and answering success + +Clause-②: no (narrowing) — a create or edit body that carries `password` or `connectionString` at its top level, which answered 201 / 200 with the key silently dropped, is refused with `400 DATASOURCE_ADMIN_ERROR`. Nothing is widened. +Metadata-protocol: none + + + +**BREAKING** accept-set narrowing at the datasource admin write doors (`@objectstack/service-datasource`). + +- **Before.** The doors built the stored record from its known keys only, so a `password` or a `connectionString` written at the top level of the body vanished and the write answered success. The author got a datasource that could not connect and no explanation, while `os compile` refused the same datasource by name. +- **Now.** Either key at the top level of a create or edit body is refused before anything is read or written, naming the key and never its value. The message is `DatasourceSchema`'s own refusal for that key, the one `os compile` prints: a `password` is bound through the connection form's secret field or `external.credentialsRef`; a `connectionString` belongs in `config` as `url`. An edit is refused even when it touches only `label` or `active`. +- **Unchanged.** A credential sent as `secret` is still stored in the secret store and bound at `external.credentialsRef`. `config.password` keeps the driver contract's refusal. Other unknown top-level keys are still dropped as before. + +**The remedy.** Send the credential as `secret` (the connection form's secret field), or move a connection string into `config.url` without userinfo. diff --git a/packages/services/service-datasource/src/__tests__/datasource-admin-top-level-credential.test.ts b/packages/services/service-datasource/src/__tests__/datasource-admin-top-level-credential.test.ts new file mode 100644 index 00000000000..196eb24d895 --- /dev/null +++ b/packages/services/service-datasource/src/__tests__/datasource-admin-top-level-credential.test.ts @@ -0,0 +1,277 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, vi } from 'vitest'; +import { DatasourceSchema } from '@objectstack/spec/data'; +import { HonoHttpServer } from '@objectstack/plugin-hono-server'; +import { registerDatasourceAdminRoutes } from '../admin-routes.js'; +import { + DatasourceAdminService, + type DatasourceAdminServiceConfig, + type StoredDatasource, +} from '../datasource-admin-service.js'; +import { + ENTITLED_CREDENTIAL, + createSessionAuthService, + createGrantsEngine, +} from './entitled-caller.fixture.js'; + +/** + * #28549 — a credential written at the TOP level of a datasource body is + * refused by name at the admin write doors, as the build door refuses it. + * + * `os compile` judges a datasource against `DatasourceSchema`, whose strict + * shape refuses a top-level `password` ("must never be inlined", bind it + * through `external.credentialsRef`) and a top-level `connectionString` + * ("belongs inside `config`"). `POST /api/v1/datasources` and + * `PATCH /api/v1/datasources/:name` projected the body onto the record's known + * keys first, so both keys vanished and the write answered success: the + * author got a datasource that could not connect and no explanation. + * + * Driven through the REAL routes over the REAL service. Each refusal reads the + * envelope (status + `error.code`), the message (the heading plus the spec's + * own refusal for that key, derived here from `DatasourceSchema`, never + * restated), the absence of the value from the answer, and the store behind + * it: nothing stored, minted or registered. + * + * Every credential below is an obvious placeholder. + */ + +const authService = createSessionAuthService(); +const grantsEngine = createGrantsEngine(); + +const PLACEHOLDER_PASSWORD = 'PLACEHOLDER_NOT_A_SECRET'; +const PLACEHOLDER_DSN = `postgres://app:${PLACEHOLDER_PASSWORD}@db.example.invalid:5432/analytics`; + +/** In-memory datasource store and secret store behind a real {@link DatasourceAdminService}. */ +function makeDoor(seed: StoredDatasource[] = []) { + const records = new Map(seed.map((r) => [r.name, structuredClone(r)])); + const secrets = new Map(); + let seq = 0; + const ops: string[] = []; + + const config: DatasourceAdminServiceConfig = { + probe: async () => ({ ok: true, latencyMs: 1 }), + listDatasourceRecords: async () => [...records.values()].map((r) => structuredClone(r)), + getDatasourceRecord: async (name) => { + const r = records.get(name); + return r ? structuredClone(r) : undefined; + }, + putDatasourceRecord: async (record) => { + ops.push(`put:${record.name}`); + records.set(record.name, structuredClone(record)); + }, + deleteDatasourceRecord: async (name) => { + records.delete(name); + }, + writeSecret: async (input, hint) => { + ops.push('writeSecret'); + const ref = `sys_secret:sec_${hint.name}_${++seq}`; + secrets.set(ref, input.value); + return ref; + }, + removeSecret: async (ref) => { + ops.push('removeSecret'); + secrets.delete(ref); + }, + countBoundObjects: async () => 0, + listObjectsBoundTo: async () => [], + registerPool: () => { + ops.push('registerPool'); + }, + unregisterPool: () => { + ops.push('unregisterPool'); + }, + reregisterPool: () => { + ops.push('reregisterPool'); + }, + }; + + const service = new DatasourceAdminService(config); + const server = new HonoHttpServer(0); + const ctx = { + getService: vi.fn((name: string) => + name === 'auth' + ? authService + : name === 'objectql' || name === 'data' + ? grantsEngine + : name === 'datasource-admin' + ? service + : undefined, + ), + } as any; + registerDatasourceAdminRoutes(server, ctx, '/api/v1'); + const app = server.getRawApp(); + + const send = (method: string, path: string, body: unknown) => + app.fetch( + new Request(`http://local/api/v1${path}`, { + method, + headers: { 'content-type': 'application/json', authorization: ENTITLED_CREDENTIAL }, + body: JSON.stringify(body), + }), + ); + + return { send, records, secrets, ops }; +} + +/** + * The build door's refusal of `keys` at the top level of a datasource: + * `DatasourceSchema`'s own `unrecognized_keys` message. Throws when the spec + * makes no such refusal, so a pin can never pass on a premise the spec no + * longer holds. + */ +function specRefusal(keys: string[]): string { + const result = DatasourceSchema.safeParse(Object.fromEntries(keys.map((k) => [k, null]))); + const issue = result.success + ? undefined + : result.error.issues.find((i) => i.code === 'unrecognized_keys' && i.path.length === 0); + if (!issue) throw new Error(`fixture premise broken: DatasourceSchema does not refuse ${keys.join(', ')}`); + return issue.message; +} + +async function expectRefusal(res: Response): Promise { + const body = (await res.json()) as { success: boolean; error?: { code: string; message: string } }; + expect({ status: res.status, success: body.success, code: body.error?.code }).toEqual({ + status: 400, + success: false, + code: 'DATASOURCE_ADMIN_ERROR', + }); + return body.error!.message; +} + +const BASE = { driver: 'postgres', config: { host: 'db.example.invalid', database: 'analytics' } }; +const STORED: StoredDatasource = { name: 'wh', ...BASE, origin: 'runtime' }; + +describe('#28549 — POST /api/v1/datasources refuses a top-level credential by name', () => { + it('refuses a top-level `password` with the build door\'s prescription, storing nothing', async () => { + const { send, records, secrets, ops } = makeDoor(); + + const message = await expectRefusal( + await send('POST', '/datasources', { name: 'r7p_top', ...BASE, password: PLACEHOLDER_PASSWORD }), + ); + + expect(message).toBe(`Invalid datasource 'r7p_top'.\n${specRefusal(['password'])}`); + expect(message).toContain('`password`'); + expect(message).toContain('external.credentialsRef'); + expect(message).not.toContain(PLACEHOLDER_PASSWORD); + expect(records.has('r7p_top')).toBe(false); + expect(secrets.size).toBe(0); + expect(ops).toEqual([]); + }); + + it('refuses a top-level `connectionString` carrying URL userinfo, storing nothing', async () => { + const { send, records, secrets, ops } = makeDoor(); + + const message = await expectRefusal( + await send('POST', '/datasources', { name: 'r7p_top2', ...BASE, connectionString: PLACEHOLDER_DSN }), + ); + + expect(message).toBe(`Invalid datasource 'r7p_top2'.\n${specRefusal(['connectionString'])}`); + expect(message).toContain('`connectionString`'); + expect(message).not.toContain(PLACEHOLDER_PASSWORD); + expect(message).not.toContain('db.example.invalid'); + expect(records.has('r7p_top2')).toBe(false); + expect(secrets.size).toBe(0); + expect(ops).toEqual([]); + }); + + it('names both keys in one answer when both are written', async () => { + const { send, records } = makeDoor(); + + const message = await expectRefusal( + await send('POST', '/datasources', { + name: 'r7p_both', + ...BASE, + password: PLACEHOLDER_PASSWORD, + connectionString: PLACEHOLDER_DSN, + }), + ); + + expect(message).toBe(`Invalid datasource 'r7p_both'.\n${specRefusal(['password', 'connectionString'])}`); + expect(records.has('r7p_both')).toBe(false); + }); + + it('refuses it beside a supplied `secret` too: the secret field is the one credential channel', async () => { + const { send, records, secrets, ops } = makeDoor(); + + await expectRefusal( + await send('POST', '/datasources', { + name: 'r7p_secret', + ...BASE, + password: PLACEHOLDER_PASSWORD, + secret: PLACEHOLDER_PASSWORD, + }), + ); + + expect(records.has('r7p_secret')).toBe(false); + expect(secrets.size).toBe(0); + expect(ops).toEqual([]); + }); +}); + +describe('#28549 — PATCH /api/v1/datasources/:name refuses a top-level credential by name', () => { + it.each([ + ['password', { password: PLACEHOLDER_PASSWORD }], + ['connectionString', { connectionString: PLACEHOLDER_DSN }], + ])('refuses a top-level `%s`, leaving the stored record as it was', async (key, extra) => { + const { send, records, ops } = makeDoor([STORED]); + + const message = await expectRefusal(await send('PATCH', '/datasources/wh', { config: BASE.config, ...extra })); + + expect(message).toBe(`Invalid datasource 'wh'.\n${specRefusal([key])}`); + expect(message).not.toContain(PLACEHOLDER_PASSWORD); + expect(records.get('wh')).toEqual(STORED); + expect(ops).toEqual([]); + }); + + it('refuses it on a `label`-only edit too: the exemption covers a stored row, not a credential in the body', async () => { + const { send, records, ops } = makeDoor([STORED]); + + await expectRefusal(await send('PATCH', '/datasources/wh', { label: 'Warehouse', password: PLACEHOLDER_PASSWORD })); + + expect(records.get('wh')).toEqual(STORED); + expect(ops).toEqual([]); + }); +}); + +describe('#28549 — controls: the doors keep their other answers', () => { + it('still creates a datasource whose credential arrives as `secret`, bound at `external.credentialsRef`', async () => { + const { send, records, secrets } = makeDoor(); + + const res = await send('POST', '/datasources', { name: 'wh_ok', ...BASE, secret: PLACEHOLDER_PASSWORD }); + + expect(res.status).toBe(201); + const ref = records.get('wh_ok')?.external?.credentialsRef; + expect(ref).toMatch(/^sys_secret:/); + expect(secrets.get(ref!)).toBe(PLACEHOLDER_PASSWORD); + expect(JSON.stringify(records.get('wh_ok'))).not.toContain(PLACEHOLDER_PASSWORD); + }); + + it('still answers an edit that keeps the bound `external.credentialsRef`', async () => { + const bound: StoredDatasource = { ...STORED, external: { credentialsRef: 'sys_secret:sec_wh_own' } }; + const { send, records } = makeDoor([bound]); + + const res = await send('PATCH', '/datasources/wh', { label: 'Warehouse' }); + + expect(res.status).toBe(200); + expect(records.get('wh')?.external?.credentialsRef).toBe('sys_secret:sec_wh_own'); + }); + + it('keeps the driver contract\'s refusal of `config.password`', async () => { + const { send, records, ops } = makeDoor(); + + const message = await expectRefusal( + await send('POST', '/datasources', { + name: 'wh_cfg', + ...BASE, + config: { ...BASE.config, password: PLACEHOLDER_PASSWORD }, + }), + ); + + expect(message.split('\n')[0]).toBe("Invalid configuration for driver 'postgres'."); + expect(message).toContain('config.password'); + expect(message).not.toContain(PLACEHOLDER_PASSWORD); + expect(records.has('wh_cfg')).toBe(false); + expect(ops).toEqual([]); + }); +}); diff --git a/packages/services/service-datasource/src/datasource-admin-service.ts b/packages/services/service-datasource/src/datasource-admin-service.ts index 420e0221f6d..fae370d6fc0 100644 --- a/packages/services/service-datasource/src/datasource-admin-service.ts +++ b/packages/services/service-datasource/src/datasource-admin-service.ts @@ -86,6 +86,17 @@ const PROBE_DRAFT_NAME = 'connection_test_draft'; */ const RECORD_JUDGED_PATCH_KEYS = ['driver', 'schemaMode', 'config', 'external', 'pool'] as const; +/** + * [#28549] The top-level body keys a credential arrives under that the record + * projection ({@link DatasourceAdminService.toRecord}, the update merge) would + * otherwise drop without a word: a `password`, and a `connectionString` that + * can carry one as URL userinfo. `DatasourceSchema` refuses both at the build + * door; these doors judge exactly these keys through it. Not every key the + * projection drops: those carry no credential, and a closed body at these + * doors is a change of its own. + */ +const TOP_LEVEL_CREDENTIAL_KEYS = ['password', 'connectionString'] as const; + /** A copy of `record` carrying the binding a supplied secret is about to create. */ function withPendingSecretRef(record: StoredDatasource): StoredDatasource { return { ...record, external: { ...(record.external ?? {}), credentialsRef: PENDING_SECRET_REF } }; @@ -667,6 +678,7 @@ export class DatasourceAdminService implements IDatasourceAdminService { async createDatasource(input: DatasourceDraft, secret?: SecretInput): Promise { this.assertValidName(input?.name); this.assertNoDraftCredentialsRef(input); + this.assertNoTopLevelCredential(input.name, input); if (!input.driver) throw new Error('A driver is required to create a datasource.'); this.assertValidConfig(input.driver, input.config); // The wizard is a publish door for `pool` too (#5714). Rejected BEFORE the @@ -728,6 +740,10 @@ export class DatasourceAdminService implements IDatasourceAdminService { if (existing.origin !== 'runtime') { throw new Error(`Datasource '${name}' is code-defined and cannot be edited at runtime.`); } + // [#28549] Whatever else the patch touches, a `label`/`active`-only edit + // included: that exemption spares a row stored before a gate, and this + // judges a credential the author is writing now. + this.assertNoTopLevelCredential(existing.name, patch); // Merge patch over the existing record; `name`/`origin` are never patched. const merged: StoredDatasource = { @@ -1244,6 +1260,35 @@ export class DatasourceAdminService implements IDatasourceAdminService { ); } + /** + * [#28549] Refuse a body that writes a credential at the top level + * ({@link TOP_LEVEL_CREDENTIAL_KEYS}). The record is built from the known + * keys only, so such a key would vanish and the write answer success over a + * datasource that cannot connect, while the build door refuses the same + * datasource by name. + * + * The verdict and its prescription are `DatasourceSchema`'s own refusal of + * those keys, the one `os compile` prints, under the heading + * {@link assertValidRecord} gives. Only the key names are judged, never the + * values, so the answer names the key and cannot echo the credential. ⛔ No + * prescription is restated here; the spec is the one copy. Thrown before + * anything is read or written (a `400` at the route). + */ + private assertNoTopLevelCredential(name: string, body: object): void { + const present = TOP_LEVEL_CREDENTIAL_KEYS.filter( + (key) => (body as Record)[key] !== undefined, + ); + if (present.length === 0) return; + const result = DatasourceSchema.safeParse(Object.fromEntries(present.map((key) => [key, null]))); + const detail = result.success + ? [] + : result.error.issues + .filter((issue) => issue.code === 'unrecognized_keys' && issue.path.length === 0) + .map((issue) => issue.message); + if (detail.length === 0) return; + throw new Error(`Invalid datasource '${name}'.\n${detail.join('\n')}`); + } + private toRecord(input: DatasourceDraft): StoredDatasource { return { name: input.name,