From f669194298ea36d5dab375f2b297a48266de80a3 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 7 Oct 2026 10:16:49 -0500 Subject: [PATCH] fix(runner): propagate configured environment to future turns (#15451) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native runners start provider processes and enforce a separate tool environment policy. > - The server resolves task environment bindings at each run boundary. > - Fixed launch allowlists dropped custom variables after resolution. > - Warm process reuse and a blanket fingerprint exclusion also hid configuration changes. > - This pull request carries a bounded, server-selected list of task variable names through each process boundary. > - The benefit is that later turns and tool commands receive configured values while ambient host secrets stay excluded. ## Linked Issues or Issue Description **What happened?** A native Codex agent could not use configured task credentials. Adding the variables in Settings did not fix the next turn. The provider sanitizer, runner launch, Rust provider launch, and shell policy each used fixed allowlists. Effective config fingerprints also excluded all variables with the `PAPERCLIP_` prefix. **Expected behavior** Explicitly bound task variables must reach provider processes and tool commands. Added, changed, and removed values must take effect at the next run boundary. A running turn keeps its original configuration. **Steps to reproduce** 1. Start a native Codex task without a custom environment binding. 2. Add a fake `PAPERCLIP_PAGE_BUCKET` value and a fake Pages credential binding in Settings. 3. Continue the task and inspect the tool environment. 4. Before this fix, those values are absent even from a fresh runner launch. **Paperclip version or commit** Reproduced at `b31558064`. The fix is rebased on current master. **Deployment mode** Self-hosted server with a native process runner. Related changes: [the legacy Codex MCP environment fix](https://github.com/paperclipai/paperclip/pull/13321) and [ambient server-secret exclusion](https://github.com/paperclipai/paperclip/pull/12870). These affect different launch paths. This change preserves their credential boundaries. ## What Changed - Capture scoped task bindings after resolution, before managed provider credential injection. Mint and validate the names-only projection at native dispatch before host inheritance. Legacy adapters retain their previous environment limits. - Strip user-supplied projection markers from agent, environment, project, and routine config. - Carry selected values through the Codex, ACPX, OpenCode, runnerd, and Rust subprocess launch boundaries. - Add selected names to native and ACPX Codex shell include lists. Keep selected values out of command arguments, including selected bootstrap values. - Reject malformed projections, reserved authority and loader names, missing values, null bytes, and oversized input. - Replace a retained native process when projected values change. Keep unchanged processes reusable. - Fingerprint custom namespaced variables while excluding known generated runtime variables. - Document next-run behavior and add regression coverage. ## Verification - Red: the permanent reproduction failed at four launch/tool boundaries and the namespaced fingerprint check. Two control checks passed. - Green: the initial regression plus existing Codex environment and shell tests passed (39 tests). - Server config resolution, fingerprints, and native-session suites passed (653 tests), including addition, rotation, removal, and unchanged warm-session reuse. - Rust regression tests passed. A real shell child received added and rotated values, then lost them after removal. Unselected host variables stayed absent. - `pnpm -r typecheck` and `pnpm build` passed after rebase. The full `pnpm test:run` was attempted but could not complete: fresh embedded PostgreSQL databases fail during bootstrap on this macOS host. An isolated suite and a disposable native `initdb` probe reproduced the failure before test execution. `shmget` reports `No space left on device` because the host has exhausted shared-memory IDs. This is not disk exhaustion. The run was stopped after confirming the external setup failure. CI results will be recorded separately. - Runner boundary suites: 361 tests passed. Two process-launch errors during concurrent binary staging passed on isolated rerun. - Rust Codex provider and process supervisor integration suites: 97 passed, 2 intentionally ignored. - ACPX shell and selected-bootstrap argv regressions: 3 failed before the fix, then all 55 relevant tests passed. - Review compatibility regression: 129-variable and large-value legacy configurations failed before the correction and passed after moving native-only validation to dispatch. - Final review head `3f11e8d25`: repository typechecks and production build passed. CI completed its implementation checks; one general-server shard hit SQL `40P01` in `heartbeat-runtime-skills.test.ts` during its `beforeEach` table truncate (1,199 tests passed in that shard). The shard passed on its single rerun. All CI checks for this head are green. Greptile reviewed this head at 5/5 with no new actionable findings; the compatibility thread is resolved. - No live provider credentials or model calls are required by these tests. ## Risks - Configured task credentials now reach the tools they were configured for. The controller selects names only after existing scope and secret-binding authorization. - TypeScript and Rust validate the same bounded projection. Their reserved-name rules must stay aligned. - A changed projection replaces an idle provider process. Unchanged values preserve reuse. Active turns retain their original environment. - No database migration or API schema change. > This fixes existing runner configuration behavior. It does not add a new roadmap capability. ## Model Used - OpenAI GPT-6 (Codex), with reasoning, local code execution, and repository tools. The session does not expose a more specific API model identifier or context window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/DEVELOPING.md | 2 +- .../runner-core/src/configured_environment.rs | 225 ++++++++++++++++++ .../runner/crates/runner-core/src/lib.rs | 1 + .../runner-core/src/process_supervisor.rs | 3 + .../src/configured-environment.test.ts | 99 ++++++++ .../src/configured-environment.ts | 76 ++++++ .../durable-prp-control-plane.ts | 3 +- .../src/drivers/acpx/environment.ts | 3 +- .../src/drivers/acpx/runtime-sandbox.test.ts | 17 ++ .../src/drivers/acpx/runtime-sandbox.ts | 9 +- .../src/drivers/codex/app-server-transport.ts | 3 +- .../drivers/codex/codex-security-config.ts | 8 +- packages/paperclip-runner/src/index.ts | 1 + .../src/live/runnerd-codex-transport.ts | 5 +- .../effective-run-config-fingerprints.test.ts | 27 +++ .../__tests__/heartbeat-project-env.test.ts | 39 +++ .../effective-run-config-fingerprints.ts | 4 +- server/src/services/heartbeat.ts | 10 +- .../native-session-executor.test.ts | 37 +++ .../native-runtime/native-session-executor.ts | 7 + server/src/vendor/paperclip-runner/index.ts | 5 + 21 files changed, 571 insertions(+), 13 deletions(-) create mode 100644 packages/paperclip-runner/runner/crates/runner-core/src/configured_environment.rs create mode 100644 packages/paperclip-runner/src/configured-environment.test.ts create mode 100644 packages/paperclip-runner/src/configured-environment.ts diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index cc6c53791cd..a25a6801f56 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -858,7 +858,7 @@ If a repository is detached or its source configuration changes, its previous ta ## Config Freshness -Agent, project, environment, secret, skill, and workspace config edits are sampled at the next run boundary. A heartbeat that is already running finishes with the config it started with. +Agent, project, environment, secret, skill, and workspace config edits are sampled at the next run boundary. A heartbeat that is already running finishes with the config it started with. Native runners project explicitly configured task environment variables into provider processes and tool commands, including custom `PAPERCLIP_*` names such as `PAPERCLIP_PAGE_BUCKET`. Adding, changing, or removing a projected variable replaces a retained provider process at the next run boundary. Unchanged variables permit process reuse. The projection contains names only; secret values stay in the child environment. Ambient host secrets are not projected. Native projections allow up to 128 variable names, 64 KiB per entry, and 256 KiB of values in total. These native launch limits do not apply to legacy adapter configuration. Runtime authority, provider login credentials, and process-loader settings use their existing restricted paths. When effective run config changes, Paperclip may intentionally skip a saved adapter session, refresh persisted workspace runtime config, replace a reused execution workspace, or avoid reusing a sandbox/environment lease. Fresh execution can lose adapter-specific session, workspace, or sandbox state; correctness of the next run's config takes priority over continuity. Plain environment values affect freshness through value hashes; run result JSON and workspace operation logs expose only the non-sensitive freshness decision categories, without storing secret values, full env maps, provider credentials, or private path details. diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/configured_environment.rs b/packages/paperclip-runner/runner/crates/runner-core/src/configured_environment.rs new file mode 100644 index 00000000000..27c0c24b004 --- /dev/null +++ b/packages/paperclip-runner/runner/crates/runner-core/src/configured_environment.rs @@ -0,0 +1,225 @@ +//! Controller-selected task environment; mirrors configured-environment.ts. +use crate::local_runner::LocalRunnerError; +use std::process::Command; + +const MARKER: &str = "PAPERCLIP_CONFIGURED_ENV_KEYS"; +const RESERVED: &[&str] = &[ + "AGENT_HOME", + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "AWS_BEARER_TOKEN_BEDROCK", + "BASH_ENV", + "CLAUDE_CODE_OAUTH_TOKEN", + "CODEX_API_KEY", + "CODEX_HOME", + "COPILOT_GITHUB_TOKEN", + "CURSOR_API_KEY", + "CURSOR_AUTH_TOKEN", + "ENV", + "GH_ENTERPRISE_TOKEN", + "GH_TOKEN", + "GITHUB_ENTERPRISE_TOKEN", + "GITHUB_TOKEN", + "HOME", + "NODE_OPTIONS", + "NODE_PATH", + "OPENAI_API_KEY", + "OPENROUTER_API_KEY", + "PAPERCLIP_ACPX_CREDENTIAL_BINDING", + "PAPERCLIP_AGENT_ID", + "PAPERCLIP_AGENT_KEY_ID", + "PAPERCLIP_AGENT_MESSAGE_KEY", + "PAPERCLIP_AGENT_PRIVATE_KEY", + "PAPERCLIP_AGENT_PUBLIC_KEY", + "PAPERCLIP_AI_PROVIDER_KEY", + "PAPERCLIP_API_BRIDGE_MODE", + "PAPERCLIP_API_KEY", + "PAPERCLIP_API_URL", + "PAPERCLIP_APPROVAL_ID", + "PAPERCLIP_APPROVAL_STATUS", + "PAPERCLIP_COMPANY_ID", + "PAPERCLIP_CONFIGURED_ENV_KEYS", + "PAPERCLIP_EXECUTION_MODE", + "PAPERCLIP_EXTERNAL_CHAT_EXECUTION_BOUND_KEY", + "PAPERCLIP_GITHUB_AUTH_MODE", + "PAPERCLIP_GITHUB_BRIDGE_TOKEN", + "PAPERCLIP_GITHUB_BROKER_TOKEN", + "PAPERCLIP_GITHUB_BROKER_URL", + "PAPERCLIP_GITHUB_HOST_HOME", + "PAPERCLIP_GITHUB_LAUNCHER_DIR", + "PAPERCLIP_GIT_METADATA_ROOTS", + "PAPERCLIP_GIT_TOKEN", + "PAPERCLIP_HARNESS_CHECKOUT_KEY", + "PAPERCLIP_INSTANCE_ID", + "PAPERCLIP_LINKED_ISSUE_IDS", + "PAPERCLIP_NATIVE_MCP_NAME", + "PAPERCLIP_NATIVE_MCP_TOKEN", + "PAPERCLIP_NATIVE_MCP_URL", + "PAPERCLIP_NORMALIZED_SESSION_ID", + "PAPERCLIP_PROVIDER_TRACE_MAX_BYTES", + "PAPERCLIP_PROVIDER_TRACE_PATH", + "PAPERCLIP_RUNNER_BOOTSTRAP_TICKET", + "PAPERCLIP_RUNNER_EXTERNAL_SANDBOX", + "PAPERCLIP_RUNNER_INSTANCE_ID", + "PAPERCLIP_RUNNER_NETWORK_ACCESS", + "PAPERCLIP_RUNNER_NETWORK_ROOTS", + "PAPERCLIP_RUNTIME_PRIMARY_URL", + "PAPERCLIP_RUNTIME_SERVICES_JSON", + "PAPERCLIP_RUNTIME_SERVICE_INTENTS_JSON", + "PAPERCLIP_RUN_ID", + "PAPERCLIP_TASK_ID", + "PAPERCLIP_WAKE_COMMENT_ID", + "PAPERCLIP_WAKE_PAYLOAD_JSON", + "PAPERCLIP_WAKE_REASON", + "PAPERCLIP_WORKSPACES_JSON", + "PAPERCLIP_WORKSPACE_AUTHORITATIVE_ROOT", + "PAPERCLIP_WORKSPACE_BRANCH", + "PAPERCLIP_WORKSPACE_CWD", + "PAPERCLIP_WORKSPACE_ID", + "PAPERCLIP_WORKSPACE_REALIZATION_MODE", + "PAPERCLIP_WORKSPACE_REPO_REF", + "PAPERCLIP_WORKSPACE_REPO_URL", + "PAPERCLIP_WORKSPACE_SOURCE", + "PAPERCLIP_WORKSPACE_WORKTREE_PATH", + "PATH", + "PERL5LIB", + "PERL5OPT", + "PYTHONHOME", + "PYTHONPATH", + "RUBYLIB", + "RUBYOPT", + "SHELL", + "USERPROFILE", + "XAI_API_KEY", +]; + +fn eligible_key(key: &str) -> bool { + let upper = key.to_ascii_uppercase(); + !key.is_empty() + && key.len() <= 128 + && key + .bytes() + .enumerate() + .all(|(i, b)| b == b'_' || b.is_ascii_alphabetic() || (i > 0 && b.is_ascii_digit())) + && !RESERVED.contains(&upper.as_str()) + && ![ + "LD_", + "DYLD_", + "GIT_CONFIG_", + "PAPERCLIP_RUNNER_", + "PAPERCLIP_NATIVE_", + "PAPERCLIP_GITHUB_", + "PAPERCLIP_ACPX_", + "PAPERCLIP_VERIFIED_", + ] + .iter() + .any(|prefix| upper.starts_with(prefix)) +} + +pub(crate) fn apply_configured_environment( + command: &mut Command, + lookup: impl Fn(&str) -> Option, +) -> Result<(), LocalRunnerError> { + let Some(raw) = lookup(MARKER) else { + return Ok(()); + }; + let invalid = || LocalRunnerError::invalid("invalid configured environment projection"); + if raw.len() > 20_000 { + return Err(invalid()); + } + let mut names: Vec = serde_json::from_str(&raw).map_err(|_| invalid())?; + if names.len() > 128 || names.iter().any(|name| !eligible_key(name)) { + return Err(invalid()); + } + names.sort(); + if names.windows(2).any(|pair| pair[0] == pair[1]) { + return Err(invalid()); + } + let mut bytes = 0; + // Validate all values before modifying the child launch specification. + let mut values = Vec::new(); + for name in &names { + let value = lookup(name).ok_or_else(invalid)?; + let size = name.len() + value.len(); + bytes += size; + if value.contains('\0') || size > 65_536 || bytes > 262_144 { + return Err(invalid()); + } + values.push((name, value)); + } + command.envs(values); + command.env( + MARKER, + serde_json::to_string(&names).map_err(|_| invalid())?, + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + + #[test] + fn rejects_reserved_malformed_missing_and_oversized_environment() { + for raw in [ + "not-json", + "[1]", + "[\"NODE_OPTIONS\"]", + "[\"PAPERCLIP_API_KEY\"]", + "[\"PAPERCLIP_RUNNER_BOOTSTRAP_TICKET\"]", + "[\"OPENAI_API_KEY\"]", + "[\"LD_PRELOAD\"]", + "[\"bad=name\"]", + "[\"CUSTOM\",\"CUSTOM\"]", + "[\"MISSING\"]", + ] { + let mut command = Command::new("unused"); + assert!( + apply_configured_environment(&mut command, |key| if key == MARKER { + Some(raw.into()) + } else { + None + }) + .is_err() + ); + assert_eq!(command.get_envs().count(), 0); + } + let mut command = Command::new("unused"); + assert!( + apply_configured_environment(&mut command, |key| Some(if key == MARKER { + "[\"CUSTOM\"]".into() + } else { + "x".repeat(65_536) + })) + .is_err() + ); + } + + #[test] + #[cfg(unix)] + fn child_receives_only_selected_task_values_across_configuration_changes() { + for secret in [None, Some("first-secret"), Some("rotated-secret"), None] { + let mut source = BTreeMap::from([ + ("HOST_SECRET", "unbound-secret".to_string()), + ("NODE_OPTIONS", "unbound-loader".to_string()), + ]); + let names = if let Some(value) = secret { + source.insert("PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY", value.into()); + vec!["PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY"] + } else { + vec![] + }; + source.insert(MARKER, serde_json::to_string(&names).unwrap()); + let mut command = Command::new("/bin/sh"); + command.env_clear().args(["-c", "printf '%s|%s|%s' \"$PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY\" \"$HOST_SECRET\" \"$NODE_OPTIONS\""]); + apply_configured_environment(&mut command, |key| source.get(key).cloned()).unwrap(); + let output = command.output().unwrap(); + assert!(output.status.success()); + assert_eq!( + String::from_utf8(output.stdout).unwrap(), + format!("{}||", secret.unwrap_or_default()) + ); + } + } +} diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs b/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs index ab2e2774dfa..a96f4cb07c5 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs @@ -12,6 +12,7 @@ pub mod aws_agentcore_provider; pub mod claude_managed_provider; pub mod codex_provider; mod codex_startup_trust; +mod configured_environment; pub mod durable; pub mod fake_harness; mod generated_acpx_profiles; diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/process_supervisor.rs b/packages/paperclip-runner/runner/crates/runner-core/src/process_supervisor.rs index af12df41e53..415a72186b5 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/process_supervisor.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/process_supervisor.rs @@ -780,6 +780,9 @@ impl SupervisedProcess { command.env(key, value); } } + crate::configured_environment::apply_configured_environment(&mut command, |key| { + std::env::var(key).ok() + })?; if let Some(executable) = verified_runtime_executable { // Node reports a sealed memfd launch as `/memfd:... (deleted)` via // process.execPath. Give descriptor-loaded runtimes the inherited, diff --git a/packages/paperclip-runner/src/configured-environment.test.ts b/packages/paperclip-runner/src/configured-environment.test.ts new file mode 100644 index 00000000000..94313010790 --- /dev/null +++ b/packages/paperclip-runner/src/configured-environment.test.ts @@ -0,0 +1,99 @@ +import { CONFIGURED_ENVIRONMENT_KEYS, configuredEnvironment, configuredEnvironmentProjection } from './configured-environment.js'; +import { describe, expect, it, vi } from 'vitest'; +import { createSanitizedCodexEnvironment } from './drivers/codex/app-server-transport.js'; +import { createIsolatedCodexAppServerArgs } from './drivers/codex/codex-security-config.js'; +import { createCapabilityRunnerdProviderEnvironment } from './live/runnerd-codex-transport.js'; +import { spawnRunner } from './control-plane/durable-prp-control-plane.js'; + +const pages = { + PAPERCLIP_PAGE_AWS_ACCESS_KEY_ID: 'fake-page-access-key', + PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY: 'fake-page-secret', + PAPERCLIP_PAGE_BUCKET: 'pages.example.test', +}; +const source = { ...configuredEnvironmentProjection(pages), PATH: '/bin', ...pages, DATABASE_URL: 'host-secret-must-not-cross', NODE_OPTIONS: '--require=/untrusted/bootstrap.js', PAPERCLIP_API_KEY: 'controller-api-key-must-not-cross' }; +const identity = { runnerInstanceId: 'runner-proof', environmentLeaseId: 'lease-proof', runId: 'run-proof', normalizedSessionId: 'session-proof', turnId: 'turn-proof', itemId: 'item-proof' }; +function shellKeys() { + const args = createIsolatedCodexAppServerArgs(source); + const setting = args.find(value => value.startsWith('shell_environment_policy.include_only='))!; + return { keys: JSON.parse(setting.slice(setting.indexOf('=') + 1)) as string[], serialized: args.join('\n') }; +} + +describe('controller-configured environment across native runner boundaries', () => { + it('retains configured Pages values at the native Codex provider sanitizer', () => { + expect(createSanitizedCodexEnvironment(source)).toMatchObject(pages); + }); + it('retains configured Pages values when preparing a fresh runnerd process', () => { + expect(createCapabilityRunnerdProviderEnvironment({ provider: 'codex', options: { environment: source }, identity, codexHome: '/isolated/codex-home', runtimeContextPath: '/isolated/runtime-context.json', hasRuntimeContext: false })).toMatchObject(pages); + }); + it('passes configured Pages values through the runner spawn boundary', () => { + let launched: NodeJS.ProcessEnv | undefined; + spawnRunner({ connection: { mode: 'connect', connectUrl: 'ws://127.0.0.1:43127' }, stateDirectory: '/tmp/runner-env-proof', identity, ticket: 'fake-ticket', maxOutboxBytes: 262144, p0ReserveBytes: 65536, runnerVersion: '0.3.0', runnerDigest: `sha256:${'a'.repeat(64)}`, environment: source, + processLauncher: spec => { launched = spec.environment; return { child: { pid: 42, exitCode: null, signalCode: null, kill: () => true }, completion: Promise.resolve({ code: 0, signal: null, stdout: '', stderr: '' }) }; }, + }); + expect(launched).toMatchObject(pages); + expect(launched!.DATABASE_URL).toBeUndefined(); + expect(launched!.NODE_OPTIONS).toBeUndefined(); + expect(launched!.PAPERCLIP_API_KEY).toBeUndefined(); + }); + it('allows configured Pages values into model-issued shell commands without serializing secrets into argv', () => { + const { keys, serialized } = shellKeys(); + expect(keys).toEqual(expect.arrayContaining(Object.keys(pages))); + expect(keys).not.toContain('DATABASE_URL'); + expect(keys).not.toContain('NODE_OPTIONS'); + expect(keys).not.toContain('PAPERCLIP_API_KEY'); + for (const value of Object.values(pages)) expect(serialized).not.toContain(value); + }); + it('continues to exclude unbound ambient Pages credentials and host secrets', () => { + vi.stubEnv('PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY', 'ambient-page-secret'); + try { + expect(createSanitizedCodexEnvironment().PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY).toBeUndefined(); + const sanitized = createSanitizedCodexEnvironment(source); + expect(sanitized.DATABASE_URL).toBeUndefined(); + expect(sanitized.NODE_OPTIONS).toBeUndefined(); + expect(sanitized.PAPERCLIP_API_KEY).toBeUndefined(); + } finally { vi.unstubAllEnvs(); } + }); +}); + + +describe("configured environment authority", () => { + it("keeps selected bootstrap values in the environment rather than argv", () => { + const environment = { PATH: "/bin", ...configuredEnvironmentProjection({ LANG: "configured-language-value" }) }; + const args = createIsolatedCodexAppServerArgs(environment); + expect(args.join("\n")).not.toContain("configured-language-value"); + expect(args.find(arg => arg.startsWith("shell_environment_policy.include_only="))).toContain("LANG"); + }); + + it("projects ordinary task credentials only when explicitly selected", () => { + const projected = configuredEnvironmentProjection({ DATABASE_URL: "task-db", CUSTOM_FLAG: "on", NODE_OPTIONS: "unsafe", PAPERCLIP_API_KEY: "controller" }); + expect(createSanitizedCodexEnvironment(projected)).toMatchObject({ DATABASE_URL: "task-db", CUSTOM_FLAG: "on" }); + expect(projected.NODE_OPTIONS).toBeUndefined(); + expect(projected.PAPERCLIP_API_KEY).toBeUndefined(); + }); + + it("does not accept an ambient projection in the provider or shell policy", () => { + vi.stubEnv(CONFIGURED_ENVIRONMENT_KEYS, JSON.stringify(["PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY"])); + vi.stubEnv("PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY", "ambient-secret"); + try { + expect(createSanitizedCodexEnvironment().PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY).toBeUndefined(); + expect(createIsolatedCodexAppServerArgs().join("\n")).not.toContain("PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY"); + } finally { vi.unstubAllEnvs(); } + }); + + it.each(["not-json", "[1]", '["NODE_OPTIONS"]', '["PAPERCLIP_API_KEY"]', '["PAPERCLIP_RUNNER_BOOTSTRAP_TICKET"]', '["OPENAI_API_KEY"]', '["LD_PRELOAD"]', '["bad=name"]', '["CUSTOM","CUSTOM"]', '["MISSING"]']) + ("rejects malformed or reserved projection %s", raw => { + expect(() => configuredEnvironment({ [CONFIGURED_ENVIRONMENT_KEYS]: raw })).toThrow("Invalid configured environment"); + }); + + it("rejects oversized and null-containing values without reporting their contents", () => { + for (const value of ["x".repeat(65_536), "secret\0suffix"]) { + expect(() => configuredEnvironmentProjection({ CUSTOM: value })).toThrow(/configured environment|Configured environment/); + } + }); + + it("preserves configured values through ACPX and OpenCode preparation", async () => { + const { createSanitizedAcpxSpawnInput } = await import("./drivers/acpx/environment.js"); + expect(createSanitizedAcpxSpawnInput(source, "codex").env).toMatchObject(pages); + expect(createCapabilityRunnerdProviderEnvironment({ provider: "opencode", options: { environment: source }, identity, codexHome: "/isolated/home", runtimeContextPath: "/isolated/context", hasRuntimeContext: false })).toMatchObject(pages); + }); +}); diff --git a/packages/paperclip-runner/src/configured-environment.ts b/packages/paperclip-runner/src/configured-environment.ts new file mode 100644 index 00000000000..bd10a7e7813 --- /dev/null +++ b/packages/paperclip-runner/src/configured-environment.ts @@ -0,0 +1,76 @@ +/** Names minted by the controller from the resolved task configuration. + * Values remain in the process environment, never in argv or this manifest. + * Do not mint this projection from ambient process.env. + */ +export const CONFIGURED_ENVIRONMENT_KEYS = "PAPERCLIP_CONFIGURED_ENV_KEYS"; + +export const GENERATED_RUNTIME_ENVIRONMENT_KEYS: ReadonlySet = new Set([ + CONFIGURED_ENVIRONMENT_KEYS, + "PAPERCLIP_AGENT_ID", "PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY", + "PAPERCLIP_API_KEY", "PAPERCLIP_API_URL", "PAPERCLIP_API_BRIDGE_MODE", "PAPERCLIP_COMPANY_ID", "PAPERCLIP_INSTANCE_ID", + "PAPERCLIP_RUN_ID", "PAPERCLIP_NORMALIZED_SESSION_ID", "PAPERCLIP_RUNNER_INSTANCE_ID", "PAPERCLIP_RUNNER_BOOTSTRAP_TICKET", "PAPERCLIP_TASK_ID", "PAPERCLIP_APPROVAL_ID", "PAPERCLIP_APPROVAL_STATUS", "PAPERCLIP_LINKED_ISSUE_IDS", + "PAPERCLIP_WAKE_REASON", "PAPERCLIP_WAKE_COMMENT_ID", "PAPERCLIP_WAKE_PAYLOAD_JSON", "PAPERCLIP_EXECUTION_MODE", + "PAPERCLIP_WORKSPACES_JSON", "PAPERCLIP_WORKSPACE_ID", "PAPERCLIP_WORKSPACE_CWD", "PAPERCLIP_WORKSPACE_SOURCE", + "PAPERCLIP_WORKSPACE_REPO_URL", "PAPERCLIP_WORKSPACE_REPO_REF", "PAPERCLIP_WORKSPACE_BRANCH", + "PAPERCLIP_WORKSPACE_WORKTREE_PATH", "PAPERCLIP_WORKSPACE_REALIZATION_MODE", "PAPERCLIP_WORKSPACE_AUTHORITATIVE_ROOT", + "PAPERCLIP_RUNTIME_PRIMARY_URL", "PAPERCLIP_RUNTIME_SERVICES_JSON", "PAPERCLIP_RUNTIME_SERVICE_INTENTS_JSON", + "PAPERCLIP_AGENT_MESSAGE_KEY", "PAPERCLIP_HARNESS_CHECKOUT_KEY", "PAPERCLIP_EXTERNAL_CHAT_EXECUTION_BOUND_KEY", + "PAPERCLIP_NATIVE_MCP_NAME", "PAPERCLIP_NATIVE_MCP_URL", "PAPERCLIP_NATIVE_MCP_TOKEN", "PAPERCLIP_AI_PROVIDER_KEY", + "PAPERCLIP_PROVIDER_TRACE_PATH", "PAPERCLIP_PROVIDER_TRACE_MAX_BYTES", "PAPERCLIP_ACPX_CREDENTIAL_BINDING", + "PAPERCLIP_RUNNER_NETWORK_ACCESS", "PAPERCLIP_RUNNER_NETWORK_ROOTS", "PAPERCLIP_RUNNER_EXTERNAL_SANDBOX", + "PAPERCLIP_GITHUB_AUTH_MODE", "PAPERCLIP_GITHUB_HOST_HOME", "PAPERCLIP_GIT_METADATA_ROOTS", + "PAPERCLIP_GITHUB_BROKER_TOKEN", "PAPERCLIP_GITHUB_BROKER_URL", "PAPERCLIP_GITHUB_BRIDGE_TOKEN", "PAPERCLIP_GITHUB_LAUNCHER_DIR", +]); + +const RESERVED_KEYS = new Set([ + "PATH", "HOME", "USERPROFILE", "CODEX_HOME", "AGENT_HOME", "SHELL", "NODE_OPTIONS", "NODE_PATH", + "PYTHONPATH", "PYTHONHOME", "RUBYOPT", "RUBYLIB", "PERL5OPT", "PERL5LIB", "BASH_ENV", "ENV", + "OPENAI_API_KEY", "CODEX_API_KEY", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", + "AWS_BEARER_TOKEN_BEDROCK", "OPENROUTER_API_KEY", "XAI_API_KEY", "CURSOR_API_KEY", "CURSOR_AUTH_TOKEN", + "COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN", "PAPERCLIP_GIT_TOKEN", +]); + +function eligibleKey(key: string): boolean { + const upper = key.toUpperCase(); + return /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(key) + && !GENERATED_RUNTIME_ENVIRONMENT_KEYS.has(upper) + && !RESERVED_KEYS.has(upper) + && !/^(?:LD_|DYLD_|GIT_CONFIG_|PAPERCLIP_(?:RUNNER_|NATIVE_|GITHUB_|ACPX_|VERIFIED_))/.test(upper); +} + +function checkedNames(names: unknown): string[] { + if (!Array.isArray(names) || names.length > 128 || names.some(name => typeof name !== "string" || !eligibleKey(name)) + || new Set(names).size !== names.length) throw new Error("Invalid configured environment projection"); + return (names as string[]).sort(); +} + +/** Mint at the server's resolved configuration boundary, before host inheritance. */ +export function configuredEnvironmentProjection(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const names = checkedNames(Object.keys(source).filter(key => source[key] !== undefined && eligibleKey(key))); + return configuredEnvironment({ ...source, [CONFIGURED_ENVIRONMENT_KEYS]: JSON.stringify(names) }); +} + +/** Accept only an explicitly supplied, controller-minted projection. */ +export function configuredEnvironment(source: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv { + const raw = source?.[CONFIGURED_ENVIRONMENT_KEYS]; + if (raw === undefined) return {}; + if (Buffer.byteLength(raw) > 20_000) throw new Error("Invalid configured environment projection"); + let names: string[]; + try { names = checkedNames(JSON.parse(raw)); } catch { throw new Error("Invalid configured environment projection"); } + const result: NodeJS.ProcessEnv = {}; + let bytes = 0; + for (const name of names) { + const value = source?.[name]; + if (typeof value !== "string" || value.includes("\0")) throw new Error("Invalid configured environment value"); + const size = Buffer.byteLength(name) + Buffer.byteLength(value); + bytes += size; + if (size > 65_536 || bytes > 262_144) throw new Error("Configured environment exceeds its bounded launch size"); + result[name] = value; + } + result[CONFIGURED_ENVIRONMENT_KEYS] = JSON.stringify(names); + return result; +} + +export function configuredEnvironmentKeys(source: NodeJS.ProcessEnv | undefined): string[] { + return Object.keys(configuredEnvironment(source)).filter(key => key !== CONFIGURED_ENVIRONMENT_KEYS).sort(); +} diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts index 4c4e20c73f3..27e8a2b1d05 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts @@ -1,3 +1,4 @@ +import { configuredEnvironment } from "../configured-environment.js"; import { spawn } from "node:child_process"; import { createCipheriv, @@ -3440,7 +3441,7 @@ function runnerEnvironment( if (explicitSource[key] !== undefined) environment[key] = explicitSource[key]; } } - Object.assign(environment, githubCredentialEnvironment(explicitSource)); + Object.assign(environment, githubCredentialEnvironment(explicitSource), configuredEnvironment(explicitSource)); } return environment; } diff --git a/packages/paperclip-runner/src/drivers/acpx/environment.ts b/packages/paperclip-runner/src/drivers/acpx/environment.ts index 2ecbf367474..069333204bf 100644 --- a/packages/paperclip-runner/src/drivers/acpx/environment.ts +++ b/packages/paperclip-runner/src/drivers/acpx/environment.ts @@ -1,3 +1,4 @@ +import { configuredEnvironment } from "../../configured-environment.js"; import type { QualifiedAcpxAgent } from "./qualified-profiles.js"; export const ACPX_CREDENTIAL_BINDING_ENV = "PAPERCLIP_ACPX_CREDENTIAL_BINDING"; @@ -87,7 +88,7 @@ export function createSanitizedAcpxSpawnInput( ): SanitizedAcpxSpawnInput { const source = environment ?? process.env; const candidate = isCandidate(agent); - const result: NodeJS.ProcessEnv = {}; + const result: NodeJS.ProcessEnv = configuredEnvironment(environment); const credentialNames = ACPX_CREDENTIAL_NAMES[agent]; const allowed = new Set([ "PATH", diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.test.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.test.ts index 53423467c92..fbe2ff00faa 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.test.ts @@ -1,3 +1,4 @@ +import { configuredEnvironmentProjection } from "../../configured-environment.js"; import { chmod, lstat, @@ -34,6 +35,22 @@ afterEach(async () => { }); describe("ACPX runtime sandbox", () => { + it.each([false, true])("allows selected task secrets in Codex shells (agent identity: %s)", async identity => { + const fixture = await sandboxFixture("codex"); + const pages = { PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY: "task-pages-secret", CUSTOM_TOKEN: "task-service-secret" }; + const sandbox = await prepareAcpxRuntimeSandbox({ binding: fixture.binding, agent: "codex", environment: { + PATH: process.env.PATH, OPENAI_API_KEY: "provider-secret", HOST_SECRET: "unselected-secret", + ...configuredEnvironmentProjection(pages), ...(identity ? { PAPERCLIP_AGENT_KEY_ID: "agent-key" } : {}), + } }); + const config = await readFile(join(sandbox.agentHomeDirectory, "config.toml"), "utf8"); + const keys = JSON.parse(config.split("\n").find(line => line.startsWith("include_only = "))?.slice("include_only = ".length) ?? "[]"); + expect(keys).toEqual(expect.arrayContaining(Object.keys(pages))); + expect(keys).not.toContain("OPENAI_API_KEY"); + expect(keys).not.toContain("HOST_SECRET"); + expect(sandbox.launchEnvironment).toMatchObject(pages); + for (const value of Object.values(pages)) expect(config).not.toContain(value); + }); + it("restores Grok permission controls on recovery without importing compatible hooks or credentials", async () => { const fixture = await sandboxFixture("grok"); const sandbox = await prepareAcpxRuntimeSandbox({ binding: fixture.binding, agent: "grok" }); diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts index 74c2e1c45a1..f38f174712d 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts @@ -1,3 +1,4 @@ +import { configuredEnvironmentKeys } from "../../configured-environment.js"; import { randomBytes } from "node:crypto"; import { constants, @@ -443,6 +444,7 @@ export async function prepareAcpxRuntimeSandbox(input: { })}\n`); } if (input.agent === "codex") { + const taskEnvironmentKeys = configuredEnvironmentKeys(input.environment); await writePrivateFile( join(agentHomeDirectory, "config.toml"), [ @@ -454,14 +456,15 @@ export async function prepareAcpxRuntimeSandbox(input: { // also affect provider startup and belongs at the launch boundary. "[features]", "shell_snapshot = false", - ...(input.environment?.PAPERCLIP_AGENT_KEY_ID ? [ + ...(input.environment?.PAPERCLIP_AGENT_KEY_ID || taskEnvironmentKeys.length > 0 ? [ "[shell_environment_policy]", 'inherit = "all"', "ignore_default_excludes = true", `include_only = ${JSON.stringify([...new Set([ "PATH", "HOME", "LANG", "LANGUAGE", "TZ", "TMPDIR", "TEMP", "TMP", "CODEX_HOME", "PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY", - // Provider/config secrets keep Codex's default shell exclusions; + ...taskEnvironmentKeys, + // Unselected provider/config secrets keep Codex's default shell exclusions; // only Paperclip's scoped API token is required by Bash/curl skills. - ...Object.keys(input.environment).filter(key => key === "PAPERCLIP_API_KEY" || !/key|secret|token/i.test(key)), + ...Object.keys(input.environment ?? {}).filter(key => key === "PAPERCLIP_API_KEY" || !/key|secret|token/i.test(key)), ])])}`, ] : []), "", diff --git a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts index 53ce851d113..5e6fac128da 100644 --- a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts +++ b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts @@ -1,3 +1,4 @@ +import { configuredEnvironment } from "../../configured-environment.js"; import type { NativeTurnControlCapabilities } from "../../contracts/types.js"; import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; import type { HarnessRuntimeRequestResolution } from "../../contracts/harness-driver.js"; @@ -243,7 +244,7 @@ export function createSanitizedCodexEnvironment( for (const key of ["PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY"]) { if (explicit?.[key] !== undefined) environment[key] = explicit[key]; } - Object.assign(environment, githubCredentialEnvironment(source)); + Object.assign(environment, githubCredentialEnvironment(source), configuredEnvironment(explicit)); return environment; } diff --git a/packages/paperclip-runner/src/drivers/codex/codex-security-config.ts b/packages/paperclip-runner/src/drivers/codex/codex-security-config.ts index 3cc702004c2..f363bd8163b 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-security-config.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-security-config.ts @@ -1,3 +1,4 @@ +import { configuredEnvironmentKeys } from "../../configured-environment.js"; import { resolve, isAbsolute, join, dirname, delimiter } from "node:path"; import { existsSync, realpathSync, readFileSync, statSync } from "node:fs"; import { createRequire } from "node:module"; @@ -167,23 +168,28 @@ function tomlString(value: string): string { } export function createIsolatedCodexAppServerArgs( - source: NodeJS.ProcessEnv = process.env, + source: NodeJS.ProcessEnv | undefined = undefined, readOnlyRoots: string[] = [], /** Server-registered run copy, never an environment/config-supplied root. */ instructionWorkingCopyRoot?: string, ): string[] { + const explicitSource = source; + source ??= process.env; const gitRoots = gitFilesystemRoots(source); readOnlyRoots = [...new Set([...readOnlyRoots, ...codexNetworkReadOnlyRoots(source)])]; const networkAccess = codexNetworkAccess(source); const externalRunnerSandbox = usesExternalRunnerSandbox(source); const inheritedGitHubKeys = [ ...githubCredentialEnvironmentKeys(source), + ...configuredEnvironmentKeys(explicitSource), ...["PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY"].filter(key => source[key] !== undefined), ]; const hasProjectedEnvironment = inheritedGitHubKeys.length > 0; // Codex filters the configured `set` values through include_only as well. // Retain the explicit command PATH/HOME/locale settings, not ambient secrets. const commandEnvironment = codexCommandEnvironment(source); + // Selected task values are inherited, never serialized into configuration argv. + for (const key of configuredEnvironmentKeys(explicitSource)) delete commandEnvironment[key]; if (instructionWorkingCopyRoot && source.AGENT_HOME === instructionWorkingCopyRoot) commandEnvironment.AGENT_HOME = instructionWorkingCopyRoot; const shellEnvironmentKeys = [...new Set([...inheritedGitHubKeys, ...Object.keys(commandEnvironment)])].sort(); if (source.PAPERCLIP_GITHUB_LAUNCHER_DIR) readOnlyRoots = [...readOnlyRoots, source.PAPERCLIP_GITHUB_LAUNCHER_DIR]; diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.ts index fb89bc147b8..ba50467357b 100644 --- a/packages/paperclip-runner/src/index.ts +++ b/packages/paperclip-runner/src/index.ts @@ -1,3 +1,4 @@ +export * from "./configured-environment.js"; export * from "./catalog/index.js"; export { CURSOR_DISTRIBUTION_PINS } from "./drivers/acpx/generated-profiles.js"; export * from "./contracts/control-plane-port.js"; diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 5b92af0a3ee..ba6f3f32487 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -1,3 +1,4 @@ +import { configuredEnvironment } from "../configured-environment.js"; import { resolveAcpxProviderMode } from "../drivers/acpx/provider-mode.js"; import { isAcpxCanonicalInputMethod } from "../drivers/acpx/profile-extensions.js"; import { RunnerdTraceFrameIndex } from "./runnerd-trace-frame-index.js"; @@ -3339,14 +3340,14 @@ function createSanitizedOpenCodeRunnerEnvironment( delete candidate[key]; if (source?.[key] !== undefined) candidate[key] = source[key]; } - return Object.fromEntries( + return { ...configuredEnvironment(source), ...Object.fromEntries( Object.entries(candidate).filter( ([key, value]) => typeof value === "string" && (OPEN_CODE_RUNNER_ENVIRONMENT_KEYS.has(key) || /^LC_[A-Z0-9_]{1,32}$/.test(key)), ), - ); + ) }; } export function resolveSourceCodexHome( diff --git a/server/src/__tests__/effective-run-config-fingerprints.test.ts b/server/src/__tests__/effective-run-config-fingerprints.test.ts index 02afa38a4c4..aceed12fd7d 100644 --- a/server/src/__tests__/effective-run-config-fingerprints.test.ts +++ b/server/src/__tests__/effective-run-config-fingerprints.test.ts @@ -3,6 +3,7 @@ import { canonicalizeEffectiveRunConfigCategory, createEffectiveRunConfigFingerprints, diffEffectiveRunConfigFingerprints, + type EffectiveRunConfigSecretManifestEntry, } from "../services/effective-run-config-fingerprints.ts"; describe("effective run config fingerprints", () => { @@ -301,3 +302,29 @@ describe("effective run config fingerprints", () => { }); }); }); + + +describe("configured Paperclip environment freshness", () => { + const fingerprint = (env: Record, secretManifest?: EffectiveRunConfigSecretManifestEntry[]) => + createEffectiveRunConfigFingerprints({ session: { env }, secretManifest }).sessionFingerprint; + + it("detects additions, changes, and removals without recording values", () => { + const absent = fingerprint({}); + const first = fingerprint({ PAPERCLIP_PAGE_BUCKET: "first-bucket" }); + const changed = fingerprint({ PAPERCLIP_PAGE_BUCKET: "second-bucket" }); + expect(first.fingerprint).not.toBe(absent.fingerprint); + expect(changed.fingerprint).not.toBe(first.fingerprint); + expect(fingerprint({}).fingerprint).toBe(absent.fingerprint); + expect(first.canonicalJson).not.toContain("first-bucket"); + for (const key of ["PAPERCLIP_RUN_ID", "PAPERCLIP_RUNNER_EXTERNAL_SANDBOX", "PAPERCLIP_NORMALIZED_SESSION_ID"]) { + expect(fingerprint({ [key]: "first" }).fingerprint).toBe(fingerprint({ [key]: "second" }).fingerprint); + } + }); + + it("detects custom namespaced secret version changes", () => { + const env = { PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY: { type: "secret_ref", secretId: "pages-key" } }; + const manifest = (version: number) => [{ configPath: "env.PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY", envKey: "PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY", secretId: "pages-key", version }]; + expect(fingerprint(env, manifest(1)).fingerprint).not.toBe(fingerprint(env, manifest(2)).fingerprint); + expect(fingerprint(env, manifest(1)).canonicalJson).toContain("pages-key"); + }); +}); diff --git a/server/src/__tests__/heartbeat-project-env.test.ts b/server/src/__tests__/heartbeat-project-env.test.ts index b14ba118ae4..fe200aa1dd9 100644 --- a/server/src/__tests__/heartbeat-project-env.test.ts +++ b/server/src/__tests__/heartbeat-project-env.test.ts @@ -21,6 +21,45 @@ import type { AuthorizationActor, AuthorizationDecision } from "../services/auth import { resolveManagedProjectWorkspaceDir } from "../home-paths.ts"; describe("resolveExecutionRunAdapterConfig", () => { + it.each(["many variables", "large value"])("keeps legacy adapter configuration compatible with %s", async kind => { + const env = kind === "many variables" + ? Object.fromEntries(Array.from({ length: 129 }, (_, index) => [`CUSTOM_${index}`, "value"])) + : { CUSTOM_VALUE: "x".repeat(65_536) }; + const result = await resolveExecutionRunAdapterConfig({ companyId: "company-1", adapterType: "process", executionRunConfig: { env }, secretsSvc: { + resolveAdapterConfigForRuntime: vi.fn(async (_companyId, config) => ({ config, secretKeys: new Set(), manifest: [] })), + } as any }); + expect(result.resolvedConfig.env).toEqual(env); + }); + + it("captures scoped resolved task values and rejects configured markers", async () => { + const key = "PAPERCLIP_CONFIGURED_ENV_KEYS"; + const secret = { type: "secret_ref", secretId: "pages-secret" }; + const result = await resolveExecutionRunAdapterConfig({ + companyId: "company-1", agentId: "agent-1", environmentId: "environment-1", projectId: "project-1", routineId: "routine-1", + executionRunConfig: { env: { PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY: secret, SHARED: "agent", [key]: '["HOST_SECRET"]' } }, + environmentEnv: { SHARED: "environment", [key]: '["HOST_SECRET"]' }, + projectEnv: { SHARED: "project", [key]: '["HOST_SECRET"]' }, + routineEnv: { SHARED: "routine", [key]: '["HOST_SECRET"]' }, + secretsSvc: { + resolveAdapterConfigForRuntime: vi.fn(async (companyId, config) => { + expect(companyId).toBe("company-1"); + expect(config.env[key]).toBeUndefined(); + return { config: { ...config, env: { ...config.env, PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY: "resolved-task-secret" } }, secretKeys: new Set(["PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY"]), manifest: [] }; + }), + resolveEnvBindings: vi.fn(async (companyId, env) => { + expect(companyId).toBe("company-1"); + expect(env[key]).toBeUndefined(); + return { env, secretKeys: new Set(), manifest: [] }; + }), + } as any, + }); + expect(result.configuredTaskEnvironment).toEqual({ + PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY: "resolved-task-secret", SHARED: "routine", + }); + expect(result.resolvedConfig.env).not.toHaveProperty(key); + expect(result.configuredTaskEnvironment).not.toHaveProperty(key); + }); + it("does not preflight or resolve legacy GitHub token bindings for managed executions", async () => { const assertNoGitHubBinding = (env: Record) => { for (const key of Object.keys(env)) if (/^(GH_TOKEN|GITHUB_TOKEN|GH_ENTERPRISE_TOKEN|GITHUB_ENTERPRISE_TOKEN|PAPERCLIP_GIT_TOKEN)$/.test(key)) { diff --git a/server/src/services/effective-run-config-fingerprints.ts b/server/src/services/effective-run-config-fingerprints.ts index 3dd19c17822..1438d7939fe 100644 --- a/server/src/services/effective-run-config-fingerprints.ts +++ b/server/src/services/effective-run-config-fingerprints.ts @@ -1,3 +1,4 @@ +import { GENERATED_RUNTIME_ENVIRONMENT_KEYS } from "../vendor/paperclip-runner/index.js"; import { createHash } from "node:crypto"; import type { RuntimeSecretManifestEntry } from "./secrets.js"; @@ -66,7 +67,6 @@ export interface EffectiveRunConfigFingerprintDiff { const OMIT = Symbol("omit-from-effective-run-config-fingerprint"); const REDACTED_VALUE: EffectiveRunConfigCanonicalValue = { type: "redacted", present: true }; -const GENERATED_RUNTIME_ENV_KEY_RE = /^PAPERCLIP_/; const SENSITIVE_CONFIG_KEY_RE = /(?:api[_-]?key|access[_-]?token|auth(?:orization)?|bearer|cookie|credential|jwt|password|passwd|private[_-]?key|secret|token)$/i; const VOLATILE_CONFIG_KEYS = new Set([ @@ -276,7 +276,7 @@ function canonicalizeEnvRecord( if (!isPlainObject(envValue)) return {}; const canonicalEnv: Record = {}; for (const key of Object.keys(envValue).sort()) { - if (GENERATED_RUNTIME_ENV_KEY_RE.test(key)) continue; + if (GENERATED_RUNTIME_ENVIRONMENT_KEYS.has(key)) continue; const manifestEntry = context.secrets.byConfigPath.get(`env.${key}`) ?? context.secrets.byEnvKey.get(key); if (manifestEntry) { canonicalEnv[key] = canonicalSecretMetadata(manifestEntry); diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index f406b9de39f..744f1ec293c 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -1,3 +1,4 @@ +import { CONFIGURED_ENVIRONMENT_KEYS, configuredEnvironmentProjection } from "../vendor/paperclip-runner/index.js"; import { activeIssueInteractionCondition, TASK_QUESTION_GUIDANCE } from "./issue-question-context.js"; import { createAgentIdentityRedactor } from "./agent-identity-redaction.js"; import { agentIdentityService, supportsManagedAgentIdentity } from "./agent-identity.js"; @@ -1495,6 +1496,7 @@ const LOW_TRUST_SENSITIVE_ENV_KEY_RE = // 3. Any other PAPERCLIP_*-named binding is user data and flows through to // the run env like any non-prefixed binding. const FORBIDDEN_ENV_BINDING_KEYS = new Set([ + CONFIGURED_ENVIRONMENT_KEYS, "PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY", "PAPERCLIP_RUNNER_NETWORK_ACCESS", "PAPERCLIP_RUNNER_NETWORK_ROOTS", @@ -1950,6 +1952,11 @@ export async function resolveExecutionRunAdapterConfig(input: { } return { resolvedConfig, + // Capture resolved task values before provider credential injection or host + // inheritance. Native-only launch limits are checked at native dispatch. + configuredTaskEnvironment: Object.fromEntries( + Object.entries(parseObject(resolvedConfig.env)).filter((entry): entry is [string, string] => typeof entry[1] === "string"), + ), secretKeys, secretManifest: [ ...(environmentEnvResolution.manifest ?? []), @@ -21794,7 +21801,7 @@ export function heartbeatService( selectedEnvironmentForConfig?.driver ?? "local", ); - const { resolvedConfig, secretKeys, secretManifest } = + const { resolvedConfig, configuredTaskEnvironment, secretKeys, secretManifest } = await resolveExecutionRunAdapterConfig({ managedAiCredentials: Boolean(aiBinding), managedGitHubCredentials: !useHostGitHub, @@ -24991,6 +24998,7 @@ export function heartbeatService( managedAiCredentialIdentity: managedAiRuntime?.identity, managedAiCredentialHome: managedAiRuntime ? String((managedAiRuntime.config.env as Record).CODEX_HOME) : undefined, runnerEnvironment: { + ...configuredEnvironmentProjection(configuredTaskEnvironment), ...buildNativeProviderEnvironment( adapterEnv, process.env, diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index ed6f95e1e65..ba758de838b 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -1,3 +1,4 @@ +import { configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { readFileSync } from "node:fs"; import { PgDialect } from "drizzle-orm/pg-core"; @@ -6325,6 +6326,42 @@ describe("native session same-turn steering", () => { }); describe("native warm session supervision", () => { + it.each([ + { change: "addition", before: {}, after: { CUSTOM_TOKEN: "first" }, replaced: true }, + { change: "rotation", before: { CUSTOM_TOKEN: "first" }, after: { CUSTOM_TOKEN: "second" }, replaced: true }, + { change: "removal", before: { CUSTOM_TOKEN: "first" }, after: {}, replaced: true }, + { change: "unchanged values", before: { CUSTOM_TOKEN: "first", FLAG: "on" }, after: { FLAG: "on", CUSTOM_TOKEN: "first" }, replaced: false }, + ])("applies configured environment $change on the next warm turn", async ({ change, before, after, replaced }) => { + const name = `warm-task-env-${change}`; + const current = { ...execution, + binding: { ...execution.binding, runId: `${name}-one`, executionWorkspaceId: name }, + session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 20 } }, + } as NativeExecutionInputV1; + const first = { close: vi.fn(async () => undefined) }; + const second = { close: vi.fn(async () => undefined) }; + const result = { result: { summary: "done" }, terminal: { runTerminalState: "succeeded" }, + turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", + nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + state.execute.mockReset() + .mockImplementationOnce(async options => { await options.onSession?.(first); return result; }) + .mockImplementationOnce(async options => { + expect(options.existingSession).toBe(replaced ? undefined : first); + await options.onSession?.(replaced ? second : first); + return result; + }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name, + runnerEnvironment: configuredEnvironmentProjection(before) }); + const next = { ...current, binding: { ...current.binding, runId: `${name}-two` } }; + await executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: name, + runnerEnvironment: configuredEnvironmentProjection(after) }); + expect(first.close).toHaveBeenCalledTimes(replaced ? 1 : 0); + if (replaced) expect(first.close).toHaveBeenCalledWith({ reason: "warm native session configuration changed" }); + await vi.advanceTimersByTimeAsync(20); + } finally { vi.useRealTimers(); } + }); + it.each([ { runTerminalState: "failed", managedFiles: true }, { runTerminalState: "cancelled", managedFiles: true }, diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index d4dec4ee160..b815f976d2e 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -1,3 +1,4 @@ +import { configuredEnvironment } from "../../vendor/paperclip-runner/index.js"; import { CURSOR_DISTRIBUTION_PINS, QUALIFIED_ACPX_PROFILES, QUALIFIED_ACPX_VERSION } from "../../vendor/paperclip-runner/index.js"; import { isProviderMode } from "../../vendor/paperclip-runner/index.js"; import { bundledRemoteProviderPackManifestPath, bundledRemoteRunnerBinary } from "../../vendor/paperclip-runner/index.js"; @@ -413,6 +414,7 @@ type WarmNativeSession = { session: NativeSession; ownerToken: symbol; configDigest: string; + configuredEnvironmentDigest: string; ownerScope: string; companyId: string; environmentId: string | null; @@ -8268,6 +8270,9 @@ async function executePaperclipNativeSessionWithinScope( input.runnerExecutionTarget?.kind ?? "local", ) : null; + const configuredEnvironmentDigest = createHash("sha256") + .update(JSON.stringify(configuredEnvironment(input.runnerEnvironment))) + .digest("hex"); const warmSessionOwnerToken = Symbol( `native-warm-session:${input.execution.binding.runId}`, ); @@ -8294,6 +8299,7 @@ async function executePaperclipNativeSessionWithinScope( input.refreshTools === true || entry.closeOnReleaseReason !== undefined || entry.configDigest !== warmConfigDigest || + entry.configuredEnvironmentDigest !== configuredEnvironmentDigest || entry.instructionCopy?.root !== input.instructionWorkingCopy?.root || entry.managedAiCredentialIdentity !== input.managedAiCredentialIdentity || credentialRunChanged || @@ -8674,6 +8680,7 @@ async function executePaperclipNativeSessionWithinScope( session, ownerToken: warmSessionOwnerToken, configDigest: warmConfigDigest, + configuredEnvironmentDigest, ownerScope: nativeSessionOwnerScope( input.execution, input.runnerExecutionTarget?.environmentId ?? null, ), diff --git a/server/src/vendor/paperclip-runner/index.ts b/server/src/vendor/paperclip-runner/index.ts index 8d76d47ca82..2c603f543cc 100644 --- a/server/src/vendor/paperclip-runner/index.ts +++ b/server/src/vendor/paperclip-runner/index.ts @@ -139,3 +139,8 @@ export const completeTerminatedLocalNativeSessionCleanup = runner.completeTermin export const bundledRemoteProviderPackManifestPath = runner.bundledRemoteProviderPackManifestPath; export const bundledRemoteRunnerBinary = runner.bundledRemoteRunnerBinary; + +export const CONFIGURED_ENVIRONMENT_KEYS = runner.CONFIGURED_ENVIRONMENT_KEYS; +export const GENERATED_RUNTIME_ENVIRONMENT_KEYS = runner.GENERATED_RUNTIME_ENVIRONMENT_KEYS; +export const configuredEnvironmentProjection = runner.configuredEnvironmentProjection; +export const configuredEnvironment = runner.configuredEnvironment;