Skip to content

Commit 30dc658

Browse files
committed
fix(service-automation): refuse a non-https oauth2 endpoint off loopback, and answer an unreadable connection store 503
An `oauth2` instance whose `tokenUrl` or `authorizationUrl` is not https (plain http is accepted only to a loopback host) is held degraded at the reconcile and refused 400 at the connection door, naming the field and never the URL. The connection door's read now answers 503 when the deployment has no data engine or the store read fails, as the `getConnectorConnection` contract says, instead of "not connected". The connectors page also says a revoke does not yet revoke the refresh token at the vendor. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cxkPFWL5Ht4oxW9eG5
1 parent 23bbe3f commit 30dc658

8 files changed

Lines changed: 194 additions & 10 deletions

File tree

‎content/docs/automation/connectors.mdx‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -494,13 +494,18 @@ a rotating refresh token is never spent twice.
494494
instance's only connection, and is refused when there are several. When the
495495
vendor refuses the grant (`invalid_grant`), the connection is marked
496496
**reconnect required** and the instance degraded until an administrator
497-
connects it again.
497+
connects it again. A revoke deletes the stored connection only: the server
498+
does not yet revoke the refresh token at the vendor (RFC 7009), so it stays
499+
valid there until it expires or is revoked in the vendor's console.
498500

499501
What is not served yet is held **degraded** with a reason that names it, and
500502
never called without its credential: `app-credential` (its vendor exchanges
501503
are not run yet), an `oauth2` instance on a provider that does not yet ask the
502504
credential handle (the built-in `rest`, `openapi` and `mcp` providers do not
503-
yet), and an `mcp` instance that left its endpoints to discovery. A datasource
505+
yet), an `mcp` instance that left its endpoints to discovery, and an `oauth2`
506+
instance whose `tokenUrl` or `authorizationUrl` is not `https://` (plain
507+
`http://` is accepted only to a loopback host, so the client secret and the
508+
refresh token never cross a network in the clear). A datasource
504509
that borrows from a grant-bearing instance (`external.connector`) is refused
505510
with `422`. Until then, declare a static kind (`bearer`, `api-key` or `basic`)
506511
to dispatch now; don't emulate a grant by putting a short-lived access token

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

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ async function dataEngine(): Promise<ObjectQL> {
230230
return ql;
231231
}
232232

233-
async function boot(declared: unknown[] = [crm()], opts: { redirectUri?: string | null; cluster?: unknown } = {}) {
233+
async function boot(declared: unknown[] = [crm()], opts: { redirectUri?: string | null; cluster?: unknown; noData?: boolean } = {}) {
234234
const ql = await dataEngine();
235235
const provider = grantedProvider();
236236
const kernel = new LiteKernel({ logger: { level: 'debug', format: 'json' } } as never);
@@ -247,7 +247,7 @@ async function boot(declared: unknown[] = [crm()], opts: { redirectUri?: string
247247
dependencies: ['com.objectstack.service-automation'],
248248
async init(ctx: any) {
249249
ctx.registerService('objectql', { registry: { listItems: (t: string) => (t === 'connector' ? declared : []) } });
250-
ctx.registerService('data', ql);
250+
if (!opts.noData) ctx.registerService('data', ql);
251251
if (opts.cluster) ctx.registerService('cluster', opts.cluster);
252252
ctx.getService('automation').registerConnectorProvider('granted', provider.factory, { credentialHandle: true });
253253
},
@@ -382,6 +382,40 @@ describe('ADR-0143 D4/D5 — connect an instance nobody authorized yet', () => {
382382
.rejects.toMatchObject({ status: 400, message: expect.stringContaining('needs a signed-in user') });
383383
});
384384

385+
it('⛔ the door refuses an instance whose tokenUrl or authorizationUrl is not https off loopback, naming the field', async () => {
386+
const plain = crm({ name: 'plain', auth: { ...crm().auth, authorizationUrl: 'http://idp.example.com/authorize' } });
387+
const { engine } = await boot([crm(), plain]);
388+
for (const call of [
389+
() => engine.getConnectorConnection({ connector: 'plain', context: ADMIN_A as never }),
390+
() => engine.beginConnectorConnection({ connector: 'plain', context: ADMIN_A as never }),
391+
]) {
392+
const err = (await call().catch((e: Error) => e)) as Error & { status?: number };
393+
expect(err.status).toBe(400);
394+
expect(err.message).toContain('`authorizationUrl` not over https');
395+
expect(err.message).not.toContain('idp.example.com');
396+
}
397+
// The loopback token endpoint of `crm()` itself is accepted.
398+
await expect(engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never }))
399+
.resolves.toMatchObject({ status: 'not_connected' });
400+
});
401+
402+
it('⛔ a store this deployment cannot read is a 503 at the door, never "not connected"', async () => {
403+
const none = await boot([crm()], { noData: true });
404+
await expect(none.engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never }))
405+
.rejects.toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE', message: expect.stringContaining('no data engine') });
406+
407+
const { engine, ql } = await boot();
408+
const find = ql.find.bind(ql);
409+
vi.spyOn(ql, 'find').mockImplementation(async (object: string, ...rest: unknown[]) => {
410+
if (object === CONNECTOR_CONNECTION_OBJECT) throw new Error('dummy-store-down-26702');
411+
return (find as any)(object, ...rest);
412+
});
413+
const err = (await engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never }).catch((e: Error) => e)) as Error & { status?: number };
414+
expect(err.status).toBe(503);
415+
expect(err.message).toContain("connection of connector instance 'crm' cannot be read");
416+
expect(err.message).not.toContain('dummy-store-down-26702');
417+
});
418+
385419
it('the redirect URI is fixed per deployment: with none configured, begin is a 503 and is never taken from the request', async () => {
386420
const saved = { a: process.env.OS_AUTH_URL, b: process.env.OS_BASE_URL };
387421
delete process.env.OS_AUTH_URL;

‎packages/services/service-automation/src/connector-connections.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,22 @@ export class ConnectorConnectionStore {
107107
return engine;
108108
}
109109

110+
/**
111+
* As {@link read}, for the connection door: a store this deployment cannot
112+
* read — no data engine, or one whose read fails — is a 503
113+
* `ConnectorCredentialUnavailableError`, never "not connected". The
114+
* engine's own message is not carried (it may name the row it was handed).
115+
*/
116+
async readOrRefuse(organizationId: string, connectorName: string): Promise<ConnectorConnectionRecord | undefined> {
117+
const what = `The connection of connector instance '${connectorName}' cannot be read`;
118+
this.engineOrThrow(what);
119+
try {
120+
return await this.read(organizationId, connectorName);
121+
} catch {
122+
throw new ConnectorCredentialUnavailableError(`${what}: the connection store did not answer the read.`);
123+
}
124+
}
125+
110126
/** The row for one instance in one organization, or `undefined` when it is not connected there. */
111127
async read(organizationId: string, connectorName: string): Promise<ConnectorConnectionRecord | undefined> {
112128
const engine = this.resolveEngine();

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1106,6 +1106,35 @@ describe('ADR-0143 D4 — a grant-bearing instance is served through its credent
11061106
await kernel.shutdown();
11071107
});
11081108

1109+
it.each([
1110+
['tokenUrl', { tokenUrl: 'http://idp.example.com/token' }],
1111+
['authorizationUrl', { authorizationUrl: 'http://idp.example.com/authorize' }],
1112+
['tokenUrl', { tokenUrl: 'ftp://idp.example.com/token' }],
1113+
] as const)('⛔ holds an `oauth2` instance degraded when its `%s` is not https off loopback, naming the field', async (field, over) => {
1114+
const { factory, calls } = makeFakeProvider();
1115+
const kernel = await boot([providerConnector('vendor', { auth: { ...AUTHORIZATION_CODE, ...over } as ConnectorInstanceAuth })], {
1116+
providerFactory: factory,
1117+
providerOptions: { credentialHandle: true },
1118+
credentialResolver: () => 'resolved-secret',
1119+
});
1120+
expectHeld(automationOf(kernel), calls, `\`${field}\` not over https`, 'not served');
1121+
// The reason names the field, never the URL it was given.
1122+
expect(automationOf(kernel).getConnectorDegradedReason('vendor')).not.toContain('idp.example.com');
1123+
await kernel.shutdown();
1124+
});
1125+
1126+
it('serves an `oauth2` instance whose token endpoint is plain http on a loopback host', async () => {
1127+
const { factory, calls } = makeFakeProvider();
1128+
const kernel = await boot([providerConnector('vendor', { auth: { ...CLIENT_CREDENTIALS, tokenUrl: 'http://127.0.0.1:8080/token' } as ConnectorInstanceAuth })], {
1129+
providerFactory: factory,
1130+
providerOptions: { credentialHandle: true },
1131+
credentialResolver: () => 'resolved-secret',
1132+
});
1133+
expect(calls).toHaveLength(1);
1134+
expect(automationOf(kernel).getConnectorDescriptors().find((d) => d.name === 'vendor')?.state).toBe('ready');
1135+
await kernel.shutdown();
1136+
});
1137+
11091138
it('serves a `client_credentials` instance on an opted-in provider: a credential handle, and no static auth', async () => {
11101139
const { factory, calls } = makeFakeProvider();
11111140
const kernel = await boot([providerConnector('vendor', { auth: CLIENT_CREDENTIALS })], {
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// ADR-0143 D4 / D5 — an `oauth2` instance sends its client secret and refresh
4+
// token only over https, or over plain http to a loopback host.
5+
6+
import { describe, expect, it } from 'vitest';
7+
import { insecureOAuth2EndpointFields, isSecureOAuth2Endpoint } from './endpoint-transport.js';
8+
9+
describe('ADR-0143 D4 — which oauth2 endpoint a secret may be sent to', () => {
10+
it.each([
11+
'https://idp.example.com/token',
12+
'HTTPS://IDP.EXAMPLE.COM/token',
13+
'http://localhost:8080/token',
14+
'http://idp.localhost/token',
15+
'http://127.0.0.1:9000/token',
16+
'http://127.255.0.1/token',
17+
'http://[::1]:9000/token',
18+
])('accepts %s', (url) => {
19+
expect(isSecureOAuth2Endpoint(url)).toBe(true);
20+
});
21+
22+
it.each([
23+
'http://idp.example.com/token',
24+
'http://10.0.0.5/token',
25+
'http://128.0.0.1/token',
26+
'http://127.0.0.1.example.com/token',
27+
'http://localhost.example.com/token',
28+
'ftp://idp.example.com/token',
29+
'javascript:alert(1)',
30+
'not a url',
31+
])('refuses %s', (url) => {
32+
expect(isSecureOAuth2Endpoint(url)).toBe(false);
33+
});
34+
35+
it('names the refused fields, in order, and ignores the ones not declared', () => {
36+
expect(insecureOAuth2EndpointFields({ tokenUrl: 'http://idp.example.com/t', authorizationUrl: 'http://idp.example.com/a' }))
37+
.toEqual(['tokenUrl', 'authorizationUrl']);
38+
expect(insecureOAuth2EndpointFields({ tokenUrl: 'https://idp.example.com/t' })).toEqual([]);
39+
expect(insecureOAuth2EndpointFields({})).toEqual([]);
40+
});
41+
});
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* ADR-0143 D4 / D5 — which endpoint an `oauth2` instance may send its secrets
5+
* to. The token request carries the client secret (HTTP Basic) and the refresh
6+
* token, and the authorization URL is where an administrator's browser is sent,
7+
* so both must be `https:`. The spec admits any URL (`z.string().url()`), so the
8+
* server holds the line: plain `http:` is accepted only to a loopback host,
9+
* where nothing crosses a network, and every other scheme is refused.
10+
*/
11+
12+
/** The `oauth2` endpoint fields this check covers, in the order a reason names them. */
13+
export const OAUTH2_ENDPOINT_FIELDS = ['tokenUrl', 'authorizationUrl'] as const;
14+
15+
/** True for `localhost`, a `*.localhost` name, any `127.0.0.0/8` address and `[::1]`. */
16+
function isLoopbackHost(hostname: string): boolean {
17+
const host = hostname.toLowerCase();
18+
if (host === 'localhost' || host.endsWith('.localhost')) return true;
19+
if (host === '[::1]') return true;
20+
return /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(host);
21+
}
22+
23+
/**
24+
* True when `url` is an endpoint an `oauth2` instance may send its secrets to:
25+
* `https:`, or `http:` to a loopback host. A value that does not parse is not.
26+
*/
27+
export function isSecureOAuth2Endpoint(url: string): boolean {
28+
let parsed: URL;
29+
try {
30+
parsed = new URL(url);
31+
} catch {
32+
return false;
33+
}
34+
if (parsed.protocol === 'https:') return true;
35+
return parsed.protocol === 'http:' && isLoopbackHost(parsed.hostname);
36+
}
37+
38+
/**
39+
* The endpoint fields of `auth` that {@link isSecureOAuth2Endpoint} refuses,
40+
* by name. The URLs themselves are never echoed: a reason names the field.
41+
*/
42+
export function insecureOAuth2EndpointFields(auth: Partial<Record<(typeof OAUTH2_ENDPOINT_FIELDS)[number], unknown>>): string[] {
43+
return OAUTH2_ENDPOINT_FIELDS.filter((field) => {
44+
const value = auth[field];
45+
return typeof value === 'string' && !isSecureOAuth2Endpoint(value);
46+
});
47+
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@
1010
export * from './token-endpoint.js';
1111
export * from './grant-handle.js';
1212
export * from './authorization.js';
13+
export * from './endpoint-transport.js';

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

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ import {
7171
createAuthorizationState,
7272
createOAuth2GrantHandle,
7373
createPkcePair,
74+
insecureOAuth2EndpointFields,
7475
kvPendingAuthorizationStore,
7576
memoryPendingAuthorizationStore,
7677
notConnectedReason,
@@ -458,7 +459,10 @@ function appCredentialNotServedReason(name: string, auth: Extract<ConnectorInsta
458459
* request (`registerConnectorProvider(…, { credentialHandle: true })`), and
459460
* the endpoints and client the handle sends a token request with — on
460461
* `provider: 'mcp'` over http they may be omitted for the MCP authorization
461-
* flow to discover and register, which is not run here yet.
462+
* flow to discover and register, which is not run here yet. An endpoint over
463+
* plain `http:` off loopback, or any other scheme, is refused by field
464+
* (`./oauth2-grant/endpoint-transport.ts`): the client secret and the refresh
465+
* token would cross the network in the clear.
462466
*/
463467
function oauth2NotServableReason(name: string, provider: string, auth: OAuth2InstanceAuth, providerApplies: boolean): string | undefined {
464468
if (!providerApplies) {
@@ -471,10 +475,17 @@ function oauth2NotServableReason(name: string, provider: string, auth: OAuth2Ins
471475
auth.clientId === undefined ? 'clientId' : undefined,
472476
auth.grant === 'authorization_code' && auth.authorizationUrl === undefined ? 'authorizationUrl' : undefined,
473477
].filter((k): k is string => k !== undefined);
474-
if (missing.length === 0) return undefined;
475-
return `connector instance '${name}' declares auth type 'oauth2' without ${missing.map((k) => `\`${k}\``).join(', ')}: `
476-
+ 'discovering the endpoints and registering a client (the MCP authorization flow) is not run by this server yet '
477-
+ '(ADR-0143 D2.1), so the instance is not served. Declare them to dispatch it now.';
478+
if (missing.length > 0) {
479+
return `connector instance '${name}' declares auth type 'oauth2' without ${missing.map((k) => `\`${k}\``).join(', ')}: `
480+
+ 'discovering the endpoints and registering a client (the MCP authorization flow) is not run by this server yet '
481+
+ '(ADR-0143 D2.1), so the instance is not served. Declare them to dispatch it now.';
482+
}
483+
const insecure = insecureOAuth2EndpointFields(auth as Partial<Record<'tokenUrl' | 'authorizationUrl', unknown>>);
484+
if (insecure.length === 0) return undefined;
485+
return `connector instance '${name}' declares auth type 'oauth2' with ${insecure.map((k) => `\`${k}\``).join(', ')} `
486+
+ 'not over https: the client secret, the refresh token and the authorization redirect would cross the network in '
487+
+ 'the clear (ADR-0143 D4), so the instance is not served. Declare an https:// endpoint; plain http:// is accepted '
488+
+ 'only to a loopback host.';
478489
}
479490

480491
/**
@@ -3100,7 +3111,7 @@ export class AutomationServicePlugin implements Plugin {
31003111
/** ADR-0143 D3 — `IAutomationService.getConnectorConnection`. */
31013112
private async getConnectorConnection(ctx: PluginContext, request: ConnectorConnectionRequest): Promise<ConnectorConnectionState> {
31023113
const { name, organizationId } = await this.connectionDoorSubject(ctx, request);
3103-
return this.describeConnection(name, organizationId, await this.connectorConnectionStoreOrNone().read(organizationId, name));
3114+
return this.describeConnection(name, organizationId, await this.connectorConnectionStoreOrNone().readOrRefuse(organizationId, name));
31043115
}
31053116

31063117
/**

0 commit comments

Comments
 (0)