|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * ConnectionCredentialStore + the plugin's credential behavior |
| 5 | + * (cloud ADR-0008 consumption side): |
| 6 | + * - store round-trip / clear / corrupt tolerance / 0600 mode |
| 7 | + * - bind/poll persists the one-time runtime_token and STRIPS it from |
| 8 | + * the browser-facing response |
| 9 | + * - forwards fall back to the stored bearer when no service key is set |
| 10 | + * - unbind revokes (best-effort) and clears the local credential |
| 11 | + */ |
| 12 | + |
| 13 | +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; |
| 14 | +import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'; |
| 15 | +import { join } from 'node:path'; |
| 16 | +import { tmpdir } from 'node:os'; |
| 17 | +import { ConnectionCredentialStore } from './connection-credential-store.js'; |
| 18 | +import { CloudConnectionPlugin } from './cloud-connection-plugin.js'; |
| 19 | + |
| 20 | +let dir: string; |
| 21 | +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'ccs-')); }); |
| 22 | +afterEach(() => { rmSync(dir, { recursive: true, force: true }); vi.unstubAllGlobals(); }); |
| 23 | + |
| 24 | +const CRED = { runtimeToken: 'oscc_abc', environmentId: 'env_1', controlPlaneUrl: 'http://cloud.test' }; |
| 25 | + |
| 26 | +describe('ConnectionCredentialStore', () => { |
| 27 | + it('round-trips, clears, and tolerates corrupt files', () => { |
| 28 | + const store = new ConnectionCredentialStore(join(dir, 'cc.json')); |
| 29 | + expect(store.read()).toBeNull(); |
| 30 | + store.write(CRED); |
| 31 | + expect(store.read()?.runtimeToken).toBe('oscc_abc'); |
| 32 | + expect(store.clear()).toBe(true); |
| 33 | + expect(store.clear()).toBe(false); |
| 34 | + |
| 35 | + writeFileSync(store.path, '{nope', 'utf8'); |
| 36 | + expect(store.read()).toBeNull(); |
| 37 | + }); |
| 38 | + |
| 39 | + it('writes the secret 0600', () => { |
| 40 | + const store = new ConnectionCredentialStore(join(dir, 'cc.json')); |
| 41 | + store.write(CRED); |
| 42 | + const mode = statSync(store.path).mode & 0o777; |
| 43 | + expect(mode).toBe(0o600); |
| 44 | + }); |
| 45 | +}); |
| 46 | + |
| 47 | +// ── plugin harness ────────────────────────────────────────────────────── |
| 48 | +type Handler = (c: any) => Promise<any>; |
| 49 | +function makeRawApp() { |
| 50 | + const routes = new Map<string, Handler>(); |
| 51 | + return { |
| 52 | + routes, |
| 53 | + get: (p: string, h: Handler) => routes.set(`GET ${p}`, h), |
| 54 | + post: (p: string, h: Handler) => routes.set(`POST ${p}`, h), |
| 55 | + }; |
| 56 | +} |
| 57 | +const sessionAuth = (userId?: string) => ({ api: { getSession: async () => (userId ? { user: { id: userId } } : null) } }); |
| 58 | +function makeCtx(rawApp: any, services: Record<string, any> = {}) { |
| 59 | + const hooks = new Map<string, any>(); |
| 60 | + return { |
| 61 | + ctx: { |
| 62 | + hook: (e: string, h: any) => hooks.set(e, h), |
| 63 | + getService: (name: string) => { |
| 64 | + if (name === 'http-server') return { getRawApp: () => rawApp }; |
| 65 | + const svc = services[name]; |
| 66 | + if (svc === undefined) throw new Error(`no ${name}`); |
| 67 | + return svc; |
| 68 | + }, |
| 69 | + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, |
| 70 | + }, |
| 71 | + fire: async () => { await hooks.get('kernel:ready')?.(); }, |
| 72 | + }; |
| 73 | +} |
| 74 | +function makeC(url: string, body?: any) { |
| 75 | + const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })); |
| 76 | + return { req: { url, raw: new Request(url), json: async () => body ?? {} }, json }; |
| 77 | +} |
| 78 | + |
| 79 | +describe('CloudConnectionPlugin credential behavior', () => { |
| 80 | + it('bind/poll persists runtime_token to the store and strips it from the response', async () => { |
| 81 | + const credPath = join(dir, 'cc.json'); |
| 82 | + const rawApp = makeRawApp(); |
| 83 | + const { ctx, fire } = makeCtx(rawApp, { auth: sessionAuth('admin'), manifest: { register: vi.fn() } }); |
| 84 | + vi.stubGlobal('fetch', vi.fn(async (url: any) => { |
| 85 | + const u = String(url); |
| 86 | + if (u.includes('/auth/device/token')) { |
| 87 | + return new Response(JSON.stringify({ access_token: 'op-token' }), { status: 200 }); |
| 88 | + } |
| 89 | + if (u.includes('/cloud-connection/bind')) { |
| 90 | + return new Response(JSON.stringify({ success: true, data: { bound: true, connection: { organization_id: 'org_x' }, runtime_token: 'oscc_minted' } }), { status: 200 }); |
| 91 | + } |
| 92 | + throw new Error(`unexpected fetch ${u}`); |
| 93 | + })); |
| 94 | + await new CloudConnectionPlugin({ |
| 95 | + singleEnvironment: true, environmentId: 'env_1', |
| 96 | + controlPlaneUrl: 'http://cloud.test', credentialPath: credPath, |
| 97 | + }).start(ctx as any); |
| 98 | + await fire(); |
| 99 | + |
| 100 | + const res = await rawApp.routes.get('POST /api/v1/cloud-connection/bind/poll')!( |
| 101 | + makeC('http://localhost:3000/x', { device_code: 'dc' }), |
| 102 | + ); |
| 103 | + expect(res.payload.success).toBe(true); |
| 104 | + expect(JSON.stringify(res.payload)).not.toContain('oscc_minted'); |
| 105 | + const stored = new ConnectionCredentialStore(credPath).read(); |
| 106 | + expect(stored?.runtimeToken).toBe('oscc_minted'); |
| 107 | + expect(stored?.environmentId).toBe('env_1'); |
| 108 | + }); |
| 109 | + |
| 110 | + it('forwards use the stored bearer when no service key is configured', async () => { |
| 111 | + const credPath = join(dir, 'cc.json'); |
| 112 | + new ConnectionCredentialStore(credPath).write({ runtimeToken: 'oscc_stored', environmentId: 'env_1' }); |
| 113 | + const rawApp = makeRawApp(); |
| 114 | + const { ctx, fire } = makeCtx(rawApp, { auth: sessionAuth('admin'), manifest: { register: vi.fn() } }); |
| 115 | + const fetchSpy = vi.fn(async () => new Response(JSON.stringify({ success: true, data: { items: [] } }), { status: 200 })); |
| 116 | + vi.stubGlobal('fetch', fetchSpy); |
| 117 | + await new CloudConnectionPlugin({ |
| 118 | + singleEnvironment: true, controlPlaneUrl: 'http://cloud.test', controlPlaneApiKey: '', credentialPath: credPath, |
| 119 | + }).start(ctx as any); |
| 120 | + await fire(); |
| 121 | + |
| 122 | + // env id resolves from the STORE (no OS_ENVIRONMENT_ID, no config id). |
| 123 | + const res = await rawApp.routes.get('GET /api/v1/cloud-connection/org-packages')!( |
| 124 | + makeC('http://localhost:3000/api/v1/cloud-connection/org-packages'), |
| 125 | + ); |
| 126 | + expect(res.payload.success).toBe(true); |
| 127 | + const [, init] = fetchSpy.mock.calls[0]!; |
| 128 | + expect((init as any).headers.Authorization).toBe('Bearer oscc_stored'); |
| 129 | + }); |
| 130 | + |
| 131 | + it('unbind revokes against the control plane and clears the local credential', async () => { |
| 132 | + const credPath = join(dir, 'cc.json'); |
| 133 | + const store = new ConnectionCredentialStore(credPath); |
| 134 | + store.write({ runtimeToken: 'oscc_stored', environmentId: 'env_1' }); |
| 135 | + const rawApp = makeRawApp(); |
| 136 | + const { ctx, fire } = makeCtx(rawApp, { auth: sessionAuth('admin'), manifest: { register: vi.fn() } }); |
| 137 | + const fetchSpy = vi.fn(async () => new Response(JSON.stringify({ success: true }), { status: 200 })); |
| 138 | + vi.stubGlobal('fetch', fetchSpy); |
| 139 | + await new CloudConnectionPlugin({ |
| 140 | + singleEnvironment: true, controlPlaneUrl: 'http://cloud.test', controlPlaneApiKey: '', credentialPath: credPath, |
| 141 | + }).start(ctx as any); |
| 142 | + await fire(); |
| 143 | + |
| 144 | + const res = await rawApp.routes.get('POST /api/v1/cloud-connection/unbind')!( |
| 145 | + makeC('http://localhost:3000/x'), |
| 146 | + ); |
| 147 | + expect(res.payload.data).toEqual({ environmentId: 'env_1', revoked: true, cleared: true }); |
| 148 | + expect(String(fetchSpy.mock.calls[0]![0])).toContain('/cloud-connection/revoke'); |
| 149 | + expect((fetchSpy.mock.calls[0]![1] as any).headers.Authorization).toBe('Bearer oscc_stored'); |
| 150 | + expect(store.read()).toBeNull(); |
| 151 | + }); |
| 152 | + |
| 153 | + it('registers the SDUI bundle (page + nav) with the manifest service', async () => { |
| 154 | + const register = vi.fn(); |
| 155 | + const rawApp = makeRawApp(); |
| 156 | + const { ctx, fire } = makeCtx(rawApp, { manifest: { register } }); |
| 157 | + await new CloudConnectionPlugin({ singleEnvironment: true, controlPlaneUrl: 'http://cloud.test', credentialPath: join(dir, 'cc.json') }).start(ctx as any); |
| 158 | + await fire(); |
| 159 | + expect(register).toHaveBeenCalledWith(expect.objectContaining({ |
| 160 | + id: 'com.objectstack.cloud-connection.ui', |
| 161 | + pages: [expect.objectContaining({ name: 'cloud_connection_settings' })], |
| 162 | + navigationContributions: [expect.objectContaining({ app: 'setup' })], |
| 163 | + })); |
| 164 | + }); |
| 165 | +}); |
0 commit comments