Skip to content

Commit 1bcba1e

Browse files
committed
fix(service-automation): a borrowed token refused at mcp tool discovery marks its connection, not the client secret
An mcp instance with an authorization_code grant lists its tools with the token of its discovery organization's connection (ruled B). When the server refused that token, the refusal took the static-credential path: the client secret row was marked rejected and the instance held on a key a reconnect does not move. The refusal is now recorded on that connection (reconnect_required, the platform's sentence), the client secret is left alone, and the instance lists as the next connected organization or holds until a reconnect, which lists again. Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 310cb96 commit 1bcba1e

2 files changed

Lines changed: 225 additions & 12 deletions

File tree

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

Lines changed: 87 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,12 @@ import { SqlDriver } from '@objectstack/driver-sql';
2323
import { SysSecret } from '@objectstack/platform-objects';
2424
import { callWithBorrowedCredential } from '@objectstack/types';
2525
import type { CryptoContext, CryptoHandle, ICryptoProvider } from '@objectstack/spec/contracts';
26-
import type { Connector, ConnectorProviderContext, ConnectorProviderFactory } from '@objectstack/spec/integration';
26+
import {
27+
ConnectorCredentialRejectedError,
28+
type Connector,
29+
type ConnectorProviderContext,
30+
type ConnectorProviderFactory,
31+
} from '@objectstack/spec/integration';
2732

2833
import { AutomationServicePlugin } from './plugin.js';
2934
import type { AutomationEngine } from './engine.js';
@@ -149,14 +154,25 @@ function notion(auth: Record<string, unknown> = {}, transportUrl?: string) {
149154
* the real provider's `tools/list` does: an ask that names no organization.
150155
*/
151156
function mcpStandIn(lists = false) {
152-
const state = { materialized: [] as ConnectorProviderContext[], sent: [] as string[], listedWith: [] as string[], refuse: new Set<string>() };
157+
const state = {
158+
materialized: [] as ConnectorProviderContext[],
159+
sent: [] as string[],
160+
listedWith: [] as string[],
161+
refuse: new Set<string>(),
162+
/** What the next listings answer, in order (then `200`): a `403` is thrown as the real provider throws it. */
163+
listingAnswers: [] as number[],
164+
};
153165
const factory: ConnectorProviderFactory = async (ctx) => {
154166
state.materialized.push(ctx);
155167
if (lists) {
156-
await callWithBorrowedCredential(ctx.credentialHandle!, async (auth) => {
157-
state.listedWith.push(auth.type === 'bearer' ? auth.token : '');
158-
return { status: 200 };
168+
const listed = await callWithBorrowedCredential(ctx.credentialHandle!, async (auth) => {
169+
const token = auth.type === 'bearer' ? auth.token : '';
170+
state.listedWith.push(token);
171+
return { status: state.listingAnswers.shift() ?? 200 };
159172
}, {});
173+
if (listed.status === 403) {
174+
throw new ConnectorCredentialRejectedError(`connector-mcp provider: connector '${ctx.name}' was refused by its MCP server (HTTP 403)`, 403);
175+
}
160176
}
161177
return {
162178
def: {
@@ -385,6 +401,72 @@ describe('ADR-0143 D4, ruled B — the connection an mcp instance lists its tool
385401
});
386402
});
387403

404+
describe('ADR-0143 D4 — a borrowed token refused at tool discovery is its connection\'s, not the client secret\'s', () => {
405+
const SECRET_REF = 'NOTION_CLIENT_SECRET';
406+
const STORED_SECRET = 'dummy-stored-secret-26702';
407+
const OPERATOR = { userId: 'usr_admin' } as never;
408+
const secretRow = async (engine: AutomationEngine) =>
409+
(await engine.listConnectorCredentialRefs()).find((r) => r.ref === SECRET_REF);
410+
const connectionOf = (engine: AutomationEngine, as: { userId: string; tenantId: string }) =>
411+
engine.getConnectorConnection({ connector: 'notion', context: as as never });
412+
413+
it('the discovery organization\'s connection needs reconnecting; a reconnect there lists again', async () => {
414+
const { engine, provider, connect, call } = await boot([notion()], { lists: true });
415+
provider.state.listingAnswers.push(403);
416+
await (await connect()).done();
417+
expect(provider.state.listedWith).toHaveLength(1);
418+
419+
// The connection whose token was refused is the one marked, with the platform's sentence.
420+
await vi.waitFor(async () => expect(await connectionOf(engine, ADMIN_A)).toMatchObject({
421+
status: 'reconnect_required',
422+
statusReason: expect.stringContaining('refused the token of this connection while it listed its tools (HTTP 403)'),
423+
}));
424+
await vi.waitFor(() => expect(engine.getConnectorDegradedReason('notion')).toContain("needs to be reconnected for organization 'org_a'"));
425+
expect(engine.getConnectorDegradedReason('notion')).toContain('while it listed its tools (HTTP 403)');
426+
await expect(call()).rejects.toMatchObject({ status: 503 });
427+
428+
// A reconnect by the same organization re-attempts discovery, and the instance serves.
429+
await (await connect()).done();
430+
await vi.waitFor(() => expect(engine.getConnectorDegradedReason('notion')).toBeUndefined());
431+
expect(provider.state.listedWith).toHaveLength(2);
432+
expect(await connectionOf(engine, ADMIN_A)).toMatchObject({ status: 'connected' });
433+
expect(await call()).toMatchObject({ status: 200 });
434+
});
435+
436+
it('the stored client secret stays `set`; the instance lists as the next organization, each dispatch keeps its own', async () => {
437+
const { engine, provider, connect } = await boot([notion({ clientId: 'notion-app', credentialRef: SECRET_REF })], { lists: true });
438+
await engine.setConnectorCredential({ ref: SECRET_REF, value: STORED_SECRET, context: OPERATOR });
439+
await (await connect(undefined, ADMIN_A)).done();
440+
await (await connect(undefined, ADMIN_B)).done();
441+
expect(provider.state.materialized).toHaveLength(1);
442+
443+
// The secret is set again: the instance materializes again, listing as org_a (the earliest), which is refused.
444+
provider.state.listingAnswers.push(403);
445+
await engine.setConnectorCredential({ ref: SECRET_REF, value: `${STORED_SECRET}-2`, context: OPERATOR });
446+
await vi.waitFor(() => expect(provider.state.materialized).toHaveLength(3));
447+
await vi.waitFor(() => expect(engine.getConnectorDegradedReason('notion')).toBeUndefined());
448+
449+
expect(await secretRow(engine)).toMatchObject({ status: 'set' });
450+
expect(await connectionOf(engine, ADMIN_A)).toMatchObject({ status: 'reconnect_required' });
451+
expect(await connectionOf(engine, ADMIN_B)).toMatchObject({ status: 'connected' });
452+
const dispatch = (tenantId: string) =>
453+
engine.resolveConnectorAction('notion', 'search')!({}, { automation: { tenantId } } as never);
454+
expect(await dispatch('org_b')).toMatchObject({ status: 200 });
455+
await expect(dispatch('org_a')).rejects.toMatchObject({ status: 503, message: expect.stringContaining("needs to be reconnected for organization 'org_a'") });
456+
});
457+
458+
it('CONTROL: a client_credentials token the instance mints itself keeps the client secret\'s attribution', async () => {
459+
const { engine, provider } = await boot([notion({
460+
grant: 'client_credentials', clientId: 'notion-app', tokenUrl: `${mcp.base}/auth/token`, credentialRef: SECRET_REF,
461+
})], { lists: true });
462+
provider.state.listingAnswers.push(403);
463+
await engine.setConnectorCredential({ ref: SECRET_REF, value: STORED_SECRET, context: OPERATOR });
464+
await vi.waitFor(() => expect(provider.state.listedWith).toHaveLength(1));
465+
await vi.waitFor(async () => expect(await secretRow(engine)).toMatchObject({ status: 'rejected' }));
466+
expect(engine.getConnectorDegradedReason('notion')).toContain('HTTP 403');
467+
});
468+
});
469+
388470
describe('ADR-0143 D2.1 — the pre-registered clientId form', () => {
389471
it('a declared clientId is used as is: no registration, the exchange authenticates with the declared secret', async () => {
390472
const { connect, ql } = await boot([notion({ clientId: 'hubspot-app', credentialRef: 'HUBSPOT_CLIENT_SECRET' })]);

‎packages/services/service-automation/src/plugin.ts‎

Lines changed: 138 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,10 @@ type ConnectionStateOfInstance =
550550
readonly reconnectRequired: readonly string[];
551551
/** The organization whose connection is the oldest standing one: see {@link discoveryOrganizationOf}. */
552552
readonly discovery?: string;
553+
/** When that connection was made: a refusal of its token marks it only while it is still that connect. */
554+
readonly discoveryConnectedAt?: string;
555+
/** The reason the first `reconnect_required` connection records, the platform's sentence. */
556+
readonly reconnectRequiredReason?: string;
553557
}
554558
| { readonly kind: 'unreadable' };
555559

@@ -576,6 +580,21 @@ function discoveryOrganizationOf(rows: readonly ConnectorConnectionRecord[]): st
576580
return pick?.organizationId;
577581
}
578582

583+
/**
584+
* ADR-0143 D4 — why the discovery organization's connection needs
585+
* reconnecting: the upstream refused the token borrowed from it while the
586+
* instance listed its tools (ruled B on #26702). The refusal is the
587+
* connection's grant, not the instance's client secret, so it is recorded on
588+
* the connection, and a reconnect there lists again. The platform's sentence,
589+
* never the upstream's text.
590+
*/
591+
function discoveryTokenRefusedReason(connector: string, organizationId: string, status: number): string {
592+
return `connector instance '${connector}' needs to be reconnected for organization '${organizationId}': its MCP server `
593+
+ `refused the token of this connection while it listed its tools (HTTP ${status}), so the grant does not reach what `
594+
+ 'the server serves. Reconnect required: an administrator connects it again, granting what the server asks for, and '
595+
+ 'the instance lists its tools with the new connection (ADR-0143 D4)';
596+
}
597+
579598
/**
580599
* The handle a provider is given while it materializes an instance whose
581600
* materialization asks name {@link discoveryOrganizationOf}: until `settle()`
@@ -2506,11 +2525,17 @@ export class AutomationServicePlugin implements Plugin {
25062525
let state: ConnectionStateOfInstance;
25072526
try {
25082527
const rows = await this.connectorConnectionStoreOrNone().listFor(name);
2528+
const reconnectRequired = rows.filter((r) => r.status === 'reconnect_required').map((r) => r.organizationId).sort();
2529+
const discovery = discoveryOrganizationOf(rows);
2530+
const discoveryConnectedAt = rows.find((r) => r.organizationId === discovery)?.connectedAt;
2531+
const reconnectRequiredReason = rows.find((r) => r.organizationId === reconnectRequired[0])?.statusReason;
25092532
state = {
25102533
kind: 'read',
25112534
connected: rows.filter((r) => r.status === 'connected').map((r) => r.organizationId).sort(),
2512-
reconnectRequired: rows.filter((r) => r.status === 'reconnect_required').map((r) => r.organizationId).sort(),
2513-
discovery: discoveryOrganizationOf(rows),
2535+
reconnectRequired,
2536+
...(discovery === undefined ? {} : { discovery }),
2537+
...(discoveryConnectedAt === undefined ? {} : { discoveryConnectedAt }),
2538+
...(reconnectRequiredReason === undefined ? {} : { reconnectRequiredReason }),
25142539
};
25152540
} catch (err) {
25162541
state = { kind: 'unreadable' };
@@ -2699,6 +2724,8 @@ export class AutomationServicePlugin implements Plugin {
26992724
// The handle the provider is given while it materializes an `mcp`
27002725
// `authorization_code` instance: see `askingDuringMaterializationAs`.
27012726
let materializingHandle: ReturnType<typeof askingDuringMaterializationAs> | undefined;
2727+
// Its connection, when the provider lists in its name: a refusal of that token is the connection's.
2728+
let discoveryConnection: { organizationId: string; connectedAt?: string } | undefined;
27022729
if (entry.auth?.type === 'signed') {
27032730
try {
27042731
requestSigner = createConnectorRequestSigner(name, entry.auth, {
@@ -2740,17 +2767,21 @@ export class AutomationServicePlugin implements Plugin {
27402767
signature,
27412768
existing,
27422769
reason: state && state.reconnectRequired.length > 0
2743-
? reconnectRequiredReason(name, state.reconnectRequired[0])
2770+
? state.reconnectRequiredReason ?? reconnectRequiredReason(name, state.reconnectRequired[0])
27442771
: notConnectedReason(name),
27452772
});
27462773
continue;
27472774
}
27482775
}
27492776
credentialHandle = this.createGrantHandle(ctx, name, entry, entry.auth, credential?.value);
2750-
const discovery = entry.auth.grant === 'authorization_code' && provider === 'mcp'
2751-
? (() => { const state = connectionStates.get(name); return state?.kind === 'read' ? state.discovery : undefined; })()
2752-
: undefined;
2753-
if (discovery !== undefined) materializingHandle = askingDuringMaterializationAs(credentialHandle, discovery);
2777+
const state = entry.auth.grant === 'authorization_code' && provider === 'mcp' ? connectionStates.get(name) : undefined;
2778+
if (state?.kind === 'read' && state.discovery !== undefined) {
2779+
materializingHandle = askingDuringMaterializationAs(credentialHandle, state.discovery);
2780+
discoveryConnection = {
2781+
organizationId: state.discovery,
2782+
...(state.discoveryConnectedAt === undefined ? {} : { connectedAt: state.discoveryConnectedAt }),
2783+
};
2784+
}
27542785
} else if (entry.auth?.type === 'app-credential') {
27552786
// ADR-0143 D2.2 — the vendor exchange the closed `vendor` names,
27562787
// run from the app secret its `credentialRef` resolved to; the
@@ -2839,6 +2870,24 @@ export class AutomationServicePlugin implements Plugin {
28392870
// echoes the credential back must not carry it into the husk's
28402871
// reason, a log record or the thrown boot error.
28412872
const thrown = withoutCredentialThrown(err, credentialForms(credential?.value, basicUsernameOf(entry.auth)));
2873+
// ADR-0143 D4 — the upstream refused the token borrowed from the
2874+
// discovery organization's connection while the instance listed
2875+
// its tools: that connection's grant, not the client secret the
2876+
// instance's `credentialRef` names, so the connection is marked
2877+
// and the secret left alone (#26702).
2878+
if (isConnectorCredentialRejected(thrown) && discoveryConnection !== undefined) {
2879+
await this.holdConnectorForRefusedConnection(engine, ctx, {
2880+
name,
2881+
entry,
2882+
provider,
2883+
signature,
2884+
hasLive: existing !== undefined,
2885+
connection: discoveryConnection,
2886+
status: typeof (thrown as { status?: unknown }).status === 'number' ? (thrown as { status: number }).status : 403,
2887+
cause: thrown,
2888+
});
2889+
continue;
2890+
}
28422891
// [#27237] The upstream refused the credential (ruling on
28432892
// #27237, comment 6470087293): degrade the instance and mark a
28442893
// stored credential `rejected` — never a failed boot, never a
@@ -3224,6 +3273,88 @@ export class AutomationServicePlugin implements Plugin {
32243273
});
32253274
}
32263275

3276+
/**
3277+
* ADR-0143 D4 — the upstream refused the token an `mcp` instance borrowed
3278+
* from its discovery organization's connection (ruled B on #26702) while
3279+
* it listed its tools. That organization's connection is marked
3280+
* `reconnect_required`, with the platform's sentence, and the client
3281+
* secret the instance's `credentialRef` names is left as it is: it is not
3282+
* what the upstream refused. The connection's change moves the
3283+
* instance's signature, so the reconcile queued here lists as the next
3284+
* connected organization, or holds the instance "reconnect required"
3285+
* until a reconnect, which lists again.
3286+
*
3287+
* The connection is marked only while it is still the connect whose token
3288+
* was sent (same `connected_at`); a reconnect that landed since keeps its
3289+
* fresh grant. When the connection could not be marked, the instance is
3290+
* degraded on the #3017 backoff instead, so the refusal is retried rather
3291+
* than held on a key that nothing moves. A live connector keeps serving,
3292+
* as on every failed re-materialization.
3293+
*/
3294+
private async holdConnectorForRefusedConnection(
3295+
engine: AutomationEngine,
3296+
ctx: PluginContext,
3297+
info: {
3298+
name: string;
3299+
entry: DeclaredConnectorItem;
3300+
provider: string;
3301+
signature: string;
3302+
hasLive: boolean;
3303+
connection: { organizationId: string; connectedAt?: string };
3304+
status: number;
3305+
cause: unknown;
3306+
},
3307+
): Promise<void> {
3308+
const { name, connection } = info;
3309+
const reason = discoveryTokenRefusedReason(name, connection.organizationId, info.status);
3310+
let marked = false;
3311+
try {
3312+
const store = this.connectorConnectionStoreOrNone();
3313+
const record = await store.read(connection.organizationId, name);
3314+
if (record && record.status === 'connected' && record.connectedAt === connection.connectedAt) {
3315+
await store.markReconnectRequired(record, reason);
3316+
marked = true;
3317+
}
3318+
} catch (err) {
3319+
ctx.logger.warn(
3320+
`[Automation] connector instance '${name}': the connection of organization '${connection.organizationId}' `
3321+
+ 'could not be marked to be reconnected; the instance retries.',
3322+
describeThrownForLog(err),
3323+
);
3324+
}
3325+
if (!marked) {
3326+
this.degradeConnectorInstance(engine, ctx, {
3327+
name,
3328+
entry: info.entry,
3329+
provider: info.provider,
3330+
signature: info.signature,
3331+
hasLive: info.hasLive,
3332+
reason: `connector instance '${name}': its MCP server refused the token of organization `
3333+
+ `'${connection.organizationId}' while it listed its tools (HTTP ${info.status}); it retries`,
3334+
cause: info.cause,
3335+
});
3336+
return;
3337+
}
3338+
this.degradedInstances.set(name, { attempts: 1, signature: info.signature, reason, held: true });
3339+
if (!info.hasLive) {
3340+
try {
3341+
engine.registerDegradedConnector(this.buildDegradedHuskDef(name, info.entry), reason, 'declarative', info.cause, { kind: 'connection' });
3342+
} catch (err) {
3343+
ctx.logger.warn(
3344+
`[Automation] could not register degraded husk for '${name}' — the instance stays absent from the `
3345+
+ 'connector registry until it is reconnected.',
3346+
describeThrownForLog(err),
3347+
);
3348+
}
3349+
}
3350+
ctx.logger.warn(
3351+
`[Automation] connector instance '${name}' (provider '${info.provider}'): its MCP server refused the token of `
3352+
+ `organization '${connection.organizationId}' while it listed its tools (HTTP ${info.status}); that connection `
3353+
+ 'needs to be reconnected (ADR-0143 D4).',
3354+
);
3355+
void this.materializeDeclaredConnectors(ctx, { fatal: false }).catch(() => { /* logged by the reconcile */ });
3356+
}
3357+
32273358
/**
32283359
* ADR-0143 D4 — hold an `authorization_code` instance with no working
32293360
* connection degraded: "not connected" (never authorized) or "reconnect

0 commit comments

Comments
 (0)