mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 03:16:20 +08:00
## Description `headroom install apply --scope user` (and `--scope system`) writes a managed `export` block into `~/.bashrc`, `~/.zshrc` and `~/.profile` (or the `/etc` equivalents). Two bugs in `headroom/install/providers.py` meant the values in that block didn't survive: 1. **No shell quoting.** `_env_block()` wrote `export NAME="value"` with no escaping, so a `$`, `"` or backtick in a value is expanded or breaks the line when the shell sources the file. For example, `--env HTTPS_PROXY=http://bob:pa$$w0rd@proxy:3128` comes back as `http://bob:pa43794w0rd@proxy:3128` (`$$` is the shell's PID), and `{"a": "b"}` comes back as `{a: b}`. 2. **The block was used as a regex template on re-apply.** When the block already exists, `_merge_marker_block()` calls `pattern.sub(block, existing)`, so backslashes in the new block are parsed as escapes. Re-running `install apply` with a value like `D:\work\headroom` or `\d+` raises `re.error: bad escape \w` and the install aborts. The supervisor runner script in `install/supervisors.py` already writes the same values with `shlex.quote`, so only the shell-rc path was affected. Closes: N/A (no matching issue found) ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - `headroom/install/providers.py`: `_env_block()` writes `export NAME=<shlex.quote(value)>`. Plain values such as `8787` or `http://127.0.0.1:8787` stay unquoted; anything with shell metacharacters is single-quoted. - `headroom/install/providers.py`: `_merge_marker_block()` passes a callable to `pattern.sub`, so the block is inserted as literal text. - `tests/test_install/test_providers.py`: `test_unix_env_block_round_trips_shell_special_values` applies a block with `$$`, double quotes and backticks, re-applies it with a backslash value added, then sources the file with real `bash` and checks every value comes back byte for byte and that there is still exactly one block. ## Testing - [x] Unit tests pass (`pytest`): `tests/test_install/`, not the full suite - [x] Linting passes (`ruff check .`): on the changed files - [ ] Type checking passes (`mypy headroom`): not run - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output New test on `main` (fix reverted, test kept) fails on the re-apply crash: ```text $ python -m pytest tests/test_install/test_providers.py -q -k round_trips E re.error: bad escape \d at position 185 (line 5, column 38) ======================= 1 failed, 54 deselected in 4.45s ======================= ``` With only the `re.sub` half of the fix, it fails on the quoting half: ```text E At index 0 diff: 'http://bob:pa31588w0rd@proxy:3128' != 'http://bob:pa$$w0rd@proxy:3128' ======================= 1 failed, 54 deselected in 4.01s ======================= ``` With the full fix: ```text $ python -m pytest tests/test_install -q ======================= 251 passed, 13 skipped in 45.17s ======================= $ ruff check headroom/install/providers.py tests/test_install/test_providers.py All checks passed! $ ruff format --check headroom/install/providers.py tests/test_install/test_providers.py 2 files already formatted ``` ## Real Behavior Proof - Environment: macOS 27.0.1 (arm64), Python 3.12.11, source tree on this branch (native `headroom._core` from the 0.41.0 wheel), `HOME` pointed at a fresh temp dir, bash 3.2 and zsh 5.9 from macOS - Exact command / steps: built a real user-scope manifest with `headroom.install.planner.build_manifest(preset="persistent-service", scope="user", targets=["claude"], extra_env={"HTTPS_PROXY": "http://bob:pa$$w0rd@proxy:3128", "HEADROOM_WORKSPACE_DIR": r"D:\work\headroom"})` (what `install apply --env` produces) and ran `headroom.install.providers.apply_mutations()` twice (first install, then a re-run), then sourced the written `~/.bashrc` in `bash` and `zsh` and printed both variables. Same script on `main` and on this branch. - Observed result: on `main` the second apply fails with `bad escape \w` and both shells read the proxy password as `pa43794w0rd`; on this branch both applies succeed and both shells read the values exactly. ```text == main apply #1: ok apply #2: error: bad escape \w at position 356 (line 10, column 34) export HTTPS_PROXY="http://bob:pa$$w0rd@proxy:3128" bash sees: ['http://bob:pa43794w0rd@proxy:3128', 'D:\\work\\headroom'] zsh sees: ['http://bob:pa43804w0rd@proxy:3128', 'D:\\work\\headroom'] == this branch apply #1: ok apply #2: ok export HTTPS_PROXY='http://bob:pa$$w0rd@proxy:3128' export HEADROOM_WORKSPACE_DIR='D:\work\headroom' export ANTHROPIC_BASE_URL=http://127.0.0.1:8787 bash sees: ['http://bob:pa$$w0rd@proxy:3128', 'D:\\work\\headroom'] zsh sees: ['http://bob:pa$$w0rd@proxy:3128', 'D:\\work\\headroom'] ``` - Not tested: the full `headroom install apply` CLI end to end (it would also install a launchd service on this machine, so I called the same planner + `apply_mutations` functions it uses); fish shell; system scope (`/etc/*`); Windows (the PowerShell path is separate and unchanged). ## Runtime Rollout Safety - Rollout-managed feature(s): none - Minimum rollout channel: N/A - Stable/default behavior changed: values in the managed shell block are now shell-quoted (`export X=8787` instead of `export X="8787"`); what the shell ends up with is the same for plain values and now correct for values with `$`, `"`, backticks or backslashes. Existing blocks are rewritten on the next apply; `install remove` matches on the markers, so it is unaffected. - Kill switch / disable path: N/A - Unsafe override required: no - Qualification impact: none - Rollback path: revert this commit ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Additional Notes Docs unchecked: no user-facing docs describe the block's quoting. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4289" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> ### Reviewer-requested commit history correction Reworded the merge commit as `chore: merge upstream main for aiohttp remediation`, preserving both merge parents and the exact final source tree (`e39ceb04133a87face651962106bc843d506d8ac`). The resulting head is `9a4d01111e788d132b42d37f8f65a5fd88f70d37`. Commitlint passes over the repaired contribution range. This update changes commit metadata only; previous source validation is unchanged. The documented upload-hook exception was used for this metadata-only repair; full native checks and required hosted security CI are not claimed as passing. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: JD Davis <mxjerrett@gmail.com>
104 lines
3.6 KiB
Python
104 lines
3.6 KiB
Python
"""Real-shell regression controls for the init E2E environment assertions."""
|
|
|
|
import json
|
|
import os
|
|
import shutil
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from e2e._lib import CaseContext
|
|
from e2e.init.run import _verify_copilot_global
|
|
from headroom.install.providers import _env_block
|
|
|
|
pytestmark = pytest.mark.skipif(
|
|
os.name != "posix" or shutil.which("bash") is None,
|
|
reason="The Docker init E2E oracle requires a native POSIX Bash",
|
|
)
|
|
|
|
EXPECTED = {
|
|
"COPILOT_PROVIDER_TYPE": "openai",
|
|
"COPILOT_PROVIDER_BASE_URL": "http://127.0.0.1:9005/v1",
|
|
"COPILOT_PROVIDER_WIRE_API": "completions",
|
|
}
|
|
|
|
|
|
@pytest.fixture
|
|
def copilot_context(tmp_path: Path) -> CaseContext:
|
|
home = tmp_path / "home with spaces"
|
|
(home / ".copilot").mkdir(parents=True)
|
|
config = {
|
|
"hooks": {
|
|
"SessionStart": [{"command": "headroom init hook ensure --profile init-user"}],
|
|
"PreToolUse": [],
|
|
}
|
|
}
|
|
(home / ".copilot" / "config.json").write_text(
|
|
json.dumps(config), encoding="utf-8", newline="\n"
|
|
)
|
|
log = tmp_path / "shim-log.jsonl"
|
|
calls = [
|
|
["plugin", "marketplace", "add", "/workspace"],
|
|
["plugin", "install", "headroom@headroom-marketplace"],
|
|
]
|
|
log.write_text(
|
|
"".join(json.dumps({"tool": "copilot", "argv": argv}) + "\n" for argv in calls),
|
|
encoding="utf-8",
|
|
newline="\n",
|
|
)
|
|
for name in [".bashrc", ".zshrc", ".profile"]:
|
|
(home / name).write_text(_env_block(EXPECTED), encoding="utf-8", newline="\n")
|
|
return CaseContext(
|
|
name="seq_copilot_global",
|
|
home=home,
|
|
project=tmp_path,
|
|
shim_dir=tmp_path,
|
|
shim_log=log,
|
|
stdout="",
|
|
stderr="",
|
|
exit_code=0,
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("style", ["producer", "double", "single"])
|
|
def test_copilot_e2e_accepts_equivalent_export_spellings(
|
|
copilot_context: CaseContext, style: str
|
|
) -> None:
|
|
if style != "producer":
|
|
quote = '"' if style == "double" else "'"
|
|
content = "\n".join(
|
|
f"export {name}={quote}{value}{quote}" for name, value in EXPECTED.items()
|
|
)
|
|
for name in [".bashrc", ".zshrc", ".profile"]:
|
|
(copilot_context.home / name).write_text(content, encoding="utf-8", newline="\n")
|
|
_verify_copilot_global(copilot_context)
|
|
|
|
|
|
@pytest.mark.parametrize("shell_file", [".bashrc", ".zshrc", ".profile"])
|
|
@pytest.mark.parametrize("mutation", ["missing", "unexported", "wrong", "source-failure"])
|
|
def test_copilot_e2e_rejects_invalid_runtime_environment(
|
|
copilot_context: CaseContext, monkeypatch: pytest.MonkeyPatch, shell_file: str, mutation: str
|
|
) -> None:
|
|
# Ambient variables must never turn a missing/unexported setting into a pass.
|
|
for name, value in EXPECTED.items():
|
|
monkeypatch.setenv(name, value)
|
|
startup = copilot_context.home / "ambient-startup"
|
|
startup.write_text(_env_block(EXPECTED), encoding="utf-8", newline="\n")
|
|
monkeypatch.setenv("BASH_ENV", str(startup))
|
|
content = _env_block(EXPECTED)
|
|
if mutation == "missing":
|
|
content = "\n".join(
|
|
line
|
|
for line in content.splitlines()
|
|
if not line.startswith("export COPILOT_PROVIDER_TYPE=")
|
|
)
|
|
elif mutation == "unexported":
|
|
content = content.replace("export COPILOT_PROVIDER_TYPE=", "COPILOT_PROVIDER_TYPE=")
|
|
elif mutation == "wrong":
|
|
content = content.replace("COPILOT_PROVIDER_TYPE=openai", "COPILOT_PROVIDER_TYPE=wrong")
|
|
else:
|
|
content = "return 23\n" + content
|
|
(copilot_context.home / shell_file).write_text(content, encoding="utf-8", newline="\n")
|
|
with pytest.raises(AssertionError):
|
|
_verify_copilot_global(copilot_context)
|