mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 22:13:59 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server has about 1,100 test and helper files in `server/src/__tests__` > - `server/tsconfig.json` excludes that directory, Vitest does not check types, and no script runs the tsconfig in that directory > - So a test can call a function with the wrong arguments and still pass, and no tool reports it > - This gap hid 2,168 real type errors, and some of them hid tests that did not test what they claim > - This pull request fixes all of these errors and adds the directory to the server layers from paperclipai/paperclip#18737 > - The benefit is that a type error in a server test now fails the typecheck, with no baseline and no backlog ## Linked Issues or Issue Description Refs paperclipai/paperclip#18737, which is merged and added the server layers. Refs paperclipai/paperclip#18738, which is merged and checks the test projects outside `pnpm -r`, so it is not a duplicate. Refs paperclipai/paperclip#18137, which records that this directory has no check. **What happened?** No tool checked the types of 1,074 of the 1,101 files in `server/src/__tests__`. I searched `package.json`, the workflows, and all tsconfig files. 27 files are in the program of another tsconfig, and these 27 have 0 errors. 11 of the 27 are in `helpers/maintenance/tsconfig.json`. No script ran that project when I measured this. paperclipai/paperclip#18738 now runs it. **Expected behavior** The server typecheck checks these files, and a type error fails the check. **Steps to reproduce** 1. On the base commit, run `tsc -p server/src/__tests__/tsconfig.json --noEmit`. It reports 6,536 errors and needs 12.3 GiB. 2. Add a type error to any file in `server/src/__tests__`. 3. Run `pnpm --filter @paperclipai/server typecheck`. It passes. **Paperclip version or commit** I measured the error breakdown below on commit `8dfd632452`, with TypeScript 7.0.2. The branch now includes master up to paperclipai/paperclip#18865. **Deployment mode** Not applicable. This issue applies to development and CI. No production source file in the server changes. ### Error breakdown Each row adds one change to the row above. | Step | Total errors | Change | Cause | | --- | --- | --- | --- | | Config as committed | 6,536 | | | | Add `src/types/*.d.ts` | 4,447 | -2,089 | Config. The Express request types were missing. | | Set `rootDir` to the repository root | 2,436 | -2,011 | Config. | | Set `allowImportingTsExtensions` | 2,181 | -255 | Config. Vitest accepts `.ts` imports. | | Add `ES2024.Promise` to `lib` | 2,138 | -43 | Config. Node 24 has `Promise.withResolvers`. | | Set `allowJs` for `.mjs` imports | 2,148 | +10 | Config. It removes 8 `TS7016` errors and shows new real errors. | | Set `declaration` to false | 2,142 | -6 | Config. Tests emit nothing. | | Count only files in `server/src` | 2,058 | -84 | Other packages: 53 Daytona, 29 Runner test, 2 UI. | So 4,478 of the 6,536 errors (69%) came from config or scope, and 2,058 are real type errors in 314 files. The 29 Runner test errors are also real, which gives 2,087 errors. Tests that master added after this measurement had 81 more errors, so this pull request fixes 2,168 errors. This table classifies the first 2,058 errors. | Kind of real error | Errors | | --- | --- | | Wrong argument or assignment type | 1,023 | | Stale or partial fixture objects | 525 | | Property that the type does not have | 317 | | Missing narrowing of null or unknown | 101 | | Implicit any | 60 | | Missing name or module | 16 | | Other | 16 | ### What the type errors hid Most errors were stale fixtures and loose mocks. These errors hid real test problems, and this pull request fixes them: - **A test that never ran.** `instrumentation.test.ts` required `sdk-trace-base`, which is not installed. So 3 span tests were skipped. They now run and pass. - **Assertions that could not fail.** - `issue-thread-interactions-service` used a company ID as an issue ID. - `status-card-evaluation-work` compared `[]` with `[]` in a rollback check. - `slack-conversation-lifecycle` read `item.issueId`, which does not exist. - `email-channels` used a permission key that does not exist. - `heartbeat-project-env` imported `LOW_TRUST_REVIEW_PRESET`, which is not exported. The value was undefined. - **Postgres processes that did not stop.** 11 test files called `stop` on the test database helper. That method does not exist, and the helper method is `cleanup`. - **Arguments that the service ignored.** - `methodKey` is now `connectionMethodKey` in the Daytona, Unikraft, 1Password, and Railway tests. - 108 calls passed `"owner-user"` to a parameter that expects an options object. - 9 chat wizard fixtures passed `managementContext` as `source`, so they ran `existing_app` and not `manifest`. - 2 tests passed a `{ userId }` actor that the function ignores. - Inserts into `environments` passed a `companyId` column that the table does not have. - **Problems in tests that master added during this work.** - `sandbox-creation-operations` read `database.connectionString` when an external test database was set. In that mode `database` is undefined, so the fixture would stop with a TypeError. It now uses the external URL. - `idle-completed-history` set a Dot operation to `dispatched`. That is a Muse status, and the Dot type does not have it. The fixture now uses `admitted`, which is a real in-flight Dot status. ### Possible product problems, not changed These may be real problems in production code or types. I did not change them, because this pull request does not change production behavior: - `decisions-service` `service.create` does not validate the lenient `cancel_issue_tree` input. - `createConnection` ignores `input.connectionPurpose`. - The `createConnection` route schema default stores `{}` for `transportConfig`. - `prepareManagedAiRuntime` accepted the invalid value `mode: "connection"`. - `createBinding` accepts invalid `projectionClass` strings outside class 3. - `ensureManagedProjectWorkspace` forwards an untyped `repoRef` by spread. - `routineVariableSchema.label` is optional, but `RoutineVariable.label` is required. - `ToolRunContext.projectId` may be too strict. - `withdrawInteraction` reads `issue.status`, which its type omits. - `issueService.list` and `reconcileNativeFinalizations` omit fields that they return at runtime. - `createGitHubExternalObjectProvider` handles `tokenProvider: null`, but its type forbids this value. ## What Changed - Fixed the 2,168 type errors. The diff changes 322 test and helper files. - Corrected `server/src/__tests__/tsconfig.json`. Editors and the typecheck now read the same options and report the same errors. - Added three `test-tree` layers to `server/scripts/typecheck-layers.mjs`. They read the server layers as declarations, and any error fails them. A hash of the path selects the shard, so a new file does not move other files. - Added `server/scripts/typecheck-stubs/daytona-sdk.d.ts`. Server tests reach Daytona plugin source, and the root install does not have `@daytonaio/sdk`. - Changed two imports in `ui/src/lib/issue-execution-policy.ts` to use `.js` extensions, because server tests import this file. - Made `declarationsConfig` and `--declarations-only` skip the `test-tree` layers, because these layers emit nothing. Other projects read only the source layers. Added a test for this. - Updated `doc/DEVELOPING.md`. ## Verification Run these commands: ```sh pnpm --filter @paperclipai/server typecheck pnpm exec vitest run server/scripts/typecheck-layers.test.mjs ``` Results on macOS (arm64), Node 24, 16 cores. Each check ran after the merge of paperclipai/paperclip#18738 unless the row says otherwise: | Check | Commit | Result | | --- | --- | --- | | Server typecheck, `PAPERCLIP_TYPECHECK_LOW_MEMORY=1`, all 7 layers | `6e45a08573` | Exit 0, 0 errors, 62 seconds, peak 3.52 GiB | | `node scripts/typecheck-test-projects.mjs --low-memory` | `a3306bd13e` | Exit 0, 0 errors, 42 seconds, peak 3.25 GiB | | The same script with `--reuse-declarations` | `1b878aabc0` | Exit 0, 0 errors | | `typecheck-layers.test.mjs` and `live-recovery-work.test.ts` | `01db5634e4` | 90 passed. These include real compiler runs for a pass, a type error, and an invalid tsconfig. | | `tsconfig.declarations.json` after a full server typecheck | `0fb1e4fb0a` | It references only `below`, `cycle`, and `above`. No generated config names a `tsconfig.layers.json` file. | | Owned runtime test in `idle-completed-history` | `e8f2f448ac` | Passed, with the fix that master later replaced | | `idle-incoming-wake`, `plugin-idle-manager`, and the changed `chat-channels` test | `6e45a08573` | 30 passed | | Runner `native-execution.test.ts` | `eab4dcc1f4` | 114 passed | | The 19 server test files that changed since `eab4dcc1f4`, and `typecheck-layers.test.mjs` | `259737b700` | 4,275 of 4,277 passed. The 2 failures are in `chat-channels` and are in the list of 7 below. | The peak is the largest single process, from `/usr/bin/time -l`. Peaks for the server typecheck were between 3.42 GiB and 3.56 GiB across 8 runs. Peaks for the test projects were 3.25 GiB and 3.37 GiB across 2 runs. I did not measure a cgroup. **Runtime check of the fixes.** Types do not prove that a test still works. So I ran all 309 changed server test files, 11,929 tests, before the rebase onto paperclipai/paperclip#18737: | Result | Tests | Detail | | --- | --- | --- | | Passed | 11,913 | Includes the 2 tests and the 54 `dot-runner` tests that passed in a later run, as described below. | | Failed | 7 | The same 7 tests also fail on the commit before the fixes. | | Skipped | 9 | These tests have their own skip conditions: `sentry` 5, and 1 each in `bundled-plugin-registration`, `customer-success-cloud`, `onepassword-connection`, and `workspace-runtime-https-live-exercise`. | The 7 tests that fail with and without this change, on my machine: - 3 tests in `chat-channels` and `email-channels` stop with `ENOENT` on a `SKILL.md` file. The path is in the parent checkout, above the git worktree that I used, so I expect that the worktree is the cause. I did not prove this. - `workspace-instance-cleanup` compares `/private/var/...` with `/var/...`. This is a macOS symlink difference. - 2 tests in `git-reproducible-managed-checkouts` get `unknown_base_git_files` and expect `unpushed_managed_checkout`. I did not find the cause. - 1 more test in `chat-channels`, `materializes direct external-chat finals once`, gets `undefined`. I did not find the cause. CI is the check for these 7 tests. `ci / verify` passed on `eab4dcc1f4`. Failures during this work: - My fix to `agent-runtime-connector-access` changed an invalid permission key in the setup, but not in the assertion. The runtime check found this. I corrected the assertion, and the file passes. - `heartbeat-plugin-environment` failed one wait in the full run. It passed three times alone, so I think that load caused the failure. It can fail again under load. - `dot-runner` skipped all 54 tests in the full run because `cargo` was not on my `PATH`. It then passed 54 of 54 with the toolchain on the `PATH`. - My first `lib` value removed the default DOM types, and the error count went up by 375. I added the DOM libraries. - My Daytona stub with bare `any` left 48 errors, because generic helpers then inferred `unknown`. I added shapes that return promises. - One fix to `agent-secrets-routes` used `class_3_static_lease`, and the test failed. That class allows only specific paths. I reverted to `unclassified`. - `ci / General tests (server (8/12))` failed on `259737b700` because of the flaky port in `idle-completed-history`. paperclipai/paperclip#18853 fixed this test on master, so this pull request keeps that fix. **Audit of the diff.** I counted these patterns in added and removed lines, to find fixes that only hide an error: | Pattern | Added | Removed | | --- | --- | --- | | `@ts-ignore` | 0 | 0 | | `@ts-expect-error` | 0 | 1 | | `.skip` | 0 | 0 | | `as any` | 9 | 9 | | `: any` | 11 | 2 | | `as never` | 8 | 2 | | `as unknown as` | 35 | 4 | | `Promise<unknown>` | 16 | 5 | | `expect(` | 128 | 113 | No hunk removes more `expect(` calls than it adds. Three removals of test content were intentional, and I checked each one: - `muse-control` removed `signalToken`. Line 1012 already asserts that it is absent. - `merged-pr-confirmation-sweep` removed legacy aliases. Other tests cover them. - `heartbeat-workspace-branch-containment` removed a `finalize` branch that no test row can reach. Some partial fixtures stay unchecked through `as unknown as` and `Promise<unknown>`, mostly in `issue-agent-mutation-ownership-routes` and `issue-comment-reopen-routes`. **Accuracy of the check.** One program over the tree and the three shards reported the same errors at the same positions. Memory, as the peak of the largest process on one thread, was 3.93 GiB for one program and 2.43 GiB for the largest shard. I measured these two values before the fixes. Not run or not proven: - I did not run the full `pnpm test:run`, or a root `pnpm build`. I expect CI to run the full suites. - I did not run the 4 GiB container check, or the full `scripts/typecheck-low-memory.mjs`. The peaks above come from macOS, so they are not a Linux cgroup measurement. - I did not run the UI typecheck after the merges. - `workspace-runtime-https-live-exercise` is skipped, so its `cleanup` fix did not run. ## Risks - **A large diff in test files.** 328 files change. A pull request that edits the same tests can get merge conflicts. New tests on master can also add type errors before this merges. Any such error fails this check and needs a fix here. - **A higher cost for changes to source types.** A change to a type can add errors in test files that the author did not touch. The author must then fix them. This is the purpose of the check, but it is new work. - **Changed test behavior.** Some tests now run paths that they did not run before, such as the 9 chat wizard fixtures and the 3 span tests. They pass here, but they can be more sensitive to timing or to the environment. - **The Daytona stub can go stale.** The stub is written by hand. If the plugin uses a new SDK member, the typecheck reports an error until someone updates the stub. - **The release path.** `release-verify.yml` and `scripts/release.sh` run `pnpm -r typecheck`, so they now run this check. - **The tsconfig change.** The test transform reads `server/src/__tests__/tsconfig.json`. The options that I changed are for type checks, and the runs above passed. - **A gap that remains.** Tsconfigs in `packages/paperclip-runner` and in most sandbox provider plugins exclude `*.test.ts`. This check does not read most of those test files, so they can still drift. That work is separate from this pull request. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used Anthropic Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with reasoning, tool use, code execution, and subagents. The runtime does not show the context window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] I have run tests locally and they pass (7 tests fail locally, with and without this change. See Verification.) - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1773 lines
76 KiB
TypeScript
1773 lines
76 KiB
TypeScript
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
|
import { registerCustomImageCleanupWork } from "../services/custom-image-cleanup-work.js";
|
|
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
|
import { idleWorkSnapshot } from "../services/task-admission.js";
|
|
import { randomUUID } from "node:crypto";
|
|
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { desc, eq, sql } from "drizzle-orm";
|
|
import {
|
|
activityLog,
|
|
companies,
|
|
createDb,
|
|
environmentCustomImageSetupSessions,
|
|
environmentCustomImageTemplates,
|
|
environments,
|
|
plugins,
|
|
} from "@paperclipai/db";
|
|
import type { PaperclipPluginManifestV1 } from "@paperclipai/shared";
|
|
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
|
|
import {
|
|
environmentCustomImageService,
|
|
} from "../services/environment-custom-images.js";
|
|
import {
|
|
ENVIRONMENT_CUSTOM_IMAGE_CONFIG_FINGERPRINT_EXCLUDED_PATHS,
|
|
environmentCustomImageTemplateMatchesBaseConfig,
|
|
fingerprintEnvironmentSandboxProviderConfig,
|
|
} from "../services/environment-custom-image-runtime.js";
|
|
import {
|
|
resolveEnvironmentDriverConfigForRuntime,
|
|
} from "../services/environment-config.js";
|
|
import {
|
|
getEmbeddedPostgresTestSupport,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "./helpers/embedded-postgres.js";
|
|
|
|
const externalTestDatabase = resolveExternalTestDatabaseUrl("PAPERCLIP_CUSTOM_IMAGE_TEST_DATABASE_URL");
|
|
const embeddedPostgresSupport = externalTestDatabase ? { supported: true, reason: undefined } : await getEmbeddedPostgresTestSupport();
|
|
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
|
|
|
if (!embeddedPostgresSupport.supported) {
|
|
console.warn(
|
|
`Skipping embedded Postgres environment customImage tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
|
);
|
|
}
|
|
|
|
function pluginManifest() {
|
|
return {
|
|
id: "paperclip.fake-sandbox-provider",
|
|
apiVersion: 1,
|
|
version: "0.1.0",
|
|
displayName: "Fake Sandbox Provider",
|
|
description: "Test fake sandbox provider",
|
|
author: "Paperclip",
|
|
categories: ["automation"],
|
|
capabilities: ["environment.drivers.register"],
|
|
entrypoints: { worker: "./dist/worker.js" },
|
|
environmentDrivers: [
|
|
{
|
|
driverKey: "fake-plugin",
|
|
kind: "sandbox_provider",
|
|
displayName: "Fake Sandbox Provider",
|
|
supportsInteractiveSetup: true,
|
|
interactiveSetupConnectionTypes: ["ssh"],
|
|
supportsTemplateCapture: true,
|
|
templateRefKind: "snapshot",
|
|
templateConfigBinding: {
|
|
field: "customTemplate",
|
|
unsetFields: ["image"],
|
|
},
|
|
templateIdentityPaths: ["apiUrl"],
|
|
supportsTemplateDelete: true,
|
|
configSchema: { type: "object" },
|
|
},
|
|
],
|
|
} satisfies PaperclipPluginManifestV1;
|
|
}
|
|
|
|
const ALL_CUSTOM_IMAGE_WORKER_METHODS = [
|
|
"environmentStartInteractiveSetup",
|
|
"environmentGetInteractiveSetup",
|
|
"environmentCancelInteractiveSetup",
|
|
"environmentCaptureTemplate",
|
|
"environmentDeleteTemplate",
|
|
] as const;
|
|
|
|
function createWorkerManager(options?: { workerMethods?: readonly string[] }) {
|
|
const supportedMethods = options?.workerMethods ?? ALL_CUSTOM_IMAGE_WORKER_METHODS;
|
|
const call = vi.fn(async (_pluginId: string, method: string, params: Record<string, unknown>) => {
|
|
if (method === "environmentInspectLease") return { providerLeaseId: params.providerLeaseId, state: "destroyed" };
|
|
if (method === "environmentStartInteractiveSetup") {
|
|
return {
|
|
providerLeaseId: `lease-${params.sessionId}`,
|
|
status: "waiting_for_user",
|
|
connectionSummary: {
|
|
type: "ssh",
|
|
username: "sandbox",
|
|
hostRedacted: true,
|
|
portRedacted: true,
|
|
},
|
|
connectionPayload: {
|
|
type: "ssh",
|
|
command: "ssh sandbox@203.0.113.10",
|
|
expiresAt: params.expiresAt,
|
|
},
|
|
expiresAt: params.expiresAt,
|
|
metadata: {
|
|
connectUrl: "https://203.0.113.10/setup",
|
|
safeLabel: "setup",
|
|
},
|
|
};
|
|
}
|
|
if (method === "environmentGetInteractiveSetup") {
|
|
return {
|
|
providerLeaseId: params.providerLeaseId,
|
|
status: "waiting_for_user",
|
|
connectionSummary: {
|
|
type: "ssh",
|
|
username: "sandbox",
|
|
hostRedacted: true,
|
|
portRedacted: true,
|
|
},
|
|
connectionPayload: {
|
|
type: "ssh",
|
|
command: "ssh sandbox@203.0.113.10",
|
|
},
|
|
metadata: {
|
|
safeLabel: "setup",
|
|
},
|
|
};
|
|
}
|
|
if (method === "environmentCaptureTemplate") {
|
|
return {
|
|
templateRef: `snapshot-${String(params.providerLeaseId).slice(-8)}`,
|
|
templateKind: "snapshot",
|
|
metadata: {
|
|
provider: "fake-plugin",
|
|
sourceTemplateRefRedacted: Boolean(params.sourceTemplateRef),
|
|
previousTemplateRefRedacted: Boolean(params.previousTemplateRef),
|
|
},
|
|
};
|
|
}
|
|
if (method === "environmentCancelInteractiveSetup") {
|
|
return {
|
|
status: params.reason === "timed_out" ? "timed_out" : "cancelled",
|
|
metadata: { provider: "fake-plugin", found: true },
|
|
};
|
|
}
|
|
if (method === "environmentDeleteTemplate") {
|
|
return { deleted: true, metadata: { provider: "fake-plugin" } };
|
|
}
|
|
throw new Error(`Unexpected plugin call: ${method}`);
|
|
});
|
|
return {
|
|
call,
|
|
isRunning: vi.fn(() => true),
|
|
getWorker: vi.fn(() => ({ supportedMethods: [...supportedMethods] })),
|
|
} as unknown as PluginWorkerManager & { call: typeof call };
|
|
}
|
|
|
|
describeEmbeddedPostgres("environmentCustomImageService", () => {
|
|
let stopDb: (() => Promise<void>) | null = null;
|
|
let db!: ReturnType<typeof createDb>;
|
|
|
|
beforeAll(async () => {
|
|
if (externalTestDatabase) { db = createDb(externalTestDatabase, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); return; }
|
|
const started = await startEmbeddedPostgresTestDatabase("environment-custom-images");
|
|
stopDb = started.cleanup;
|
|
db = createDb(started.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await db.delete(environmentCustomImageSetupSessions);
|
|
await db.delete(environmentCustomImageTemplates);
|
|
await db.delete(plugins);
|
|
await db.delete(environments);
|
|
await db.delete(companies);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await db?.$client.end({ timeout: 1 });
|
|
await stopDb?.();
|
|
});
|
|
|
|
async function seed() {
|
|
const companyId = randomUUID();
|
|
const environmentId = randomUUID();
|
|
await db.insert(companies).values(
|
|
{ id: companyId, name: "Acme", issuePrefix: `A${companyId.slice(0, 4)}` },
|
|
);
|
|
await db.insert(environments).values({
|
|
id: environmentId,
|
|
name: `Fake ${environmentId.slice(0, 8)}`,
|
|
driver: "sandbox",
|
|
status: "active",
|
|
config: {
|
|
provider: "fake-plugin",
|
|
image: "fake:base",
|
|
reuseLease: false,
|
|
},
|
|
envVars: {},
|
|
});
|
|
await db.insert(plugins).values({
|
|
pluginKey: "paperclip.fake-sandbox-provider",
|
|
packageName: "paperclip-plugin-fake-sandbox",
|
|
version: "0.1.0",
|
|
apiVersion: 1,
|
|
categories: ["automation"],
|
|
manifestJson: pluginManifest(),
|
|
status: "ready",
|
|
});
|
|
return { companyId, environmentId };
|
|
}
|
|
|
|
describe("expiry scheduling", () => {
|
|
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
|
|
let service: ReturnType<typeof environmentCustomImageService>;
|
|
let provider: ReturnType<typeof createWorkerManager>;
|
|
let draining: boolean;
|
|
const errors: unknown[] = [];
|
|
|
|
beforeEach(async () => {
|
|
await Promise.all(Array.from({ length: 6 }, () => db.execute(sql`select pg_sleep(0.01)`)));
|
|
draining = false;
|
|
errors.length = 0;
|
|
provider = createWorkerManager();
|
|
service = environmentCustomImageService(db, { pluginWorkerManager: provider });
|
|
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: true });
|
|
});
|
|
afterEach(async () => {
|
|
await coordinator?.stop();
|
|
coordinator = undefined;
|
|
vi.useRealTimers();
|
|
vi.restoreAllMocks();
|
|
expect(errors).toEqual([]);
|
|
});
|
|
async function start() {
|
|
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining,
|
|
canReconcile: () => true, onError: error => errors.push(error) });
|
|
await registerCustomImageCleanupWork(coordinator, service, () => !draining).ready;
|
|
}
|
|
async function settle(ms = 60_000) {
|
|
await vi.advanceTimersByTimeAsync(ms);
|
|
if (!draining) await vi.waitFor(() => expect(idleWorkSnapshot().active === 0 || coordinator!.nextWakeAt() !== null).toBe(true), { timeout: 5000 });
|
|
}
|
|
async function quiet() {
|
|
await settle();
|
|
expect(coordinator!.nextWakeAt()).toBeNull();
|
|
const reads = vi.spyOn(db, "select"), calls = provider.call.mock.calls.length;
|
|
await settle(30 * 60_000);
|
|
expect(reads).not.toHaveBeenCalled();
|
|
expect(provider.call).toHaveBeenCalledTimes(calls);
|
|
reads.mockRestore();
|
|
}
|
|
async function create() {
|
|
const fixture = await seed();
|
|
return service.startSetupSession({ environmentId: fixture.environmentId,
|
|
actor: { userId: "fixture-user" }, ttlSeconds: 3600 });
|
|
}
|
|
const cancellations = () => provider.call.mock.calls.filter(([, method]) => method === "environmentCancelInteractiveSetup");
|
|
|
|
it("is quiet when empty, wakes from the real producer, expires once, and keeps terminal history quiet", async () => {
|
|
await start(); await quiet();
|
|
const created = await create();
|
|
await settle();
|
|
expect(coordinator!.nextWakeAt()).toBe(new Date(created.session.expiresAt!).getTime());
|
|
const reads = vi.spyOn(db, "select");
|
|
await settle(30 * 60_000);
|
|
expect(reads).not.toHaveBeenCalled(); reads.mockRestore();
|
|
expect(cancellations()).toHaveLength(0);
|
|
await settle(30 * 60_000);
|
|
expect(cancellations()).toHaveLength(1);
|
|
expect(await service.getSessionById(created.session.id)).toMatchObject({ status: "timed_out" });
|
|
await quiet();
|
|
});
|
|
|
|
it("honors a committed expiry inside the retry window", async () => {
|
|
await start();
|
|
const created = await create();
|
|
await settle();
|
|
const earlier = new Date(Date.now() + 5_000);
|
|
provider.call.mockResolvedValueOnce({ providerLeaseId: created.session.providerLeaseId,
|
|
status: "waiting_for_user", expiresAt: earlier.toISOString() } as never);
|
|
await service.refreshSetupSession({ sessionId: created.session.id });
|
|
await vi.waitFor(() => expect(coordinator!.nextWakeAt()).toBe(earlier.getTime()));
|
|
expect(cancellations()).toHaveLength(0);
|
|
await settle(Math.max(0, earlier.getTime() - Date.now()));
|
|
await vi.waitFor(() => expect(cancellations()).toHaveLength(1));
|
|
expect(await service.getSessionById(created.session.id)).toMatchObject({ status: "timed_out" });
|
|
await quiet();
|
|
});
|
|
|
|
it("replaces an expiry when the provider moves it earlier and disarms on user cancellation", async () => {
|
|
await start();
|
|
const created = await create(); await settle();
|
|
const earlier = new Date(Date.now() + 5 * 60_000);
|
|
provider.call.mockResolvedValueOnce({ providerLeaseId: created.session.providerLeaseId,
|
|
status: "waiting_for_user", expiresAt: earlier.toISOString() } as never);
|
|
await service.refreshSetupSession({ sessionId: created.session.id });
|
|
await settle();
|
|
expect(coordinator!.nextWakeAt()).toBe(earlier.getTime());
|
|
await service.cancelSetupSession({ sessionId: created.session.id });
|
|
await quiet();
|
|
expect(cancellations()).toHaveLength(1);
|
|
});
|
|
|
|
it.each([false, true])("waits for the producer's outer transaction (rollback %s)", async rollback => {
|
|
const fixture = await seed(); await start(); await quiet();
|
|
let release!: () => void, written!: () => void;
|
|
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
const staged = new Promise<void>(resolve => { written = resolve; });
|
|
const writing = db.transaction(async tx => {
|
|
const scoped = environmentCustomImageService(tx as unknown as typeof db, { pluginWorkerManager: provider });
|
|
await scoped.startSetupSession({ environmentId: fixture.environmentId, actor: { userId: "fixture-user" }, ttlSeconds: 1 });
|
|
written(); await gate;
|
|
if (rollback) throw new Error("rollback fixture");
|
|
}).catch(error => { if (!rollback) throw error; });
|
|
await staged;
|
|
try {
|
|
await vi.advanceTimersByTimeAsync(60_000);
|
|
expect(cancellations()).toHaveLength(0);
|
|
} finally { release(); }
|
|
await writing; await settle();
|
|
expect(cancellations()).toHaveLength(rollback ? 0 : 1);
|
|
await quiet();
|
|
});
|
|
|
|
it("retains a producer commit that arrives during the deadline read", async () => {
|
|
await start(); const created = await create(); await settle();
|
|
await coordinator!.stop();
|
|
let release!: () => void, reading!: () => void;
|
|
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
const entered = new Promise<void>(resolve => { reading = resolve; });
|
|
const readDeadline = service.nextSetupCleanupAt;
|
|
vi.spyOn(service, "nextSetupCleanupAt").mockImplementationOnce(async () => {
|
|
const stale = await readDeadline();
|
|
reading(); await gate;
|
|
return stale;
|
|
});
|
|
const starting = start();
|
|
await entered;
|
|
const earlier = new Date(Date.now() + 5 * 60_000);
|
|
try {
|
|
provider.call.mockResolvedValueOnce({ providerLeaseId: created.session.providerLeaseId,
|
|
status: "waiting_for_user", expiresAt: earlier.toISOString() } as never);
|
|
await service.refreshSetupSession({ sessionId: created.session.id });
|
|
} finally { release(); }
|
|
await starting; await settle();
|
|
await vi.waitFor(() => expect(coordinator!.nextWakeAt()).toBe(earlier.getTime()));
|
|
await settle(5 * 60_000);
|
|
await vi.waitFor(() => expect(cancellations()).toHaveLength(1));
|
|
await quiet();
|
|
});
|
|
|
|
it("reconstructs a saved expiry after restart", async () => {
|
|
await start(); const created = await create(); await settle();
|
|
await coordinator!.stop();
|
|
await start();
|
|
expect(coordinator!.nextWakeAt()).toBe(new Date(created.session.expiresAt!).getTime());
|
|
await settle(60 * 60_000);
|
|
expect(cancellations()).toHaveLength(1); await quiet();
|
|
});
|
|
|
|
it.each(["startup", "first_write", "failed_pass"])("retains %s work through drain without passive SQL", async mode => {
|
|
if (mode === "startup") draining = true;
|
|
await start();
|
|
if (mode === "first_write") { await quiet(); draining = true; }
|
|
await create();
|
|
if (mode === "failed_pass") {
|
|
vi.spyOn(service, "nextSetupCleanupAt").mockRejectedValueOnce(new Error("database unavailable"));
|
|
await settle(30_000);
|
|
await vi.waitFor(() => expect(errors).toHaveLength(1)); errors.length = 0;
|
|
draining = true;
|
|
}
|
|
await settle();
|
|
const reads = vi.spyOn(db, "select");
|
|
await settle(2 * 60 * 60_000);
|
|
expect(reads).not.toHaveBeenCalled(); reads.mockRestore();
|
|
expect(cancellations()).toHaveLength(0);
|
|
draining = false; await settle();
|
|
expect(cancellations()).toHaveLength(1); await quiet();
|
|
});
|
|
});
|
|
|
|
it.each(["supported", "old_worker", "changed_config"])("inspects historical setup read-only with exact config and capability gates: %s", async mode => {
|
|
const fixture = await seed();
|
|
const worker = createWorkerManager({ workerMethods: [...ALL_CUSTOM_IMAGE_WORKER_METHODS,
|
|
...(mode === "old_worker" ? [] : ["environmentInspectLease"])] });
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: worker });
|
|
const created = await service.startSetupSession({ environmentId: fixture.environmentId,
|
|
actor: { userId: "fixture-user" }, now: new Date("2099-01-01T00:00:00Z") });
|
|
await service.cancelSetupSession({ sessionId: created.session.id });
|
|
const [session] = await db.select().from(environmentCustomImageSetupSessions).where(eq(environmentCustomImageSetupSessions.id, created.session.id));
|
|
expect(session!.metadata).toMatchObject({ setupRpcCompanyId: created.session.metadata!.setupRpcCompanyId,
|
|
sourceEnvironmentConfigFingerprint: created.session.metadata!.sourceEnvironmentConfigFingerprint });
|
|
if (mode === "changed_config") await db.update(environments).set({ config: { provider: "fake-plugin", image: "replacement:base" } }).where(eq(environments.id, fixture.environmentId));
|
|
worker.call.mockClear();
|
|
const observed = await service.inspectSetupResource(session!);
|
|
if (mode === "supported") {
|
|
expect(observed).toEqual({ providerLeaseId: session!.providerLeaseId, state: "destroyed" });
|
|
expect(worker.call).toHaveBeenCalledExactlyOnceWith(expect.any(String), "environmentInspectLease", expect.objectContaining({
|
|
companyId: session!.metadata!.setupRpcCompanyId, providerLeaseId: session!.providerLeaseId,
|
|
}), 15_000);
|
|
} else { expect(observed).toBeUndefined(); expect(worker.call).not.toHaveBeenCalled(); }
|
|
});
|
|
|
|
it("starts, refreshes, finishes, refreshes again, and rolls back setup sessions", async () => {
|
|
const { environmentId } = await seed();
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
ttlSeconds: 600,
|
|
});
|
|
|
|
expect(started.session.status).toBe("waiting_for_user");
|
|
expect(started.connectionPayload?.command).toContain("203.0.113.10");
|
|
expect(JSON.stringify(started.session.metadata)).not.toContain("203.0.113.10");
|
|
|
|
const status = await service.refreshSetupSession({
|
|
sessionId: started.session.id,
|
|
includeConnectionPayload: true,
|
|
});
|
|
expect(status.connectionPayload?.command).toContain("ssh sandbox@203.0.113.10");
|
|
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
expect(promoted.session.status).toBe("promoted");
|
|
expect(promoted.template.status).toBe("active");
|
|
expect(promoted.template.templateKind).toBe("snapshot");
|
|
expect(promoted.template.metadata).toMatchObject({
|
|
runtimeConfigBinding: {
|
|
field: "customTemplate",
|
|
unsetFields: ["image"],
|
|
},
|
|
});
|
|
|
|
const refresh = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
});
|
|
const replacement = await service.finishSetupSession({ sessionId: refresh.session.id });
|
|
expect(replacement.template.id).not.toBe(promoted.template.id);
|
|
|
|
const rollback = await service.rollbackTemplate({ environmentId });
|
|
expect(rollback.activeTemplate.id).toBe(promoted.template.id);
|
|
expect(rollback.supersededTemplate.id).toBe(replacement.template.id);
|
|
});
|
|
|
|
it("reuses the setup provider company context across lifecycle calls", async () => {
|
|
const { companyId, environmentId } = await seed();
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
secretContextCompanyId: companyId,
|
|
});
|
|
expect(started.session.metadata).toMatchObject({
|
|
setupRpcCompanyId: companyId,
|
|
});
|
|
|
|
await service.refreshSetupSession({
|
|
sessionId: started.session.id,
|
|
includeConnectionPayload: true,
|
|
});
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
const lifecycleCalls = workerManager.call.mock.calls
|
|
.filter(([, method]) => [
|
|
"environmentStartInteractiveSetup",
|
|
"environmentGetInteractiveSetup",
|
|
"environmentCaptureTemplate",
|
|
"environmentCancelInteractiveSetup",
|
|
].includes(method))
|
|
.map(([, method, params]) => ({
|
|
method,
|
|
companyId: (params as Record<string, unknown>).companyId,
|
|
}));
|
|
|
|
expect(lifecycleCalls).toEqual([
|
|
{ method: "environmentStartInteractiveSetup", companyId },
|
|
{ method: "environmentGetInteractiveSetup", companyId },
|
|
{ method: "environmentCaptureTemplate", companyId },
|
|
{ method: "environmentCancelInteractiveSetup", companyId },
|
|
]);
|
|
expect(promoted.session.metadata).toMatchObject({
|
|
setupRpcCompanyId: companyId,
|
|
});
|
|
expect(promoted.template.metadata).toMatchObject({
|
|
setupRpcCompanyId: companyId,
|
|
});
|
|
});
|
|
|
|
it("revokes the active template before deleting the provider template", async () => {
|
|
const { environmentId } = await seed();
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
});
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
let statusAtProviderDelete: string | null = null;
|
|
workerManager.call.mockImplementation(async (_pluginId, method) => {
|
|
if (method !== "environmentDeleteTemplate") {
|
|
throw new Error(`Unexpected plugin call after setup: ${method}`);
|
|
}
|
|
const [row] = await db
|
|
.select({ status: environmentCustomImageTemplates.status })
|
|
.from(environmentCustomImageTemplates)
|
|
.where(eq(environmentCustomImageTemplates.id, promoted.template.id));
|
|
statusAtProviderDelete = row?.status ?? null;
|
|
return { deleted: true, metadata: { provider: "fake-plugin" } };
|
|
});
|
|
|
|
const disabled = await service.disableTemplate({
|
|
environmentId,
|
|
deleteProviderTemplate: true,
|
|
});
|
|
|
|
expect(disabled.status).toBe("revoked");
|
|
expect(statusAtProviderDelete).toBe("revoked");
|
|
expect(workerManager.call).toHaveBeenLastCalledWith(
|
|
expect.any(String),
|
|
"environmentDeleteTemplate",
|
|
expect.objectContaining({
|
|
templateRef: promoted.template.templateRef,
|
|
reason: "disabled",
|
|
}),
|
|
undefined,
|
|
);
|
|
});
|
|
|
|
it("does not send provider template refs to a different current provider", async () => {
|
|
const { environmentId } = await seed();
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
});
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
const deleteCallsBefore = workerManager.call.mock.calls
|
|
.filter(([, method]) => method === "environmentDeleteTemplate")
|
|
.length;
|
|
|
|
await db.update(environments)
|
|
.set({
|
|
config: {
|
|
provider: "other-plugin",
|
|
image: "other:base",
|
|
reuseLease: false,
|
|
},
|
|
})
|
|
.where(eq(environments.id, environmentId));
|
|
|
|
await expect(service.disableTemplate({
|
|
environmentId,
|
|
deleteProviderTemplate: true,
|
|
})).rejects.toThrow("Environment customImage provider changed");
|
|
|
|
const deleteCallsAfter = workerManager.call.mock.calls
|
|
.filter(([, method]) => method === "environmentDeleteTemplate")
|
|
.length;
|
|
const [templateRow] = await db
|
|
.select({ status: environmentCustomImageTemplates.status })
|
|
.from(environmentCustomImageTemplates)
|
|
.where(eq(environmentCustomImageTemplates.id, promoted.template.id));
|
|
|
|
expect(deleteCallsAfter).toBe(deleteCallsBefore);
|
|
expect(templateRow?.status).toBe("active");
|
|
});
|
|
|
|
it("cancels and times out setup sessions without changing the active template", async () => {
|
|
const { environmentId } = await seed();
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
});
|
|
const cancelled = await service.cancelSetupSession({
|
|
sessionId: started.session.id,
|
|
reason: "user_cancelled",
|
|
});
|
|
expect(cancelled.status).toBe("cancelled");
|
|
expect(cancelled.metadata).toMatchObject({ setupRpcCompanyId: started.session.metadata!.setupRpcCompanyId,
|
|
sourceEnvironmentConfigFingerprint: started.session.metadata!.sourceEnvironmentConfigFingerprint });
|
|
expect(await service.getActiveTemplate({ environmentId })).toBeNull();
|
|
|
|
const expired = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
ttlSeconds: 60,
|
|
now: new Date("2026-06-25T00:00:00.000Z"),
|
|
});
|
|
const cleanup = await service.cleanupExpiredSetupSessions({
|
|
now: new Date("2026-06-25T00:02:00.000Z"),
|
|
});
|
|
expect(cleanup).toMatchObject({ scanned: 1, timedOut: 1, failed: 0 });
|
|
const timedOut = await service.getSessionById(expired.session.id);
|
|
expect(timedOut?.status).toBe("timed_out");
|
|
expect(timedOut?.metadata).toMatchObject({ setupRpcCompanyId: expired.session.metadata!.setupRpcCompanyId,
|
|
sourceEnvironmentConfigFingerprint: expired.session.metadata!.sourceEnvironmentConfigFingerprint });
|
|
});
|
|
|
|
it("rejects interactive setup when the provider declares it but the worker omits a setup method", async () => {
|
|
const { environmentId } = await seed();
|
|
// The manifest declares supportsInteractiveSetup, but the worker reports
|
|
// none of the three setup methods. The gate must name the first missing one.
|
|
const workerManager = createWorkerManager({
|
|
workerMethods: ["environmentCaptureTemplate", "environmentDeleteTemplate"],
|
|
});
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
await expect(service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
})).rejects.toThrow('does not report the "environmentStartInteractiveSetup" method');
|
|
expect(workerManager.call).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects template capture when the provider declares it but the worker omits the capture method", async () => {
|
|
const { environmentId } = await seed();
|
|
// The worker reports every setup method, so the session starts and
|
|
// finishes the interactive part. It omits environmentCaptureTemplate, so
|
|
// finishing the session must fail at the capture gate.
|
|
const workerManager = createWorkerManager({
|
|
workerMethods: [
|
|
"environmentStartInteractiveSetup",
|
|
"environmentGetInteractiveSetup",
|
|
"environmentCancelInteractiveSetup",
|
|
"environmentDeleteTemplate",
|
|
],
|
|
});
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
});
|
|
await expect(service.finishSetupSession({ sessionId: started.session.id }))
|
|
.rejects.toThrow('does not report the "environmentCaptureTemplate" method');
|
|
});
|
|
|
|
it("rejects template deletion when the provider declares it but the worker omits the delete method", async () => {
|
|
const { environmentId } = await seed();
|
|
// The worker reports every setup and capture method but omits
|
|
// environmentDeleteTemplate, so a delete-on-disable request must fail at
|
|
// the delete gate after the template is already captured.
|
|
const workerManager = createWorkerManager({
|
|
workerMethods: [
|
|
"environmentStartInteractiveSetup",
|
|
"environmentGetInteractiveSetup",
|
|
"environmentCancelInteractiveSetup",
|
|
"environmentCaptureTemplate",
|
|
],
|
|
});
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
});
|
|
await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
await expect(service.disableTemplate({
|
|
environmentId,
|
|
deleteProviderTemplate: true,
|
|
})).rejects.toThrow('does not report the "environmentDeleteTemplate" method');
|
|
});
|
|
|
|
it("passes every gate when the provider declares each flag and the worker reports every matching method", async () => {
|
|
const { environmentId } = await seed();
|
|
// The default worker manager reports all five methods, matching every
|
|
// flag the manifest declares. Every gate must pass.
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
});
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
expect(promoted.template.status).toBe("active");
|
|
|
|
const disabled = await service.disableTemplate({
|
|
environmentId,
|
|
deleteProviderTemplate: true,
|
|
});
|
|
expect(disabled.status).toBe("revoked");
|
|
expect(workerManager.call).toHaveBeenCalledWith(
|
|
expect.any(String),
|
|
"environmentDeleteTemplate",
|
|
expect.any(Object),
|
|
undefined,
|
|
);
|
|
});
|
|
|
|
it("rejects templates from another environment", async () => {
|
|
const { environmentId } = await seed();
|
|
const otherEnvironmentId = randomUUID();
|
|
await db.insert(environments).values({
|
|
id: otherEnvironmentId,
|
|
name: `Other ${otherEnvironmentId.slice(0, 8)}`,
|
|
driver: "sandbox",
|
|
status: "active",
|
|
config: {
|
|
provider: "fake-plugin",
|
|
image: "fake:base",
|
|
reuseLease: false,
|
|
},
|
|
envVars: {},
|
|
});
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
const [otherTemplate] = await db.insert(environmentCustomImageTemplates).values({
|
|
environmentId: otherEnvironmentId,
|
|
provider: "fake-plugin",
|
|
templateKind: "snapshot",
|
|
templateRef: "snapshot-other-environment",
|
|
status: "active",
|
|
}).returning();
|
|
|
|
await expect(service.startSetupSession({
|
|
environmentId,
|
|
templateId: otherTemplate!.id,
|
|
actor: { userId: "user-1" },
|
|
})).rejects.toThrow("Setup template must be the active template");
|
|
});
|
|
|
|
it("applies the active template regardless of base-config changes and falls back when none exists", async () => {
|
|
const { companyId, environmentId } = await seed();
|
|
const environment = await db.select().from(environments).where(eq(environments.id, environmentId)).then((rows) => rows[0]!);
|
|
|
|
const fallback = await resolveEnvironmentDriverConfigForRuntime(db, companyId, {
|
|
id: environment.id,
|
|
driver: "sandbox",
|
|
config: environment.config,
|
|
}, { heartbeatRunId: randomUUID() });
|
|
expect(fallback.driver).toBe("sandbox");
|
|
expect(fallback.config).toMatchObject({ image: "fake:base" });
|
|
|
|
await db.insert(environmentCustomImageTemplates).values({
|
|
environmentId,
|
|
provider: "fake-plugin",
|
|
templateKind: "snapshot",
|
|
templateRef: "snapshot-active",
|
|
sourceEnvironmentConfigFingerprint: fingerprintEnvironmentSandboxProviderConfig(environment.config as any, {
|
|
excludePaths: ENVIRONMENT_CUSTOM_IMAGE_CONFIG_FINGERPRINT_EXCLUDED_PATHS,
|
|
}),
|
|
status: "active",
|
|
});
|
|
const resolved = await resolveEnvironmentDriverConfigForRuntime(db, companyId, {
|
|
id: environment.id,
|
|
driver: "sandbox",
|
|
config: environment.config,
|
|
}, { heartbeatRunId: randomUUID() });
|
|
expect(resolved.driver).toBe("sandbox");
|
|
expect(resolved.config).toMatchObject({ snapshot: "snapshot-active" });
|
|
expect(resolved.config).not.toHaveProperty("image");
|
|
|
|
// Runtime-only resource/lease edits must NOT silently discard the captured
|
|
// template.
|
|
await db.update(environments)
|
|
.set({
|
|
config: {
|
|
...(environment.config as Record<string, unknown>),
|
|
cpu: 4,
|
|
timeoutMs: 600000,
|
|
reuseLease: true,
|
|
},
|
|
})
|
|
.where(eq(environments.id, environment.id));
|
|
const afterResourceChangeEnvironment = await db.select().from(environments).where(eq(environments.id, environmentId)).then((rows) => rows[0]!);
|
|
const afterResourceChange = await resolveEnvironmentDriverConfigForRuntime(db, companyId, {
|
|
id: afterResourceChangeEnvironment.id,
|
|
driver: "sandbox",
|
|
config: afterResourceChangeEnvironment.config,
|
|
}, { heartbeatRunId: randomUUID() });
|
|
expect(afterResourceChange.driver).toBe("sandbox");
|
|
expect(afterResourceChange.config).toMatchObject({ snapshot: "snapshot-active" });
|
|
expect(afterResourceChange.config).not.toHaveProperty("image");
|
|
|
|
// Changing the base image is a meaningful source-template change. In that
|
|
// case, the old capture must not mask the newly saved image.
|
|
await db.update(environmentCustomImageTemplates)
|
|
.set({
|
|
sourceEnvironmentConfigFingerprint: fingerprintEnvironmentSandboxProviderConfig(environment.config as any, {
|
|
excludePaths: ENVIRONMENT_CUSTOM_IMAGE_CONFIG_FINGERPRINT_EXCLUDED_PATHS,
|
|
}),
|
|
})
|
|
.where(eq(environmentCustomImageTemplates.templateRef, "snapshot-active"));
|
|
await db.update(environments)
|
|
.set({
|
|
config: {
|
|
...(environment.config as Record<string, unknown>),
|
|
image: "fake:new-base",
|
|
},
|
|
})
|
|
.where(eq(environments.id, environment.id));
|
|
const afterImageChangeEnvironment = await db.select().from(environments).where(eq(environments.id, environmentId)).then((rows) => rows[0]!);
|
|
const afterImageChange = await resolveEnvironmentDriverConfigForRuntime(db, companyId, {
|
|
id: afterImageChangeEnvironment.id,
|
|
driver: "sandbox",
|
|
config: afterImageChangeEnvironment.config,
|
|
}, { heartbeatRunId: randomUUID() });
|
|
expect(afterImageChange.driver).toBe("sandbox");
|
|
expect(afterImageChange.config).toMatchObject({ image: "fake:new-base" });
|
|
expect(afterImageChange.config).not.toHaveProperty("snapshot");
|
|
});
|
|
|
|
it("applies the active template for ad-hoc Test probes only when applyCustomImageTemplate is set", async () => {
|
|
const { companyId, environmentId } = await seed();
|
|
const environment = await db.select().from(environments).where(eq(environments.id, environmentId)).then((rows) => rows[0]!);
|
|
|
|
await db.insert(environmentCustomImageTemplates).values({
|
|
environmentId,
|
|
provider: "fake-plugin",
|
|
templateKind: "snapshot",
|
|
templateRef: "snapshot-active",
|
|
status: "active",
|
|
});
|
|
|
|
// No issueId/heartbeatRunId and no opt-in: an operator Test probe would
|
|
// otherwise silently boot the base image instead of the captured template.
|
|
const withoutOptIn = await resolveEnvironmentDriverConfigForRuntime(db, companyId, {
|
|
id: environment.id,
|
|
driver: "sandbox",
|
|
config: environment.config,
|
|
});
|
|
expect(withoutOptIn.config).toMatchObject({ image: "fake:base" });
|
|
expect(withoutOptIn.config).not.toHaveProperty("snapshot");
|
|
|
|
// The Test route opts in explicitly so the probe uses the captured image.
|
|
const withOptIn = await resolveEnvironmentDriverConfigForRuntime(db, companyId, {
|
|
id: environment.id,
|
|
driver: "sandbox",
|
|
config: environment.config,
|
|
}, { applyCustomImageTemplate: true });
|
|
expect(withOptIn.config).toMatchObject({ snapshot: "snapshot-active" });
|
|
expect(withOptIn.config).not.toHaveProperty("image");
|
|
});
|
|
|
|
it("applies provider-declared runtime config bindings for captured templates", async () => {
|
|
const { companyId, environmentId } = await seed();
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({
|
|
environmentId,
|
|
actor: { userId: "user-1" },
|
|
});
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
const environment = await db.select().from(environments).where(eq(environments.id, environmentId)).then((rows) => rows[0]!);
|
|
const resolved = await resolveEnvironmentDriverConfigForRuntime(db, companyId, {
|
|
id: environment.id,
|
|
driver: "sandbox",
|
|
config: environment.config,
|
|
}, { heartbeatRunId: randomUUID() });
|
|
|
|
expect(promoted.template.metadata).toMatchObject({
|
|
runtimeConfigBinding: {
|
|
field: "customTemplate",
|
|
unsetFields: ["image"],
|
|
},
|
|
});
|
|
expect(resolved.driver).toBe("sandbox");
|
|
expect(resolved.config).toMatchObject({ customTemplate: promoted.template.templateRef });
|
|
expect(resolved.config).not.toHaveProperty("image");
|
|
expect(resolved.config).not.toHaveProperty("snapshot");
|
|
});
|
|
});
|
|
|
|
describe("fingerprintEnvironmentSandboxProviderConfig", () => {
|
|
it("ignores excluded secret-ref paths so secretizing a credential on save keeps the fingerprint stable", () => {
|
|
// Mirrors the real flow: a template is captured before "Save Environment"
|
|
// rewrites the raw apiKey into a secret ref. Excluding the secret path must
|
|
// keep the capture-time and run-time fingerprints equal.
|
|
const rawCredential = {
|
|
provider: "daytona",
|
|
image: "daytonaio/sandbox:0.8.0",
|
|
apiKey: "raw-api-key-value",
|
|
} as any;
|
|
const secretRefCredential = {
|
|
provider: "daytona",
|
|
image: "daytonaio/sandbox:0.8.0",
|
|
apiKey: "0d9a7b0e-a3ba-4605-8a68-eb230d494e98",
|
|
} as any;
|
|
|
|
const exclude = { excludePaths: ["apiKey"] };
|
|
expect(fingerprintEnvironmentSandboxProviderConfig(rawCredential, exclude)).toBe(
|
|
fingerprintEnvironmentSandboxProviderConfig(secretRefCredential, exclude),
|
|
);
|
|
|
|
// Without exclusion the credential change would (incorrectly) invalidate the template.
|
|
expect(fingerprintEnvironmentSandboxProviderConfig(rawCredential)).not.toBe(
|
|
fingerprintEnvironmentSandboxProviderConfig(secretRefCredential),
|
|
);
|
|
|
|
// A meaningful base change (e.g. switching the base image) still changes the fingerprint.
|
|
expect(fingerprintEnvironmentSandboxProviderConfig(rawCredential, exclude)).not.toBe(
|
|
fingerprintEnvironmentSandboxProviderConfig(
|
|
{ ...rawCredential, image: "daytonaio/sandbox:0.9.0" } as any,
|
|
exclude,
|
|
),
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("environmentCustomImageTemplateMatchesBaseConfig", () => {
|
|
it("keeps captures across runtime-only edits but not base image changes", () => {
|
|
const baseConfig = {
|
|
provider: "daytona",
|
|
image: "daytonaio/sandbox:0.8.0",
|
|
timeoutMs: 300000,
|
|
reuseLease: false,
|
|
} as any;
|
|
const template = {
|
|
id: "template-1",
|
|
environmentId: "env-1",
|
|
provider: "daytona",
|
|
templateKind: "snapshot",
|
|
templateRef: "snapshot-active",
|
|
sourceTemplateRef: "daytonaio/sandbox:0.8.0",
|
|
sourceEnvironmentConfigFingerprint: fingerprintEnvironmentSandboxProviderConfig(baseConfig, {
|
|
excludePaths: ENVIRONMENT_CUSTOM_IMAGE_CONFIG_FINGERPRINT_EXCLUDED_PATHS,
|
|
}),
|
|
status: "active",
|
|
createdByUserId: null,
|
|
createdByAgentId: null,
|
|
capturedAt: null,
|
|
lastUsedAt: null,
|
|
supersededByTemplateId: null,
|
|
metadata: null,
|
|
createdAt: new Date("2026-07-09T00:00:00.000Z"),
|
|
updatedAt: new Date("2026-07-09T00:00:00.000Z"),
|
|
} as const;
|
|
|
|
expect(environmentCustomImageTemplateMatchesBaseConfig({
|
|
template,
|
|
baseConfig: {
|
|
...baseConfig,
|
|
timeoutMs: 600000,
|
|
reuseLease: true,
|
|
cpu: 4,
|
|
},
|
|
})).toBe(true);
|
|
expect(environmentCustomImageTemplateMatchesBaseConfig({
|
|
template,
|
|
baseConfig: {
|
|
...baseConfig,
|
|
image: "daytonaio/sandbox:0.9.0",
|
|
},
|
|
})).toBe(false);
|
|
});
|
|
|
|
it("matches configs carrying a secret-ref credential when the capture excluded that path", () => {
|
|
// Capture-time fingerprints exclude the provider's secret-ref paths (e.g.
|
|
// daytona apiKey). The runtime re-check must exclude the same paths or a
|
|
// config with any credential never matches and the template is dropped.
|
|
const baseConfig = {
|
|
provider: "daytona",
|
|
image: "daytonaio/sandbox:0.8.0",
|
|
apiKey: "raw-api-key-value",
|
|
} as any;
|
|
const template = {
|
|
id: "template-1",
|
|
environmentId: "env-1",
|
|
provider: "daytona",
|
|
templateKind: "snapshot",
|
|
templateRef: "snapshot-active",
|
|
sourceTemplateRef: "daytonaio/sandbox:0.8.0",
|
|
sourceEnvironmentConfigFingerprint: fingerprintEnvironmentSandboxProviderConfig(baseConfig, {
|
|
excludePaths: [
|
|
...ENVIRONMENT_CUSTOM_IMAGE_CONFIG_FINGERPRINT_EXCLUDED_PATHS,
|
|
"apiKey",
|
|
],
|
|
}),
|
|
status: "active",
|
|
createdByUserId: null,
|
|
createdByAgentId: null,
|
|
capturedAt: null,
|
|
lastUsedAt: null,
|
|
supersededByTemplateId: null,
|
|
metadata: null,
|
|
createdAt: new Date("2026-07-09T00:00:00.000Z"),
|
|
updatedAt: new Date("2026-07-09T00:00:00.000Z"),
|
|
} as const;
|
|
|
|
expect(environmentCustomImageTemplateMatchesBaseConfig({
|
|
template,
|
|
baseConfig,
|
|
secretRefExcludePaths: ["apiKey"],
|
|
})).toBe(true);
|
|
// A rotated credential still matches — credentials are not part of the
|
|
// captured image identity.
|
|
expect(environmentCustomImageTemplateMatchesBaseConfig({
|
|
template,
|
|
baseConfig: { ...baseConfig, apiKey: "rotated-key" },
|
|
secretRefExcludePaths: ["apiKey"],
|
|
})).toBe(true);
|
|
// Without the exclusion the same config fails to match (the pre-fix bug).
|
|
expect(environmentCustomImageTemplateMatchesBaseConfig({
|
|
template,
|
|
baseConfig,
|
|
})).toBe(false);
|
|
});
|
|
});
|
|
|
|
describeEmbeddedPostgres("environmentCustomImageService reconciliation", () => {
|
|
let stopDb: (() => Promise<void>) | null = null;
|
|
let db!: ReturnType<typeof createDb>;
|
|
|
|
beforeAll(async () => {
|
|
if (externalTestDatabase) { db = createDb(externalTestDatabase, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); return; }
|
|
const started = await startEmbeddedPostgresTestDatabase("environment-custom-images-reconcile");
|
|
stopDb = started.cleanup;
|
|
db = createDb(started.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await db.delete(environmentCustomImageSetupSessions);
|
|
await db.delete(environmentCustomImageTemplates);
|
|
await db.delete(plugins);
|
|
await db.delete(environments);
|
|
await db.delete(companies);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await db?.$client.end({ timeout: 1 });
|
|
await stopDb?.();
|
|
});
|
|
|
|
async function seed() {
|
|
const companyId = randomUUID();
|
|
const environmentId = randomUUID();
|
|
await db.insert(companies).values(
|
|
{ id: companyId, name: "Acme", issuePrefix: `A${companyId.slice(0, 4)}` },
|
|
);
|
|
await db.insert(environments).values({
|
|
id: environmentId,
|
|
name: `Fake ${environmentId.slice(0, 8)}`,
|
|
driver: "sandbox",
|
|
status: "active",
|
|
config: {
|
|
provider: "fake-plugin",
|
|
image: "fake:base",
|
|
reuseLease: false,
|
|
},
|
|
envVars: {},
|
|
});
|
|
await db.insert(plugins).values({
|
|
pluginKey: "paperclip.fake-sandbox-provider",
|
|
packageName: "paperclip-plugin-fake-sandbox",
|
|
version: "0.1.0",
|
|
apiVersion: 1,
|
|
categories: ["automation"],
|
|
manifestJson: pluginManifest(),
|
|
status: "ready",
|
|
});
|
|
return { companyId, environmentId };
|
|
}
|
|
|
|
it("re-links the active template on save when only non-identity fields change", async () => {
|
|
const { companyId, environmentId } = await seed();
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
const baseConfig = { provider: "fake-plugin", image: "fake:base", reuseLease: false };
|
|
const nextConfig = { ...baseConfig, region: "eu-west" };
|
|
|
|
const relinked = await service.reconcileActiveTemplateForConfigChange({
|
|
environmentId,
|
|
previous: { driver: "sandbox", config: baseConfig },
|
|
next: { driver: "sandbox", config: nextConfig },
|
|
});
|
|
expect(relinked.action).toBe("relinked");
|
|
if (relinked.action !== "relinked") throw new Error("expected relink");
|
|
expect(relinked.template.sourceEnvironmentConfigFingerprint)
|
|
.not.toBe(promoted.template.sourceEnvironmentConfigFingerprint);
|
|
|
|
// Re-running with the same configs is a no-op: the template already
|
|
// matches the new config.
|
|
const repeat = await service.reconcileActiveTemplateForConfigChange({
|
|
environmentId,
|
|
previous: { driver: "sandbox", config: baseConfig },
|
|
next: { driver: "sandbox", config: nextConfig },
|
|
});
|
|
expect(repeat.action).toBe("none");
|
|
|
|
// The captured template keeps applying at runtime under the new config.
|
|
await db.update(environments)
|
|
.set({ config: nextConfig })
|
|
.where(eq(environments.id, environmentId));
|
|
const resolved = await resolveEnvironmentDriverConfigForRuntime(db, companyId, {
|
|
id: environmentId,
|
|
driver: "sandbox",
|
|
config: nextConfig,
|
|
}, { heartbeatRunId: randomUUID() });
|
|
expect(resolved.driver).toBe("sandbox");
|
|
expect(resolved.config).toMatchObject({ customTemplate: promoted.template.templateRef });
|
|
expect(resolved.config).not.toHaveProperty("image");
|
|
});
|
|
|
|
it("reports detached on save when a boot-source or provider identity field changes", async () => {
|
|
const { environmentId } = await seed();
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
const baseConfig = { provider: "fake-plugin", image: "fake:base", reuseLease: false };
|
|
|
|
// Base image change: the user asked for a different base, so the capture
|
|
// cannot be re-linked.
|
|
const imageChange = await service.reconcileActiveTemplateForConfigChange({
|
|
environmentId,
|
|
previous: { driver: "sandbox", config: baseConfig },
|
|
next: { driver: "sandbox", config: { ...baseConfig, image: "fake:other" } },
|
|
});
|
|
expect(imageChange.action).toBe("detached");
|
|
|
|
// Provider-declared identity path change (apiUrl): captured templates do
|
|
// not exist on a different provider endpoint.
|
|
const endpointChange = await service.reconcileActiveTemplateForConfigChange({
|
|
environmentId,
|
|
previous: { driver: "sandbox", config: baseConfig },
|
|
next: { driver: "sandbox", config: { ...baseConfig, apiUrl: "https://other.example" } },
|
|
});
|
|
expect(endpointChange.action).toBe("detached");
|
|
|
|
// Binding-field change counts as a boot-source change too.
|
|
const bindingChange = await service.reconcileActiveTemplateForConfigChange({
|
|
environmentId,
|
|
previous: { driver: "sandbox", config: baseConfig },
|
|
next: { driver: "sandbox", config: { ...baseConfig, customTemplate: "someone-elses-snapshot" } },
|
|
});
|
|
expect(bindingChange.action).toBe("detached");
|
|
|
|
// Detach never mutates the stored fingerprint; rollback/disable stay
|
|
// available and the old config still matches.
|
|
const template = await service.getActiveTemplate({ environmentId, provider: "fake-plugin" });
|
|
expect(template?.sourceEnvironmentConfigFingerprint)
|
|
.toBe(promoted.template.sourceEnvironmentConfigFingerprint);
|
|
|
|
// A template that was already detached before the save is left alone.
|
|
const alreadyDetached = await service.reconcileActiveTemplateForConfigChange({
|
|
environmentId,
|
|
previous: { driver: "sandbox", config: { ...baseConfig, image: "fake:unrelated" } },
|
|
next: { driver: "sandbox", config: { ...baseConfig, image: "fake:unrelated", region: "eu" } },
|
|
});
|
|
expect(alreadyDetached.action).toBe("none");
|
|
});
|
|
|
|
it("reports whether the active template matches the saved config in the overview", async () => {
|
|
const { environmentId } = await seed();
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
const inSync = await service.getOverview({ environmentId });
|
|
expect(inSync.activeTemplateMatchesConfig).toBe(true);
|
|
|
|
await db.update(environments)
|
|
.set({ config: { provider: "fake-plugin", image: "fake:other", reuseLease: false } })
|
|
.where(eq(environments.id, environmentId));
|
|
const outOfSync = await service.getOverview({ environmentId });
|
|
expect(outOfSync.activeTemplate).not.toBeNull();
|
|
expect(outOfSync.activeTemplateMatchesConfig).toBe(false);
|
|
// A boot-source field changed, so the overview attributes the drift and
|
|
// names the field with its `from`/`to` values.
|
|
expect(outOfSync.activeTemplateDrift?.classification).toBe("boot_source_drift");
|
|
expect(outOfSync.activeTemplateDrift?.driftedPaths).toEqual(
|
|
expect.arrayContaining([{ path: "image", from: "fake:base", to: "fake:other" }]),
|
|
);
|
|
});
|
|
|
|
it("attributes a knob-only overview change without naming a boot-source field", async () => {
|
|
const { environmentId } = await seed();
|
|
const workerManager = createWorkerManager();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: workerManager });
|
|
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
// A non-boot-relevant field changes. The fingerprint no longer matches, but
|
|
// every boot-source value still matches, so the drift is knob-only.
|
|
await db.update(environments)
|
|
.set({ config: { provider: "fake-plugin", image: "fake:base", reuseLease: false, region: "eu" } })
|
|
.where(eq(environments.id, environmentId));
|
|
const overview = await service.getOverview({ environmentId });
|
|
expect(overview.activeTemplateMatchesConfig).toBe(false);
|
|
expect(overview.activeTemplateDrift?.classification).toBe("knob_only");
|
|
expect(overview.activeTemplateDrift?.driftedPaths).toEqual([]);
|
|
});
|
|
|
|
it("attributes an unclassified overview drift for a legacy template with no snapshot", async () => {
|
|
const { environmentId } = await seed();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
// A legacy template carries no boot-relevant snapshot. The overview must
|
|
// fail closed and give no false "safe to relink" signal.
|
|
await db.insert(environmentCustomImageTemplates).values({
|
|
environmentId,
|
|
provider: "fake-plugin",
|
|
templateKind: "snapshot",
|
|
templateRef: "snapshot-legacy",
|
|
sourceEnvironmentConfigFingerprint: "stale-fingerprint",
|
|
status: "active",
|
|
metadata: { runtimeConfigBinding: { field: "customTemplate", unsetFields: ["image"] } },
|
|
});
|
|
|
|
const overview = await service.getOverview({ environmentId });
|
|
expect(overview.activeTemplate).not.toBeNull();
|
|
expect(overview.activeTemplateDrift?.classification).toBe("unclassified");
|
|
expect(overview.activeTemplateDrift?.driftedPaths).toEqual([]);
|
|
});
|
|
});
|
|
|
|
function secretPluginManifest() {
|
|
return {
|
|
id: "paperclip.fake-secret-sandbox-provider",
|
|
apiVersion: 1,
|
|
version: "0.1.0",
|
|
displayName: "Fake Secret Sandbox Provider",
|
|
description: "Test fake sandbox provider",
|
|
author: "Paperclip",
|
|
categories: ["automation"],
|
|
capabilities: ["environment.drivers.register"],
|
|
entrypoints: { worker: "./dist/worker.js" },
|
|
environmentDrivers: [
|
|
{
|
|
driverKey: "fake-secret-plugin",
|
|
kind: "sandbox_provider",
|
|
displayName: "Fake Secret Sandbox Provider",
|
|
supportsInteractiveSetup: true,
|
|
interactiveSetupConnectionTypes: ["ssh"],
|
|
supportsTemplateCapture: true,
|
|
templateRefKind: "snapshot",
|
|
templateConfigBinding: { field: "customTemplate", unsetFields: ["image"] },
|
|
// apiUrl overlaps a secret exactly; auth.token is a child of secret
|
|
// `auth`; credentials is a parent of secret `credentials.secret`.
|
|
templateIdentityPaths: ["apiUrl", "auth.token", "credentials"],
|
|
supportsTemplateDelete: true,
|
|
configSchema: {
|
|
type: "object",
|
|
properties: {
|
|
apiUrl: { type: "string", format: "secret-ref" },
|
|
auth: { type: "string", format: "secret-ref" },
|
|
credentials: {
|
|
type: "object",
|
|
properties: { secret: { type: "string", format: "secret-ref" } },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
],
|
|
} satisfies PaperclipPluginManifestV1;
|
|
}
|
|
|
|
function invalidIdentityPluginManifest() {
|
|
return {
|
|
id: "paperclip.fake-invalid-sandbox-provider",
|
|
apiVersion: 1,
|
|
version: "0.1.0",
|
|
displayName: "Fake Invalid Identity Sandbox Provider",
|
|
description: "Test fake sandbox provider",
|
|
author: "Paperclip",
|
|
categories: ["automation"],
|
|
capabilities: ["environment.drivers.register"],
|
|
entrypoints: { worker: "./dist/worker.js" },
|
|
environmentDrivers: [
|
|
{
|
|
driverKey: "fake-invalid-plugin",
|
|
kind: "sandbox_provider",
|
|
displayName: "Fake Invalid Identity Sandbox Provider",
|
|
supportsInteractiveSetup: true,
|
|
interactiveSetupConnectionTypes: ["ssh"],
|
|
supportsTemplateCapture: true,
|
|
templateRefKind: "snapshot",
|
|
templateConfigBinding: { field: "customTemplate", unsetFields: ["image"] },
|
|
// A valid path plus two that must fail canonicalization.
|
|
templateIdentityPaths: ["apiUrl", "bad path!", "a..b"],
|
|
supportsTemplateDelete: true,
|
|
configSchema: { type: "object" },
|
|
},
|
|
],
|
|
} satisfies PaperclipPluginManifestV1;
|
|
}
|
|
|
|
function prototypeKeyIdentityPluginManifest() {
|
|
return {
|
|
id: "paperclip.fake-prototype-key-sandbox-provider",
|
|
apiVersion: 1,
|
|
version: "0.1.0",
|
|
displayName: "Fake Prototype Key Sandbox Provider",
|
|
description: "Test fake sandbox provider",
|
|
author: "Paperclip",
|
|
categories: ["automation"],
|
|
capabilities: ["environment.drivers.register"],
|
|
entrypoints: { worker: "./dist/worker.js" },
|
|
environmentDrivers: [
|
|
{
|
|
driverKey: "fake-prototype-key-plugin",
|
|
kind: "sandbox_provider",
|
|
displayName: "Fake Prototype Key Sandbox Provider",
|
|
supportsInteractiveSetup: true,
|
|
interactiveSetupConnectionTypes: ["ssh"],
|
|
supportsTemplateCapture: true,
|
|
templateRefKind: "snapshot",
|
|
templateConfigBinding: { field: "customTemplate", unsetFields: ["image"] },
|
|
// Every prototype key has an identifier shape but names no own field.
|
|
// Each must fail canonicalization and record only the marker.
|
|
templateIdentityPaths: ["__proto__", "constructor", "prototype", "nested.__proto__"],
|
|
supportsTemplateDelete: true,
|
|
configSchema: { type: "object" },
|
|
},
|
|
],
|
|
} satisfies PaperclipPluginManifestV1;
|
|
}
|
|
|
|
describeEmbeddedPostgres("environmentCustomImageService relink", () => {
|
|
let stopDb: (() => Promise<void>) | null = null;
|
|
let db!: ReturnType<typeof createDb>;
|
|
|
|
beforeAll(async () => {
|
|
if (externalTestDatabase) { db = createDb(externalTestDatabase, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); return; }
|
|
const started = await startEmbeddedPostgresTestDatabase("environment-custom-images-relink");
|
|
stopDb = started.cleanup;
|
|
db = createDb(started.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await db.delete(activityLog);
|
|
await db.delete(environmentCustomImageSetupSessions);
|
|
await db.delete(environmentCustomImageTemplates);
|
|
await db.delete(plugins);
|
|
await db.delete(environments);
|
|
await db.delete(companies);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await db?.$client.end({ timeout: 1 });
|
|
await stopDb?.();
|
|
});
|
|
|
|
async function seed(opts?: {
|
|
manifest?: ReturnType<typeof pluginManifest> | ReturnType<typeof secretPluginManifest> | ReturnType<typeof invalidIdentityPluginManifest> | ReturnType<typeof prototypeKeyIdentityPluginManifest>;
|
|
config?: Record<string, unknown>;
|
|
}) {
|
|
const manifest = opts?.manifest ?? pluginManifest();
|
|
const provider = manifest.environmentDrivers[0]!.driverKey;
|
|
const companyId = randomUUID();
|
|
const environmentId = randomUUID();
|
|
await db.insert(companies).values(
|
|
{ id: companyId, name: "Acme", issuePrefix: `A${companyId.slice(0, 4)}` },
|
|
);
|
|
await db.insert(environments).values({
|
|
id: environmentId,
|
|
name: `Fake ${environmentId.slice(0, 8)}`,
|
|
driver: "sandbox",
|
|
status: "active",
|
|
config: opts?.config ?? { provider, image: "fake:base", reuseLease: false },
|
|
envVars: {},
|
|
});
|
|
await db.insert(plugins).values({
|
|
pluginKey: manifest.id,
|
|
packageName: `paperclip-plugin-${provider}`,
|
|
version: "0.1.0",
|
|
apiVersion: 1,
|
|
categories: ["automation"],
|
|
manifestJson: manifest,
|
|
status: "ready",
|
|
});
|
|
return { companyId, environmentId, provider };
|
|
}
|
|
|
|
const relinkActor = {
|
|
actorType: "user" as const,
|
|
actorId: "user-1",
|
|
agentId: null,
|
|
runId: null,
|
|
agentApiKeyId: null,
|
|
};
|
|
|
|
async function activeTemplateRow(environmentId: string) {
|
|
return db
|
|
.select()
|
|
.from(environmentCustomImageTemplates)
|
|
.where(eq(environmentCustomImageTemplates.environmentId, environmentId))
|
|
.orderBy(desc(environmentCustomImageTemplates.createdAt))
|
|
.then((rows) => rows[0]!);
|
|
}
|
|
|
|
async function relinkActivityRows(environmentId: string) {
|
|
return db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(eq(activityLog.entityId, environmentId));
|
|
}
|
|
|
|
it("keeps secret-ref values out of metadata, the response, and activity, and relinks with the flag", async () => {
|
|
const config = {
|
|
provider: "fake-secret-plugin",
|
|
image: "fake:base",
|
|
apiUrl: "https://secret-endpoint.example",
|
|
auth: "auth-secret-value",
|
|
credentials: { secret: "cred-secret-value", region: "eu" },
|
|
reuseLease: false,
|
|
};
|
|
const { companyId, environmentId } = await seed({ manifest: secretPluginManifest(), config });
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
// The public template response never carries the server-internal snapshot.
|
|
expect((promoted.template.metadata as Record<string, unknown>).bootRelevantConfig).toBeUndefined();
|
|
|
|
// The persisted snapshot lives in the row. Every secret-ref overlap is
|
|
// excluded with no value (exact, child, parent).
|
|
const persistedRow = await activeTemplateRow(environmentId);
|
|
const boot = (persistedRow.metadata as Record<string, unknown>).bootRelevantConfig as {
|
|
values: Record<string, unknown>;
|
|
excludedPaths: string[];
|
|
};
|
|
expect(boot.excludedPaths).toEqual(expect.arrayContaining(["apiUrl", "auth.token", "credentials"]));
|
|
expect(Object.keys(boot.values)).not.toContain("apiUrl");
|
|
expect(Object.keys(boot.values)).not.toContain("auth.token");
|
|
expect(Object.keys(boot.values)).not.toContain("credentials");
|
|
// Neither the persisted snapshot nor the response leaks a secret value.
|
|
for (const metadataJson of [
|
|
JSON.stringify(persistedRow.metadata),
|
|
JSON.stringify(promoted.template.metadata),
|
|
]) {
|
|
expect(metadataJson).not.toContain("secret-endpoint.example");
|
|
expect(metadataJson).not.toContain("auth-secret-value");
|
|
expect(metadataJson).not.toContain("cred-secret-value");
|
|
}
|
|
|
|
// An excluded path forces the fail-closed unclassified result: the flag is required.
|
|
await expect(service.relinkActiveTemplate({ environmentId, actor: relinkActor, companyId }))
|
|
.rejects.toMatchObject({ status: 409 });
|
|
const relinked = await service.relinkActiveTemplate({
|
|
environmentId,
|
|
confirmBootSourceDrift: true,
|
|
actor: relinkActor,
|
|
companyId,
|
|
});
|
|
expect(relinked.classification).toBe("unclassified");
|
|
const responseJson = JSON.stringify(relinked);
|
|
expect(responseJson).not.toContain("secret-endpoint.example");
|
|
expect(responseJson).not.toContain("auth-secret-value");
|
|
expect(responseJson).not.toContain("cred-secret-value");
|
|
|
|
const activities = await relinkActivityRows(environmentId);
|
|
const relinkActivity = activities.find((row) => row.action === "environment.custom_image_template.relinked");
|
|
expect(relinkActivity).toBeDefined();
|
|
const activityJson = JSON.stringify(relinkActivity!.details);
|
|
expect(activityJson).not.toContain("secret-endpoint.example");
|
|
expect(activityJson).not.toContain("auth-secret-value");
|
|
expect(activityJson).not.toContain("cred-secret-value");
|
|
// Drift detail carries path names only, never a fingerprint value.
|
|
expect(activityJson).not.toContain(promoted.template.sourceEnvironmentConfigFingerprint);
|
|
});
|
|
|
|
it("keeps secret values and the fingerprint out of the overview payload", async () => {
|
|
const config = {
|
|
provider: "fake-secret-plugin",
|
|
image: "fake:base",
|
|
apiUrl: "https://secret-endpoint.example",
|
|
auth: "auth-secret-value",
|
|
credentials: { secret: "cred-secret-value", region: "eu" },
|
|
reuseLease: false,
|
|
};
|
|
const { environmentId } = await seed({ manifest: secretPluginManifest(), config });
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
// A boot-source field changes, so the overview reports drift and carries the
|
|
// drifted paths. The payload must never leak a secret value or a fingerprint.
|
|
await db.update(environments)
|
|
.set({ config: { ...config, image: "fake:other" } })
|
|
.where(eq(environments.id, environmentId));
|
|
const overview = await service.getOverview({ environmentId });
|
|
// An excluded secret-ref path forces the fail-closed unclassified result.
|
|
expect(overview.activeTemplateDrift?.classification).toBe("unclassified");
|
|
// The full overview never leaks a secret value, and the server-internal
|
|
// snapshot never reaches the template response.
|
|
const overviewJson = JSON.stringify(overview);
|
|
expect(overviewJson).not.toContain("secret-endpoint.example");
|
|
expect(overviewJson).not.toContain("auth-secret-value");
|
|
expect(overviewJson).not.toContain("cred-secret-value");
|
|
expect(overviewJson).not.toContain("bootRelevantConfig");
|
|
// The drift attribution carries path names and non-secret values only, never
|
|
// a fingerprint value.
|
|
const driftJson = JSON.stringify(overview.activeTemplateDrift);
|
|
expect(driftJson).not.toContain(promoted.template.sourceEnvironmentConfigFingerprint);
|
|
expect(driftJson).not.toContain("secret-endpoint.example");
|
|
expect(driftJson).not.toContain("auth-secret-value");
|
|
expect(driftJson).not.toContain("cred-secret-value");
|
|
});
|
|
|
|
it("fails closed for legacy templates without a boot-relevant snapshot", async () => {
|
|
const { companyId, environmentId } = await seed();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
await db.insert(environmentCustomImageTemplates).values({
|
|
environmentId,
|
|
provider: "fake-plugin",
|
|
templateKind: "snapshot",
|
|
templateRef: "snapshot-legacy",
|
|
sourceEnvironmentConfigFingerprint: "stale-fingerprint",
|
|
status: "active",
|
|
metadata: { runtimeConfigBinding: { field: "customTemplate", unsetFields: ["image"] } },
|
|
});
|
|
|
|
await expect(service.relinkActiveTemplate({ environmentId, actor: relinkActor, companyId }))
|
|
.rejects.toMatchObject({ status: 409 });
|
|
const beforeRow = await activeTemplateRow(environmentId);
|
|
expect(beforeRow.sourceEnvironmentConfigFingerprint).toBe("stale-fingerprint");
|
|
|
|
const relinked = await service.relinkActiveTemplate({
|
|
environmentId,
|
|
confirmBootSourceDrift: true,
|
|
actor: relinkActor,
|
|
companyId,
|
|
});
|
|
expect(relinked.classification).toBe("unclassified");
|
|
const afterRow = await activeTemplateRow(environmentId);
|
|
expect(afterRow.sourceEnvironmentConfigFingerprint).not.toBe("stale-fingerprint");
|
|
});
|
|
|
|
it("relinks a knob-only change without a flag and keeps the fail-closed runtime gate", async () => {
|
|
const { companyId, environmentId } = await seed();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
// A non-boot field changes the fingerprint and detaches the template.
|
|
await db.update(environments)
|
|
.set({ config: { provider: "fake-plugin", image: "fake:base", reuseLease: false, region: "eu" } })
|
|
.where(eq(environments.id, environmentId));
|
|
const detached = await service.getOverview({ environmentId });
|
|
expect(detached.activeTemplateMatchesConfig).toBe(false);
|
|
|
|
const relinked = await service.relinkActiveTemplate({ environmentId, actor: relinkActor, companyId });
|
|
expect(relinked.classification).toBe("knob_only");
|
|
const afterRelink = await service.getOverview({ environmentId });
|
|
expect(afterRelink.activeTemplateMatchesConfig).toBe(true);
|
|
const resolved = await resolveEnvironmentDriverConfigForRuntime(db, companyId, {
|
|
id: environmentId,
|
|
driver: "sandbox",
|
|
config: { provider: "fake-plugin", image: "fake:base", reuseLease: false, region: "eu" },
|
|
}, { heartbeatRunId: randomUUID() });
|
|
expect(resolved.config).toMatchObject({ customTemplate: promoted.template.templateRef });
|
|
|
|
// The gate stays fail-closed: a base image change detaches again.
|
|
await db.update(environments)
|
|
.set({ config: { provider: "fake-plugin", image: "fake:other", reuseLease: false, region: "eu" } })
|
|
.where(eq(environments.id, environmentId));
|
|
const afterImageChange = await service.getOverview({ environmentId });
|
|
expect(afterImageChange.activeTemplateMatchesConfig).toBe(false);
|
|
});
|
|
|
|
it("requires the flag for boot-source drift and re-stamps only after confirmation", async () => {
|
|
const { companyId, environmentId } = await seed();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
await db.update(environments)
|
|
.set({ config: { provider: "fake-plugin", image: "fake:other", reuseLease: false } })
|
|
.where(eq(environments.id, environmentId));
|
|
|
|
await expect(service.relinkActiveTemplate({ environmentId, actor: relinkActor, companyId }))
|
|
.rejects.toMatchObject({
|
|
status: 409,
|
|
details: {
|
|
classification: "boot_source_drift",
|
|
driftedPaths: expect.arrayContaining([
|
|
expect.objectContaining({ path: "image", from: "fake:base", to: "fake:other" }),
|
|
]),
|
|
},
|
|
});
|
|
|
|
const relinked = await service.relinkActiveTemplate({
|
|
environmentId,
|
|
confirmBootSourceDrift: true,
|
|
actor: relinkActor,
|
|
companyId,
|
|
});
|
|
expect(relinked.classification).toBe("boot_source_drift");
|
|
const afterRelink = await service.getOverview({ environmentId });
|
|
expect(afterRelink.activeTemplateMatchesConfig).toBe(true);
|
|
});
|
|
|
|
it("re-stamps only the active template and never a superseded one", async () => {
|
|
const { companyId, environmentId } = await seed();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
const first = await service.finishSetupSession({
|
|
sessionId: (await service.startSetupSession({ environmentId, actor: { userId: "user-1" } })).session.id,
|
|
});
|
|
const second = await service.finishSetupSession({
|
|
sessionId: (await service.startSetupSession({ environmentId, actor: { userId: "user-1" } })).session.id,
|
|
});
|
|
// The first template is now superseded; the second is active.
|
|
const supersededBefore = await db
|
|
.select()
|
|
.from(environmentCustomImageTemplates)
|
|
.where(eq(environmentCustomImageTemplates.id, first.template.id))
|
|
.then((rows) => rows[0]!);
|
|
|
|
await db.update(environments)
|
|
.set({ config: { provider: "fake-plugin", image: "fake:base", reuseLease: false, region: "eu" } })
|
|
.where(eq(environments.id, environmentId));
|
|
const relinked = await service.relinkActiveTemplate({ environmentId, actor: relinkActor, companyId });
|
|
expect(relinked.template.id).toBe(second.template.id);
|
|
|
|
const supersededAfter = await db
|
|
.select()
|
|
.from(environmentCustomImageTemplates)
|
|
.where(eq(environmentCustomImageTemplates.id, first.template.id))
|
|
.then((rows) => rows[0]!);
|
|
expect(supersededAfter.status).toBe("superseded");
|
|
expect(supersededAfter.sourceEnvironmentConfigFingerprint)
|
|
.toBe(supersededBefore.sourceEnvironmentConfigFingerprint);
|
|
});
|
|
|
|
it("aborts with a conflict and writes no active template when none exists", async () => {
|
|
const { companyId, environmentId } = await seed();
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
await expect(service.relinkActiveTemplate({ environmentId, actor: relinkActor, companyId }))
|
|
.rejects.toMatchObject({ status: 404 });
|
|
const activities = await relinkActivityRows(environmentId);
|
|
expect(activities.filter((row) => row.action === "environment.custom_image_template.relinked")).toHaveLength(0);
|
|
});
|
|
|
|
it("classifies an invalid driver identity path as unclassified without treating it as value-bearing", async () => {
|
|
const { companyId, environmentId } = await seed({ manifest: invalidIdentityPluginManifest(), config: {
|
|
provider: "fake-invalid-plugin",
|
|
image: "fake:base",
|
|
reuseLease: false,
|
|
} });
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
expect((promoted.template.metadata as Record<string, unknown>).bootRelevantConfig).toBeUndefined();
|
|
const persistedRow = await activeTemplateRow(environmentId);
|
|
const boot = (persistedRow.metadata as Record<string, unknown>).bootRelevantConfig as {
|
|
values: Record<string, unknown>;
|
|
excludedPaths: string[];
|
|
};
|
|
expect(boot.excludedPaths).toContain("[unresolved-identity-path]");
|
|
// The raw invalid paths are never persisted and never value-bearing.
|
|
const metadataJson = JSON.stringify(persistedRow.metadata);
|
|
expect(metadataJson).not.toContain("bad path!");
|
|
expect(metadataJson).not.toContain("a..b");
|
|
expect(Object.keys(boot.values)).not.toContain("bad path!");
|
|
expect(Object.keys(boot.values)).not.toContain("a..b");
|
|
|
|
await expect(service.relinkActiveTemplate({ environmentId, actor: relinkActor, companyId }))
|
|
.rejects.toMatchObject({ status: 409 });
|
|
const relinked = await service.relinkActiveTemplate({
|
|
environmentId,
|
|
confirmBootSourceDrift: true,
|
|
actor: relinkActor,
|
|
companyId,
|
|
});
|
|
expect(relinked.classification).toBe("unclassified");
|
|
});
|
|
|
|
it("fails closed for prototype-key driver identity paths and never persists them", async () => {
|
|
const { companyId, environmentId } = await seed({ manifest: prototypeKeyIdentityPluginManifest(), config: {
|
|
provider: "fake-prototype-key-plugin",
|
|
image: "fake:base",
|
|
reuseLease: false,
|
|
} });
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
const promoted = await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
expect((promoted.template.metadata as Record<string, unknown>).bootRelevantConfig).toBeUndefined();
|
|
const persistedRow = await activeTemplateRow(environmentId);
|
|
const boot = (persistedRow.metadata as Record<string, unknown>).bootRelevantConfig as {
|
|
values: Record<string, unknown>;
|
|
excludedPaths: string[];
|
|
};
|
|
// Every prototype key fails canonicalization and records only the marker.
|
|
expect(boot.excludedPaths).toContain("[unresolved-identity-path]");
|
|
// No raw prototype-key path and no value for one persists in the snapshot.
|
|
expect(boot.excludedPaths).not.toContain("__proto__");
|
|
expect(boot.excludedPaths).not.toContain("constructor");
|
|
expect(boot.excludedPaths).not.toContain("prototype");
|
|
expect(Object.keys(boot.values)).not.toContain("__proto__");
|
|
expect(Object.keys(boot.values)).not.toContain("constructor");
|
|
expect(Object.keys(boot.values)).not.toContain("prototype");
|
|
// The prototype of the values map stays clean; no key leaked onto it.
|
|
expect(Object.getPrototypeOf(boot.values)).toBe(Object.prototype);
|
|
const metadataJson = JSON.stringify(persistedRow.metadata);
|
|
expect(metadataJson).not.toContain("__proto__");
|
|
expect(metadataJson).not.toContain("nested.__proto__");
|
|
|
|
// An unflagged relink fails closed with 409 and the unclassified class.
|
|
await expect(service.relinkActiveTemplate({ environmentId, actor: relinkActor, companyId }))
|
|
.rejects.toMatchObject({ status: 409, details: { classification: "unclassified" } });
|
|
// A confirmed relink succeeds and writes the relinked activity entry.
|
|
const relinked = await service.relinkActiveTemplate({
|
|
environmentId,
|
|
confirmBootSourceDrift: true,
|
|
actor: relinkActor,
|
|
companyId,
|
|
});
|
|
expect(relinked.classification).toBe("unclassified");
|
|
const activities = await relinkActivityRows(environmentId);
|
|
const relinkActivity = activities.find((row) => row.action === "environment.custom_image_template.relinked");
|
|
expect(relinkActivity).toBeDefined();
|
|
});
|
|
|
|
it("fails closed when the provider adds a boot-relevant identity path after capture", async () => {
|
|
const { companyId, environmentId } = await seed({ config: {
|
|
provider: "fake-plugin",
|
|
image: "fake:base",
|
|
region: "us",
|
|
reuseLease: false,
|
|
} });
|
|
const service = environmentCustomImageService(db, { pluginWorkerManager: createWorkerManager() });
|
|
const started = await service.startSetupSession({ environmentId, actor: { userId: "user-1" } });
|
|
await service.finishSetupSession({ sessionId: started.session.id });
|
|
|
|
// A knob-only region change detaches the template. On its own it would
|
|
// relink without confirmation.
|
|
await db.update(environments)
|
|
.set({ config: { provider: "fake-plugin", image: "fake:base", region: "eu", reuseLease: false } })
|
|
.where(eq(environments.id, environmentId));
|
|
|
|
// The provider now declares `region` a boot-relevant identity path. The
|
|
// capture snapshot never covered it, so the server cannot verify the boot
|
|
// source and must not classify the drift as knob-only.
|
|
const manifest = pluginManifest();
|
|
const nextManifest = {
|
|
...manifest,
|
|
environmentDrivers: [
|
|
{ ...manifest.environmentDrivers[0], templateIdentityPaths: ["apiUrl", "region"] },
|
|
],
|
|
};
|
|
await db.update(plugins)
|
|
.set({ manifestJson: nextManifest })
|
|
.where(eq(plugins.pluginKey, manifest.id));
|
|
|
|
await expect(service.relinkActiveTemplate({ environmentId, actor: relinkActor, companyId }))
|
|
.rejects.toMatchObject({ status: 409, details: { classification: "unclassified" } });
|
|
const relinked = await service.relinkActiveTemplate({
|
|
environmentId,
|
|
confirmBootSourceDrift: true,
|
|
actor: relinkActor,
|
|
companyId,
|
|
});
|
|
expect(relinked.classification).toBe("unclassified");
|
|
});
|
|
});
|