Skip to content

Commit 58f66b9

Browse files
feat(cloud-connection,plugin-audit): forward the install mode and the installer; an unmanaged grant is copied and audited by the environment (#31475)
domain:server#3 · os-project-manager · session_01FEkQ5pXkgNXVpCn2GZDjyy Body: seat refresh (round 1) · 2026-11-08T11:19Z Fixes #30964 <!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XJZfATGni9GCmv2TJRug9bZ)_ Clause-②: yes (widening) — `POST /api/v1/cloud-connection/install` accepts `install_mode` (or `installMode`) and sends `sys_package.install_package` the body params `install_mode` and `installer_user_id`; on an unmanaged grant it answers the install-local door's answer; the install-local plugin registers the in-process `marketplace-install-local` service; `sys_audit_log.action` gains `package_unmanaged_import`, which plugin-audit's package lifecycle writer accepts; `@objectstack/plugin-audit` newly exports `PACKAGE_UNMANAGED_IMPORT_AUDIT_ACTION`, `PackageUninstallAuditEvent` and `PackageUnmanagedImportAuditEvent`, `PackageLifecycleAuditEvent` is now their union (narrow it on `action`), and `PackageLifecycleAuditAction` gains `package_unmanaged_import`. No spec schema changes Metadata-protocol: none ## 维护者速读 1. 云端托管环境的安装入口 `POST /cloud-connection/install` 现在会把安装模式 `install_mode`(不传即托管)和安装人 `installer_user_id` 以 body 参数转发给控制平面;安装人取自本入口已认证的会话,不取请求体里的值,也不用请求头。 2. 控制平面批准非托管安装后,由环境自己的 install-local 入口完成复制:以调用者本人的请求头、批准的版本进行,install-local 的全部关卡照常生效(安装权限、协议握手、命名空间占用、副本记录、示例数据归安装人);默认不加载示例数据,调用者要求时才加载。 3. 跨仓库假设,未实测:控制平面批准非托管时跳过自身安装,并在应答中回显 `install_mode: 'unmanaged'` 和 `version_id`。若应答不回显模式或缺少版本号,返回 502,不复制任何内容;应答里完全没有 `install_mode` 时,502 还会提示:不读取该参数的控制平面可能已按托管方式安装,重试前先查看已安装列表。应答里即使带 `data.manifest` 也不读取。cloud 仓库本会话无权读取。另一项未实测的假设:托管环境的内核是否挂载了 install-local 插件。本仓库的托管 Console 认为云端 base 没有 install-local 入口(30963 changeset);未挂载时返回 503,不复制(#31482)。 4. `target_namespace` 暂不转发给控制平面(不确定其 action 是否拒绝未知参数),后续见 #31482。 5. 环境侧审计:每次非托管复制(无论成败)都在 `sys_audit_log` 写一条 `package_unmanaged_import` 行,记录源包与版本、新 base、命名空间、复制条数、成功或失败(失败时记错误码和 HTTP 状态,不记消息);审计服务异常不改变安装应答。 6. 无 spec 改动;`sys_audit_log.action` 新增选项,标签由 `os i18n extract` 生成(各语言暂为英文回填);#30512(ru)后合并者需重新执行提取。 ## What changes **The install mode, forwarded (`@objectstack/cloud-connection`, `POST /api/v1/cloud-connection/install`).** The door reads `install_mode`, the control plane's spelling, or `installMode`, the install-local door's spelling, and parses it against `InstallModeSchema` by reference. A value the schema refuses, or the two spellings naming different modes, answers 400 `INVALID_REQUEST` before the control plane is called. When the caller names a mode, it is sent as the action's `install_mode` body param, the name the cloud half asked for (comment 6696363641). When the caller names none, nothing is sent, and the control plane reads that as `managed`, so a managed install's request differs from today's only by the installer below. **The installing user, forwarded.** Every install sends `installer_user_id` as a body param on the same `install_package` action, never as a header, because cloud#2245 removed `x-actor-id` as an authorization input. The value is the id of the session this door admitted. A value in the request body is never read. How the control plane bounds the assertion (triage's question) is the cloud half's: per comment 6696363641 it reads the id only when the user is a member of the environment's organization, and otherwise records its service principal and logs the unverified claim. This PR does not change that bound. **An unmanaged grant is copied by the environment (Ask 3).** On an unmanaged grant, the door hands the copy to the environment's own install-local door. It sends `installMode: 'unmanaged'`, the granted `version_id`, `seedSampleData` only when the caller asked for it, and the caller's own headers, so the door admits and gates the same person. The answer is that door's answer, status included. The copy is not re-implemented here. It keeps every gate `POST /api/v1/marketplace/install-local` applies: the installer's install capability (`manage_metadata`), the protocol handshake, the namespace holds, the #30808 copy record, and sample rows owned by the installer. By default it loads no sample data, matching the framework default (Ask 3's "framework parity"). - In a multi-tenant deployment the door is read from the environment's own kernel (`kernel-manager`). In a single-environment deployment it is read from the host kernel. That a hosted environment's kernel mounts the install-local plugin at all is NOT MEASURED (see below, #31482). - A grant the door cannot read answers 502 `PLUGIN_INSTALL_FAILED` and copies nothing. That covers an answer that does not echo `install_mode: 'unmanaged'` and one with no `version_id`. A `data.manifest` in the answer is never read. When the answer has no `install_mode` at all, the 502 and its warn line add: "The control plane did not echo install_mode; a control plane that does not read it may have installed the package managed. Check Installed before retrying." An echoed different mode, or an echoed `unmanaged` with no `version_id`, keeps the plain 502. - An environment without the install-local plugin answers 503 `SERVICE_UNAVAILABLE` and copies nothing. - A control-plane refusal, and every managed install, is answered exactly as before. **The in-process install door.** The install-local plugin registers the `marketplace-install-local` service at `init` and declares it in `providesServices`. Its `install(request)` takes a Fetch `Request` and runs the same `handleInstall` the `POST` route mounts. It answers that route's `Response`. `routeContextOf` is the slice of a route context the handler reads: one cached read of the body, `header`, `raw`, `url`, and `json` for the answer. The seat approved this registration line in the claim amendment. **The environment's audit row (Ask 4, `@objectstack/plugin-audit`).** The install-local door's unmanaged branch (`installUnmanaged`) hands the `audit` slot one `package_unmanaged_import` event per copy it attempted, whether it landed or not. Both doors that reach the branch do this. The event is declared structurally in cloud-connection, as metadata-protocol declares its uninstall event, so cloud-connection does not depend on plugin-audit. plugin-audit's package lifecycle writer stores the event as a deployment-level `sys_audit_log` row: no record and no organization, like `package_uninstall`. Its `metadata` holds: - `package_id` and `version`; - `environment_id`, which is null because the door does not know it; - `target_package_id`, `namespace` and `source_namespace`; - `copied_count`; - `outcome`, which is `success` or `failure`. A failure adds `error_code` and `status`, never the message, because a refusal message can quote package content. The ledger's `action` select gains the value writer-first, as `package_uninstall` did in #31186. The enum test and the writer inventory each name its writer. Its labels were regenerated with `os i18n extract` (the command in the plugin's `scripts/i18n-extract.config.ts`). Every locale is filled from English, with a source-hash record, until a translator replaces it. An audit slot that throws changes no answer; the failure is logged at `error`. ## Cross-repo, NOT MEASURED The grant's shape is assumed, not measured. The cloud half is cloud PR #3683, and neither this session nor the seat could read objectstack-ai/cloud. The assumption, ruled by the seat: on an unmanaged grant the control plane skips its own install and answers `data.install_mode: 'unmanaged'` with the granted `data.version_id` (and `data.version`). The environment then fetches that version's manifest itself, through the install-local cloud branch's existing `/api/v1/marketplace/packages/:id/versions/:versionId/manifest` fetch. The door fails closed when the answer is not that shape. The control-plane double in `cloud-connection-plugin.test.ts` pins this shape and names it as assumed. Also not measured: that a hosted environment's kernel mounts the install-local plugin at all. Nothing in this repo shows it, and this repo's own hosted Console reads a cloud base as having no install-local door (the 30963 changeset, `MarketplacePage`). Where the door is not mounted, an unmanaged grant copies nothing and answers 503 `SERVICE_UNAVAILABLE`, naming the missing plugin. The `install-local-door-service.ts` docblock states the same. Follow-up: #31482. `target_namespace` is held back. Ask 1 forwards the namespace "once #30794 lands", and it has landed. Whether cloud's action rejects an unknown body param with 400 is not known here, so this PR does not send one. Follow-up: #31482. The install-local door already accepts `targetNamespace` on an unmanaged copy, but this door does not pass one to it yet either. ## Tests - `packages/cloud-connection/src/cloud-connection-plugin.test.ts`, 3 forwarding cases and 9 unmanaged-grant cases: - The managed request now carries `installer_user_id`, and no `install_mode` when none was named. - Both body spellings send `install_mode: 'unmanaged'`, and `'managed'` is sent when named. - `installer_user_id` is the session's user even when the body names another. - `'copy'`, `true`, or two disagreeing spellings answer 400 with no control-plane call. - The granted version is copied through the door as the caller: the cookie is forwarded, no `Authorization` is added, and the body is exactly `{ packageId, versionId, installMode }`. - `seed_sample_data: true` asks the door for `seedSampleData: true`. - A door refusal is the answer, status and all. - In single-environment mode the door is the host's. - Five unreadable grants answer 502 and the door is never called; one of them carries a manifest. - An answer with no `install_mode` at all (absent, null, or no data) adds the "may have installed the package managed" sentence to the 502 and the warn line; an echoed `managed`, or `unmanaged` with a missing or blank `version_id`, does not. - A control-plane 403 is relayed and the door is never called. - A managed install never reaches the door. - No door answers 503. - `packages/cloud-connection/src/marketplace-install-local-install-modes.test.ts`, 5 cases on the #30808 harness, now with `init` called and an `audit` slot: - A landed copy hands one success event naming the new base, namespace and count. - A re-run's 409 hands one failure event with `RESOURCE_CONFLICT` and 409. - A throwing slot changes no answer and logs one `error` line. - The in-process door makes the same copy, sample rows included, and refuses a malformed JSON body with 400. - The in-process door refuses a caller without the install capability (`manage_metadata`) with 403 `FORBIDDEN`, as the route does: no import call and no audit event. - `packages/plugins/plugin-audit/src/package-lifecycle-audit.test.ts`, 2 cases on the real `audit` slot (`ObjectQLPlugin` + `AuditPlugin` on sqlite), each read back: the success row's columns and exact `metadata`, and the failure row's `metadata` with its absences as null. - `sys-audit-log-action-labels.test.ts`, `sys-audit-log-retired-actions.test.ts` (the writer inventory) and `audit-log-deployment-level-rows.integration.test.ts` name the new value. ## Acceptance notes - **Who gates the copy.** `POST /cloud-connection/install` admits any signed-in environment session. The copy additionally needs the install capability (`manage_metadata`), because it runs through that door. A caller without it gets the door's 403 after the control plane has already recorded its grant. Nothing is copied, and the environment's audit has no row: the door refused before the import ran, and only an attempted copy is recorded. Follow-up: #31481. - **What the environment row does not hold.** The environment id is null, because the install-local door has no reading of it; the row lives in that environment's own ledger. The new label reads English in every locale until it is translated. - **Sibling.** #30512 (ru) adds an ru bundle in the same translations directory. Whichever lands second merges origin/main and re-runs the extraction. ## Verification Head `6a9ae1bd` (review round 1 on top of `359ed69a`), origin/main merged at `c0dc4059`. - **Round 1 (`6a9ae1bd`).** Three new ablations, each red: `unechoed` forced `false` (the absent-echo case loses its sentence), `unechoed` forced `true` (the echoed-mismatch case gains it), and the install-capability check forced off (the in-process door answers 200 instead of 403). The cloud-connection suite then passed 75 files, 1011 tests. Typecheck (including the test layer) and lint passed. The 75 derived dispatch gates were re-run, all exit 0, and `--ran` reports 75/75 with a derived zero. - **Red on main first.** With the production files restored to base `1ff99441`, the new file removed and the new tests kept: - `cloud-connection-plugin.test.ts` and `marketplace-install-local-install-modes.test.ts`: 14 failed, 69 passed. For example: `expected { recordId: 'pkg_1', params: { …(2) } } to deeply equal { recordId: 'pkg_1', params: { …(4) } }`, `{"package_id":"pkg_1","install_mode":"copy"}: expected 200 to be 400`, `{"version_id":"ver_9"}: expected 200 to be 502`, `expected undefined to deeply equal { packageId: 'pkg_1', …(3) }`, and `expected [] to deeply equal [ { …(8) } ]` (no audit event). - The plugin-audit files: 4 failed, 34 passed. For example: `expected [ 'create', 'read', 'update', …(11) ] to deeply equal [ …(12) ]`, the writer-inventory refusal "sys_audit_log.action and the writer inventory in this file disagree", and the two row cases (no row was written). - Then green on head. - **Ablations** (`scripts/ablation-replace.mjs`; each mutation landed, was run, and the tree was restored to HEAD; each red): - the echo check → `const unread = false`: the fail-closed pin is red; - the version check → `: false ? …`: the fail-closed pin is red; - the enum refusal → `if (false)`: the 400 pin is red; - the disagreeing-spellings refusal → `if (false)`: the 400 pin is red; - the installer → `body?.installer_user_id ?? session.userId`: the installer pin is red; - the refusal relay → `if (installMode !== 'unmanaged')`: the control-plane refusal pin is red, because the door was called; - the missing-door answer → `if (false)`: the 503 pin is red; - the failure event's outcome → `'success'`: the failure-event pin is red; - the writer's acceptance of the new action → removed: both plugin-audit row pins are red. - **Package suites** (under the verify lock): cloud-connection 75 files, 1009 passed; plugin-audit 79 files, 1222 passed. `pnpm --filter @objectstack/plugin-audit --filter @objectstack/cloud-connection run typecheck` exit 0, including each test layer. `pnpm lint packages/cloud-connection packages/plugins/plugin-audit` exit 0. - **Dispatch gates:** `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 75 commands. Each was run with its exit captured before any pipe and recorded as `<command> :: exit N`; `--ran` reports `75 derived famil(ies) accounted for — 75 run, 0 NOT-MEASURED (a DERIVED zero — all 75 recorded an exit code and none of them is 3)`. The first pass found `check:slot-lookup` red: `cloud-connection-plugin.ts: erasure count grew 5 → 6`, from the new `getService<any>('kernel-manager')` read. It was fixed in `359ed69a` by typing the read with its one member, then exit 0. The other 74 exited 0 on the first pass. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5pQJCx8STEq28nr3Ej)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7d0b47c commit 58f66b9

35 files changed

Lines changed: 915 additions & 33 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/cloud-connection': patch
3+
'@objectstack/plugin-audit': patch
4+
---
5+
6+
feat(cloud-connection,plugin-audit): the hosted install door forwards the install mode and the installing user, an unmanaged grant is copied by the environment's own install-local door, and every unmanaged copy writes a `package_unmanaged_import` audit row
7+
8+
Clause-②: yes (widening) — `POST /api/v1/cloud-connection/install` accepts `install_mode` (or `installMode`) and sends the control plane's `sys_package.install_package` action `install_mode` and `installer_user_id`; on an unmanaged grant it answers the install-local door's answer; the install-local plugin registers the in-process `marketplace-install-local` service; `sys_audit_log.action` gains `package_unmanaged_import`, and plugin-audit's package lifecycle writer accepts that event; `@objectstack/plugin-audit` newly exports `PACKAGE_UNMANAGED_IMPORT_AUDIT_ACTION`, `PackageUninstallAuditEvent` and `PackageUnmanagedImportAuditEvent`, `PackageLifecycleAuditEvent` is now the union of the two event types (narrow it on `action`), and `PackageLifecycleAuditAction` gains `package_unmanaged_import`
9+
Metadata-protocol: none
10+
11+
- **The install mode, forwarded.** `POST /api/v1/cloud-connection/install` reads `install_mode` (the control plane's spelling) or `installMode` (the install-local door's), parsed against `InstallModeSchema`. A value the schema refuses, or two spellings that disagree, answers 400 `INVALID_REQUEST` before the control plane is called. When the caller names a mode, it is sent as the action's `install_mode` body param; when the caller names none, nothing is sent, and the control plane reads that as `managed`, as before.
12+
- **The installing user, forwarded.** Every install now sends `installer_user_id`, a body param on the same action, never a header. Its value is the id of the session this door admitted, never a value from the request body. The control plane reads it only for a member of the environment's organization, and records its service principal otherwise (the cloud half, cloud#3624).
13+
- **An unmanaged grant is copied by the environment.** When the control plane grants an unmanaged install, this door hands the copy to the environment's own install-local door: `installMode: 'unmanaged'`, the granted `version_id`, `seedSampleData` only when the caller asked for it, and the caller's own headers, so the door admits and gates the same person. The answer is that door's answer. The copy keeps every gate the install-local door applies: the installer's install capability, the protocol handshake, the namespace holds, the copy record, and sample rows owned by the installer. A grant this door cannot read (no `install_mode: 'unmanaged'` echoed, or no `version_id`) answers 502 and copies nothing; a `data.manifest` in the answer is never read. When the answer has no `install_mode` at all, the 502 adds that a control plane that does not read the param may already have installed the package managed, and to check Installed before retrying. An environment without the install-local plugin answers 503 and copies nothing. A control-plane refusal, and every managed install, is answered exactly as before.
14+
- **Cross-repo, not measured here.** The grant's shape (the control plane skips its own install on an unmanaged grant and answers `data.install_mode: 'unmanaged'` with `data.version_id`) is assumed from the cloud half's design; cloud PR #3683 is not readable from this repository. So is the install-local plugin being mounted in a hosted environment's kernel at all: this repo's hosted Console reads a cloud base as having no install-local door (the 30963 changeset), and without the door an unmanaged grant answers 503 (#31482). The namespace a copy is renamed into (`targetNamespace`, #30794) is not forwarded to the control plane yet (#31482): whether its action accepts an unknown param is not known here.
15+
- **The in-process install door.** The install-local plugin registers the `marketplace-install-local` service at `init`. Its `install(request)` runs `POST /api/v1/marketplace/install-local` for a Fetch `Request` and answers that route's `Response`, through the same handler.
16+
- **New plugin-audit exports.** `@objectstack/plugin-audit` exports `PACKAGE_UNMANAGED_IMPORT_AUDIT_ACTION`, `PackageUninstallAuditEvent` and `PackageUnmanagedImportAuditEvent`. `PackageLifecycleAuditEvent` is now `PackageUninstallAuditEvent | PackageUnmanagedImportAuditEvent`, so a reader narrows it on `action`; `PackageLifecycleAuditAction` gains `package_unmanaged_import`.
17+
- **The environment's audit row of each unmanaged copy.** The install-local door's unmanaged branch hands the `audit` slot one `package_unmanaged_import` event per copy it attempted, whether it landed or not, from both doors that reach it. plugin-audit's package lifecycle writer stores it as a deployment-level `sys_audit_log` row (no record, no organization), with `metadata` naming the source package and version, the new base, its namespace, the namespace a rename came from, the items copied and `outcome` (`success` or `failure`; a failure adds its error code and HTTP status, never its message). `environment_id` is null on this row: the door does not know it. The ledger's `action` select gains the value writer-first, with its labels regenerated by `os i18n extract`; the new label is filled from English in every locale until a translator replaces it. An audit slot that throws changes no answer.

‎packages/cloud-connection/src/cloud-connection-plugin.test.ts‎

Lines changed: 204 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,10 +185,62 @@ describe('multi-tenant mode (env-registry + per-env kernel auth)', () => {
185185
expect(res.payload.success).toBe(true);
186186
const [url, init] = fetchSpy.mock.calls[0]!;
187187
expect(url).toBe('http://cloud.test/api/v1/actions/sys_package/install_package');
188-
expect(JSON.parse((init as any).body)).toEqual({ recordId: 'pkg_1', params: { environment_id: ENV, seed_sample_data: true } });
188+
// [#30964] No mode asked: no `install_mode` sent (the control plane's absent value is `managed`); the installer always is.
189+
expect(JSON.parse((init as any).body)).toEqual({
190+
recordId: 'pkg_1', params: { environment_id: ENV, seed_sample_data: true, installer_user_id: 'user-1' },
191+
});
189192
expect((init as any).headers.Authorization).toBe('Bearer svc-key');
190193
});
191194

195+
// ── [#30964, cloud#3624 ruling A] the install mode and the installing user, forwarded ──
196+
197+
async function installWith(body: Record<string, unknown>, userId = 'user-1') {
198+
const rawApp = makeRawApp();
199+
const { ctx, fireKernelReady } = makeCtx({ rawApp, services: mtServices(userId) });
200+
const fetchSpy = vi.fn(async (_url: string, _init?: RequestInit) => new Response(JSON.stringify({ success: true, data: { installed: true } }), { status: 200 }));
201+
vi.stubGlobal('fetch', fetchSpy);
202+
await new CloudConnectionPlugin({ controlPlaneUrl: 'http://cloud.test', controlPlaneApiKey: 'svc-key' }).start(ctx as any);
203+
await fireKernelReady();
204+
const res = await rawApp.routes.get('POST /api/v1/cloud-connection/install')!(
205+
makeC('https://t1.example.com/api/v1/cloud-connection/install', body),
206+
);
207+
const sent = fetchSpy.mock.calls[0] ? JSON.parse((fetchSpy.mock.calls[0][1] as any).body) : undefined;
208+
return { res, fetchSpy, sent };
209+
}
210+
211+
it('install forwards `install_mode` as the control plane spells it, from either spelling of the body', async () => {
212+
for (const body of [{ package_id: 'pkg_1', install_mode: 'unmanaged' }, { package_id: 'pkg_1', installMode: 'unmanaged' }]) {
213+
// What is SENT is pinned here; what the answer does with an unmanaged grant is pinned below.
214+
const { sent } = await installWith(body);
215+
expect(sent).toEqual({
216+
recordId: 'pkg_1',
217+
params: { environment_id: ENV, seed_sample_data: false, install_mode: 'unmanaged', installer_user_id: 'user-1' },
218+
});
219+
}
220+
const managed = await installWith({ package_id: 'pkg_1', install_mode: 'managed' });
221+
expect(managed.sent.params).toMatchObject({ install_mode: 'managed', installer_user_id: 'user-1' });
222+
});
223+
224+
it('install forwards the admitted session\'s user as `installer_user_id`, never one the body names', async () => {
225+
const { sent } = await installWith({ package_id: 'pkg_1', installer_user_id: 'usr_someone_else', installerUserId: 'usr_other' }, 'user-7');
226+
expect(sent.params.installer_user_id).toBe('user-7');
227+
expect(Object.keys(sent.params).sort()).toEqual(['environment_id', 'installer_user_id', 'seed_sample_data']);
228+
});
229+
230+
it('install refuses an install mode the manifest enum does not hold, or two spellings that disagree: 400, no control-plane call', async () => {
231+
for (const body of [
232+
{ package_id: 'pkg_1', install_mode: 'copy' },
233+
{ package_id: 'pkg_1', installMode: true },
234+
{ package_id: 'pkg_1', install_mode: 'managed', installMode: 'unmanaged' },
235+
]) {
236+
const { res, fetchSpy } = await installWith(body);
237+
expect(res.status, JSON.stringify(body)).toBe(400);
238+
expect(res.payload.error.code).toBe('INVALID_REQUEST');
239+
expect(res.payload.error.message).toContain('install_mode');
240+
expect(fetchSpy).not.toHaveBeenCalled();
241+
}
242+
});
243+
192244
it('installed degrades to an empty disconnected list without cloud credentials', async () => {
193245
const rawApp = makeRawApp();
194246
const { ctx, fireKernelReady } = makeCtx({ rawApp, services: mtServices('user-1') });
@@ -330,3 +382,154 @@ describe('CloudConnectionPlugin — the routes and the binding read the control-
330382
expect(called).toEqual([`${expected}/api/v1/cloud/environments/${ENV}/packages`]);
331383
});
332384
});
385+
386+
// ── [#30964, cloud#3624 ruling A] an UNMANAGED grant: the copy is made in the environment, by its install-local door ──
387+
//
388+
// Cross-repo, NOT MEASURED: the grant's shape. The control-plane double below
389+
// answers what the cloud half is assumed to (cloud PR #3683 is not readable
390+
// from this repository): on an unmanaged grant it skips its own install and
391+
// echoes `install_mode: 'unmanaged'` with the granted `version_id`.
392+
393+
describe('[#30964] an unmanaged grant hands the copy to the environment\'s install-local door', () => {
394+
const ENV = 'env-123';
395+
const COOKIE = 'os.session=abc';
396+
397+
function cWithCookie(body: any) {
398+
const url = 'https://t1.example.com/api/v1/cloud-connection/install';
399+
const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 }));
400+
return { req: { url, raw: new Request(url, { method: 'POST', headers: { cookie: COOKIE } }), json: async () => body }, json };
401+
}
402+
403+
async function grant(opts: {
404+
body?: Record<string, unknown>;
405+
answer?: { status?: number; json: unknown };
406+
door?: { install: (r: Request) => Promise<Response> } | null;
407+
singleEnvironment?: boolean;
408+
} = {}) {
409+
const rawApp = makeRawApp();
410+
const seen: { request?: Request; body?: any } = {};
411+
const door = opts.door === null ? undefined : opts.door ?? {
412+
install: vi.fn(async (request: Request) => {
413+
seen.request = request;
414+
seen.body = await request.json();
415+
return new Response(JSON.stringify({ success: true, data: { installMode: 'unmanaged', targetPackageId: 'com.acme.crm-copy' } }), { status: 200 });
416+
}),
417+
};
418+
const envKernel = {
419+
getServiceAsync: async (name: string) => {
420+
if (name === 'auth') return sessionAuth('user-1');
421+
if (name === 'marketplace-install-local' && door) return door;
422+
throw new Error(`no ${name}`);
423+
},
424+
};
425+
const services: Record<string, any> = opts.singleEnvironment
426+
? { auth: sessionAuth('user-1'), ...(door ? { 'marketplace-install-local': door } : {}) }
427+
: { 'env-registry': { resolveByHostname: async () => ({ environmentId: ENV }) }, 'kernel-manager': { getOrCreate: async () => envKernel } };
428+
const { ctx, fireKernelReady } = makeCtx({ rawApp, services });
429+
const answer = opts.answer ?? { json: { success: true, data: { install_mode: 'unmanaged', version_id: 'ver_9', version: '2.0.0' } } };
430+
const fetchSpy = vi.fn(async () => new Response(JSON.stringify(answer.json), { status: answer.status ?? 200 }));
431+
vi.stubGlobal('fetch', fetchSpy);
432+
await new CloudConnectionPlugin({
433+
controlPlaneUrl: 'http://cloud.test', controlPlaneApiKey: 'svc-key',
434+
...(opts.singleEnvironment ? { singleEnvironment: true, environmentId: ENV } : {}),
435+
}).start(ctx as any);
436+
await fireKernelReady();
437+
const res = await rawApp.routes.get('POST /api/v1/cloud-connection/install')!(
438+
cWithCookie(opts.body ?? { package_id: 'pkg_1', install_mode: 'unmanaged' }),
439+
);
440+
return { res, door, seen, fetchSpy, logger: ctx.logger };
441+
}
442+
443+
it('copies the granted version through the door, as the caller (their own headers), and answers the door\'s answer', async () => {
444+
const { res, seen, fetchSpy } = await grant();
445+
expect(fetchSpy).toHaveBeenCalledTimes(1);
446+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
447+
expect(res.payload).toEqual({ success: true, data: { installMode: 'unmanaged', targetPackageId: 'com.acme.crm-copy' } });
448+
expect(seen.request!.method).toBe('POST');
449+
expect(new URL(seen.request!.url).pathname).toBe('/api/v1/marketplace/install-local');
450+
expect(seen.request!.headers.get('cookie')).toBe(COOKIE);
451+
expect(seen.request!.headers.get('authorization')).toBeNull();
452+
// No sample data unless asked (framework parity), and never a manifest from the grant.
453+
expect(seen.body).toEqual({ packageId: 'pkg_1', versionId: 'ver_9', installMode: 'unmanaged' });
454+
});
455+
456+
it('asked for the sample data, the door is asked for it too (the #30808 copy, owned by the installer)', async () => {
457+
const { seen } = await grant({ body: { package_id: 'pkg_1', install_mode: 'unmanaged', seed_sample_data: true } });
458+
expect(seen.body).toEqual({ packageId: 'pkg_1', versionId: 'ver_9', installMode: 'unmanaged', seedSampleData: true });
459+
});
460+
461+
it('a door refusal is the answer, status and all', async () => {
462+
const door = { install: vi.fn(async () => new Response(JSON.stringify({ success: false, error: { code: 'FORBIDDEN', message: 'nope' } }), { status: 403 })) };
463+
const { res } = await grant({ door });
464+
expect(res.status).toBe(403);
465+
expect(res.payload.error.code).toBe('FORBIDDEN');
466+
});
467+
468+
it('single-environment: the door is the host kernel\'s', async () => {
469+
const { res, seen } = await grant({ singleEnvironment: true });
470+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
471+
expect(seen.body).toMatchObject({ packageId: 'pkg_1', versionId: 'ver_9', installMode: 'unmanaged' });
472+
});
473+
474+
it('fails closed on a grant it cannot read: no echoed mode, or no version id — 502, nothing copied', async () => {
475+
for (const data of [
476+
{ version_id: 'ver_9' },
477+
{ install_mode: 'managed', version_id: 'ver_9' },
478+
{ install_mode: 'unmanaged' },
479+
{ install_mode: 'unmanaged', version_id: ' ' },
480+
// A manifest in the answer is never a substitute for the granted version.
481+
{ install_mode: 'unmanaged', manifest: { id: 'com.acme.crm', version: '2.0.0' } },
482+
]) {
483+
const { res, door } = await grant({ answer: { json: { success: true, data } } });
484+
expect(res.status, JSON.stringify(data)).toBe(502);
485+
expect(res.payload.error.code).toBe('PLUGIN_INSTALL_FAILED');
486+
expect(res.payload.error.message).toContain('Nothing was copied');
487+
expect((door as any).install).not.toHaveBeenCalled();
488+
}
489+
});
490+
491+
it('no echoed install_mode at all says the package may already be installed managed; an echoed mismatch or a missing version does not', async () => {
492+
const MANAGED_NOTE = 'The control plane did not echo install_mode; a control plane that does not read it may have '
493+
+ 'installed the package managed. Check Installed before retrying.';
494+
for (const data of [{ version_id: 'ver_9' }, { install_mode: null, version_id: 'ver_9' }, {}]) {
495+
const { res, logger } = await grant({ answer: { json: { success: true, data } } });
496+
expect(res.status, JSON.stringify(data)).toBe(502);
497+
expect(res.payload.error.message).toContain('Nothing was copied.');
498+
expect(res.payload.error.message).toContain(MANAGED_NOTE);
499+
const warned = (logger.warn as any).mock.calls.map((call: unknown[]) => String(call[0])).join('\n');
500+
expect(warned).toContain(MANAGED_NOTE);
501+
}
502+
for (const data of [
503+
{ install_mode: 'managed', version_id: 'ver_9' },
504+
{ install_mode: 'unmanaged' },
505+
{ install_mode: 'unmanaged', version_id: ' ' },
506+
]) {
507+
const { res, logger } = await grant({ answer: { json: { success: true, data } } });
508+
expect(res.status, JSON.stringify(data)).toBe(502);
509+
expect(res.payload.error.message).not.toContain('may have installed the package managed');
510+
const warned = (logger.warn as any).mock.calls.map((call: unknown[]) => String(call[0])).join('\n');
511+
expect(warned).toContain('was not copied');
512+
expect(warned).not.toContain('may have installed the package managed');
513+
}
514+
});
515+
516+
it('a control-plane refusal is relayed as it was, and nothing is copied', async () => {
517+
const { res, door } = await grant({ answer: { status: 403, json: { success: false, error: { code: 'FORBIDDEN', message: 'not entitled' } } } });
518+
expect(res.status).toBe(403);
519+
expect(res.payload).toEqual({ success: false, error: { code: 'FORBIDDEN', message: 'not entitled' } });
520+
expect((door as any).install).not.toHaveBeenCalled();
521+
});
522+
523+
it('a managed install is never handed to the door', async () => {
524+
const { res, door } = await grant({ body: { package_id: 'pkg_1' }, answer: { json: { success: true, data: { installed: true } } } });
525+
expect(res.payload).toEqual({ success: true, data: { installed: true } });
526+
expect((door as any).install).not.toHaveBeenCalled();
527+
});
528+
529+
it('an environment with no install-local door answers 503 and copies nothing', async () => {
530+
const { res } = await grant({ door: null });
531+
expect(res.status).toBe(503);
532+
expect(res.payload.error.code).toBe('SERVICE_UNAVAILABLE');
533+
expect(res.payload.error.message).toContain('Nothing was copied');
534+
});
535+
});

0 commit comments

Comments
 (0)