Skip to content

Commit 66a746c

Browse files
committed
fix(service-datasource)!: the datasource admin doors refuse an empty secret instead of sealing it over the working credential
POST /api/v1/datasources and PATCH /api/v1/datasources/:name took "secret": "" as a value: a create sealed an empty credential, and an edit minted a new sys_secret holding nothing, repointed credentialsRef at it and removed the working row. Both now refuse it 400 DATASOURCE_ADMIN_ERROR naming `secret` before anything is written. null, an absent secret and a whitespace-only value are unchanged. A row sealed empty before still fails closed at connect; its status reason now says the credential is empty instead of blaming a missing row or a changed encryption key. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5mTYb1BTJNRqf3bdJ8
1 parent 00d0668 commit 66a746c

5 files changed

Lines changed: 265 additions & 1 deletion

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/service-datasource': patch
3+
---
4+
5+
fix(service-datasource)!: the datasource admin doors refuse an empty `secret` instead of sealing it over the working credential
6+
7+
Clause-②: no (narrowing) — `POST /api/v1/datasources` and `PATCH /api/v1/datasources/:name` refuse one body that used to answer 201 / 200: a `secret` whose value is the empty string (`"secret": ""` or `"secret": { "value": "" }`), now `400 DATASOURCE_ADMIN_ERROR` naming `secret`. No new error code, no new answer member, no exported type changes.
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped: secret is the doors' own credential channel, split off the body before the datasource draft is judged. The refused value stored nothing usable, and a row sealed with it before is reported at connect with a reason that says the credential is empty, so there is nothing at rest for a migration to rewrite. -->
11+
12+
**BREAKING** accept-set narrowing at the datasource admin doors (`@objectstack/service-datasource`): an empty `secret` is refused.
13+
14+
- **Before.** An empty `secret` was taken as a value. A create sealed it as the datasource's credential. An edit took it as a rotation: a new `sys_secret` row holding an empty value, `external.credentialsRef` repointed at it, and the working row removed. The live pool kept serving, so the datasource broke only at its next connect, with the old credential already gone.
15+
- **Now.** Both doors refuse it before anything is written: no `sys_secret` row is written, the stored record and its `credentialsRef` are unchanged, and no row is removed. A whitespace-only value is still a value, sealed and used as sent. `null` and an absent `secret` keep the stored credential, as before.
16+
- **Rows sealed before.** A datasource whose stored credential decrypts to an empty value still fails closed at connect (`failed-credentials`), and its status reason now says the credential is empty instead of blaming a missing `sys_secret` row or a changed encryption key.
17+
- **Who moves.** The console sends `secret` only when the field holds a value, so it never sent an empty one. A script or SDK call that sends `"secret": ""` to mean "no change" gets the 400.
18+
19+
**The remedy.** To keep the stored credential, leave `secret` out of the request (or send `null`). To replace it, send the new credential.

‎packages/services/service-datasource/src/__tests__/datasource-connection-service.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -987,6 +987,19 @@ describe('D3 credential resolution — fail-closed', () => {
987987
expect(factory.create).not.toHaveBeenCalled();
988988
});
989989

990+
// [#28928] A row sealed before the doors refused an empty `secret` decrypts
991+
// to ''. Still fail-closed, but the reason names an empty credential, not a
992+
// missing row or a changed key.
993+
it('fails closed on a credential that decrypts to an empty value, and says it is empty', async () => {
994+
const factory = fakeFactory();
995+
const { service } = svc({ factory, secrets: { resolve: async () => '' } });
996+
const result = await service.connect(credExternal, { context: { trigger: 'runtime-admin' } });
997+
expect(result.status).toBe('failed-credentials');
998+
expect(result.reason).toMatch(/credential 'sys_secret:abc' is empty/);
999+
expect(result.reason).not.toMatch(/could not be resolved|missing sys_secret row|encryption key/);
1000+
expect(factory.create).not.toHaveBeenCalled();
1001+
});
1002+
9901003
it('fails closed when the resolver throws', async () => {
9911004
const factory = fakeFactory();
9921005
const { service } = svc({
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect, vi } from 'vitest';
4+
import { HonoHttpServer } from '@objectstack/plugin-hono-server';
5+
import { registerDatasourceAdminRoutes } from '../admin-routes.js';
6+
import {
7+
DatasourceAdminService,
8+
type DatasourceAdminServiceConfig,
9+
type ProbeInput,
10+
type StoredDatasource,
11+
} from '../datasource-admin-service.js';
12+
import {
13+
ENTITLED_CREDENTIAL,
14+
createSessionAuthService,
15+
createGrantsEngine,
16+
} from './entitled-caller.fixture.js';
17+
18+
/**
19+
* #28928 — an empty `secret` is refused at the datasource admin doors, never
20+
* sealed as the credential.
21+
*
22+
* `POST /api/v1/datasources` and `PATCH /api/v1/datasources/:name` take a
23+
* door-only `secret` and seal it into the secret store. `"secret": ""` was
24+
* read as a value: the create sealed an empty credential, and an update
25+
* minted a new `sys_secret` holding an empty value, repointed
26+
* `external.credentialsRef` at it and removed the working one. The pool in
27+
* service kept running, so the datasource broke only at the next connect.
28+
*
29+
* Now both doors refuse it `400` naming `secret`, before any write: no secret
30+
* is written, the stored record and its `credentialsRef` are unchanged, and no
31+
* secret is removed. `null`, an absent `secret` and a real one are unchanged.
32+
*
33+
* Driven through the REAL routes over the REAL service on in-memory stores
34+
* (the harness of `datasource-admin-declared-keys-kept.test.ts`). Every
35+
* secret below is an obvious placeholder.
36+
*/
37+
38+
const authService = createSessionAuthService();
39+
const grantsEngine = createGrantsEngine();
40+
41+
const BASE = { driver: 'postgres', config: { host: 'db.example.invalid', database: 'analytics', username: 'qa' } };
42+
const WORKING_REF = 'sys_secret:sec_working';
43+
const PLACEHOLDER_SECRET = 'dummy-rotated-password';
44+
45+
/** In-memory stores behind a real {@link DatasourceAdminService}, recording every seam call. */
46+
function makeDoor(seed: StoredDatasource[] = []) {
47+
const records = new Map<string, StoredDatasource>(seed.map((r) => [r.name, structuredClone(r)]));
48+
const ops: string[] = [];
49+
const pooled: StoredDatasource[] = [];
50+
const probes: ProbeInput[] = [];
51+
const written: string[] = [];
52+
53+
const config: DatasourceAdminServiceConfig = {
54+
probe: async (input) => {
55+
ops.push('probe');
56+
probes.push(structuredClone(input));
57+
return { ok: true, latencyMs: 1 };
58+
},
59+
listDatasourceRecords: async () => [...records.values()].map((r) => structuredClone(r)),
60+
getDatasourceRecord: async (name) => {
61+
const r = records.get(name);
62+
return r ? structuredClone(r) : undefined;
63+
},
64+
putDatasourceRecord: async (record) => {
65+
ops.push(`put:${record.name}`);
66+
records.set(record.name, structuredClone(record));
67+
},
68+
deleteDatasourceRecord: async (name) => {
69+
records.delete(name);
70+
},
71+
writeSecret: async (input, hint) => {
72+
ops.push('writeSecret');
73+
written.push(input.value);
74+
return `sys_secret:sec_${hint.name}_${written.length}`;
75+
},
76+
removeSecret: async (ref) => {
77+
ops.push(`removeSecret:${ref}`);
78+
},
79+
countBoundObjects: async () => 0,
80+
listObjectsBoundTo: async () => [],
81+
registerPool: (record) => {
82+
ops.push('registerPool');
83+
pooled.push(structuredClone(record));
84+
},
85+
unregisterPool: () => {
86+
ops.push('unregisterPool');
87+
},
88+
reregisterPool: (_previous, next) => {
89+
ops.push('reregisterPool');
90+
pooled.push(structuredClone(next));
91+
},
92+
};
93+
94+
const service = new DatasourceAdminService(config);
95+
const server = new HonoHttpServer(0);
96+
const ctx = {
97+
getService: vi.fn((name: string) =>
98+
name === 'auth'
99+
? authService
100+
: name === 'objectql' || name === 'data'
101+
? grantsEngine
102+
: name === 'datasource-admin'
103+
? service
104+
: undefined,
105+
),
106+
} as any;
107+
registerDatasourceAdminRoutes(server, ctx, '/api/v1');
108+
const app = server.getRawApp();
109+
110+
const send = (method: string, path: string, body?: unknown) =>
111+
app.fetch(
112+
new Request(`http://local/api/v1${path}`, {
113+
method,
114+
headers: { 'content-type': 'application/json', authorization: ENTITLED_CREDENTIAL },
115+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
116+
}),
117+
);
118+
119+
return { send, records, ops, pooled, probes, written };
120+
}
121+
122+
/** A runtime datasource bound to a working credential. */
123+
const STORED: StoredDatasource = {
124+
name: 'wh',
125+
...BASE,
126+
origin: 'runtime',
127+
external: { credentialsRef: WORKING_REF },
128+
} as StoredDatasource;
129+
130+
async function expectSecretRefusal(res: Response): Promise<string> {
131+
const body = (await res.json()) as { success: boolean; error?: { code: string; message: string } };
132+
expect({ status: res.status, success: body.success, code: body.error?.code }).toEqual({
133+
status: 400,
134+
success: false,
135+
code: 'DATASOURCE_ADMIN_ERROR',
136+
});
137+
expect(body.error!.message).toContain('`secret`');
138+
return body.error!.message;
139+
}
140+
141+
describe('PATCH /api/v1/datasources/:name — an empty secret (#28928)', () => {
142+
for (const [label, secret] of [['an empty string', ''], ['an empty `value` object', { value: '' }]] as const) {
143+
it(`${label} is refused 400 naming \`secret\`; the credential, its ref and the record are unchanged`, async () => {
144+
const { send, records, ops, written } = makeDoor([STORED]);
145+
await expectSecretRefusal(await send('PATCH', '/datasources/wh', { secret }));
146+
expect(records.get('wh')).toEqual(STORED);
147+
expect(written).toEqual([]);
148+
expect(ops).toEqual([]);
149+
});
150+
}
151+
152+
it('control: a real secret still rotates (a new ref, the old one removed)', async () => {
153+
const { send, records, ops, written } = makeDoor([STORED]);
154+
expect((await send('PATCH', '/datasources/wh', { secret: PLACEHOLDER_SECRET })).status).toBe(200);
155+
expect(written).toEqual([PLACEHOLDER_SECRET]);
156+
expect(records.get('wh')?.external?.credentialsRef).toBe('sys_secret:sec_wh_1');
157+
expect(ops).toContain(`removeSecret:${WORKING_REF}`);
158+
});
159+
160+
for (const [label, body] of [['`secret: null`', { secret: null, label: 'Warehouse' }], ['no `secret`', { label: 'Warehouse' }]] as const) {
161+
it(`control: ${label} changes no credential`, async () => {
162+
const { send, records, ops, written } = makeDoor([STORED]);
163+
expect((await send('PATCH', '/datasources/wh', body)).status).toBe(200);
164+
expect(written).toEqual([]);
165+
expect(records.get('wh')?.external?.credentialsRef).toBe(WORKING_REF);
166+
expect(ops.some((op) => op.startsWith('removeSecret'))).toBe(false);
167+
});
168+
}
169+
});
170+
171+
describe('POST /api/v1/datasources — an empty secret (#28928)', () => {
172+
it('is refused 400 naming `secret`; nothing is stored and no secret is written', async () => {
173+
const { send, records, ops, written } = makeDoor();
174+
await expectSecretRefusal(await send('POST', '/datasources', { name: 'wh', ...BASE, secret: '' }));
175+
expect(records.has('wh')).toBe(false);
176+
expect(written).toEqual([]);
177+
expect(ops).toEqual([]);
178+
});
179+
180+
it('control: a real secret is sealed and bound', async () => {
181+
const { send, records, written } = makeDoor();
182+
expect((await send('POST', '/datasources', { name: 'wh', ...BASE, secret: PLACEHOLDER_SECRET })).status).toBe(201);
183+
expect(written).toEqual([PLACEHOLDER_SECRET]);
184+
expect(records.get('wh')?.external?.credentialsRef).toBe('sys_secret:sec_wh_1');
185+
});
186+
187+
it('control: `secret: null` creates the datasource with no credential', async () => {
188+
const { send, records, written } = makeDoor();
189+
expect((await send('POST', '/datasources', { name: 'wh', ...BASE, secret: null })).status).toBe(201);
190+
expect(written).toEqual([]);
191+
expect(records.get('wh')?.external?.credentialsRef).toBeUndefined();
192+
});
193+
});

‎packages/services/service-datasource/src/datasource-admin-service.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,29 @@ export function datasourceNotFoundError(name: string): Error {
473473
return err;
474474
}
475475

476+
/**
477+
* [#28928] Refuse a `secret` whose value is the empty string, on create and on
478+
* edit, before anything is read for the secret or written.
479+
*
480+
* A create sealed it as the datasource's credential, and an edit took it as a
481+
* rotation: a new `sys_secret` row holding nothing, `external.credentialsRef`
482+
* repointed at it, and the working row removed. The live pool kept serving, so
483+
* the datasource broke only at its next connect, with nothing left to restore.
484+
* The console never sends one (it leaves `secret` out of an untouched field);
485+
* a script or an SDK call that clears the field is what reached it.
486+
*
487+
* `null` and an absent `secret` are unchanged: they keep the stored
488+
* credential. A whitespace-only value is a value, sealed and used as sent.
489+
* Only the empty string is judged, so the answer cannot echo a credential.
490+
*/
491+
function assertSecretNotEmpty(heading: string, secret: SecretInput | undefined): void {
492+
if (secret == null || (secret as { value?: unknown }).value !== '') return;
493+
throw new Error(
494+
`${heading}\nThe \`secret\` is empty. Send the credential to store, or leave \`secret\` out (or null) `
495+
+ 'to keep the stored one. Nothing was written.',
496+
);
497+
}
498+
476499
function metadataIncompleteError(message: string, errors: string[]): Error {
477500
const err = new Error(message) as Error & { code?: string; status?: number; cause?: unknown };
478501
err.code = 'SERVICE_UNAVAILABLE';
@@ -793,6 +816,7 @@ export class DatasourceAdminService implements IDatasourceAdminService {
793816

794817
async createDatasource(input: DatasourceDraft, secret?: SecretInput): Promise<DatasourceSummary> {
795818
this.assertValidName(input?.name);
819+
assertSecretNotEmpty(`Invalid datasource '${input.name}'.`, secret);
796820
this.assertNoDraftCredentialsRef(input);
797821
this.assertNoUndeclaredTopLevelKey(`Invalid datasource '${input.name}'.`, input);
798822
assertNoInlineSslKey(`Invalid datasource '${input.name}'.`, input);
@@ -862,6 +886,7 @@ export class DatasourceAdminService implements IDatasourceAdminService {
862886
// judges a key the author is writing now.
863887
this.assertNoUndeclaredTopLevelKey(`Invalid datasource '${existing.name}'.`, patch);
864888
assertNoInlineSslKey(`Invalid datasource '${existing.name}'.`, patch);
889+
assertSecretNotEmpty(`Invalid datasource '${existing.name}'.`, secret);
865890

866891
// Merge patch over the existing record; `name`/`origin` are never patched.
867892
// [#28633] Every key the create door stores is patchable the same way

‎packages/services/service-datasource/src/datasource-connection-service.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -727,7 +727,21 @@ export class DatasourceConnectionService {
727727
} catch (err) {
728728
return this.handleFailure(record, 'failed-credentials', `resolving credential '${credentialsRef}' threw: ${errMsg(err)}`, opts.context, opts.objects, opts.mappedObjects, err);
729729
}
730-
if (secret == null || secret === '') {
730+
// [#28928] An empty credential is told apart from one that is gone: the
731+
// admin doors refuse an empty `secret` now, but a row sealed before that
732+
// decrypts to '' and its datasource still reaches this branch. Blaming a
733+
// missing row or a changed key would send the operator after the wrong
734+
// fault; the fix is to set the credential again.
735+
if (secret === '') {
736+
return this.handleFailure(
737+
record,
738+
'failed-credentials',
739+
`credential '${credentialsRef}' is empty (its sys_secret row holds an empty value); set the datasource's secret again`,
740+
opts.context,
741+
opts.objects,
742+
);
743+
}
744+
if (secret == null) {
731745
return this.handleFailure(
732746
record,
733747
'failed-credentials',

0 commit comments

Comments
 (0)