Skip to content

Command-scoped secrets persist across TerminalExecutor session boundaries #2944

Closed as not planned

Description

@fasrm

The TerminalExecutor exports secrets into a persistent shell session before executing a command. Due to the persistent nature of the session, secrets intended for a single authorized command remain available to subsequent unrelated commands.

This creates a mismatch between the command-scoped secret model and the session-scoped execution model.

PoC 1
from openhands.tools.terminal.definition import TerminalAction
from openhands.tools.terminal.impl import TerminalExecutor

class FakeSecretRegistry:
def get_secrets_as_env_vars(self, command):
if "needs_secret" in command:
return {"FAKE_AGENT_SECRET": "fake-secret-value"}
return {}

def mask_secrets_in_output(self, text):
    return text.replace("fake-secret-value", "***MASKED***")

class FakeState:
secret_registry = FakeSecretRegistry()

class FakeConversation:
state = FakeState()

executor = TerminalExecutor(working_dir=".", terminal_type="subprocess")
conv = FakeConversation()

Step 1: authorized command (receives secret)
executor(
TerminalAction(command="echo needs_secret >/dev/null"),
conversation=conv,
)

Step 2: unrelated command (should not receive secret)
obs = executor(
TerminalAction(
command="python3 -c "import os; print('present=', 'FAKE_AGENT_SECRET' in os.environ)""
),
conversation=conv,
)

print(obs.text)
executor.close()

Observed Output
present= True

PoC 2
!/usr/bin/env python3
"""
PoC: Command-scoped secrets persist across OpenHands TerminalExecutor sessions.

This PoC uses only fake secrets and does not perform any network exfiltration.
"""

import os
import re

from openhands.tools.terminal.definition import TerminalAction
from openhands.tools.terminal.impl import TerminalExecutor

FAKE_SECRETS = {
"FAKE_AWS_KEY": "AKIAIOSFODNN7EXAMPLE",
"FAKE_GCP_TOKEN": "ya29.fake-gcp-token",
"FAKE_GITHUB_PAT": "ghp_fakeGithubToken123",
"FAKE_DOCKER_PASS": "dckr_pat_fake123",
}

class FakeSecretRegistry:
def get_secrets_as_env_vars(self, command: str):
"""
Simulates command-scoped secret authorization.

    Only commands containing one of the expected deployment/build keywords
    should receive the fake secrets.
    """
    allowed_triggers = ("needs_deploy", "needs_build", "needs_cloud_access")

    if any(trigger in command.lower() for trigger in allowed_triggers):
        return FAKE_SECRETS.copy()

    return {}

def mask_secrets_in_output(self, text: str):
    """
    Simulates OpenHands secret masking behavior.
    """
    for secret_value in FAKE_SECRETS.values():
        text = re.sub(re.escape(secret_value), "***MASKED***", text)

    return text

class FakeState:
secret_registry = FakeSecretRegistry()

class FakeConversation:
state = FakeState()

def execute(executor: TerminalExecutor, command: str, conversation: FakeConversation):
obs = executor(
TerminalAction(command=command),
conversation=conversation,
)
return obs.text

def main():
executor = TerminalExecutor(
working_dir=".",
terminal_type="subprocess",
)
conversation = FakeConversation()

print("=== OpenHands TerminalExecutor Secret Persistence PoC ===\n")

print("[1] Execute a command that is authorized to receive secrets")
authorized_output = execute(
    executor,
    "echo needs_deploy >/dev/null && echo authorized command completed",
    conversation,
)
print(authorized_output)

print("[2] Execute an unrelated command that does NOT request secret access")
unrelated_output = execute(
    executor,
    (
        "python3 - <<'PY'\n"
        "import os\n"
        "names = [name for name in os.environ if name.startswith('FAKE_')]\n"
        "print('fake_secret_names_present=', sorted(names))\n"
        "print('fake_secret_count=', len(names))\n"
        "for name in sorted(names):\n"
        "    print(name + '=' + os.environ.get(name, ''))\n"
        "PY"
    ),
    conversation,
)
print(unrelated_output)

print("[3] Execute through a child shell to show inheritance by subprocesses")
child_shell_output = execute(
    executor,
    "bash -lc 'env | grep ^FAKE_ | sort'",
    conversation,
)
print(child_shell_output)

print("[4] Reset terminal session and verify secrets are cleared")
reset_output = executor(
    TerminalAction(command="", reset=True),
    conversation=conversation,
)
print(reset_output.text)

after_reset_output = execute(
    executor,
    (
        "python3 - <<'PY'\n"
        "import os\n"
        "names = [name for name in os.environ if name.startswith('FAKE_')]\n"
        "print('fake_secret_count_after_reset=', len(names))\n"
        "PY"
    ),
    conversation,
)
print(after_reset_output)

executor.close()

if name == "main":
main()

Output:
$ uv run python poc_report_safe.py
+----------------------------------------------------------------------+
| OpenHands SDK v1.18.1 |
| |
| Report a bug: github.com/OpenHands/software-agent-sdk/issues |
| Get help: openhands.dev/joinslack |
| Scale up: openhands.dev/product/sdk |
| |
| Set OPENHANDS_SUPPRESS_BANNER=1 to hide this message |
+----------------------------------------------------------------------+

[04/24/26 13:07:56] INFO Using forced SubprocessTerminal factory.py:98
[04/24/26 13:07:56] INFO Using shell: subprocess_terminal.py:136
/usr/bin/bash
[04/24/26 13:07:57] INFO TerminalExecutor initialized with impl.py:96
working_dir: ., username: None,
terminal_type: subprocess
=== OpenHands TerminalExecutor Secret Persistence PoC ===

[1] Execute a command that is authorized to receive secrets
authorized command completed

[2] Execute an unrelated command that does NOT request secret access
python3 - <<'PY'
import os
names = [name for name in os.environ if name.startswith('FAKE_')]
print('fake_secret_names_present=', sorted(names))
print('fake_secret_count=', len(names))
for name in sorted(names):
print(name + '=' + os.environ.get(name, ''))
PY
fake_secret_names_present= ['FAKE_AWS_KEY', 'FAKE_DOCKER_PASS', 'FAKE_GCP_TOKEN', 'FAKE_GITHUB_PAT']
fake_secret_count= 4
FAKE_AWS_KEY=MASKED
FAKE_DOCKER_PASS=MASKED
FAKE_GCP_TOKEN=MASKED
FAKE_GITHUB_PAT=MASKED

[3] Execute through a child shell to show inheritance by subprocesses
FAKE_AWS_KEY=MASKED
FAKE_DOCKER_PASS=MASKED
FAKE_GCP_TOKEN=MASKED
FAKE_GITHUB_PAT=MASKED

[4] Reset terminal session and verify secrets are cleared
[04/24/26 13:07:59] WARNING tmux is not installed. Falling back factory.py:130
to subprocess-based terminal, which
may be less stable. For best agent
performance, install tmux (e.g.
apt-get install tmux or brew install tmux).
/home/franciny-rojas/Desktop/research/real-ai-agents/software-agent-sdk/openhands-tools/openhands/tools/terminal/impl.py:287: UserWarning: tmux is not installed. Falling back to subprocess-based terminal, which may be less stable. For best agent performance, install tmux (e.g. apt-get install tmux or brew install tmux).
self._session = create_terminal_session(
[04/24/26 13:07:59] INFO Using shell: subprocess_terminal.py:136
/usr/bin/bash
[04/24/26 13:08:00] INFO Terminal session reset successfully impl.py:296
with working_dir: .
Terminal session has been reset. All previous environment variables and session state have been cleared.

python3 - <<'PY'
import os
names = [name for name in os.environ if name.startswith('FAKE_')]
print('fake_secret_count_after_reset=', len(names))
PY
fake_secret_count_after_reset= 0

Additional Observation
Even though secret values are masked in output:

FAKE_AGENT_SECRET=MASKED

the variable still exists in the environment and is accessible to:

subsequent commands
child processes / subprocesses
Root Cause

Secrets are exported into the shell via:

export KEY=value

but the shell session is persistent:

environment variables persist between commands

As a result, secrets outlive the command they were authorized for.

Impact
Secrets may be reused by later unrelated commands
Child processes inherit previously authorized secrets
Breaks command-level secret isolation assumptions

Note: masking protects output display, but does not enforce secret lifetime or isolation.

Activity

  1. added
    bug
    on Apr 27, 2026
  2. all-hands-bot commented on Apr 27, 2026

    @all-hands-bot
    Collaborator

    [Automatic Post]: This issue has been waiting for triage. @xingyaoww @neubig @enyst, could you please take a look and add the appropriate priority label when you have a chance?

  3. neubig commented on Apr 27, 2026

    @neubig
    Member

    Interesting use case, I'll mark this as an enhancement! I think that we'd need to develop some concept of secret scope, which is non-trivial. We'd welcome well-thought-out proposals on how to make it possible to specify secrets for a smaller scope than a single conversation.

  4. added
    enhancement
    and removed
    bug
    on Apr 27, 2026
  5. fasrm commented on Apr 27, 2026

    @fasrm
    Author

    Thanks for the clarification — that makes sense.

    My concern was mainly around the mismatch between the command-scoped secret model and the persistent session behavior, which could lead integrators to assume stricter isolation than what is actually enforced.

    Happy to propose possible approaches for per-command secret scoping if helpful.

  6. github-actions commented on Jun 7, 2026

    @github-actions
    Contributor

    This issue is stale because it has been open for 40 days with no activity. Remove the stale label or leave a comment, otherwise it will be closed in 10 days.

  7. github-actions commented on Jun 17, 2026

    @github-actions
    Contributor

    This issue was automatically closed due to 50 days of inactivity. We do this to help keep the issues somewhat manageable and focus on active issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Staleenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions