Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 50 additions & 7 deletions hermes_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,25 +215,59 @@ def _warn_config_parse_failure(
# NOT a HERMES_* blanket: integration credentials (HERMES_GEMINI_*,
# HERMES_LANGFUSE_*, HERMES_SPOTIFY_*, ...) ARE allowed.
"HERMES_HOME", "HERMES_PROFILE", "HERMES_CONFIG", "HERMES_ENV",
"HERMES_CONFIG_PATH", "HERMES_ENV_PATH",
# MCP catalog trust root. Package-manager wrappers may still provide this
# in the process environment; only generic persistence writes are blocked.
"HERMES_OPTIONAL_MCPS",
# Hermes security policy / approval-routing context. These remain available
# through their dedicated CLI/config/session controls, but a generic
# credential writer must not persist them for the next process startup.
"HERMES_YOLO_MODE", "HERMES_ACCEPT_HOOKS", "HERMES_REDACT_SECRETS",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Block the complete execution-control class, not selected names. HERMES_OPTIONAL_MCPS is still writable here; mcp_catalog._catalog_root() trusts it as the catalog root, and a manifest from that directory can supply install.bootstrap, which _run_bootstrap() executes with shell=True. The shared writer also still accepts HERMES_COPILOT_ACP_COMMAND / HERMES_COPILOT_ACP_ARGS, which agent/copilot_acp_client.py uses to construct a subprocess invocation. Because save_env_value() updates os.environ immediately, these are live in the current dashboard process as well as future children. Define one authoritative non-writable set covering catalog/skill trust roots and the behavioral keys already identified by _PROFILE_MANAGED_ENV_KEYS, then add public /api/env regressions. Otherwise the new catalog schema blocks one route while equivalent execution paths remain open.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — I agree with the MCP-specific trust-root gap. Commit 6818ea0e4f adds HERMES_OPTIONAL_MCPS to the shared writer denylist, so authenticated /api/env writes can no longer replace the catalog root in either the current process or a later restart. The restriction is deliberately write-only: pre-existing .env values still load, and package-manager/process-supplied HERMES_OPTIONAL_MCPS still resolves. The public endpoint and both compatibility paths now have regression coverage (test_generic_env_endpoint_rejects_protected_key, test_preexisting_optional_mcps_override_still_loads, and test_process_supplied_catalog_root_remains_supported).

I did not fold all of _PROFILE_MANAGED_ENV_KEYS into this MCP PR. That set includes documented Copilot ACP command/path/base-URL overrides; blocking all of them through the generic writer would change an unrelated provider configuration surface and widen the blast radius for MCP users. The catalog route is closed against undeclared keys, and this follow-up closes its alternate MCP trust-root path. The Copilot/shared-writer execution-control class should be handled separately with its own compatibility analysis rather than being bundled into this MCP fix.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at exact head 6818ea0e4fb1820916a1f76bbc018cdb521cfadc: the MCP trust-root half is fixed, but this P1 is only partially closed. HERMES_OPTIONAL_MCPS is now protected and the Windows-name bypass is handled, but the same shared writer still accepts HERMES_COPILOT_ACP_COMMAND / HERMES_COPILOT_ACP_ARGS; agent/copilot_acp_client.py reads those values directly to choose the executable/argv for a subprocess. Because save_env_value() also updates the live process environment, the generic authenticated env-writing surface still has an execution-control path.

If that class is intentionally split out of this MCP patch, it needs an explicit interlock to a concrete follow-up rather than treating the original finding as closed. I am leaving this thread unresolved until either the shared boundary is closed here or that follow-up exists and this PR is scoped/proven as an MCP-only slice.

@andrexibiza andrexibiza Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved on exact head 6b94252f4226bed24f0a3152b5165e4f9486ec66. The PR now absorbs #91565 directly: HERMES_COPILOT_ACP_COMMAND and HERMES_COPILOT_ACP_ARGS are blocked by the shared writer, Windows aliases are covered, rejected public /api/env writes cannot change the live ACP command/argv resolvers, and pre-existing operator configuration remains readable. The original P1 execution-control finding is closed on this head.

"HERMES_INTERACTIVE", "HERMES_EXEC_ASK", "HERMES_GATEWAY_SESSION",
"HERMES_CRON_SESSION", "HERMES_SINGLE_QUERY_SESSION",
"HERMES_SESSION_KEY", "HERMES_SESSION_PLATFORM",
})


def _env_var_policy_name(key: str, *, is_windows: Optional[bool] = None) -> str:
"""Return the name used for environment policy comparisons.

Windows environment names are case-insensitive; POSIX names are not. The
explicit override keeps both semantics directly testable without pretending
the test interpreter is running on another host OS.
"""
windows = _IS_WINDOWS if is_windows is None else is_windows
return key.upper() if windows else key


def _reject_denylisted_env_var(key: str) -> None:
"""Raise if ``key`` is in :data:`_ENV_VAR_NAME_DENYLIST`.

Centralised so both the regular and "secure" env writers share the
same gate, and so the message is consistent for callers.
"""
if key in _ENV_VAR_NAME_DENYLIST:
if _env_var_policy_name(key) in _ENV_VAR_NAME_DENYLIST:
raise ValueError(
f"Environment variable {key!r} is on the writer denylist. "
"Names that influence subprocess execution (LD_PRELOAD, "
"PYTHONPATH, PATH, EDITOR, ...) or Hermes runtime location "
"(HERMES_HOME, HERMES_PROFILE, ...) cannot be persisted via "
"and security policy (HERMES_HOME, HERMES_YOLO_MODE, ...) "
"cannot be persisted via "
"the env writer. If you really need this, edit "
"~/.hermes/.env directly."
)


def validate_env_var_name_for_write(key: str) -> None:
"""Validate an environment name before a generic persistence write.

Exposed separately from :func:`save_env_value` so batch-style callers can
validate their complete request before writing the first value.
"""
if not _ENV_VAR_NAME_RE.match(key):
raise ValueError(f"Invalid environment variable name: {key!r}")
_reject_denylisted_env_var(key)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Canonicalize the name before the policy lookup. _reject_denylisted_env_var() uses exact-string membership, but Windows environment names are case-insensitive: Path or Hermes_Yolo_Mode pass this validation and then os.environ[key] = value aliases them to PATH / HERMES_YOLO_MODE in the current process and child processes. Normalize before denylist membership (and before matching/updating existing .env assignments), or reject case-insensitive collisions, with mixed-case Windows-semantics regression coverage.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Commit 6818ea0e4f now canonicalizes names for policy lookup with native host semantics: uppercase on Windows, identity on POSIX. The same rule is applied when matching existing .env assignments, so Windows cannot create case-variant duplicates such as Path beside PATH, while Linux/macOS retain case-sensitive behavior.

Coverage includes pure Windows/POSIX policy tests without faking the host OS, export and plain assignment matching, and a native @pytest.mark.windows_only writer regression for Hermes_Yolo_Mode. The focused affected suite passes 154 tests locally (the one native Windows test is running on the Windows CI lane), plus Ruff and git diff --check.

@andrexibiza andrexibiza Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved on exact head 6b94252f4226bed24f0a3152b5165e4f9486ec66. Policy lookup and existing .env assignment matching use Windows-case-insensitive semantics while POSIX remains case-sensitive; mixed-case aliases now cover the MCP trust root, security controls, and Copilot ACP execution controls. This P1 finding is closed.


_LAST_EXPANDED_CONFIG_BY_PATH: Dict[str, Any] = {}
# (path, mtime_ns, size) -> cached expanded config dict.
# load_config() returns a deepcopy of the cached value when the file
Expand Down Expand Up @@ -4190,7 +4224,12 @@ def _quote_env_value(value: str) -> str:
return f'"{escaped}"'


def _env_line_defines_key(line: str, key: str) -> bool:
def _env_line_defines_key(
line: str,
key: str,
*,
is_windows: Optional[bool] = None,
) -> bool:
"""True when a .env line assigns ``key`` — plain or ``export``-prefixed.

``load_env()`` accepts the bash-compatible ``export KEY=value`` form
Expand All @@ -4201,7 +4240,13 @@ def _env_line_defines_key(line: str, key: str) -> bool:
stripped = line.strip()
if stripped.startswith("export "):
stripped = stripped[7:].lstrip()
return stripped.startswith(f"{key}=")
assigned_key, separator, _value = stripped.partition("=")
if not separator:
return False
return _env_var_policy_name(
assigned_key,
is_windows=is_windows,
) == _env_var_policy_name(key, is_windows=is_windows)


def save_env_value(key: str, value: str):
Expand All @@ -4222,9 +4267,7 @@ def save_env_value(key: str, value: str):
file=sys.stderr,
)
return
if not _ENV_VAR_NAME_RE.match(key):
raise ValueError(f"Invalid environment variable name: {key!r}")
_reject_denylisted_env_var(key)
validate_env_var_name_for_write(key)
value = value.replace("\n", "").replace("\r", "")
# API keys / tokens must be ASCII — strip non-ASCII with a warning.
value = _check_non_ascii_credential(key, value)
Expand Down
27 changes: 25 additions & 2 deletions hermes_cli/web_routers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,8 +503,31 @@ async def install_mcp_catalog_entry(body: MCPCatalogInstall, profile: Optional[s
if entry is None:
raise HTTPException(status_code=404, detail=f"No catalog entry '{name}'")

# Persist any supplied env vars first (catalog entries declare which names
# they need; we only write the ones the user provided).
# Catalog credentials are a closed schema: configuring one MCP must not
# become a generic write primitive for unrelated process environment.
declared_env = {spec.name for spec in (entry.auth.env or [])}
undeclared_env = sorted(set(body.env) - declared_env)
if undeclared_env:
raise HTTPException(
status_code=400,
detail=(
f"Catalog entry '{name}' does not declare environment "
f"variable(s): {', '.join(undeclared_env)}"
),
)

# Validate the complete map before the first write. This preserves the
# existing writer/install flow while ensuring a mixed valid+invalid request
# cannot partially persist credentials.
from hermes_cli.config import validate_env_var_name_for_write

try:
for key in body.env:
validate_env_var_name_for_write(key)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc

# Persist any supplied, declared env vars first.
effective_profile = body.profile or profile
if body.env:
def _write_env():
Expand Down
81 changes: 75 additions & 6 deletions tests/hermes_cli/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1043,7 +1043,7 @@ def test_migrate_preserves_custom_providers_and_no_defaults_dump(self, tmp_path)
class TestEnvWriteDenylist:
"""``save_env_value`` refuses to persist env-var names that
influence how subprocesses execute — ``LD_PRELOAD``, ``PYTHONPATH``,
``PATH``, ``EDITOR``, etc. — or any ``HERMES_*`` runtime flag.
``PATH``, ``EDITOR``, etc. — or selected Hermes runtime/security controls.

The dashboard exposes ``PUT /api/env`` to any authed caller (and
the session token lives in the SPA's HTML where any future plugin
Expand Down Expand Up @@ -1073,15 +1073,84 @@ def _hermes_home(self, tmp_path, monkeypatch):
],
)
def test_hermes_integration_keys_still_writable(self, allowed_key):
"""``HERMES_*`` overall is NOT blocked — only the four runtime
location names (HOME/PROFILE/CONFIG/ENV) are. Integration
credentials following the ``HERMES_*`` convention must keep
working or we'd regress every provider setup wizard that
currently writes one of these (auth.py, Spotify, Langfuse, …)."""
"""``HERMES_*`` overall is NOT blocked.

Integration credentials following that convention must keep working
or we'd regress provider setup flows (auth.py, Spotify, Langfuse, …).
"""
save_env_value(allowed_key, "test-value-123")
env = load_env()
assert env[allowed_key] == "test-value-123"

@pytest.mark.parametrize(
"protected_key",
[
"HERMES_CONFIG_PATH",
"HERMES_ENV_PATH",
"HERMES_OPTIONAL_MCPS",
"HERMES_YOLO_MODE",
"HERMES_ACCEPT_HOOKS",
"HERMES_REDACT_SECRETS",
"HERMES_INTERACTIVE",
"HERMES_EXEC_ASK",
"HERMES_GATEWAY_SESSION",
"HERMES_CRON_SESSION",
"HERMES_SINGLE_QUERY_SESSION",
"HERMES_SESSION_KEY",
"HERMES_SESSION_PLATFORM",
],
)
def test_hermes_security_control_keys_are_not_writable(self, protected_key):
"""Generic writers must not persist runtime or approval controls."""
with pytest.raises(ValueError, match="denylist"):
save_env_value(protected_key, "1")

assert protected_key not in load_env()

def test_preexisting_optional_mcps_override_still_loads(self, tmp_path):
"""The writer gate must not migrate or ignore operator-owned .env state."""
from hermes_cli.config import invalidate_env_cache

catalog = tmp_path / "custom-mcp-catalog"
(tmp_path / ".env").write_text(
f"HERMES_OPTIONAL_MCPS={catalog}\n",
encoding="utf-8",
)
invalidate_env_cache()

assert load_env()["HERMES_OPTIONAL_MCPS"] == str(catalog)

@pytest.mark.parametrize(
("key", "expected"),
[
("Path", "PATH"),
("Hermes_Yolo_Mode", "HERMES_YOLO_MODE"),
("Hermes_Optional_Mcps", "HERMES_OPTIONAL_MCPS"),
],
)
def test_windows_policy_names_are_case_insensitive(self, key, expected):
from hermes_cli.config import _env_var_policy_name

assert _env_var_policy_name(key, is_windows=True) == expected

def test_posix_policy_names_remain_case_sensitive(self):
from hermes_cli.config import _env_var_policy_name

assert _env_var_policy_name("Path", is_windows=False) == "Path"

@pytest.mark.parametrize("prefix", ["", "export "])
def test_windows_env_assignment_matching_is_case_insensitive(self, prefix):
from hermes_cli.config import _env_line_defines_key

line = f"{prefix}Path=C:\\Windows\\System32\n"
assert _env_line_defines_key(line, "PATH", is_windows=True)
assert not _env_line_defines_key(line, "PATH", is_windows=False)

@pytest.mark.windows_only
def test_windows_writer_rejects_mixed_case_protected_name(self):
with pytest.raises(ValueError, match="denylist"):
save_env_value("Hermes_Yolo_Mode", "1")



def test_save_env_value_secure_inherits_denylist(self):
Expand Down
Loading
Loading