Repository navigation
Description
Summary
The agent-server's credential-inject endpoints mirror every .env key into the long-lived
agent-server process's os.environ, and every execution is spawned with that environment. The
.env file itself is never loaded into the agent-server process. So the file an operator
inspects and the environment executions actually receive are two independent channels that sync
only inside one code path.
Consequence: after any .env edit that does not go through /api/credentials/* (SSH, docker exec,
or an agent execution editing its own .env), a value removed from the file keeps applying to
every execution until the container restarts. The stale value is invisible to /proc/<pid>/environ
(an exec-time snapshot — runtime os.environ mutations never appear there) and to docker exec
(which gets the container baseline, not the server process env). Both standard inspection routes
agree with the file and disagree with reality.
Security framing: credential revocation silently fails. Removing a leaked or rotated key from
.env does not stop executions from using it, and nothing an operator can inspect reveals that.
Context
Observed on a production instance, where a retired feature-flag variable re-entered a running
agent-server via a credential push, survived a same-day .env cleanup, and silently altered the
behaviour of two scheduled executions over the following ~19 hours. Root-causing it took hours
precisely because every inspection tool reported the variable as unset.
Reproduced on dev @ 3f1d4c89. The mechanism is present in every released version — both
mirror blocks date to the initial commit.
Reproduction
Verified end-to-end against a local agent with real Claude Code executions.
Probe: python3 -c "import os; print('CANARY:', repr(os.environ.get('CANARY_VAR')))"
| Step | .env on disk |
Execution sees |
|---|---|---|
| Baseline | absent | None |
POST /api/agents/{name}/credentials/inject → {".env": "CANARY_VAR=ghost123\n"} |
present | 'ghost123' |
Delete the line via docker exec (non-mirroring path) |
gone | 'ghost123' ← ghost |
tr '\0' '\n' < /proc/<agent-server-pid>/environ | grep CANARY |
— | no match |
docker exec <container> python3 -c "...os.environ.get(...)" |
— | None |
Re-inject the cleaned .env (key line absent) |
gone | 'ghost123' ← still ghosted |
Re-inject with key present but empty (CANARY_VAR=) |
CANARY_VAR= |
'' (cleared) |
| Container restart | CANARY_VAR= |
None |
Two results worth calling out:
The obvious mitigation usually fails. The mirror loop only sets keys present in the file — it
has no delete phase — so a key deleted from .env is never removed from os.environ. Only
blanking the value (KEY=) clears the ghost. "Delete the stale line, then re-push credentials" is
the intuitive operator action and it leaves the runtime poisoned while returning success.
The last row proves the channels are independent. At restart the file literally contained
CANARY_VAR=, yet the fresh process had no such key — confirming .env is never loaded into the
agent-server process at all.
Acceptance Criteria
- A key removed from
.envno longer reaches subsequently-spawned executions (any write path:
credentials API, SSH,docker exec, or an agent editing its own.env) - The
.envfile is the authoritative source for credential values in the execution environment -
/api/credentials/reload-tokenstill rotatesCLAUDE_CODE_OAUTH_TOKENfor the next execution
(feat: credential rotation via hot-reload, not container recreate #1089 must not regress — see Technical Notes) -
EXECUTION_TAG_NAMEstill reaches every spawned process (bug: agent-server.py spins at ~83% CPU after claude CLI subprocess becomes defunct #407 orphan sweep) -
AGENT_RUNTIME,ANTHROPIC_API_KEY,GOOGLE_API_KEYstill resolve for platform code that
reads them from the process env - The
/api/credentials/injectmirror removes keys that are absent from the newly-written
.env, so re-injecting a cleaned file clears a deleted key - Regression test: inject a key, remove it from
.envout-of-band, assert a new execution does
not see it - Applied uniformly across all runtimes (Claude Code, Codex, Gemini)
Technical Notes
Mechanism
Mirror sites — docker/base-image/agent_server/routers/credentials.py:
POST /api/credentials/update—os.environ[var_name] = str(value)for every submitted keyPOST /api/credentials/inject— re-parses the written.envand mirrors every line
Spawn sites — all five pass env={**os.environ, EXECUTION_TAG_NAME: ...}, i.e. an explicit
snapshot of the mutated runtime env:
services/claude_code.py,services/headless_executor.py,services/codex_runtime.py,
services/gemini_runtime.py(×2)
(Historically these were bare Popen calls with no env=; the {**os.environ} form was added for
#407 orphan-tagging and is behaviourally identical for this issue.)
No counterweight — there is no dotenv anywhere in agent_server/, and
docker/base-image/startup.sh exports only GITHUB_PAT and CLAUDE_CODE_OAUTH_TOKEN, never the
general .env.
Note docker/base-image/agent_server/routers/files.py is not a divergence path — .env is in
its EDIT_PROTECTED_PATHS list and always has been.
⚠️ The obvious fix breaks #1089
The natural fix — spawn with env={**INITIAL_ENV, **parse(home/.env)} — would silently break
subscription-token rotation. POST /api/credentials/reload-token rotates the token by mutating
only the process env and deliberately does not write .env ("the subscription token is not a
.env credential"). Under that fix the rotated token is in neither source, so every execution after a
rotation would receive the stale token.
Suggested shape instead:
env = {
**INITIAL_ENV, # boot snapshot captured at module import
**RUNTIME_OVERRIDES, # explicit allowlist: CLAUDE_CODE_OAUTH_TOKEN, ANTHROPIC_API_KEY, ...
**parse_env_file(HOME / ".env"), # file is authoritative for credentials
EXECUTION_TAG_NAME: execution_id,
}with RUNTIME_OVERRIDES a small named dict the reload-token endpoint writes to, making precedence
explicit rather than implicit in global process state.
Simply deleting the mirror blocks is not viable: it would break #1089 and the credential
sanitizer refresh.
Amplifiers
- Boot re-push.
inject_assigned_credentials(src/backend/services/agent_service/lifecycle.py)
runs on every agent start and pushes.credentials.encthrough the mirroring/injectendpoint,
so a stale snapshot re-poisons the runtime env and rewrites.envon every boot. (Skipped for
subscription-mode agents, which is why a restart clears the ghost for those.) - Fleet-wide pushes.
src/backend/services/github_pat_propagation_service.pyreads an agent's
current.env, patches one line, and re-posts the whole file — mirroring every key in it.
A single global PAT rotation can therefore re-arm this across the fleet. Related: bug: global GitHub PAT rotation never reaches agents — propagation skips agents without .env and never re-templates the git remote #1967 is an
open bug in that same propagation path; fixing bug: global GitHub PAT rotation never reaches agents — propagation skips agents without .env and never re-templates the git remote #1967 will make this fire more often. - Sanitizer interaction.
agent_server/utils/credential_sanitizer.pybuilds its redaction set
from the union ofos.environand~/.env, so a ghosted value matching a sensitive-name pattern
(.*TOKEN.*,.*KEY.*, …) is scrubbed from the very transcripts an operator would use to spot
it — making a ghosted API key more invisible than a ghosted plain variable.
Diagnosability (suggested, cheap, high value)
Extend GET /api/credentials/status with a per-key drift report — key names only, no values:
{key, in_file, in_process_env, equal}. This turns the entire class from a multi-hour forensic hunt
into a single API call. The agent-server's uvicorn access logs also carry no timestamps, which made
correlating the originating credential push impossible after the fact.
Activity
dolho commentedon Aug 5, 2026
/claim
github-actions commentedon Aug 5, 2026
Claimed by @dolho. Label
status-in-progressadded.Next steps:
feature/1999-<short-slug>Fixes #1999fix(agent-server): keep .env parsing byte-faithful; re-point the ent#…
fix(agent-server): rebuild the execution env per spawn so a removed .…
fix(agent-server): keep .env parsing byte-faithful; re-point the ent#…
fix(github-pat): level every GITHUB_PAT line, not just the first (#2016…
fix(2010): gate the env-drift report, harden PROTECTED_KEYS, and pin …
fix(agent-server): rebuild the execution env per spawn so a removed .…
fix(credentials): make the .env quote encoding reversible (#2023) (#2030
fix(subscriptions): stop .env-resident ANTHROPIC_API_KEY shadowing su…
fix(sanitizer): redact the whole sk- key family, not three known pref…
fix(codex): materialise API-key auth.json, or every turn 401s (#2208) (…