diff --git a/docs/deploy/environment-variables.md b/docs/deploy/environment-variables.md index 67fa6faa4ed..383de84ffdd 100644 --- a/docs/deploy/environment-variables.md +++ b/docs/deploy/environment-variables.md @@ -29,6 +29,7 @@ All environment variables that Paperclip uses for server configuration. | `PAPERCLIP_HIDDEN_SETTINGS` | (unset) | Comma-separated settings surfaces to hide from the UI and floor at the API, for operators hosting Paperclip for others (managed cloud, internal shared server). See [Hiding settings surfaces](#hiding-settings-surfaces). | | `PAPERCLIP_SETTING_DEFAULTS` | (unset) | JSON object replacing the schema default of selected instance settings, for hosting operators. See [Operator setting defaults](#operator-setting-defaults). | | `PAPERCLIP_DEBUG_WORK_SIGNALS` | (unset) | Diagnostic only. Comma-separated allowlist of work-signal topics, each optionally followed by `:N` (for example `stranded-assignments:10,run-dispatch`). For each listed topic the server writes JSON lines to stderr: every work signal (topic and hint), with the caller stack on one signal in N (default 20); remote and reconnect notifications; direct settled publishes; and the recovery queues' loads, checks and direct wakes (direct wakes always carry the caller stack). Logged values are internal ids only (company, issue, run), never secrets or user identifiers. Stack frames keep their raw file and line positions, so bundled builds map them offline with that build's source map. Each topic and event pair is capped at 10 lines per second; a `suppressed` line names the dropped event and its count. The value is read once at startup, so enabling or changing it requires a restart. Unset or empty disables it completely. | +| `PAPERCLIP_MANAGED_CONFIG` | (unset) | Trusted deployment configuration for managed features, plugins and environments. See [Managed sandbox reconciliation](#managed-sandbox-reconciliation). | Daytona connectivity for `paperclip_runner` uses authenticated provider WebSocket ingress and follows the instance experimental setting @@ -180,6 +181,78 @@ Unknown field names are logged and ignored (mixed-version fleet safe). Malformed JSON or an invalid value for a known field refuses startup — policy configuration fails closed. +### Managed sandbox reconciliation + +Managed-config sandbox declarations reconcile the instance's Paperclip-marked +environment after its provider plugin becomes ready. Platform-owned stock can +advance before the first company exists; company-scoped stock bindings are +initialized when companies appear. This includes legacy marked rows that have +no stock baseline. Ordinary self-hosted reconciliation continues to preserve +operator modifications. + +The internal `platformFullyManaged` assertion is reserved for deployment callers +that prevent operator edits. Other callers of `ensureManagedSandboxEnvironment` +leave it unset. Platform reconciliation requires the row's existing +`managedByPaperclip` ownership marker even when company bindings exist: a +tracking binding recorded for a skipped tenant-created row never authorizes +adopting it. Archived rows require a matching stock binding that records both +the archive status and Paperclip's archive token before automatic reactivation. +A token on the environment row alone is insufficient. An operator save removes +that token when reaffirming an archive. An archived row without a corroborating +binding stays preserved for individual operator review, including when it was +archived before the first company existed. Later tracking-only bindings do not +authorize its reactivation. + +Re-running reconciliation with the desired declaration repairs stale managed +stock in place and is idempotent. It preserves environment identity, tenant +environment variables and unrelated metadata, and does not replace running +provider leases. Existing workspaces can therefore receive a separately +scheduled reconciliation rather than deleting their environments or leases. +An unmarked environment holding the declared name remains untouched. A +deliberately archived row remains archived; only Paperclip's own availability +archive can reactivate automatically. + +Inspect the reconciliation's `action`, `stockStatus` and `updateAvailable` +outcomes when verifying an update. Writing the desired configuration or seeing +healthy HTTP responses alone does not prove that a database environment row +converged. Entry failures and skipped stock updates are logged while startup +continues degraded. Validate repeated empty-instance boots and the actual row +in deployment qualification; do not turn a performance check into a startup gate. + +### Qualify a sandbox runtime before deployment + +The image includes `/app/server/dist/qualify-sandbox-runtime.js`. Deployment +systems can run it without a database, network access or provider credentials: + +```sh +node /app/server/dist/qualify-sandbox-runtime.js \ + --manifest /opt/paperclip-runner/provider-pack/provider-pack.json \ + --runner /app/packages/paperclip-runner/dist/bin/paperclip-runnerd < installed.json +``` + +The input has `installed` (`manifest`, hexadecimal `runnerSha256`, and `immutable`) +and an optional nonempty `providers` list (`{ "kind": "opencode" }` or +`{ "kind": "acpx", "agent": "claude" }`, for example). The deployment system +chooses its provider list. Omit the list to check OpenCode and every packaged +provider profile. The report records `allPackProviders: true` for that scope. +Core contains no hosting-provider policy. + +The caller must collect the installed manifest and runner hash from the exact +sandbox snapshot under qualification, verify its files against that manifest, +and establish that the installation is protected against runtime writes before +asserting `immutable: true`. This command does not make those remote observations +itself. Its result is deployment evidence, not a signed grant or a replacement +for file-integrity verification. + +The command uses the same compatibility check as task startup. Different pack +hashes remain compatible when their interface contract and selected provider +profiles agree. A different daemon binary, missing protected installation, +changed contract, or changed provider profile refuses qualification. Exit code +0 means compatible, 2 means incompatible, and 1 means invalid input or an +unavailable qualification. The JSON result records the manifests, daemon hash +and provider scope. Qualify the candidate before publishing or deploying it; +a refusal should leave the current deployment serving. + ## Secrets | Variable | Default | Description | diff --git a/server/src/__tests__/environment-service.test.ts b/server/src/__tests__/environment-service.test.ts index 5087c19cfb8..c542facf87c 100644 --- a/server/src/__tests__/environment-service.test.ts +++ b/server/src/__tests__/environment-service.test.ts @@ -27,6 +27,8 @@ import { } from "./helpers/embedded-postgres.js"; import { environmentService } from "../services/environments.ts"; import { attachPaperclipSessionMetadataToSessionParams, buildEffectiveRunSessionConfigMetadata, resolveTaskSessionConfigFreshness } from "../services/heartbeat/workspaces.js"; +import { parseManagedConfigEnv } from "../services/managed-config.js"; +import { applyManagedEnvironments } from "../services/managed-environments.js"; const externalTestDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; if (externalTestDatabaseUrl && !new URL(externalTestDatabaseUrl).pathname.endsWith("_test")) { @@ -1594,6 +1596,206 @@ describeEmbeddedPostgres("environmentService leases", () => { expect(activity.at(-1)?.action).toBe("environment.managed_stock_skipped"); }); + it("applies repeated managed-config snapshot updates before signup and binds the first company to current stock", async () => { + const boot = async (version: string) => { + const config = parseManagedConfigEnv({ + PAPERCLIP_MANAGED_CONFIG: JSON.stringify({ + v: 1, + mode: "cloud", + catalogVersion: version, + features: {}, + plugins: { autoInstall: ["daytona"] }, + environments: [{ name: "Managed sandbox", provider: "daytona", config: { snapshot: version } }], + }), + }); + return applyManagedEnvironments(db, config, { + env: {}, + resolveSandboxProviderDriver: async () => ({ + plugin: { id: "fixture-plugin", pluginKey: "sandbox-providers/daytona", status: "ready" }, + }), + workerManager: { isRunning: () => true, getWorker: () => undefined }, + }); + }; + + expect(await db.select().from(companies)).toHaveLength(0); + expect(await boot("v1")).toMatchObject({ added: 1, failed: 0, skipped: 0 }); + const original = (await svc.findManagedSandboxEnvironment())!; + await svc.update(original.id, { + envVars: { FIXTURE_FLAG: "keep" }, + metadata: { ...original.metadata, operatorNote: "keep" }, + }); + for (const version of ["v2", "v3"]) { + expect(await boot(version)).toMatchObject({ updated: 1, failed: 0, skipped: 0 }); + const current = (await svc.findManagedSandboxEnvironment())!; + expect(current).toMatchObject({ + id: original.id, + config: { provider: "daytona", snapshot: version }, + envVars: { FIXTURE_FLAG: "keep" }, + metadata: { operatorNote: "keep" }, + }); + expect(await boot(version)).toMatchObject({ unchanged: 1, failed: 0, skipped: 0 }); + expect((await svc.getById(original.id))?.updatedAt).toEqual(current.updatedAt); + expect(await db.select().from(builtInManagedResources)).toHaveLength(0); + } + + const companyId = await seedCompany(); + expect(await boot("v3")).toMatchObject({ unchanged: 1, failed: 0, skipped: 0 }); + const [binding] = await db.select().from(builtInManagedResources) + .where(eq(builtInManagedResources.companyId, companyId)); + expect(binding).toMatchObject({ resourceId: original.id, stockVersion: "v3" }); + expect(binding?.defaultsJson.config).toEqual({ provider: "daytona", snapshot: "v3" }); + expect(await boot("v4")).toMatchObject({ updated: 1, failed: 0, skipped: 0 }); + const [advancedBinding] = await db.select().from(builtInManagedResources) + .where(eq(builtInManagedResources.companyId, companyId)); + expect(advancedBinding).toMatchObject({ resourceId: original.id, stockVersion: "v4" }); + expect(advancedBinding?.stockHash).not.toBe(binding?.stockHash); + expect((await svc.getById(original.id))?.config.snapshot).toBe("v4"); + expect(await db.select().from(environments)).toHaveLength(1); + }); + + it.each([false, true])("repairs legacy unbound managed stock only under the trusted platform contract (%s)", async (platformFullyManaged) => { + const companyId = await seedCompany(); + const legacy = await svc.create({ + name: "Legacy managed sandbox", + driver: "sandbox", + status: "active", + envVars: {}, + config: { provider: "daytona", snapshot: "old" }, + metadata: { managedByPaperclip: true, managedSandboxProvider: "daytona" }, + }); + const reconcile = () => svc.ensureManagedSandboxEnvironment({ + companyId, + name: legacy.name, + provider: "daytona", + config: { snapshot: "current" }, + platformFullyManaged, + }); + expect(await db.select().from(builtInManagedResources)).toHaveLength(0); + const first = await reconcile(); + const repeated = await reconcile(); + expect(first.action).toBe(platformFullyManaged ? "updated" : "skipped"); + expect(repeated.action).toBe(platformFullyManaged ? "unchanged" : "skipped"); + expect(repeated.environment.id).toBe(legacy.id); + expect(repeated.environment.config.snapshot).toBe(platformFullyManaged ? "current" : "old"); + }); + + it("serializes platform stock updates and first-company binding initialization on the same row", async () => { + const input = { name: "Managed sandbox", provider: "daytona", platformFullyManaged: true }; + const original = await svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: "v1" } }); + for (const version of ["v2", "v3"]) { + if (version === "v3") await seedCompany(); + const results = await Promise.all(Array.from({ length: 8 }, () => + svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: version } }), + )); + expect(results.filter((result) => result.action === "updated")).toHaveLength(1); + expect(results.filter((result) => result.action === "unchanged")).toHaveLength(7); + expect(results.every((result) => result.environment.id === original.environment.id)).toBe(true); + const bindings = await db.select().from(builtInManagedResources); + expect(bindings).toHaveLength(version === "v3" ? 1 : 0); + if (version === "v3") expect(bindings[0]?.stockHash).toBe(results[0]?.stockHash); + } + expect(await db.select().from(environments)).toHaveLength(1); + }); + + it("switches providers in the platform-owned slot before the first company exists", async () => { + const original = await svc.ensureKubernetesEnvironment({ inCluster: true, backend: "job" }); + const switched = await svc.ensureManagedSandboxEnvironment({ + name: "Managed sandbox", + provider: "daytona", + config: { snapshot: "current" }, + platformFullyManaged: true, + }); + expect(switched).toMatchObject({ action: "updated", environment: { + id: original.id, + config: { provider: "daytona", snapshot: "current" }, + metadata: { managedByPaperclip: true, managedSandboxProvider: "daytona" }, + } }); + expect(switched.environment.config.backend).toBeUndefined(); + expect(switched.environment.metadata?.managedKubernetesSandbox).toBeUndefined(); + }); + + it.each([false, true])("preserves unbound archives for operator review regardless of token removal (%s)", async (reaffirm) => { + const input = { name: "Managed sandbox", provider: "daytona", platformFullyManaged: true }; + const original = await svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: "old" } }); + await svc.archiveManagedSandboxEnvironment({ provider: "daytona" }); + if (reaffirm) await svc.update(original.environment.id, { status: "archived" }); + const reconcile = () => svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: "current" } }); + const first = await reconcile(); + expect(first.action).toBe("skipped"); + expect(first.environment.status).toBe("archived"); + expect(first.environment.config.snapshot).toBe("old"); + await seedCompany(); + expect((await reconcile()).action).toBe("skipped"); + expect((await reconcile()).environment.status).toBe("archived"); + }); + + it("preserves a forged unbound archive through repeated reconciliation and later company bindings", async () => { + const archived = await svc.create({ + name: "Managed sandbox", + driver: "sandbox", + status: "archived", + envVars: { FIXTURE_FLAG: "keep" }, + config: { provider: "daytona", snapshot: "operator" }, + metadata: { + managedByPaperclip: true, + managedSandboxProvider: "daytona", + _paperclipManagedArchiveToken: "forged-fixture-token", + }, + }); + const reconcile = (snapshot: string) => svc.ensureManagedSandboxEnvironment({ + name: archived.name, + provider: "daytona", + config: { snapshot }, + platformFullyManaged: true, + }); + for (const snapshot of ["v1", "v1", "v2"]) { + expect(await reconcile(snapshot)).toMatchObject({ + action: "skipped", stockStatus: "operator_modified", updateAvailable: true, + environment: { id: archived.id, status: "archived", config: archived.config, updatedAt: archived.updatedAt }, + }); + } + expect(await db.select().from(builtInManagedResources)).toHaveLength(0); + + const companyId = await seedCompany(); + const tracked = await reconcile("v3"); + expect(tracked.action).toBe("skipped"); + const [binding] = await db.select().from(builtInManagedResources) + .where(eq(builtInManagedResources.companyId, companyId)); + expect(binding).toMatchObject({ resourceId: archived.id, stockHash: tracked.stockHash }); + expect(binding?.defaultsJson.status).toBe("active"); + expect(binding?.defaultsJson._paperclipManagedArchiveToken).toBeUndefined(); + for (const snapshot of ["v3", "v4", "v4"]) { + expect(await reconcile(snapshot)).toMatchObject({ + action: "skipped", stockStatus: "operator_modified", updateAvailable: true, + environment: { + id: archived.id, status: "archived", config: archived.config, + envVars: archived.envVars, metadata: archived.metadata, updatedAt: archived.updatedAt, + }, + }); + } + const [unchangedBinding] = await db.select().from(builtInManagedResources) + .where(eq(builtInManagedResources.companyId, companyId)); + expect(unchangedBinding).toEqual(binding); + }); + + it("reactivates drifted platform stock only with a corroborating archive binding", async () => { + const companyId = await seedCompany(); + const input = { companyId, name: "Managed sandbox", provider: "daytona", platformFullyManaged: true }; + const original = await svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: "old" } }); + await svc.update(original.environment.id, { config: { provider: "daytona", snapshot: "drifted" } }); + await svc.archiveManagedSandboxEnvironment({ provider: "daytona" }); + const [binding] = await db.select().from(builtInManagedResources) + .where(eq(builtInManagedResources.companyId, companyId)); + expect(binding?.defaultsJson.status).toBe("archived"); + expect(binding?.defaultsJson._paperclipManagedArchiveToken).toBeTypeOf("string"); + const restored = await svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: "current" } }); + expect(restored).toMatchObject({ + action: "updated", stockStatus: "stock_update_available", updateAvailable: false, + environment: { id: original.environment.id, status: "active", config: { snapshot: "current" } }, + }); + expect(restored.environment.metadata?._paperclipManagedArchiveToken).toBeUndefined(); + }); + it("platformFullyManaged applies drift instead of preserving it, since no operator can edit this row", async () => { const companyId = await seedCompany(); const created = await svc.ensureManagedSandboxEnvironment({ @@ -1869,13 +2071,8 @@ describeEmbeddedPostgres("environmentService leases", () => { expect(rows).toHaveLength(1); }); - it("platformFullyManaged never adopts an unbound same-name sandbox row", async () => { - // Same setup as the plain case above: a tenant-created sandbox row holds - // the desired name and has no stock binding. It reads as - // `operator_modified` too, but there is no prior platform pass for it to - // have drifted from — the bypass must require a binding for this exact - // row, or it would overwrite the tenant's config and stamp it managed. - const companyId = await seedCompany(); + it.each([false, true])("platformFullyManaged never adopts an unmarked same-name sandbox row (%s)", async (hasCompany) => { + const companyId = hasCompany ? await seedCompany() : undefined; const handMade = await svc.create({ name: "Daytona", driver: "sandbox", @@ -1885,13 +2082,15 @@ describeEmbeddedPostgres("environmentService leases", () => { }); expect(handMade.metadata?.managedByPaperclip).toBeUndefined(); - const reconciliation = await svc.ensureManagedSandboxEnvironment({ + const input = { companyId, name: "Daytona", provider: "daytona", config: { target: "eu" }, platformFullyManaged: true, - }); + }; + await svc.ensureManagedSandboxEnvironment(input); + const reconciliation = await svc.ensureManagedSandboxEnvironment(input); expect(reconciliation).toMatchObject({ action: "skipped", stockStatus: "operator_modified", diff --git a/server/src/qualify-sandbox-runtime.test.ts b/server/src/qualify-sandbox-runtime.test.ts new file mode 100644 index 00000000000..c5070cb21d8 --- /dev/null +++ b/server/src/qualify-sandbox-runtime.test.ts @@ -0,0 +1,85 @@ +import { createHash } from "node:crypto"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; +import { buildSync } from "esbuild"; +import { describe, expect, it } from "vitest"; +import { qualifySandboxRuntime } from "./qualify-sandbox-runtime.js"; +import { canonicalProviderPackJson, type ProviderPackIdentity } from "./services/native-runtime/provider-pack-compatibility.js"; + +const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex"); +const reseal = (manifest: ProviderPackIdentity) => ({ ...manifest, digest: `sha256:${hash(canonicalProviderPackJson(manifest.payload))}` }); +const pack = (revision: string): ProviderPackIdentity => reseal({ + schema: "paperclip-runner/remote-provider-pack/v1", digest: "", + payload: { compatibility: { opencode: 1, acpx: 1 }, contractDigest: `sha256:${hash("interface")}`, + pins: { opencode: "1.2.3" }, target: { platform: "linux", architecture: "x64" }, runnerSourceRevision: revision.repeat(40), + acpxProfileDigests: { claude: hash("claude-profile") }, artifacts: { + nodeCommand: { path: "node/bin/node", sha256: `sha256:${hash(`${revision}-node`)}` }, + opencodeCommand: { path: "opencode", sha256: `sha256:${hash(`${revision}-opencode`)}` }, + } }, +}); +const expected = { manifest: pack("b"), runnerSha256: hash("same-runner") }; +const input = () => ({ installed: { manifest: pack("a"), runnerSha256: expected.runnerSha256, immutable: true }, + providers: [{ kind: "opencode" as const }, { kind: "acpx" as const, agent: "claude" }] }); + +describe("deployment sandbox runtime qualification", () => { + it("accepts different publication hashes when the runtime contract and requested profiles agree", () => { + const report = qualifySandboxRuntime(input(), expected); + expect(report.compatible).toBe(true); + expect(report.installedPackDigest).not.toBe(report.expectedPackDigest); + }); + + it.each(["runner", "protection", "contract", "revision", "profile", "digest"])("refuses an incompatible %s", change => { + const value = input(); + if (change === "runner") value.installed.runnerSha256 = hash("other-runner"); + if (change === "protection") value.installed.immutable = false; + if (change === "contract") value.installed.manifest.payload.contractDigest = `sha256:${hash("other-interface")}`; + if (change === "revision") value.installed.manifest.payload.compatibility!.acpx++; + if (change === "profile") value.installed.manifest.payload.acpxProfileDigests!.claude = hash("other-profile"); + value.installed.manifest = reseal(value.installed.manifest); + if (change === "digest") value.installed.manifest.digest = `sha256:${hash("corrupt")}`; + expect(qualifySandboxRuntime(value, expected)).toMatchObject({ compatible: false, failedCheck: expect.any(String) }); + }); + + it("checks every packaged provider by default, including candidate profiles", () => { + const candidate = pack("b"); + candidate.payload.acpxProfileDigests!.codex = hash("codex-profile"); + const expectedAll = { ...expected, manifest: reseal(candidate) }; + const report = qualifySandboxRuntime({ installed: input().installed }, expectedAll); + expect(report).toMatchObject({ compatible: false, allPackProviders: true }); + expect(report.providers).toContainEqual({ kind: "acpx", agent: "codex" }); + expect(qualifySandboxRuntime(input(), expectedAll)).toMatchObject({ compatible: true, allPackProviders: false }); + }); + + it("leaves unrequested provider profiles outside deployment policy", () => { + const value = input(); + value.installed.manifest.payload.acpxProfileDigests!.unrequested = hash("other-profile"); + value.installed.manifest = reseal(value.installed.manifest); + expect(qualifySandboxRuntime(value, expected).compatible).toBe(true); + }); + + it("ships an offline command with distinct compatible, incompatible and invalid outcomes", () => { + const directory = mkdtempSync(join(tmpdir(), "sandbox-runtime-qualification-")); + try { + const entry = join(directory, "qualify.mjs"), manifest = join(directory, "provider-pack.json"), runner = join(directory, "runnerd"); + buildSync({ entryPoints: [fileURLToPath(new URL("./qualify-sandbox-runtime.ts", import.meta.url))], + outfile: entry, bundle: true, platform: "node", format: "esm" }); + writeFileSync(manifest, JSON.stringify(expected.manifest)); + writeFileSync(runner, "same-runner"); + const run = (source: string) => spawnSync(process.execPath, [entry, "--manifest", manifest, "--runner", runner], + { input: source, encoding: "utf8", env: { PATH: process.env.PATH }, timeout: 5_000 }); + const accepted = run(JSON.stringify(input())); + expect(accepted.status, accepted.stderr).toBe(0); + expect(JSON.parse(accepted.stdout)).toMatchObject({ compatible: true, expectedPackDigest: expected.manifest.digest }); + const invalid = input(); invalid.installed.runnerSha256 = hash("other-runner"); + expect(run(JSON.stringify(invalid)).status).toBe(2); + expect(run("invalid JSON").status).toBe(1); + const { manifest: _manifest, ...withoutManifest } = input().installed; + expect(run(JSON.stringify({ installed: withoutManifest })).status).toBe(1); + expect(run(JSON.stringify({ installed: { ...withoutManifest, manifest: {} } })).status).toBe(1); + expect(readFileSync(manifest, "utf8")).toBe(JSON.stringify(expected.manifest)); + } finally { rmSync(directory, { recursive: true, force: true }); } + }); +}); diff --git a/server/src/qualify-sandbox-runtime.ts b/server/src/qualify-sandbox-runtime.ts new file mode 100644 index 00000000000..208c2d1782a --- /dev/null +++ b/server/src/qualify-sandbox-runtime.ts @@ -0,0 +1,74 @@ +import { createHash } from "node:crypto"; +import { readFileSync, realpathSync } from "node:fs"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import { canonicalProviderPackJson, compatibleProviderPackInstallation, + type PackProvider, type ProviderPackIdentity } from "./services/native-runtime/provider-pack-compatibility.js"; + +type QualificationInput = { + installed: { manifest: ProviderPackIdentity; runnerSha256: string; immutable: boolean }; + providers?: PackProvider[]; +}; + +export function qualifySandboxRuntime(input: QualificationInput, expected: { + manifest: ProviderPackIdentity; runnerSha256: string; +}) { + const providers = input?.providers ?? [{ kind: "opencode" as const }, + ...[...new Set([...Object.keys(expected.manifest?.payload?.acpxProfileDigests ?? {}), + ...Object.keys(expected.manifest?.payload?.providers ?? {}), ...Object.keys(expected.manifest?.payload?.candidateProviders ?? {})])] + .sort().map(agent => ({ kind: "acpx" as const, agent }))]; + if (!input || !input.installed || !input.installed.manifest || + typeof input.installed.manifest.schema !== "string" || typeof input.installed.manifest.digest !== "string" || + !input.installed.manifest.payload || typeof input.installed.manifest.payload !== "object" || Array.isArray(input.installed.manifest.payload) || + !Array.isArray(providers) || !providers.length || providers.length > 32 || + !/^[a-f0-9]{64}$/.test(input.installed.runnerSha256) || typeof input.installed.immutable !== "boolean" || + providers.some(provider => !provider || (provider.kind !== "opencode" && + (provider.kind !== "acpx" || typeof provider.agent !== "string" || !/^[a-z][a-z0-9_-]{0,63}$/.test(provider.agent))))) { + throw new Error("Invalid sandbox runtime qualification input"); + } + const digest = (value: unknown) => `sha256:${createHash("sha256").update(canonicalProviderPackJson(value)).digest("hex")}`; + if (!expected.manifest?.payload || expected.manifest.digest !== digest(expected.manifest.payload)) { + throw new Error("Invalid expected provider-pack manifest"); + } + let failedCheck: string | undefined; + if (input.installed.runnerSha256 !== expected.runnerSha256) failedCheck = "runner_binary"; + for (const provider of providers) { + if (failedCheck) break; + try { + compatibleProviderPackInstallation({ root: "/opt/paperclip-runner/provider-pack", + manifest: input.installed.manifest, immutable: input.installed.immutable }, expected.manifest, + "/opt/paperclip-runner/provider-pack", provider, false, false); + } catch (error) { + failedCheck = (error as { failureCheck?: string }).failureCheck ?? "provider_pack"; + } + } + return { + schema: "paperclip.sandbox-runtime-qualification.v1", + compatible: failedCheck === undefined, + ...(failedCheck ? { failedCheck } : {}), + expectedPackDigest: expected.manifest.digest, + installedPackDigest: input.installed.manifest?.digest, + runnerSha256: expected.runnerSha256, + providers, + allPackProviders: input.providers === undefined, + }; +} + +export function runSandboxRuntimeQualification(args: string[], source: string) { + if (args.length !== 4 || args[0] !== "--manifest" || args[2] !== "--runner" || !args[1] || !args[3] || + Buffer.byteLength(source) > 2 * 1024 * 1024) throw new Error("Invalid sandbox qualification arguments"); + const manifest = JSON.parse(readFileSync(args[1], "utf8")) as ProviderPackIdentity; + const runnerSha256 = createHash("sha256").update(readFileSync(args[3])).digest("hex"); + return qualifySandboxRuntime(JSON.parse(source), { manifest, runnerSha256 }); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(resolve(process.argv[1]))).href) { + try { + const report = runSandboxRuntimeQualification(process.argv.slice(2), readFileSync(0, "utf8")); + process.stdout.write(`${JSON.stringify(report)}\n`); + process.exitCode = report.compatible ? 0 : 2; + } catch { + process.stderr.write("Sandbox runtime qualification could not be completed\n"); + process.exitCode = 1; + } +} diff --git a/server/src/services/environments.ts b/server/src/services/environments.ts index e1a29c71d6c..f586d31d887 100644 --- a/server/src/services/environments.ts +++ b/server/src/services/environments.ts @@ -180,17 +180,6 @@ export interface ManagedSandboxEnvironmentInput { extraMetadata?: Record; /** Version label recorded with the stock binding; hashes remain the drift authority. */ stockVersion?: string; - /** - * Asserts the caller's deployment gives no operator any path to hand-edit - * this row (currently only true for the PAPERCLIP_MANAGED_CONFIG applier, - * where `enableManagedSandboxOnly` removes the tenant's own environment - * choice entirely). When set, a plain content-hash mismatch against a real - * prior binding is treated as ordinary stock drift instead of an operator - * customization to protect — see the `operator_modified` handling below. - * Leave unset for any caller (self-hosted `kubernetes-execution-mode` - * bootstrap, tests, admin routes) where an operator could realistically - * have edited the row through the normal environments UI/API. - */ platformFullyManaged?: boolean; } @@ -648,35 +637,19 @@ export function environmentService(db: Db) { ); if (operatorReaffirmedArchive) stockStatus = "operator_modified"; - // `platformFullyManaged` callers (currently: the PAPERCLIP_MANAGED_CONFIG - // applier) assert that nothing in their deployment can hand-edit this - // row — the product gives a cloud-harness tenant no path to it, unlike - // the general self-hosted contract this function otherwise protects - // (see "classifies operator drift" in environment-service.test.ts, - // which exercises a real operator edit and must keep winning). Under - // that assertion, a plain content-hash mismatch against a real prior - // binding can only be drift between two platform-driven reconciliation - // passes (e.g. a stock hash recorded by an older app build before a - // later stock field was added), never a customization to protect — - // apply it like any other stock-outdated row. - // - // Two things the bypass must never touch: - // - A row with NO matching binding. `row` can be a same-name sandbox - // row that was never Paperclip-managed (the fallback lookup above). - // It also reads as `operator_modified`, but there is no prior - // platform pass to have drifted from — adopting it would overwrite - // a tenant-created environment and stamp it managed. Require a - // binding for this exact row, so "prior binding" is enforced, not - // just documented. - // - Archive-reaffirmation. A `sandbox_image` update must never - // resurrect a row something else deliberately kept archived after - // Paperclip's own provider-unavailability archival, so that path - // still skips below regardless of this flag. + const platformOwnedRow = row.metadata?.managedByPaperclip === true; + const platformArchivedRow = row.status === "archived" && + typeof rowArchiveToken === "string" && + matchingBindings.some((binding) => + binding.defaultsJson.status === "archived" && + binding.defaultsJson[MANAGED_ENVIRONMENT_ARCHIVE_TOKEN_DEFAULTS_KEY] === rowArchiveToken, + ); if ( input.platformFullyManaged && stockStatus === "operator_modified" && !operatorReaffirmedArchive && - matchingBindings.length > 0 + platformOwnedRow && + (row.status === "active" || platformArchivedRow) ) { stockStatus = "stock_update_available"; } diff --git a/server/src/services/native-runtime/provider-pack-compatibility.ts b/server/src/services/native-runtime/provider-pack-compatibility.ts new file mode 100644 index 00000000000..a7379f43131 --- /dev/null +++ b/server/src/services/native-runtime/provider-pack-compatibility.ts @@ -0,0 +1,79 @@ +import { createHash } from "node:crypto"; + +export function canonicalProviderPackJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalProviderPackJson).join(",")}]`; + if (value && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)) + .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalProviderPackJson(entry)}`).join(",")}}`; + return JSON.stringify(value) ?? "null"; +} + +export type ProviderPackIdentity = { + schema: string; + digest: string; + payload: { + compatibility?: { opencode: number; acpx: number }; + contractDigest?: string; + acpxProfileDigests?: Record; + providers?: Record; + candidateProviders?: Record; + pins: { opencode: string; [key: string]: string | null }; + target: { platform: string; architecture: string }; + runnerSourceRevision: string; + runnerInputsDigest?: string; + artifacts: { nodeCommand: { path: string; sha256: string }; opencodeCommand: { path: string; sha256: string }; [key: string]: { path: string; sha256: string } }; + }; +}; + +export function providerPackIncompatible(check: string, detail: string): Error & { failureCheck: string } { + return Object.assign(new Error(`runner_remote_provider_artifact_incompatible: ${detail}`), { failureCheck: check }); +} + +export type ProviderPackInstallation = { root: string; manifest: unknown; immutable: boolean }; +export type PackProvider = { kind: "opencode" } | { kind: "acpx"; agent: string }; + +export function compatibleProviderPackInstallation( + installation: ProviderPackInstallation, expected: T, packRoot: string, + provider: PackProvider, requireExactIdentity: boolean, requireCurrentOpenCodeProxy: boolean, +): T { + const actual = installation.manifest as T | null; + const payload = actual?.payload; + const contract = expected.payload.compatibility?.[provider.kind]; + const failed = !installation.immutable ? "installation_unprotected" + : installation.root !== packRoot ? "installation_root" + : !payload ? "manifest_missing" + : actual.schema !== expected.schema ? "schema" + : actual.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex")}` ? "manifest_digest" + : canonicalProviderPackJson(payload.target) !== canonicalProviderPackJson(expected.payload.target) ? "target" + : requireExactIdentity ? (actual.digest !== expected.digest ? "exact_identity" : null) + : !Number.isSafeInteger(contract) || contract! < 1 ? "expected_compatibility_missing" + : payload.compatibility?.[provider.kind] !== contract ? "compatibility_revision" + : !/^sha256:[a-f0-9]{64}$/.test(expected.payload.contractDigest ?? "") ? "expected_contract_digest_missing" + : payload.contractDigest === undefined ? "contract_digest_missing" + : payload.contractDigest !== expected.payload.contractDigest ? "contract_digest" + : null; + if (failed || !actual || !payload || typeof payload.pins?.opencode !== "string") { + throw providerPackIncompatible(failed ?? "opencode_pin_missing", "installed provider pack interface or installation is incompatible"); + } + for (const [name, expectedArtifact] of Object.entries(expected.payload.artifacts)) { + const artifact = payload.artifacts?.[name]; + if (artifact?.path !== expectedArtifact.path || !/^sha256:[a-f0-9]{64}$/.test(artifact.sha256)) { + throw providerPackIncompatible(`artifact:${name}`, "installed provider pack artifact identity is invalid"); + } + } + if (provider.kind === "opencode" && requireCurrentOpenCodeProxy + && payload.artifacts.opencodeProxy?.sha256 !== expected.payload.artifacts.opencodeProxy?.sha256) { + throw providerPackIncompatible("opencode_proxy", "installed proxy does not match the requested OpenCode diagnostics"); + } + if (provider.kind === "acpx") { + const agent = provider.agent; + const currentProfile = expected.payload.acpxProfileDigests?.[agent]; + const selected = expected.payload.providers?.[agent] ?? expected.payload.candidateProviders?.[agent]; + const installed = payload.providers?.[agent] ?? payload.candidateProviders?.[agent]; + if (currentProfile ? payload.acpxProfileDigests?.[agent] !== currentProfile + : !selected || !installed || ["version", "profileDigest", "closureDigest", "qualification", "path"].some(key => + (installed as Record)[key] !== (selected as Record)[key])) { + throw providerPackIncompatible("acpx_profile", "selected ACPX provider profile is incompatible"); + } + } + return structuredClone(actual); +} diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.ts b/server/src/services/native-runtime/remote-provider-pack-verification.ts index 0fc4d332ea6..021fec76fbd 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.ts @@ -3,34 +3,10 @@ import { posix } from "node:path"; import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; import { runRemoteProviderVerification } from "./remote-provider-pack.js"; -export function canonicalProviderPackJson(value: unknown): string { - if (Array.isArray(value)) return `[${value.map(canonicalProviderPackJson).join(",")}]`; - if (value && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)) - .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalProviderPackJson(entry)}`).join(",")}}`; - return JSON.stringify(value) ?? "null"; -} - -export type ProviderPackIdentity = { - schema: string; - digest: string; - payload: { - compatibility?: { opencode: number; acpx: number }; - contractDigest?: string; - acpxProfileDigests?: Record; - providers?: Record; - candidateProviders?: Record; - pins: { opencode: string; [key: string]: string | null }; - target: { platform: string; architecture: string }; - runnerSourceRevision: string; - /** Identity of the Runner image the pack was built in, when it was built there. Provenance only. */ - runnerInputsDigest?: string; - artifacts: { nodeCommand: { path: string; sha256: string }; opencodeCommand: { path: string; sha256: string }; [key: string]: { path: string; sha256: string } }; - }; -}; - -export function providerPackIncompatible(check: string, detail: string): Error & { failureCheck: string } { - return Object.assign(new Error(`runner_remote_provider_artifact_incompatible: ${detail}`), { failureCheck: check }); -} +import { canonicalProviderPackJson, providerPackIncompatible, compatibleProviderPackInstallation, + type ProviderPackIdentity, type ProviderPackInstallation, type PackProvider } from "./provider-pack-compatibility.js"; +export { canonicalProviderPackJson, providerPackIncompatible, type ProviderPackIdentity, + type ProviderPackInstallation, type PackProvider } from "./provider-pack-compatibility.js"; async function withProviderPackCheck(step: "pack" | "opencode", verify: () => Promise): Promise { try { @@ -44,66 +20,6 @@ async function withProviderPackCheck(step: "pack" | "opencode", verify: () => } } -export type ProviderPackInstallation = { root: string; manifest: unknown; immutable: boolean }; -export type PackProvider = { kind: "opencode" } | { kind: "acpx"; agent: string }; - -/** Admission of a build-qualified, OS-protected installation. Source revisions, - * dependency pins and unrelated provider changes are provenance, not an interface. - * The interface is the hand-maintained compatibility revision plus the pack's - * computed contract digest; a pack without a digest predates that check and - * is replaced rather than reused. - * The metadata comes from the trusted runner, never from a provider tool result. - */ -function compatibleInstallation( - installation: ProviderPackInstallation, expected: T, packRoot: string, - provider: PackProvider, requireExactIdentity: boolean, requireCurrentOpenCodeProxy: boolean, -): T { - const actual = installation.manifest as T | null; - const payload = actual?.payload; - const contract = expected.payload.compatibility?.[provider.kind]; - const failed = !installation.immutable ? "installation_unprotected" - : installation.root !== packRoot ? "installation_root" - : !payload ? "manifest_missing" - : actual.schema !== expected.schema ? "schema" - : actual.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex")}` ? "manifest_digest" - : canonicalProviderPackJson(payload.target) !== canonicalProviderPackJson(expected.payload.target) ? "target" - : requireExactIdentity ? (actual.digest !== expected.digest ? "exact_identity" : null) - : !Number.isSafeInteger(contract) || contract! < 1 ? "expected_compatibility_missing" - : payload.compatibility?.[provider.kind] !== contract ? "compatibility_revision" - : !/^sha256:[a-f0-9]{64}$/.test(expected.payload.contractDigest ?? "") ? "expected_contract_digest_missing" - : payload.contractDigest === undefined ? "contract_digest_missing" - : payload.contractDigest !== expected.payload.contractDigest ? "contract_digest" - : null; - if (failed || !actual || !payload || typeof payload.pins?.opencode !== "string") { - throw providerPackIncompatible(failed ?? "opencode_pin_missing", "installed provider pack interface or installation is incompatible"); - } - // Launch profiles and recovery receipts bind the selected installation's own - // bytes, never the current controller's artifact hashes. - for (const [name, expectedArtifact] of Object.entries(expected.payload.artifacts)) { - const artifact = payload.artifacts?.[name]; - if (artifact?.path !== expectedArtifact.path || !/^sha256:[a-f0-9]{64}$/.test(artifact.sha256)) { - throw providerPackIncompatible(`artifact:${name}`, "installed provider pack artifact identity is invalid"); - } - } - if (provider.kind === "opencode" && requireCurrentOpenCodeProxy - && payload.artifacts.opencodeProxy?.sha256 !== expected.payload.artifacts.opencodeProxy?.sha256) { - throw providerPackIncompatible("opencode_proxy", "installed proxy does not match the requested OpenCode diagnostics"); - } - if (provider.kind === "acpx") { - const agent = provider.agent; - const currentProfile = expected.payload.acpxProfileDigests?.[agent]; - const selected = expected.payload.providers?.[agent] ?? expected.payload.candidateProviders?.[agent]; - const installed = payload.providers?.[agent] ?? payload.candidateProviders?.[agent]; - // ACPX's existing qualified launch profiles remain authoritative for the - // selected agent. Other providers in the same pack do not invalidate it. - if (currentProfile ? payload.acpxProfileDigests?.[agent] !== currentProfile - : !selected || !installed || ["version", "profileDigest", "closureDigest", "qualification", "path"].some(key => - (installed as Record)[key] !== (selected as Record)[key])) { - throw providerPackIncompatible("acpx_profile", "selected ACPX provider profile is incompatible"); - } - } - return structuredClone(actual); -} /** * A Node expression defining `packIdentity(root)`: a digest of the kernel @@ -153,7 +69,7 @@ export async function verifyRemoteProviderPack({ }): Promise { if (installation) { if (!provider) throw new Error("runner_remote_provider_artifact_incompatible: provider interface is required"); - return compatibleInstallation(installation, manifest, packRoot, provider, requireExactIdentity, requireCurrentOpenCodeProxy); + return compatibleProviderPackInstallation(installation, manifest, packRoot, provider, requireExactIdentity, requireCurrentOpenCodeProxy); } const providerNodeCommand = posix.join( packRoot,