|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * #29879 — a datasource PATCH whose new configuration fails to connect |
| 5 | + * answers that the previous pool was kept and the new configuration is NOT in |
| 6 | + * force; nothing of the new configuration may then be stored, so the next |
| 7 | + * restart connects the configuration that was serving. |
| 8 | + * |
| 9 | + * The defect: `updateDatasource` stored the merged record, repointed |
| 10 | + * `external.credentialsRef` at the newly sealed secret and removed the |
| 11 | + * working one BEFORE the rebuild. The rebuild failed and the previous pool |
| 12 | + * kept serving, so the answer read "nothing changed", but the restart read |
| 13 | + * the failing credential and the datasource could no longer connect, with |
| 14 | + * the working credential already gone. |
| 15 | + * |
| 16 | + * The rig boots the REAL `DatasourceAdminServicePlugin` and |
| 17 | + * `ExternalDatasourceServicePlugin` behind the REAL admin routes, with the |
| 18 | + * REAL `sys_secret` binder, over one in-memory store (`sys_metadata` and |
| 19 | + * `sys_secret`) that outlives a boot. A restart is a second boot over the |
| 20 | + * same store: fresh registries, fresh pools, the stored rows only. The |
| 21 | + * driver factory's pool connects only with the database's real password, |
| 22 | + * the one fact a wrong secret changes. |
| 23 | + */ |
| 24 | + |
| 25 | +import { describe, it, expect, vi } from 'vitest'; |
| 26 | +import { HonoHttpServer } from '@objectstack/plugin-hono-server'; |
| 27 | +import { |
| 28 | + assertEngineDeleteDispatch, |
| 29 | + assertEngineFindOnePredicate, |
| 30 | + assertEngineUpdateDispatch, |
| 31 | +} from '@objectstack/metadata-core'; |
| 32 | +import type { CryptoContext, CryptoHandle, ICryptoProvider, IDataDriver } from '@objectstack/spec/contracts'; |
| 33 | +import { DatasourceAdminServicePlugin } from '../datasource-admin-plugin.js'; |
| 34 | +import { ExternalDatasourceServicePlugin } from '../plugin.js'; |
| 35 | +import { registerDatasourceAdminRoutes } from '../admin-routes.js'; |
| 36 | +import { createDatasourceSecretBinder } from '../datasource-secret-binder.js'; |
| 37 | +import type { IDatasourceDriverFactory, DatasourceConnectionSpec } from '../contracts/datasource-driver-factory.js'; |
| 38 | +import { ENTITLED_CREDENTIAL, createSessionAuthService, createGrantsEngine } from './entitled-caller.fixture.js'; |
| 39 | + |
| 40 | +type Row = Record<string, unknown>; |
| 41 | + |
| 42 | +/** The database's real password: the only secret its pool connects with. */ |
| 43 | +const REAL_PASSWORD = 'placeholder-real-password'; |
| 44 | +const WRONG_PASSWORD = 'placeholder-wrong-password'; |
| 45 | +const NEW_PASSWORD = 'placeholder-new-password'; |
| 46 | + |
| 47 | +/** The store a restart keeps: `sys_metadata` and `sys_secret`, by table. */ |
| 48 | +function makeStore() { |
| 49 | + return { tables: new Map<string, Row[]>(), seq: 0 }; |
| 50 | +} |
| 51 | +type Store = ReturnType<typeof makeStore>; |
| 52 | + |
| 53 | +function rowsOf(store: Store, table: string): Row[] { |
| 54 | + if (!store.tables.has(table)) store.tables.set(table, []); |
| 55 | + return store.tables.get(table)!; |
| 56 | +} |
| 57 | + |
| 58 | +function matches(row: Row, where: Record<string, unknown>): boolean { |
| 59 | + for (const [k, v] of Object.entries(where)) { |
| 60 | + if (k.startsWith('$')) throw new Error(`fake engine: unsupported operator ${k}`); |
| 61 | + if (v === undefined) continue; |
| 62 | + if (row[k] !== v) return false; |
| 63 | + } |
| 64 | + return true; |
| 65 | +} |
| 66 | + |
| 67 | +/** AAD-binding crypto double, a fresh handle id per seal (as the shipped provider mints). */ |
| 68 | +function fakeCrypto(store: Store): ICryptoProvider { |
| 69 | + const aadOf = (ctx: CryptoContext) => JSON.stringify([ctx.scope, ctx.namespace, ctx.key]); |
| 70 | + return { |
| 71 | + async encrypt(plain: string, ctx: CryptoContext): Promise<CryptoHandle> { |
| 72 | + return { |
| 73 | + id: `sec_${++store.seq}`, |
| 74 | + kmsKeyId: 'local:test:v1', |
| 75 | + alg: 'aes-256-gcm', |
| 76 | + version: 1, |
| 77 | + ciphertext: Buffer.from(JSON.stringify([aadOf(ctx), plain]), 'utf8').toString('base64'), |
| 78 | + }; |
| 79 | + }, |
| 80 | + async decrypt(handle: CryptoHandle, ctx: CryptoContext): Promise<string> { |
| 81 | + const [aad, plain] = JSON.parse(Buffer.from(handle.ciphertext, 'base64').toString('utf8')); |
| 82 | + if (aad !== aadOf(ctx)) throw new Error('AAD mismatch'); |
| 83 | + return plain; |
| 84 | + }, |
| 85 | + async rotateKey(handle: CryptoHandle): Promise<CryptoHandle> { |
| 86 | + return handle; |
| 87 | + }, |
| 88 | + digest: (plain: string) => `sha256:${plain.length}`, |
| 89 | + keyedDigest: async (plain: string) => `k:${plain.length}`, |
| 90 | + }; |
| 91 | +} |
| 92 | + |
| 93 | +/** A pool: it connects only to database `qa` with the real password; its health is its connection. */ |
| 94 | +function passwordFactory(): IDatasourceDriverFactory & { built: string[] } { |
| 95 | + const built: string[] = []; |
| 96 | + return { |
| 97 | + built, |
| 98 | + supports: () => true, |
| 99 | + create: async (spec: DatasourceConnectionSpec) => { |
| 100 | + built.push(spec.secret ?? ''); |
| 101 | + let connected = false; |
| 102 | + const driver = { |
| 103 | + name: 'com.fake.postgres', |
| 104 | + checkHealth: async () => connected, |
| 105 | + disconnect: async () => { |
| 106 | + connected = false; |
| 107 | + }, |
| 108 | + }; |
| 109 | + return { |
| 110 | + driver: driver as unknown as IDataDriver, |
| 111 | + connect: async () => { |
| 112 | + if ((spec.config as { database?: unknown })?.database !== 'qa') throw new Error('database does not exist'); |
| 113 | + if (spec.secret !== REAL_PASSWORD) throw new Error('password authentication failed'); |
| 114 | + connected = true; |
| 115 | + }, |
| 116 | + }; |
| 117 | + }, |
| 118 | + }; |
| 119 | +} |
| 120 | + |
| 121 | +/** One boot over `store`: the real plugins, the real routes, a driver registry of its own. */ |
| 122 | +async function boot(store: Store) { |
| 123 | + const drivers = new Map<string, IDataDriver>(); |
| 124 | + const data = { |
| 125 | + findOne: async (table: string, q: { where: Record<string, unknown> }) => { |
| 126 | + assertEngineFindOnePredicate(table, q); |
| 127 | + return rowsOf(store, table).find((r) => matches(r, q.where)) ?? null; |
| 128 | + }, |
| 129 | + find: async (table: string, q?: { where?: Record<string, unknown>; limit?: number }) => { |
| 130 | + const all = rowsOf(store, table).filter((r) => matches(r, q?.where ?? {})); |
| 131 | + return typeof q?.limit === 'number' ? all.slice(0, q.limit) : all; |
| 132 | + }, |
| 133 | + insert: async (table: string, row: Row) => { |
| 134 | + const stored = { ...row, id: row.id ?? `r_${++store.seq}` }; |
| 135 | + rowsOf(store, table).push(stored); |
| 136 | + return { id: stored.id }; |
| 137 | + }, |
| 138 | + update: async (table: string, row: Row, q: { where: Record<string, unknown> }) => { |
| 139 | + assertEngineUpdateDispatch(row, q); |
| 140 | + for (const r of rowsOf(store, table)) if (matches(r, q.where)) Object.assign(r, row); |
| 141 | + return {}; |
| 142 | + }, |
| 143 | + delete: async (table: string, q: { where: Record<string, unknown> }) => { |
| 144 | + assertEngineDeleteDispatch(q); |
| 145 | + const rows = rowsOf(store, table); |
| 146 | + const before = rows.length; |
| 147 | + for (let i = rows.length - 1; i >= 0; i--) if (matches(rows[i], q.where)) rows.splice(i, 1); |
| 148 | + return { deleted: before - rows.length }; |
| 149 | + }, |
| 150 | + registerDriver: (driver: IDataDriver) => { |
| 151 | + if (!drivers.has(driver.name)) drivers.set(driver.name, driver); |
| 152 | + }, |
| 153 | + unregisterDriver: (name: string) => drivers.delete(name), |
| 154 | + getDriverByName: (name: string) => drivers.get(name), |
| 155 | + registerDatasourceDef: () => {}, |
| 156 | + markDatasourceUnavailable: () => {}, |
| 157 | + clearDatasourceUnavailable: () => {}, |
| 158 | + }; |
| 159 | + |
| 160 | + const registry = new Map<string, Map<string, unknown>>(); |
| 161 | + const metadata = { |
| 162 | + get: async (t: string, n: string) => registry.get(t)?.get(n), |
| 163 | + list: async (t: string) => [...(registry.get(t)?.values() ?? [])], |
| 164 | + register: async (t: string, n: string, d: unknown) => { |
| 165 | + if (!registry.has(t)) registry.set(t, new Map()); |
| 166 | + registry.get(t)!.set(n, d); |
| 167 | + }, |
| 168 | + unregister: async (t: string, n: string) => { |
| 169 | + registry.get(t)?.delete(n); |
| 170 | + }, |
| 171 | + listObjects: async () => [], |
| 172 | + }; |
| 173 | + |
| 174 | + const services = new Map<string, unknown>([ |
| 175 | + ['data', data], |
| 176 | + ['metadata', metadata], |
| 177 | + ['auth', createSessionAuthService()], |
| 178 | + // The routes resolve the caller's grants from `objectql` first. |
| 179 | + ['objectql', createGrantsEngine()], |
| 180 | + ]); |
| 181 | + const logger = { warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: vi.fn() }; |
| 182 | + const ctx: any = { |
| 183 | + getService: (name: string) => { |
| 184 | + if (services.has(name)) return services.get(name); |
| 185 | + throw new Error(`no service ${name}`); |
| 186 | + }, |
| 187 | + registerService: (name: string, svc: unknown) => { |
| 188 | + services.set(name, svc); |
| 189 | + }, |
| 190 | + trigger: async () => {}, |
| 191 | + logger, |
| 192 | + }; |
| 193 | + |
| 194 | + const secrets = createDatasourceSecretBinder({ engine: data as never, cryptoProvider: fakeCrypto(store) }); |
| 195 | + const factory = passwordFactory(); |
| 196 | + const admin = new DatasourceAdminServicePlugin({ driverFactory: factory, secrets, logger }); |
| 197 | + const external = new ExternalDatasourceServicePlugin(); |
| 198 | + await admin.init(ctx); |
| 199 | + await external.init(ctx); |
| 200 | + await admin.start(ctx); |
| 201 | + await external.start(ctx); |
| 202 | + |
| 203 | + const server = new HonoHttpServer(0); |
| 204 | + registerDatasourceAdminRoutes(server, ctx, '/api/v1'); |
| 205 | + const app = server.getRawApp(); |
| 206 | + const send = async (method: string, path: string, body?: unknown) => { |
| 207 | + const res = await app.fetch( |
| 208 | + new Request(`http://local/api/v1${path}`, { |
| 209 | + method, |
| 210 | + headers: { 'content-type': 'application/json', authorization: ENTITLED_CREDENTIAL }, |
| 211 | + ...(body === undefined ? {} : { body: JSON.stringify(body) }), |
| 212 | + }), |
| 213 | + ); |
| 214 | + return { status: res.status, body: (await res.json()) as any }; |
| 215 | + }; |
| 216 | + return { send, factory, logger }; |
| 217 | +} |
| 218 | + |
| 219 | +const CREATE = { |
| 220 | + name: 'r7pg3', |
| 221 | + driver: 'postgres', |
| 222 | + schemaMode: 'external', |
| 223 | + external: {}, |
| 224 | + config: { host: '127.0.0.1', port: 5432, database: 'qa', username: 'qa' }, |
| 225 | +}; |
| 226 | + |
| 227 | +/** The stored datasource record and the `sys_secret` ids, as a restart will read them. */ |
| 228 | +function atRest(store: Store) { |
| 229 | + const row = rowsOf(store, 'sys_metadata').find((r) => r.type === 'datasource' && r.name === CREATE.name); |
| 230 | + return { |
| 231 | + record: row ? JSON.parse(String(row.metadata)) : undefined, |
| 232 | + secretIds: rowsOf(store, 'sys_secret').map((r) => r.id).sort(), |
| 233 | + }; |
| 234 | +} |
| 235 | + |
| 236 | +async function created(store: Store) { |
| 237 | + const first = await boot(store); |
| 238 | + const res = await first.send('POST', '/datasources', { ...CREATE, secret: REAL_PASSWORD }); |
| 239 | + expect({ status: res.status, dsStatus: res.body.data?.status }).toEqual({ status: 201, dsStatus: 'ok' }); |
| 240 | + return first; |
| 241 | +} |
| 242 | + |
| 243 | +describe('PATCH /api/v1/datasources/:name — a new secret that fails to connect (#29879)', () => { |
| 244 | + it('answers NOT in force, stores nothing of it, and the restart still connects', async () => { |
| 245 | + const store = makeStore(); |
| 246 | + const first = await created(store); |
| 247 | + const before = atRest(store); |
| 248 | + expect(before.record.external.credentialsRef).toMatch(/^sys_secret:/); |
| 249 | + expect(before.secretIds).toHaveLength(1); |
| 250 | + |
| 251 | + const res = await first.send('PATCH', `/datasources/${CREATE.name}`, { |
| 252 | + secret: WRONG_PASSWORD, |
| 253 | + label: 'Renamed in the same patch', |
| 254 | + }); |
| 255 | + expect(res.status).toBe(200); |
| 256 | + expect(res.body.data.status).toBe('error'); |
| 257 | + expect(res.body.data.statusReason).toContain('the new configuration is NOT in force'); |
| 258 | + |
| 259 | + // Nothing of the patch is at rest: not the new binding, not the other key, |
| 260 | + // and the secret sealed for it is gone again. |
| 261 | + expect(atRest(store)).toEqual(before); |
| 262 | + // The kept pool still serves. |
| 263 | + expect((await first.send('POST', `/datasources/${CREATE.name}/test`)).body.data).toMatchObject({ ok: true }); |
| 264 | + |
| 265 | + const restarted = await boot(store); |
| 266 | + expect((await restarted.send('POST', `/datasources/${CREATE.name}/test`)).body.data).toMatchObject({ ok: true }); |
| 267 | + expect(restarted.factory.built).toEqual([REAL_PASSWORD]); |
| 268 | + }); |
| 269 | + |
| 270 | + it('the same for a failing config change: the stored config is the one serving', async () => { |
| 271 | + const store = makeStore(); |
| 272 | + const first = await created(store); |
| 273 | + const before = atRest(store); |
| 274 | + |
| 275 | + const res = await first.send('PATCH', `/datasources/${CREATE.name}`, { |
| 276 | + config: { ...CREATE.config, database: 'qa_other' }, |
| 277 | + }); |
| 278 | + expect(res.body.data.statusReason).toContain('the new configuration is NOT in force'); |
| 279 | + expect(atRest(store)).toEqual(before); |
| 280 | + expect((await boot(store)).factory.built).toEqual([REAL_PASSWORD]); |
| 281 | + }); |
| 282 | + |
| 283 | + it('control: a secret that connects is in force and stored, and the one it replaces is retired', async () => { |
| 284 | + const store = makeStore(); |
| 285 | + const first = await created(store); |
| 286 | + const before = atRest(store); |
| 287 | + |
| 288 | + const res = await first.send('PATCH', `/datasources/${CREATE.name}`, { secret: REAL_PASSWORD }); |
| 289 | + expect(res.status).toBe(200); |
| 290 | + expect(res.body.data.status).toBe('ok'); |
| 291 | + |
| 292 | + const after = atRest(store); |
| 293 | + expect(after.record.external.credentialsRef).not.toBe(before.record.external.credentialsRef); |
| 294 | + expect(after.secretIds).toHaveLength(1); |
| 295 | + expect(after.secretIds).not.toEqual(before.secretIds); |
| 296 | + |
| 297 | + const restarted = await boot(store); |
| 298 | + expect((await restarted.send('POST', `/datasources/${CREATE.name}/test`)).body.data).toMatchObject({ ok: true }); |
| 299 | + }); |
| 300 | + |
| 301 | + it('a second failing PATCH after a first stores nothing either', async () => { |
| 302 | + // The first leaves the previous pool serving under a FAILED verdict, so |
| 303 | + // "kept" cannot be read off the verdict the rebuild started from. |
| 304 | + const store = makeStore(); |
| 305 | + const first = await created(store); |
| 306 | + const before = atRest(store); |
| 307 | + for (const secret of [WRONG_PASSWORD, NEW_PASSWORD]) { |
| 308 | + const res = await first.send('PATCH', `/datasources/${CREATE.name}`, { secret }); |
| 309 | + expect(res.body.data.statusReason).toContain('the new configuration is NOT in force'); |
| 310 | + } |
| 311 | + expect(atRest(store)).toEqual(before); |
| 312 | + expect((await boot(store)).factory.built).toEqual([REAL_PASSWORD]); |
| 313 | + }); |
| 314 | +}); |
0 commit comments