mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 18:26:40 +01:00
## Thinking Path > - Paperclip manages work for AI agents. > - SSH environments run tasks on computers that users own. > - A Paperclip server needs network access before it can reach a private computer. > - A reusable Tailscale connection belongs in Connectors. > - Connected machines should become choices in the existing SSH environment form. > - This change connects a tailnet and resolves selected machines through a private network client. > - Agents retain their choice of harness and AI account. ## Linked Issues or Issue Description **Subsystem affected** Connectors, environment settings, SSH execution, company secret storage, and runtime packaging. **Problem or motivation** Entering a Tailscale address in the SSH form does not connect the Paperclip server to that tailnet. Requiring a separate device key for every environment also duplicates network setup. **Proposed solution** Add a Tailscale Connector with **Connect Tailscale Network**. Use brokered OAuth consent to enroll one private network client per connection. Let SSH environments select a connected network and stable machine identity. Preserve the enrolled node state through the company vault so a restart does not reuse the one-time token. **Alternatives considered** A separate Tailscale environment type would duplicate SSH behavior and mix network access with harness selection. This change uses the existing `ssh` driver. Related #15648 adds OAuth client credentials and a health check; this change uses user consent and supplies outbound task execution. Related #11743 concerns HTTPS brokering. **Roadmap alignment** This extends the existing Connected Apps, environment, and Personal & Shared AI Accounts capabilities. This PR is stacked on #21248, which provides SSH account selection independently of Tailscale. The hosted OAuth broker is a companion control-plane change. ## What Changed - Preserve Cloud reauthentication in the current browser tab. Explain canceled or failed consent in the connector and offer a retry of the same authorized saved connection. - Record Cloud enrollment starts initiated through the Tailscale connector in the company activity log. - Check install-preparation descendant liveness through the kernel process table in the Runner support test. Keep the direct child’s strict reaping assertion and reject any non-zombie descendant. - Align the application image stage contract with the Tailscale client stage after the upstream Runner-image refactor. Keep the exact stage list and check every application stage, including `tailscale-client`, for prohibited Runner compiler commands. - Group Tailscale consent, discovery, daemon lifecycle, pairing, and deletion under `server/src/services/connectors/tailscale/`, with their service tests. Update existing route, runtime, environment, vault, and company-deletion imports. Keep the existing contracts, authorization, audit, and transaction owners. - Handle early stdin closure in the Kubernetes real-shell test helper. Stop the input stream on `EPIPE`, preserve nonzero child exits, and reject a zero exit when input was lost. Add two real-process regression cases. Production transfer code and confinement checks are unchanged. - Read configured Tailscale executable paths when a client starts, after supported `.env` loading. Keep explicit command overrides available. - Discard pending pairing results after switching to Direct SSH or closing the form. Retain the existing company, connection, machine, and port checks. - Store network credentials with an immutable server-owned purpose from their first vault row. Exclude them from generic catalogs, bindings, environment projection, and value reads. Use a dedicated audited server consumer for pinned connector reads. Block unclassified legacy serialized node state at the same value boundary. Keep SSH private-key binding separate from connector credentials. - Gate network queries and setup on verified local-implicit or instance-admin access. Hide Tailscale catalog rows for other members, show an admin requirement on direct setup navigation, and avoid device discovery before management access is known. - Keep failed-client cleanup in the network manager. A failed request cannot disconnect a newer retry for the same identity; explicit connector disconnect and enrollment retirement still stop their networks. - Check for readable Ed25519, ECDSA, or RSA host public keys before pairing edits `authorized_keys`. Print a known-hosts entry for every available key, or fail before changing authorized keys if none are available. - Return self-hosted Cloud enrollment to the Tailscale connector. Save the unprefixed setup path and let the shared callback add the verified company prefix. Keep external and unrelated destinations rejected. - Hide pairing instructions after an SSH port change. Ignore late key-selection results for the old port. Operators prepare again for matching known-hosts output. - Retire connector references before deleting a company or its vault credential. Stop company daemons after the database commit. Keep failed secret retirement retryable and prevent late node-state writes from restoring deleted connections. Discard retired state without blocking behind the vault deletion lock. - Reload a mismatched credential before replacing a ready daemon. Recheck the active entry and manager generation after the read. An older request cannot stop a newer healthy socket or cross shutdown. - Pin connector credentials to the exact vault version and SHA-256 digest recorded by trusted enrollment and node-state writes. Ignore generic secret rotations. Advance both fields with a compare-and-set guard. Reject unpinned or tampered credentials before network startup. - Save an explicit Direct SSH selection and clear old Tailscale fields after config merging. Preserve the operator's entered direct host. - Route all Tailscale SSH runtime access through the connection service after SSH-key loading. Pin access to the environment's saved connector identity and recheck after device discovery. Remove standalone key-based daemon startup and reject raw enrollment keys or credential-only network configurations. Align the shared config type and SDK pins. - Correct two E2E assumptions exposed during connector qualification. Keep the two-window chat fixture stale until its own mutation. Validate the original failed run and its permitted write-revocation timestamp in the legacy recovery browser test. - Add the Tailscale Connector page, catalog entry, OAuth return flow, connected-network management, device discovery, and disconnect. Document all six routes in OpenAPI and the API reference, including their instance-admin requirement. - Add company-scoped connection storage in `0480_lazy_lethal_legion`, trusted credential version/digest fields in `0481_round_pet_avengers`, and server-owned secret purpose/backfill in `0482_aberrant_rumiko_fujikawa`. Generate all three migrations through the maintained command and retain the five newest snapshots. - Add machine pairing that generates a fresh SSH key per request, stores its private half in the company vault, and uses the generated public half in the install command. Do not trust editable saved metadata. Preserve existing authorized keys, including a file without a final newline. Keep SSH username, workspace, and trusted host keys explicit. - Use the existing SSH driver. Resolve the machine's current address from its stable device ID. Reject disconnected, removed, offline, and wrong-company selections. - Hide Network when Direct is the only option. Select a sole connected tailnet automatically and hide its selector. Remove the requested setup helper copy. Do not restrict the harness to Claude. - Run a private userspace Tailscale daemon with a separate socket. Persist its node state before execution. Restore it after restart, bound startup, serialize reconnect cleanup, and close it during server shutdown. - Guard OAuth completion with a durable attempt marker. Disconnect and newer authorization invalidate older callbacks. Close replaced daemons and remove cancelled enrollment secrets without changing newer connection state. - Preserve SSH host verification and tailnet-specific session identity. Honor the configured Tailscale executable path, including spaces and OpenSSH percent escaping. - Package checksum-pinned Tailscale clients and their license in the standard runtime image. Exercise the client build stage in PR CI and include it in image smoke checks. ## Verification - Merge status: all CI and image checks pass, and current-head Apex is 5/5 with no unresolved comments. GitHub rejected a direct merge because the active master ruleset requires code-owner approval for `.github/workflows/pr-trusted.yml`. The [CODEOWNERS workflow pattern](https://github.com/paperclipai/paperclip/blob/master/.github/CODEOWNERS#L3) applies; eligible maintainers already have review requests. Auto-merge is enabled with the squash method for the verified head. The PR remains open pending that required approval; no branch policy was bypassed. - Final revision: `fdb29b2cc366f4945b7f4c3e2b2d25070329a21b`, including master `999709b0a6dd416af335b5debded13e1de7fcb7a`. [Final CI verification passed](https://github.com/paperclipai/paperclip/actions/runs/43518584814/job/132213508320). All required checks pass, all applicable test/build gates are green, and the branch is mergeable against master. SSH prerequisite #21248 and Cloud broker paperclipai/paperclip-cloud#1314 are already merged. - [Apex reviewed this exact revision at 5/5](https://github.com/paperclipai/paperclip/pull/20617#issuecomment-6776629437). There are no unresolved review threads. The PR is classified as Critical impact. - Final image qualification passes for the [application Runner path](https://github.com/paperclipai/paperclip/actions/runs/43518584522/job/132206784267), [amd64 Runner image](https://github.com/paperclipai/paperclip/actions/runs/43518584544/job/132207296198), and [arm64 Runner image](https://github.com/paperclipai/paperclip/actions/runs/43518584544/job/132207296156). Typechecks, Runner support, native/Rust tests, provider tests, serialized-server suites, browser shards, and the remaining applicable CI checks pass. This is source/image CI qualification, not a production rollout. - The last master conflict affected only Docker stage declarations and their boundary test. Both the checksum-pinned Tailscale stage and upstream `runner-lockfile` guard are retained, including the upstream `deps` inheritance. The Tailscale client stage is byte-identical. All 180 cases across five Docker/image contract suites pass locally, along with server and UI typechecks. The maintained 543-input SDK check has no drift. Runtime and lock pins are unchanged. Secret/PII and whitespace scans pass. - Seven OAuth regression cases failed before the fixes. The current-tab test uses the real handoff helper, checks that the session is stored before reauthentication navigation, mounts the shared return page, resumes consent, and verifies handoff cleanup. Callback tests check trusted saved-connection context, fixed safe outcomes, failure audit metadata, denied membership and expired-state rejection, JSON API errors, and no provider text in browser returns. UI retries require a connection in the current company's catalog. All 80 OAuth route/service/UI/shared-handoff cases pass; server and UI source/test typechecks pass. - [Server shard 4/12 on the prior refresh](https://github.com/paperclipai/paperclip/actions/runs/43510727031/job/132180301436) passed 2,784 cases and skipped 21, then failed a reassignment fixture's `TRUNCATE companies CASCADE` cleanup with PostgreSQL `40P01`. Its automatic retry found the surviving `REA` prefix. The unchanged test passes all three cases locally. A controlled reader/cleanup overlap reproduces the same deadlock, but the exact competing CI query was not logged. Each case now has a distinct company prefix and identifier; the owned database is removed at suite end. The three test bodies and assertions are byte-identical. Eight local reassignment/lock-release cases pass, and the [final server shard 4/12 passes](https://github.com/paperclipai/paperclip/actions/runs/43518584814/job/132207159392). Production reassignment logic, deadlines, and retries are unchanged. - The initial master integration passed 330 cases across 17 suites. Coverage includes connector state, device discovery, network lifecycle, pairing, routes, SSH binding and exports, environment persistence, and connector UI. All three unpublished migrations were regenerated after master's `0479_short_darkstar`: `0480_lazy_lethal_legion`, `0481_round_pet_avengers`, and `0482_aberrant_rumiko_fujikawa`. Each SQL body is byte-identical to its earlier unpublished migration. Generated snapshots preserve existing master tables and add only the intended Tailscale table and secret-purpose column. Exactly five snapshots remain, 0478–0482. Numbering, safety, compatibility, and snapshot-drift checks pass. The later Docker refresh did not alter this migration sequence. - Earlier attempts remain part of the verification record. On `1c020a0`, Rust cache restoration and server shard 5/12 were interrupted by shutdown signals, Runner shard 2/3 lost communication with no retrievable log, and an amd64 provider download failed with npm `ECONNRESET`. Same-head retries recovered, without establishing the cause of the communication loss. Later superseded runs also had cancellations with incomplete logs. These interrupted attempts are not counted as passes. The final revision has fresh successful CI. - Local platform limits remain recorded. The Kubernetes suite on macOS passed 191 cases, failed 12 Linux `/proc/self/fd` transfer cases, and skipped four Linux-only cases. Unchanged source reproduced the same 12 failures. An initial run also lacked provider dependencies until the maintained preparation command installed them. Those local attempts are not green qualification. Final Linux provider CI passes. Local Docker qualification was unavailable; final image checks passed in CI. - Before PR separation, a live tailnet/SSH Claude Code task completed on Ubuntu ARM64 without provider login for the remote user. The selected Paperclip subscription ran it, wrote the expected file, posted completion, and marked the task done. File contents and private runtime cleanup were checked. This is prior live evidence; the final revision was not live-retested. Other providers have automated coverage only. Hosted registration for unrelated tailnets and production concurrency remain qualification limits below. - The Superagent security and supply-chain reports remain neutral and inconclusive. Earlier attempts to restart the failed security scan returned HTTP 404. Supply-chain intelligence lacked coverage for extracted pinned dependencies and the shared workflow reference. These reports do not establish successful security qualification. The required CI and review gates pass; this external coverage gap remains disclosed. ## Risks - The Superagent security and supply-chain reports are inconclusive. The security scan re-run request returned HTTP 404, and the supply-chain scanner lacks coverage for the extracted dependencies and shared workflow reference. These neutral results are not successful security qualification. - The server-owned secret purpose is internal database metadata, not an HTTP-writable field. The generic secret service owns enforcement so direct API reads and runtime projection share the same restriction. Previously copied node state remains valid outside Paperclip until the enrolled device is revoked in Tailscale; a local disconnect cannot stop an external copy. - Tailscale network configurations now require a connected Connector and selected machine. The unreleased key-only path is removed; any saved configuration from that path needs Connector setup. - The connector remains a pilot. The local test used an OAuth app registered in the consenting user's tailnet. Qualify hosted app registration for unrelated customer tailnets before general availability. - This implementation supports one serving process per instance. Concurrent replicas need exclusive ownership of the persisted network identity before production rollout. Preserve the database and company vault master key across restarts. - Each machine-pairing preparation creates a new vault secret. Unused generated keys follow the existing secret deletion lifecycle. A saved SSH key remains available as an explicit choice. - Apply additive migrations `0480_lazy_lethal_legion`, `0481_round_pet_avengers`, and `0482_aberrant_rumiko_fujikawa` before application rollout. The new credential version and digest columns are nullable. Existing unpinned connections require fresh OAuth consent; the migration deliberately does not trust or backfill a generic secret value. Regenerate or renumber migrations if master advances the sequence before merge. - The target needs an SSH server, its chosen harness, and allowed tailnet access. A reachable network does not grant SSH or provider authorization. Pairing reads standard `/etc/ssh` host-public-key files; custom host-key locations require manual known-hosts configuration. - Roll back the application revision to remove new entry points. Existing connection secrets and registered Tailscale nodes retain their separate lifecycle. Do not drop the table or delete node state as part of an application rollback. - Production qualification still needs denied-policy, revocation, cancellation, and deployment-overlap checks. Local Docker and a production deployment were not performed. ## Model Used OpenAI Codex, gpt-6.1-sol, xhigh reasoning, with local code execution and tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used - [x] I have checked ROADMAP.md and this extends existing connector and environment features - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in-PR using the feature request fields - [x] I have not referenced internal issues, local URLs, or private machine identifiers - [x] My branch name describes the change - [x] I have run focused tests locally and they pass - [x] I have added tests for new behavior and failure paths - [x] I have updated documentation - [x] I have documented migration and runtime risks - [x] All Paperclip CI gates are green - [ ] Required code-owner approval received for the workflow change - [x] Greptile Apex is 5/5 on the final head with no unresolved comments - [x] I will address CI and review findings before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
3368 lines
126 KiB
TypeScript
3368 lines
126 KiB
TypeScript
import type { Server } from "node:http";
|
|
import express from "express";
|
|
import request from "supertest";
|
|
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { conflict, unprocessable } from "../errors.js";
|
|
import { environmentRoutes } from "../routes/environments.js";
|
|
import { errorHandler } from "../middleware/index.js";
|
|
|
|
const mockAccessService = vi.hoisted(() => ({
|
|
canUser: vi.fn(),
|
|
hasPermission: vi.fn(),
|
|
decide: vi.fn(),
|
|
}));
|
|
|
|
const mockAgentService = vi.hoisted(() => ({
|
|
getById: vi.fn(),
|
|
}));
|
|
|
|
const mockIssueService = vi.hoisted(() => ({
|
|
getById: vi.fn(),
|
|
clearExecutionWorkspaceEnvironmentSelection: vi.fn(),
|
|
}));
|
|
|
|
const mockProjectService = vi.hoisted(() => ({
|
|
getById: vi.fn(),
|
|
clearExecutionWorkspaceEnvironmentSelection: vi.fn(),
|
|
}));
|
|
|
|
const mockEnvironmentRuntimeService = vi.hoisted(() => ({
|
|
destroyReusableSandboxLeasesForEnvironment: vi.fn(async () => ({ destroyed: 0, failed: 0, skippedLiveRun: 0 })),
|
|
releaseRestoreSourcesForEnvironmentDelete: vi.fn(async () => 0),
|
|
}));
|
|
const mockCloseWarmNativeSessionsForEnvironment = vi.hoisted(() =>
|
|
vi.fn(async (): Promise<{ closed: number; busy: number; failed: number; failures: Array<Record<string, unknown>> }> =>
|
|
({ closed: 0, busy: 0, failed: 0, failures: [] })),
|
|
);
|
|
const mockInstanceSettingsService = vi.hoisted(() => ({
|
|
get: vi.fn(async () => ({ defaultEnvironmentId: null })),
|
|
listCompanyIds: vi.fn(),
|
|
getGeneral: vi.fn(),
|
|
getExperimental: vi.fn(),
|
|
}));
|
|
|
|
const mockEnvironmentService = vi.hoisted(() => ({
|
|
list: vi.fn(),
|
|
getById: vi.fn(),
|
|
create: vi.fn(),
|
|
update: vi.fn(),
|
|
removeIfDeletable: vi.fn(),
|
|
getDeleteBlastRadius: vi.fn(),
|
|
hasUnresolvedPendingCleanupLeases: vi.fn(),
|
|
listLeases: vi.fn(),
|
|
getLeaseById: vi.fn(),
|
|
}));
|
|
|
|
const mockEnvironmentCustomImageService = vi.hoisted(() => ({
|
|
getOverview: vi.fn(),
|
|
getActiveTemplate: vi.fn(),
|
|
getSessionById: vi.fn(),
|
|
startSetupSession: vi.fn(),
|
|
refreshSetupSession: vi.fn(),
|
|
finishSetupSession: vi.fn(),
|
|
cancelSetupSession: vi.fn(),
|
|
rollbackTemplate: vi.fn(),
|
|
disableTemplate: vi.fn(),
|
|
cleanupExpiredSetupSessions: vi.fn(),
|
|
}));
|
|
|
|
const mockLogActivity = vi.hoisted(() => vi.fn());
|
|
const mockProbeEnvironment = vi.hoisted(() => vi.fn());
|
|
const mockSecretService = vi.hoisted(() => ({
|
|
create: vi.fn(),
|
|
normalizeEnvBindingsForPersistence: vi.fn(),
|
|
listBindingCompanyIdsForTarget: vi.fn(),
|
|
resolveSecretValue: vi.fn(),
|
|
resolveSecretValueForEphemeralAccess: vi.fn(),
|
|
syncEnvBindingsForTarget: vi.fn(),
|
|
syncSecretRefsForTarget: vi.fn(),
|
|
replaceSecretRefsForInstanceTarget: vi.fn(),
|
|
describeSecretRefs: vi.fn(),
|
|
remove: vi.fn(),
|
|
}));
|
|
const mockValidatePluginEnvironmentDriverConfig = vi.hoisted(() => vi.fn());
|
|
const mockValidatePluginSandboxProviderConfig = vi.hoisted(() => vi.fn());
|
|
const mockListReadyPluginEnvironmentDrivers = vi.hoisted(() => vi.fn());
|
|
const mockResolvePluginSandboxProviderDriverByKey = vi.hoisted(() => vi.fn());
|
|
const mockStartPluginEnvironmentInteractiveSetup = vi.hoisted(() => vi.fn());
|
|
const mockGetPluginEnvironmentInteractiveSetup = vi.hoisted(() => vi.fn());
|
|
const mockCapturePluginEnvironmentTemplate = vi.hoisted(() => vi.fn());
|
|
const mockCancelPluginEnvironmentInteractiveSetup = vi.hoisted(() => vi.fn());
|
|
const mockDeletePluginEnvironmentTemplate = vi.hoisted(() => vi.fn());
|
|
const mockExecutionWorkspaceService = vi.hoisted(() => ({
|
|
clearEnvironmentSelection: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../services/index.js", () => ({
|
|
issueService: () => mockIssueService,
|
|
instanceSettingsService: () => mockInstanceSettingsService,
|
|
environmentCustomImageService: () => mockEnvironmentCustomImageService,
|
|
environmentService: () => mockEnvironmentService,
|
|
logActivity: mockLogActivity,
|
|
projectService: () => mockProjectService,
|
|
}));
|
|
|
|
vi.mock("../services/environment-probe.js", () => ({
|
|
probeEnvironment: mockProbeEnvironment,
|
|
}));
|
|
|
|
vi.mock("../services/secrets.js", () => ({
|
|
secretService: () => mockSecretService,
|
|
}));
|
|
|
|
vi.mock("../services/environments.js", () => ({
|
|
environmentService: () => mockEnvironmentService,
|
|
}));
|
|
|
|
vi.mock("../services/environment-runtime.js", () => ({
|
|
environmentRuntimeService: () => mockEnvironmentRuntimeService,
|
|
}));
|
|
vi.mock("../services/native-runtime/native-session-executor.js", () => ({
|
|
closeWarmNativeSessionsForEnvironment:
|
|
mockCloseWarmNativeSessionsForEnvironment,
|
|
}));
|
|
|
|
vi.mock("../services/execution-workspaces.js", () => ({
|
|
executionWorkspaceService: () => mockExecutionWorkspaceService,
|
|
}));
|
|
|
|
const mockAssertAgentsReadyForEnvironmentChange = vi.hoisted(() => vi.fn(async () => {}));
|
|
|
|
vi.mock("../services/plugin-environment-driver.js", () => ({
|
|
// The runtime reads this published constant at import time. Mirror the real
|
|
// value so the mocked module keeps the same reusable-lease method contract.
|
|
REUSABLE_LEASE_WORKER_METHODS: ["environmentResumeLease", "environmentReleaseLease", "environmentDestroyLease"],
|
|
assertAgentsReadyForEnvironmentChange: mockAssertAgentsReadyForEnvironmentChange,
|
|
listReadyPluginEnvironmentDrivers: mockListReadyPluginEnvironmentDrivers,
|
|
resolvePluginSandboxProviderDriverByKey: mockResolvePluginSandboxProviderDriverByKey,
|
|
resolvePluginSandboxProviderConfigSchema: async (input: { db: unknown; driverKey: string }) =>
|
|
(await mockResolvePluginSandboxProviderDriverByKey(input))?.driver?.configSchema ?? null,
|
|
startPluginEnvironmentInteractiveSetup: mockStartPluginEnvironmentInteractiveSetup,
|
|
getPluginEnvironmentInteractiveSetup: mockGetPluginEnvironmentInteractiveSetup,
|
|
capturePluginEnvironmentTemplate: mockCapturePluginEnvironmentTemplate,
|
|
cancelPluginEnvironmentInteractiveSetup: mockCancelPluginEnvironmentInteractiveSetup,
|
|
deletePluginEnvironmentTemplate: mockDeletePluginEnvironmentTemplate,
|
|
validatePluginEnvironmentDriverConfig: mockValidatePluginEnvironmentDriverConfig,
|
|
validatePluginSandboxProviderConfig: mockValidatePluginSandboxProviderConfig,
|
|
}));
|
|
|
|
function createEnvironment() {
|
|
const now = new Date("2026-04-16T05:00:00.000Z");
|
|
return {
|
|
id: "env-1",
|
|
companyId: "company-1",
|
|
name: "Local",
|
|
description: "Current development machine",
|
|
driver: "local",
|
|
status: "active" as const,
|
|
config: { shell: "zsh" },
|
|
envVars: {},
|
|
metadata: { source: "manual" },
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
};
|
|
}
|
|
|
|
function createDeleteBlastRadius(overrides: Partial<{
|
|
isManagedLocal: boolean;
|
|
isInstanceDefault: boolean;
|
|
agentDefaultCount: number;
|
|
executionWorkspaceSelectionCount: number;
|
|
issueSelectionCount: number;
|
|
projectSelectionCount: number;
|
|
secretBindingCount: number;
|
|
activeLeaseCount: number;
|
|
activeCustomImageSetupSessionCount: number;
|
|
pendingCleanupLeaseCount: number;
|
|
reusableSandboxLeaseCount: number;
|
|
reusableSandboxLeaseHolders: Array<{
|
|
leaseId: string;
|
|
executionWorkspaceId: string | null;
|
|
executionWorkspaceName: string | null;
|
|
issueId: string | null;
|
|
issueIdentifier: string | null;
|
|
issueTitle: string | null;
|
|
}>;
|
|
}> = {}) {
|
|
const staticReferences = {
|
|
isManagedLocal: overrides.isManagedLocal ?? false,
|
|
isInstanceDefault: overrides.isInstanceDefault ?? false,
|
|
agentDefaultCount: overrides.agentDefaultCount ?? 0,
|
|
executionWorkspaceSelectionCount: overrides.executionWorkspaceSelectionCount ?? 0,
|
|
issueSelectionCount: overrides.issueSelectionCount ?? 0,
|
|
projectSelectionCount: overrides.projectSelectionCount ?? 0,
|
|
secretBindingCount: overrides.secretBindingCount ?? 0,
|
|
};
|
|
const activeRuntimeUse = {
|
|
activeLeaseCount: overrides.activeLeaseCount ?? 0,
|
|
activeCustomImageSetupSessionCount: overrides.activeCustomImageSetupSessionCount ?? 0,
|
|
hasActiveRuntimeUse:
|
|
(overrides.activeLeaseCount ?? 0) > 0
|
|
|| (overrides.activeCustomImageSetupSessionCount ?? 0) > 0,
|
|
};
|
|
const pendingCleanupLeaseCount = overrides.pendingCleanupLeaseCount ?? 0;
|
|
const reusableSandboxLeaseCount = overrides.reusableSandboxLeaseCount ?? 0;
|
|
const reusableSandboxLeaseHolders =
|
|
overrides.reusableSandboxLeaseHolders
|
|
?? Array.from({ length: reusableSandboxLeaseCount }, (_, index) => ({
|
|
leaseId: `lease-${index + 1}`,
|
|
executionWorkspaceId: null,
|
|
executionWorkspaceName: null,
|
|
issueId: null,
|
|
issueIdentifier: null,
|
|
issueTitle: null,
|
|
}));
|
|
const deleteBlockedReasons = [
|
|
...(staticReferences.isManagedLocal ? ["managed_local" as const] : []),
|
|
...(staticReferences.isInstanceDefault ? ["instance_default" as const] : []),
|
|
...(pendingCleanupLeaseCount > 0 ? ["pending_sandbox_cleanup" as const] : []),
|
|
...(reusableSandboxLeaseCount > 0 ? ["reusable_sandbox_lease" as const] : []),
|
|
];
|
|
return {
|
|
environmentId: "env-1",
|
|
canDelete: deleteBlockedReasons.length === 0,
|
|
deleteBlockedReasons,
|
|
pendingCleanupLeaseCount,
|
|
reusableSandboxLeaseCount,
|
|
reusableSandboxLeaseHolders,
|
|
staticReferences,
|
|
activeRuntimeUse,
|
|
};
|
|
}
|
|
|
|
let server: Server | null = null;
|
|
let currentActor: Record<string, unknown> = localBoardActor();
|
|
const routeOptions: Record<string, unknown> = {};
|
|
const originalSecretsProviderEnv = process.env.PAPERCLIP_SECRETS_PROVIDER;
|
|
|
|
// The routes open a transaction around environment writes and their binding
|
|
// syncs. Service calls are mocked, so the executor never runs a real query —
|
|
// it only needs to be identity-checkable in assertions.
|
|
const routeDbTx = { __routeDbTx: true };
|
|
const routeDb = {
|
|
transaction: async <T>(fn: (tx: unknown) => Promise<T>): Promise<T> =>
|
|
fn(routeDbTx),
|
|
};
|
|
|
|
function createApp(actor: Record<string, unknown>, options: Record<string, unknown> = {}) {
|
|
currentActor = actor;
|
|
for (const key of Object.keys(routeOptions)) {
|
|
delete routeOptions[key];
|
|
}
|
|
Object.assign(routeOptions, options);
|
|
if (server) return server;
|
|
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
(req as any).actor = currentActor;
|
|
next();
|
|
});
|
|
app.use("/api", environmentRoutes(routeDb as any, routeOptions as any));
|
|
app.use(errorHandler);
|
|
server = app.listen(0);
|
|
return server;
|
|
}
|
|
|
|
function localBoardActor(userId = "user-1") {
|
|
return {
|
|
type: "board",
|
|
userId: userId,
|
|
source: "local_implicit",
|
|
};
|
|
}
|
|
|
|
function createSecurePluginDriver() {
|
|
return {
|
|
driverKey: "secure-plugin",
|
|
kind: "sandbox_provider",
|
|
displayName: "Secure Sandbox",
|
|
configSchema: {
|
|
type: "object",
|
|
properties: {
|
|
template: { type: "string" },
|
|
apiKey: { type: "string", format: "secret-ref" },
|
|
timeoutMs: { type: "number" },
|
|
reuseLease: { type: "boolean" },
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
function createSecretBackedSshEnvironment() {
|
|
return {
|
|
...createEnvironment(),
|
|
id: "env-ssh",
|
|
name: "SSH Fixture",
|
|
driver: "ssh" as const,
|
|
config: {
|
|
host: "ssh.example.test",
|
|
port: 22,
|
|
username: "ssh-user",
|
|
remoteWorkspacePath: "/srv/paperclip/workspace",
|
|
privateKey: null,
|
|
privateKeySecretRef: {
|
|
type: "secret_ref",
|
|
secretId: "11111111-1111-1111-1111-111111111111",
|
|
version: "latest",
|
|
},
|
|
knownHosts: null,
|
|
strictHostKeyChecking: true,
|
|
},
|
|
};
|
|
}
|
|
|
|
function createSshConfig() {
|
|
return {
|
|
host: "ssh.example.test",
|
|
port: 22,
|
|
username: "ssh-user",
|
|
remoteWorkspacePath: "/srv/paperclip/workspace",
|
|
privateKey: null,
|
|
privateKeySecretRef: null,
|
|
knownHosts: null,
|
|
strictHostKeyChecking: true,
|
|
};
|
|
}
|
|
|
|
describe("environment routes", () => {
|
|
afterAll(async () => {
|
|
if (originalSecretsProviderEnv === undefined) {
|
|
delete process.env.PAPERCLIP_SECRETS_PROVIDER;
|
|
} else {
|
|
process.env.PAPERCLIP_SECRETS_PROVIDER = originalSecretsProviderEnv;
|
|
}
|
|
if (!server) return;
|
|
await new Promise<void>((resolve, reject) => {
|
|
server?.close((err) => {
|
|
if (err) reject(err);
|
|
else resolve();
|
|
});
|
|
});
|
|
server = null;
|
|
});
|
|
|
|
beforeEach(() => {
|
|
mockAccessService.canUser.mockReset();
|
|
mockAccessService.hasPermission.mockReset();
|
|
mockAccessService.decide.mockReset();
|
|
mockAgentService.getById.mockReset();
|
|
mockIssueService.getById.mockReset();
|
|
mockIssueService.clearExecutionWorkspaceEnvironmentSelection.mockReset();
|
|
mockProjectService.getById.mockReset();
|
|
mockProjectService.clearExecutionWorkspaceEnvironmentSelection.mockReset();
|
|
mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment.mockReset();
|
|
mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment.mockResolvedValue(
|
|
{ destroyed: 0, failed: 0, skippedLiveRun: 0 },
|
|
);
|
|
mockCloseWarmNativeSessionsForEnvironment.mockReset();
|
|
mockCloseWarmNativeSessionsForEnvironment.mockResolvedValue({
|
|
closed: 0,
|
|
busy: 0,
|
|
failed: 0,
|
|
failures: [],
|
|
});
|
|
mockInstanceSettingsService.listCompanyIds.mockReset();
|
|
mockInstanceSettingsService.getGeneral.mockReset();
|
|
mockInstanceSettingsService.getGeneral.mockResolvedValue({ executionMode: "any" });
|
|
mockInstanceSettingsService.getExperimental.mockReset();
|
|
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableManagedSandboxOnly: false });
|
|
mockEnvironmentService.list.mockReset();
|
|
mockEnvironmentService.list.mockResolvedValue([]);
|
|
mockEnvironmentService.getById.mockReset();
|
|
mockEnvironmentService.create.mockReset();
|
|
mockEnvironmentService.update.mockReset();
|
|
mockEnvironmentService.removeIfDeletable.mockReset();
|
|
mockEnvironmentService.getDeleteBlastRadius.mockReset();
|
|
mockEnvironmentService.hasUnresolvedPendingCleanupLeases.mockReset();
|
|
mockEnvironmentService.hasUnresolvedPendingCleanupLeases.mockResolvedValue(false);
|
|
mockEnvironmentService.listLeases.mockReset();
|
|
mockEnvironmentService.getLeaseById.mockReset();
|
|
mockExecutionWorkspaceService.clearEnvironmentSelection.mockReset();
|
|
Object.values(mockEnvironmentCustomImageService).forEach((mock) => mock.mockReset());
|
|
mockEnvironmentCustomImageService.getOverview.mockResolvedValue({
|
|
activeTemplate: null,
|
|
activeSession: null,
|
|
latestSession: null,
|
|
});
|
|
mockEnvironmentCustomImageService.getActiveTemplate.mockResolvedValue(null);
|
|
mockEnvironmentCustomImageService.getSessionById.mockResolvedValue(null);
|
|
mockLogActivity.mockReset();
|
|
mockProbeEnvironment.mockReset();
|
|
mockSecretService.create.mockReset();
|
|
mockSecretService.normalizeEnvBindingsForPersistence.mockReset();
|
|
mockSecretService.listBindingCompanyIdsForTarget.mockReset();
|
|
mockSecretService.resolveSecretValue.mockReset();
|
|
mockSecretService.resolveSecretValueForEphemeralAccess.mockReset();
|
|
mockSecretService.syncEnvBindingsForTarget.mockReset();
|
|
mockSecretService.syncSecretRefsForTarget.mockReset();
|
|
mockSecretService.replaceSecretRefsForInstanceTarget.mockReset();
|
|
mockSecretService.describeSecretRefs.mockReset();
|
|
mockSecretService.describeSecretRefs.mockResolvedValue([]);
|
|
mockSecretService.remove.mockReset();
|
|
mockSecretService.create.mockResolvedValue({
|
|
id: "11111111-1111-1111-1111-111111111111",
|
|
});
|
|
mockInstanceSettingsService.listCompanyIds.mockResolvedValue(["company-1"]);
|
|
mockIssueService.clearExecutionWorkspaceEnvironmentSelection.mockResolvedValue(0);
|
|
mockProjectService.clearExecutionWorkspaceEnvironmentSelection.mockResolvedValue(0);
|
|
mockExecutionWorkspaceService.clearEnvironmentSelection.mockResolvedValue(0);
|
|
mockSecretService.normalizeEnvBindingsForPersistence.mockImplementation(async (_companyId, env) => env ?? {});
|
|
mockSecretService.listBindingCompanyIdsForTarget.mockResolvedValue([]);
|
|
mockSecretService.syncEnvBindingsForTarget.mockResolvedValue([]);
|
|
mockSecretService.syncSecretRefsForTarget.mockResolvedValue([]);
|
|
mockSecretService.replaceSecretRefsForInstanceTarget.mockResolvedValue([]);
|
|
mockSecretService.remove.mockResolvedValue(null);
|
|
mockSecretService.resolveSecretValueForEphemeralAccess.mockResolvedValue("resolved-provider-key");
|
|
delete process.env.PAPERCLIP_SECRETS_PROVIDER;
|
|
mockValidatePluginEnvironmentDriverConfig.mockReset();
|
|
mockValidatePluginEnvironmentDriverConfig.mockImplementation(async ({ config }) => config);
|
|
mockValidatePluginSandboxProviderConfig.mockReset();
|
|
mockValidatePluginSandboxProviderConfig.mockImplementation(async ({ provider, config }) => ({
|
|
normalizedConfig: config,
|
|
pluginId: `plugin-${provider}`,
|
|
pluginKey: `plugin.${provider}`,
|
|
driver: {
|
|
driverKey: provider,
|
|
kind: "sandbox_provider",
|
|
displayName: provider,
|
|
configSchema: { type: "object" },
|
|
},
|
|
}));
|
|
mockResolvePluginSandboxProviderDriverByKey.mockReset();
|
|
mockResolvePluginSandboxProviderDriverByKey.mockImplementation(async ({ driverKey }) => (
|
|
driverKey === "secure-plugin"
|
|
? {
|
|
pluginId: "plugin-secure",
|
|
pluginKey: "acme.secure-sandbox-provider",
|
|
driver: createSecurePluginDriver(),
|
|
}
|
|
: null
|
|
));
|
|
mockListReadyPluginEnvironmentDrivers.mockReset();
|
|
mockListReadyPluginEnvironmentDrivers.mockResolvedValue([]);
|
|
mockStartPluginEnvironmentInteractiveSetup.mockReset();
|
|
mockGetPluginEnvironmentInteractiveSetup.mockReset();
|
|
mockCapturePluginEnvironmentTemplate.mockReset();
|
|
mockCancelPluginEnvironmentInteractiveSetup.mockReset();
|
|
mockDeletePluginEnvironmentTemplate.mockReset();
|
|
mockAccessService.decide.mockResolvedValue({
|
|
allowed: true,
|
|
explanation: "Allowed by test harness",
|
|
});
|
|
});
|
|
|
|
it("lists instance-scoped environments through the company route alias", async () => {
|
|
mockEnvironmentService.list.mockResolvedValue([createEnvironment()]);
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app).get("/api/companies/company-1/environments?driver=local");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body).toHaveLength(1);
|
|
expect(mockEnvironmentService.list).toHaveBeenCalledWith({
|
|
status: undefined,
|
|
driver: "local",
|
|
});
|
|
});
|
|
|
|
it("redacts environment config for non-admin board readers", async () => {
|
|
mockEnvironmentService.list.mockResolvedValue([createEnvironment()]);
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-2",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
memberships: [{ companyId: "company-1", status: "active", membershipRole: "member" }],
|
|
isInstanceAdmin: false,
|
|
});
|
|
|
|
const res = await request(app).get("/api/companies/company-1/environments");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body[0]).toMatchObject({
|
|
id: "env-1",
|
|
name: "Local",
|
|
config: {},
|
|
envVars: {},
|
|
metadata: null,
|
|
});
|
|
});
|
|
|
|
it("redacts environment detail config for non-admin board readers", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(createEnvironment());
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-2",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
memberships: [{ companyId: "company-1", status: "active", membershipRole: "member" }],
|
|
isInstanceAdmin: false,
|
|
});
|
|
|
|
const res = await request(app).get("/api/environments/env-1");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body).toMatchObject({
|
|
id: "env-1",
|
|
config: {},
|
|
envVars: {},
|
|
metadata: null,
|
|
});
|
|
});
|
|
|
|
it.each(["list", "detail"])("exposes only plugin driver identity in the restricted environment %s", async view => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
driver: "plugin",
|
|
config: { pluginKey: "example.runtime", driverKey: "tasks", driverConfig: { token: "fixture" } },
|
|
envVars: { API_KEY: "fixture" },
|
|
};
|
|
mockEnvironmentService.list.mockResolvedValue([environment]);
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
const app = createApp({
|
|
type: "board", userId: "user-2", source: "session", companyIds: ["company-1"],
|
|
memberships: [{ companyId: "company-1", status: "active", membershipRole: "member" }],
|
|
isInstanceAdmin: false,
|
|
});
|
|
const response = await request(app).get(view === "list" ? "/api/companies/company-1/environments" : "/api/environments/env-1");
|
|
expect(response.status).toBe(200);
|
|
expect(view === "list" ? response.body[0] : response.body).toMatchObject({
|
|
id: "env-1", pluginDriver: { pluginKey: "example.runtime", driverKey: "tasks" },
|
|
config: {}, envVars: {}, metadata: null,
|
|
});
|
|
expect(JSON.stringify(response.body)).not.toContain("fixture");
|
|
});
|
|
|
|
describe("platform-provisioned environment floor on cloud-managed instances", () => {
|
|
function createPlatformSandboxEnvironment() {
|
|
const now = new Date("2026-04-16T05:00:00.000Z");
|
|
return {
|
|
id: "env-managed-1",
|
|
companyId: "company-1",
|
|
name: "Daytona",
|
|
description: "Managed sandbox environment",
|
|
driver: "sandbox",
|
|
status: "active" as const,
|
|
config: {
|
|
provider: "daytona",
|
|
image: "custom-image:latest",
|
|
target: "us",
|
|
apiKey: "config-credential-must-never-echo",
|
|
},
|
|
envVars: { MY_AGENT_TOOL_SETTING: "tenant-env-value" },
|
|
metadata: { managedByPaperclip: true, managedSandboxProvider: "daytona" },
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
};
|
|
}
|
|
|
|
const ownerAdminActor = {
|
|
type: "board",
|
|
userId: "owner-1",
|
|
source: "cloud_tenant",
|
|
companyIds: ["company-1"],
|
|
memberships: [{ companyId: "company-1", status: "active", membershipRole: "owner" }],
|
|
isInstanceAdmin: true,
|
|
};
|
|
|
|
// A minimal valid managed-config document whose `environments` entry makes
|
|
// the managed-sandbox provisioner own the marked sandbox slot row.
|
|
const MANAGED_CONFIG_WITH_SANDBOX_ENTRY = JSON.stringify({
|
|
v: 1,
|
|
mode: "cloud",
|
|
catalogVersion: "2026.720.0",
|
|
features: {},
|
|
plugins: { autoInstall: [] },
|
|
environments: [{ name: "Sandbox", provider: "daytona" }],
|
|
});
|
|
|
|
beforeEach(() => {
|
|
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "test-server-token";
|
|
});
|
|
afterEach(() => {
|
|
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
|
|
});
|
|
|
|
it("never echoes credential-shaped config keys, while tenant env vars round-trip", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app).get("/api/environments/env-managed-1");
|
|
|
|
expect(res.status).toBe(200);
|
|
// Env vars are the tenant-owned field on the managed sandbox row
|
|
// (the platform never writes them), so they echo for editing.
|
|
expect(res.body.envVars).toEqual({ MY_AGENT_TOOL_SETTING: "tenant-env-value" });
|
|
expect(res.body.config).toEqual({
|
|
provider: "daytona",
|
|
image: "custom-image:latest",
|
|
target: "us",
|
|
});
|
|
expect(res.body.metadata).toMatchObject({ managedByPaperclip: true });
|
|
expect(JSON.stringify(res.body)).not.toContain("config-credential-must-never-echo");
|
|
});
|
|
|
|
it("redacts credential-shaped keys inside arrays nested in arrays", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue({
|
|
...createPlatformSandboxEnvironment(),
|
|
config: {
|
|
provider: "daytona",
|
|
groups: [[{ name: "a", apiToken: "nested-credential-must-never-echo" }], ["plain"]],
|
|
},
|
|
});
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app).get("/api/environments/env-managed-1");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.config).toEqual({ provider: "daytona", groups: [[{ name: "a" }], ["plain"]] });
|
|
expect(JSON.stringify(res.body)).not.toContain("nested-credential-must-never-echo");
|
|
});
|
|
|
|
it("keeps blanking env vars on legacy kubernetes-marker rows", async () => {
|
|
// Pre-generalization builds may have written platform values into
|
|
// these rows' env vars, so the legacy floor stays absolute there.
|
|
mockEnvironmentService.getById.mockResolvedValue({
|
|
...createPlatformSandboxEnvironment(),
|
|
metadata: {
|
|
managedByPaperclip: true,
|
|
managedSandboxProvider: "kubernetes",
|
|
managedKubernetesSandbox: true,
|
|
},
|
|
});
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app).get("/api/environments/env-managed-1");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.envVars).toEqual({});
|
|
});
|
|
|
|
it("exposes structural config to restricted company readers instead of blanking it", async () => {
|
|
mockEnvironmentService.list.mockResolvedValue([createPlatformSandboxEnvironment()]);
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-2",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
memberships: [{ companyId: "company-1", status: "active", membershipRole: "member" }],
|
|
isInstanceAdmin: false,
|
|
});
|
|
|
|
const res = await request(app).get("/api/companies/company-1/environments");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body[0].config).toEqual({
|
|
provider: "daytona",
|
|
image: "custom-image:latest",
|
|
target: "us",
|
|
});
|
|
// Tenant env vars can carry pasted credentials, so restricted readers
|
|
// get the same blank envVars posture as on every other environment.
|
|
expect(res.body[0].envVars).toEqual({});
|
|
expect(res.body[0].metadata).toMatchObject({ managedByPaperclip: true });
|
|
});
|
|
|
|
it("rejects updates to platform-provisioned rows, including for instance admins", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app).patch("/api/environments/env-managed-1").send({ name: "Renamed" });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("allows an envVars-only patch on the managed sandbox row", async () => {
|
|
const row = createPlatformSandboxEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(row);
|
|
mockEnvironmentService.update.mockResolvedValue({
|
|
...row,
|
|
envVars: { MY_AGENT_TOOL_SETTING: "updated-value", EXTRA: "added" },
|
|
});
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1")
|
|
.send({ envVars: { MY_AGENT_TOOL_SETTING: "updated-value", EXTRA: "added" } });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.update).toHaveBeenCalledWith(
|
|
"env-managed-1",
|
|
expect.objectContaining({
|
|
envVars: { MY_AGENT_TOOL_SETTING: "updated-value", EXTRA: "added" },
|
|
}),
|
|
expect.anything(),
|
|
);
|
|
expect(res.body.envVars).toEqual({ MY_AGENT_TOOL_SETTING: "updated-value", EXTRA: "added" });
|
|
});
|
|
|
|
it("scopes the envVars patch to an explicit companyId query for a multi-company actor", async () => {
|
|
const row = createPlatformSandboxEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(row);
|
|
mockEnvironmentService.update.mockResolvedValue({ ...row, envVars: { A: "1" } });
|
|
// No prior bindings and two memberships: neither inference path can
|
|
// pin a company, so the explicit query context must carry the save.
|
|
mockSecretService.listBindingCompanyIdsForTarget.mockResolvedValue([]);
|
|
const app = createApp({
|
|
...ownerAdminActor,
|
|
companyIds: ["company-1", "company-2"],
|
|
memberships: [
|
|
{ companyId: "company-1", status: "active", membershipRole: "owner" },
|
|
{ companyId: "company-2", status: "active", membershipRole: "member" },
|
|
],
|
|
});
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1?companyId=company-1")
|
|
.send({ envVars: { A: "1" } });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockSecretService.normalizeEnvBindingsForPersistence).toHaveBeenCalledWith(
|
|
"company-1",
|
|
{ A: "1" },
|
|
expect.anything(),
|
|
);
|
|
});
|
|
|
|
it("falls back to the instance's only company when the actor's memberships cannot pin one", async () => {
|
|
const row = createPlatformSandboxEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(row);
|
|
mockEnvironmentService.update.mockResolvedValue({ ...row, envVars: { A: "1" } });
|
|
mockSecretService.listBindingCompanyIdsForTarget.mockResolvedValue([]);
|
|
// An instance admin provisioned without membership rows — the
|
|
// owner-as-admin shape on managed stacks.
|
|
const app = createApp({
|
|
...ownerAdminActor,
|
|
companyIds: [],
|
|
memberships: [],
|
|
});
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1")
|
|
.send({ envVars: { A: "1" } });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockSecretService.normalizeEnvBindingsForPersistence).toHaveBeenCalledWith(
|
|
"company-1",
|
|
{ A: "1" },
|
|
expect.anything(),
|
|
);
|
|
});
|
|
|
|
it("still fails closed when no companyId context is resolvable on a multi-company instance", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());
|
|
mockSecretService.listBindingCompanyIdsForTarget.mockResolvedValue([]);
|
|
mockInstanceSettingsService.listCompanyIds.mockResolvedValue(["company-1", "company-2"]);
|
|
const app = createApp({
|
|
...ownerAdminActor,
|
|
companyIds: ["company-1", "company-2"],
|
|
memberships: [
|
|
{ companyId: "company-1", status: "active", membershipRole: "owner" },
|
|
{ companyId: "company-2", status: "active", membershipRole: "member" },
|
|
],
|
|
});
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1")
|
|
.send({ envVars: { A: "1" } });
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.error).toContain("requires a companyId context");
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects a patch that mixes envVars with any other field on the managed sandbox row", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1")
|
|
.send({ envVars: { A: "1" }, name: "Renamed" });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects an envVars-only patch on a legacy kubernetes-marker row", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue({
|
|
...createPlatformSandboxEnvironment(),
|
|
metadata: {
|
|
managedByPaperclip: true,
|
|
managedSandboxProvider: "kubernetes",
|
|
managedKubernetesSandbox: true,
|
|
},
|
|
});
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1")
|
|
.send({ envVars: { A: "1" } });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
|
|
|
|
it("hides the local environment from every read surface under managed-sandbox-only", async () => {
|
|
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableManagedSandboxOnly: true });
|
|
const localRow = {
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-local-1",
|
|
name: "Local",
|
|
driver: "local",
|
|
config: {},
|
|
envVars: {},
|
|
metadata: { managedByPaperclip: true, defaultForInstance: true },
|
|
};
|
|
mockEnvironmentService.list.mockResolvedValue([localRow, createPlatformSandboxEnvironment()]);
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const listRes = await request(app).get("/api/companies/company-1/environments");
|
|
expect(listRes.status).toBe(200);
|
|
expect(listRes.body.map((row: { id: string }) => row.id)).toEqual(["env-managed-1"]);
|
|
|
|
mockEnvironmentService.getById.mockResolvedValue(localRow);
|
|
const byIdRes = await request(app).get("/api/environments/env-local-1");
|
|
expect(byIdRes.status).toBe(404);
|
|
});
|
|
|
|
it("keeps the local environment visible when managed-sandbox-only is off", async () => {
|
|
const localRow = {
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-local-1",
|
|
name: "Local",
|
|
driver: "local",
|
|
config: {},
|
|
envVars: {},
|
|
metadata: { managedByPaperclip: true },
|
|
};
|
|
mockEnvironmentService.list.mockResolvedValue([localRow]);
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const listRes = await request(app).get("/api/companies/company-1/environments");
|
|
expect(listRes.status).toBe(200);
|
|
expect(listRes.body.map((row: { id: string }) => row.id)).toEqual(["env-local-1"]);
|
|
});
|
|
|
|
it("allows a marker-clear-only patch to unblock a row with a stale legacy kubernetes marker", async () => {
|
|
// A sandbox row carrying only the legacy wrapper marker does not hold
|
|
// the managed sandbox slot (`environments_managed_sandbox_idx` keys on
|
|
// `managedByPaperclip`), and with the persisted execution mode not
|
|
// forcing kubernetes nothing selects rows by that marker either — so
|
|
// the marker is a stale leftover, not live platform state.
|
|
const staleRow = {
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-legacy-1",
|
|
metadata: { managedKubernetesSandbox: true },
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(staleRow);
|
|
mockEnvironmentService.update.mockResolvedValue({ ...staleRow, metadata: {} });
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-legacy-1")
|
|
.send({ metadata: { managedKubernetesSandbox: false } });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.update).toHaveBeenCalled();
|
|
});
|
|
|
|
it("allows a marker-clear-only patch on a non-slot driver with a stale platform marker", async () => {
|
|
const staleRow = {
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-stale-ssh-1",
|
|
driver: "ssh",
|
|
metadata: { managedByPaperclip: true },
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(staleRow);
|
|
mockEnvironmentService.update.mockResolvedValue({ ...staleRow, metadata: {} });
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-stale-ssh-1")
|
|
.send({ metadata: { managedByPaperclip: false, managedKubernetesSandbox: false } });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.update).toHaveBeenCalled();
|
|
});
|
|
|
|
it("refuses the marker-clear patch on the sandbox slot row while managed provisioning is configured", async () => {
|
|
// With a managed-config `environments` entry, driver=sandbox +
|
|
// managedByPaperclip is THE provisioner-owned slot row, adopted and
|
|
// refreshed on every boot — clearing its markers would reclassify it
|
|
// tenant-managed and let the next PATCH/DELETE bypass the write floor.
|
|
process.env.PAPERCLIP_MANAGED_CONFIG = MANAGED_CONFIG_WITH_SANDBOX_ENTRY;
|
|
try {
|
|
mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1")
|
|
.send({ metadata: { managedByPaperclip: false, managedKubernetesSandbox: false } });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
} finally {
|
|
delete process.env.PAPERCLIP_MANAGED_CONFIG;
|
|
}
|
|
});
|
|
|
|
it("refuses the marker-clear patch on the sandbox slot row under the forced kubernetes execution mode", async () => {
|
|
// PAPERCLIP_EXECUTION_MODE=kubernetes is the other bootstrap path that
|
|
// owns (adopts and refreshes) the single marked sandbox row.
|
|
process.env.PAPERCLIP_EXECUTION_MODE = "kubernetes";
|
|
try {
|
|
mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1")
|
|
.send({ metadata: { managedByPaperclip: false, managedKubernetesSandbox: false } });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
} finally {
|
|
delete process.env.PAPERCLIP_EXECUTION_MODE;
|
|
}
|
|
});
|
|
|
|
it("refuses the marker-clear patch on a kubernetes-marked row while the persisted execution mode forces kubernetes", async () => {
|
|
// `findKubernetesEnvironment` selects sandbox rows by the legacy
|
|
// marker alone whenever the persisted executionMode forces kubernetes
|
|
// — including when the bootstrap env that seeded the setting is gone
|
|
// (rollback / config drift, which the heartbeat handles explicitly).
|
|
// Clearing the marker would declassify the live runtime row.
|
|
mockInstanceSettingsService.getGeneral.mockResolvedValue({ executionMode: "kubernetes" });
|
|
mockEnvironmentService.getById.mockResolvedValue({
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-legacy-1",
|
|
metadata: { managedKubernetesSandbox: true },
|
|
});
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-legacy-1")
|
|
.send({ metadata: { managedKubernetesSandbox: false } });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("refuses the marker-clear patch on the kubernetes-managed row when only the persisted execution mode remains forced", async () => {
|
|
// Drift variant with the fully-stamped managed row: no managed-config
|
|
// entry and no bootstrap env, but the persisted executionMode still
|
|
// forces kubernetes, so the marker keeps selecting this row for runs.
|
|
mockInstanceSettingsService.getGeneral.mockResolvedValue({ executionMode: "kubernetes" });
|
|
mockEnvironmentService.getById.mockResolvedValue({
|
|
...createPlatformSandboxEnvironment(),
|
|
metadata: {
|
|
managedByPaperclip: true,
|
|
managedSandboxProvider: "kubernetes",
|
|
managedKubernetesSandbox: true,
|
|
},
|
|
});
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1")
|
|
.send({ metadata: { managedByPaperclip: false, managedKubernetesSandbox: false } });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("allows the marker-clear patch on a marked sandbox row when no provisioning path is configured", async () => {
|
|
// Without a managed-config `environments` entry or a forced execution
|
|
// mode, nothing on this instance provisions a sandbox environment, so a
|
|
// platform marker on a sandbox row can only be a stale leftover of the
|
|
// old unrestricted API — the recovery hatch must apply or the row is
|
|
// locked forever.
|
|
const staleRow = createPlatformSandboxEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(staleRow);
|
|
mockEnvironmentService.update.mockResolvedValue({ ...staleRow, metadata: {} });
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1")
|
|
.send({ metadata: { managedByPaperclip: false, managedKubernetesSandbox: false } });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.update).toHaveBeenCalled();
|
|
});
|
|
|
|
it("refuses the marker-clear patch on the managed local row", async () => {
|
|
// The local slot needs no configuration check: on a cloud-managed
|
|
// instance `ensureLocalEnvironment` adopts and stamps the single local
|
|
// row from every caller, so its markers are always live platform state.
|
|
mockEnvironmentService.getById.mockResolvedValue({
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-local-1",
|
|
driver: "local",
|
|
metadata: { managedByPaperclip: true, defaultForInstance: true },
|
|
});
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-local-1")
|
|
.send({ metadata: { managedByPaperclip: false } });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects non-marker-only patches to platform-provisioned rows even from instance admins", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-managed-1")
|
|
.send({ name: "Renamed", metadata: { managedByPaperclip: false } });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects deletes of platform-provisioned rows, including for instance admins", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app).delete("/api/environments/env-managed-1");
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.getDeleteBlastRadius).not.toHaveBeenCalled();
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects creates that stamp platform markers so tenants cannot self-lock rows", async () => {
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Fake managed",
|
|
driver: "sandbox",
|
|
config: { provider: "daytona" },
|
|
metadata: { managedByPaperclip: true },
|
|
});
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_marker_reserved" });
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
describe("managed plugin environment rows", () => {
|
|
const PLUGIN_KEY = "example.remote-host-plugin";
|
|
const MANAGED_CONFIG_WITH_PLUGIN_ENTRY = JSON.stringify({
|
|
v: 1,
|
|
mode: "cloud",
|
|
catalogVersion: "2026.1106.0",
|
|
features: {},
|
|
plugins: { autoInstall: ["remote-host"] },
|
|
environments: [{
|
|
name: "Remote Host",
|
|
driver: "plugin",
|
|
pluginKey: PLUGIN_KEY,
|
|
driverKey: "tasks",
|
|
driverConfig: {},
|
|
}],
|
|
});
|
|
const pluginRow = () => ({
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-plugin-1",
|
|
name: "Remote Host",
|
|
driver: "plugin",
|
|
config: { pluginKey: PLUGIN_KEY, driverKey: "tasks", driverConfig: {} },
|
|
envVars: {},
|
|
metadata: { managedByPaperclip: true, managedPluginEnvironment: `${PLUGIN_KEY}:tasks` },
|
|
});
|
|
|
|
it("refuses edits, env-var edits, and deletes, including for instance admins", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(pluginRow());
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
for (const body of [{ name: "Renamed" }, { envVars: { A: "1" } }, { status: "archived" }]) {
|
|
const res = await request(app).patch("/api/environments/env-plugin-1").send(body);
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
}
|
|
const deleted = await request(app).delete("/api/environments/env-plugin-1");
|
|
expect(deleted.status).toBe(403);
|
|
expect(deleted.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps the row behind the floor on the plugin marker alone", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue({
|
|
...pluginRow(),
|
|
metadata: { managedPluginEnvironment: `${PLUGIN_KEY}:tasks` },
|
|
});
|
|
const res = await request(createApp(ownerAdminActor)).patch("/api/environments/env-plugin-1").send({ name: "Renamed" });
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
});
|
|
|
|
it("refuses a marker clear while the document declares the entry", async () => {
|
|
process.env.PAPERCLIP_MANAGED_CONFIG = MANAGED_CONFIG_WITH_PLUGIN_ENTRY;
|
|
try {
|
|
mockEnvironmentService.getById.mockResolvedValue(pluginRow());
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
for (const metadata of [
|
|
{ managedByPaperclip: false },
|
|
{ managedPluginEnvironment: null },
|
|
{ managedByPaperclip: null, managedPluginEnvironment: null },
|
|
]) {
|
|
const res = await request(app).patch("/api/environments/env-plugin-1").send({ metadata });
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });
|
|
}
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
} finally {
|
|
delete process.env.PAPERCLIP_MANAGED_CONFIG;
|
|
}
|
|
});
|
|
|
|
it("allows the marker clear once the entry left the document", async () => {
|
|
process.env.PAPERCLIP_MANAGED_CONFIG = JSON.stringify({
|
|
...JSON.parse(MANAGED_CONFIG_WITH_PLUGIN_ENTRY),
|
|
environments: [],
|
|
});
|
|
try {
|
|
const row = pluginRow();
|
|
mockEnvironmentService.getById.mockResolvedValue(row);
|
|
mockEnvironmentService.update.mockResolvedValue({ ...row, metadata: {} });
|
|
|
|
const res = await request(createApp(ownerAdminActor))
|
|
.patch("/api/environments/env-plugin-1")
|
|
.send({ metadata: { managedByPaperclip: null, managedPluginEnvironment: null } });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.update).toHaveBeenCalled();
|
|
} finally {
|
|
delete process.env.PAPERCLIP_MANAGED_CONFIG;
|
|
}
|
|
});
|
|
|
|
it("refuses a client that stamps the plugin marker on its own row", async () => {
|
|
const res = await request(createApp(ownerAdminActor))
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Fake remote host",
|
|
driver: "plugin",
|
|
config: { pluginKey: PLUGIN_KEY, driverKey: "tasks", driverConfig: {} },
|
|
metadata: { managedPluginEnvironment: `${PLUGIN_KEY}:tasks` },
|
|
});
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_marker_reserved" });
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
it("rejects tenant patches that stamp platform markers so the row cannot become locked", async () => {
|
|
const tenantEnvironment = {
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-tenant-1",
|
|
metadata: { source: "manual" },
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(tenantEnvironment);
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-tenant-1")
|
|
.send({ metadata: { source: "manual", managedKubernetesSandbox: true } });
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.details).toMatchObject({ code: "environment_platform_marker_reserved" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("accepts platform markers in client payloads on self-hosted instances", async () => {
|
|
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
|
|
const existing = {
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-tenant-1",
|
|
metadata: { source: "manual" },
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(existing);
|
|
mockEnvironmentService.update.mockResolvedValue({
|
|
...existing,
|
|
metadata: { source: "manual", managedByPaperclip: true },
|
|
});
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "admin-1",
|
|
source: "session",
|
|
isInstanceAdmin: true,
|
|
});
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-tenant-1")
|
|
.send({ metadata: { source: "manual", managedByPaperclip: true } });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.update).toHaveBeenCalled();
|
|
});
|
|
|
|
it("still updates tenant-created environments for instance admins on cloud-managed instances", async () => {
|
|
const tenantEnvironment = {
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-tenant-1",
|
|
metadata: { source: "manual" },
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(tenantEnvironment);
|
|
mockEnvironmentService.update.mockResolvedValue({ ...tenantEnvironment, name: "Renamed" });
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app).patch("/api/environments/env-tenant-1").send({ name: "Renamed" });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.name).toBe("Renamed");
|
|
expect(mockEnvironmentService.update).toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not floor writes to platform-marked rows on self-hosted instances", async () => {
|
|
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
|
|
const existing = createPlatformSandboxEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(existing);
|
|
mockEnvironmentService.update.mockResolvedValue({ ...existing, name: "Renamed" });
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "admin-1",
|
|
source: "session",
|
|
isInstanceAdmin: true,
|
|
});
|
|
|
|
const res = await request(app).patch("/api/environments/env-managed-1").send({ name: "Renamed" });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.name).toBe("Renamed");
|
|
});
|
|
|
|
it("leaves tenant-created environments unfloored for instance admins", async () => {
|
|
const tenantEnvironment = {
|
|
...createPlatformSandboxEnvironment(),
|
|
id: "env-tenant-1",
|
|
metadata: { source: "manual" },
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(tenantEnvironment);
|
|
const app = createApp(ownerAdminActor);
|
|
|
|
const res = await request(app).get("/api/environments/env-tenant-1");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.envVars).toEqual({ MY_AGENT_TOOL_SETTING: "tenant-env-value" });
|
|
expect(res.body.config.apiKey).toBe("config-credential-must-never-echo");
|
|
});
|
|
|
|
it("does not floor platform-marked rows on self-hosted instances", async () => {
|
|
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
|
|
mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "admin-1",
|
|
source: "session",
|
|
isInstanceAdmin: true,
|
|
});
|
|
|
|
const res = await request(app).get("/api/environments/env-managed-1");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.envVars).toEqual({ MY_AGENT_TOOL_SETTING: "tenant-env-value" });
|
|
expect(res.body.config.apiKey).toBe("config-credential-must-never-echo");
|
|
});
|
|
});
|
|
|
|
it("rejects non-admin blast-radius reads for instance-scoped environments", async () => {
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-2",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
memberships: [{ companyId: "company-1", status: "active", membershipRole: "member" }],
|
|
isInstanceAdmin: false,
|
|
});
|
|
|
|
const res = await request(app).get("/api/environments/env-1/delete-blast-radius");
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(mockEnvironmentService.getDeleteBlastRadius).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns delete blast radius counts for instance admins", async () => {
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius({
|
|
agentDefaultCount: 2,
|
|
secretBindingCount: 3,
|
|
activeLeaseCount: 1,
|
|
}));
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "admin-1",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
isInstanceAdmin: true,
|
|
});
|
|
|
|
const res = await request(app).get("/api/environments/env-1/delete-blast-radius");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body).toEqual({
|
|
environmentId: "env-1",
|
|
canDelete: true,
|
|
deleteBlockedReasons: [],
|
|
pendingCleanupLeaseCount: 0,
|
|
reusableSandboxLeaseCount: 0,
|
|
reusableSandboxLeaseHolders: [],
|
|
staticReferences: {
|
|
isManagedLocal: false,
|
|
isInstanceDefault: false,
|
|
agentDefaultCount: 2,
|
|
executionWorkspaceSelectionCount: 0,
|
|
issueSelectionCount: 0,
|
|
projectSelectionCount: 0,
|
|
secretBindingCount: 3,
|
|
},
|
|
activeRuntimeUse: {
|
|
activeLeaseCount: 1,
|
|
activeCustomImageSetupSessionCount: 0,
|
|
hasActiveRuntimeUse: true,
|
|
},
|
|
});
|
|
expect(res.body).not.toHaveProperty("config");
|
|
expect(res.body).not.toHaveProperty("envVars");
|
|
expect(res.body).not.toHaveProperty("metadata");
|
|
});
|
|
|
|
it("returns 404 for missing delete blast radius targets", async () => {
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(null);
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "admin-1",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
isInstanceAdmin: true,
|
|
});
|
|
|
|
const res = await request(app).get("/api/environments/missing/delete-blast-radius");
|
|
|
|
expect(res.status).toBe(404);
|
|
expect(res.body.error).toBe("Environment not found");
|
|
});
|
|
|
|
it("returns provider capabilities for the company", async () => {
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app).get("/api/companies/company-1/environments/capabilities");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.drivers.ssh).toBe("supported");
|
|
expect(res.body.sandboxProviders.fake.supportsRunExecution).toBe(false);
|
|
expect(res.body.sandboxProviders).not.toHaveProperty("fake-plugin");
|
|
});
|
|
|
|
it("returns installed plugin-backed sandbox capabilities for environment creation", async () => {
|
|
mockListReadyPluginEnvironmentDrivers.mockResolvedValue([
|
|
{
|
|
pluginId: "plugin-1",
|
|
pluginKey: "acme.secure-sandbox-provider",
|
|
driverKey: "secure-plugin",
|
|
displayName: "Secure Sandbox",
|
|
description: "Provisions schema-driven cloud sandboxes.",
|
|
supportsInteractiveSetup: true,
|
|
interactiveSetupConnectionTypes: ["ssh"],
|
|
supportsTemplateCapture: true,
|
|
templateRefKind: "snapshot",
|
|
templateConfigBinding: {
|
|
field: "template",
|
|
unsetFields: ["image"],
|
|
},
|
|
supportsTemplateDelete: true,
|
|
configSchema: {
|
|
type: "object",
|
|
properties: {
|
|
template: { type: "string" },
|
|
apiKey: { type: "string", format: "secret-ref" },
|
|
},
|
|
},
|
|
},
|
|
]);
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app).get("/api/companies/company-1/environments/capabilities");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.sandboxProviders["secure-plugin"]).toMatchObject({
|
|
status: "supported",
|
|
supportsRunExecution: true,
|
|
// The mock manifest omits reusable leases, so the capability defaults to
|
|
// false and agrees with the execution guard.
|
|
supportsReusableLeases: false,
|
|
supportsInteractiveSetup: true,
|
|
interactiveSetupConnectionTypes: ["ssh"],
|
|
supportsTemplateCapture: true,
|
|
templateRefKind: "snapshot",
|
|
templateConfigBinding: {
|
|
field: "template",
|
|
unsetFields: ["image"],
|
|
},
|
|
supportsTemplateDelete: true,
|
|
displayName: "Secure Sandbox",
|
|
source: "plugin",
|
|
pluginKey: "acme.secure-sandbox-provider",
|
|
pluginId: "plugin-1",
|
|
configSchema: {
|
|
type: "object",
|
|
properties: {
|
|
template: { type: "string" },
|
|
apiKey: { type: "string", format: "secret-ref" },
|
|
},
|
|
},
|
|
});
|
|
expect(res.body.adapters.find((row: any) => row.adapterType === "codex_local").sandboxProviders["secure-plugin"])
|
|
.toBe("supported");
|
|
});
|
|
|
|
it("publishes reusable leases from the nested capability, not the legacy flag, so the API agrees with acquisition", async () => {
|
|
// The manifest sets the legacy flag `true` but the nested override `false`.
|
|
// Acquisition lets the nested value win and refuses reuse. The published
|
|
// API value must derive from the same declaration resolver and present the
|
|
// provider as not reusable, even when the worker verified both lifecycle
|
|
// methods.
|
|
mockListReadyPluginEnvironmentDrivers.mockResolvedValue([
|
|
{
|
|
pluginId: "plugin-1",
|
|
pluginKey: "acme.legacy-override-provider",
|
|
driverKey: "override-plugin",
|
|
displayName: "Override Sandbox",
|
|
supportsReusableLeases: true,
|
|
sandboxCapabilities: { reusableLeases: false },
|
|
reusableLeaseMethodsVerified: true,
|
|
configSchema: { type: "object", properties: {} },
|
|
},
|
|
]);
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app).get("/api/companies/company-1/environments/capabilities");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.sandboxProviders["override-plugin"].supportsReusableLeases).toBe(false);
|
|
});
|
|
|
|
it("publishes reusable leases from the legacy flag when the manifest omits the nested override and the worker verified both methods", async () => {
|
|
mockListReadyPluginEnvironmentDrivers.mockResolvedValue([
|
|
{
|
|
pluginId: "plugin-1",
|
|
pluginKey: "acme.legacy-only-provider",
|
|
driverKey: "legacy-plugin",
|
|
displayName: "Legacy Sandbox",
|
|
supportsReusableLeases: true,
|
|
reusableLeaseMethodsVerified: true,
|
|
configSchema: { type: "object", properties: {} },
|
|
},
|
|
]);
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app).get("/api/companies/company-1/environments/capabilities");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.sandboxProviders["legacy-plugin"].supportsReusableLeases).toBe(true);
|
|
});
|
|
|
|
it("does not publish reusable leases when the declaration allows them but the worker omits a lifecycle method", async () => {
|
|
// A positive declaration alone is not enough. Acquisition verifies both
|
|
// reuse lifecycle methods live and falls back to an ephemeral lease when one
|
|
// is missing. The published value must agree and present as not reusable.
|
|
mockListReadyPluginEnvironmentDrivers.mockResolvedValue([
|
|
{
|
|
pluginId: "plugin-1",
|
|
pluginKey: "acme.unverified-reuse-provider",
|
|
driverKey: "unverified-plugin",
|
|
displayName: "Unverified Reuse Sandbox",
|
|
sandboxCapabilities: { reusableLeases: true },
|
|
reusableLeaseMethodsVerified: false,
|
|
configSchema: { type: "object", properties: {} },
|
|
},
|
|
]);
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app).get("/api/companies/company-1/environments/capabilities");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.sandboxProviders["unverified-plugin"].supportsReusableLeases).toBe(false);
|
|
});
|
|
|
|
it("rejects agent list reads for instance-scoped environments", async () => {
|
|
mockEnvironmentService.list.mockResolvedValue([createEnvironment()]);
|
|
mockAgentService.getById.mockResolvedValue({
|
|
id: "agent-1",
|
|
companyId: "company-1",
|
|
role: "engineer",
|
|
permissions: { canCreateAgents: false },
|
|
});
|
|
mockAccessService.hasPermission.mockResolvedValue(false);
|
|
const app = createApp({
|
|
type: "agent",
|
|
agentId: "agent-1",
|
|
companyId: "company-1",
|
|
source: "agent_key",
|
|
runId: "run-1",
|
|
});
|
|
|
|
const res = await request(app).get("/api/companies/company-1/environments");
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error).toContain("Board access required");
|
|
expect(mockEnvironmentService.list).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([
|
|
["get", "/api/companies/company-1/environments/capabilities"],
|
|
["post", "/api/companies/company-1/environments"],
|
|
["post", "/api/environments/env-1/probe"],
|
|
["patch", "/api/environments/env-1"],
|
|
["delete", "/api/environments/env-1"],
|
|
["get", "/api/environments/env-1/leases"],
|
|
] as const)("gives an agent denied %s %s the final environment settings guidance", async (method, path) => {
|
|
const app = createApp({ type: "agent", agentId: "agent-1", companyId: "company-1", source: "agent_key", runId: "run-1" });
|
|
const res = await request(app)[method](path).send(method === "post" && path.endsWith("/environments") ? { name: "Agent computer", driver: "local", config: {} } : {});
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error).toBe("Board access required");
|
|
expect(res.body.remediation).toContain("this denial is final");
|
|
expect(res.body.remediation).toContain("Execution environments are board-only throughout");
|
|
expect(res.body.remediation).toContain("[Open environment settings](/<prefix>/company/settings/instance/environments)");
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects agent detail reads for instance-scoped environments", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(createEnvironment());
|
|
mockAgentService.getById.mockResolvedValue({
|
|
id: "agent-1",
|
|
companyId: "company-1",
|
|
role: "cto",
|
|
permissions: { canCreateAgents: true },
|
|
});
|
|
mockAccessService.hasPermission.mockResolvedValue(false);
|
|
const app = createApp({
|
|
type: "agent",
|
|
agentId: "agent-1",
|
|
companyId: "company-1",
|
|
source: "agent_key",
|
|
runId: "run-1",
|
|
});
|
|
|
|
const res = await request(app).get("/api/environments/env-1");
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error).toContain("Board access required");
|
|
});
|
|
|
|
it("creates an environment and logs activity", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Local",
|
|
driver: "local",
|
|
description: "Current development machine",
|
|
config: { shell: "zsh" },
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockEnvironmentService.create).toHaveBeenCalledWith({
|
|
name: "Local",
|
|
driver: "local",
|
|
description: "Current development machine",
|
|
status: "active",
|
|
config: { shell: "zsh" },
|
|
envVars: {},
|
|
}, undefined, { db: routeDbTx });
|
|
expect(mockLogActivity).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
companyId: "company-1",
|
|
actorType: "user",
|
|
actorId: "user-1",
|
|
agentId: null,
|
|
runId: null,
|
|
action: "environment.created",
|
|
entityType: "environment",
|
|
entityId: environment.id,
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("returns conflict when creating a second local environment", async () => {
|
|
mockEnvironmentService.list.mockResolvedValue([createEnvironment()]);
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Another Local",
|
|
driver: "local",
|
|
config: {},
|
|
});
|
|
|
|
expect(res.status).toBe(409);
|
|
expect(res.body.error).toBe("A local environment already exists for this instance.");
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects non-admin board users even when they have company environment permissions", async () => {
|
|
const environment = createEnvironment();
|
|
mockAccessService.canUser.mockResolvedValue(true);
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
isInstanceAdmin: false,
|
|
});
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Local",
|
|
driver: "local",
|
|
config: {},
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error).toContain("Instance admin access required");
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects non-admin board users without instance admin access", async () => {
|
|
mockAccessService.canUser.mockResolvedValue(false);
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
isInstanceAdmin: false,
|
|
});
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Local",
|
|
driver: "local",
|
|
config: {},
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error).toContain("Instance admin access required");
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects agent environment creation even with explicit company grants", async () => {
|
|
const environment = createEnvironment();
|
|
mockAgentService.getById.mockResolvedValue({
|
|
id: "agent-1",
|
|
companyId: "company-1",
|
|
role: "engineer",
|
|
permissions: { canCreateAgents: false },
|
|
});
|
|
mockAccessService.hasPermission.mockResolvedValue(true);
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
const app = createApp({
|
|
type: "agent",
|
|
agentId: "agent-1",
|
|
companyId: "company-1",
|
|
source: "agent_key",
|
|
runId: "run-1",
|
|
});
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Local",
|
|
driver: "local",
|
|
config: {},
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error).toBe("Board access required");
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects deleting the managed local environment", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius({
|
|
isManagedLocal: true,
|
|
}));
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app).delete("/api/environments/env-1");
|
|
|
|
expect(res.status).toBe(409);
|
|
expect(res.body.error).toBe("Cannot delete the managed local environment.");
|
|
expect(res.body.details).toEqual({ deleteBlockedReasons: ["managed_local"] });
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
expect(mockExecutionWorkspaceService.clearEnvironmentSelection).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects deleting the current instance default environment", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
driver: "ssh" as const,
|
|
name: "SSH Fixture",
|
|
config: createSshConfig(),
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius({
|
|
isInstanceDefault: true,
|
|
}));
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app).delete("/api/environments/env-1");
|
|
|
|
expect(res.status).toBe(409);
|
|
expect(res.body.error).toBe(
|
|
"Cannot delete the current instance default environment. Set a new default environment before deleting this one.",
|
|
);
|
|
expect(res.body.details).toEqual({ deleteBlockedReasons: ["instance_default"] });
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects deleting an environment with a pending sandbox cleanup", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
driver: "ssh" as const,
|
|
name: "SSH Fixture",
|
|
config: createSshConfig(),
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius({
|
|
pendingCleanupLeaseCount: 1,
|
|
}));
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app).delete("/api/environments/env-1");
|
|
|
|
expect(res.status).toBe(409);
|
|
expect(res.body.error).toBe(
|
|
"Cannot delete this environment while a sandbox cleanup is pending. Wait for the cleanup sweep to destroy the orphan sandbox, then retry.",
|
|
);
|
|
expect(res.body.details).toEqual({ deleteBlockedReasons: ["pending_sandbox_cleanup"] });
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects deleting an environment with a live reusable sandbox lease", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
driver: "sandbox" as const,
|
|
name: "Reusable Sandbox Fixture",
|
|
config: {
|
|
provider: "fake-plugin",
|
|
image: "fixture:test",
|
|
reuseLease: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius({
|
|
activeLeaseCount: 1,
|
|
reusableSandboxLeaseCount: 1,
|
|
}));
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app).delete("/api/environments/env-1");
|
|
|
|
expect(res.status).toBe(409);
|
|
expect(res.body.error).toBe(
|
|
"Cannot delete this environment while it has a reusable sandbox lease. Remove the associated execution workspace or issue so Paperclip can destroy the sandbox, then retry.",
|
|
);
|
|
expect(res.body.details).toEqual({ deleteBlockedReasons: ["reusable_sandbox_lease"] });
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
expect(mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("destroys reusable sandbox leases and deletes with explicit consent", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius
|
|
.mockResolvedValueOnce(createDeleteBlastRadius({ reusableSandboxLeaseCount: 2 }))
|
|
.mockResolvedValueOnce(createDeleteBlastRadius());
|
|
mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment.mockResolvedValue({
|
|
destroyed: 2,
|
|
failed: 0,
|
|
skippedLiveRun: 0,
|
|
});
|
|
mockEnvironmentService.removeIfDeletable.mockResolvedValue(environment);
|
|
mockInstanceSettingsService.listCompanyIds.mockResolvedValue(["company-1"]);
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app).delete("/api/environments/env-1?destroyReusableSandboxLeases=true");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(
|
|
mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment,
|
|
).toHaveBeenCalledExactlyOnceWith({
|
|
environmentId: "env-1",
|
|
failureReason: "environment_deleted",
|
|
consentedBy: "admin-1",
|
|
});
|
|
expect(
|
|
mockCloseWarmNativeSessionsForEnvironment,
|
|
).toHaveBeenCalledExactlyOnceWith({
|
|
environmentId: "env-1",
|
|
reason: "environment deleted",
|
|
forceStopUnsettled: true,
|
|
db: expect.anything(),
|
|
});
|
|
expect(mockEnvironmentService.removeIfDeletable).toHaveBeenCalledWith(
|
|
"env-1",
|
|
);
|
|
expect(res.body.destroyedReusableSandboxLeaseCount).toBe(2);
|
|
});
|
|
|
|
it("names the warm runner session that could not be stopped and why", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius({ reusableSandboxLeaseCount: 1 }));
|
|
const failure = { runId: "run-parked", issueId: "issue-1", environmentId: "env-1", providerLeaseId: "sandbox-1",
|
|
reason: "close failed: native_session_close_unrecoverable: runner did not durably suspend; forced Runner stop failed: handoff unconfirmed" };
|
|
mockCloseWarmNativeSessionsForEnvironment.mockResolvedValue({ closed: 0, busy: 0, failed: 1, failures: [failure] });
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app).delete("/api/environments/env-1?destroyReusableSandboxLeases=true");
|
|
|
|
expect(res.status).toBe(409);
|
|
expect(res.body.error).toContain(`run run-parked: ${failure.reason}`);
|
|
expect(res.body.details.nativeRunnerSessions.failures).toEqual([failure]);
|
|
expect(mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment).not.toHaveBeenCalled();
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps rejecting a consented delete when a non-lease blocker remains", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius({
|
|
isInstanceDefault: true,
|
|
reusableSandboxLeaseCount: 1,
|
|
}));
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app).delete("/api/environments/env-1?destroyReusableSandboxLeases=true");
|
|
|
|
// Destroying provider sandboxes and then rejecting on the other gate would
|
|
// be an irreversible action with nothing gained, so the destroy must not run.
|
|
expect(res.status).toBe(409);
|
|
expect(mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment).not.toHaveBeenCalled();
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps rejecting when leases survive the consented destroy", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius
|
|
.mockResolvedValueOnce(createDeleteBlastRadius({ reusableSandboxLeaseCount: 1 }))
|
|
.mockResolvedValueOnce(createDeleteBlastRadius({ pendingCleanupLeaseCount: 1 }));
|
|
mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment.mockResolvedValue({
|
|
destroyed: 1,
|
|
failed: 1,
|
|
skippedLiveRun: 0,
|
|
});
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app).delete("/api/environments/env-1?destroyReusableSandboxLeases=true");
|
|
|
|
expect(res.status).toBe(409);
|
|
// The rejection names what the consented destroy already did: provider
|
|
// destruction is not transactional with the delete guard.
|
|
expect(res.body.details).toEqual({
|
|
deleteBlockedReasons: ["pending_sandbox_cleanup"],
|
|
destroyedReusableSandboxLeaseCount: 1,
|
|
});
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("runs the environment's pending sandbox cleanup now and deletes with explicit consent", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius
|
|
.mockResolvedValueOnce(createDeleteBlastRadius({ pendingCleanupLeaseCount: 1 }))
|
|
.mockResolvedValueOnce(createDeleteBlastRadius());
|
|
mockEnvironmentService.removeIfDeletable.mockResolvedValue(environment);
|
|
mockInstanceSettingsService.listCompanyIds.mockResolvedValue(["company-1"]);
|
|
const retryPendingEnvironmentCleanup = vi.fn(async () => ({ swept: 1, destroyed: 1, capped: 0 }));
|
|
const app = createApp(localBoardActor("admin-1"), { retryPendingEnvironmentCleanup });
|
|
|
|
const res = await request(app).delete("/api/environments/env-1?destroyReusableSandboxLeases=true");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(retryPendingEnvironmentCleanup).toHaveBeenCalledExactlyOnceWith({ environmentId: "env-1", actorId: "admin-1" });
|
|
// Consent releases restore-source protection before the cleanup retry, or a
|
|
// protected source would refuse every attempt and keep the delete blocked.
|
|
expect(mockEnvironmentRuntimeService.releaseRestoreSourcesForEnvironmentDelete)
|
|
.toHaveBeenCalledWith({ environmentId: "env-1", consentedBy: "admin-1" });
|
|
expect(mockEnvironmentRuntimeService.releaseRestoreSourcesForEnvironmentDelete.mock.invocationCallOrder[0])
|
|
.toBeLessThan(retryPendingEnvironmentCleanup.mock.invocationCallOrder[0]!);
|
|
expect(mockEnvironmentService.removeIfDeletable).toHaveBeenCalledWith("env-1");
|
|
});
|
|
|
|
it("keeps rejecting when the consented pending cleanup attempt does not finish", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius({ pendingCleanupLeaseCount: 1 }));
|
|
const retryPendingEnvironmentCleanup = vi.fn(async () => ({ swept: 1, destroyed: 0, capped: 0 }));
|
|
const app = createApp(localBoardActor("admin-1"), { retryPendingEnvironmentCleanup });
|
|
|
|
const res = await request(app).delete("/api/environments/env-1?destroyReusableSandboxLeases=true");
|
|
|
|
expect(res.status).toBe(409);
|
|
expect(res.body.details).toEqual({ deleteBlockedReasons: ["pending_sandbox_cleanup"] });
|
|
expect(retryPendingEnvironmentCleanup).toHaveBeenCalledOnce();
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not run pending sandbox cleanup without consent or past another blocker", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
const retryPendingEnvironmentCleanup = vi.fn(async () => ({ swept: 0, destroyed: 0, capped: 0 }));
|
|
const app = createApp(localBoardActor("admin-1"), { retryPendingEnvironmentCleanup });
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius({ pendingCleanupLeaseCount: 1 }));
|
|
expect((await request(app).delete("/api/environments/env-1")).status).toBe(409);
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius({
|
|
pendingCleanupLeaseCount: 1, isInstanceDefault: true,
|
|
}));
|
|
expect((await request(app).delete("/api/environments/env-1?destroyReusableSandboxLeases=true")).status).toBe(409);
|
|
expect(retryPendingEnvironmentCleanup).not.toHaveBeenCalled();
|
|
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects a driver or provider config change while a sandbox cleanup is pending", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
id: "env-ssh",
|
|
driver: "ssh" as const,
|
|
name: "SSH Fixture",
|
|
config: createSshConfig(),
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.hasUnresolvedPendingCleanupLeases.mockResolvedValue(true);
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-ssh")
|
|
.send({
|
|
config: {
|
|
host: "changed.example.test",
|
|
port: 22,
|
|
username: "ssh-user",
|
|
remoteWorkspacePath: "/srv/paperclip/workspace",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(409);
|
|
expect(res.body.error).toBe(
|
|
"Cannot change the driver or provider config while a sandbox cleanup is pending. Wait for the cleanup sweep to destroy the orphan sandbox, then retry.",
|
|
);
|
|
expect(res.body.details).toEqual({ code: "environment_pending_sandbox_cleanup" });
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("allows a non-provider update while a sandbox cleanup is pending", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
id: "env-ssh",
|
|
driver: "ssh" as const,
|
|
name: "SSH Fixture",
|
|
config: createSshConfig(),
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.hasUnresolvedPendingCleanupLeases.mockResolvedValue(true);
|
|
mockEnvironmentService.update.mockResolvedValue({ ...environment, description: "Updated" });
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-ssh")
|
|
.send({ description: "Updated" });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.hasUnresolvedPendingCleanupLeases).not.toHaveBeenCalled();
|
|
expect(mockEnvironmentService.update).toHaveBeenCalled();
|
|
});
|
|
|
|
it("describes an environment's secret refs with owner metadata", async () => {
|
|
const secretId = "22222222-2222-2222-2222-222222222222";
|
|
mockEnvironmentService.getById.mockResolvedValue({
|
|
...createEnvironment(),
|
|
id: "env-sandbox",
|
|
name: "Daytona",
|
|
driver: "sandbox" as const,
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: secretId,
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
});
|
|
mockSecretService.describeSecretRefs.mockResolvedValue([
|
|
{
|
|
configPath: "apiKey",
|
|
secretId,
|
|
name: "DAYTONA_API_KEY",
|
|
status: "active",
|
|
companyId: "company-2",
|
|
companyName: "Other Team",
|
|
},
|
|
]);
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app).get("/api/environments/env-sandbox/secret-refs");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.refs).toEqual([
|
|
{
|
|
configPath: "apiKey",
|
|
secretId,
|
|
name: "DAYTONA_API_KEY",
|
|
status: "active",
|
|
companyId: "company-2",
|
|
companyName: "Other Team",
|
|
},
|
|
]);
|
|
expect(mockSecretService.describeSecretRefs).toHaveBeenCalledWith([
|
|
{ secretId, configPath: "apiKey", versionSelector: "latest" },
|
|
]);
|
|
});
|
|
|
|
it("denies secret-ref descriptors to agents without instance environment access", async () => {
|
|
mockAgentService.getById.mockResolvedValue({
|
|
id: "agent-1",
|
|
companyId: "company-1",
|
|
role: "engineer",
|
|
permissions: { canCreateAgents: false },
|
|
});
|
|
mockAccessService.hasPermission.mockResolvedValue(false);
|
|
const app = createApp({
|
|
type: "agent",
|
|
agentId: "agent-1",
|
|
companyId: "company-1",
|
|
source: "agent_key",
|
|
});
|
|
|
|
const res = await request(app).get("/api/environments/env-1/secret-refs");
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(mockSecretService.describeSecretRefs).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("clears environment selections and secret bindings across all companies when deleting an environment", async () => {
|
|
const environment = createSecretBackedSshEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.getDeleteBlastRadius.mockResolvedValue(createDeleteBlastRadius());
|
|
mockEnvironmentService.removeIfDeletable.mockResolvedValue(environment);
|
|
mockInstanceSettingsService.listCompanyIds.mockResolvedValue(["company-1", "company-2"]);
|
|
const app = createApp(localBoardActor("admin-1"));
|
|
|
|
const res = await request(app).delete("/api/environments/env-ssh");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.removeIfDeletable).toHaveBeenCalledWith("env-ssh");
|
|
for (const companyId of ["company-1", "company-2"]) {
|
|
expect(mockExecutionWorkspaceService.clearEnvironmentSelection)
|
|
.toHaveBeenCalledWith(companyId, "env-ssh");
|
|
expect(mockIssueService.clearExecutionWorkspaceEnvironmentSelection)
|
|
.toHaveBeenCalledWith(companyId, "env-ssh");
|
|
expect(mockProjectService.clearExecutionWorkspaceEnvironmentSelection)
|
|
.toHaveBeenCalledWith(companyId, "env-ssh");
|
|
expect(mockSecretService.syncEnvBindingsForTarget).toHaveBeenCalledWith(
|
|
companyId,
|
|
{ targetType: "environment", targetId: "env-ssh" },
|
|
{},
|
|
);
|
|
expect(mockSecretService.syncSecretRefsForTarget).toHaveBeenCalledWith(
|
|
companyId,
|
|
{ targetType: "environment", targetId: "env-ssh" },
|
|
[],
|
|
{ replaceAll: true },
|
|
);
|
|
}
|
|
expect(mockSecretService.remove).toHaveBeenCalledWith("11111111-1111-1111-1111-111111111111");
|
|
expect(mockLogActivity).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
companyId: "company-1",
|
|
action: "environment.deleted",
|
|
entityType: "environment",
|
|
entityId: "env-ssh",
|
|
}),
|
|
);
|
|
});
|
|
|
|
it.each([undefined, true, false])("defaults new SSH API environments to managed auth while preserving explicit %s", async (useHostAuth) => {
|
|
const environment = { ...createEnvironment(), driver: "ssh" as const, config: createSshConfig() };
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
const app = createApp(localBoardActor());
|
|
const res = await request(app).post("/api/companies/company-1/environments").send({
|
|
name: "SSH Fixture", driver: "ssh", config: { ...createSshConfig(), ...(useHostAuth === undefined ? {} : { useHostAuth }) },
|
|
});
|
|
expect(res.status).toBe(201);
|
|
expect(mockEnvironmentService.create.mock.calls[0]![0].config.useHostAuth).toBe(useHostAuth ?? false);
|
|
});
|
|
|
|
it("preserves absent authentication on an existing SSH API environment update", async () => {
|
|
const environment = { ...createEnvironment(), id: "env-ssh", driver: "ssh" as const, config: createSshConfig() };
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.update.mockResolvedValue(environment);
|
|
const app = createApp(localBoardActor());
|
|
const res = await request(app).patch("/api/environments/env-ssh").send({ config: { host: "changed.example.test" } });
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.update.mock.calls[0]![1].config).not.toHaveProperty("useHostAuth");
|
|
});
|
|
|
|
it("rejects invalid SSH config on create", async () => {
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "SSH Fixture",
|
|
driver: "ssh",
|
|
config: {
|
|
host: "ssh.example.test",
|
|
username: "ssh-user",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.error).toContain("remote workspace path");
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects standalone Tailscale enrollment keys before storing an environment secret", async () => {
|
|
const res = await request(createApp(localBoardActor())).post("/api/companies/company-1/environments").send({
|
|
name: "My workstation", driver: "ssh", config: { network: "tailscale", host: "workstation", username: "developer",
|
|
remoteWorkspacePath: "/workspace", tailscaleAuthKey: "tskey-auth-fixture" },
|
|
});
|
|
expect(res.status).toBe(422);
|
|
expect(mockSecretService.create).not.toHaveBeenCalled();
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
expect(JSON.stringify(res.body)).not.toContain("tskey-auth-fixture");
|
|
});
|
|
|
|
it("rejects Tailscale environment setup from a non-admin before storing credentials", async () => {
|
|
const res = await request(createApp({ type: "board", userId: "member", source: "session", companyIds: ["company-1"] }))
|
|
.post("/api/companies/company-1/environments").send({ name: "My workstation", driver: "ssh", config: {
|
|
network: "tailscale", host: "workstation", username: "developer", remoteWorkspacePath: "/workspace", tailscaleAuthKey: "tskey-auth-fixture" } });
|
|
expect(res.status).toBe(403);
|
|
expect(mockSecretService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("normalizes SSH private keys into secret refs before persistence", async () => {
|
|
const environment = createSecretBackedSshEnvironment();
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
const pluginWorkerManager = {};
|
|
const app = createApp(localBoardActor(), { pluginWorkerManager });
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "SSH Fixture",
|
|
driver: "ssh",
|
|
config: {
|
|
host: "ssh.example.test",
|
|
username: "ssh-user",
|
|
remoteWorkspacePath: "/srv/paperclip/workspace",
|
|
privateKey: " super-secret-key ",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockEnvironmentService.create).toHaveBeenCalledWith(expect.objectContaining({
|
|
config: expect.objectContaining({
|
|
privateKey: null,
|
|
privateKeySecretRef: {
|
|
type: "secret_ref",
|
|
secretId: "11111111-1111-1111-1111-111111111111",
|
|
version: "latest",
|
|
},
|
|
}),
|
|
envVars: {},
|
|
}), undefined, { db: routeDbTx });
|
|
expect(JSON.stringify(mockEnvironmentService.create.mock.calls[0][0])).not.toContain("super-secret-key");
|
|
expect(mockSecretService.create).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({
|
|
provider: "local_encrypted",
|
|
value: "super-secret-key",
|
|
}),
|
|
expect.any(Object),
|
|
);
|
|
});
|
|
|
|
it("uses the configured provider for SSH private key secret materialization", async () => {
|
|
process.env.PAPERCLIP_SECRETS_PROVIDER = "aws_secrets_manager";
|
|
const environment = createSecretBackedSshEnvironment();
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "SSH Fixture",
|
|
driver: "ssh",
|
|
config: {
|
|
host: "ssh.example.test",
|
|
username: "ssh-user",
|
|
remoteWorkspacePath: "/srv/paperclip/workspace",
|
|
privateKey: "super-secret-key",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockSecretService.create).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({
|
|
provider: "aws_secrets_manager",
|
|
value: "super-secret-key",
|
|
}),
|
|
expect.any(Object),
|
|
);
|
|
});
|
|
|
|
it("rejects persisted fake sandbox environments", async () => {
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Fake Sandbox",
|
|
driver: "sandbox",
|
|
config: {
|
|
provider: "fake",
|
|
image: " ubuntu:24.04 ",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.error).toContain("reserved for internal probes");
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("creates a sandbox environment with normalized Fake plugin config", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
id: "env-sandbox-fake-plugin",
|
|
name: "Fake plugin Sandbox",
|
|
driver: "sandbox" as const,
|
|
config: {
|
|
provider: "fake-plugin",
|
|
image: "fake:test",
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
const pluginWorkerManager = {};
|
|
const app = createApp(localBoardActor(), { pluginWorkerManager });
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Fake plugin Sandbox",
|
|
driver: "sandbox",
|
|
config: {
|
|
provider: "fake-plugin",
|
|
image: "fake:test",
|
|
timeoutMs: "450000",
|
|
reuseLease: true,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockValidatePluginSandboxProviderConfig).toHaveBeenCalledWith({
|
|
db: expect.anything(),
|
|
workerManager: pluginWorkerManager,
|
|
provider: "fake-plugin",
|
|
config: {
|
|
image: "fake:test",
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
});
|
|
expect(mockEnvironmentService.create).toHaveBeenCalledWith({
|
|
name: "Fake plugin Sandbox",
|
|
driver: "sandbox",
|
|
status: "active",
|
|
config: {
|
|
provider: "fake-plugin",
|
|
image: "fake:test",
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
envVars: {},
|
|
}, undefined, { db: routeDbTx });
|
|
expect(mockSecretService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps host-owned sandbox flags and drops a removed flag a saved config still carries", async () => {
|
|
// The host owns run-log streaming and runner lifecycle. A provider plugin
|
|
// may normalize only its own driver fields, so it drops these host flags.
|
|
// The host must re-apply them or a saved warm environment silently becomes
|
|
// per-turn at execution time.
|
|
//
|
|
// `streamAgentSessionOutput` is a removed operator flag. A saved config can
|
|
// still carry it, but session-output streaming now follows the capability
|
|
// snapshot alone. The removed key must load and then drop, so it never
|
|
// reaches the persisted config.
|
|
const environment = {
|
|
...createEnvironment(),
|
|
id: "env-sandbox-fake-plugin",
|
|
name: "Streamed Sandbox",
|
|
driver: "sandbox" as const,
|
|
config: { provider: "fake-plugin", image: "fake:test" },
|
|
};
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
mockValidatePluginSandboxProviderConfig.mockImplementation(
|
|
async ({ provider, config }) => {
|
|
// Drop the host flag to reproduce a plugin that allowlists driver fields.
|
|
const {
|
|
streamRunLogs,
|
|
runnerLifecycleMode,
|
|
runnerIdleTimeoutMs,
|
|
...driverConfig
|
|
} = config as Record<string, unknown>;
|
|
void streamRunLogs;
|
|
void runnerLifecycleMode;
|
|
void runnerIdleTimeoutMs;
|
|
return {
|
|
normalizedConfig: driverConfig,
|
|
pluginId: `plugin-${provider}`,
|
|
pluginKey: `plugin.${provider}`,
|
|
driver: {
|
|
driverKey: provider,
|
|
kind: "sandbox_provider",
|
|
displayName: provider,
|
|
configSchema: { type: "object" },
|
|
},
|
|
};
|
|
},
|
|
);
|
|
const pluginWorkerManager = {};
|
|
const app = createApp(localBoardActor(), { pluginWorkerManager });
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Streamed Sandbox",
|
|
driver: "sandbox",
|
|
config: {
|
|
provider: "fake-plugin",
|
|
image: "fake:test",
|
|
streamRunLogs: false,
|
|
runnerLifecycleMode: "warm",
|
|
runnerIdleTimeoutMs: 180_000,
|
|
streamAgentSessionOutput: true,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
const persisted = mockEnvironmentService.create.mock.calls[0][0].config as Record<string, unknown>;
|
|
// The removed key never reaches the persisted config.
|
|
expect(persisted.streamAgentSessionOutput).toBeUndefined();
|
|
expect(persisted.streamRunLogs).toBe(false);
|
|
expect(persisted.runnerLifecycleMode).toBe("warm");
|
|
expect(persisted.runnerIdleTimeoutMs).toBe(180_000);
|
|
});
|
|
|
|
it("creates a schema-driven sandbox environment with secret-ref fields persisted as secrets", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
id: "env-sandbox-secure-plugin",
|
|
name: "Secure Sandbox",
|
|
driver: "sandbox" as const,
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: "11111111-1111-1111-1111-111111111111",
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
mockValidatePluginSandboxProviderConfig.mockResolvedValue({
|
|
normalizedConfig: {
|
|
template: "base",
|
|
apiKey: "test-provider-key",
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
pluginId: "plugin-secure",
|
|
pluginKey: "acme.secure-sandbox-provider",
|
|
driver: createSecurePluginDriver(),
|
|
});
|
|
const pluginWorkerManager = {};
|
|
const app = createApp(localBoardActor(), { pluginWorkerManager });
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Secure Sandbox",
|
|
driver: "sandbox",
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: " base ",
|
|
apiKey: " test-provider-key ",
|
|
timeoutMs: "450000",
|
|
reuseLease: true,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockValidatePluginSandboxProviderConfig).toHaveBeenCalledWith({
|
|
db: expect.anything(),
|
|
workerManager: pluginWorkerManager,
|
|
provider: "secure-plugin",
|
|
config: {
|
|
template: " base ",
|
|
apiKey: " test-provider-key ",
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
});
|
|
expect(mockEnvironmentService.create).toHaveBeenCalledWith({
|
|
name: "Secure Sandbox",
|
|
driver: "sandbox",
|
|
status: "active",
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: "11111111-1111-1111-1111-111111111111",
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
envVars: {},
|
|
}, undefined, { db: routeDbTx });
|
|
expect(JSON.stringify(mockEnvironmentService.create.mock.calls[0][0])).not.toContain("test-provider-key");
|
|
expect(mockSecretService.create).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({
|
|
provider: "local_encrypted",
|
|
value: "test-provider-key",
|
|
}),
|
|
expect.any(Object),
|
|
);
|
|
});
|
|
|
|
it("persists a picker-submitted secret_ref binding object as the bare secret id", async () => {
|
|
const secretId = "11111111-1111-1111-1111-111111111111";
|
|
const environment = {
|
|
...createEnvironment(),
|
|
id: "env-sandbox-secure-plugin",
|
|
name: "Secure Sandbox",
|
|
driver: "sandbox" as const,
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: secretId,
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
mockValidatePluginSandboxProviderConfig.mockImplementation(async ({ config }: { config: Record<string, unknown> }) => ({
|
|
normalizedConfig: { ...config },
|
|
pluginId: "plugin-secure",
|
|
pluginKey: "acme.secure-sandbox-provider",
|
|
driver: createSecurePluginDriver(),
|
|
}));
|
|
const pluginWorkerManager = {};
|
|
const app = createApp(localBoardActor(), { pluginWorkerManager });
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Secure Sandbox",
|
|
driver: "sandbox",
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: { type: "secret_ref", secretId, version: "latest" },
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockEnvironmentService.create).toHaveBeenCalledWith({
|
|
name: "Secure Sandbox",
|
|
driver: "sandbox",
|
|
status: "active",
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: secretId,
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
envVars: {},
|
|
}, undefined, { db: routeDbTx });
|
|
expect(mockSecretService.create).not.toHaveBeenCalled();
|
|
expect(mockSecretService.replaceSecretRefsForInstanceTarget).toHaveBeenCalledWith(
|
|
{ targetType: "environment", targetId: "env-sandbox-secure-plugin" },
|
|
[{ secretId, configPath: "apiKey", versionSelector: "latest" }],
|
|
{ db: routeDbTx },
|
|
);
|
|
});
|
|
|
|
it("uses the configured provider for schema-driven sandbox secret fields", async () => {
|
|
process.env.PAPERCLIP_SECRETS_PROVIDER = "aws_secrets_manager";
|
|
const environment = {
|
|
...createEnvironment(),
|
|
id: "env-sandbox-secure-plugin",
|
|
name: "Secure Sandbox",
|
|
driver: "sandbox" as const,
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: "11111111-1111-1111-1111-111111111111",
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
mockValidatePluginSandboxProviderConfig.mockResolvedValue({
|
|
normalizedConfig: {
|
|
template: "base",
|
|
apiKey: "test-provider-key",
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
pluginId: "plugin-secure",
|
|
pluginKey: "acme.secure-sandbox-provider",
|
|
driver: createSecurePluginDriver(),
|
|
});
|
|
const pluginWorkerManager = {};
|
|
const app = createApp(localBoardActor(), { pluginWorkerManager });
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Secure Sandbox",
|
|
driver: "sandbox",
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: "test-provider-key",
|
|
timeoutMs: "450000",
|
|
reuseLease: true,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockSecretService.create).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({
|
|
provider: "aws_secrets_manager",
|
|
value: "test-provider-key",
|
|
}),
|
|
expect.any(Object),
|
|
);
|
|
});
|
|
|
|
it("validates plugin environment config through the plugin driver host", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
id: "env-plugin",
|
|
name: "Plugin Sandbox",
|
|
driver: "plugin" as const,
|
|
config: {
|
|
pluginKey: "acme.environments",
|
|
driverKey: "sandbox",
|
|
driverConfig: {
|
|
template: "normalized",
|
|
},
|
|
},
|
|
};
|
|
mockValidatePluginEnvironmentDriverConfig.mockResolvedValue(environment.config);
|
|
mockEnvironmentService.create.mockResolvedValue(environment);
|
|
const pluginWorkerManager = {};
|
|
const app = createApp(localBoardActor(), { pluginWorkerManager });
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Plugin Sandbox",
|
|
driver: "plugin",
|
|
config: {
|
|
pluginKey: "acme.environments",
|
|
driverKey: "sandbox",
|
|
driverConfig: {
|
|
template: "base",
|
|
},
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockValidatePluginEnvironmentDriverConfig).toHaveBeenCalledWith({
|
|
db: expect.anything(),
|
|
workerManager: pluginWorkerManager,
|
|
config: {
|
|
pluginKey: "acme.environments",
|
|
driverKey: "sandbox",
|
|
driverConfig: {
|
|
template: "base",
|
|
},
|
|
},
|
|
});
|
|
expect(mockEnvironmentService.create).toHaveBeenCalledWith(expect.objectContaining({
|
|
config: environment.config,
|
|
envVars: {},
|
|
}), undefined, { db: routeDbTx });
|
|
});
|
|
|
|
it("rejects agent mutations for instance-scoped environments", async () => {
|
|
mockAgentService.getById.mockResolvedValue({
|
|
id: "agent-1",
|
|
companyId: "company-1",
|
|
role: "engineer",
|
|
permissions: { canCreateAgents: false },
|
|
});
|
|
mockAccessService.hasPermission.mockResolvedValue(false);
|
|
const app = createApp({
|
|
type: "agent",
|
|
agentId: "agent-1",
|
|
companyId: "company-1",
|
|
source: "agent_key",
|
|
runId: "run-1",
|
|
});
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments")
|
|
.send({
|
|
name: "Sandbox host",
|
|
driver: "local",
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error).toBe("Board access required");
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("lists leases for an environment after company access is confirmed", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.listLeases.mockResolvedValue([
|
|
{
|
|
id: "lease-1",
|
|
companyId: "company-1",
|
|
environmentId: environment.id,
|
|
executionWorkspaceId: "workspace-1",
|
|
issueId: null,
|
|
heartbeatRunId: null,
|
|
status: "active",
|
|
providerLeaseId: "provider-lease-1",
|
|
acquiredAt: new Date("2026-04-16T05:00:00.000Z"),
|
|
lastUsedAt: new Date("2026-04-16T05:05:00.000Z"),
|
|
expiresAt: null,
|
|
releasedAt: null,
|
|
metadata: { provider: "fake" },
|
|
createdAt: new Date("2026-04-16T05:00:00.000Z"),
|
|
updatedAt: new Date("2026-04-16T05:05:00.000Z"),
|
|
},
|
|
]);
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app).get(`/api/environments/${environment.id}/leases?status=active`);
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.listLeases).toHaveBeenCalledWith(environment.id, {
|
|
status: "active",
|
|
});
|
|
});
|
|
|
|
it("returns a single lease after company access is confirmed", async () => {
|
|
mockEnvironmentService.getLeaseById.mockResolvedValue({
|
|
id: "lease-1",
|
|
companyId: "company-1",
|
|
environmentId: "env-1",
|
|
executionWorkspaceId: "workspace-1",
|
|
issueId: null,
|
|
heartbeatRunId: "run-1",
|
|
status: "active",
|
|
leasePolicy: "ephemeral",
|
|
provider: "ssh",
|
|
providerLeaseId: "ssh://ssh-user@example.test:22/workspace",
|
|
acquiredAt: new Date("2026-04-16T05:00:00.000Z"),
|
|
lastUsedAt: new Date("2026-04-16T05:05:00.000Z"),
|
|
expiresAt: null,
|
|
releasedAt: null,
|
|
failureReason: null,
|
|
cleanupStatus: null,
|
|
metadata: { remoteCwd: "/workspace" },
|
|
createdAt: new Date("2026-04-16T05:00:00.000Z"),
|
|
updatedAt: new Date("2026-04-16T05:05:00.000Z"),
|
|
});
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app).get("/api/environment-leases/lease-1");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.provider).toBe("ssh");
|
|
expect(mockEnvironmentService.getLeaseById).toHaveBeenCalledWith("lease-1");
|
|
});
|
|
|
|
it("rejects agent access regardless of company when environment management is instance-scoped", async () => {
|
|
mockEnvironmentService.list.mockResolvedValue([]);
|
|
const app = createApp({
|
|
type: "agent",
|
|
agentId: "agent-2",
|
|
companyId: "company-2",
|
|
source: "agent_key",
|
|
runId: "run-2",
|
|
});
|
|
|
|
const res = await request(app).get("/api/companies/company-1/environments");
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error).toContain("Board access required");
|
|
expect(mockEnvironmentService.list).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("refuses a config change that gives active agents an unprepared plugin", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockAssertAgentsReadyForEnvironmentChange.mockRejectedValueOnce(conflict("need setup first"));
|
|
const res = await request(createApp(localBoardActor()))
|
|
.patch(`/api/environments/${environment.id}?companyId=company-1`)
|
|
.send({ driver: "local", config: {} });
|
|
expect(res.status).toBe(409);
|
|
expect(mockAssertAgentsReadyForEnvironmentChange).toHaveBeenCalledWith(expect.anything(), environment,
|
|
expect.objectContaining({ driver: "local" }), expect.objectContaining({ environmentId: environment.id }));
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("logs a redacted update summary instead of raw config or metadata", async () => {
|
|
const environment = createEnvironment();
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.update.mockResolvedValue({
|
|
...environment,
|
|
status: "archived",
|
|
});
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app)
|
|
.patch(`/api/environments/${environment.id}?companyId=company-1`)
|
|
.send({
|
|
status: "archived",
|
|
config: {
|
|
apiKey: "super-secret",
|
|
token: "another-secret",
|
|
},
|
|
metadata: {
|
|
password: "do-not-log",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockLogActivity).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
action: "environment.updated",
|
|
details: {
|
|
changedFields: ["config", "metadata", "status"],
|
|
status: "archived",
|
|
configChanged: true,
|
|
configTopLevelKeyCount: expect.any(Number),
|
|
metadataChanged: true,
|
|
metadataTopLevelKeyCount: 1,
|
|
},
|
|
}),
|
|
);
|
|
expect(JSON.stringify(mockLogActivity.mock.calls[0][1].details)).not.toContain("super-secret");
|
|
expect(JSON.stringify(mockLogActivity.mock.calls[0][1].details)).not.toContain("do-not-log");
|
|
});
|
|
|
|
it("resets config instead of inheriting SSH secrets when switching to local without an explicit config", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
name: "SSH Fixture",
|
|
driver: "ssh" as const,
|
|
config: {
|
|
host: "ssh.example.test",
|
|
port: 22,
|
|
username: "ssh-user",
|
|
remoteWorkspacePath: "/srv/paperclip/workspace",
|
|
privateKey: "super-secret-key",
|
|
knownHosts: "known-host",
|
|
strictHostKeyChecking: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockEnvironmentService.update.mockResolvedValue({
|
|
...createEnvironment(),
|
|
driver: "local" as const,
|
|
config: {},
|
|
});
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app)
|
|
.patch(`/api/environments/${environment.id}?companyId=company-1`)
|
|
.send({
|
|
driver: "local",
|
|
});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.update).toHaveBeenCalledWith(environment.id, {
|
|
driver: "local",
|
|
config: {},
|
|
}, { db: routeDbTx });
|
|
expect(JSON.stringify(mockEnvironmentService.update.mock.calls[0][1])).not.toContain("super-secret-key");
|
|
expect(JSON.stringify(mockEnvironmentService.update.mock.calls[0][1])).not.toContain("known-host");
|
|
});
|
|
|
|
it("re-points a sandbox secret ref to another company's secret even when existing bindings disagree", async () => {
|
|
const oldSecretId = "11111111-1111-1111-1111-111111111111";
|
|
const newSecretId = "22222222-2222-2222-2222-222222222222";
|
|
const existing = {
|
|
...createEnvironment(),
|
|
id: "env-sandbox",
|
|
name: "Daytona",
|
|
driver: "sandbox" as const,
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: oldSecretId,
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
};
|
|
const updated = {
|
|
...existing,
|
|
config: { ...existing.config, apiKey: newSecretId },
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(existing);
|
|
mockEnvironmentService.update.mockResolvedValue(updated);
|
|
mockValidatePluginSandboxProviderConfig.mockImplementation(async ({ config }: { config: Record<string, unknown> }) => ({
|
|
normalizedConfig: { ...config },
|
|
pluginId: "plugin-secure",
|
|
pluginKey: "acme.secure-sandbox-provider",
|
|
driver: createSecurePluginDriver(),
|
|
}));
|
|
// The environment's only binding still lives in another company. Before
|
|
// bindings moved with the referenced secret, this state made every save
|
|
// from the caller's company fail, with no route-level way out.
|
|
mockSecretService.listBindingCompanyIdsForTarget.mockResolvedValue(["company-old"]);
|
|
const app = createApp(localBoardActor(), { pluginWorkerManager: {} });
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-sandbox?companyId=company-new")
|
|
.send({
|
|
config: {
|
|
apiKey: { type: "secret_ref", secretId: newSecretId, version: "latest" },
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.update).toHaveBeenCalledWith(
|
|
"env-sandbox",
|
|
expect.objectContaining({
|
|
config: expect.objectContaining({ apiKey: newSecretId }),
|
|
}),
|
|
{ db: routeDbTx },
|
|
);
|
|
expect(mockSecretService.replaceSecretRefsForInstanceTarget).toHaveBeenCalledWith(
|
|
{ targetType: "environment", targetId: "env-sandbox" },
|
|
[{ secretId: newSecretId, configPath: "apiKey", versionSelector: "latest" }],
|
|
{ db: routeDbTx },
|
|
);
|
|
// Explicit caller context wins outright; stale bindings are never consulted.
|
|
expect(mockSecretService.listBindingCompanyIdsForTarget).not.toHaveBeenCalled();
|
|
expect(mockSecretService.syncSecretRefsForTarget).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("fails the whole save when a referenced secret cannot be bound", async () => {
|
|
const existing = {
|
|
...createEnvironment(),
|
|
id: "env-sandbox",
|
|
name: "Daytona",
|
|
driver: "sandbox" as const,
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: "11111111-1111-1111-1111-111111111111",
|
|
timeoutMs: 450000,
|
|
reuseLease: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(existing);
|
|
mockEnvironmentService.update.mockResolvedValue({
|
|
...existing,
|
|
config: { ...existing.config, apiKey: "33333333-3333-3333-3333-333333333333" },
|
|
});
|
|
mockSecretService.replaceSecretRefsForInstanceTarget.mockRejectedValue(
|
|
unprocessable("Secret referenced at apiKey was not found", { code: "secret_missing" }),
|
|
);
|
|
const app = createApp(localBoardActor(), { pluginWorkerManager: {} });
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-sandbox?companyId=company-1")
|
|
.send({
|
|
config: {
|
|
apiKey: { type: "secret_ref", secretId: "33333333-3333-3333-3333-333333333333", version: "latest" },
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.error).toContain("was not found");
|
|
});
|
|
|
|
it("requires explicit SSH config when switching from local to SSH", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(createEnvironment());
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-1?companyId=company-1")
|
|
.send({
|
|
driver: "ssh",
|
|
});
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.error).toContain("host");
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects switching an environment to the built-in fake sandbox provider", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(createEnvironment());
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/env-1?companyId=company-1")
|
|
.send({
|
|
driver: "sandbox",
|
|
config: {
|
|
provider: "fake",
|
|
image: "ubuntu:24.04",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.error).toContain("reserved for internal probes");
|
|
expect(mockEnvironmentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns 404 when patching a missing environment", async () => {
|
|
mockEnvironmentService.getById.mockResolvedValue(null);
|
|
const app = createApp(localBoardActor());
|
|
|
|
const res = await request(app)
|
|
.patch("/api/environments/missing-env")
|
|
.send({ status: "archived" });
|
|
|
|
expect(res.status).toBe(404);
|
|
expect(res.body.error).toBe("Environment not found");
|
|
expect(mockLogActivity).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("probes an SSH environment and logs the result", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
name: "SSH Fixture",
|
|
driver: "ssh" as const,
|
|
config: {
|
|
host: "ssh.example.test",
|
|
port: 22,
|
|
username: "ssh-user",
|
|
remoteWorkspacePath: "/srv/paperclip/workspace",
|
|
privateKey: null,
|
|
knownHosts: null,
|
|
strictHostKeyChecking: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockProbeEnvironment.mockResolvedValue({
|
|
ok: true,
|
|
driver: "ssh",
|
|
summary: "Connected to ssh-user@ssh.example.test and verified the remote workspace path.",
|
|
details: {
|
|
host: "ssh.example.test",
|
|
},
|
|
});
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "local_implicit",
|
|
runId: "run-1",
|
|
});
|
|
|
|
const res = await request(app)
|
|
.post(`/api/environments/${environment.id}/probe`)
|
|
.send({});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.ok).toBe(true);
|
|
expect(mockProbeEnvironment).toHaveBeenCalledWith(expect.anything(), environment, {
|
|
// The instance has exactly one company, so the secret-context fallback
|
|
// resolves it even though the actor carries no memberships.
|
|
companyId: "company-1",
|
|
pluginWorkerManager: undefined,
|
|
applyCustomImageTemplate: false,
|
|
acquireSandboxRuntimeLease: false,
|
|
});
|
|
expect(mockLogActivity).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
companyId: "company-1",
|
|
action: "environment.probed",
|
|
entityType: "environment",
|
|
entityId: environment.id,
|
|
details: expect.objectContaining({
|
|
driver: "ssh",
|
|
ok: true,
|
|
}),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("requires explicit companyId when probing a secret-backed environment without inferable secret context", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
driver: "ssh" as const,
|
|
config: {
|
|
host: "ssh.example.test",
|
|
port: 22,
|
|
username: "ssh-user",
|
|
remoteWorkspacePath: "/srv/paperclip/workspace",
|
|
privateKey: null,
|
|
privateKeySecretRef: {
|
|
type: "secret_ref",
|
|
secretId: "11111111-1111-4111-8111-111111111111",
|
|
version: "latest",
|
|
},
|
|
knownHosts: null,
|
|
strictHostKeyChecking: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockSecretService.listBindingCompanyIdsForTarget.mockResolvedValue([]);
|
|
// A multi-company instance keeps the context genuinely ambiguous — a
|
|
// single-company instance would resolve via the instance fallback.
|
|
mockInstanceSettingsService.listCompanyIds.mockResolvedValue(["company-1", "company-2"]);
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "session",
|
|
companyIds: ["company-1", "company-2"],
|
|
memberships: [
|
|
{ companyId: "company-1", status: "active", membershipRole: "member" },
|
|
{ companyId: "company-2", status: "active", membershipRole: "member" },
|
|
],
|
|
isInstanceAdmin: true,
|
|
runId: "run-1",
|
|
});
|
|
|
|
const res = await request(app)
|
|
.post(`/api/environments/${environment.id}/probe`)
|
|
.send({});
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(res.body.error).toContain("explicit companyId");
|
|
expect(mockProbeEnvironment).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("probes a sandbox environment and logs the result", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
id: "env-sandbox",
|
|
name: "Fake Sandbox",
|
|
driver: "sandbox" as const,
|
|
config: {
|
|
provider: "fake",
|
|
image: "ubuntu:24.04",
|
|
reuseLease: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockProbeEnvironment.mockResolvedValue({
|
|
ok: true,
|
|
driver: "sandbox",
|
|
summary: "Fake sandbox provider is ready for image ubuntu:24.04.",
|
|
details: {
|
|
provider: "fake",
|
|
image: "ubuntu:24.04",
|
|
reuseLease: true,
|
|
},
|
|
});
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "local_implicit",
|
|
runId: "run-1",
|
|
});
|
|
|
|
const res = await request(app)
|
|
.post(`/api/environments/${environment.id}/probe`)
|
|
.send({});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.driver).toBe("sandbox");
|
|
expect(mockProbeEnvironment).toHaveBeenCalledWith(expect.anything(), environment, {
|
|
companyId: "company-1",
|
|
pluginWorkerManager: undefined,
|
|
applyCustomImageTemplate: true,
|
|
acquireSandboxRuntimeLease: true,
|
|
});
|
|
expect(mockLogActivity).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
companyId: "company-1",
|
|
action: "environment.probed",
|
|
entityType: "environment",
|
|
entityId: environment.id,
|
|
details: expect.objectContaining({
|
|
driver: "sandbox",
|
|
ok: true,
|
|
}),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("probes saved sandbox environments with the active custom image template without company context", async () => {
|
|
const environment = {
|
|
...createEnvironment(),
|
|
id: "env-sandbox",
|
|
name: "Daytona Sandbox",
|
|
driver: "sandbox" as const,
|
|
config: {
|
|
provider: "daytona",
|
|
image: "ubuntu:24.04",
|
|
reuseLease: true,
|
|
},
|
|
};
|
|
mockEnvironmentService.getById.mockResolvedValue(environment);
|
|
mockProbeEnvironment.mockResolvedValue({
|
|
ok: true,
|
|
driver: "sandbox",
|
|
summary: "Connected to Daytona sandbox.",
|
|
details: {
|
|
provider: "daytona",
|
|
snapshot: "captured-template",
|
|
},
|
|
});
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "local_implicit",
|
|
runId: "run-1",
|
|
});
|
|
|
|
const res = await request(app)
|
|
.post(`/api/environments/${environment.id}/probe`)
|
|
.send({});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.driver).toBe("sandbox");
|
|
expect(mockProbeEnvironment).toHaveBeenCalledWith(expect.anything(), environment, {
|
|
companyId: "company-1",
|
|
pluginWorkerManager: undefined,
|
|
applyCustomImageTemplate: true,
|
|
acquireSandboxRuntimeLease: true,
|
|
});
|
|
});
|
|
|
|
it("probes unsaved provider config without persisting secrets", async () => {
|
|
mockProbeEnvironment.mockResolvedValue({
|
|
ok: true,
|
|
driver: "sandbox",
|
|
summary: "Fake plugin sandbox provider is ready.",
|
|
details: { provider: "fake-plugin" },
|
|
});
|
|
const pluginWorkerManager = {};
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "local_implicit",
|
|
runId: "run-1",
|
|
}, { pluginWorkerManager });
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments/probe-config")
|
|
.send({
|
|
name: "Draft Fake plugin",
|
|
driver: "sandbox",
|
|
config: {
|
|
provider: "fake-plugin",
|
|
template: "base",
|
|
apiKey: "unsaved-test-key",
|
|
timeoutMs: 300000,
|
|
reuseLease: true,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
expect(mockSecretService.create).not.toHaveBeenCalled();
|
|
expect(mockProbeEnvironment).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
id: "unsaved",
|
|
driver: "sandbox",
|
|
config: expect.objectContaining({
|
|
apiKey: "unsaved-test-key",
|
|
}),
|
|
}),
|
|
expect.objectContaining({
|
|
pluginWorkerManager,
|
|
resolvedConfig: expect.objectContaining({
|
|
driver: "sandbox",
|
|
}),
|
|
}),
|
|
);
|
|
expect(JSON.stringify(mockLogActivity.mock.calls[0][1].details)).not.toContain("unsaved-test-key");
|
|
});
|
|
|
|
it("resolves selected secret refs before probing unsaved provider config", async () => {
|
|
mockValidatePluginSandboxProviderConfig.mockResolvedValue({
|
|
normalizedConfig: {
|
|
template: "base",
|
|
apiKey: "11111111-1111-1111-1111-111111111111",
|
|
timeoutMs: 300000,
|
|
reuseLease: true,
|
|
},
|
|
pluginId: "plugin-secure",
|
|
pluginKey: "acme.secure-sandbox-provider",
|
|
driver: createSecurePluginDriver(),
|
|
});
|
|
mockProbeEnvironment.mockResolvedValue({
|
|
ok: true,
|
|
driver: "sandbox",
|
|
summary: "Secure sandbox provider is ready.",
|
|
details: { provider: "secure-plugin" },
|
|
});
|
|
const pluginWorkerManager = {};
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "local_implicit",
|
|
runId: "run-1",
|
|
}, { pluginWorkerManager });
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments/probe-config")
|
|
.send({
|
|
name: "Draft Secure Sandbox",
|
|
driver: "sandbox",
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: "11111111-1111-1111-1111-111111111111",
|
|
timeoutMs: 300000,
|
|
reuseLease: true,
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
|
|
expect(mockSecretService.create).not.toHaveBeenCalled();
|
|
expect(mockSecretService.resolveSecretValueForEphemeralAccess).toHaveBeenCalledWith(
|
|
"company-1",
|
|
"11111111-1111-1111-1111-111111111111",
|
|
"latest",
|
|
{
|
|
consumerType: "system",
|
|
consumerId: "environment-probe-config",
|
|
configPath: "apiKey",
|
|
actorType: "user",
|
|
actorId: "user-1",
|
|
actorSource: "local_implicit",
|
|
heartbeatRunId: "run-1",
|
|
},
|
|
);
|
|
expect(mockProbeEnvironment).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
id: "unsaved",
|
|
driver: "sandbox",
|
|
config: expect.objectContaining({
|
|
apiKey: "resolved-provider-key",
|
|
}),
|
|
}),
|
|
expect.objectContaining({
|
|
pluginWorkerManager,
|
|
resolvedConfig: expect.objectContaining({
|
|
driver: "sandbox",
|
|
config: expect.objectContaining({
|
|
apiKey: "resolved-provider-key",
|
|
}),
|
|
}),
|
|
}),
|
|
);
|
|
expect(JSON.stringify(mockLogActivity.mock.calls[0][1].details)).not.toContain("resolved-provider-key");
|
|
});
|
|
|
|
it("rejects sandbox draft probes for non-admin board users", async () => {
|
|
mockValidatePluginSandboxProviderConfig.mockResolvedValue({
|
|
normalizedConfig: {
|
|
template: "base",
|
|
apiKey: "11111111-1111-1111-1111-111111111111",
|
|
},
|
|
pluginId: "plugin-secure",
|
|
pluginKey: "acme.secure-sandbox-provider",
|
|
driver: {
|
|
driverKey: "secure-plugin",
|
|
kind: "sandbox_provider",
|
|
displayName: "Secure Sandbox",
|
|
configSchema: {
|
|
type: "object",
|
|
properties: {
|
|
template: { type: "string" },
|
|
apiKey: { type: "string", format: "secret-ref" },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
mockAccessService.canUser.mockResolvedValue(true);
|
|
mockAccessService.decide.mockResolvedValue({
|
|
allowed: false,
|
|
explanation: "Missing permission: secrets:read",
|
|
});
|
|
const pluginWorkerManager = {};
|
|
const app = createApp({
|
|
type: "board",
|
|
userId: "user-2",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
memberships: [{ companyId: "company-1", status: "active", membershipRole: "member" }],
|
|
}, { pluginWorkerManager });
|
|
|
|
const res = await request(app)
|
|
.post("/api/companies/company-1/environments/probe-config")
|
|
.send({
|
|
name: "Draft Secure Sandbox",
|
|
driver: "sandbox",
|
|
config: {
|
|
provider: "secure-plugin",
|
|
template: "base",
|
|
apiKey: "11111111-1111-1111-1111-111111111111",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error).toContain("Instance admin access required");
|
|
expect(mockSecretService.resolveSecretValueForEphemeralAccess).not.toHaveBeenCalled();
|
|
expect(mockProbeEnvironment).not.toHaveBeenCalled();
|
|
});
|
|
});
|