fix(install): keep an explicitly empty dashboard allowlist on Windows PowerShell 5.1 (#4012)

## Description

On Windows PowerShell 5.1, the persistent Docker install ignores an
explicitly empty `HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS` and
trusts the Docker bridge gateway anyway.

`Add-DashboardGatewayEnv` is meant to skip its gateway default whenever
the variable is set, including set to an empty string. That empty case
is the documented way to opt out, and
`test_powershell_native_installer_supports_persistent_docker_lifecycle`
asserts it. The function checks with `Test-Path Env:...`. But
`Get-PassthroughEnvArgs` enumerates `Env:` first, and once that has
happened Windows PowerShell 5.1 reports an empty variable as **unset**
through both `Test-Path` and `[Environment]::GetEnvironmentVariable`.
The enumeration itself still lists it. The result is that `docker run`
gets both arguments:

```
--env HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS                 # passthrough of the empty value
--env HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS=172.17.0.1/32   # gateway default, wins
```

Standalone repro in Windows PowerShell 5.1, with a variable inherited as
empty from the parent process:

```
first, in function     Test-Path=True  GetEnvVar!=null=True  Contains=True
after Get-ChildItem    Test-Path=False GetEnvVar!=null=False Contains=True
```

CI's `windows-native-wrapper` job doesn't catch this because
`_powershell_executable()` prefers `pwsh`, which is unaffected. Windows
PowerShell 5.1 is still what a stock Windows install runs as
`powershell`.

The bash installer already gets this right
(`${HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS+x}`).

## 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

- `scripts/install.ps1`: `Add-DashboardGatewayEnv` now finds the
variable through the same `Get-ChildItem Env:` enumeration that
`Get-PassthroughEnvArgs` uses, so the gateway default is skipped exactly
when the passthrough forwards the caller's value.
- `tests/test_install/test_native_installers.py`: new
`test_powershell_dashboard_gateway_default_respects_explicit_allowlist`.
It AST-extracts both functions from the wrapper template, the same
approach as the existing `Ensure-PathEntry` harness, and runs them in
installer order with `docker` stubbed. It's parametrized over
`powershell` and `pwsh` × unset / configured / explicitly empty, so CI's
Windows runner now covers 5.1 as well.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`): no Python source changed
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

Before the fix (Windows PowerShell 5.1):

```text
test_powershell_dashboard_gateway_default_respects_explicit_allowlist[unset-windows-powershell] PASSED
test_powershell_dashboard_gateway_default_respects_explicit_allowlist[configured-windows-powershell] PASSED
test_powershell_dashboard_gateway_default_respects_explicit_allowlist[explicitly-empty-windows-powershell] FAILED
E   assert ('HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS=172.17.0.1/32' in [...]) is False
```

The existing end-to-end test fails on `main` under 5.1 for the same
reason:

```text
FAILED tests/test_install/test_native_installers.py::test_powershell_native_installer_supports_persistent_docker_lifecycle
    assert not any(arg.startswith(f"{trusted_cidrs}=") for arg in install_call)
    # offending args: ['HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS', 'HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS=172.17.0.1/32']
```

After the fix:

```text
$ python -m pytest tests/test_install/test_native_installers.py -q
10 passed, 5 skipped in 73.90s

$ ruff check tests/test_install/test_native_installers.py
All checks passed!
```

## Real Behavior Proof

- Environment: Windows 11 (10.0.26200), Windows PowerShell
5.1.26100.9444 (no pwsh installed), Python 3.12.3, headroom `main` @
dea9092e.
- Exact command / steps: `python -m pytest
tests/test_install/test_native_installers.py -q`. This includes
`test_powershell_native_installer_supports_persistent_docker_lifecycle`,
which runs the real `scripts/install.ps1` and then the generated
`headroom.ps1 install apply` against the repo's fake Docker shim, with
the variable set to `""`.
- Observed result: before the fix, the persistent container's `docker
run` carried
`HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS=172.17.0.1/32` despite
the empty opt-out. After the fix, only the name-only passthrough is
sent, and the container env holds `""`.
- Not tested: a real Docker daemon (only the fake Docker shim was used);
`pwsh` 7 locally, since it isn't installed here, though CI's Windows
runner has it and the new test covers it there; macOS/Linux, where the
bash installer is unaffected.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: only for Windows PowerShell 5.1 users
who set the allowlist to an empty string. They now get the opt-out they
asked for. Unset and non-empty values behave as before.
- 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: no doc
change needed
- [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`

## Additional Notes

Unrelated and not fixed here:
`tests/test_install/test_planner.py::test_build_manifest_for_persistent_service_uses_safe_model_backends`
also fails on a Windows host. `build_manifest` rewrites
`persistent-service` to `persistent-task` on Windows (#2552), so the
service-only CPU/ONNX defaults from #3646 aren't applied, and the test
doesn't pin `sys.platform`. CI never runs `test_planner.py` on Windows.
Happy to send a separate PR if you'd like the test pinned, or the
defaults keyed off the requested preset.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Nishil Rathod
2026-10-08 10:09:05 -05:00
committed by GitHub
co-authored by Claude Opus 5.5 JD Davis
parent 51ec6e8ffe
commit c195a1220f
2 changed files with 105 additions and 1 deletions
+7 -1
View File
@@ -402,7 +402,13 @@ function Add-DashboardGatewayEnv {
# 127.0.0.1. Trust only that exact gateway by default so the dashboard's
# metadata gate works for the first-party persistent Docker preset while
# preserving an explicitly configured allowlist.
if (Test-Path Env:HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS) {
#
# An explicitly empty allowlist counts as configured. Look it up the way
# Get-PassthroughEnvArgs does: once Env: has been enumerated, Windows
# PowerShell 5.1 reports an empty variable as unset through Test-Path and
# [Environment]::GetEnvironmentVariable, which would add the gateway on top
# of the forwarded empty value.
if (Get-ChildItem Env: | Where-Object { $_.Name -eq 'HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS' }) {
return
}
@@ -932,6 +932,104 @@ def test_path_scope_rejects_machine_and_invalid_values(tmp_path: Path) -> None:
assert "User" in out and "Process" in out, out
# AST-extract the two functions Start-PersistentDockerInstall uses to build the
# dashboard allowlist env and run them in the same order: the passthrough
# enumerates Env: before Add-DashboardGatewayEnv checks for an explicit value.
# Both live in the generated wrapper, i.e. inside install.ps1's single-quoted
# here-string template, so that template is parsed in turn. `docker` is stubbed
# so no real daemon is queried. Prints one docker arg per line.
_DASHBOARD_GATEWAY_HARNESS = r"""
param([string]$InstallScript)
$ErrorActionPreference = 'Stop'
$ast = [System.Management.Automation.Language.Parser]::ParseFile(
$InstallScript, [ref]$null, [ref]$null)
$template = $ast.FindAll({
param($n)
$n -is [System.Management.Automation.Language.StringConstantExpressionAst] -and
$n.StringConstantType -eq 'SingleQuotedHereString' -and
$n.Value.Contains('function Add-DashboardGatewayEnv')
}, $true) | Select-Object -First 1
if (-not $template) { Write-Output 'NOTEMPLATE'; exit 3 }
$ast = [System.Management.Automation.Language.Parser]::ParseInput(
$template.Value, [ref]$null, [ref]$null)
$functions = $ast.FindAll({
param($n)
$n -is [System.Management.Automation.Language.FunctionDefinitionAst]
}, $true)
foreach ($name in 'Get-PassthroughEnvArgs', 'Add-DashboardGatewayEnv') {
$fn = $functions | Where-Object { $_.Name -eq $name } | Select-Object -First 1
if (-not $fn) { Write-Output "NOFUNC:$name"; exit 3 }
Invoke-Expression $fn.Extent.Text
}
function docker { $global:LASTEXITCODE = 0; '172.17.0.1' }
$dockerArgs = New-Object System.Collections.Generic.List[string]
$dockerArgs.AddRange([string[]](Get-PassthroughEnvArgs))
Add-DashboardGatewayEnv -ArgsList $dockerArgs
$dockerArgs | ForEach-Object { Write-Output $_ }
"""
@pytest.mark.skipif(
os.name != "nt", reason="Windows PowerShell coverage runs on Windows hosts only"
)
@pytest.mark.parametrize(
"shell",
[
# Windows PowerShell 5.1 ships with every Windows install and is what a
# plain `powershell` resolves to; pwsh is PowerShell 7+.
pytest.param("powershell", id="windows-powershell"),
pytest.param("pwsh", id="pwsh"),
],
)
@pytest.mark.parametrize(
("configured", "expect_gateway_default"),
[
pytest.param(None, True, id="unset"),
pytest.param("10.20.0.0/16", False, id="configured"),
pytest.param("", False, id="explicitly-empty"),
],
)
def test_powershell_dashboard_gateway_default_respects_explicit_allowlist(
tmp_path: Path, shell: str, configured: str | None, expect_gateway_default: bool
) -> None:
"""An explicit allowlist, even an empty one, must suppress the gateway default.
Windows PowerShell 5.1 stops reporting an empty variable through
``Test-Path Env:`` once ``Env:`` has been enumerated, so the explicit opt-out
was forwarded by name *and* overridden by the trusted bridge gateway.
"""
executable = shutil.which(shell)
if executable is None:
pytest.skip(f"{shell} is not installed")
trusted_cidrs = "HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS"
env = {key: value for key, value in os.environ.items() if key.upper() != trusted_cidrs}
if configured is not None:
env[trusted_cidrs] = configured
harness = tmp_path / "dashboard_gateway_harness.ps1"
harness.write_text(_DASHBOARD_GATEWAY_HARNESS, encoding="utf-8")
result = _run(
[
executable,
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
str(harness),
"-InstallScript",
str(REPO_ROOT / "scripts" / "install.ps1"),
],
env=env,
)
docker_args = result.stdout.splitlines()
gateway_default = f"{trusted_cidrs}=172.17.0.1/32"
assert (gateway_default in docker_args) is expect_gateway_default, docker_args
# Docker's name-only --env form forwards the caller's value unchanged.
assert (trusted_cidrs in docker_args) is (configured is not None), docker_args
@pytest.mark.skipif(
os.name != "nt" or _powershell_executable() is None,
reason="Windows PowerShell coverage runs on Windows hosts only",