Skip to content

Commit c4e1506

Browse files
committed
fix(service-automation): harden the OAuth2 connection door (ADR-0143 S1 should-fixes)
- Seal the pending authorization (PKCE verifier, user, organization, redirect URI) with AES-256-GCM under a key derived from the raw state, which the server keeps only as a digest; an edited or moved KV value opens as nothing. Documents the cluster KV trust boundary. - Write a refresh, the "reconnect required" mark and a reconnect only over the revision they read, as one conditional write (where id + revision). - Route connect()/revoke() reads through readOrRefuse (503, never 500). - Never follow a token endpoint redirect; refuse it. - Drop the *.localhost arm of the plain-http loopback allowance. - State the missing RFC 7009 vendor revocation in the route ledger and docs. Claude-Session: https://claude.ai/code/session_01QUs3BvFbD3DRY4t9ByMH8B Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3ba5206 commit c4e1506

10 files changed

Lines changed: 506 additions & 44 deletions

File tree

‎content/docs/automation/connectors.mdx‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,15 @@ a rotating refresh token is never spent twice.
495495
(`not_connected`, `connected`, `reconnect_required`), never a token. The
496496
`state` and the PKCE verifier are bound to the user and organization that
497497
began the connect and are used once; a callback from anyone else is refused
498-
before its code is exchanged. The redirect URI is the deployment's
498+
before its code is exchanged. While the connect waits (ten minutes at most)
499+
it is held in the cluster KV, or in process on a single node, **sealed**
500+
under a key derived from the `state` itself, which the server never stores:
501+
the KV holds only the state's digest and an AES-256-GCM envelope, so a party
502+
that can read the KV learns no verifier, user or organization, and a value
503+
edited or moved there opens as nothing and its code is never exchanged.
504+
Write access to the cluster KV stays inside the platform's trust boundary,
505+
as it is for the cluster lock: such a writer can still delete a waiting
506+
connect. The redirect URI is the deployment's
499507
(`OS_BASE_URL` or `OS_AUTH_URL` plus `/api/v1/automation/connectors/oauth/callback`,
500508
or the automation plugin's `connectorOAuthRedirectUri`), never the
501509
request's; register that URI with the vendor. The refresh token is kept
@@ -505,18 +513,27 @@ a rotating refresh token is never spent twice.
505513
instance's only connection, and is refused when there are several. When the
506514
vendor refuses the grant (`invalid_grant`), the connection is marked
507515
**reconnect required** and the instance degraded until an administrator
508-
connects it again. A revoke deletes the stored connection only: the server
509-
does not yet revoke the refresh token at the vendor (RFC 7009), so it stays
510-
valid there until it expires or is revoked in the vendor's console.
516+
connects it again. A refresh, and the mark "reconnect required", are each
517+
written only over the revision they read, in one conditional write, so a
518+
stale one never overwrites a newer connect on any replica. A revoke deletes
519+
the stored connection only: the server does not revoke the refresh token at
520+
the vendor (RFC 7009), because no revocation endpoint is known for the
521+
instance yet — the auth declares none, and the discovery that would supply
522+
one is ADR-0143 S2. The refresh token stays valid at the vendor until it
523+
expires or is revoked in the vendor's console; revoke it there too when the
524+
disconnect is a response to a leak.
511525

512526
What is not served yet is held **degraded** with a reason that names it, and
513527
never called without its credential: `app-credential` (its vendor exchanges
514528
are not run yet), an `oauth2` instance on a provider that does not yet ask the
515529
credential handle (the built-in `rest`, `openapi` and `mcp` providers do not
516530
yet), an `mcp` instance that left its endpoints to discovery, and an `oauth2`
517531
instance whose `tokenUrl` or `authorizationUrl` is not `https://` (plain
518-
`http://` is accepted only to a loopback host, so the client secret and the
519-
refresh token never cross a network in the clear). A datasource
532+
`http://` is accepted only to `localhost`, a `127.0.0.0/8` address or
533+
`[::1]` — not a `*.localhost` name, which the system resolver sends to DNS —
534+
so the client secret and the refresh token never cross a network in the
535+
clear; a token endpoint that answers with a redirect is refused rather than
536+
followed). A datasource
520537
that borrows from a grant-bearing instance (`external.connector`) is refused
521538
with `422`. Until then, declare a static kind (`bearer`, `api-key` or `basic`)
522539
to dispatch now; don't emulate a grant by putting a short-lived access token

‎packages/runtime/src/route-ledger.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -548,9 +548,9 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [
548548
{ route: 'GET /automation/connectors/:name/connection', domain: '/automation', disposition: 'server-only',
549549
note: "The caller's organization's connection of one declared `oauth2` `authorization_code` instance: `status` (`not_connected` / `connected` / `reconnect_required`), its reason, the granted scopes, the access token's expiry and who connected it. ⛔ Never a token. Refused: an undeclared instance 404 `RESOURCE_NOT_FOUND`; one whose auth is not that grant, or a caller with no organization, 400 `VALIDATION_ERROR`. ⚑ `manage_metadata`, fail-closed, only `isSystem` bypassing; no walled refusal, since a connection belongs to its organization. Closed query set: none. NOT JS-SDK surface on this leg: the driver is the Console's Connect / Reconnect flow (ADR-0143 S4). Pinned in `domains/automation-connector-connection-door.test.ts`" },
550550
{ route: 'POST /automation/connectors/:name/connection', domain: '/automation', disposition: 'server-only',
551-
note: "Begin connecting (or reconnecting) the instance for the caller's organization: answers `{ authorizationUrl, expiresAt }`, the vendor URL carrying a fresh `state` and an `S256` PKCE challenge. Nothing is written to the connection record until the callback completes; the pending authorization (verifier included) waits ten minutes in the cluster KV, or in process on a single node. The redirect URI is the deployment's (`OS_AUTH_URL` / `OS_BASE_URL`, or the plugin option), never the request's — 503 `SERVICE_UNAVAILABLE` when there is none. No body. Same refusals, gates and SDK posture as the GET row above. Pinned in `domains/automation-connector-connection-door.test.ts`" },
551+
note: "Begin connecting (or reconnecting) the instance for the caller's organization: answers `{ authorizationUrl, expiresAt }`, the vendor URL carrying a fresh `state` and an `S256` PKCE challenge. Nothing is written to the connection record until the callback completes; the pending authorization (verifier included) waits ten minutes in the cluster KV, or in process on a single node, sealed (AES-256-GCM) under a key derived from the raw `state`, which the server keeps only as a digest. The redirect URI is the deployment's (`OS_AUTH_URL` / `OS_BASE_URL`, or the plugin option), never the request's — 503 `SERVICE_UNAVAILABLE` when there is none. No body. Same refusals, gates and SDK posture as the GET row above. Pinned in `domains/automation-connector-connection-door.test.ts`" },
552552
{ route: 'DELETE /automation/connectors/:name/connection', domain: '/automation', disposition: 'server-only',
553-
note: "Revoke the caller's organization's connection: the row is removed, the cached access token dropped, and the instance re-judged — its next dispatch there is refused 'not connected'. 404 `RESOURCE_NOT_FOUND` when it was not connected. Same gates and SDK posture as the GET row above. Pinned in `domains/automation-connector-connection-door.test.ts`" },
553+
note: "Revoke the caller's organization's connection: the row is removed, the cached access token dropped, and the instance re-judged — its next dispatch there is refused 'not connected'. ⚑ Local only: no RFC 7009 revocation is sent to the vendor, because no revocation endpoint is known for the instance (the auth declares none; ADR-0143 S2 discovery would supply one), so the refresh token stays valid at the vendor until it expires or is revoked there. 404 `RESOURCE_NOT_FOUND` when it was not connected; 503 `SERVICE_UNAVAILABLE` when the connection store cannot be read. Same gates and SDK posture as the GET row above. Pinned in `domains/automation-connector-connection-door.test.ts`" },
554554
{ route: 'GET /automation/connectors/oauth/callback', domain: '/automation', disposition: 'server-only',
555555
note: "The authorization server's redirect (ADR-0143 D5). Closed query set: `code`, `state`, `error`, `error_description`, `error_uri`, `iss`; an unknown or repeated one is 400 `VALIDATION_ERROR`. The `state` is taken once and must have been begun by the same user in the same organization, else 400 before any code is exchanged; an `error` answer is 400 naming its registered code only. The code is exchanged with the PKCE verifier and the connection stored; answers the connection's status. 503 when the token endpoint cannot be reached. Same capability gate as the rows above: the browser landing here is the administrator's. Pinned in `domains/automation-connector-connection-door.test.ts`" },
556556
{ route: 'GET /automation/_status', domain: '/automation', disposition: 'sdk', client: 'automation.getRuntimeStatus' },
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// ADR-0143 D3 / D4 — the `sys_connector_connection` store over a real ObjectQL
4+
// engine (SQLite, a test crypto provider): a refresh and the "reconnect
5+
// required" mark are written only over the revision they read, by the write
6+
// itself; a store that cannot be read refuses a connect and a revoke with the
7+
// declared 503. The values below are obvious dummies.
8+
9+
import { afterEach, describe, expect, it } from 'vitest';
10+
import { ObjectQL } from '@objectstack/objectql';
11+
import { SqlDriver } from '@objectstack/driver-sql';
12+
import { SysSecret } from '@objectstack/platform-objects';
13+
import type { CryptoContext, CryptoHandle, ICryptoProvider } from '@objectstack/spec/contracts';
14+
15+
import {
16+
CONNECTOR_CONNECTION_OBJECT,
17+
ConnectorConnectionStore,
18+
type ConnectorConnectionRecord,
19+
} from './connector-connections.js';
20+
import type { ConnectorCredentialEngine } from './connector-credentials.js';
21+
import { SysConnectorConnection } from './sys-connector-connection.object.js';
22+
23+
const SYSTEM = { isSystem: true } as const;
24+
25+
function fakeCrypto(): ICryptoProvider {
26+
let n = 0;
27+
return {
28+
async encrypt(plain: string, _ctx: CryptoContext): Promise<CryptoHandle> {
29+
n += 1;
30+
return { id: `sec_${n}`, kmsKeyId: 'test', alg: 'test-rev', version: 1, ciphertext: [...plain].reverse().join('') };
31+
},
32+
async decrypt(handle: CryptoHandle): Promise<string> {
33+
return [...handle.ciphertext].reverse().join('');
34+
},
35+
async rotateKey(handle: CryptoHandle): Promise<CryptoHandle> {
36+
return { ...handle, version: handle.version + 1 };
37+
},
38+
digest: (plain: string) => `d:${plain.length}`,
39+
keyedDigest: async (plain: string) => `k:${plain.length}`,
40+
};
41+
}
42+
43+
const engines: ObjectQL[] = [];
44+
afterEach(async () => {
45+
for (const e of engines.splice(0)) {
46+
try { await (e as any).destroy?.(); } catch { /* noop */ }
47+
}
48+
});
49+
50+
async function dataEngine(): Promise<ObjectQL> {
51+
const ql = new ObjectQL();
52+
engines.push(ql);
53+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
54+
await driver.connect();
55+
ql.registerDriver(driver, true);
56+
await ql.init();
57+
for (const object of [SysSecret, SysConnectorConnection]) (ql as any).registry.registerObject(object as never, 'test');
58+
await ql.syncSchemas();
59+
ql.setCryptoProvider(fakeCrypto());
60+
return ql;
61+
}
62+
63+
/**
64+
* The engine as the store sees it, with `beforeUpdate` run between the store's
65+
* call and the real write — another replica's write landing in that gap.
66+
*/
67+
function interleaved(ql: ObjectQL, beforeUpdate: () => Promise<void>): ConnectorCredentialEngine {
68+
let armed = true;
69+
return {
70+
find: (o, q) => ql.find(o, q as never),
71+
insert: (o, d, opts) => ql.insert(o, d, opts as never),
72+
delete: (o, opts) => ql.delete(o, opts as never),
73+
resolveSecretField: (o, id, f) => (ql as any).resolveSecretField(o, id, f),
74+
async update(o, d, opts) {
75+
if (armed) {
76+
armed = false;
77+
await beforeUpdate();
78+
}
79+
return ql.update(o, d, opts as never);
80+
},
81+
};
82+
}
83+
84+
async function connected(ql: ObjectQL): Promise<{ store: ConnectorConnectionStore; record: ConnectorConnectionRecord }> {
85+
const store = new ConnectorConnectionStore(() => ql as unknown as ConnectorCredentialEngine);
86+
const record = await store.connect({ organizationId: 'org_a', connectorName: 'crm', userId: 'usr_admin', refreshToken: 'dummy-rt-1' });
87+
return { store, record };
88+
}
89+
90+
/** Another replica's reconnect: a fresh grant over the same row, revision raised. */
91+
async function reconnectElsewhere(ql: ObjectQL, record: ConnectorConnectionRecord): Promise<void> {
92+
await ql.update(
93+
CONNECTOR_CONNECTION_OBJECT,
94+
{ id: record.id, refresh_token: 'dummy-rt-elsewhere', status: 'connected', status_reason: null, revision: record.revision + 1 },
95+
{ context: SYSTEM } as never,
96+
);
97+
}
98+
99+
describe('ADR-0143 D4 — a refresh is written only over the revision it read', () => {
100+
it('writes a rotated token and raises the revision when the row has not moved', async () => {
101+
const ql = await dataEngine();
102+
const { store, record } = await connected(ql);
103+
const expiresAt = new Date('2030-01-01T00:00:00.000Z');
104+
expect(await store.recordRefresh(record, { refreshToken: 'dummy-rt-2', scopes: 'crm.read', expiresAt })).toBe(true);
105+
const now = (await store.read('org_a', 'crm'))!;
106+
expect(now).toMatchObject({ revision: record.revision + 1, scopes: 'crm.read', expiresAt: expiresAt.toISOString() });
107+
expect(await store.resolveRefreshToken(now)).toBe('dummy-rt-2');
108+
});
109+
110+
it('a refresh that rotates nothing keeps the token and the revision, and still writes the expiry', async () => {
111+
const ql = await dataEngine();
112+
const { store, record } = await connected(ql);
113+
expect(await store.recordRefresh(record, { expiresAt: new Date('2030-01-01T00:00:00.000Z') })).toBe(true);
114+
const now = (await store.read('org_a', 'crm'))!;
115+
expect(now.revision).toBe(record.revision);
116+
expect(now.expiresAt).toBe('2030-01-01T00:00:00.000Z');
117+
expect(await store.resolveRefreshToken(now)).toBe('dummy-rt-1');
118+
});
119+
120+
it('⛔ a reconnect landing between the refresh and its write is never overwritten by the stale rotation', async () => {
121+
const ql = await dataEngine();
122+
const { record } = await connected(ql);
123+
const store = new ConnectorConnectionStore(() => interleaved(ql, () => reconnectElsewhere(ql, record)));
124+
expect(await store.recordRefresh(record, { refreshToken: 'dummy-rt-stale' })).toBe(false);
125+
const now = (await store.read('org_a', 'crm'))!;
126+
expect(now.revision).toBe(record.revision + 1);
127+
expect(await store.resolveRefreshToken(now)).toBe('dummy-rt-elsewhere');
128+
});
129+
130+
it('⛔ a row revoked since the refresh read it is not written', async () => {
131+
const ql = await dataEngine();
132+
const { store, record } = await connected(ql);
133+
expect(await store.revoke('org_a', 'crm')).toBe(true);
134+
expect(await store.recordRefresh(record, { refreshToken: 'dummy-rt-stale' })).toBe(false);
135+
expect(await store.read('org_a', 'crm')).toBeUndefined();
136+
});
137+
});
138+
139+
describe('ADR-0143 D4 — "reconnect required" is written only over the revision that was refused', () => {
140+
it('marks the refused grant and drops its token when the row has not moved', async () => {
141+
const ql = await dataEngine();
142+
const { store, record } = await connected(ql);
143+
await store.markReconnectRequired(record, 'the vendor refused the grant');
144+
const now = (await store.read('org_a', 'crm'))!;
145+
expect(now).toMatchObject({ status: 'reconnect_required', statusReason: 'the vendor refused the grant', hasRefreshToken: false });
146+
});
147+
148+
it('⛔ a reconnect landing between the refusal and its write keeps its fresh grant', async () => {
149+
const ql = await dataEngine();
150+
const { record } = await connected(ql);
151+
const store = new ConnectorConnectionStore(() => interleaved(ql, () => reconnectElsewhere(ql, record)));
152+
await store.markReconnectRequired(record, 'the vendor refused the grant');
153+
const now = (await store.read('org_a', 'crm'))!;
154+
expect(now).toMatchObject({ status: 'connected', revision: record.revision + 1, hasRefreshToken: true });
155+
expect(await store.resolveRefreshToken(now)).toBe('dummy-rt-elsewhere');
156+
});
157+
});
158+
159+
describe('ADR-0143 D5 — a reconnect is written only over the revision it read', () => {
160+
it('replaces the grant and raises the revision', async () => {
161+
const ql = await dataEngine();
162+
const { store, record } = await connected(ql);
163+
const again = await store.connect({ organizationId: 'org_a', connectorName: 'crm', refreshToken: 'dummy-rt-again' });
164+
expect(again.id).toBe(record.id);
165+
expect(again.revision).toBe(record.revision + 1);
166+
expect(await store.resolveRefreshToken(again)).toBe('dummy-rt-again');
167+
});
168+
169+
it('⛔ a reconnect racing another one refuses 503 and keeps nothing of its own', async () => {
170+
const ql = await dataEngine();
171+
const { record } = await connected(ql);
172+
const store = new ConnectorConnectionStore(() => interleaved(ql, () => reconnectElsewhere(ql, record)));
173+
await expect(store.connect({ organizationId: 'org_a', connectorName: 'crm', refreshToken: 'dummy-rt-loser' }))
174+
.rejects.toMatchObject({ name: 'ConnectorCredentialUnavailableError', status: 503 });
175+
const now = (await store.read('org_a', 'crm'))!;
176+
expect(await store.resolveRefreshToken(now)).toBe('dummy-rt-elsewhere');
177+
});
178+
});
179+
180+
describe('ADR-0143 D5 — a connection store that cannot be read refuses 503, never 500', () => {
181+
const unreadable = (): ConnectorCredentialEngine => ({
182+
find: async () => { throw new Error('dummy driver failure naming row 42'); },
183+
insert: async () => { throw new Error('not reached'); },
184+
update: async () => { throw new Error('not reached'); },
185+
delete: async () => { throw new Error('not reached'); },
186+
});
187+
188+
it.each([
189+
['connect', (s: ConnectorConnectionStore) => s.connect({ organizationId: 'org_a', connectorName: 'crm', refreshToken: 'dummy-rt' })],
190+
['revoke', (s: ConnectorConnectionStore) => s.revoke('org_a', 'crm')],
191+
] as const)('⛔ %s', async (_verb, act) => {
192+
const err = await act(new ConnectorConnectionStore(unreadable)).catch((e: unknown) => e);
193+
expect(err).toMatchObject({ name: 'ConnectorCredentialUnavailableError', status: 503 });
194+
expect(String((err as Error).message)).not.toContain('row 42');
195+
});
196+
});

0 commit comments

Comments
 (0)