|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#24150] The release this server reports to the cloud is the release |
| 5 | + * discovery reports. |
| 6 | + * |
| 7 | + * `runtime_version` reaches the cloud at two sites, both driven here through |
| 8 | + * the routes `CloudConnectionPlugin` really mounts (`start()` + |
| 9 | + * `kernel:ready`): the approval links `bind/start` returns (the page an |
| 10 | + * approver reads to see WHAT they are authorizing), and the registration claim |
| 11 | + * `bind/poll` sends to the control plane's `/bind`, captured at a stand-in |
| 12 | + * control plane. |
| 13 | + * |
| 14 | + * - With `OS_RUNTIME_VERSION` unset, both sites carry the `version` the real |
| 15 | + * discovery producer (`ObjectStackProtocolImplementation.getDiscovery()`, |
| 16 | + * the one `GET /api/v1/discovery` serves) returns on the same harness. The |
| 17 | + * expected value is READ from that producer, never written here, so a |
| 18 | + * constant at either site fails whatever constant it picks. |
| 19 | + * - A set `OS_RUNTIME_VERSION` is sent verbatim, with or without a discovery |
| 20 | + * producer on the kernel: the operator's stamp is the plugin's own read. |
| 21 | + * - With no discovery read (no `protocol` service, or one that throws), |
| 22 | + * neither site sends a version. Before this, both sent the plugin's own |
| 23 | + * `version` field, which names the plugin, not the server's release. |
| 24 | + */ |
| 25 | + |
| 26 | +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; |
| 27 | +import { mkdtempSync, rmSync } from 'node:fs'; |
| 28 | +import { join } from 'node:path'; |
| 29 | +import { tmpdir } from 'node:os'; |
| 30 | +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; |
| 31 | +import { CloudConnectionPlugin } from './cloud-connection-plugin.js'; |
| 32 | +import { bindCatalogFromTables } from './__tests__/security-catalog.testkit.js'; |
| 33 | + |
| 34 | +const CC = '/api/v1/cloud-connection'; |
| 35 | +const ORIGIN = 'https://env.example.test'; |
| 36 | +const CLOUD = 'http://cloud.test'; |
| 37 | + |
| 38 | +/** Holds `setup.access`, which the two bind doors demand. */ |
| 39 | +const ADMIN = 'u_admin'; |
| 40 | +const GRANTS: Record<string, any[]> = { |
| 41 | + sys_user_permission_set: [{ id: 'ups_1', user_id: ADMIN, permission_set_id: 'ps_1', permission_set: 'setup_admin', organization_id: null }], |
| 42 | + sys_permission_set: [{ id: 'ps_1', name: 'setup_admin', system_permissions: ['setup.access'] }], |
| 43 | +}; |
| 44 | + |
| 45 | +/** |
| 46 | + * The discovery producer `GET /api/v1/discovery` serves, over the minimal |
| 47 | + * engine `discovery-version.test.ts` in `@objectstack/metadata-protocol` uses. |
| 48 | + */ |
| 49 | +function discoveryProducer() { |
| 50 | + const engine = { registry: { getObject: () => undefined, getRegisteredTypes: () => [] } }; |
| 51 | + return new ObjectStackProtocolImplementation(engine as any, () => new Map()); |
| 52 | +} |
| 53 | + |
| 54 | +/** What the discovery producer reports, read on this harness. */ |
| 55 | +async function discoveryRelease(): Promise<unknown> { |
| 56 | + return (await discoveryProducer().getDiscovery()).version; |
| 57 | +} |
| 58 | + |
| 59 | +type Handler = (c: any) => Promise<any>; |
| 60 | +type Mode = 'single' | 'multi'; |
| 61 | +/** `real` mounts the discovery producer; `none` mounts no `protocol` service; `throws` mounts one whose read fails. */ |
| 62 | +type Discovery = 'real' | 'none' | 'throws'; |
| 63 | + |
| 64 | +function makeC(path: string, body?: unknown) { |
| 65 | + const url = `${ORIGIN}${path}`; |
| 66 | + const headers = new Headers(); |
| 67 | + return { |
| 68 | + req: { |
| 69 | + url, |
| 70 | + raw: new Request(url, { headers }), |
| 71 | + header: (n: string) => headers.get(n) ?? undefined, |
| 72 | + json: async () => body ?? {}, |
| 73 | + }, |
| 74 | + json: (payload: any, status?: number) => ({ payload, status: status ?? 200 }), |
| 75 | + }; |
| 76 | +} |
| 77 | + |
| 78 | +let dir: string; |
| 79 | +const ORIGINAL_STAMP = process.env.OS_RUNTIME_VERSION; |
| 80 | +beforeEach(() => { |
| 81 | + dir = mkdtempSync(join(tmpdir(), 'cc-runtime-version-')); |
| 82 | + delete process.env.OS_RUNTIME_VERSION; |
| 83 | +}); |
| 84 | +afterEach(() => { |
| 85 | + rmSync(dir, { recursive: true, force: true }); |
| 86 | + if (ORIGINAL_STAMP === undefined) delete process.env.OS_RUNTIME_VERSION; |
| 87 | + else process.env.OS_RUNTIME_VERSION = ORIGINAL_STAMP; |
| 88 | + vi.unstubAllGlobals(); |
| 89 | +}); |
| 90 | + |
| 91 | +async function mount(mode: Mode, discovery: Discovery) { |
| 92 | + const routes = new Map<string, Handler>(); |
| 93 | + const rawApp = { |
| 94 | + get: (p: string, h: Handler) => routes.set(`GET ${p}`, h), |
| 95 | + post: (p: string, h: Handler) => routes.set(`POST ${p}`, h), |
| 96 | + }; |
| 97 | + const hooks = new Map<string, any>(); |
| 98 | + const auth = { api: { getSession: async () => ({ user: { id: ADMIN }, session: { id: 'sess_admin' } }) } }; |
| 99 | + const objectql = bindCatalogFromTables({ find: async (object: string) => GRANTS[object] ?? [] }, GRANTS); |
| 100 | + const protocol = discovery === 'real' |
| 101 | + ? discoveryProducer() |
| 102 | + : discovery === 'throws' |
| 103 | + ? { getDiscovery: async () => { throw new Error('discovery unavailable'); } } |
| 104 | + : undefined; |
| 105 | + const envKernelServices: Record<string, unknown> = { auth, objectql }; |
| 106 | + const services: Record<string, unknown> = { |
| 107 | + ...(mode === 'single' |
| 108 | + ? { auth, objectql } |
| 109 | + : { |
| 110 | + 'env-registry': { resolveByHostname: async () => ({ environmentId: 'env-1' }) }, |
| 111 | + 'kernel-manager': { getOrCreate: async () => ({ getServiceAsync: async (name: string) => envKernelServices[name] }) }, |
| 112 | + }), |
| 113 | + ...(protocol ? { protocol } : {}), |
| 114 | + }; |
| 115 | + const ctx = { |
| 116 | + hook: (e: string, h: any) => hooks.set(e, h), |
| 117 | + getService: (name: string) => { |
| 118 | + if (name === 'http-server') return { getRawApp: () => rawApp }; |
| 119 | + if (name in services) return services[name]; |
| 120 | + throw new Error(`service ${name} not registered`); |
| 121 | + }, |
| 122 | + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, |
| 123 | + }; |
| 124 | + // The stand-in control plane: a device code with both approval links, a |
| 125 | + // granted token, and a `/bind` that records the claim it was sent. |
| 126 | + const bindBodies: any[] = []; |
| 127 | + vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => { |
| 128 | + const path = new URL(String(url)).pathname; |
| 129 | + let body: unknown = { success: true, data: {} }; |
| 130 | + if (path.endsWith('/device/code')) { |
| 131 | + body = { |
| 132 | + device_code: 'dc_1', user_code: 'ABCD-EFGH', interval: 5, expires_in: 600, |
| 133 | + verification_uri: `${CLOUD}/device`, |
| 134 | + verification_uri_complete: `${CLOUD}/device?user_code=ABCD-EFGH`, |
| 135 | + }; |
| 136 | + } else if (path.endsWith('/device/token')) { |
| 137 | + body = { access_token: 'at_1' }; |
| 138 | + } else if (path.endsWith('/cloud-connection/bind')) { |
| 139 | + bindBodies.push(JSON.parse(String(init?.body))); |
| 140 | + body = { success: true, data: { runtime_token: 'oscc_new', runtime_id: 'rt_1', connection: { runtime_id: 'rt_1' } } }; |
| 141 | + } |
| 142 | + return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); |
| 143 | + })); |
| 144 | + const plugin = new CloudConnectionPlugin({ |
| 145 | + controlPlaneUrl: CLOUD, |
| 146 | + credentialPath: join(dir, 'cloud-connection.json'), |
| 147 | + ...(mode === 'single' ? { singleEnvironment: true, environmentId: 'env-1' } : {}), |
| 148 | + }); |
| 149 | + await plugin.start(ctx as any); |
| 150 | + await hooks.get('kernel:ready')?.(); |
| 151 | + |
| 152 | + /** `runtime_version` on each approval link `bind/start` answered with (`null` = no such parameter). */ |
| 153 | + const approvalLinkVersions = async () => { |
| 154 | + const res = await routes.get(`POST ${CC}/bind/start`)!(makeC(`${CC}/bind/start`)); |
| 155 | + expect(res.status, JSON.stringify(res.payload)).toBe(200); |
| 156 | + const { verification_uri, verification_uri_complete } = res.payload.data; |
| 157 | + return [verification_uri, verification_uri_complete].map((uri: string) => new URL(uri).searchParams.get('runtime_version')); |
| 158 | + }; |
| 159 | + /** The registration claim `bind/poll` sent the control plane's `/bind`. */ |
| 160 | + const bindClaim = async () => { |
| 161 | + const res = await routes.get(`POST ${CC}/bind/poll`)!(makeC(`${CC}/bind/poll`, { device_code: 'dc_1' })); |
| 162 | + expect(res.status, JSON.stringify(res.payload)).toBe(200); |
| 163 | + expect(bindBodies, 'the control plane received exactly one bind').toHaveLength(1); |
| 164 | + return bindBodies[0]; |
| 165 | + }; |
| 166 | + return { plugin, approvalLinkVersions, bindClaim }; |
| 167 | +} |
| 168 | + |
| 169 | +for (const mode of ['single', 'multi'] as const) { |
| 170 | + describe(`[#24150] runtime_version is the release discovery reports (${mode}-environment)`, () => { |
| 171 | + it('OS_RUNTIME_VERSION unset: both approval links carry the discovery release', async () => { |
| 172 | + const { plugin, approvalLinkVersions } = await mount(mode, 'real'); |
| 173 | + const release = await discoveryRelease(); |
| 174 | + // Not vacuous: discovery reports a real release, and it is not the |
| 175 | + // plugin's own version field (which the defect sent instead). |
| 176 | + expect(typeof release === 'string' && release.length > 0, String(release)).toBe(true); |
| 177 | + expect(release).not.toBe(plugin.version); |
| 178 | + |
| 179 | + expect(await approvalLinkVersions()).toEqual([release, release]); |
| 180 | + }); |
| 181 | + |
| 182 | + it('OS_RUNTIME_VERSION unset: the bind claim sent to the control plane carries the discovery release', async () => { |
| 183 | + const { bindClaim } = await mount(mode, 'real'); |
| 184 | + const release = await discoveryRelease(); |
| 185 | + |
| 186 | + expect((await bindClaim()).runtime_version).toBe(release); |
| 187 | + }); |
| 188 | + |
| 189 | + for (const discovery of ['real', 'none'] as const) { |
| 190 | + it(`CONTROL: a set OS_RUNTIME_VERSION is sent verbatim at both sites (discovery producer: ${discovery})`, async () => { |
| 191 | + const stamp = `stamp-24150-${mode}-${discovery}-not-a-release`; |
| 192 | + process.env.OS_RUNTIME_VERSION = stamp; |
| 193 | + const { approvalLinkVersions, bindClaim } = await mount(mode, discovery); |
| 194 | + |
| 195 | + expect(await approvalLinkVersions()).toEqual([stamp, stamp]); |
| 196 | + expect((await bindClaim()).runtime_version).toBe(stamp); |
| 197 | + }); |
| 198 | + } |
| 199 | + |
| 200 | + for (const discovery of ['none', 'throws'] as const) { |
| 201 | + it(`no discovery read (${discovery === 'none' ? 'no protocol service' : 'the read throws'}): neither site sends a version`, async () => { |
| 202 | + const { approvalLinkVersions, bindClaim } = await mount(mode, discovery); |
| 203 | + |
| 204 | + expect(await approvalLinkVersions()).toEqual([null, null]); |
| 205 | + const claim = await bindClaim(); |
| 206 | + expect('runtime_version' in claim, JSON.stringify(claim)).toBe(false); |
| 207 | + }); |
| 208 | + } |
| 209 | + }); |
| 210 | +} |
0 commit comments