|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// #17647 — the BOTH-HALVES WIRE pin for Connect-an-Agent visibility. |
| 4 | +// |
| 5 | +// --------------------------------------------------------------------------- |
| 6 | +// What this pins, and why one half of it would be worthless |
| 7 | +// --------------------------------------------------------------------------- |
| 8 | +// #16746's ruling (option A) promises two facts at once, and they are only a |
| 9 | +// promise TOGETHER: |
| 10 | +// |
| 11 | +// 1. a PERMISSIONLESS principal gets `200` on `GET /api/v1/meta/apps/account` |
| 12 | +// with `nav_connect_agent` present in `grp_account_developer`; and |
| 13 | +// 2. that SAME principal still gets `403` / `PERMISSION_DENIED` on |
| 14 | +// `GET /api/v1/meta/apps/setup`, with `connect_agent` absent from the body. |
| 15 | +// |
| 16 | +// A test asserting only (1) would stay green if someone ungated Setup — which |
| 17 | +// is not hypothetical: #16746's own history produced exactly that once, and |
| 18 | +// dropping Setup's two gates was measured to expose 14+ unrelated Setup |
| 19 | +// surfaces (Packages, Users, Organization, Business Units, Teams, Invitations, |
| 20 | +// Localization, Company, Branding, Feature Flags and their groups) to every |
| 21 | +// signed-in user. The PAIRING is the pin. |
| 22 | +// |
| 23 | +// --------------------------------------------------------------------------- |
| 24 | +// Why the positive control is not optional |
| 25 | +// --------------------------------------------------------------------------- |
| 26 | +// A `403` with no LIT control proves the harness ran exactly as much as it |
| 27 | +// proves the gate held — which is to say, neither. So the permitted principal's |
| 28 | +// reading sits in the same `it()` as the refusal: if the fold or the fixture |
| 29 | +// ever stops reaching the Connect-an-Agent card at all, the control goes red |
| 30 | +// instead of the refusal going quietly vacuous. |
| 31 | +// |
| 32 | +// --------------------------------------------------------------------------- |
| 33 | +// It lives in `packages/cli/test/` on purpose |
| 34 | +// --------------------------------------------------------------------------- |
| 35 | +// This is a COMPOSED fact: the real `SETUP_APP` / `ACCOUNT_APP` / |
| 36 | +// `SETUP_NAV_CONTRIBUTIONS` (`@objectstack/platform-objects`), the real |
| 37 | +// `CONNECT_AGENT_UI_BUNDLE` (`@objectstack/mcp`), the real `SchemaRegistry` |
| 38 | +// fold (`@objectstack/objectql`) and the real per-request RBAC-by-route filter |
| 39 | +// (`@objectstack/rest`). Read from `package.json`, `packages/cli` is the only |
| 40 | +// workspace package that depends on all four at once — the same argument |
| 41 | +// `packages/cli/scripts/check-app-nav-i18n.mjs` already makes in its own |
| 42 | +// header for living here ("`cli` is the composition root … a gate in |
| 43 | +// `platform-objects` could not import the plugins"). |
| 44 | +// |
| 45 | +// ⛔ It is NOT beside the change in `packages/mcp`: that package declares no |
| 46 | +// dependency on `@objectstack/rest`, `@objectstack/objectql` or |
| 47 | +// `@objectstack/platform-objects`, and reimplementing the fold or the RBAC |
| 48 | +// filter there to keep the test local is precisely the divergence |
| 49 | +// `packages/cli/src/utils/nav-contribution-groups.ts` exists to refuse. |
| 50 | +// |
| 51 | +// --------------------------------------------------------------------------- |
| 52 | +// The harness is the established one |
| 53 | +// --------------------------------------------------------------------------- |
| 54 | +// Stub-the-exec-context, from `packages/rest/src/meta-app-publish-gate.test.ts` |
| 55 | +// and `meta-app-area-nav-gate.test.ts`: a real `RestServer` over a stubbed |
| 56 | +// protocol, `resolveExecCtx` replaced by a caller carrying a given |
| 57 | +// `systemPermissions` set, driven through the registered |
| 58 | +// `GET /api/v1/meta/:type/:name` route. Nothing about the gate is re-expressed |
| 59 | +// here — the assertions read the RESPONSE BODY, which is the only surface the |
| 60 | +// console and an AI client ever see. |
| 61 | +// |
| 62 | +// ⚠️ The two `requiresService` / `requiresObject` gates are deliberately NOT |
| 63 | +// exercised: the stubbed context carries no `__kernel` and no service provider, |
| 64 | +// so ADR-0057 D10's capability probe fails OPEN exactly as it does in the two |
| 65 | +// sibling harnesses. Permission gating is what is under test. |
| 66 | + |
| 67 | +import { describe, expect, it, vi } from 'vitest'; |
| 68 | +import { CONNECT_AGENT_UI_BUNDLE } from '@objectstack/mcp'; |
| 69 | +import { SchemaRegistry } from '@objectstack/objectql'; |
| 70 | +import { ACCOUNT_APP, SETUP_APP, SETUP_NAV_CONTRIBUTIONS } from '@objectstack/platform-objects/apps'; |
| 71 | +import { RestServer } from '@objectstack/rest'; |
| 72 | + |
| 73 | +type AnyRec = Record<string, any>; |
| 74 | + |
| 75 | +/** The two nav-contribution halves the MCP bundle ships, read by target app. */ |
| 76 | +const bundleContributions = (): AnyRec[] => |
| 77 | + (CONNECT_AGENT_UI_BUNDLE as AnyRec).navigationContributions as AnyRec[]; |
| 78 | + |
| 79 | +/** |
| 80 | + * Build the real composition. |
| 81 | + * |
| 82 | + * `structuredClone` on the two apps is deliberate and changes no content: |
| 83 | + * `registerItem` runs `applyProtection` on what it is handed, which WRITES the |
| 84 | + * `_lock` envelope onto the object (ADR-0010 §3.7). Handing it the imported |
| 85 | + * module constants would mutate them for every other file in this suite. |
| 86 | + * |
| 87 | + * @param includeAccountHalf when false, only the MCP bundle's `app: 'setup'` |
| 88 | + * contribution is folded — the counterfactual M4 reads Setup against. |
| 89 | + */ |
| 90 | +function composedRegistry(includeAccountHalf = true): SchemaRegistry { |
| 91 | + const registry = new SchemaRegistry({ multiTenant: false, collisionPolicy: 'error' }); |
| 92 | + // The fold's own diagnostics are not under test here; keep the run quiet. |
| 93 | + (registry as AnyRec).logLevel = 'silent'; |
| 94 | + |
| 95 | + registry.registerApp(structuredClone(SETUP_APP), '@objectstack/platform-objects'); |
| 96 | + registry.registerApp(structuredClone(ACCOUNT_APP), '@objectstack/platform-objects'); |
| 97 | + |
| 98 | + for (const contribution of SETUP_NAV_CONTRIBUTIONS) { |
| 99 | + registry.registerAppNavContribution(contribution as any, '@objectstack/platform-objects'); |
| 100 | + } |
| 101 | + for (const contribution of bundleContributions()) { |
| 102 | + if (!includeAccountHalf && contribution.app !== 'setup') continue; |
| 103 | + registry.registerAppNavContribution(contribution as any, '@objectstack/mcp'); |
| 104 | + } |
| 105 | + return registry; |
| 106 | +} |
| 107 | + |
| 108 | +function createMockServer() { |
| 109 | + return { |
| 110 | + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), use: vi.fn(), |
| 111 | + listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), |
| 112 | + }; |
| 113 | +} |
| 114 | + |
| 115 | +function makeRes() { |
| 116 | + const res: AnyRec = { statusCode: 200, body: undefined }; |
| 117 | + res.status = vi.fn((c: number) => { res.statusCode = c; return res; }); |
| 118 | + res.json = vi.fn((b: unknown) => { res.body = b; return res; }); |
| 119 | + res.header = vi.fn(); res.setHeader = vi.fn(); res.write = vi.fn(); res.end = vi.fn(); |
| 120 | + return res; |
| 121 | +} |
| 122 | + |
| 123 | +/** |
| 124 | + * A `RestServer` serving the composed apps to a caller holding `perms`. |
| 125 | + * |
| 126 | + * The protocol answers `getMetaItem` out of the registry, so the bytes under |
| 127 | + * test have gone through `applyNavContributions` — the real fold — exactly as |
| 128 | + * the serving path does (ADR-0029 D7: "the REST app endpoints read through the |
| 129 | + * protocol, not these helpers, so the merge must be reachable from there too"). |
| 130 | + */ |
| 131 | +function setup(perms: string[], includeAccountHalf = true) { |
| 132 | + const registry = composedRegistry(includeAccountHalf); |
| 133 | + const protocol: AnyRec = { |
| 134 | + getDiscovery: vi.fn().mockResolvedValue({ |
| 135 | + version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' }, |
| 136 | + }), |
| 137 | + getMetaTypes: vi.fn().mockResolvedValue([]), |
| 138 | + getMetaItems: vi.fn(async ({ type }: AnyRec) => { |
| 139 | + const t = String(type ?? ''); |
| 140 | + return t === 'app' || t === 'apps' ? registry.getAllApps() : []; |
| 141 | + }), |
| 142 | + getMetaItem: vi.fn(async ({ name }: AnyRec) => { |
| 143 | + const item = registry.getApp(String(name)); |
| 144 | + return item ? { type: 'app', name, item } : undefined; |
| 145 | + }), |
| 146 | + findData: vi.fn().mockResolvedValue([]), |
| 147 | + }; |
| 148 | + const rest: AnyRec = new RestServer( |
| 149 | + createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any, |
| 150 | + ); |
| 151 | + // The RBAC filter only runs for a RESOLVED caller; stubbing the exec |
| 152 | + // context is this repo's established pattern for exercising it by route. |
| 153 | + rest.resolveExecCtx = async () => ({ userId: 'u1', systemPermissions: perms }); |
| 154 | + rest.registerRoutes(); |
| 155 | + return rest; |
| 156 | +} |
| 157 | + |
| 158 | +/** `GET /api/v1/meta/apps/:name`, answered as `{ statusCode, body }`. */ |
| 159 | +async function getApp(rest: AnyRec, name: string) { |
| 160 | + const route = rest.getRoutes().find( |
| 161 | + (r: AnyRec) => r.method === 'GET' && r.path === '/api/v1/meta/:type/:name', |
| 162 | + ); |
| 163 | + if (!route) throw new Error('meta/:type/:name route not registered'); |
| 164 | + const res = makeRes(); |
| 165 | + await route.handler( |
| 166 | + { method: 'GET', params: { type: 'apps', name }, query: {}, body: {}, headers: {} }, res, |
| 167 | + ); |
| 168 | + return res; |
| 169 | +} |
| 170 | + |
| 171 | +/** Every nav id in the served document, groups included, depth-first. */ |
| 172 | +function navIds(app: AnyRec | undefined): string[] { |
| 173 | + const out: string[] = []; |
| 174 | + const walk = (items: AnyRec[] | undefined) => { |
| 175 | + for (const item of items ?? []) { |
| 176 | + if (item?.id) out.push(String(item.id)); |
| 177 | + if (Array.isArray(item?.children)) walk(item.children); |
| 178 | + } |
| 179 | + }; |
| 180 | + walk(app?.navigation); |
| 181 | + for (const area of app?.areas ?? []) walk(area?.navigation); |
| 182 | + return out; |
| 183 | +} |
| 184 | + |
| 185 | +/** The children of one nav group, by id. */ |
| 186 | +function groupChildren(app: AnyRec | undefined, groupId: string): string[] { |
| 187 | + let found: AnyRec | undefined; |
| 188 | + const walk = (items: AnyRec[] | undefined) => { |
| 189 | + for (const item of items ?? []) { |
| 190 | + if (item?.id === groupId) { found = item; return; } |
| 191 | + if (Array.isArray(item?.children)) walk(item.children); |
| 192 | + if (found) return; |
| 193 | + } |
| 194 | + }; |
| 195 | + walk(app?.navigation); |
| 196 | + return (found?.children ?? []).map((c: AnyRec) => String(c?.id)); |
| 197 | +} |
| 198 | + |
| 199 | +/** The declared ADR-0112 refusal envelope, as the console reads it. */ |
| 200 | +const refusal = (body: AnyRec | undefined) => ({ |
| 201 | + code: body?.error?.code, message: body?.error?.message, |
| 202 | +}); |
| 203 | + |
| 204 | +describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', () => { |
| 205 | + it('a permissionless principal sees the Account entry AND is still refused Setup', async () => { |
| 206 | + // ONE principal, two routes — the pairing is the pin, so both readings |
| 207 | + // and the lit control are asserted here rather than in three `it()`s |
| 208 | + // that could pass one at a time. |
| 209 | + const rest = setup([]); |
| 210 | + |
| 211 | + // ── M1 — permissionless on `GET /api/v1/meta/apps/account` ───────── |
| 212 | + const account = await getApp(rest, 'account'); |
| 213 | + expect(account.statusCode).toBe(200); |
| 214 | + expect(account.body).toMatchObject({ type: 'app', name: 'account' }); |
| 215 | + |
| 216 | + // `ACCOUNT_APP` declares no `requiredPermissions` — deliberately, so |
| 217 | + // every authenticated user reaches their own security surface — and the |
| 218 | + // fold puts the contributed entry inside the group that already carries |
| 219 | + // `nav_account_api_keys`. |
| 220 | + expect(groupChildren(account.body?.item, 'grp_account_developer')) |
| 221 | + .toEqual(['nav_account_api_keys', 'nav_account_oauth_apps', 'nav_connect_agent']); |
| 222 | + // The whole served tree, counted: 11 authored ids + the one contributed. |
| 223 | + expect(navIds(account.body?.item)).toHaveLength(12); |
| 224 | + // …and the entry's TARGET rode along, so the menu item resolves. |
| 225 | + expect(JSON.stringify(account.body)).toContain('connect_agent'); |
| 226 | + |
| 227 | + // ── M2 — the SAME principal on `GET /api/v1/meta/apps/setup` ─────── |
| 228 | + const setupDenied = await getApp(rest, 'setup'); |
| 229 | + expect(setupDenied.statusCode).toBe(403); |
| 230 | + // ⛔ The status alone is not the assertion: a bare 403 cannot tell a |
| 231 | + // permission refusal from a route that was never reached. ADR-0112's |
| 232 | + // STANDARD catalog member for an authorization refusal, nested inside |
| 233 | + // `error` per `BaseResponseSchema`, is what objectui branches on. |
| 234 | + expect(refusal(setupDenied.body).code).toBe('PERMISSION_DENIED'); |
| 235 | + expect(setupDenied.body?.success).toBe(false); |
| 236 | + expect(typeof refusal(setupDenied.body).message).toBe('string'); |
| 237 | + |
| 238 | + // Refused means refused, judged on the WIRE BYTES rather than on "not |
| 239 | + // in the nav group": neither the page name nor the nav id leaked. |
| 240 | + const deniedWire = JSON.stringify(setupDenied.body ?? {}); |
| 241 | + expect(deniedWire).not.toContain('connect_agent'); |
| 242 | + expect(setupDenied.body?.item).toBeUndefined(); |
| 243 | + |
| 244 | + // ── M3 — the LIT positive control, same composition ──────────────── |
| 245 | + // Without this, M2's 403 proves the gate held exactly as much as it |
| 246 | + // proves the harness never reached the card. |
| 247 | + const permitted = setup(['setup.access', 'manage_platform_settings']); |
| 248 | + const setupAllowed = await getApp(permitted, 'setup'); |
| 249 | + expect(setupAllowed.statusCode).toBe(200); |
| 250 | + expect(setupAllowed.body?.error).toBeUndefined(); |
| 251 | + const allowedIds = navIds(setupAllowed.body?.item); |
| 252 | + expect(allowedIds).toContain('nav_connect_agent'); |
| 253 | + expect(groupChildren(setupAllowed.body?.item, 'group_integrations')) |
| 254 | + .toContain('nav_connect_agent'); |
| 255 | + // The Setup tree the platform admin is served: 9 authored groups less |
| 256 | + // `group_approvals`, which nothing contributes into and the filter |
| 257 | + // collapses, plus 25 contributed entries plus the MCP one. |
| 258 | + expect(allowedIds).toHaveLength(34); |
| 259 | + }); |
| 260 | + |
| 261 | + it('the Account half widened NOTHING on Setup — the admin tree is unchanged', async () => { |
| 262 | + // ── M4 — anti-widening control ───────────────────────────────────── |
| 263 | + // `SETUP_APP.requiredPermissions = ['setup.access']` has no pin of its |
| 264 | + // own anywhere in `packages/platform-objects`; this reading covers that |
| 265 | + // the gate is still DECLARED, and that adding the per-user half moved |
| 266 | + // nothing on the admin side. The counterfactual folds only the bundle's |
| 267 | + // `app: 'setup'` contribution. |
| 268 | + const withAccountHalf = await getApp(setup(['setup.access', 'manage_platform_settings']), 'setup'); |
| 269 | + const withoutAccountHalf = await getApp( |
| 270 | + setup(['setup.access', 'manage_platform_settings'], false), 'setup', |
| 271 | + ); |
| 272 | + |
| 273 | + expect(withAccountHalf.statusCode).toBe(200); |
| 274 | + expect(withoutAccountHalf.statusCode).toBe(200); |
| 275 | + expect(navIds(withAccountHalf.body?.item)).toEqual(navIds(withoutAccountHalf.body?.item)); |
| 276 | + expect(navIds(withAccountHalf.body?.item)).toHaveLength(34); |
| 277 | + |
| 278 | + // The mechanism behind the invariance, asserted rather than assumed: |
| 279 | + // the bundle aims exactly one contribution at `setup` and one at |
| 280 | + // `account`, and the registry keys contributions by TARGET APP. |
| 281 | + expect(bundleContributions().map((c) => c.app)).toEqual(['setup', 'account']); |
| 282 | + }); |
| 283 | +}); |
0 commit comments