diff --git a/.changeset/31699-connection-store-package.md b/.changeset/31699-connection-store-package.md new file mode 100644 index 00000000000..bbf4a13f5fd --- /dev/null +++ b/.changeset/31699-connection-store-package.md @@ -0,0 +1,41 @@ +--- +'@objectstack/service-automation': patch +--- + +feat(service-automation): the connector connection store, the connect door and the OAuth callback read and write one instance by its package and name (ADR-0150 D4, #31699) + +Clause-②: yes (widening) — the connect door (`getConnectorConnection`, `beginConnectorConnection`, `completeConnectorConnection`, `revokeConnectorConnection`) and a dispatch answer new refusals, each listed under "What answers differently"; a connection row now carries its instance's package. The one-holder backstop still keeps every connector name to one package at boot, and while a name has one holder every row of the name answers its one instance, as the read by name did, so on a database where each organization keeps one connection of an instance and the name has one holder, every answer is as before, a declaration that moved to another package or to the environment included. +Metadata-protocol: none +Skills-docs: `content/docs/automation/connectors.mdx` says a callback completes the instance its connect was begun for and the door refuses a name two packages hold. `skills/**` teaches "connect once per organization", which still holds per instance. + + + +Part of #31699 (ADR-0150 child B, PR 3a-ii). PR 3a widened `sys_connector_connection`'s key to `(organization_id, connector_package, connector_name)`; this PR makes the store and its callers use it. + +**The store: `ConnectorConnectionStore`.** + +- `connect`, `read`, `readOrRefuse`, `revoke` and `listFor` take the instance's package (`string`: a package's instance; `null`: no package's). `revoke` and `listFor` require it; on `connect`, `read` and `readOrRefuse` an absent package still reads the bare name, for the callers that know no package. A connect writes `connector_package` on the row it inserts. +- While the name has one holder (its durable resolution, the question the boot backfill asks, disabled packages included, answers one), or no registry can judge it, every row of the name answers its instance, whatever package the row names: a row naming no package, and a row a moved declaration left under its old package, are the instance's connection, as the read by name answered. A connect adopts the row and stamps it with the instance's package in place (design M2; `null` for the environment's or the platform's instance): one row, never two. A revoke removes it. While two packages hold the name, each package reads its own row; a row naming no package, or naming a package that is not one of the holders, is no package's, and with no row of its own the package's read is refused `409` naming `os migrate stored-references bind --table sys_connector_connection`. +- Two rows answering one instance (a package's own row and another row of the name under one holder, or two rows a guard-less database admitted) are refused `409` by the door and `503` by a dispatch, with or without the run's organization, never one of them used; a revoke removes every row that answers. The connection list (`listFor`) still counts such an organization, carrying the refusal: a dispatch with no organization is refused `422` where another organization is connected too, as before, and the materializer does not count it as connected. +- The post-insert take-back that PR 3a added now counts by `(organization, package, name)`. + +**The door and the callback.** + +- The connect door resolves the name to one declared instance and its package: the resolved package's entry; with no registry to ask (a code-registered instance, a composition with no ObjectQL) or no holder, the one declared entry with the package it carries; two holders, or two declared entries with no registry, `409`. +- The begin records the package in the pending authorization (`packageId`, `null` for the environment's or the platform's instance). The callback completes exactly that package's entry, never the name resolved again; when that package no longer declares the instance, the callback is refused `404` before its code is exchanged. A pending record written before this change (no key, at most ten minutes old) resolves the name, as the begin did. +- An instance's package is its entry's stamp when that is a real package, none for the environment's stored entry, and, for an entry with no stamp or the compatibility API's default, the package the name's durable resolution holds it under (the package the boot backfill binds a package-less row of the name to, so a row the instance connected stays its own once bound), else none. The door, the dispatch handle, the materializer and the reconnect-required mark all read by that one rule. When the name resolves to a package no declared entry is the instance of, the door serves the one declared entry with its own package, as with no registry. + +**What answers differently.** + +- `409` at the door where a name has two holders, and where two declared entries share a name with no registry to resolve it; before, the first declared entry was served. +- `409` at the door, and `503` at a dispatch, where two rows answer one instance in one organization (above). Before, the old key kept one row per organization and name, so this needs a database where the guard was refused or a package's row beside an adopted package-less one; when the two rows are met only at the callback, the code has already been exchanged and the connect is refused after it. +- `409` on the read and the revoke of a row of a name two packages hold that names no package, or a package that is not one of the holders (a disabled holder counts: the question is the boot backfill's), where the read answered the row before. Bind it with `os migrate stored-references bind --table sys_connector_connection` and revoke it as its package's, or uninstall one of the holders, after which a revoke of the one remaining instance removes it. +- `404` at the callback when the package its connect recorded no longer declares the instance; before, any entry of the name completed it. + +**Declared deviations from the design review.** + +- M5: no `?package=` on the HTTP door and no spec change. The door addresses one instance by resolving its name; addressing a second holder's instance explicitly comes with the PR that narrows the one-holder backstop, which is the first PR under which two holders can boot, and no later. Until then a name with two holders (a package installed after boot) is refused at every leg of the door, revoke included: its connections stay stored and keep no dispatch, and the remedy is to uninstall one holder or bind the row. +- M6: where the name has no holder or no registry answers, the door serves the one declared entry with the package that entry carries, not `null`: the row a code-registered package instance connects is that package's, as the backfill would bind it. That stamp is durable while the judgment is not (a later registry may resolve the name elsewhere); it never loosens: while two packages hold the name, the stamped row answers only its own package. +- S3: under two holders a package's own row wins over a package-less row of the name, and the package-less row answers neither (ADR-0150 R9 refuses such a row; the store reads around it rather than refusing the package's own connection). The stray row keeps its encrypted refresh token until it is removed: the door is refused `409` at every leg while two packages hold the name (M5), so it is removed by uninstalling one of the holders, after which the name has one holder, every row of it answers that instance, and a revoke removes them all. + +**In-process APIs.** None public: the store, the pending authorization and the grant handle are internal modules of `@objectstack/service-automation`, none exported from its entry point. diff --git a/content/docs/automation/connectors.mdx b/content/docs/automation/connectors.mdx index 594b14c82b7..a726ee031cd 100644 --- a/content/docs/automation/connectors.mdx +++ b/content/docs/automation/connectors.mdx @@ -757,7 +757,10 @@ a rotating refresh token is never spent twice. encrypted in `sys_connector_connection`, one row per organization and instance, an instance being its package and name (one per organization for an instance the environment authored or a plugin registers); it is - not a sign-in account, and signing in never touches it. A run dispatches + not a sign-in account, and signing in never touches it. A callback + completes the instance its connect was begun for, never the name read + again, and the connect door refuses with `409` a name two packages hold + rather than pick one. A run dispatches with its own organization's connection; a run with no organization uses the instance's only connection, and is refused when there are several. When the grant stops working, the connection is marked **reconnect required** and the diff --git a/packages/services/service-automation/src/connector-connection-door.test.ts b/packages/services/service-automation/src/connector-connection-door.test.ts index cbf2fe51c89..e5e535b7063 100644 --- a/packages/services/service-automation/src/connector-connection-door.test.ts +++ b/packages/services/service-automation/src/connector-connection-door.test.ts @@ -25,7 +25,7 @@ import { createServer, type IncomingMessage, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { LiteKernel } from '@objectstack/core'; -import { ObjectQL } from '@objectstack/objectql'; +import { ObjectQL, SchemaRegistry } from '@objectstack/objectql'; import { collectMaskedReadFields } from '@objectstack/objectql/core'; import { SqlDriver } from '@objectstack/driver-sql'; import { SysSecret } from '@objectstack/platform-objects'; @@ -237,7 +237,14 @@ async function dataEngine(): Promise { return ql; } -async function boot(declared: unknown[] = [crm()], opts: { redirectUri?: string | null; cluster?: unknown; noData?: boolean } = {}) { +/** + * `opts.registry` (#31699): a real package-scoped registry the door's name + * resolution asks; the declared list stays `declared` either way. + */ +async function boot( + declared: unknown[] = [crm()], + opts: { redirectUri?: string | null; cluster?: unknown; noData?: boolean; registry?: SchemaRegistry } = {}, +) { const ql = await dataEngine(); const provider = grantedProvider(); const kernel = new LiteKernel({ logger: { level: 'debug', format: 'json' } } as never); @@ -253,7 +260,9 @@ async function boot(declared: unknown[] = [crm()], opts: { redirectUri?: string version: '1.0.0', dependencies: ['com.objectstack.service-automation'], async init(ctx: any) { - ctx.registerService('objectql', { registry: { listItems: (t: string) => (t === 'connector' ? declared : []) } }); + const listItems = (t: string) => (t === 'connector' ? declared : []); + const registry = opts.registry ? Object.assign(Object.create(opts.registry), { listItems }) : { listItems }; + ctx.registerService('objectql', { registry }); if (!opts.noData) ctx.registerService('data', ql); if (opts.cluster) ctx.registerService('cluster', opts.cluster); ctx.getService('automation').registerConnectorProvider('granted', provider.factory, { credentialHandle: true }); @@ -919,3 +928,209 @@ describe("ADR-0143 D2.1 — an instance that takes the installer's OAuth client" expect(SysConnectorConnection.fields.client_has_secret.type).toBe('boolean'); }); }); + +// ─── ADR-0150 D4: one instance by package ──────────────────────────── + +describe('ADR-0150 D4 [#31699] — the connection door connects one instance, by package', () => { + const OTHER = 'com.example.other'; + const rowPackages = async (ql: ObjectQL) => (await rowsOf(ql)).map((r) => r.connector_package ?? null); + + /** `registry` holds `crm` under `id` too (installed, shipped). */ + function hold(r: SchemaRegistry, id: string): SchemaRegistry { + r.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code'); + r.registerItem('connector', crm({ _packageId: id }) as never, 'name' as never, id); + return r; + } + /** A real registry holding `crm` under package `id`. */ + const registryHolding = (id: string) => hold(new SchemaRegistry({ multiTenant: false }), id); + + it('the name resolves to one package: the connect stamps that package on the row, and the read answers it', async () => { + const { engine, connect, ql } = await boot([crm()], { registry: registryHolding('com.example.crm') }); + await (await connect()).done(); + expect(await rowPackages(ql)).toEqual(['com.example.crm']); + expect(await engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never })) + .toMatchObject({ status: 'connected' }); + }); + + it('⛔ two packages hold the name: the read, the begin and the revoke are refused 409 naming both, and nothing is written', async () => { + // A boot refuses a second holder (the one-holder backstop this card + // narrows last), so the second package arrives after the boot. + const declared: unknown[] = [crm()]; + const registry = registryHolding('com.example.crm'); + const { engine, ql } = await boot(declared, { registry }); + declared.push(crm({ _packageId: OTHER })); + hold(registry, OTHER); + for (const leg of [ + () => engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never }), + () => engine.beginConnectorConnection({ connector: 'crm', context: ADMIN_A as never }), + () => engine.revokeConnectorConnection({ connector: 'crm', context: ADMIN_A as never }), + ]) { + const err = (await leg().catch((e: unknown) => e)) as Record; + expect(err).toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(String(err.message)).toContain('com.example.crm'); + expect(String(err.message)).toContain(OTHER); + } + expect(idp.requests).toHaveLength(0); + expect(await rowsOf(ql)).toHaveLength(0); + }); + + it('no registry to ask: the one declared entry is served with the package it carries; the environment’s entry stamps no package', async () => { + const packaged = await boot([crm()]); + await (await packaged.connect()).done(); + expect(await rowPackages(packaged.ql)).toEqual(['com.example.crm']); + + const environment = await boot([crm({ _packageId: 'sys_metadata' })]); + await (await environment.connect()).done(); + expect(await rowPackages(environment.ql)).toEqual([null]); + }); + + it('⛔ no registry and two declared entries of the name: refused 409, never the first one picked', async () => { + const declared: unknown[] = [crm()]; + const { engine } = await boot(declared); + declared.push(crm({ _packageId: OTHER })); + await expect(engine.beginConnectorConnection({ connector: 'crm', context: ADMIN_A as never })) + .rejects.toMatchObject({ status: 409, code: 'RESOURCE_CONFLICT' }); + }); + + it('the callback completes exactly the package the begin recorded, never the name resolved again', async () => { + // Begun with one declared entry; a second package declares the name + // while the browser is away. Resolved again, the name is refused (409): + // the recorded package completes. + const declared: unknown[] = [crm()]; + const { connect, ql } = await boot(declared); + const { done } = await connect(); + declared.push(crm({ _packageId: OTHER })); + await expect(done()).resolves.toMatchObject({ status: 'connected' }); + expect(await rowPackages(ql)).toEqual(['com.example.crm']); + }); + + it('the recorded package is kept when it is none: an environment instance’s callback completes with no package beside a package’s entry', async () => { + const declared: unknown[] = [crm({ _packageId: 'sys_metadata' })]; + const { connect, ql } = await boot(declared); + const { done } = await connect(); + declared.push(crm({ _packageId: OTHER })); + await expect(done()).resolves.toMatchObject({ status: 'connected' }); + expect(await rowPackages(ql)).toEqual([null]); + }); + + it('⛔ the recorded package no longer declares the instance: the callback is refused before its code is used', async () => { + const declared: unknown[] = [crm()]; + const { connect, ql } = await boot(declared); + const { done } = await connect(); + declared.splice(0, 1, crm({ _packageId: OTHER })); + await expect(done()).rejects.toMatchObject({ status: 404 }); + expect(idp.requests).toHaveLength(0); + expect(await rowsOf(ql)).toHaveLength(0); + }); + + /** A row the guard admits beside a package's own: one naming no package (an upgraded database's). */ + const packagelessRow = (ql: ObjectQL, id: string, organizationId: string) => ql.insert(CONNECTOR_CONNECTION_OBJECT, { + id, organization_id: organizationId, connector_name: 'crm', connector_package: null, + grant: 'authorization_code', status: 'connected', revision: 1, + } as never, { context: SYSTEM } as never); + + it('⛔ two rows answer the instance in the one organization: a dispatch with or without the organization is refused 503, never one row used', async () => { + const { call, connect, provider, ql } = await boot([crm()], { registry: registryHolding('com.example.crm') }); + await (await connect()).done(); + await call('org_a'); + await call(); + const sent = [...provider.state.sent]; + await packagelessRow(ql, 'conn_stray', 'org_a'); + for (const organizationId of ['org_a', undefined]) { + await expect(call(organizationId)).rejects.toMatchObject({ status: 503, message: expect.stringContaining('has 2 connections') }); + } + expect(provider.state.sent).toEqual(sent); + }); + + it('⛔ an organization whose read is refused still counts: a dispatch with no organization is refused 422, not run with the other organization', async () => { + const declared: unknown[] = [crm()]; + const registry = registryHolding('com.example.crm'); + const { call, connect, provider, ql } = await boot(declared, { registry }); + await (await connect(ADMIN_B)).done(); + await packagelessRow(ql, 'conn_a', 'org_a'); + declared.push(crm({ _packageId: OTHER })); + hold(registry, OTHER); + await expect(call()).rejects.toMatchObject({ status: 422, message: expect.stringContaining('connected for 2 organizations') }); + expect(provider.state.sent).toEqual([]); + }); + + it('⛔ a package-less row a second (disabled) holder makes no one package’s: the read and the revoke are both refused 409, and the row stays', async () => { + const registry = registryHolding('com.example.crm'); + const { engine, ql } = await boot([crm()], { registry }); + await packagelessRow(ql, 'conn_a', 'org_a'); + hold(registry, OTHER); + registry.disablePackage(OTHER); + for (const leg of [ + () => engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never }), + () => engine.revokeConnectorConnection({ connector: 'crm', context: ADMIN_A as never }), + ]) { + const err = (await leg().catch((e: unknown) => e)) as Record; + expect(err).toMatchObject({ status: 409, message: expect.stringContaining('stored-references bind') }); + } + expect(await rowsOf(ql)).toHaveLength(1); + }); + + it('an entry with no package stamp, or the compatibility default, is the instance of the package the name resolves to: its row stays its own once the backfill binds it', async () => { + for (const stamp of [undefined, '__runtime__']) { + const { connect, call, engine, ql } = await boot([crm({ _packageId: stamp })], { registry: registryHolding('com.example.crm') }); + // A connection the instance kept from before the key carried a package. + await packagelessRow(ql, 'conn_old', 'org_a'); + const read = () => engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never }); + await expect(read(), String(stamp)).resolves.toMatchObject({ status: 'connected' }); + // The boot backfill binds it to the name's one holder: still this instance's. + await ql.update(CONNECTOR_CONNECTION_OBJECT, { id: 'conn_old', connector_package: 'com.example.crm' } as never, { context: SYSTEM } as never); + await expect(read(), String(stamp)).resolves.toMatchObject({ status: 'connected' }); + // A connect writes the holder's package, and replaces the row in place. + await (await connect()).done(); + expect(await rowPackages(ql), String(stamp)).toEqual(['com.example.crm']); + await expect(call('org_a'), String(stamp)).resolves.toMatchObject({ status: 200 }); + } + }); + + it('[contract review F1] a declaration that moves to another package keeps its connection: read, dispatch and revoke, one row', async () => { + const declared: unknown[] = [crm({ _packageId: 'com.example.crm' })]; + const registry = registryHolding('com.example.crm'); + const { engine, connect, call, ql } = await boot(declared, { registry }); + await (await connect()).done(); + expect(await rowPackages(ql)).toEqual(['com.example.crm']); + // The name moves: the old package is uninstalled and another declares it. One holder throughout. + registry.uninstallPackage('com.example.crm'); + registry.unregisterItemsByPackage('com.example.crm'); + hold(registry, OTHER); + declared.splice(0, 1, crm({ _packageId: OTHER })); + expect(await engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never })) + .toMatchObject({ status: 'connected' }); + await expect(call('org_a')).resolves.toMatchObject({ status: 200 }); + await engine.revokeConnectorConnection({ connector: 'crm', context: ADMIN_A as never }); + expect(await rowsOf(ql)).toHaveLength(0); + }); + + it('a resolved holder no declared entry is the instance of: the one declared entry is served, with its own package', async () => { + const { connect, ql } = await boot([crm({ _packageId: OTHER })], { registry: registryHolding('com.example.crm') }); + await expect((await connect()).done()).resolves.toMatchObject({ status: 'connected' }); + expect(await rowPackages(ql)).toEqual([OTHER]); + }); + + it('[contract review F1(b)] there, a row from before the package column (naming none) is the served instance\'s: one holder, read by its name', async () => { + const { engine, connect, ql } = await boot([crm({ _packageId: OTHER })], { registry: registryHolding('com.example.crm') }); + await (await connect()).done(); + const [row] = await rowsOf(ql); + await ql.update(CONNECTOR_CONNECTION_OBJECT, { id: row.id, connector_package: null } as never, { context: SYSTEM } as never); + expect(await engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never })) + .toMatchObject({ status: 'connected' }); + await (await connect()).done(); + expect((await rowsOf(ql)).map((r) => [r.id, r.connector_package])).toEqual([[row.id, OTHER]]); + }); + + it('a row naming no package is adopted by the resolved package’s connect (M2): one row, stamped in place', async () => { + const { connect, ql } = await boot([crm()], { registry: registryHolding('com.example.crm') }); + await (await connect()).done(); + // Strip the stamp: the row an environment connected before the key carried a package. + const [row] = await rowsOf(ql); + await ql.update(CONNECTOR_CONNECTION_OBJECT, { id: row.id, connector_package: null } as never, { context: SYSTEM } as never); + expect(await rowPackages(ql)).toEqual([null]); + await (await connect()).done(); + const rows = await rowsOf(ql); + expect(rows.map((r) => [r.id, r.connector_package])).toEqual([[row.id, 'com.example.crm']]); + }); +}); diff --git a/packages/services/service-automation/src/connector-connection-package.test.ts b/packages/services/service-automation/src/connector-connection-package.test.ts new file mode 100644 index 00000000000..830107bf2d5 --- /dev/null +++ b/packages/services/service-automation/src/connector-connection-package.test.ts @@ -0,0 +1,253 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0150 D4, #31699] The `sys_connector_connection` store reads and writes +// one instance by `(package, name)`, over a real ObjectQL engine (SQLite, a +// test crypto provider), with the key `(organization_id, connector_package, +// connector_name)`. A row naming no package answers a package's instance only +// where the name's durable resolution binds it to that package (or no registry +// can judge it), and is adopted by a connect; a row of a name two packages hold +// is no package's; two rows answering one instance are refused, never picked. +// The values below are obvious dummies. + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysSecret } from '@objectstack/platform-objects'; +import type { CryptoContext, CryptoHandle, ICryptoProvider } from '@objectstack/spec/contracts'; + +import { + CONNECTOR_CONNECTION_OBJECT, + ConnectorConnectionConflictError, + ConnectorConnectionStore, + type ConnectorNullRowHolder, +} from './connector-connections.js'; +import type { ConnectorCredentialEngine } from './connector-credentials.js'; +import { SysConnectorConnection } from './sys-connector-connection.object.js'; + +const SYSTEM = { isSystem: true } as const; +const A = 'com.acme.alpha'; +const B = 'com.acme.beta'; + +function fakeCrypto(): ICryptoProvider { + let n = 0; + return { + async encrypt(plain: string, _ctx: CryptoContext): Promise { + n += 1; + return { id: `sec_${n}`, kmsKeyId: 'test', alg: 'test-rev', version: 1, ciphertext: [...plain].reverse().join('') }; + }, + async decrypt(handle: CryptoHandle): Promise { + return [...handle.ciphertext].reverse().join(''); + }, + async rotateKey(handle: CryptoHandle): Promise { + return { ...handle, version: handle.version + 1 }; + }, + digest: (plain: string) => `d:${plain.length}`, + keyedDigest: async (plain: string) => `k:${plain.length}`, + }; +} + +const engines: ObjectQL[] = []; +afterEach(async () => { + for (const e of engines.splice(0)) { + try { await (e as any).destroy?.(); } catch { /* noop */ } + } +}); + +async function dataEngine(): Promise { + const ql = new ObjectQL(); + engines.push(ql); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + await ql.init(); + for (const object of [SysSecret, SysConnectorConnection]) (ql as any).registry.registerObject(object as never, 'test'); + await ql.syncSchemas(); + ql.setCryptoProvider(fakeCrypto()); + return ql; +} + +/** The durable resolution of the name, as the plugin's resolver answers it. */ +const resolvedTo = (packageId: string): ConnectorNullRowHolder => () => ({ + status: 'resolved', item: {}, holder: { kind: 'package', packageId } as never, via: 'unique-holder', +}); +const environmentHolds: ConnectorNullRowHolder = () => ({ status: 'resolved', item: {}, holder: { kind: 'environment' }, via: 'environment' }); +const twoHolders: ConnectorNullRowHolder = (name) => ({ + status: 'refused', reason: 'ambiguous-in-environment', type: 'connector', name, callerPackageId: null, + candidates: [{ kind: 'package', packageId: A } as never, { kind: 'package', packageId: B } as never], + message: 'two holders', +}); + +async function insertRow(ql: ObjectQL, id: string, pkg: string | null, org = 'org_a'): Promise { + await ql.insert(CONNECTOR_CONNECTION_OBJECT, { + id, organization_id: org, connector_name: 'crm', connector_package: pkg, + grant: 'authorization_code', status: 'connected', revision: 1, + }, { context: SYSTEM } as never); +} + +async function packages(ql: ObjectQL, org = 'org_a'): Promise> { + const rows = (await ql.find(CONNECTOR_CONNECTION_OBJECT, { where: { organization_id: org }, context: SYSTEM } as never)) as Array>; + return rows.map((r) => (r.connector_package as string | null) ?? null).sort(); +} + +function storeOver(ql: ObjectQL, holder?: ConnectorNullRowHolder): ConnectorConnectionStore { + return new ConnectorConnectionStore(() => ql as unknown as ConnectorCredentialEngine, holder); +} + +describe('[#31699] one instance is read and written by its package', () => { + it('a connect names the instance\'s package and that package reads it; another instance reads it only while the name has one holder', async () => { + const ql = await dataEngine(); + const store = storeOver(ql, resolvedTo(A)); + const record = await store.connect({ organizationId: 'org_a', connectorName: 'crm', packageId: A, refreshToken: 'dummy-rt' }); + expect(record.packageId).toBe(A); + expect((await store.read('org_a', 'crm', A))?.id).toBe(record.id); + expect((await store.read('org_a', 'crm'))?.id).toBe(record.id); + // One holder: the name's connection, as the read by name answered (red line 3). + expect((await store.read('org_a', 'crm', null))?.id).toBe(record.id); + // Two holders: the package's row is that package's alone. + expect(await storeOver(ql, twoHolders).read('org_a', 'crm', null)).toBeUndefined(); + expect(await storeOver(ql, twoHolders).read('org_a', 'crm', B)).toBeUndefined(); + }); + + it('an environment instance (package null) writes and reads the row naming none', async () => { + const ql = await dataEngine(); + const store = storeOver(ql, environmentHolds); + const record = await store.connect({ organizationId: 'org_a', connectorName: 'crm', packageId: null, refreshToken: 'dummy-rt' }); + expect(record.packageId).toBeNull(); + expect((await store.read('org_a', 'crm', null))?.id).toBe(record.id); + // Two holders: a row naming no package is no one package's. + await expect(storeOver(ql, twoHolders).read('org_a', 'crm', A)).rejects.toBeInstanceOf(ConnectorConnectionConflictError); + expect((await storeOver(ql, twoHolders).read('org_a', 'crm', null))?.id).toBe(record.id); + }); +}); + +describe('[#31699, design review M2] a row naming no package is the package\'s the name resolves to, and a connect adopts it', () => { + it('one holder: the package reads the row, and a reconnect stamps it in place: one row, never two', async () => { + const ql = await dataEngine(); + await insertRow(ql, 'c0', null); + const store = storeOver(ql, resolvedTo(A)); + expect((await store.read('org_a', 'crm', A))?.id).toBe('c0'); + const record = await store.connect({ organizationId: 'org_a', connectorName: 'crm', packageId: A, refreshToken: 'dummy-rt-2' }); + expect(record.id).toBe('c0'); + expect(record.packageId).toBe(A); + expect(await packages(ql)).toEqual([A]); + }); + + it('no registry to judge it: the row answers as it did before the package column', async () => { + const ql = await dataEngine(); + await insertRow(ql, 'c0', null); + expect((await storeOver(ql).read('org_a', 'crm', A))?.id).toBe('c0'); + }); + + it('the name resolves to another package: one holder, so the row answers by its name, as before', async () => { + const ql = await dataEngine(); + await insertRow(ql, 'c0', null); + expect((await storeOver(ql, resolvedTo(B)).read('org_a', 'crm', A))?.id).toBe('c0'); + }); +}); + +describe('[#31699, contract review F1] a declaration that moves keeps its connection while the name has one holder', () => { + it('to another package: the new package reads the old package\'s row, a connect stamps it in place, and a revoke removes it', async () => { + const ql = await dataEngine(); + await insertRow(ql, 'c0', A); + const store = storeOver(ql, resolvedTo(B)); + expect((await store.read('org_a', 'crm', B))?.id).toBe('c0'); + const record = await store.connect({ organizationId: 'org_a', connectorName: 'crm', packageId: B, refreshToken: 'dummy-rt-b' }); + expect(record.id).toBe('c0'); + expect(await packages(ql)).toEqual([B]); + expect(await store.revoke('org_a', 'crm', undefined, B)).toBe(true); + expect(await packages(ql)).toEqual([]); + }); + + it('to the environment: the environment\'s instance reads the package\'s row, and a connect clears its stamp', async () => { + const ql = await dataEngine(); + await insertRow(ql, 'c0', A); + const store = storeOver(ql, environmentHolds); + expect((await store.read('org_a', 'crm', null))?.id).toBe('c0'); + const record = await store.connect({ organizationId: 'org_a', connectorName: 'crm', packageId: null, refreshToken: 'dummy-rt-env' }); + expect(record.id).toBe('c0'); + expect(record.packageId).toBeNull(); + expect(await packages(ql)).toEqual([null]); + }); + + it('two holders: a row naming a package that holds no longer is no one package\'s; a row naming a holder is that holder\'s', async () => { + const ql = await dataEngine(); + await insertRow(ql, 'c0', 'com.acme.gone'); + const store = storeOver(ql, twoHolders); + const refusal = await store.read('org_a', 'crm', A).then(() => undefined, (e: unknown) => e); + expect(refusal).toBeInstanceOf(ConnectorConnectionConflictError); + expect((refusal as Error).message).toMatch(/os migrate stored-references bind/); + await expect(store.revoke('org_a', 'crm', undefined, A)).rejects.toBeInstanceOf(ConnectorConnectionConflictError); + expect(await packages(ql)).toEqual(['com.acme.gone']); + + const held = await dataEngine(); + await insertRow(held, 'c1', A); + expect(await storeOver(held, twoHolders).read('org_a', 'crm', B)).toBeUndefined(); + expect((await storeOver(held, twoHolders).read('org_a', 'crm', A))?.id).toBe('c1'); + }); +}); + +describe('[#31699, ADR-0150 red line 2] two packages hold the name: a row naming none is no one package\'s', () => { + it('it is all a package has: the read is refused 409, naming the bind, and nothing is written', async () => { + const ql = await dataEngine(); + await insertRow(ql, 'c0', null); + const store = storeOver(ql, twoHolders); + const refusal = await store.readOrRefuse('org_a', 'crm', A).then(() => undefined, (e: unknown) => e); + expect(refusal).toBeInstanceOf(ConnectorConnectionConflictError); + expect((refusal as ConnectorConnectionConflictError).status).toBe(409); + expect((refusal as Error).message).toMatch(/os migrate stored-references bind/); + await expect(store.connect({ organizationId: 'org_a', connectorName: 'crm', packageId: A, refreshToken: 'x' })) + .rejects.toBeInstanceOf(ConnectorConnectionConflictError); + expect(await packages(ql)).toEqual([null]); + }); + + it('beside the package\'s own row: the own row answers; a revoke of the package leaves the row naming none', async () => { + const ql = await dataEngine(); + await insertRow(ql, 'c0', null); + await insertRow(ql, 'c1', A); + const store = storeOver(ql, twoHolders); + expect((await store.read('org_a', 'crm', A))?.id).toBe('c1'); + expect(await store.revoke('org_a', 'crm', undefined, A)).toBe(true); + expect(await packages(ql)).toEqual([null]); + }); + + it('each package connects its own instance in one organization (the key admits both)', async () => { + const ql = await dataEngine(); + const store = storeOver(ql, twoHolders); + await store.connect({ organizationId: 'org_a', connectorName: 'crm', packageId: A, refreshToken: 'a' }); + await store.connect({ organizationId: 'org_a', connectorName: 'crm', packageId: B, refreshToken: 'b' }); + expect(await packages(ql)).toEqual([A, B]); + expect((await store.read('org_a', 'crm', A))?.packageId).toBe(A); + expect((await store.read('org_a', 'crm', B))?.packageId).toBe(B); + // A caller that knows only the name gets no pick of the two. + await expect(store.read('org_a', 'crm')).rejects.toBeInstanceOf(ConnectorConnectionConflictError); + }); +}); + +describe('[#31699, design review S2] two rows answering one instance are refused, never picked by row order', () => { + it('the package\'s row and a row naming none it adopts: the read refuses; a revoke removes both', async () => { + const ql = await dataEngine(); + await insertRow(ql, 'c0', null); + await insertRow(ql, 'c1', A); + const store = storeOver(ql, resolvedTo(A)); + await expect(store.read('org_a', 'crm', A)).rejects.toThrow(/has 2 connections in this organization/); + expect(await store.revoke('org_a', 'crm', undefined, A)).toBe(true); + expect(await packages(ql)).toEqual([]); + }); + + it('listFor counts one entry per organization, and one whose read is refused carries the refusal, never a row as its connection', async () => { + const ql = await dataEngine(); + await insertRow(ql, 'c0', null, 'org_a'); + await insertRow(ql, 'c1', A, 'org_a'); + await insertRow(ql, 'c2', A, 'org_b'); + await insertRow(ql, 'c3', null, 'org_c'); + const listed = await storeOver(ql, resolvedTo(A)).listFor('crm', A); + const byOrganization = Object.fromEntries(listed.map((r) => [r.organizationId, r.conflict])); + expect(Object.keys(byOrganization).sort()).toEqual(['org_a', 'org_b', 'org_c']); + expect(byOrganization.org_a).toContain('has 2 connections'); + expect(byOrganization.org_b).toBeUndefined(); + expect(byOrganization.org_c).toBeUndefined(); + // Two holders: org_c's package-less row is no package's, listed with the read's refusal. + const twoHeld = await storeOver(ql, twoHolders).listFor('crm', A); + expect(twoHeld.find((r) => r.organizationId === 'org_c')?.conflict).toContain('stored-references bind'); + }); +}); diff --git a/packages/services/service-automation/src/connector-connections.test.ts b/packages/services/service-automation/src/connector-connections.test.ts index 3ed8eeaf3bd..ba6dbfab6c9 100644 --- a/packages/services/service-automation/src/connector-connections.test.ts +++ b/packages/services/service-automation/src/connector-connections.test.ts @@ -135,7 +135,7 @@ describe('ADR-0143 D4 — a refresh is written only over the revision it read', it('⛔ a row revoked since the refresh read it is not written', async () => { const ql = await dataEngine(); const { store, record } = await connected(ql); - expect(await store.revoke('org_a', 'crm')).toBe(true); + expect(await store.revoke('org_a', 'crm', undefined, null)).toBe(true); expect(await store.recordRefresh(record, { refreshToken: 'dummy-rt-stale' })).toBe(false); expect(await store.read('org_a', 'crm')).toBeUndefined(); }); @@ -198,7 +198,7 @@ describe('ADR-0143 D5 — a connection store that cannot be read refuses 503, ne it.each([ ['connect', (s: ConnectorConnectionStore) => s.connect({ organizationId: 'org_a', connectorName: 'crm', refreshToken: 'dummy-rt' })], - ['revoke', (s: ConnectorConnectionStore) => s.revoke('org_a', 'crm')], + ['revoke', (s: ConnectorConnectionStore) => s.revoke('org_a', 'crm', undefined, null)], ] as const)('⛔ %s', async (_verb, act) => { const err = await act(new ConnectorConnectionStore(unreadable)).catch((e: unknown) => e); expect(err).toMatchObject({ name: 'ConnectorCredentialUnavailableError', status: 503 }); diff --git a/packages/services/service-automation/src/connector-connections.ts b/packages/services/service-automation/src/connector-connections.ts index 15b79d793c2..b40a2cc3948 100644 --- a/packages/services/service-automation/src/connector-connections.ts +++ b/packages/services/service-automation/src/connector-connections.ts @@ -15,6 +15,8 @@ * organization, the instance, a status and a revision — never a token. */ +import type { PackageScopedResolution } from '@objectstack/objectql'; + import { ConnectorCredentialUnavailableError, isSecretProtectionFailure, @@ -43,6 +45,43 @@ export const CONNECTOR_CONNECTION_CLIENT_ID_FIELD = 'client_id'; /** Whether the installer's client came with a secret (kept only inside the encrypted client). */ export const CONNECTOR_CONNECTION_CLIENT_HAS_SECRET_FIELD = 'client_has_secret'; +/** Its package column: the package of the instance the row connects (ADR-0150 D4, D8 row R11). */ +export const CONNECTOR_CONNECTION_PACKAGE_FIELD = 'connector_package'; + +/** + * [ADR-0150 D4, #31699] Which instance of a connector name a store call is + * about: a package id, `null` for an instance the environment authored or a + * plugin registers in code, or `undefined` for a caller that knows only the + * name (every row of the name in the organization answers it, and two + * refuse). + */ +export type ConnectorInstancePackage = string | null | undefined; + +/** + * [#31699] How many holders the connector name has: its durable resolution + * for a caller with no package (disabled packages counted), the question the + * boot backfill asks before it binds a row naming no package. While it + * answers one holder, every row of the name is the one instance's; when it + * refuses (two holders), each package's rows are its own. `undefined` when + * the composition has no registry to ask. + */ +export type ConnectorNullRowHolder = (connectorName: string) => PackageScopedResolution | undefined; + +/** + * [#31699] Two rows answer one instance in one organization, or a row of a + * name two packages hold names none of them: answered `409`, never one of them + * picked. + */ +export class ConnectorConnectionConflictError extends Error { + readonly code = 'RESOURCE_CONFLICT'; + readonly status = 409; + readonly statusCode = 409; + constructor(message: string) { + super(message); + this.name = 'ConnectorConnectionConflictError'; + } +} + /** A connection's status (`not connected` is the absence of a row). */ export type ConnectorConnectionRowStatus = 'connected' | 'reconnect_required'; @@ -54,6 +93,8 @@ export interface ConnectorConnectionRecord { id: string; organizationId: string; connectorName: string; + /** [#31699] The package the row names, `null` when it names none. */ + packageId: string | null; status: ConnectorConnectionRowStatus; statusReason?: string; /** The granted scopes, as the authorization server answered them. */ @@ -76,11 +117,18 @@ export interface ConnectorConnectionRecord { installerClientHasSecret: boolean; connectedAt?: string; connectedBy?: string; + /** + * [#31699] Set only on a {@link ConnectorConnectionStore.listFor} entry: + * the refusal a read of this organization's connection answers (two rows + * answering the instance, or a row of a name two packages hold that + * names none of them). The entry stands for the organization, never as its connection. + */ + conflict?: string; } /** The columns a read asks for — `refresh_token` is never among them; its presence is read from the masked value. */ const RECORD_FIELDS = [ - 'id', 'organization_id', 'connector_name', 'status', 'status_reason', 'scopes', 'expires_at', + 'id', 'organization_id', 'connector_name', CONNECTOR_CONNECTION_PACKAGE_FIELD, 'status', 'status_reason', 'scopes', 'expires_at', 'revision', 'connected_at', 'connected_by', CONNECTOR_CONNECTION_REFRESH_TOKEN_FIELD, CONNECTOR_CONNECTION_REGISTERED_CLIENT_FIELD, CONNECTOR_CONNECTION_CLIENT_ID_FIELD, CONNECTOR_CONNECTION_CLIENT_HAS_SECRET_FIELD, @@ -98,6 +146,7 @@ function toRecord(row: Record): ConnectorConnectionRecord | und id: String(row.id), organizationId: row.organization_id, connectorName: row.connector_name, + packageId: rowPackage(row), status: row.status === 'reconnect_required' ? 'reconnect_required' : 'connected', statusReason: optionalText(row.status_reason), scopes: optionalText(row.scopes), @@ -115,6 +164,12 @@ function toRecord(row: Record): ConnectorConnectionRecord | und }; } +/** The package a row names, `null` when it names none (NULL, absent or empty). */ +function rowPackage(row: Record): string | null { + const value = row[CONNECTOR_CONNECTION_PACKAGE_FIELD]; + return typeof value === 'string' && value.length > 0 ? value : null; +} + /** What a connect, or a refresh that rotated or renewed the grant, writes. */ export interface ConnectorGrantWrite { /** The refresh token to keep; `undefined` keeps the stored one (a server that does not rotate). */ @@ -133,12 +188,95 @@ function affectedRows(result: unknown): number { return Number.isFinite(count) ? count : 0; } +/** [#31699] The refusal of two rows answering one instance in one organization. */ +function twoConnections(connectorName: string, count: number): ConnectorConnectionConflictError { + return new ConnectorConnectionConflictError( + `Connector instance '${connectorName}' has ${count} connections in this organization, and one ` + + 'instance keeps one. Revoke the connection, which removes every one of them, then connect again.', + ); +} + /** * The `sys_connector_connection` store. One per automation plugin. It never * caches a token: {@link resolveRefreshToken} reads the row at the moment of use. */ export class ConnectorConnectionStore { - constructor(private readonly resolveEngine: () => ConnectorCredentialEngine | undefined) {} + constructor( + private readonly resolveEngine: () => ConnectorCredentialEngine | undefined, + private readonly nullRowHolderOf: ConnectorNullRowHolder = () => undefined, + ) {} + + /** + * [ADR-0150 D4, #31699] The rows of one organization's connections of + * `connectorName` that answer the instance of `packageId`, by one rule: + * + * - while the name has one holder (its durable resolution, disabled + * packages included, answers one), or no registry can judge it: every + * row of the name, whatever package it names, as the read by name + * answered before the key carried a package. A connection follows its + * name across a move of the declaration (another package, the + * environment), and a connect adopts the row and stamps it with the + * instance's package in place ({@link connect}), so a one-holder + * answer never moves (ADR-0150 red line 3, epic ruling R2-C); + * - while two packages hold the name: the rows naming that package + * (`null`: the rows naming none). A row naming no package, or a package + * that is not one of the holders, is no package's: when it is all a + * package has, the read is refused, naming the bind that settles it, + * never handed to one of them (ADR-0150 red line 2). It is not the R9 + * rule (#31696), where such a row beside the package's own row wins and + * is refused: here the package's own row is its connection, and the + * backfill reports the stray row; + * - for a caller that knows only the name, every row. + */ + private answering( + rows: readonly Record[], + connectorName: string, + packageId: ConnectorInstancePackage, + ): Record[] { + if (packageId === undefined) return [...rows]; + const own = rows.filter((r) => rowPackage(r) === packageId); + if (own.length === rows.length) return own; + const holder = this.nullRowHolderOf(connectorName); + if (holder?.status !== 'refused') return [...rows]; + if (packageId === null || own.length > 0) return own; + const holders = new Set(holder.candidates.flatMap((c) => (c.kind === 'package' ? [c.packageId] : []))); + const unclaimed = rows.filter((r) => { + const named = rowPackage(r); + return named === null || !holders.has(named); + }); + if (unclaimed.length === 0) return own; + throw new ConnectorConnectionConflictError( + `The connection of connector instance '${connectorName}' in this organization names no package that holds ` + + `that name, and ${holder.candidates.length} packages hold it, so it is no one package's connection. Bind it to ` + + 'its package with `os migrate stored-references bind --table sys_connector_connection`, or uninstall one of ' + + 'the packages, then read it again.', + ); + } + + /** The one row answering the instance, refusing two (see {@link answering}). */ + private chosen( + rows: readonly Record[], + connectorName: string, + packageId: ConnectorInstancePackage, + ): Record | undefined { + const answering = this.answering(rows, connectorName, packageId); + if (answering.length > 1) throw twoConnections(connectorName, answering.length); + return answering[0]; + } + + private async rowsOfInstance( + engine: ConnectorCredentialEngine, + organizationId: string, + connectorName: string, + fields: readonly string[] = RECORD_FIELDS, + ): Promise[]> { + const found = await engine.find(CONNECTOR_CONNECTION_OBJECT, { + where: { organization_id: organizationId, connector_name: connectorName }, + fields: [...fields], + context: SYSTEM_CONTEXT, + }); + return rowsOf(found); + } private engineOrThrow(what: string): ConnectorCredentialEngine { const engine = this.resolveEngine(); @@ -157,30 +295,37 @@ export class ConnectorConnectionStore { * `ConnectorCredentialUnavailableError`, never "not connected". The * engine's own message is not carried (it may name the row it was handed). */ - async readOrRefuse(organizationId: string, connectorName: string): Promise { + async readOrRefuse( + organizationId: string, + connectorName: string, + packageId?: ConnectorInstancePackage, + ): Promise { const what = `The connection of connector instance '${connectorName}' cannot be read`; this.engineOrThrow(what); try { - return await this.read(organizationId, connectorName); - } catch { + return await this.read(organizationId, connectorName, packageId); + } catch (err) { + if (err instanceof ConnectorConnectionConflictError) throw err; throw new ConnectorCredentialUnavailableError(`${what}: the connection store did not answer the read.`); } } - /** The row for one instance in one organization, or `undefined` when it is not connected there. */ - async read(organizationId: string, connectorName: string): Promise { + /** + * The row for one instance in one organization, or `undefined` when it is + * not connected there. `packageId` names the instance (see + * {@link ConnectorInstancePackage}); two rows answering it are refused + * ({@link ConnectorConnectionConflictError}). + */ + async read( + organizationId: string, + connectorName: string, + packageId?: ConnectorInstancePackage, + ): Promise { const engine = this.resolveEngine(); if (!engine) return undefined; - const found = await engine.find(CONNECTOR_CONNECTION_OBJECT, { - where: { organization_id: organizationId, connector_name: connectorName }, - fields: RECORD_FIELDS, - context: SYSTEM_CONTEXT, - }); - for (const row of rowsOf(found)) { - const record = toRecord(row); - if (record) return record; - } - return undefined; + const rows = (await this.rowsOfInstance(engine, organizationId, connectorName)).filter((r) => toRecord(r) !== undefined); + const row = this.chosen(rows, connectorName, packageId); + return row ? toRecord(row) : undefined; } /** @@ -205,18 +350,35 @@ export class ConnectorConnectionStore { return affectedRows(result) > 0; } - /** How many rows one instance has in one organization: one at most, but for a connect that raced the backfill. */ - private async rowCount(engine: ConnectorCredentialEngine, organizationId: string, connectorName: string): Promise { - const found = await engine.find(CONNECTOR_CONNECTION_OBJECT, { - where: { organization_id: organizationId, connector_name: connectorName }, - fields: ['id'], - context: SYSTEM_CONTEXT, - }); - return rowsOf(found).length; + /** + * How many rows answer one instance in one organization: one at most, but + * for a connect that raced the backfill. A row of a name two packages + * hold that names none of them counts as none. + */ + private async rowCount( + engine: ConnectorCredentialEngine, + organizationId: string, + connectorName: string, + packageId: ConnectorInstancePackage, + ): Promise { + const rows = await this.rowsOfInstance(engine, organizationId, connectorName, ['id', CONNECTOR_CONNECTION_PACKAGE_FIELD]); + try { + return this.answering(rows, connectorName, packageId).length; + } catch (err) { + if (err instanceof ConnectorConnectionConflictError) return 0; + throw err; + } } - /** Every organization's row for one instance. */ - async listFor(connectorName: string): Promise { + /** + * Every organization's connection of one instance, one per organization + * (`packageId` names the instance, as {@link read}). An organization whose + * read is refused (two rows answering, or a row of a name two packages + * hold that names none of them) is still listed, once, carrying that refusal in + * `conflict`: the list counts organizations as the read would, and a + * caller never takes such an entry for the organization's connection. + */ + async listFor(connectorName: string, packageId: ConnectorInstancePackage): Promise { const engine = this.resolveEngine(); if (!engine) return []; const found = await engine.find(CONNECTOR_CONNECTION_OBJECT, { @@ -224,7 +386,26 @@ export class ConnectorConnectionStore { fields: RECORD_FIELDS, context: SYSTEM_CONTEXT, }); - return rowsOf(found).map(toRecord).filter((r): r is ConnectorConnectionRecord => r !== undefined); + const byOrganization = new Map[]>(); + for (const row of rowsOf(found)) { + if (toRecord(row) === undefined) continue; + const organizationId = String(row.organization_id); + byOrganization.set(organizationId, [...(byOrganization.get(organizationId) ?? []), row]); + } + const out: ConnectorConnectionRecord[] = []; + for (const rows of byOrganization.values()) { + let answering: Record[]; + try { + answering = this.answering(rows, connectorName, packageId); + if (answering.length > 1) throw twoConnections(connectorName, answering.length); + } catch (err) { + if (!(err instanceof ConnectorConnectionConflictError)) throw err; + out.push({ ...toRecord(rows[0])!, conflict: err.message }); + continue; + } + if (answering.length > 0) out.push(toRecord(answering[0])!); + } + return out; } /** @@ -283,14 +464,28 @@ export class ConnectorConnectionStore { args: { organizationId: string; connectorName: string; + /** + * [#31699] The instance's package (`null`: the environment's or + * the platform's instance; absent: a caller that knows only the + * name, whose row names no package, as before). + */ + packageId?: ConnectorInstancePackage; userId?: string; registeredClient?: string; installerClient?: { clientId: string; hasSecret: boolean }; } & ConnectorGrantWrite, ): Promise { const engine = this.engineOrThrow(`Connector instance '${args.connectorName}' was not connected`); - const existing = await this.readOrRefuse(args.organizationId, args.connectorName); + const existing = await this.readOrRefuse(args.organizationId, args.connectorName, args.packageId); const context = { ...SYSTEM_CONTEXT, ...(args.userId ? { userId: args.userId } : {}) }; + // [#31699] The row names the instance's package. A row the instance + // adopts (`answering`: one naming no package, or another package, while + // the name has one holder) is stamped by this same write, so the + // instance's connection is one row (design review M2). `null` (the + // environment's or the platform's instance) clears another package's + // stamp; an absent package (a caller that knows only the name) leaves + // the row as it is. + const stamp = args.packageId === undefined ? {} : { [CONNECTOR_CONNECTION_PACKAGE_FIELD]: args.packageId }; const row = { grant: 'authorization_code', [CONNECTOR_CONNECTION_REFRESH_TOKEN_FIELD]: args.refreshToken ?? null, @@ -309,11 +504,11 @@ export class ConnectorConnectionStore { let insertedId: string | undefined; try { if (existing) { - moved = !(await this.updateAtRevision(engine, existing.id, existing.revision, row, context)); + moved = !(await this.updateAtRevision(engine, existing.id, existing.revision, { ...row, ...stamp }, context)); } else { const created = await engine.insert( CONNECTOR_CONNECTION_OBJECT, - { organization_id: args.organizationId, connector_name: args.connectorName, ...row }, + { organization_id: args.organizationId, connector_name: args.connectorName, ...stamp, ...row }, { context }, ); const id = (created as { id?: unknown } | null | undefined)?.id; @@ -338,8 +533,8 @@ export class ConnectorConnectionStore { // rows of one instance in one organization would leave `read` answering // either and `revoke` deleting one. So the insert that made the second // row takes itself back and is refused, as the old key refused it. - // (3a-ii counts by package once the store carries it.) A foreign - // message is never quoted, as above. + // Counted for this instance (`answering`). A foreign message is never + // quoted, as above. if (!existing && !moved) { const twice = new ConnectorCredentialUnavailableError( `Connector instance '${args.connectorName}' was connected twice in this organization: another connect ` @@ -347,7 +542,7 @@ export class ConnectorConnectionStore { ); let rows: number; try { - rows = await this.rowCount(engine, args.organizationId, args.connectorName); + rows = await this.rowCount(engine, args.organizationId, args.connectorName, args.packageId); } catch { throw new ConnectorCredentialUnavailableError( `Connector instance '${args.connectorName}' was connected, but the connection store did not answer the ` @@ -371,7 +566,7 @@ export class ConnectorConnectionStore { + 'completing (another connect, a refresh or a revoke landed first). Nothing was kept; begin the connect again.', ); } - const stored = await this.readOrRefuse(args.organizationId, args.connectorName); + const stored = await this.readOrRefuse(args.organizationId, args.connectorName, args.packageId); if (!stored) { throw new ConnectorCredentialUnavailableError( `Connector instance '${args.connectorName}' was not connected: the connection did not read back after its write.`, @@ -428,13 +623,35 @@ export class ConnectorConnectionStore { ); } - /** Remove the connection of one instance in one organization. `false` when it was not connected there. */ - async revoke(organizationId: string, connectorName: string, userId?: string): Promise { - const engine = this.engineOrThrow(`The connection of connector instance '${connectorName}' was not revoked`); - const existing = await this.readOrRefuse(organizationId, connectorName); - if (!existing) return false; + /** + * Remove the connection of one instance in one organization: every row + * answering it ({@link answering}), so a revoke also clears the second row + * a read refuses, and, while the name has one holder, a row its moved + * declaration left under another package. Under two holders a row that + * names none of them is no package's, so a package's revoke leaves it (the + * bind settles it), and where it is all that package has, the revoke is + * refused as the read is ({@link ConnectorConnectionConflictError}), never + * answered "not connected". `false` when it was not connected there. + */ + async revoke( + organizationId: string, + connectorName: string, + userId: string | undefined, + packageId: string | null, + ): Promise { + const what = `The connection of connector instance '${connectorName}' was not revoked`; + const engine = this.engineOrThrow(what); + let rows: Record[]; + try { + rows = await this.rowsOfInstance(engine, organizationId, connectorName, ['id', CONNECTOR_CONNECTION_PACKAGE_FIELD]); + } catch { + throw new ConnectorCredentialUnavailableError(`${what}: the connection store did not answer the read.`); + } + const answering = this.answering(rows, connectorName, packageId); + const ids = answering.flatMap((r) => (typeof r.id === 'string' || typeof r.id === 'number' ? [String(r.id)] : [])); + if (ids.length === 0) return false; const context = { ...SYSTEM_CONTEXT, ...(userId ? { userId } : {}) }; - await engine.delete(CONNECTOR_CONNECTION_OBJECT, { where: { id: existing.id }, context }); + for (const id of ids) await engine.delete(CONNECTOR_CONNECTION_OBJECT, { where: { id }, context }); return true; } } diff --git a/packages/services/service-automation/src/oauth2-grant/authorization.ts b/packages/services/service-automation/src/oauth2-grant/authorization.ts index 75c236c59f8..45888383925 100644 --- a/packages/services/service-automation/src/oauth2-grant/authorization.ts +++ b/packages/services/service-automation/src/oauth2-grant/authorization.ts @@ -65,6 +65,15 @@ export const PENDING_AUTHORIZATION_TTL_SECONDS = 600; /** What a begun connect remembers until its callback. ⛔ Never leaves the server. */ export interface PendingAuthorization { readonly connector: string; + /** + * [ADR-0150 D4, #31699] The package of the instance the connect was begun + * for: a package id, or `null` for an instance the environment authored or + * a plugin registers (never omitted for those, so "no package" is told + * apart from "not recorded"). The callback completes exactly that + * instance. Absent only on a record written before the package was + * recorded; such a record resolves the name, for the TTL it has left. + */ + readonly packageId?: string | null; readonly organizationId: string; readonly userId: string; /** The PKCE verifier (RFC 7636 §4.1) — sent only to the token endpoint, with the code. */ diff --git a/packages/services/service-automation/src/oauth2-grant/grant-handle.test.ts b/packages/services/service-automation/src/oauth2-grant/grant-handle.test.ts index 6ecdf450f7d..42a065c20a5 100644 --- a/packages/services/service-automation/src/oauth2-grant/grant-handle.test.ts +++ b/packages/services/service-automation/src/oauth2-grant/grant-handle.test.ts @@ -48,6 +48,7 @@ function fakeConnections(rows: Array<{ org: string; refreshToken?: string; statu id: `row_${r.org}`, organizationId: r.org, connectorName: 'crm', + packageId: null, status: r.status ?? 'connected', revision: 1, hasRefreshToken: r.refreshToken !== undefined, diff --git a/packages/services/service-automation/src/oauth2-grant/grant-handle.ts b/packages/services/service-automation/src/oauth2-grant/grant-handle.ts index e2465a2dbe8..518fd0917c9 100644 --- a/packages/services/service-automation/src/oauth2-grant/grant-handle.ts +++ b/packages/services/service-automation/src/oauth2-grant/grant-handle.ts @@ -48,7 +48,7 @@ import { } from '@objectstack/types'; import { ConnectorUpstreamUnavailableError } from '@objectstack/spec/integration'; import type { ILock } from '@objectstack/spec/contracts'; -import type { ConnectorConnectionRecord, ConnectorConnectionStore } from '../connector-connections.js'; +import { ConnectorConnectionConflictError, type ConnectorConnectionRecord, type ConnectorConnectionStore } from '../connector-connections.js'; import { OAuth2GrantRefusedError, requestOAuth2Token, type OAuth2Client, type OAuth2TokenResponse } from './token-endpoint.js'; import { parseKeptConnectionClient } from './installer-client.js'; @@ -81,6 +81,12 @@ export interface OAuth2GrantConfig { export interface OAuth2GrantHandleDeps { /** The connector instance — named in every refusal. */ readonly connector: string; + /** + * [#31699] The instance's package (`null`: the environment's or the + * platform's instance): its connections are read by `(package, name)`. + * Absent, every connection of the name answers, as before. + */ + readonly packageId?: string | null; readonly config: OAuth2GrantConfig; /** The connection store (`authorization_code` only). */ readonly connections: ConnectorConnectionStore; @@ -235,9 +241,9 @@ export function createOAuth2GrantHandle(deps: OAuth2GrantHandleDeps): OAuth2Gran let record: ConnectorConnectionRecord | undefined; try { if (organizationId !== undefined) { - record = await deps.connections.read(organizationId, connector); + record = await deps.connections.read(organizationId, connector, deps.packageId); } else { - const all = await deps.connections.listFor(connector); + const all = await deps.connections.listFor(connector, deps.packageId); if (all.length > 1) { throw connectorCredentialRefusal( `connector instance '${connector}' is connected for ${all.length} organizations, and this dispatch carries ` @@ -248,9 +254,15 @@ export function createOAuth2GrantHandle(deps: OAuth2GrantHandleDeps): OAuth2Gran ); } record = all[0]; + // [#31699] The one organization's read is refused: said as the read + // says it, its row never taken for the connection. + if (record?.conflict !== undefined) throw new ConnectorConnectionConflictError(record.conflict); } } catch (err) { if ((err as { status?: unknown })?.status === 422) throw err; + // [#31699] Two connections answering the instance: said as the store + // says it (a retry does not settle it), never one of them used. + if (err instanceof ConnectorConnectionConflictError) throw unavailable(err.message.replace(/\.$/, '')); throw unavailable(`the connection of connector instance '${connector}' could not be read now; the next dispatch retries`); } if (!record) throw unavailable(notConnectedReason(connector, organizationId)); @@ -309,7 +321,14 @@ export function createOAuth2GrantHandle(deps: OAuth2GrantHandleDeps): OAuth2Gran /** One refresh of `organizationId`'s connection, read again under the lock. */ const refreshOnce = async (organizationId: string): Promise => { - const current = await deps.connections.read(organizationId, connector); + let current: ConnectorConnectionRecord | undefined; + try { + current = await deps.connections.read(organizationId, connector, deps.packageId); + } catch (err) { + // [#31699] As `select` says it: a conflict is no transient fault, never a 409 out of the dispatch. + if (err instanceof ConnectorConnectionConflictError) throw unavailable(err.message.replace(/\.$/, '')); + throw err; + } if (!current) throw unavailable(notConnectedReason(connector, organizationId)); if (current.status === 'reconnect_required') throw unavailable(markedReason(connector, current)); let refreshToken: string | undefined; diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 5fc3a001056..6c3f5eb545c 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/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 { effectiveTenancyPosture, isServiceNotRegisteredError, resolveLocalizationContext, resolveUserAuthzGrants } from '@objectstack/core'; +import { RUNTIME_COMPATIBILITY_PACKAGE_ID, effectiveTenancyPosture, isServiceNotRegisteredError, resolveLocalizationContext, resolveUserAuthzGrants } from '@objectstack/core'; import type { IClusterService, IJobService, IPubSub } from '@objectstack/spec/contracts'; import { installedManifestsOf, type InstalledPackageSource } from '@objectstack/metadata-core'; import type { @@ -1183,6 +1183,40 @@ function withFailureTextRewritten( * **instance** the automation service materializes at boot (ADR-0097); * its absence marks a catalog **descriptor** (#2612). */ +/** + * [#31699] The package a declared connector entry belongs to: its + * `_packageId`, or `null` for an entry no package ships (the environment's, + * a stored row's provenance sentinel, the compatibility API's default). + */ +function declaredEntryPackage(entry: unknown): string | null { + const stamp = (entry as { _packageId?: unknown } | null | undefined)?._packageId; + if (typeof stamp !== 'string' || stamp.length === 0) return null; + return stamp === 'sys_metadata' || stamp === RUNTIME_COMPATIBILITY_PACKAGE_ID ? null : stamp; +} + +/** + * [#31699] The package a declared connector instance's connections are read + * and written by. An entry stamped with a real package is that package's; the + * environment's stored entry (`sys_metadata`) is no package's. An entry with + * no stamp, or the compatibility API's default, is the name's durable holder's + * when that is a package: the package the boot backfill binds a package-less + * row of the name to, so a row the instance connected is still its row once + * bound. With no registry to ask, or no package holder, it is no package's. + */ +function connectorInstancePackage( + resolve: ReturnType, + entry: unknown, +): string | null { + const own = declaredEntryPackage(entry); + if (own !== null) return own; + const stamp = (entry as { _packageId?: unknown } | null | undefined)?._packageId; + if (stamp === 'sys_metadata') return null; + const name = (entry as { name?: unknown } | null | undefined)?.name; + if (typeof name !== 'string' || name.length === 0) return null; + const holder = resolve(name, null, { includeDisabledPackages: true }); + return holder?.status === 'resolved' && holder.holder.kind === 'package' ? holder.holder.packageId : null; +} + interface DeclaredConnectorItem { name?: string; label?: string; @@ -2036,7 +2070,14 @@ export class AutomationServicePlugin implements Plugin { this.connectorCredentialStore = new ConnectorCredentialStore(() => this.resolveDataEngine(ctx)); // ADR-0143 D3 / D5 — the connector connection store, and the door the // `automation` service's connection members answer through. - this.connectorConnectionStore = new ConnectorConnectionStore(() => this.resolveDataEngine(ctx)); + // [#31699] While the name's durable resolution (the question the boot + // backfill asks) answers one holder, every row of the name is the one + // instance's; under two holders each package's rows are its own. + const connectionNullRowHolder = connectorNameResolver(ctx); + this.connectorConnectionStore = new ConnectorConnectionStore( + () => this.resolveDataEngine(ctx), + (name) => connectionNullRowHolder(name, null, { includeDisabledPackages: true }), + ); this.engine.setConnectorConnectionDoor({ get: (request) => this.getConnectorConnection(ctx, request), begin: (request) => this.beginConnectorConnection(ctx, request), @@ -3360,7 +3401,9 @@ export class AutomationServicePlugin implements Plugin { if (auth?.type !== 'oauth2' || auth.grant !== 'authorization_code') continue; let state: ConnectionStateOfInstance; try { - const rows = await this.connectorConnectionStoreOrNone().listFor(name); + // [#31699] An organization whose read is refused has no connection to materialize with. + const rows = (await this.connectorConnectionStoreOrNone().listFor(name, connectorInstancePackage(connectorNameResolver(ctx), d.entry))) + .filter((r) => r.conflict === undefined); const reconnectRequired = rows.filter((r) => r.status === 'reconnect_required').map((r) => r.organizationId).sort(); const discovery = discoveryOrganizationOf(rows); const discoveryConnectedAt = rows.find((r) => r.organizationId === discovery)?.connectedAt; @@ -4128,6 +4171,7 @@ export class AutomationServicePlugin implements Plugin { // the client its administrator entered (`clientSource: 'installer'`). return createOAuth2GrantHandle({ connector: name, + packageId: connectorInstancePackage(connectorNameResolver(ctx), entry), config: { grant: auth.grant, ...(takesInstallerClient(auth) ? { clientSource: 'installer' as const } : {}), @@ -4186,7 +4230,7 @@ export class AutomationServicePlugin implements Plugin { let marked = false; try { const store = this.connectorConnectionStoreOrNone(); - const record = await store.read(connection.organizationId, name); + const record = await store.read(connection.organizationId, name, connectorInstancePackage(connectorNameResolver(ctx), info.entry)); if (record && record.status === 'connected' && record.connectedAt === connection.connectedAt) { await store.markReconnectRequired(record, reason); marked = true; @@ -4332,7 +4376,7 @@ export class AutomationServicePlugin implements Plugin { const serverUrl = mcpDiscoveryServerUrl(entry, auth); if (serverUrl === undefined) return undefined; const store = this.connectorConnectionStoreOrNone(); - const existing = installerClient ? undefined : await store.readOrRefuse(organizationId, name); + const existing = installerClient ? undefined : await store.readOrRefuse(organizationId, name, connectorInstancePackage(connectorNameResolver(ctx), entry)); if (existing?.hasRegisteredClient) { let kept: McpAuthorizationClient | undefined; try { @@ -4383,9 +4427,17 @@ export class AutomationServicePlugin implements Plugin { private async connectionDoorSubject( ctx: PluginContext, request: ConnectorConnectionRequest | undefined, + /** + * [#31699, M7] The instance's package as the pending authorization + * recorded it: a package id, `null` for the environment's or the + * platform's instance. Absent, the door resolves the name. + */ + recordedPackage?: string | null, ): Promise<{ name: string; entry: DeclaredConnectorItem; + /** [#31699] The instance's package (`null`: the environment's or the platform's instance). */ + packageId: string | null; auth: Extract; organizationId: string; userId?: string; @@ -4395,7 +4447,7 @@ export class AutomationServicePlugin implements Plugin { throw credentialDoorRefusal('A connector instance name is required.', 'VALIDATION_ERROR', 400); } const declared = await this.readDeclaredConnectorItems(ctx, { post: true }); - const entry = (declared ?? []).find((raw) => (raw as DeclaredConnectorItem | null)?.name === name) as DeclaredConnectorItem | undefined; + const { entry, packageId } = this.connectionDoorInstance(ctx, name, declared ?? [], recordedPackage); if (!entry || typeof entry.provider !== 'string' || entry.provider.length === 0) { throw credentialDoorRefusal( `No installed package declares a provider-bound connector instance '${name}'.`, @@ -4426,7 +4478,61 @@ export class AutomationServicePlugin implements Plugin { ); } const userId = typeof request?.context?.userId === 'string' && request.context.userId.length > 0 ? request.context.userId : undefined; - return { name, entry, auth, organizationId, userId }; + return { name, entry, packageId, auth, organizationId, userId }; + } + + /** + * [ADR-0150 D3/D4, #31699; design review M6] Which declared instance the + * connection door's name means, and its package. The resolver decides + * identity; the entry always comes from the declared list, matched on name + * and package: + * + * - a package the pending authorization recorded (`recordedPackage`) is + * read exactly, never re-resolved: an entry of that package, else none; + * - `refused` (two packages hold the name) answers `409` naming them; + * - `resolved` takes the entry whose instance package + * ({@link connectorInstancePackage}) is the resolved one (`null`: the + * environment's or the platform's); when no declared entry is, the rule + * below; + * - `not-found`, or no registry to ask (a code-registered instance, one only + * a dev reload declares, a composition with no ObjectQL), serves the one + * declared entry of the name as before, with the package that entry + * carries; two declared entries are refused `409`, never picked. + */ + private connectionDoorInstance( + ctx: PluginContext, + name: string, + declared: readonly unknown[], + recordedPackage: string | null | undefined, + ): { entry: DeclaredConnectorItem | undefined; packageId: string | null } { + const ofName = declared.filter((raw) => (raw as DeclaredConnectorItem | null)?.name === name) as DeclaredConnectorItem[]; + const resolve = connectorNameResolver(ctx); + const exactly = (packageId: string | null) => ({ + entry: ofName.find((entry) => connectorInstancePackage(resolve, entry) === packageId), + packageId, + }); + if (recordedPackage !== undefined) return exactly(recordedPackage); + const resolution = resolve(name, null); + if (resolution?.status === 'refused') { + throw credentialDoorRefusal(resolution.message, 'RESOURCE_CONFLICT', 409); + } + if (resolution?.status === 'resolved') { + const held = exactly(resolution.holder.kind === 'package' ? resolution.holder.packageId : null); + // A holder no declared entry is the instance of (an entry stamped + // with another package than the one the name resolves to) falls to + // the one declared entry below, with that entry's own package: the + // package the dispatch reads the same instance's connection by. + if (held.entry !== undefined) return held; + } + if (ofName.length > 1) { + throw credentialDoorRefusal( + `${ofName.length} declared connector instances are named '${name}', and the connection door connects one: ` + + 'address the instance by its package.', + 'RESOURCE_CONFLICT', + 409, + ); + } + return { entry: ofName[0], packageId: ofName[0] ? connectorInstancePackage(resolve, ofName[0]) : null }; } /** ADR-0143 D3 — a connection row (or its absence) as the door answers it. Never a token. */ @@ -4480,6 +4586,7 @@ export class AutomationServicePlugin implements Plugin { */ private async installerClientOfBegin( name: string, + packageId: string | null, auth: Extract, request: ConnectorConnectionRequest, organizationId: string, @@ -4496,7 +4603,7 @@ export class AutomationServicePlugin implements Plugin { ); } if (offered === undefined) { - const kept = await this.keptInstallerClient(name, organizationId); + const kept = await this.keptInstallerClient(name, packageId, organizationId); if (kept) return kept; throw refuse( `Connector instance '${name}' takes its OAuth client from the installer (\`clientSource: 'installer'\`), and this ` @@ -4538,9 +4645,9 @@ export class AutomationServicePlugin implements Plugin { * encrypted client column, or `undefined` when it keeps none. A store * that cannot read or decrypt it refuses (`503`), never "keeps none". */ - private async keptInstallerClient(name: string, organizationId: string): Promise { + private async keptInstallerClient(name: string, packageId: string | null, organizationId: string): Promise { const store = this.connectorConnectionStoreOrNone(); - const record = await store.readOrRefuse(organizationId, name); + const record = await store.readOrRefuse(organizationId, name, packageId); if (record?.installerClientId === undefined) return undefined; const kept = parseKeptConnectionClient(await store.resolveRegisteredClient(record)); if (!kept?.installer) return undefined; @@ -4555,9 +4662,13 @@ export class AutomationServicePlugin implements Plugin { * is absent, never a refusal: the read still answers the status. */ private async getConnectorConnection(ctx: PluginContext, request: ConnectorConnectionRequest): Promise { - const { name, organizationId } = await this.connectionDoorSubject(ctx, request); + const { name, packageId, organizationId } = await this.connectionDoorSubject(ctx, request); this.refuseClientOffLeg(name, request, 'read'); - const state = this.describeConnection(name, organizationId, await this.connectorConnectionStoreOrNone().readOrRefuse(organizationId, name)); + const state = this.describeConnection( + name, + organizationId, + await this.connectorConnectionStoreOrNone().readOrRefuse(organizationId, name, packageId), + ); const redirectUri = this.derivedConnectorOAuthRedirectUri(); return redirectUri === undefined ? state : { ...state, redirectUri }; } @@ -4568,7 +4679,7 @@ export class AutomationServicePlugin implements Plugin { * the authorization URL. Nothing is written to the connection record. */ private async beginConnectorConnection(ctx: PluginContext, request: ConnectorConnectionRequest): Promise { - const { name, entry, auth, organizationId, userId } = await this.connectionDoorSubject(ctx, request); + const { name, entry, packageId, auth, organizationId, userId } = await this.connectionDoorSubject(ctx, request); if (userId === undefined) { throw credentialDoorRefusal( `Connecting connector instance '${name}' needs a signed-in user: the callback is accepted only from the user ` @@ -4578,13 +4689,13 @@ export class AutomationServicePlugin implements Plugin { ); } const redirectUri = this.connectorOAuthRedirectUri(); - const installerClient = await this.installerClientOfBegin(name, auth, request, organizationId, redirectUri); + const installerClient = await this.installerClientOfBegin(name, packageId, auth, request, organizationId, redirectUri); const client = await this.mcpAuthorizationClient(ctx, name, entry, auth, organizationId, redirectUri, installerClient); const state = createAuthorizationState(); const { verifier, challenge } = createPkcePair(); const expiresAt = Date.now() + PENDING_AUTHORIZATION_TTL_SECONDS * 1000; await this.pendingAuthorizations(ctx).put(state, { - connector: name, organizationId, userId, verifier, redirectUri, expiresAt, + connector: name, packageId, organizationId, userId, verifier, redirectUri, expiresAt, ...(client ? { client } : {}), ...(installerClient ? { installerClient } : {}), }); @@ -4659,10 +4770,14 @@ export class AutomationServicePlugin implements Plugin { } // The declaration is read again: the instance may have changed while // the browser was away. - const { name, auth, organizationId } = await this.connectionDoorSubject(ctx, { + // [#31699, M7] Exactly the instance the connect was begun for: the + // package it recorded (`null`: the environment's or the platform's + // instance), never the bare name resolved again. A record from before + // the package was recorded (no key, within its TTL) resolves the name. + const { name, packageId, auth, organizationId } = await this.connectionDoorSubject(ctx, { connector: pending.connector, context: request.context, - }); + }, pending.packageId); const client = pending.client; // ADR-0143 D2.1 (2026-11-02 amendment): an instance that takes the // installer's client exchanges as the client its connect was begun @@ -4723,6 +4838,7 @@ export class AutomationServicePlugin implements Plugin { const stored = await this.connectorConnectionStoreOrNone().connect({ organizationId, connectorName: name, + packageId, ...(userId ? { userId } : {}), ...(token.refreshToken === undefined ? {} : { refreshToken: token.refreshToken }), ...(token.scope === undefined ? {} : { scopes: token.scope }), @@ -4758,10 +4874,10 @@ export class AutomationServicePlugin implements Plugin { /** ADR-0143 D5 — `IAutomationService.revokeConnectorConnection`. */ private async revokeConnectorConnection(ctx: PluginContext, request: ConnectorConnectionRequest): Promise { - const { name, organizationId, userId } = await this.connectionDoorSubject(ctx, request); + const { name, packageId, organizationId, userId } = await this.connectionDoorSubject(ctx, request); this.refuseClientOffLeg(name, request, 'revoke'); const removed = await this.onReconcileQueue(async () => { - const gone = await this.connectorConnectionStoreOrNone().revoke(organizationId, name, userId); + const gone = await this.connectorConnectionStoreOrNone().revoke(organizationId, name, userId, packageId); if (!gone) return false; this.grantHandles.get(name)?.forget(organizationId); ctx.logger.info( diff --git a/packages/services/service-automation/src/stored-reference-package-backfill.ts b/packages/services/service-automation/src/stored-reference-package-backfill.ts index 8ef3db5ea84..42d20a0de69 100644 --- a/packages/services/service-automation/src/stored-reference-package-backfill.ts +++ b/packages/services/service-automation/src/stored-reference-package-backfill.ts @@ -45,8 +45,9 @@ * with its flow's one holder; and a resume or a credential read of a name two * packages hold reads the row's package (a row with none answers only while * one package holds the name). A null left by this backfill still reads by - * name. The connection store (R11) still reads by name, until the connector - * child moves it. S4's upgrade report reads the columns too. R11's column is a + * name. The connection store (R11) reads by package and name (#31699): a row + * this backfill leaves null answers a package's instance only where the name's + * durable resolution binds it to that package. S4's upgrade report reads the columns too. R11's column is a * part of its table's unique key (#31699), so a bind there can meet a unique * violation (below); no other reference's key carries its column. *