Skip to content

bug: credential injects mirror .env into the agent-server long-lived process env — a removed key keeps reaching every execution, invisible to /proc and docker exec #1999

Closed

Description

@webmixgamer

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 .env no longer reaches subsequently-spawned executions (any write path:
    credentials API, SSH, docker exec, or an agent editing its own .env)
  • The .env file is the authoritative source for credential values in the execution environment
  • /api/credentials/reload-token still rotates CLAUDE_CODE_OAUTH_TOKEN for the next execution
    (feat: credential rotation via hot-reload, not container recreate #1089 must not regress — see Technical Notes)
  • EXECUTION_TAG_NAME still 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_KEY still resolve for platform code that
    reads them from the process env
  • The /api/credentials/inject mirror 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 .env out-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 key
  • POST /api/credentials/inject — re-parses the written .env and 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

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

  1. added
    priority-p1
    type-bug
    theme-security
    complexity-medium
    status-ready
    on Aug 4, 2026
  2. dolho commented on Aug 5, 2026

    @dolho
    Contributor

    /claim

  3. added
    status-in-progress
    and removed
    status-ready
    on Aug 5, 2026
  4. github-actions commented on Aug 5, 2026

    @github-actions

    Claimed by @dolho. Label status-in-progress added.

    Next steps:

    1. Create branch: feature/1999-<short-slug>
    2. Implement the feature
    3. Open a PR with Fixes #1999
  5. added
    status-in-dev
    and removed
    status-in-progress
    on Aug 10, 2026
  6. removed
    status-in-dev
    on Aug 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

complexity-mediumpriority-p1theme-securitytype-bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions