|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// ADR-0143 D3 / D4 — the `sys_connector_connection` store over a real ObjectQL |
| 4 | +// engine (SQLite, a test crypto provider): a refresh and the "reconnect |
| 5 | +// required" mark are written only over the revision they read, by the write |
| 6 | +// itself; a store that cannot be read refuses a connect and a revoke with the |
| 7 | +// declared 503. The values below are obvious dummies. |
| 8 | + |
| 9 | +import { afterEach, describe, expect, it } from 'vitest'; |
| 10 | +import { ObjectQL } from '@objectstack/objectql'; |
| 11 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 12 | +import { SysSecret } from '@objectstack/platform-objects'; |
| 13 | +import type { CryptoContext, CryptoHandle, ICryptoProvider } from '@objectstack/spec/contracts'; |
| 14 | + |
| 15 | +import { |
| 16 | + CONNECTOR_CONNECTION_OBJECT, |
| 17 | + ConnectorConnectionStore, |
| 18 | + type ConnectorConnectionRecord, |
| 19 | +} from './connector-connections.js'; |
| 20 | +import type { ConnectorCredentialEngine } from './connector-credentials.js'; |
| 21 | +import { SysConnectorConnection } from './sys-connector-connection.object.js'; |
| 22 | + |
| 23 | +const SYSTEM = { isSystem: true } as const; |
| 24 | + |
| 25 | +function fakeCrypto(): ICryptoProvider { |
| 26 | + let n = 0; |
| 27 | + return { |
| 28 | + async encrypt(plain: string, _ctx: CryptoContext): Promise<CryptoHandle> { |
| 29 | + n += 1; |
| 30 | + return { id: `sec_${n}`, kmsKeyId: 'test', alg: 'test-rev', version: 1, ciphertext: [...plain].reverse().join('') }; |
| 31 | + }, |
| 32 | + async decrypt(handle: CryptoHandle): Promise<string> { |
| 33 | + return [...handle.ciphertext].reverse().join(''); |
| 34 | + }, |
| 35 | + async rotateKey(handle: CryptoHandle): Promise<CryptoHandle> { |
| 36 | + return { ...handle, version: handle.version + 1 }; |
| 37 | + }, |
| 38 | + digest: (plain: string) => `d:${plain.length}`, |
| 39 | + keyedDigest: async (plain: string) => `k:${plain.length}`, |
| 40 | + }; |
| 41 | +} |
| 42 | + |
| 43 | +const engines: ObjectQL[] = []; |
| 44 | +afterEach(async () => { |
| 45 | + for (const e of engines.splice(0)) { |
| 46 | + try { await (e as any).destroy?.(); } catch { /* noop */ } |
| 47 | + } |
| 48 | +}); |
| 49 | + |
| 50 | +async function dataEngine(): Promise<ObjectQL> { |
| 51 | + const ql = new ObjectQL(); |
| 52 | + engines.push(ql); |
| 53 | + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); |
| 54 | + await driver.connect(); |
| 55 | + ql.registerDriver(driver, true); |
| 56 | + await ql.init(); |
| 57 | + for (const object of [SysSecret, SysConnectorConnection]) (ql as any).registry.registerObject(object as never, 'test'); |
| 58 | + await ql.syncSchemas(); |
| 59 | + ql.setCryptoProvider(fakeCrypto()); |
| 60 | + return ql; |
| 61 | +} |
| 62 | + |
| 63 | +/** |
| 64 | + * The engine as the store sees it, with `beforeUpdate` run between the store's |
| 65 | + * call and the real write — another replica's write landing in that gap. |
| 66 | + */ |
| 67 | +function interleaved(ql: ObjectQL, beforeUpdate: () => Promise<void>): ConnectorCredentialEngine { |
| 68 | + let armed = true; |
| 69 | + return { |
| 70 | + find: (o, q) => ql.find(o, q as never), |
| 71 | + insert: (o, d, opts) => ql.insert(o, d, opts as never), |
| 72 | + delete: (o, opts) => ql.delete(o, opts as never), |
| 73 | + resolveSecretField: (o, id, f) => (ql as any).resolveSecretField(o, id, f), |
| 74 | + async update(o, d, opts) { |
| 75 | + if (armed) { |
| 76 | + armed = false; |
| 77 | + await beforeUpdate(); |
| 78 | + } |
| 79 | + return ql.update(o, d, opts as never); |
| 80 | + }, |
| 81 | + }; |
| 82 | +} |
| 83 | + |
| 84 | +async function connected(ql: ObjectQL): Promise<{ store: ConnectorConnectionStore; record: ConnectorConnectionRecord }> { |
| 85 | + const store = new ConnectorConnectionStore(() => ql as unknown as ConnectorCredentialEngine); |
| 86 | + const record = await store.connect({ organizationId: 'org_a', connectorName: 'crm', userId: 'usr_admin', refreshToken: 'dummy-rt-1' }); |
| 87 | + return { store, record }; |
| 88 | +} |
| 89 | + |
| 90 | +/** Another replica's reconnect: a fresh grant over the same row, revision raised. */ |
| 91 | +async function reconnectElsewhere(ql: ObjectQL, record: ConnectorConnectionRecord): Promise<void> { |
| 92 | + await ql.update( |
| 93 | + CONNECTOR_CONNECTION_OBJECT, |
| 94 | + { id: record.id, refresh_token: 'dummy-rt-elsewhere', status: 'connected', status_reason: null, revision: record.revision + 1 }, |
| 95 | + { context: SYSTEM } as never, |
| 96 | + ); |
| 97 | +} |
| 98 | + |
| 99 | +describe('ADR-0143 D4 — a refresh is written only over the revision it read', () => { |
| 100 | + it('writes a rotated token and raises the revision when the row has not moved', async () => { |
| 101 | + const ql = await dataEngine(); |
| 102 | + const { store, record } = await connected(ql); |
| 103 | + const expiresAt = new Date('2030-01-01T00:00:00.000Z'); |
| 104 | + expect(await store.recordRefresh(record, { refreshToken: 'dummy-rt-2', scopes: 'crm.read', expiresAt })).toBe(true); |
| 105 | + const now = (await store.read('org_a', 'crm'))!; |
| 106 | + expect(now).toMatchObject({ revision: record.revision + 1, scopes: 'crm.read', expiresAt: expiresAt.toISOString() }); |
| 107 | + expect(await store.resolveRefreshToken(now)).toBe('dummy-rt-2'); |
| 108 | + }); |
| 109 | + |
| 110 | + it('a refresh that rotates nothing keeps the token and the revision, and still writes the expiry', async () => { |
| 111 | + const ql = await dataEngine(); |
| 112 | + const { store, record } = await connected(ql); |
| 113 | + expect(await store.recordRefresh(record, { expiresAt: new Date('2030-01-01T00:00:00.000Z') })).toBe(true); |
| 114 | + const now = (await store.read('org_a', 'crm'))!; |
| 115 | + expect(now.revision).toBe(record.revision); |
| 116 | + expect(now.expiresAt).toBe('2030-01-01T00:00:00.000Z'); |
| 117 | + expect(await store.resolveRefreshToken(now)).toBe('dummy-rt-1'); |
| 118 | + }); |
| 119 | + |
| 120 | + it('⛔ a reconnect landing between the refresh and its write is never overwritten by the stale rotation', async () => { |
| 121 | + const ql = await dataEngine(); |
| 122 | + const { record } = await connected(ql); |
| 123 | + const store = new ConnectorConnectionStore(() => interleaved(ql, () => reconnectElsewhere(ql, record))); |
| 124 | + expect(await store.recordRefresh(record, { refreshToken: 'dummy-rt-stale' })).toBe(false); |
| 125 | + const now = (await store.read('org_a', 'crm'))!; |
| 126 | + expect(now.revision).toBe(record.revision + 1); |
| 127 | + expect(await store.resolveRefreshToken(now)).toBe('dummy-rt-elsewhere'); |
| 128 | + }); |
| 129 | + |
| 130 | + it('⛔ a row revoked since the refresh read it is not written', async () => { |
| 131 | + const ql = await dataEngine(); |
| 132 | + const { store, record } = await connected(ql); |
| 133 | + expect(await store.revoke('org_a', 'crm')).toBe(true); |
| 134 | + expect(await store.recordRefresh(record, { refreshToken: 'dummy-rt-stale' })).toBe(false); |
| 135 | + expect(await store.read('org_a', 'crm')).toBeUndefined(); |
| 136 | + }); |
| 137 | +}); |
| 138 | + |
| 139 | +describe('ADR-0143 D4 — "reconnect required" is written only over the revision that was refused', () => { |
| 140 | + it('marks the refused grant and drops its token when the row has not moved', async () => { |
| 141 | + const ql = await dataEngine(); |
| 142 | + const { store, record } = await connected(ql); |
| 143 | + await store.markReconnectRequired(record, 'the vendor refused the grant'); |
| 144 | + const now = (await store.read('org_a', 'crm'))!; |
| 145 | + expect(now).toMatchObject({ status: 'reconnect_required', statusReason: 'the vendor refused the grant', hasRefreshToken: false }); |
| 146 | + }); |
| 147 | + |
| 148 | + it('⛔ a reconnect landing between the refusal and its write keeps its fresh grant', async () => { |
| 149 | + const ql = await dataEngine(); |
| 150 | + const { record } = await connected(ql); |
| 151 | + const store = new ConnectorConnectionStore(() => interleaved(ql, () => reconnectElsewhere(ql, record))); |
| 152 | + await store.markReconnectRequired(record, 'the vendor refused the grant'); |
| 153 | + const now = (await store.read('org_a', 'crm'))!; |
| 154 | + expect(now).toMatchObject({ status: 'connected', revision: record.revision + 1, hasRefreshToken: true }); |
| 155 | + expect(await store.resolveRefreshToken(now)).toBe('dummy-rt-elsewhere'); |
| 156 | + }); |
| 157 | +}); |
| 158 | + |
| 159 | +describe('ADR-0143 D5 — a reconnect is written only over the revision it read', () => { |
| 160 | + it('replaces the grant and raises the revision', async () => { |
| 161 | + const ql = await dataEngine(); |
| 162 | + const { store, record } = await connected(ql); |
| 163 | + const again = await store.connect({ organizationId: 'org_a', connectorName: 'crm', refreshToken: 'dummy-rt-again' }); |
| 164 | + expect(again.id).toBe(record.id); |
| 165 | + expect(again.revision).toBe(record.revision + 1); |
| 166 | + expect(await store.resolveRefreshToken(again)).toBe('dummy-rt-again'); |
| 167 | + }); |
| 168 | + |
| 169 | + it('⛔ a reconnect racing another one refuses 503 and keeps nothing of its own', async () => { |
| 170 | + const ql = await dataEngine(); |
| 171 | + const { record } = await connected(ql); |
| 172 | + const store = new ConnectorConnectionStore(() => interleaved(ql, () => reconnectElsewhere(ql, record))); |
| 173 | + await expect(store.connect({ organizationId: 'org_a', connectorName: 'crm', refreshToken: 'dummy-rt-loser' })) |
| 174 | + .rejects.toMatchObject({ name: 'ConnectorCredentialUnavailableError', status: 503 }); |
| 175 | + const now = (await store.read('org_a', 'crm'))!; |
| 176 | + expect(await store.resolveRefreshToken(now)).toBe('dummy-rt-elsewhere'); |
| 177 | + }); |
| 178 | +}); |
| 179 | + |
| 180 | +describe('ADR-0143 D5 — a connection store that cannot be read refuses 503, never 500', () => { |
| 181 | + const unreadable = (): ConnectorCredentialEngine => ({ |
| 182 | + find: async () => { throw new Error('dummy driver failure naming row 42'); }, |
| 183 | + insert: async () => { throw new Error('not reached'); }, |
| 184 | + update: async () => { throw new Error('not reached'); }, |
| 185 | + delete: async () => { throw new Error('not reached'); }, |
| 186 | + }); |
| 187 | + |
| 188 | + it.each([ |
| 189 | + ['connect', (s: ConnectorConnectionStore) => s.connect({ organizationId: 'org_a', connectorName: 'crm', refreshToken: 'dummy-rt' })], |
| 190 | + ['revoke', (s: ConnectorConnectionStore) => s.revoke('org_a', 'crm')], |
| 191 | + ] as const)('⛔ %s', async (_verb, act) => { |
| 192 | + const err = await act(new ConnectorConnectionStore(unreadable)).catch((e: unknown) => e); |
| 193 | + expect(err).toMatchObject({ name: 'ConnectorCredentialUnavailableError', status: 503 }); |
| 194 | + expect(String((err as Error).message)).not.toContain('row 42'); |
| 195 | + }); |
| 196 | +}); |
0 commit comments