|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// ADR-0143 D2.1 (2026-11-02 amendment) — an `oauth2` `authorization_code` |
| 4 | +// connector instance declaring `clientSource: 'installer'` names no client in |
| 5 | +// its definition: the administrator of each deployment registers a client |
| 6 | +// with the vendor and enters it on the connection. Booted on the showcase with |
| 7 | +// its own connector plugins, through the real HTTP connection door: |
| 8 | +// |
| 9 | +// - SERVED: saved over `PUT /meta/connector/:name`, the instance is held "not |
| 10 | +// connected" until a connect, never degraded for a missing `clientId`. |
| 11 | +// - ⛔ REFUSED: a begin with no client, and a begin body carrying a key other |
| 12 | +// than `clientId` / `clientSecret`, answer `400 VALIDATION_ERROR` and store |
| 13 | +// nothing; no refusal repeats a value the caller sent. |
| 14 | +// - CONNECTED: a begin with the administrator's client sends the browser to |
| 15 | +// the vendor as that client; the callback exchanges the code as it (its |
| 16 | +// secret in HTTP Basic); the connection's read shows which client is set, |
| 17 | +// never its secret; the stored row keeps the id in plain text and the |
| 18 | +// secret only behind the masked column; revoke removes it. |
| 19 | +// |
| 20 | +// Every credential below is an obviously-fake placeholder, and every |
| 21 | +// assertion on the secret is its absence from what a door served. |
| 22 | + |
| 23 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 24 | +import { createServer, type Server } from 'node:http'; |
| 25 | +import type { AddressInfo } from 'node:net'; |
| 26 | +import { type VerifyStack } from '@objectstack/verify'; |
| 27 | +import { bootShowcase } from './showcase-boot.js'; |
| 28 | + |
| 29 | +const SYSTEM = { isSystem: true, positions: [], permissions: [] }; |
| 30 | + |
| 31 | +const NAME = 'cioc_vendor'; |
| 32 | +const INSTALLER_ID = 'TEST_PLACEHOLDER_INSTALLER_CLIENT_ID'; |
| 33 | +const INSTALLER_SECRET = 'TEST_PLACEHOLDER_INSTALLER_CLIENT_SECRET'; |
| 34 | +const CODE = 'TEST_PLACEHOLDER_AUTHORIZATION_CODE'; |
| 35 | +const ACCESS_TOKEN = 'TEST_PLACEHOLDER_ACCESS_TOKEN'; |
| 36 | +const REFRESH_TOKEN = 'TEST_PLACEHOLDER_REFRESH_TOKEN'; |
| 37 | + |
| 38 | +const door = `/automation/connectors/${NAME}/connection`; |
| 39 | +const basicOf = (id: string, secret: string) => `Basic ${Buffer.from(`${id}:${secret}`).toString('base64')}`; |
| 40 | +const rowsOf = (r: any): any[] => (Array.isArray(r) ? r : Array.isArray(r?.records) ? r.records : Array.isArray(r?.value) ? r.value : []); |
| 41 | +const dataOf = (json: any): any => json?.data ?? json; |
| 42 | +const errorOf = (json: any): { code?: string; message?: string } => { |
| 43 | + const e = json?.error; |
| 44 | + return typeof e === 'object' && e !== null ? e : { code: json?.code, message: typeof e === 'string' ? e : json?.message }; |
| 45 | +}; |
| 46 | + |
| 47 | +describe("connector connection door: an `oauth2` instance that takes the installer's OAuth client", () => { |
| 48 | + let stack: VerifyStack; |
| 49 | + let admin: string; |
| 50 | + let ql: any; |
| 51 | + let idp: Server; |
| 52 | + let idpUrl: string; |
| 53 | + let upstream: Server; |
| 54 | + let upstreamUrl: string; |
| 55 | + const tokenRequests: Array<{ form: URLSearchParams; authorization?: string }> = []; |
| 56 | + const savedOrigin = { auth: process.env.OS_AUTH_URL, base: process.env.OS_BASE_URL }; |
| 57 | + |
| 58 | + const stored = async () => |
| 59 | + rowsOf(await ql.find('sys_connector_connection', { where: { connector_name: NAME }, context: SYSTEM })); |
| 60 | + |
| 61 | + /** The listing's entry for the instance, polled until `until` holds. */ |
| 62 | + const listed = async (until: (entry: any) => boolean): Promise<any> => { |
| 63 | + const deadline = Date.now() + 15_000; |
| 64 | + let last: any; |
| 65 | + while (Date.now() < deadline) { |
| 66 | + const res = await stack.apiAs(admin, 'GET', '/automation/connectors'); |
| 67 | + const json = (await res.json()) as any; |
| 68 | + last = (json?.data?.connectors ?? []).find((c: any) => c?.name === NAME); |
| 69 | + if (last && until(last)) return last; |
| 70 | + await new Promise((r) => setTimeout(r, 100)); |
| 71 | + } |
| 72 | + throw new Error(`connector ${NAME} never reached the expected state: ${JSON.stringify(last ?? null)}`); |
| 73 | + }; |
| 74 | + |
| 75 | + beforeAll(async () => { |
| 76 | + idp = createServer((req, res) => { |
| 77 | + let body = ''; |
| 78 | + req.on('data', (c) => (body += c)); |
| 79 | + req.on('end', () => { |
| 80 | + const authorization = req.headers.authorization; |
| 81 | + tokenRequests.push({ form: new URLSearchParams(body), ...(authorization ? { authorization } : {}) }); |
| 82 | + res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 83 | + res.end(JSON.stringify({ access_token: ACCESS_TOKEN, refresh_token: REFRESH_TOKEN, token_type: 'Bearer', expires_in: 3600 })); |
| 84 | + }); |
| 85 | + }); |
| 86 | + await new Promise<void>((r) => idp.listen(0, '127.0.0.1', () => r())); |
| 87 | + idpUrl = `http://127.0.0.1:${(idp.address() as AddressInfo).port}`; |
| 88 | + upstream = createServer((_req, res) => { |
| 89 | + res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 90 | + res.end('{"ok":true}'); |
| 91 | + }); |
| 92 | + await new Promise<void>((r) => upstream.listen(0, '127.0.0.1', () => r())); |
| 93 | + upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`; |
| 94 | + |
| 95 | + stack = await bootShowcase({}); |
| 96 | + ql = await stack.kernel.getServiceAsync<any>('objectql'); |
| 97 | + admin = await stack.signIn(); |
| 98 | + // The redirect URI is the deployment's fixed origin, read when a connect |
| 99 | + // is begun — never at boot, and never from the request (ADR-0143 D5). |
| 100 | + if (!savedOrigin.auth && !savedOrigin.base) process.env.OS_BASE_URL = 'https://dogfood.example.com'; |
| 101 | + |
| 102 | + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${NAME}`, { |
| 103 | + name: NAME, |
| 104 | + label: 'CIOC vendor', |
| 105 | + type: 'api', |
| 106 | + description: "An `oauth2` instance whose OAuth client each deployment's administrator enters.", |
| 107 | + provider: 'rest', |
| 108 | + providerConfig: { baseUrl: upstreamUrl }, |
| 109 | + auth: { |
| 110 | + type: 'oauth2', |
| 111 | + grant: 'authorization_code', |
| 112 | + authorizationUrl: `${idpUrl}/authorize`, |
| 113 | + tokenUrl: `${idpUrl}/token`, |
| 114 | + clientSource: 'installer', |
| 115 | + scopes: ['vendor.read'], |
| 116 | + }, |
| 117 | + }); |
| 118 | + expect(put.status, await put.clone().text()).toBe(200); |
| 119 | + }, 180_000); |
| 120 | + |
| 121 | + afterAll(async () => { |
| 122 | + await stack?.stop?.(); |
| 123 | + await new Promise<void>((r) => (idp ? idp.close(() => r()) : r())); |
| 124 | + await new Promise<void>((r) => (upstream ? upstream.close(() => r()) : r())); |
| 125 | + if (savedOrigin.base === undefined) delete process.env.OS_BASE_URL; |
| 126 | + else process.env.OS_BASE_URL = savedOrigin.base; |
| 127 | + }); |
| 128 | + |
| 129 | + it('SERVED: before a connect the instance is held "not connected", never for a missing `clientId`', async () => { |
| 130 | + const entry = await listed((e) => JSON.stringify(e).includes('is not connected')); |
| 131 | + expect(JSON.stringify(entry)).not.toContain('clientId'); |
| 132 | + const read = await stack.apiAs(admin, 'GET', door); |
| 133 | + expect(read.status, await read.clone().text()).toBe(200); |
| 134 | + expect(dataOf(await read.json())).toMatchObject({ connector: NAME, status: 'not_connected' }); |
| 135 | + }); |
| 136 | + |
| 137 | + it('⛔ a begin with no client is refused 400 VALIDATION_ERROR, naming the vendor registration step; nothing is stored', async () => { |
| 138 | + const res = await stack.apiAs(admin, 'POST', door); |
| 139 | + const json = (await res.json()) as any; |
| 140 | + expect(res.status, JSON.stringify(json).slice(0, 400)).toBe(400); |
| 141 | + expect(errorOf(json).code).toBe('VALIDATION_ERROR'); |
| 142 | + expect(errorOf(json).message).toContain(`Connector instance '${NAME}' takes its OAuth client from the installer`); |
| 143 | + expect(errorOf(json).message).toContain('Register an OAuth client for this deployment with the vendor'); |
| 144 | + expect(tokenRequests).toHaveLength(0); |
| 145 | + expect(await stored()).toHaveLength(0); |
| 146 | + }); |
| 147 | + |
| 148 | + it('⛔ a begin body carrying another key is refused 400 naming the key, never repeating a value', async () => { |
| 149 | + const res = await stack.apiAs(admin, 'POST', door, { clientId: INSTALLER_ID, clientSecret: INSTALLER_SECRET, client_secret: INSTALLER_SECRET }); |
| 150 | + const text = await res.text(); |
| 151 | + expect(res.status, text.slice(0, 400)).toBe(400); |
| 152 | + expect(errorOf(JSON.parse(text)).code).toBe('VALIDATION_ERROR'); |
| 153 | + expect(text).toContain('`client_secret`'); |
| 154 | + expect(text).not.toContain(INSTALLER_SECRET); |
| 155 | + expect(tokenRequests).toHaveLength(0); |
| 156 | + expect(await stored()).toHaveLength(0); |
| 157 | + }); |
| 158 | + |
| 159 | + it("CONNECTED: authorizes and exchanges as the administrator's client; the read names it, never its secret; revoke removes it", async () => { |
| 160 | + const begun = await stack.apiAs(admin, 'POST', door, { clientId: INSTALLER_ID, clientSecret: INSTALLER_SECRET }); |
| 161 | + const beginText = await begun.text(); |
| 162 | + expect(begun.status, beginText.slice(0, 400)).toBe(200); |
| 163 | + expect(beginText).not.toContain(INSTALLER_SECRET); |
| 164 | + const authorizationUrl = new URL(dataOf(JSON.parse(beginText)).authorizationUrl); |
| 165 | + expect(authorizationUrl.origin + authorizationUrl.pathname).toBe(`${idpUrl}/authorize`); |
| 166 | + expect(authorizationUrl.searchParams.get('client_id')).toBe(INSTALLER_ID); |
| 167 | + const state = authorizationUrl.searchParams.get('state'); |
| 168 | + expect(state).toBeTruthy(); |
| 169 | + |
| 170 | + const callback = await stack.apiAs( |
| 171 | + admin, 'GET', `/automation/connectors/oauth/callback?state=${encodeURIComponent(state!)}&code=${CODE}`, |
| 172 | + ); |
| 173 | + const callbackText = await callback.text(); |
| 174 | + expect(callback.status, callbackText.slice(0, 400)).toBe(200); |
| 175 | + expect(callbackText).not.toContain(INSTALLER_SECRET); |
| 176 | + expect(tokenRequests).toHaveLength(1); |
| 177 | + expect(tokenRequests[0].authorization).toBe(basicOf(INSTALLER_ID, INSTALLER_SECRET)); |
| 178 | + expect(tokenRequests[0].form.get('grant_type')).toBe('authorization_code'); |
| 179 | + expect(tokenRequests[0].form.get('code')).toBe(CODE); |
| 180 | + |
| 181 | + const read = await stack.apiAs(admin, 'GET', door); |
| 182 | + const readText = await read.text(); |
| 183 | + expect(read.status, readText.slice(0, 400)).toBe(200); |
| 184 | + expect(dataOf(JSON.parse(readText))).toMatchObject({ |
| 185 | + connector: NAME, |
| 186 | + status: 'connected', |
| 187 | + client: { source: 'installer', clientId: INSTALLER_ID, hasSecret: true }, |
| 188 | + }); |
| 189 | + expect(readText).not.toContain(INSTALLER_SECRET); |
| 190 | + expect(readText).not.toContain(REFRESH_TOKEN); |
| 191 | + |
| 192 | + const [row] = await stored(); |
| 193 | + expect(row).toMatchObject({ connector_name: NAME, client_id: INSTALLER_ID }); |
| 194 | + expect(JSON.stringify(row)).not.toContain(INSTALLER_SECRET); |
| 195 | + |
| 196 | + const revoked = await stack.apiAs(admin, 'DELETE', door); |
| 197 | + expect(revoked.status, await revoked.clone().text()).toBe(200); |
| 198 | + expect(dataOf(await revoked.json())).toMatchObject({ connector: NAME, status: 'not_connected' }); |
| 199 | + expect(await stored()).toHaveLength(0); |
| 200 | + }); |
| 201 | +}); |
0 commit comments