|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * #5519 — the `/actions` and `/automation` anonymous baseline, through a REAL |
| 5 | + * boot and over a REAL socket. |
| 6 | + * |
| 7 | + * `domains/anonymous-gate-actions-automation.test.ts` pins the DECISION (which |
| 8 | + * caller the handler denies, and that nothing dispatches behind it). This file |
| 9 | + * pins the WIRING, and the distinction is the whole reason it exists: the gate |
| 10 | + * lives in the domain handler, but the routes are mounted by |
| 11 | + * `dispatcher-plugin.ts` straight onto the host `IHttpServer` — a separate |
| 12 | + * registration path from the one `@objectstack/rest` uses for `/data`, and |
| 13 | + * precisely the seam whose divergence #5519 is about. A unit test that calls |
| 14 | + * `handleActions()` directly cannot tell you that the MOUNTED route reaches the |
| 15 | + * gated handler; only a socket can. AGENTS.md states the rule flatly: "who |
| 16 | + * serves this path" is a question about the composed, provisioned runtime — |
| 17 | + * boot it or do not claim an answer. #3913 is the standing proof, where |
| 18 | + * `POST /actions//:action` was correct in the domain and unreachable on the |
| 19 | + * wire for exactly this reason. |
| 20 | + * |
| 21 | + * The pre-fix behaviour these replace, measured on a real showcase boot: |
| 22 | + * POST /actions/showcase_task/showcase_mark_done/:id → 200 {ok:true} |
| 23 | + * POST /automation/showcase_reassign_wizard/trigger → 200 {runId: run_…} |
| 24 | + * GET /automation → 200 (full inventory) |
| 25 | + * DELETE /automation/showcase_inquiry_janitor → 200 {deleted:true} |
| 26 | + * …all with no credential of any kind, while `/data` on the same process |
| 27 | + * answered 401. |
| 28 | + */ |
| 29 | + |
| 30 | +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; |
| 31 | +import { LiteKernel, Plugin, PluginContext } from '@objectstack/core'; |
| 32 | +import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; |
| 33 | +import type { IHttpServer } from '@objectstack/spec/contracts'; |
| 34 | + |
| 35 | +import { createDispatcherPlugin } from './dispatcher-plugin.js'; |
| 36 | + |
| 37 | +const SESSION_HEADER = 'x-test-session'; |
| 38 | + |
| 39 | +const executeAction = vi.fn(async () => ({ ok: true, wrote: 'system-elevated' })); |
| 40 | +const automationExecute = vi.fn(async () => ({ success: true, status: 'paused', runId: 'run_1' })); |
| 41 | +const unregisterFlow = vi.fn(); |
| 42 | +const listFlows = vi.fn(async () => ['crm_escalation_flow']); |
| 43 | + |
| 44 | +/** One `script` action, declared on the object and carrying NO `requiredPermissions`. */ |
| 45 | +const scriptAction = { |
| 46 | + name: 'mark_primary', |
| 47 | + objectName: 'crm_contact', |
| 48 | + type: 'script', |
| 49 | + body: { language: 'js', source: 'return { ok: true };', capabilities: ['api.write'] }, |
| 50 | +}; |
| 51 | +const objectDef = { name: 'crm_contact', actions: [scriptAction] }; |
| 52 | + |
| 53 | +/** |
| 54 | + * `auth` slot in the shape `resolveExecutionContext` actually reads |
| 55 | + * (`authService.api.getSession({ headers })`). It answers a session only when |
| 56 | + * the request carries `x-test-session`, so ONE boot serves both the anonymous |
| 57 | + * and the authenticated case and the difference on the wire is a header — |
| 58 | + * which is exactly the difference the gate is supposed to key off. |
| 59 | + */ |
| 60 | +function servicesPlugin(): Plugin { |
| 61 | + return { |
| 62 | + name: 'com.objectstack.test.services-5519', |
| 63 | + version: '1.0.0', |
| 64 | + init: async (ctx: PluginContext) => { |
| 65 | + ctx.registerService('objectql', { |
| 66 | + executeAction, |
| 67 | + getSchema: (n: string) => (n === objectDef.name ? objectDef : undefined), |
| 68 | + registry: { getObject: (n: string) => (n === objectDef.name ? objectDef : undefined), getItem: () => undefined }, |
| 69 | + find: async () => [], |
| 70 | + insert: async () => ({}), update: async () => ({}), delete: async () => ({}), |
| 71 | + }); |
| 72 | + ctx.registerService('automation', { |
| 73 | + execute: automationExecute, |
| 74 | + unregisterFlow, |
| 75 | + listFlows, |
| 76 | + registerFlow: () => { /* unused */ }, |
| 77 | + handlerReady: true, |
| 78 | + }); |
| 79 | + ctx.registerService('auth', { |
| 80 | + api: { |
| 81 | + getSession: async ({ headers }: any) => |
| 82 | + (headers?.get?.(SESSION_HEADER) ? { user: { id: 'u_socket' } } : undefined), |
| 83 | + }, |
| 84 | + }); |
| 85 | + }, |
| 86 | + }; |
| 87 | +} |
| 88 | + |
| 89 | +async function boot() { |
| 90 | + const kernel = new LiteKernel(); |
| 91 | + kernel.use(new HonoServerPlugin({ port: 0, cors: false })); |
| 92 | + kernel.use(servicesPlugin()); |
| 93 | + kernel.use(createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false })); |
| 94 | + await kernel.bootstrap(); |
| 95 | + const httpServer = kernel.getService<IHttpServer>('http.server'); |
| 96 | + return { kernel, baseUrl: `http://127.0.0.1:${httpServer.getPort!()}` }; |
| 97 | +} |
| 98 | + |
| 99 | +describe('#5519 — the mounted /actions and /automation routes deny anonymous callers on the wire', () => { |
| 100 | + let kernel: LiteKernel; |
| 101 | + let baseUrl: string; |
| 102 | + |
| 103 | + beforeAll(async () => { ({ kernel, baseUrl } = await boot()); }, 60_000); |
| 104 | + afterAll(async () => { |
| 105 | + await Promise.race([kernel?.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]); |
| 106 | + }, 30_000); |
| 107 | + |
| 108 | + const post = (path: string, body: unknown, session = false) => |
| 109 | + fetch(`${baseUrl}/api/v1${path}`, { |
| 110 | + method: 'POST', |
| 111 | + headers: { 'Content-Type': 'application/json', ...(session ? { [SESSION_HEADER]: '1' } : {}) }, |
| 112 | + body: JSON.stringify(body), |
| 113 | + }); |
| 114 | + |
| 115 | + // ── /actions ──────────────────────────────────────────────────────────── |
| 116 | + |
| 117 | + it('anonymous POST /api/v1/actions/:object/:action/:recordId → 401, body never runs', async () => { |
| 118 | + executeAction.mockClear(); |
| 119 | + const res = await post('/actions/crm_contact/mark_primary/c1', { params: {} }); |
| 120 | + |
| 121 | + expect(res.status).toBe(401); |
| 122 | + const body: any = await res.json(); |
| 123 | + expect(body?.error?.code ?? body?.error?.details?.code).toBe('UNAUTHENTICATED'); |
| 124 | + expect(body?.error?.message).toBe('Authentication is required to access this endpoint.'); |
| 125 | + // The script body would have run system-elevated. It did not. |
| 126 | + expect(executeAction).not.toHaveBeenCalled(); |
| 127 | + }, 60_000); |
| 128 | + |
| 129 | + it('anonymous POST /api/v1/actions/:object/:action (no recordId) → 401', async () => { |
| 130 | + executeAction.mockClear(); |
| 131 | + const res = await post('/actions/crm_contact/mark_primary', {}); |
| 132 | + |
| 133 | + expect(res.status).toBe(401); |
| 134 | + expect(executeAction).not.toHaveBeenCalled(); |
| 135 | + }, 60_000); |
| 136 | + |
| 137 | + it('the SAME request with a session is served — the deny targets anonymity, not the route', async () => { |
| 138 | + executeAction.mockClear(); |
| 139 | + const res = await post('/actions/crm_contact/mark_primary/c1', { params: {} }, true); |
| 140 | + |
| 141 | + expect(res.status).toBe(200); |
| 142 | + expect((await res.json())?.data).toMatchObject({ ok: true }); |
| 143 | + expect(executeAction).toHaveBeenCalledTimes(1); |
| 144 | + }, 60_000); |
| 145 | + |
| 146 | + // ── /automation ───────────────────────────────────────────────────────── |
| 147 | + |
| 148 | + it('anonymous POST /api/v1/automation/:name/trigger → 401, no run started', async () => { |
| 149 | + automationExecute.mockClear(); |
| 150 | + const res = await post('/automation/crm_escalation_flow/trigger', { recordId: 'c1' }); |
| 151 | + |
| 152 | + expect(res.status).toBe(401); |
| 153 | + expect(automationExecute).not.toHaveBeenCalled(); |
| 154 | + }, 60_000); |
| 155 | + |
| 156 | + it('anonymous POST /api/v1/automation/trigger/:name (the legacy SDK shape) → 401', async () => { |
| 157 | + automationExecute.mockClear(); |
| 158 | + const res = await post('/automation/trigger/crm_escalation_flow', { recordId: 'c1' }); |
| 159 | + |
| 160 | + expect(res.status).toBe(401); |
| 161 | + expect(automationExecute).not.toHaveBeenCalled(); |
| 162 | + }, 60_000); |
| 163 | + |
| 164 | + it('anonymous GET /api/v1/automation → 401, the flow inventory stays private', async () => { |
| 165 | + listFlows.mockClear(); |
| 166 | + const res = await fetch(`${baseUrl}/api/v1/automation`); |
| 167 | + |
| 168 | + expect(res.status).toBe(401); |
| 169 | + expect(listFlows).not.toHaveBeenCalled(); |
| 170 | + }, 60_000); |
| 171 | + |
| 172 | + it('anonymous DELETE /api/v1/automation/:name → 401 — the destructive one', async () => { |
| 173 | + unregisterFlow.mockClear(); |
| 174 | + const res = await fetch(`${baseUrl}/api/v1/automation/crm_escalation_flow`, { method: 'DELETE' }); |
| 175 | + |
| 176 | + expect(res.status).toBe(401); |
| 177 | + expect(unregisterFlow).not.toHaveBeenCalled(); |
| 178 | + }, 60_000); |
| 179 | + |
| 180 | + it('the same trigger with a session is served', async () => { |
| 181 | + automationExecute.mockClear(); |
| 182 | + const res = await post('/automation/crm_escalation_flow/trigger', { recordId: 'c1' }, true); |
| 183 | + |
| 184 | + expect(res.status).toBe(200); |
| 185 | + expect(automationExecute).toHaveBeenCalledTimes(1); |
| 186 | + // Identity forwarding survives the gate — a `runAs: 'user'` flow still |
| 187 | + // learns who triggered it (#4127). |
| 188 | + expect(automationExecute.mock.calls[0]?.[1]).toMatchObject({ userId: 'u_socket' }); |
| 189 | + }, 60_000); |
| 190 | + |
| 191 | + // ── one answer, one shape ─────────────────────────────────────────────── |
| 192 | + |
| 193 | + it('both newly-gated domains answer in the IDENTICAL envelope, byte for byte', async () => { |
| 194 | + // The cross-surface contrast that made this a p0 — `/data` answering |
| 195 | + // 401 while `/actions` answered 200 in the SAME process — is not |
| 196 | + // provable on this boot: `@objectstack/rest` owns `/data` and `/meta` |
| 197 | + // and the dispatcher plugin mounts neither, so there is no second |
| 198 | + // surface here to compare against. It was measured instead on a real |
| 199 | + // showcase boot (recorded in the PR body), and asserting a lookalike |
| 200 | + // here would be a weaker claim wearing the stronger one's clothes. |
| 201 | + // |
| 202 | + // What THIS boot can prove is the half that would actually regress |
| 203 | + // unnoticed: the two domains gated by this change share one envelope |
| 204 | + // and cannot drift into two dialects of "unauthenticated". |
| 205 | + const fromActions = await (await post('/actions/crm_contact/mark_primary/c1', {})).json(); |
| 206 | + const fromAutomation = await (await post('/automation/crm_escalation_flow/trigger', {})).json(); |
| 207 | + |
| 208 | + expect(fromActions).toEqual(fromAutomation); |
| 209 | + expect((fromActions as any)?.error?.code ?? (fromActions as any)?.error?.details?.code).toBe('UNAUTHENTICATED'); |
| 210 | + }, 60_000); |
| 211 | +}); |
0 commit comments