diff --git a/docs/ADRs/0136-runner-secrets-through-one-stored-secret.md b/docs/ADRs/0136-runner-secrets-through-one-stored-secret.md index 8ff63b0a0a..e9724998a8 100644 --- a/docs/ADRs/0136-runner-secrets-through-one-stored-secret.md +++ b/docs/ADRs/0136-runner-secrets-through-one-stored-secret.md @@ -18,6 +18,11 @@ Date: 2026-10-07 Accepted +*Amended by [ADR 0145](0145-keep-credential-deny-list-out-of-runner-secret-refusal.md), +which keeps the credential deny-list that #3373 adds to the `env.sandbox` gate +out of the refused-names rule below, matches that rule case-insensitively, and +adds the `DYLD_*` family to the refused prefixes.* + ## Context A custom harness's `pre_script`, `post_script` and `validation_loop` read diff --git a/docs/ADRs/0145-keep-credential-deny-list-out-of-runner-secret-refusal.md b/docs/ADRs/0145-keep-credential-deny-list-out-of-runner-secret-refusal.md new file mode 100644 index 0000000000..adc5496012 --- /dev/null +++ b/docs/ADRs/0145-keep-credential-deny-list-out-of-runner-secret-refusal.md @@ -0,0 +1,69 @@ +--- +title: "145. Keep the credential deny-list out of the runner-secret refusal" +status: Accepted +relates_to: + - agent-infrastructure + - security-threat-model +topics: + - harness + - secrets + - github-actions +--- + +# 145. Keep the credential deny-list out of the runner-secret refusal + +Date: 2026-10-19 + +Amends: [ADR 0136](0136-runner-secrets-through-one-stored-secret.md) + +## Status + +Accepted + +## Context + +[ADR 0136](0136-runner-secrets-through-one-stored-secret.md) refuses some +names as runner-secret bundle keys, and its refusal reads the sandbox +reserved set (`reservedSandboxKeys`). #3373 makes `env.sandbox` also refuse +the credential-class deny-list: proxy, TLS-trust, Git, interpreter, loader +and shell-behavior names. + +Those names are legitimate host-side. `pre_script` and `post_script` need +proxy and TLS settings to reach internal networks, and the sandbox child +never sees a runner-secret value. If the deny-list were merged into +`reservedSandboxKeys`, a bundle carrying, for example, `HTTPS_PROXY` would +fail validation and stop every run that uses it. + +The refusal also has two gaps. It matched exact case, so a lowercase key +such as `path` passed, although the `env.sandbox` gate matches +case-insensitively. It refused `LD_*` but not the macOS dynamic-linker family +`DYLD_*`, which the plugin-env door already refuses. + +## Decision + +This ADR settles the runner-secret refusal's name set once `env.sandbox` +refuses the credential deny-list: it does not read the deny-list, it matches +case-insensitively, and it refuses the `DYLD_*` family. The second and third +close gaps in that set rather than open a separate decision. + +The `env.sandbox` gate checks the credential deny-list beside +`reservedSandboxKeys`; the deny-list is not merged into that map. The +runner-secret refusal keeps reading `reservedSandboxKeys` and does not +consult the deny-list. It also refuses the OIDC and provider-only keys, the +minted role tokens and workflow-set names refused since ADR 0136, and the +runner-owned prefixes, now including `DYLD_*`. Both doors match +case-insensitively. A credential-class name that is not also in +`reservedSandboxKeys` or under a refused prefix is refused at the +`env.sandbox` door and accepted as a runner-secret key. + +## Consequences + +- The deny-list can widen without breaking runs whose bundles carry + host-side settings. +- Both doors read `reservedSandboxKeys`, so a runner-infrastructure name + added there is refused at both with no second list to keep in sync. +- Proxy, TLS-trust and Git settings stay available to host-side scripts + through runner secrets. +- ADR 0136's refused names stay refused, now with their case variants and + the `DYLD_*` family, so a bundle key such as `path` or `github_token` fails + validation. diff --git a/docs/architecture.md b/docs/architecture.md index 3771badef3..6385073a0b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -149,6 +149,9 @@ repo baseline and overrides) `runtime.forge` or `config` (interim until ADR 0112's guarded-field check). GitLab is unchanged: one masked CI/CD variable per secret, none of these rules ([ADR 0136](ADRs/0136-runner-secrets-through-one-stored-secret.md)). + The refusal does not consult the credential deny-list that the + `env.sandbox` gate also checks + ([ADR 0145](ADRs/0145-keep-credential-deny-list-out-of-runner-secret-refusal.md)). - Agent configuration env vars: behavioral knobs use `{AGENT}_{SETTING_NAME}` naming (e.g., `REVIEW_SEVERITY_THRESHOLD`), delivered via `env.runner` and `env.sandbox` in the harness YAML. Each agent documents its config vars in diff --git a/docs/cli/README.md b/docs/cli/README.md index 1ebee635e8..f2fcd89adb 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -26,7 +26,7 @@ Download the latest binary from [GitHub Releases](https://github.com/fullsend-ai |---------|-------------| | [`fullsend run`](run.md) | Execute an agent locally in a sandbox. See [running agents locally](../guides/user/running-agents-locally.md). | | `fullsend poll` | Discover forge events and dispatch agent pipelines. `--forge gitlab` runs the cron poller ([ADR 0067](../ADRs/0067-gitlab-cron-polling-event-dispatch.md)); events-mode polling also recovers issue opens whose webhook delivery was missed. `--input-driver jira-poll` polls Jira (see [Jira integration](../guides/user/jira-integration.md)). `--input-driver gitlab-webhook` is the GitLab dispatcher job's webhook fast-path ([ADR 0125](../ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md)). It reads the native webhook body from the file-type `TRIGGER_PAYLOAD` variable, re-validates it against the GitLab API, and creates each routed stage's pipeline (typed inputs, `FULLSEND_DISPATCH_SECRET` HMAC) with the poller-role credential (the `api` route, the default). Scheduled cron polling and the webhook fast path run as the trigger-only service account: once its dispatch activation is recorded, the managed webhook carries the account's pipeline trigger token ([#8509](https://github.com/fullsend-ai/fullsend/issues/8509)), the scaffold sets `FULLSEND_GITLAB_DISPATCH_ROUTE=child-pipeline`, and the command instead starts each pipeline with the job's own `CI_JOB_TOKEN` through the pipeline trigger API (`source=pipeline`); an unknown route, or `child-pipeline` without `CI_JOB_TOKEN`, fails closed. `fullsend poll --forge gitlab --print-dispatch-routes` prints the routes the CLI supports (`api` and `child-pipeline`) and exits; the scaffold runs it before selecting `child-pipeline`, and a CLI that predates the route rejects the flag, so the job stops before any dispatch. It requires `--project`, which has no `CI_PROJECT_PATH` fallback. It deduplicates against the poller's per-mode state on the `fullsend-poll-state-slash` and `fullsend-poll-state-events` branches, so an event the webhook dispatched is not dispatched again by the poller, and the reverse. Shared poller state is occurrence-aware (label additions are keyed on the resource label event ID, dispatched keys are retained for the webhook freshness window, and a failed label dispatch is handed back to the poller as a pending retry); legacy persisted keys keep working. Older pollers do not recognise the new label keys, so before a rollback or mixed-version run, follow the [ADR 0132](../ADRs/0132-occurrence-aware-shared-poller-state.md) guidance to drain in-flight poll jobs or pin every poller to one version. | -| `fullsend lock [agent-name]` | Pin remote dependencies to `lock.yaml` | +| `fullsend lock [agent-name]` | Pin remote dependencies to `lock.yaml`. When it composes a harness (a new or stale entry, or `--update`), it also prints the harness diagnostics, including [reserved `env.sandbox` keys](run.md#reserved-envsandbox-keys). A current entry is not composed, so its keys are not checked, and `lock` composes without event context, so keys from event-guarded overlays are reported only by `fullsend run`. | | `fullsend scan` | Run security scanners on agent input/output | | `fullsend eval-measure` | Score wild-run traces into `eval-measurements.jsonl`. See [Eval measurements](../guides/infrastructure/eval-measurements.md). | diff --git a/docs/cli/run.md b/docs/cli/run.md index e37edf757f..163a4c8ce2 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -293,7 +293,8 @@ For comparison: - Child processes inherit both variables. In a pi sub-agent read the deadline, not the budget: the deadline is the same wall-clock limit the parent has, while `FULLSEND_TIMEOUT_MINUTES` is the parent iteration's whole budget, not the time the child has left. -- Both names are reserved: an `env.sandbox` entry with either name is dropped. Pre-, post- and +- Both names are reserved: an `env.sandbox` entry with either name is dropped + (see [Reserved `env.sandbox` keys](#reserved-envsandbox-keys)). Pre-, post- and validation scripts run on the host and do not see them. **Pacing from a skill.** Read the deadline, not the budget, and keep the arithmetic in two steps — @@ -454,6 +455,26 @@ receives one only when the harness declares it under `env.runner`; see Repo-level setup (provider, profile, `~/.npmrc`, code/fix overlays): [Private registries and GitHub Packages](../guides/user/customizing-agents.md#private-registries-and-github-packages). +## Reserved `env.sandbox` keys + +`fullsend run` drops reserved names from `env.sandbox` instead of exporting +them into the sandbox. Matching is case-insensitive. It warns twice: + +- When the harness loads, one warning names every reserved key: + `N env.sandbox key(s) are reserved and will be dropped instead of exported into the sandbox: ...` +- As it writes the sandbox environment, one stderr line per key: + `WARNING: env.sandbox key "NAME" is reserved (runner infrastructure or security deny-list); skipping` + +`fullsend lock` prints the load-time warning when it composes a harness. A +current lock entry is not composed; run `fullsend lock --update` to check its +keys. `lock` composes without event context, so a key added by an overlay +guarded on `event` is reported only by `fullsend run`. The reserved names are +listed in the `env.sandbox` note in [Customizing +agents](../guides/user/customizing-agents.md#reserved-envsandbox-names); +where blocked proxy and certificate settings go instead is in [Migrating proxy +and certificate +settings](../guides/user/customizing-agents.md#migrating-proxy-and-certificate-settings). + ## Runner secrets `fullsend run` reads a JSON object of name → value for host-side scripts diff --git a/docs/guides/getting-started/operations.md b/docs/guides/getting-started/operations.md index b4f8f4a565..0de7b9c193 100644 --- a/docs/guides/getting-started/operations.md +++ b/docs/guides/getting-started/operations.md @@ -299,7 +299,7 @@ Local `fullsend poll` / `fullsend run --forge gitlab` against a private-CA insta ### Sandbox hosts -OpenShell sandboxes do **not** inherit `CI_SERVER_TLS_CA_FILE`. That path is job-local and must not be treated as available inside the sandbox or on a remote gateway host. Agent-controlled TLS environment overrides (`SSL_CERT_FILE`, `SSL_CERT_DIR`, `CURL_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS`) stay blocked. +OpenShell sandboxes do **not** inherit `CI_SERVER_TLS_CA_FILE`. That path is job-local and must not be treated as available inside the sandbox or on a remote gateway host. Agent-controlled TLS environment overrides (`SSL_CERT_FILE`, `SSL_CERT_DIR`, `CURL_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS`) stay blocked; see [Migrating proxy and certificate settings](../user/customizing-agents.md#migrating-proxy-and-certificate-settings) for where those settings go instead. The OpenShell supervisor reads a fixed list of system CA paths in the sandbox container to build upstream trust (GitLab, registries, inference) and the bundle handed to sandboxed processes. Administrators provision that trust on the **sandbox host**, independently of the job container: diff --git a/docs/guides/user/customizing-agents.md b/docs/guides/user/customizing-agents.md index 075c12d0f3..fbbfc08e80 100644 --- a/docs/guides/user/customizing-agents.md +++ b/docs/guides/user/customizing-agents.md @@ -450,8 +450,143 @@ and other lines that are not plain assignments) are skipped with a warning. these files like `pre_script`. `host_files` can also place configuration that tools load, such as git config or shell rc files; that is trusted like `pre_script` too. -**Note**: `env.sandbox` cannot modify `PATH`, the harness ignores special -variables to protect sandbox operation. +#### Reserved `env.sandbox` names + +**Note**: `env.sandbox` cannot modify runner infrastructure or security +settings through the reserved names below. The runner drops these names +before writing the sandbox environment, case-insensitively: + +- **Runner infrastructure and process-loading safeguards:** `PATH`, `HOME`, + `SHELL`, `BASH_ENV`, `ENV`, `LD_PRELOAD`, `LD_LIBRARY_PATH`, `TRACEPARENT`, + and every `FULLSEND_*` variable the runner itself exports into the sandbox + (its output and fetch plumbing, the repository path, role and slug, the + iteration budget and deadline, and its own `PATH` entry). The set grows + with the runner; the warnings described below name any such key a harness + sets. +- **Credentials it mints or receives:** `FULLSEND_GCP_OIDC_AUTH_FILE`, + `FULLSEND_TRIGGER_TOKEN`, `FULLSEND_GITLAB_TRIGGER_ACCOUNT_TOKEN`, + `FULLSEND_WEBHOOK_SECRET`, `FULLSEND_INFERENCE_GATEWAY_API_KEY`, + `FULLSEND_OPENAI_API_KEY`, `OPENAI_API_KEY`, `GH_WORKFLOW_TOKEN`, the + runner-secret bundle and its staging path (`FULLSEND_GITHUB_RUNNER_SECRETS`, + `FULLSEND_GITHUB_RUNNER_SECRETS_FILE`), and the GitHub Actions OpenID Connect + (OIDC) request pair `ACTIONS_ID_TOKEN_REQUEST_URL` / + `ACTIONS_ID_TOKEN_REQUEST_TOKEN`. The runner uses this pair to request a + token proving the job's identity. +- **Non-secret, runner-only inputs that select those credentials:** + `FULLSEND_GCP_OIDC_URL`, `FULLSEND_GCP_PROJECT_ID`, + `FULLSEND_GCP_WIF_PROVIDER`, `FULLSEND_OPENAI_AUDIENCE`, + `FULLSEND_OPENAI_IDENTITY_PROVIDER_ID`, + `FULLSEND_OPENAI_SERVICE_ACCOUNT_ID`. +- **Security-sensitive names also refused in URL-sourced provider credential + definitions:** proxy settings (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`, + `ALL_PROXY`), Transport Layer Security (TLS) trust settings that select + certificates for verifying encrypted connections (`SSL_CERT_FILE`, + `SSL_CERT_DIR`, `CURL_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS`), git configuration + (`GIT_SSH_COMMAND`, `GIT_CONFIG_GLOBAL`, `GIT_EXEC_PATH`, `GIT_ASKPASS`, + `GIT_TEMPLATE_DIR`), interpreter injection (`NODE_OPTIONS`, `PYTHONPATH`, + `PYTHONSTARTUP`, `JAVA_TOOL_OPTIONS`, `RUBYOPT`, `PERL5OPT`), + dynamic-linker hooks (`LD_AUDIT`, `DYLD_INSERT_LIBRARIES`), shell behavior + (`IFS`, `CDPATH`, `PROMPT_COMMAND`) and the resolver alias file + (`HOSTALIASES`). + +The list is by name, not by namespace: harness-supplied hook inputs such as +`FULLSEND_CANARY_TOKEN` and `FULLSEND_TOOL_ALLOWLIST` are still delivered +through `env.sandbox` — see +[Runtime Implementation](../../contributing/runtime-implementation.md). +Matching is case-insensitive, so `https_proxy` is dropped exactly as +`HTTPS_PROXY` is. + +This deny-list covers selected names, not every variable that can affect +network routing, certificate trust, Git or interpreter behavior. An unlisted +name is not necessarily safe. + +`fullsend run` warns when the harness loads, naming all reserved keys it will +drop, and warns again on stderr for each key as it writes the sandbox +environment. To check the harness without starting an agent: + +1. Run `fullsend lock `. It reports the same lint warning when it + loads and composes the harness. Locking may fetch dependencies and write the + lock file. If the entry is already current, it skips composition and does + not check the keys. `lock` composes without event context, so a key added + by an overlay guarded on `event` is reported only by `fullsend run`. +2. Run `fullsend lock --update` (or + `fullsend lock --all --update`) to check the composed harness when the entry + is current. This forces dependency re-resolution and may change the lock + file; it is not a diagnostics-only operation. + +No key-specific warning on a cache hit means the keys were not checked, not +that they are allowed. + +A key must start with an ASCII letter or underscore, followed only by ASCII +letters, digits or underscores. `fullsend run` skips invalid names and warns +on stderr; this separate identifier check is not reported by `fullsend lock`. +Dropping a key removes that one `env.sandbox` export; it does not unset a value +that reaches the sandbox another way, as `host_files` `.env.d` does. + +This gate covers `env.sandbox` only. `host_files` `.env.d` files are read +before the runtime starts: every launch and the runner's in-sandbox probes +read them as data and take only assignment lines, and never take the +dynamic-loader, interpreter and shell-startup variables that the +[`.env.d` host files](../../reference/harness-reference.md#field-details) +entry in the harness reference lists. `.env` itself is still valid shell that +an agent may source, so keep treating these files like `pre_script`. Either +way, `.env.d` is not a general migration path for blocked proxy or +certificate settings; the harness reference entry has the per-runtime +rules. + +#### Migrating proxy and certificate settings + +Coordinate these changes with the operator of your OpenShell gateway: + +- **Corporate proxies:** use the operator-managed outbound-network settings + for the OpenShell version and compute driver you deploy; fullsend records + the version it pins in + [`.github/scripts/openshell-version.sh`](https://github.com/fullsend-ai/fullsend/blob/main/.github/scripts/openshell-version.sh) + at your release tag. + The [OpenShell gateway configuration reference](https://github.com/NVIDIA/OpenShell/blob/v0.1.4/docs/how-it-works/gateways/configuration.mdx) + for that version describes proxy chaining for policy-approved TLS + connections using the HTTP CONNECT method to establish a tunnel. Plain-HTTP + destination traffic remains direct. These are not fullsend harness fields or + a general replacement for every `HTTP_PROXY` or `ALL_PROXY` use. Do not + reintroduce application proxy exports through `.env.d` as a workaround. + **GitHub Action limitation:** fullsend's own GitHub Action writes + `gateway.toml` with a fixed template and has no input for upstream proxy or + CA settings. Self-hosted Actions runners behind a corporate proxy that relied + on `HTTPS_PROXY` in `env.sandbox` have no configuration step available yet. + This is tracked as a follow-up for an Action proxy input + ([#8505](https://github.com/fullsend-ai/fullsend/issues/8505)). +- **Additional certificate authorities (CAs):** preserve the active sandbox's + OpenShell CA certificate and other required roots in application trust. + OpenShell's supervisor also verifies upstream TLS separately. Follow the + selected driver's certificate-provisioning instructions in that reference, + which documents `proxy_ca_bundle` for a corporate proxy. It requires + `https_proxy`, and on Kubernetes it is a path in the gateway Pod mounted + from a ConfigMap, not a host path. Do not assume that replacing a + generated bundle with a custom-only file, or changing only the agent + image's trust store, configures both trust paths. Have the gateway operator + validate the required application and supervisor connections before + deployment. The linked tag is what the pinned gateway supports; a setting + documented only at a later OpenShell tag is not available until fullsend + bumps the pin. If the linked tag does not document `additional_ca_bundle` + (added in OpenShell 0.1.5, for Podman gateways), a private CA used without + a corporate proxy has no gateway-level replacement for `SSL_CERT_FILE` or + `NODE_EXTRA_CA_CERTS` at that version. +- **Git settings:** place git configuration with `host_files` (a git config + file or shell rc file the tools load) or use the tool's own configuration, + instead of `GIT_SSH_COMMAND`, `GIT_CONFIG_GLOBAL`, `GIT_ASKPASS` and the + other blocked `GIT_*` names. `host_files` content is trusted like + `pre_script`. Git and TLS equivalents the list does not yet cover, such as + `GIT_SSH`, `GIT_CONFIG_*` and `REQUESTS_CA_BUNDLE`, are tracked in + [#8503](https://github.com/fullsend-ai/fullsend/issues/8503). +- **Interpreter, loader and shell names:** `NODE_OPTIONS`, `PYTHONPATH`, + `JAVA_TOOL_OPTIONS`, `LD_AUDIT`, `IFS` and the other blocked names of this + class have no supported replacement route into the sandbox. They are + blocked because they change how code is loaded or run. Which of them + `host_files` `.env.d` still delivers differs by runtime; the + [`.env.d` host files](../../reference/harness-reference.md#field-details) + entry lists what each runtime drops or unsets. Whatever it delivers, it + does so only because that file is trusted like `pre_script`, so it is not + a sanctioned way to restore them. ### Adding a skill diff --git a/docs/guides/user/running-agents-locally.md b/docs/guides/user/running-agents-locally.md index 7c41803b53..7bf409e683 100644 --- a/docs/guides/user/running-agents-locally.md +++ b/docs/guides/user/running-agents-locally.md @@ -386,6 +386,9 @@ or a cached artifact is missing, `fullsend run` falls back to normal network resolution and prints a warning suggesting you re-run `fullsend lock`. Use `--update` to force re-resolution even if the lock entry appears current. +A current entry is also not composed, so `fullsend lock` does not check it for +reserved `env.sandbox` keys; see +[Reserved `env.sandbox` keys](../../cli/run.md#reserved-envsandbox-keys). ### Status notification flags diff --git a/docs/reference/harness-reference.md b/docs/reference/harness-reference.md index 2f5b83608f..772380a522 100644 --- a/docs/reference/harness-reference.md +++ b/docs/reference/harness-reference.md @@ -75,7 +75,7 @@ host_files: env: runner: # Available to pre/post scripts MY_VAR: "${MY_VAR}" - sandbox: # Available inside sandbox + sandbox: # Available inside sandbox; reserved names are dropped MY_SETTING: "value" runner_env: # ⚠ Deprecated: use env.runner instead MY_VAR: "${MY_VAR}" @@ -171,7 +171,28 @@ breaks the hash-verified fetch cache. These rules make a run fail before `pre_script` starts: -- **Refused names.** A key in the object may not be a runner-owned name. That covers `GH_WORKFLOW_TOKEN`, the OIDC request variables, provider-only keys such as `OPENAI_API_KEY`, the `FULLSEND_*`, `GITHUB_*`, `ACTIONS_*`, `RUNNER_*`, `CI_*`, `LD_*`, `OTEL_*`, `GOOGLE_*` and `CLOUDSDK_*` families, the minted role tokens (`GH_TOKEN`, `PUSH_TOKEN`, `PUSH_TOKEN_SOURCE`, `REVIEW_TOKEN`, `GITLAB_TOKEN`), `PATH`, and the sandbox-reserved names (`HOME`, `SHELL`, `TRACEPARENT`, …), and every name the reusable workflow sets on the `fullsend run` step, such as the named `JIRA_TOKEN`, `JIRA_USER_EMAIL` and `JIRA_BASE_URL` on `harness-run`. An `env.runner` key with one of those names may not receive a value from the object either. +- **Refused names.** A key in the object may not be a runner-owned name. That + covers `GH_WORKFLOW_TOKEN`, the OIDC request variables, provider-only keys + such as `OPENAI_API_KEY`, the `FULLSEND_*`, `GITHUB_*`, `ACTIONS_*`, + `RUNNER_*`, `CI_*`, `LD_*`, `DYLD_*`, `OTEL_*`, `GOOGLE_*` and `CLOUDSDK_*` + families, the minted role tokens (`GH_TOKEN`, `PUSH_TOKEN`, + `PUSH_TOKEN_SOURCE`, `REVIEW_TOKEN`, `GITLAB_TOKEN`), `PATH`, the + runner-infrastructure names (`HOME`, `SHELL`, `BASH_ENV`, `ENV`, + `TRACEPARENT`), and every name the reusable workflow sets on the `fullsend + run` step, such as the named `JIRA_TOKEN`, `JIRA_USER_EMAIL` and + `JIRA_BASE_URL` on `harness-run`. An `env.runner` key with one of those names + may not receive a value from the object either. Credential-class names beyond + the runner-infrastructure names, `PATH`, and the `LD_*`/`DYLD_*` families — + proxy, TLS trust, Git, interpreter and shell-behavior variables such as + `HTTPS_PROXY`, `SSL_CERT_FILE`, `GIT_SSH_COMMAND`, `NODE_OPTIONS` and + `HOSTALIASES` — are **not** refused here: runner secrets reach host-side + scripts (`pre_script`, `post_script`, `validation_loop`) only as `env.runner` + values, and the sandbox gate independently blocks them from `env.sandbox` + exports; see [Migrating proxy and certificate + settings](../guides/user/customizing-agents.md#migrating-proxy-and-certificate-settings) + for where the proxy and TLS-trust settings go instead. Names are matched + case-insensitively, so `path` or `github_token` is refused like `PATH` or + `GITHUB_TOKEN`. - **Host side only.** The object's names may be referenced only from `env.runner` values. A reference from `env.sandbox`, `runner_env`, a provider's `credentials` or `config`, a `host_files` `src`, the content of a `host_files` entry with `expand: true`, or a `validation_loop` field is a validation error. - **Overlays.** An overlay that references one of the object's names may be guarded only by `runtime.forge` and `config`. An overlay that reads `event` or any other `runtime` field is refused, even when it does not match. This rule is interim until [ADR 0112](../ADRs/0112-overlays-may-set-any-harness-field.md)'s guarded-field check is implemented; until then an event-guarded overlay can still swap `pre_script`, `post_script` or `validation_loop`, and so choose which script receives a referenced value. - **Shape.** The value must be a JSON object whose values are strings, with no duplicate keys and no `null` values. Each value must be at least as long as the redactor's minimum (currently 8 characters), so it can be redacted. Errors name the offending key, never its value. @@ -180,6 +201,25 @@ These rules make a run fail before `pre_script` starts: These rules cover names in the GitHub object only. GitLab is unchanged: each secret is its own masked CI/CD variable, `${NAME}` reads it directly, and no name is refused there (keeping fullsend's own credentials out of GitLab host-side scripts is tracked in [#8146](https://github.com/fullsend-ai/fullsend/issues/8146)). For setup, see [Building custom agents § Pass secrets to host-side scripts](../guides/user/building-custom-agents.md#pass-secrets-to-host-side-scripts-github). +**`env.sandbox`** — Variables exported into the sandbox environment. Reserved +names are dropped instead of exported, matched case-insensitively: the +runner-infrastructure names (`PATH`, `HOME`, `SHELL`, `BASH_ENV`, `ENV`, +`LD_PRELOAD`, `LD_LIBRARY_PATH`, `TRACEPARENT` and the `FULLSEND_*` names the +runner reserves), the credentials it mints or receives and the runner-only +inputs that select them, and the credential deny-list (proxy, TLS-trust, Git, +interpreter, loader and shell-behavior names such as `HTTPS_PROXY`, +`SSL_CERT_FILE`, `GIT_SSH_COMMAND`, `NODE_OPTIONS` and `IFS`). `fullsend run` +warns once when the harness loads, naming every dropped key, and once per key on +stderr as it writes the sandbox environment; `fullsend lock` prints the +load-time warning when it composes a harness. The full list is in the +`env.sandbox` note in [Customizing +agents](../guides/user/customizing-agents.md#reserved-envsandbox-names), +where blocked proxy and certificate settings go instead is in [Migrating proxy +and certificate +settings](../guides/user/customizing-agents.md#migrating-proxy-and-certificate-settings), +and the warnings are described in [`fullsend run` § Reserved `env.sandbox` +keys](../cli/run.md#reserved-envsandbox-keys). + **`agent_input`** — A local directory, not a file. When a URL `base:` harness declares it, the inherited value is cleared rather than fetched; supply the directory in the child harness if needed. See [Harness field semantic types](../contributing/harness-fields.md#semantic-types-adr-0127). **`host_files[].dest`** — An absolute path under `/sandbox/` or `/tmp/`. Paths the runner writes or puts on `PATH` ahead of the image are refused when the harness loads: `/sandbox/workspace/.env`, the runner and runtime binaries in `/sandbox/workspace/bin` (`claude`, `codex`, `pi`, `opencode`, `fullsend`, `fullsend-check-output`), and anything under `/sandbox/claude-config`, `/sandbox/codex-config`, `/sandbox/pi-config`, `/sandbox/workspace/.fullsend`, `/sandbox/workspace/.security`, `/sandbox/.venv` or `/sandbox/go/bin`. A `dest` containing a `..` path component is refused as well. The same rule applies to `host_files` under `overlays:`, `forge:` and inherited from `base:`. On Claude and pi runs `/sandbox/workspace/bin` is last on the agent's `PATH`, so a file there adds a command but does not replace one the image provides. Codex and OpenCode runs restore the `PATH` from before `.env`, so `/sandbox/workspace/bin` and `.env.d` additions are not on the codex or OpenCode agent's `PATH`. See [Adding executables](../guides/user/customizing-agents.md#adding-executables). diff --git a/images/sandbox/Containerfile b/images/sandbox/Containerfile index 0e619e5395..27e166d6f2 100644 --- a/images/sandbox/Containerfile +++ b/images/sandbox/Containerfile @@ -95,8 +95,7 @@ RUN NPM_CLAUDE="$(npm prefix -g)/bin/claude" \ # 0.84.4 is the FLOOR for Gemini on Vertex (the pin is above it): 0.84.3 # bundles https-proxy-agent without its named export, so every google-vertex # request fails with "HttpsProxyAgent is not a constructor" whenever -# HTTPS_PROXY is set — which the OpenShell sandbox always does -# (earendil-works/pi#8610, fixed in 0.84.4). +# HTTPS_PROXY is set (earendil-works/pi#8610, fixed in 0.84.4). # To update: bump PI_VERSION; renovate tracks this ARG via a customManagers # regex entry in renovate.json. pi releases ~weekly minors and has changed # its --mode json wire shape within a minor before (0.84.0) — the pi stream diff --git a/internal/cli/lock.go b/internal/cli/lock.go index 214eab50b5..d333aaa1b4 100644 --- a/internal/cli/lock.go +++ b/internal/cli/lock.go @@ -259,7 +259,7 @@ func lockOneAgent(ctx context.Context, agentName, absFullsendDir, forgeFlag stri } // Run lint diagnostics (non-fatal), deduplicating across forge variants - for _, diag := range h.Lint() { + for _, diag := range append(h.Lint(), reservedSandboxEnvDiagnostics(h)...) { key := diag.String() if !linted[key] { linted[key] = true diff --git a/internal/cli/lock_reserved_env_cache_test.go b/internal/cli/lock_reserved_env_cache_test.go new file mode 100644 index 0000000000..7236f1d17d --- /dev/null +++ b/internal/cli/lock_reserved_env_cache_test.go @@ -0,0 +1,39 @@ +package cli + +import ( + "bytes" + "context" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/fetch" + "github.com/fullsend-ai/fullsend/internal/lock" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// A current lock entry skips composition, so the guide sends users to +// --update to check reserved keys. --update must compose base and child. +func TestLockCurrentEntry_UpdateReportsReservedKeys(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + content := []byte("base: base.yaml\nenv:\n sandbox:\n HTTPS_PROXY: http://proxy.example:8080\n") + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "code.yaml"), content, 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "base.yaml"), + []byte("agent: agents/code.md\nrole: test\nenv:\n sandbox:\n PATH: /tmp/bin\n MY_TOOL_SETTING: keep-me\n"), 0o644)) + lf := &lock.LockFile{Harnesses: map[string]lock.HarnessLock{ + "code": {Source: "harness/code.yaml", SHA256: fetch.ComputeSHA256(content)}, + }} + + var out bytes.Buffer + _, err := lockOneAgent(context.Background(), "code", dir, "", true, lf, resolveFlags{}, ui.New(&out)) + require.NoError(t, err) + assert.Contains(t, out.String(), "2 env.sandbox key(s) are reserved") + assert.Contains(t, out.String(), "HTTPS_PROXY, PATH", "--update must check the composed base and child") + assert.NotContains(t, out.String(), "MY_TOOL_SETTING") +} diff --git a/internal/cli/run.go b/internal/cli/run.go index b50e8227ee..f77d43eb3f 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -1170,7 +1170,9 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // Run lint checks before merging env.runner into RunnerEnv so that // Lint() sees the original YAML state and only warns when runner_env // was actually declared (not when env.runner entries are merged in). - for _, diag := range h.Lint() { + // reservedSandboxEnvDiagnostics rides along: it names the env.sandbox + // keys this run will drop instead of exporting them (#3373). + for _, diag := range append(h.Lint(), reservedSandboxEnvDiagnostics(h)...) { emitDiagnostic(printer, diag) } @@ -3290,6 +3292,10 @@ func harnessEnvLookup(key string) (string, bool) { // vars that could influence sandbox execution (e.g. shared library injection, // auto-sourced shell startup files). OIDC credential vars from oidcDenyKeys // are merged in by init() to prevent re-injection into the sandbox (#5832). +// The sandbox credential deny-list is checked beside this map by +// isReservedSandboxKey, not merged into it, because runnerSecretNameRefused +// reads this map too and must accept those names (ADR 0145). +// Entries are matched case-insensitively; every name in the map is uppercase. // NOTE: keep in sync with bootstrapEnv exports below for FULLSEND_* keys. var reservedSandboxKeys = map[string]bool{ "PATH": true, @@ -3346,10 +3352,22 @@ func init() { } } +// isReservedSandboxKey reports whether an env.sandbox key is blocked by name: +// a runner-reserved name, or one the sandbox credential deny-list refuses, so +// a name unsafe as a provider credential is not exported here either (#3373). +// Matching is case-insensitive. The gate and reservedSandboxEnvDiagnostics +// both call this, so they cannot disagree about what a run drops. +func isReservedSandboxKey(k string) bool { + return reservedSandboxKeys[strings.ToUpper(k)] || sandbox.IsReservedCredentialKey(k) +} + // buildSandboxEnvLines generates export lines for env.sandbox values (ADR 0055). // Values have already been expanded by the caller. Each value is single-quoted -// with internal single quotes escaped. Keys that are not valid shell identifiers -// are silently skipped. +// with internal single quotes escaped. Keys that are not valid POSIX +// identifiers, and keys that isReservedSandboxKey rejects, are skipped with a +// warning on stderr; reservedSandboxEnvDiagnostics reports the reserved ones +// again as a lint diagnostic, so they also surface with the other harness +// warnings when the harness loads (#3373). func buildSandboxEnvLines(h *harness.Harness) []string { if h.Env == nil || len(h.Env.Sandbox) == 0 { return nil @@ -3360,8 +3378,15 @@ func buildSandboxEnvLines(h *harness.Harness) []string { fmt.Fprintf(os.Stderr, "WARNING: env.sandbox key %q is not a valid POSIX identifier; skipping\n", k) continue } - if reservedSandboxKeys[k] { - fmt.Fprintf(os.Stderr, "WARNING: env.sandbox key %q is reserved for runner infrastructure; skipping\n", k) + // Case-folded, like the credential and plugin doors. The two spellings + // are not interchangeable for the tools that read them: libcurl + // documents http_proxy as lowercase-only while other scheme proxies + // are also checked uppercase, and which of https_proxy and HTTPS_PROXY + // wins is upstream curl behavior, not something this repo controls. + // Blocking one spelling while exporting the other would make the + // strength of this blocklist depend on tool internals (#3373). + if isReservedSandboxKey(k) { + fmt.Fprintf(os.Stderr, "WARNING: env.sandbox key %q is reserved (runner infrastructure or security deny-list); skipping\n", k) continue } keys = append(keys, k) diff --git a/internal/cli/run_reserved_credential_env_test.go b/internal/cli/run_reserved_credential_env_test.go new file mode 100644 index 0000000000..a24f02e873 --- /dev/null +++ b/internal/cli/run_reserved_credential_env_test.go @@ -0,0 +1,152 @@ +package cli + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/harness" + "github.com/fullsend-ai/fullsend/internal/sandbox" +) + +// reservedInfraSandboxKeys are the seven process-loading names env.sandbox +// rejected before #3373 widened the blocklist to the credential deny-list. +// All seven are also members of reservedCredentialKeys, under its +// Process loading / shell behavior group, so the loop below asserts them twice +// — deliberately: keeping them here means the sandbox door still pins them if +// a name is ever dropped from the credential door. Some of the other +// infrastructure names are pinned elsewhere — TRACEPARENT in run_test.go, the +// runner PATH variable in run_env_path_test.go, and FULLSEND_FETCH_TOKEN and +// FULLSEND_OUTPUT_DIR in TestBuildSandboxEnvLines_SkipsReservedKeys. +var reservedInfraSandboxKeys = []string{ + "PATH", "HOME", "SHELL", "LD_PRELOAD", "LD_LIBRARY_PATH", "BASH_ENV", "ENV", +} + +// TestReservedSandboxKeys_CoversReservedCredentialKeys pins the invariant that +// a variable unsafe as a provider credential key is equally unsafe injected via +// env.sandbox. The doors write different environments — a credential lands in +// the host-side `openshell provider` process, env.sandbox is exported inside +// the sandbox — but the exposure a name creates is the same once it is set in +// a child's environment, so a gap between the two blocklists is a way to set +// that name from harness YAML (#3373). +// +// The credential half is read live from sandbox.ReservedCredentialKeys instead +// of being copied, so a name added to the credential door is asserted here the +// moment it is added there. The accessor test in internal/sandbox pins that the +// list it returns is complete; the guard below keeps a hollowed-out accessor +// from quietly reducing this test to the infrastructure names alone. +func TestReservedSandboxKeys_CoversReservedCredentialKeys(t *testing.T) { + t.Parallel() + + credentialKeys := sandbox.ReservedCredentialKeys() + require.NotEmpty(t, credentialKeys, + "sandbox.ReservedCredentialKeys returned no names; this test would silently stop covering the credential door") + + for _, key := range append(credentialKeys, reservedInfraSandboxKeys...) { + t.Run(key, func(t *testing.T) { + t.Parallel() + + assert.True(t, isReservedSandboxKey(key), + "env.sandbox must refuse %s: it can inject a variable the credential path refuses", key) + + lines := buildSandboxEnvLines(&harness.Harness{ + Env: &harness.EnvConfig{Sandbox: map[string]string{key: "/tmp/evil"}}, + }) + assert.NotContains(t, strings.Join(lines, "\n"), "export "+key+"=", + "buildSandboxEnvLines leaked %s into the sandbox environment", key) + }) + } +} + +// guideEnvNameRe matches a backticked, all-uppercase environment variable name +// as the user guide writes them. It deliberately will not match a partial +// family like `FULLSEND_OPENAI_*`, since that is prose about a family rather +// than a name the gate can be checked against. +var guideEnvNameRe = regexp.MustCompile("`([A-Z][A-Z0-9_]{2,})`") + +// documentedPassthroughNames are the names the guide's env.sandbox note says +// are still delivered through env.sandbox. They are the carve-out, so they are +// asserted in the opposite direction from everything else in that paragraph. +var documentedPassthroughNames = map[string]bool{ + "FULLSEND_CANARY_TOKEN": true, + "FULLSEND_TOOL_ALLOWLIST": true, +} + +// TestGuideNamesMatchTheGate reads the user guide itself rather than a copy of +// its list, in both directions: every name the note claims is dropped must +// really be blocked by the gate, and every name the note promises is delivered +// must really get through. A hand-copied list could only ever agree with +// itself, so a name added to the guide without a matching gate change — the +// same drift #3373 is about, one level up — would pass unnoticed. The count +// guard keeps this test from going quietly vacuous if the prose is reworded. +func TestGuideNamesMatchTheGate(t *testing.T) { + t.Parallel() + + const marker = "**Note**: `env.sandbox` cannot modify runner infrastructure" + + data, err := os.ReadFile(filepath.Join("..", "..", "docs", "guides", "user", "customizing-agents.md")) + require.NoError(t, err) + + start := strings.Index(string(data), marker) + require.Greater(t, start, 0, + "the env.sandbox note was renamed or moved; update this test along with the guide") + note := string(data)[start:] + // The note is a lead-in plus a bulleted enumeration, so it spans several + // markdown blocks. Stop at the sentence that closes it: a missing + // terminator would silently widen the scan into the reporting paragraphs, + // which name nothing the gate is being asked about. + end := strings.Index(note, "Matching is case-insensitive") + require.Greater(t, end, 0, + "the env.sandbox note no longer ends at that sentence; update this terminator along with the prose") + note = note[:end] + + matches := guideEnvNameRe.FindAllStringSubmatch(note, -1) + // The floor is what keeps this test from failing silently: a reworded + // paragraph the pattern no longer matches would otherwise scan zero names + // and pass. The note enumerates about fifty-five names today, including + // the two pass-through names in the carve-out sentence (the runner's own + // FULLSEND_* exports are described as a family, not listed, so that a new + // runner export does not need a guide edit), so a floor just under that + // also catches a whole bullet being dropped from the prose. + require.GreaterOrEqual(t, len(matches), 50, + "the note enumerates about fifty-five names but only %d matched, so either the pattern no longer fits the prose or names were dropped from it — this test proves nothing until one of those is fixed", + len(matches)) + + // The pass-through set is a second copy of what the prose promises, so pin + // that the prose still promises it. Without this, rewording the carve-out + // sentence so it stops backticking these names would leave the branch + // below running over a set nothing supplies, and the test would quietly + // check one direction instead of two. + for name := range documentedPassthroughNames { + assert.Contains(t, note, "`"+name+"`", + "the guide no longer documents %s as delivered through env.sandbox; either restore it or drop it from documentedPassthroughNames", + name) + } + + for _, m := range matches { + name := m[1] + t.Run(name, func(t *testing.T) { + t.Parallel() + + if documentedPassthroughNames[name] { + // The carve-out is a promise that hook inputs still arrive, so + // check delivery itself, not only the predicate. + require.False(t, isReservedSandboxKey(name), + "the guide says %s is still delivered through env.sandbox, but the gate now drops it", name) + lines := buildSandboxEnvLines(&harness.Harness{ + Env: &harness.EnvConfig{Sandbox: map[string]string{name: "value"}}, + }) + assert.Contains(t, strings.Join(lines, "\n"), "export "+name+"=", + "the guide promises %s reaches the sandbox, but the gate dropped it", name) + return + } + assert.True(t, isReservedSandboxKey(name), + "the guide names %s as dropped from env.sandbox, but the gate accepts it", name) + }) + } +} diff --git a/internal/cli/run_reserved_env_case_test.go b/internal/cli/run_reserved_env_case_test.go new file mode 100644 index 0000000000..fc6f74bcdf --- /dev/null +++ b/internal/cli/run_reserved_env_case_test.go @@ -0,0 +1,69 @@ +package cli + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/fullsend-ai/fullsend/internal/harness" + "github.com/fullsend-ai/fullsend/internal/sandbox" +) + +// TestBuildSandboxEnvLines_ReservesCaseInsensitively pins that the env.sandbox +// gate matches reserved names the way the provider-credential and plugin-env +// doors already do. Every reserved name is stored uppercase, so before the +// fold the credential deny-list's proxy names were reachable through their +// lowercase spelling — and libcurl documents +// http_proxy as lowercase-only, so an exact-case gate blocks a spelling tools +// may not read while exporting the one they do. The comment on +// buildSandboxEnvLines carries the full rationale (#3373). +func TestBuildSandboxEnvLines_ReservesCaseInsensitively(t *testing.T) { + t.Parallel() + + cases := []struct { + key string + why string + }{ + {"HTTPS_PROXY", "uppercase, the spelling stored in the blocklist"}, + {"https_proxy", "lowercase spelling of a reserved proxy name"}, + {"HtTp_PrOxY", "mixed case"}, + {"NO_PROXY", "uppercase no_proxy bypass"}, + {"no_proxy", "lowercase no_proxy bypass"}, + {"GIT_SSH_COMMAND", "uppercase git command injection"}, + {"git_ssh_command", "lowercase git command injection"}, + {"Node_OPTIONS", "mixed-case interpreter injection"}, + } + + for _, tc := range cases { + t.Run(tc.key, func(t *testing.T) { + t.Parallel() + + assert.True(t, isReservedSandboxKey(tc.key), + "the gate must refuse %s case-insensitively (%s)", tc.key, tc.why) + + lines := buildSandboxEnvLines(&harness.Harness{ + Env: &harness.EnvConfig{Sandbox: map[string]string{tc.key: "http://evil.example:8080"}}, + }) + assert.Empty(t, lines, + "buildSandboxEnvLines leaked %s into the sandbox environment (%s): %v", tc.key, tc.why, lines) + }) + } +} + +// TestReservedSandboxKeys_AreUppercase pins the invariant the case-folded gate +// is built on. The gate looks keys up by their uppercase form in both lists, +// which only works because every entry is stored uppercase — a name added +// later in mixed or lower case would be silently unenforceable. +func TestReservedSandboxKeys_AreUppercase(t *testing.T) { + t.Parallel() + + for key := range reservedSandboxKeys { + assert.Equal(t, strings.ToUpper(key), key, + "reservedSandboxKeys entry %q is not uppercase, so the case-folded env.sandbox gate can never match it", key) + } + for _, key := range sandbox.ReservedCredentialKeys() { + assert.Equal(t, strings.ToUpper(key), key, + "credential deny-list entry %q is not uppercase, so the case-folded env.sandbox gate can never match it", key) + } +} diff --git a/internal/cli/run_reserved_env_lint.go b/internal/cli/run_reserved_env_lint.go new file mode 100644 index 0000000000..e09c1bfc53 --- /dev/null +++ b/internal/cli/run_reserved_env_lint.go @@ -0,0 +1,65 @@ +package cli + +import ( + "fmt" + "sort" + "strings" + + "github.com/fullsend-ai/fullsend/internal/harness" +) + +// reservedSandboxEnvDiagnostics reports the env.sandbox keys that +// buildSandboxEnvLines will drop because they are reserved. +// +// The gate itself only warns on stderr while .env is being written, deep inside +// a run. Surfacing the same keys as lint diagnostics puts them next to the +// rest of the harness warnings, right after the harness loads and in +// `fullsend lock`, so a harness that quietly lost a proxy or CA setting is +// visible before a sandbox ever starts. #3373 widened the dropped set from the +// runner-infrastructure names to the full credential deny-list, which made +// silent removal a breaking change worth reporting rather than logging. +// +// It asks isReservedSandboxKey, the predicate the gate itself applies, and it +// skips keys the gate rejects as invalid identifiers before that, so it cannot +// report a key the gate dropped for some other reason. Both callers pass the +// harness before env.runner is merged into RunnerEnv, so the warning reflects +// what the user wrote; base, overlay and forge merging has already happened +// inside the loader by then, and nothing rewrites env.sandbox keys after it. +func reservedSandboxEnvDiagnostics(h *harness.Harness) []harness.Diagnostic { + if h == nil || h.Env == nil || len(h.Env.Sandbox) == 0 { + return nil + } + + var dropped []string + for k := range h.Env.Sandbox { + // The gate rejects invalid identifiers before it consults the + // blocklist, and case folding alone does not keep the two lists + // identical: strings.ToUpper folds non-ASCII lookalikes onto reserved + // names, so "ſHELL" would read here as PATH's blocked sibling while + // the gate drops it as not a POSIX identifier. Reporting that as + // reserved would name the key twice under a false heading. + if !validEnvKeyRe.MatchString(k) { + continue + } + if isReservedSandboxKey(k) { + dropped = append(dropped, k) + } + } + if len(dropped) == 0 { + return nil + } + // Map iteration order is random. The sort keeps the message stable, which + // is what lets lock's cross-variant de-duplication recognise a repeat of + // this diagnostic as the same one. + sort.Strings(dropped) + + return []harness.Diagnostic{{ + Severity: harness.SeverityWarning, + Field: "env.sandbox", + Message: fmt.Sprintf("%d env.sandbox key(s) are reserved and will be dropped instead of exported "+ + "into the sandbox: %s. Matching is case-insensitive. Review the migration guidance before "+ + "changing proxy or certificate settings; preserve OpenShell's network mediation and certificate trust. "+ + "See docs/guides/user/customizing-agents.md.", + len(dropped), strings.Join(dropped, ", ")), + }} +} diff --git a/internal/cli/run_reserved_env_lint_test.go b/internal/cli/run_reserved_env_lint_test.go new file mode 100644 index 0000000000..01d409b4c2 --- /dev/null +++ b/internal/cli/run_reserved_env_lint_test.go @@ -0,0 +1,216 @@ +package cli + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/harness" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +func TestReservedSandboxEnvDiagnostics_ReportsDroppedKeys(t *testing.T) { + t.Parallel() + + h := &harness.Harness{Env: &harness.EnvConfig{Sandbox: map[string]string{ + "PATH": "/tmp/bin", + "HTTPS_PROXY": "http://evil.example:8080", + "CUSTOM_VAR": "fine", + "FULLSEND_ROLE": "coder", + "GH_WORKFLOW_TOKEN": "ghp_x", + }}} + + diags := reservedSandboxEnvDiagnostics(h) + require.Len(t, diags, 1, "the reserved keys collapse into one warning") + assert.Equal(t, harness.SeverityWarning, diags[0].Severity) + assert.Equal(t, "env.sandbox", diags[0].Field) + + // Every key the gate will drop is named, and only those keys. + for _, key := range []string{"PATH", "HTTPS_PROXY", "FULLSEND_ROLE", "GH_WORKFLOW_TOKEN"} { + assert.Contains(t, diags[0].Message, key, + "the warning must name %s, which buildSandboxEnvLines will drop", key) + } + assert.NotContains(t, diags[0].Message, "CUSTOM_VAR", + "a key that survives must not be reported") + + // GH_WORKFLOW_TOKEN arrives through the providerOnlyKeys merge and + // FULLSEND_ROLE is a runner-infrastructure name, so a warning that names + // both proves this reads the merged gate list, not one hand-written set. + assert.True(t, reservedSandboxKeys["GH_WORKFLOW_TOKEN"], "precondition: merged into the gate") + // Four keys dropped, so the count in the message is the count that was cut. + assert.Contains(t, diags[0].Message, "4 env.sandbox key(s) are reserved") + + // The guidance is load-bearing for a breaking change: a warning that names + // the keys but not the case rule or where to read about it leaves the user + // to guess. Pin the parts that matter rather than the whole sentence. + assert.Contains(t, diags[0].Message, "Matching is case-insensitive") + assert.Contains(t, diags[0].Message, "Review the migration guidance") + assert.Contains(t, diags[0].Message, "docs/guides/user/customizing-agents.md") + assert.NotContains(t, diags[0].Message, ".env.d", "do not recommend reinjecting proxy or CA settings") + assert.NotContains(t, diags[0].Message, "named configuration field", "no such fullsend field exists") +} + +func TestReservedSandboxEnvDiagnostics_MatchesGateCaseFolding(t *testing.T) { + t.Parallel() + + h := &harness.Harness{Env: &harness.EnvConfig{Sandbox: map[string]string{ + "https_proxy": "http://evil.example:8080", + "HtTp_PrOxY": "http://evil.example:8081", + }}} + + diags := reservedSandboxEnvDiagnostics(h) + require.Len(t, diags, 1) + assert.Contains(t, diags[0].Message, "https_proxy") + assert.Contains(t, diags[0].Message, "HtTp_PrOxY") + + // The point of the case fold: the gate really does drop both spellings, so + // the warning is not overstating what a run loses. + lines := buildSandboxEnvLines(h) + for _, line := range lines { + assert.NotContains(t, line, "evil.example", "nothing reserved may be exported") + } + assert.Empty(t, lines) +} + +func TestReservedSandboxEnvDiagnostics_CleanHarness(t *testing.T) { + t.Parallel() + + for name, env := range map[string]*harness.EnvConfig{ + "nil harness env": nil, + "empty sandbox map": {Sandbox: map[string]string{}}, + "only allowed values": {Sandbox: map[string]string{"PIP_INDEX_URL": "https://pypi.example/simple"}}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + h := &harness.Harness{Env: env} + assert.Nil(t, reservedSandboxEnvDiagnostics(h), + "a harness the gate drops nothing from must produce no warning") + }) + } + + assert.Nil(t, reservedSandboxEnvDiagnostics(nil), "a nil harness must not panic") +} + +// TestReservedSandboxEnvDiagnostics_ReportsInSortedOrder pins the exact list +// text rather than membership. lock de-duplicates diagnostics across forge +// variants by diag.String(), and the keys arrive from map iteration, so +// without the sort one harness can produce two differently ordered strings and +// print the same warning once per variant. +func TestReservedSandboxEnvDiagnostics_ReportsInSortedOrder(t *testing.T) { + t.Parallel() + + h := &harness.Harness{Env: &harness.EnvConfig{Sandbox: map[string]string{ + "PATH": "/tmp/bin", "HTTPS_PROXY": "http://evil:8080", + "GH_WORKFLOW_TOKEN": "ghp_x", "FULLSEND_ROLE": "coder", + }}} + + diags := reservedSandboxEnvDiagnostics(h) + require.Len(t, diags, 1) + assert.Contains(t, diags[0].Message, "FULLSEND_ROLE, GH_WORKFLOW_TOKEN, HTTPS_PROXY, PATH", + "the list must be byte-sorted, not in random map order") + + // A dropped sort would eventually reorder; one sample would not catch it. + seen := map[string]bool{} + for range 50 { + seen[reservedSandboxEnvDiagnostics(h)[0].Message] = true + } + assert.Len(t, seen, 1, "the message must be byte-identical across runs") +} + +// TestReservedSandboxEnvDiagnostics_SkipsInvalidIdentifiers covers what case +// folding does not: strings.ToUpper folds non-ASCII lookalikes onto reserved +// names, so a key the gate rejects as "not a valid POSIX identifier" must not +// be reported to the user as a reserved-name drop. +func TestReservedSandboxEnvDiagnostics_SkipsInvalidIdentifiers(t *testing.T) { + t.Parallel() + + require.Equal(t, "SHELL", strings.ToUpper("ſHELL"), "precondition: case folding collides with a reserved name") + require.Equal(t, "IFS", strings.ToUpper("ıFS"), "precondition: case folding collides with a reserved name") + + invalid := &harness.Harness{Env: &harness.EnvConfig{Sandbox: map[string]string{ + "ſHELL": "/tmp/sh", + "ıFS": " ", + }}} + assert.Nil(t, reservedSandboxEnvDiagnostics(invalid), + "invalid identifiers are the gate's other rejection, not a reserved-name drop") + + mixed := &harness.Harness{Env: &harness.EnvConfig{Sandbox: map[string]string{ + "ſHELL": "/tmp/sh", + "HTTPS_PROXY": "http://evil:8080", + }}} + diags := reservedSandboxEnvDiagnostics(mixed) + require.Len(t, diags, 1) + assert.Contains(t, diags[0].Message, "1 env.sandbox key(s)", + "only the genuinely reserved key may be counted") + assert.NotContains(t, diags[0].Message, "ſHELL") +} + +// TestLockOneAgent_ReportsReservedSandboxEnvKeys pins the wiring, not the +// helper: every other test in this file calls reservedSandboxEnvDiagnostics +// directly, so deleting it from the append in lock.go would otherwise leave +// the suite green while the user stops hearing about dropped keys. +func TestLockOneAgent_ReportsReservedSandboxEnvKeys(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: test\n"+ + "env:\n sandbox:\n HTTPS_PROXY: http://proxy.example:8080\n"+ + " MY_TOOL_SETTING: keep-me\n"), 0o644)) + + var out bytes.Buffer + _, err := lockOneAgent(context.Background(), "code", dir, "", false, nil, resolveFlags{}, ui.New(&out)) + require.NoError(t, err) + + assert.Contains(t, out.String(), "HTTPS_PROXY", + "lock must warn about the key the run will drop") + assert.NotContains(t, out.String(), "MY_TOOL_SETTING", + "a key that survives must not be named") +} + +// TestRunAgent_ReportsReservedSandboxEnvKeys pins the same wiring on the run +// side, which is where the key is actually lost. The lint loop sits well above +// the pre-script block, so a harness whose pre-script requests a skip returns +// before any sandbox exists while still having passed through the loop — the +// cheapest way to drive it. Deleting reservedSandboxEnvDiagnostics from that +// append would otherwise leave the suite green and reduce `fullsend run` to +// the stderr warning that only appears while the sandbox environment is +// written. +func TestRunAgent_ReportsReservedSandboxEnvKeys(t *testing.T) { + usePreScriptStub(t) + + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\n"), 0o644)) + writePolicyFixture(t, dir) + + skip := writePreScript(t, `echo "skipped=true" >> "${FULLSEND_PRESCRIPT_OUTPUT}"`+"\n") + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: test\npolicy: policies/base.yaml\n"+ + "pre_script: "+skip+"\n"+ + "env:\n sandbox:\n HTTPS_PROXY: http://proxy.example:8080\n"+ + " MY_TOOL_SETTING: keep-me\n"), 0o644)) + + var out bytes.Buffer + err := runAgent(context.Background(), "code", dir, "", t.TempDir(), "", nil, false, + "", "", "", resolveFlags{maxDepth: 10, maxResources: 50}, statusOpts{}, + ui.New(&out), false, runOverrideFlags{}) + require.NoError(t, err) + + assert.Contains(t, out.String(), "HTTPS_PROXY", + "run must warn about the key it is about to drop, before the sandbox exists") + assert.NotContains(t, out.String(), "MY_TOOL_SETTING", + "a key that survives must not be named") +} diff --git a/internal/cli/runner_secrets.go b/internal/cli/runner_secrets.go index 40bdf60a23..cc8b325991 100644 --- a/internal/cli/runner_secrets.go +++ b/internal/cli/runner_secrets.go @@ -37,6 +37,9 @@ var runnerSecretRefusedPrefixes = []string{ "RUNNER_", "CI_", "LD_", + // macOS dynamic-linker injection (#3373). The plugin door refuses the + // whole prefix; the env.sandbox gate refuses only DYLD_INSERT_LIBRARIES. + "DYLD_", "OTEL_", // google-github-actions/auth exports these for the job. "GOOGLE_", @@ -66,9 +69,10 @@ var workflowSetEnvNames = []string{ // runnerSecretRefusedNames are minted role tokens and other runner-owned // names outside the refused families: GH_TOKEN, every role token in -// roleTokenVars, GITLAB_TOKEN, PATH and workflowSetEnvNames. oidcDenyKeys, providerOnlyKeys and -// reservedSandboxKeys are refused as well (runnerSecretNameRefused), which -// keeps GH_WORKFLOW_TOKEN (ADR 0114) unforgeable. +// roleTokenVars, GITLAB_TOKEN, PATH and workflowSetEnvNames. oidcDenyKeys, +// providerOnlyKeys and reservedSandboxKeys are refused as well +// (runnerSecretNameRefused), which keeps GH_WORKFLOW_TOKEN (ADR 0114) +// unforgeable. var runnerSecretRefusedNames = func() map[string]bool { names := map[string]bool{ "GH_TOKEN": true, @@ -98,13 +102,18 @@ func runnerSecretDisplayName(name string) string { // runnerSecretNameRefused reports whether name is runner-owned and so may // neither be a key in FULLSEND_GITHUB_RUNNER_SECRETS nor receive a runner secret -// value as an env.runner key. +// value as an env.runner key. Matched case-insensitively, consistent with +// the env.sandbox gate (isReservedSandboxKey), so "path" is refused like +// "PATH". It reads reservedSandboxKeys but not the credential deny-list the +// env.sandbox gate also checks: proxy, TLS-trust and Git settings are +// legitimate host-side runner secrets (ADR 0145). func runnerSecretNameRefused(name string) bool { - if harnessExpansionDenied(name) || reservedSandboxKeys[name] || runnerSecretRefusedNames[name] { + upper := strings.ToUpper(name) + if harnessExpansionDenied(upper) || reservedSandboxKeys[upper] || runnerSecretRefusedNames[upper] { return true } for _, p := range runnerSecretRefusedPrefixes { - if strings.HasPrefix(name, p) { + if strings.HasPrefix(upper, p) { return true } } diff --git a/internal/cli/runner_secrets_test.go b/internal/cli/runner_secrets_test.go index 1046e33a99..505fb9cab9 100644 --- a/internal/cli/runner_secrets_test.go +++ b/internal/cli/runner_secrets_test.go @@ -14,6 +14,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/harness" "github.com/fullsend-ai/fullsend/internal/prescript" + "github.com/fullsend-ai/fullsend/internal/sandbox" "github.com/fullsend-ai/fullsend/internal/security" "github.com/fullsend-ai/fullsend/internal/ui" "gopkg.in/yaml.v3" @@ -409,6 +410,64 @@ func TestRunnerSecretNameRefused_AllowsOrdinaryNames(t *testing.T) { } } +// TestRunnerSecretNameRefused_AllowsCredentialClassNames pins the two doors +// (ADR 0145): the env.sandbox gate refuses every credential-class name, and +// the runner-secret door accepts it, because runner secrets reach only +// host-side scripts. A name that is also in reservedSandboxKeys (PATH, HOME, +// SHELL, BASH_ENV, ENV, LD_PRELOAD, LD_LIBRARY_PATH) or under a refused +// loader prefix stays refused at both doors. Credential names are read live +// from sandbox.ReservedCredentialKeys, so a new one is covered at once. +func TestRunnerSecretNameRefused_AllowsCredentialClassNames(t *testing.T) { + t.Parallel() + + credentialKeys := sandbox.ReservedCredentialKeys() + require.NotEmpty(t, credentialKeys, "no credential names to probe; this test is vacuous") + + for _, name := range credentialKeys { + t.Run(name, func(t *testing.T) { + t.Parallel() + + assert.True(t, isReservedSandboxKey(name), + "%s must be refused by the env.sandbox gate", name) + + if reservedSandboxKeys[name] || strings.HasPrefix(name, "LD_") || strings.HasPrefix(name, "DYLD_") { + // Also refused as a runner-secret key: runner infrastructure + // or dynamic-loader names. + assert.True(t, runnerSecretNameRefused(name), + "%s is dual-class (credential and infrastructure) and must stay refused at both doors", name) + } else { + assert.False(t, runnerSecretNameRefused(name), + "%s is credential-class only: refused in env.sandbox, not as a runner-secret key for host-side scripts", name) + } + }) + } + + // Runner-only infrastructure names (not in the credential list) stay + // refused at both doors. + t.Run("TRACEPARENT", func(t *testing.T) { + t.Parallel() + + assert.True(t, runnerSecretNameRefused("TRACEPARENT"), + "TRACEPARENT is runner infrastructure and must stay refused as a runner-secret key") + assert.True(t, isReservedSandboxKey("TRACEPARENT"), + "TRACEPARENT must also stay refused by the env.sandbox gate") + }) +} + +// TestRunnerSecretNameRefused_CaseInsensitive pins the case fold: a +// lowercase or mixed-case key is refused exactly when its uppercase form +// is, and credential-class names stay allowed in any case. +func TestRunnerSecretNameRefused_CaseInsensitive(t *testing.T) { + t.Parallel() + + for _, name := range []string{"path", "Home", "github_x", "ld_preload", "dyld_library_path", "fullsend_x", "jira_token"} { + assert.True(t, runnerSecretNameRefused(name), "%s must be refused regardless of case", name) + } + for _, name := range []string{"https_proxy", "ssl_cert_file", "my_secret"} { + assert.False(t, runnerSecretNameRefused(name), "%s must stay allowed", name) + } +} + func TestValidateRunnerSecretRefs(t *testing.T) { secrets := map[string]string{"X": "value-123456"} diff --git a/internal/sandbox/reserved_credential_keys_test.go b/internal/sandbox/reserved_credential_keys_test.go new file mode 100644 index 0000000000..a057c72ad1 --- /dev/null +++ b/internal/sandbox/reserved_credential_keys_test.go @@ -0,0 +1,73 @@ +package sandbox + +import ( + "sort" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestReservedCredentialKeys pins the accessor that internal/cli's tests +// enumerate to check its env.sandbox gate (#3373). It must expose the +// complete reserved set — a silently narrowed list would reopen the drift +// this exists to close — in a stable order. +func TestReservedCredentialKeys(t *testing.T) { + t.Parallel() + + keys := ReservedCredentialKeys() + require.Len(t, keys, len(reservedCredentialKeys), + "accessor must expose every reserved credential key") + + returned := make(map[string]bool, len(keys)) + for _, k := range keys { + require.True(t, reservedCredentialKeys[k], + "accessor returned %s, which is not a reserved credential key", k) + returned[k] = true + } + for k := range reservedCredentialKeys { + assert.True(t, returned[k], "accessor omitted reserved credential key %s", k) + } + + assert.True(t, sort.StringsAreSorted(keys), + "accessor must return a deterministic order; its contract is exported") +} + +// reservedCredentialKeysUnpinnedFloor holds the entries of +// reservedCredentialKeys that no other test pins against that map. +// TestReservedCredentialKeys proves the accessor mirrors the map but cannot +// notice the map shrinking, because then both sides shrink together. SHELL, +// ENV and LD_LIBRARY_PATH are listed here even though the cli blocklist names +// them too, because that pin is satisfied by cli's own map and would stay +// green if the credential map alone dropped the name. Dropping any entry here +// has to be a deliberate edit in two files, not a silent policy change +// (#3373). +var reservedCredentialKeysUnpinnedFloor = []string{ + "ALL_PROXY", "IFS", "CDPATH", "PYTHONPATH", "JAVA_TOOL_OPTIONS", "RUBYOPT", + "PERL5OPT", "DYLD_INSERT_LIBRARIES", "GIT_TEMPLATE_DIR", "GIT_ASKPASS", + "SHELL", "ENV", "LD_LIBRARY_PATH", +} + +// TestIsReservedCredentialKey pins the predicate internal/cli's env.sandbox +// gate calls: every listed name in any case, and nothing else. +func TestIsReservedCredentialKey(t *testing.T) { + t.Parallel() + + for _, k := range ReservedCredentialKeys() { + assert.True(t, IsReservedCredentialKey(k), "%s is on the list", k) + } + assert.True(t, IsReservedCredentialKey("https_proxy"), "matching is case-insensitive") + assert.False(t, IsReservedCredentialKey("MY_TOOL_SETTING"), "an unlisted name is not reserved") +} + +// TestReservedCredentialKeys_RetainUnpinnedNames keeps the credential +// deny-list from losing an entry that nothing else would notice. +func TestReservedCredentialKeys_RetainUnpinnedNames(t *testing.T) { + t.Parallel() + + keys := ReservedCredentialKeys() + for _, want := range reservedCredentialKeysUnpinnedFloor { + assert.Contains(t, keys, want, + "reservedCredentialKeys must retain %s; no other test pins it against this map", want) + } +} diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index 3d7dd566d3..b7c71f92de 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -581,7 +581,7 @@ func ImportProfileVerified(ctx context.Context, id, profilePath string) error { // credential keys. Credential keys become env vars in the openshell child // process; allowing security-sensitive names would let a URL-fetched provider // definition influence process loading or shell behavior. -// NOTE: see also reservedSandboxKeys in internal/cli/run.go for the sandbox env blocklist. +// NOTE: internal/cli's env.sandbox gate checks this list too (#3373). var reservedCredentialKeys = map[string]bool{ // Process loading / shell behavior "PATH": true, @@ -627,6 +627,42 @@ var reservedCredentialKeys = map[string]bool{ "GIT_ASKPASS": true, } +// ReservedCredentialKeys returns the names reservedCredentialKeys refuses as +// provider credential keys. Production code checks membership through +// IsReservedCredentialKey; this accessor exists so tests in other packages +// (internal/cli's env.sandbox gate tests) can enumerate the live list +// instead of copying it. +// +// A name is on this list because letting harness-supplied configuration set it +// in a child process could change process loading, shell behavior, TLS trust +// or git behavior. The doors differ: a credential name reaches the host-side +// `openshell provider` environment, while harness `env.sandbox` is exported +// inside the sandbox. The exposure is the same once the name is in a child's +// environment, so every name here is blocked on both sides — internal/cli's +// env.sandbox gate checks it through IsReservedCredentialKey, so the two +// cannot drift apart (#3373). Absence from this list is not a statement that +// a name is safe — the plugin-env deny-list is deliberately broader, in the +// direction reserved_env_drift_test.go pins: every credential name is also a +// plugin-env name, not the converse. The cross-door invariant is pinned by +// TestReservedSandboxKeys_CoversReservedCredentialKeys in internal/cli. +// +// The result is a fresh sorted slice, so callers cannot edit the blocklist +// and subtests run in a stable order. +func ReservedCredentialKeys() []string { + keys := make([]string, 0, len(reservedCredentialKeys)) + for k := range reservedCredentialKeys { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +// IsReservedCredentialKey reports, case-insensitively, whether name is +// refused as a provider credential key. +func IsReservedCredentialKey(name string) bool { + return reservedCredentialKeys[strings.ToUpper(name)] +} + // EnsureProvider creates or updates a provider on the gateway. Credential // values may contain ${VAR} references which are expanded from the host // environment before being passed to openshell. @@ -645,7 +681,7 @@ var reservedCredentialKeys = map[string]bool{ func EnsureProvider(ctx context.Context, name, providerType string, credentials, config map[string]string, fromURL bool) error { if fromURL { for k := range credentials { - if reservedCredentialKeys[strings.ToUpper(k)] { + if IsReservedCredentialKey(k) { return fmt.Errorf("provider %q: credential key %q is a reserved environment variable name", name, k) } } @@ -665,7 +701,7 @@ func EnsureProvider(ctx context.Context, name, providerType string, credentials, // form in the child process environment, never on the command line. func EnsureProviderLiteral(ctx context.Context, name, providerType string, credentials map[string]string) error { for k := range credentials { - if reservedCredentialKeys[strings.ToUpper(k)] { + if IsReservedCredentialKey(k) { return fmt.Errorf("provider %q: credential key %q is a reserved environment variable name", name, k) } } diff --git a/renovate.json b/renovate.json index 1ed8a35a03..bba4858a4d 100644 --- a/renovate.json +++ b/renovate.json @@ -140,6 +140,17 @@ "datasourceTemplate": "github-releases", "extractVersionTemplate": "^v(?.*)$" }, + { + "customType": "regex", + "description": "Track the OpenShell tag in the gateway configuration link of the customizing agents guide (migrating proxy and certificate settings), so the link follows the pin in the same openshell group PR instead of pointing at a tag the pinned gateway does not match (#3373).", + "managerFilePatterns": ["/^docs/guides/user/customizing-agents\\.md$/"], + "matchStrings": [ + "github\\.com/NVIDIA/OpenShell/blob/v(?\\d+\\.\\d+\\.\\d+)/" + ], + "depNameTemplate": "NVIDIA/OpenShell", + "datasourceTemplate": "github-releases", + "extractVersionTemplate": "^v(?.*)$" + }, { "customType": "regex", "description": "Track the gcloud CLI version pin in the runner image. GCLOUD_SHA256_{AMD64,ARM64} must be refreshed manually from https://cloud.google.com/sdk/docs/install — the runner-image PR build fails on checksum mismatch until they are.",