Skip to content

Commit 9ae5df9

Browse files
committed
test(service-automation): a marked connection answers its stored cause; the refusal log names it
Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 00d0668 commit 9ae5df9

2 files changed

Lines changed: 124 additions & 5 deletions

File tree

‎packages/services/service-automation/src/connector-connection-door.test.ts‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ const idp = {
6262
requests: [] as TokenRequest[],
6363
/** Answer to a refresh_token grant; default rotate. */
6464
refresh: 'rotate' as 'rotate' | 'invalid_grant' | 'down' | 'no_rotate',
65+
/** Whether the code exchange issues a refresh token; default yes. */
66+
exchangeIssuesRefreshToken: true,
6567
issued: 0,
6668
};
6769

@@ -86,7 +88,11 @@ beforeAll(async () => {
8688
if (form.grant_type === 'authorization_code') {
8789
if (form.code !== GOOD_CODE) return answer(400, { error: 'invalid_grant' });
8890
return answer(200, {
89-
access_token: `dummy-at-exchange-${n}`, token_type: 'Bearer', expires_in: 3600, refresh_token: `dummy-rt-${n}`, scope: 'crm.read',
91+
access_token: `dummy-at-exchange-${n}`,
92+
token_type: 'Bearer',
93+
expires_in: 3600,
94+
...(idp.exchangeIssuesRefreshToken ? { refresh_token: `dummy-rt-${n}` } : {}),
95+
scope: 'crm.read',
9096
});
9197
}
9298
if (form.grant_type === 'refresh_token') {
@@ -200,6 +206,7 @@ afterEach(async () => {
200206
}
201207
idp.requests.length = 0;
202208
idp.refresh = 'rotate';
209+
idp.exchangeIssuesRefreshToken = true;
203210
idp.issued = 0;
204211
vi.restoreAllMocks();
205212
});
@@ -490,6 +497,25 @@ describe('ADR-0143 D4 — dispatch with the connection', () => {
490497
expect((await rowsOf(ql))[0]).toMatchObject({ status: 'connected', revision: 2 });
491498
});
492499

500+
it('[#28963] a connection marked because no refresh token was issued: the log and the hold name that cause, not a refusal', async () => {
501+
const out = captureOutput();
502+
const { call, connect, provider, engine, ql } = await boot();
503+
idp.exchangeIssuesRefreshToken = false;
504+
await (await connect()).done();
505+
provider.state.accepted = new Set();
506+
const refused = await call('org_a').catch((e) => e);
507+
expect(refused).toMatchObject({ status: 503, message: expect.stringContaining('issued no refresh token') });
508+
const [row] = await rowsOf(ql);
509+
expect(row).toMatchObject({ status: 'reconnect_required', status_reason: refused.message });
510+
// The log line is the stored reason, whose cause is the one that happened.
511+
await vi.waitFor(() => expect(out.text()).toContain(`[Automation] ${refused.message}.`));
512+
expect(out.text()).not.toContain('refused the grant');
513+
// The instance is held with the cause the row stores.
514+
await vi.waitFor(() => expect(engine.getConnectorDegradedReason('crm')).toContain('issued no refresh token'));
515+
expect(engine.getConnectorDegradedReason('crm')).not.toContain('refused the grant');
516+
expect(idp.requests.filter((r) => r.form.grant_type === 'refresh_token')).toHaveLength(0);
517+
});
518+
493519
it("the run's organization selects the connection; a run with none is refused when several exist", async () => {
494520
const { call, connect, provider } = await boot();
495521
await (await connect(ADMIN_A)).done();
@@ -573,7 +599,9 @@ describe('ADR-0143 D3/D6 — what a grant leaves behind', () => {
573599
}
574600
// The logs did record the connect — the pin is not passing on silence.
575601
expect(out.text()).toContain("connector instance 'crm' connected for organization 'org_a' by user 'usr_admin'");
576-
expect(out.text()).toContain("refused the grant of organization 'org_a'");
602+
expect(out.text()).toContain(
603+
"connector instance 'crm' needs to be reconnected for organization 'org_a': its authorization server refused the grant",
604+
);
577605
});
578606

579607
it('⛔ writes only its own record — never sys_metadata, never a sign-in account (D6) — and reads no account either', async () => {

‎packages/services/service-automation/src/oauth2-grant/grant-handle.test.ts‎

Lines changed: 94 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { callWithBorrowedCredential, BORROWED_CREDENTIAL_SKEW_MS } from '@object
1111
import { ConnectorUpstreamUnavailableError } from '@objectstack/spec/integration';
1212
import type { ILock } from '@objectstack/spec/contracts';
1313
import type { ConnectorConnectionRecord, ConnectorConnectionStore, ConnectorGrantWrite } from '../connector-connections.js';
14-
import { createOAuth2GrantHandle, type OAuth2GrantConfig } from './grant-handle.js';
14+
import { createOAuth2GrantHandle, reconnectRequiredReason, type OAuth2GrantConfig } from './grant-handle.js';
1515

1616
const TOKEN_URL = 'https://idp.example.com/oauth/token';
1717

@@ -308,7 +308,7 @@ describe('ADR-0143 D4 — authorization_code: refresh', () => {
308308
expect(refused.message).not.toContain('dummy-rt-a');
309309
expect(calls.markReconnectRequired).toEqual(['org_a']);
310310
expect(held.get('org_a')).toMatchObject({ status: 'reconnect_required', refreshToken: undefined });
311-
expect(onGrantRefused).toHaveBeenCalledWith('org_a');
311+
expect(onGrantRefused).toHaveBeenCalledWith('org_a', refused.message);
312312
// The next dispatch reads the row: refused before any token request.
313313
await expect(handle.get({ organizationId: 'org_a' })).rejects.toMatchObject({ status: 503 });
314314
expect(idp.state.requests).toHaveLength(1);
@@ -410,7 +410,7 @@ describe('ADR-0143 D2.1 — an MCP instance whose connection keeps the client it
410410
await expect(handle.get({ organizationId: 'org_a' })).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
411411
expect(idp.seen).toHaveLength(0);
412412
expect(calls.markReconnectRequired).toEqual(['org_a']);
413-
expect(onGrantRefused).toHaveBeenCalledWith('org_a');
413+
expect(onGrantRefused).toHaveBeenCalledWith('org_a', expect.stringContaining('keeps no client to refresh with'));
414414
});
415415
});
416416

@@ -458,3 +458,94 @@ describe('[#28863] the stored reason of a connection marked reconnect required n
458458
expect(idp.state.requests).toHaveLength(1);
459459
});
460460
});
461+
462+
describe('[#28963] a connection already marked reconnect required answers the cause it stores, and the log names it', () => {
463+
const NO_REFRESH_TOKEN = 'issued no refresh token, so an access token the connection has to renew cannot be renewed';
464+
const NO_CLIENT = 'keeps no client to refresh with, so an access token it has to renew cannot be renewed';
465+
const REFUSED = 'its authorization server refused the grant (revoked, or expired with no usable refresh)';
466+
const refusalOf = (p: Promise<unknown>) => p.then(() => { throw new Error('the dispatch was not refused'); }, (e: Error & { status?: number; code?: string }) => e);
467+
468+
it('a row marked because no refresh token was issued answers that sentence on the first dispatch and on every later one', async () => {
469+
const idp = tokenEndpoint();
470+
const { store, held } = fakeConnections([{ org: 'org_a' }]);
471+
const handle = createOAuth2GrantHandle({ connector: 'crm', config: AUTH_CODE, connections: store, fetch: idp.fetch });
472+
const first = await refusalOf(handle.get({ organizationId: 'org_a' }));
473+
const stored = String(held.get('org_a')?.statusReason);
474+
expect(stored).toContain(NO_REFRESH_TOKEN);
475+
expect(first.message).toBe(stored);
476+
// Every later dispatch reads the marked row and answers what it stores, not the refusal sentence.
477+
for (const later of [
478+
() => handle.get({ organizationId: 'org_a' }),
479+
() => handle.get({ organizationId: 'org_a' }),
480+
() => handle.refresh({ organizationId: 'org_a' }),
481+
]) {
482+
const refused = await refusalOf(later());
483+
expect(refused).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' });
484+
expect(refused.message).toBe(stored);
485+
expect(refused.message).not.toMatch(/refused/);
486+
}
487+
// So does a handle that never saw the marking (another replica, a restart).
488+
const other = createOAuth2GrantHandle({ connector: 'crm', config: AUTH_CODE, connections: store, fetch: idp.fetch });
489+
expect((await refusalOf(other.get({ organizationId: 'org_a' }))).message).toBe(stored);
490+
expect(idp.state.requests).toHaveLength(0);
491+
});
492+
493+
it('a row another replica marked while this one waited for the lock answers the cause that replica stored', async () => {
494+
const idp = tokenEndpoint();
495+
const { store, held } = fakeConnections([{ org: 'org_a', refreshToken: 'dummy-rt-a' }]);
496+
const markedThere = reconnectRequiredReason('crm', 'org_a', 'no_client');
497+
const lock = {
498+
async withLock(_key: string, fn: () => Promise<unknown>) {
499+
Object.assign(held.get('org_a')!, { status: 'reconnect_required', statusReason: markedThere, refreshToken: undefined });
500+
return fn();
501+
},
502+
} as unknown as ILock;
503+
const handle = createOAuth2GrantHandle({ connector: 'crm', config: AUTH_CODE, connections: store, lock: () => lock, fetch: idp.fetch });
504+
const refused = await refusalOf(handle.get({ organizationId: 'org_a' }));
505+
expect(refused).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' });
506+
expect(refused.message).toBe(markedThere);
507+
expect(idp.state.requests).toHaveLength(0);
508+
});
509+
510+
it('a marked row that stores no cause still answers the refusal sentence, on both reads', async () => {
511+
const idp = tokenEndpoint();
512+
const { store, held } = fakeConnections([{ org: 'org_a', status: 'reconnect_required' }]);
513+
const handle = createOAuth2GrantHandle({ connector: 'crm', config: AUTH_CODE, connections: store, fetch: idp.fetch });
514+
const atSelect = await refusalOf(handle.get({ organizationId: 'org_a' }));
515+
expect(atSelect.message).toBe(reconnectRequiredReason('crm', 'org_a'));
516+
expect(atSelect.message).toContain(REFUSED);
517+
518+
held.get('org_a')!.status = 'connected';
519+
held.get('org_a')!.refreshToken = 'dummy-rt-a';
520+
const lock = {
521+
async withLock(_key: string, fn: () => Promise<unknown>) {
522+
held.get('org_a')!.status = 'reconnect_required';
523+
return fn();
524+
},
525+
} as unknown as ILock;
526+
const locked = createOAuth2GrantHandle({ connector: 'crm', config: AUTH_CODE, connections: store, lock: () => lock, fetch: idp.fetch });
527+
const underLock = await refusalOf(locked.get({ organizationId: 'org_a' }));
528+
expect(underLock.message).toBe(reconnectRequiredReason('crm', 'org_a'));
529+
expect(idp.state.requests).toHaveLength(0);
530+
});
531+
532+
it('the plugin is told the cause of each refresh path, in the words it stored', async () => {
533+
const cases = [
534+
{ cause: NO_REFRESH_TOKEN, config: AUTH_CODE, row: { org: 'org_a' }, answer: undefined },
535+
{ cause: NO_CLIENT, config: { grant: 'authorization_code' } as OAuth2GrantConfig, row: { org: 'org_a', refreshToken: 'dummy-rt-a' }, answer: undefined },
536+
{ cause: REFUSED, config: AUTH_CODE, row: { org: 'org_a', refreshToken: 'dummy-rt-a' }, answer: { status: 400, body: { error: 'invalid_grant' } } },
537+
];
538+
for (const { cause, config, row, answer } of cases) {
539+
const idp = tokenEndpoint();
540+
if (answer) idp.state.answer = () => answer;
541+
const { store, held } = fakeConnections([row]);
542+
const onGrantRefused = vi.fn();
543+
const handle = createOAuth2GrantHandle({ connector: 'crm', config, connections: store, fetch: idp.fetch, onGrantRefused });
544+
await refusalOf(handle.get({ organizationId: 'org_a' }));
545+
const stored = String(held.get('org_a')?.statusReason);
546+
expect(stored).toContain(cause);
547+
expect(onGrantRefused).toHaveBeenCalledTimes(1);
548+
expect(onGrantRefused).toHaveBeenCalledWith('org_a', stored);
549+
}
550+
});
551+
});

0 commit comments

Comments
 (0)