diff --git a/.github/skills/smoke-tests/SKILL.md b/.github/skills/smoke-tests/SKILL.md index e37c58b742268d..c0a66229ea89ca 100644 --- a/.github/skills/smoke-tests/SKILL.md +++ b/.github/skills/smoke-tests/SKILL.md @@ -51,6 +51,7 @@ Some placement is coupled to the workflows: - **WSL version:** the agents' Windows Server 2022 image only has the inbox WSL, so provisioning installs the WSL release pinned in `build/checksums/wsl.txt` (see `build/azure-pipelines/common/wsl.psm1`). To update it, put the SHA256 and file name of a newer `wsl..x64.msi` from the [microsoft/WSL releases](https://github.com/microsoft/WSL/releases) there. The installer caches key on that file; `pr-pnpm-store.yml` fills the GitHub cache on `main`. - **Prepared WSL distribution:** the `wsl-distro` job of `pr-workspace-images.yml` (1ES pool, daily schedule and manual runs only) runs `wslDevContainer.ps1 -Operation Prepare` and saves the exported VHD in a cache keyed on the hash of `wslDevContainer.ps1` and `build/checksums/wsl.txt`. The WSL job restores the newest entry for its hash and imports it with `wsl --import-in-place` instead of building the distribution. It builds the distribution when there is no entry for its hash (for example after a change to either file, until the next daily run or a manual run of the workflow on `main`), or when the import fails. On Azure Pipelines, the Windows x64 smoke job prepares the distribution itself: on a miss of its daily cache key, it runs Prepare before Setup and saves the VHD when the job succeeds (see `test/smoke/README.md`). - **macOS proxy runs:** In `pr-darwin-test.yml`, the PAC, Kerberos and Basic proxy Agents Window runs happen only in the last shard, so `test/smoke/src/shard.ts` reserves their time there. +- **Sandbox proxy runs:** `run-agents-window-wsl-kerberos-proxy.ps1 -Sandbox` runs the `…proxy, sandbox` Agents Window suites, which the other runs skip because only `-Sandbox` sets `VSCODE_SMOKE_TEST_SANDBOX_PROXY`. On Azure Pipelines, the Kerberos and Basic PAC proxy steps of `product-build-win32-test.yml` run it after their main run only with the Linux server of the same build, whose Copilot runtime proxies sandboxed commands with the client's credentials; the pinned server's runtime does not, so `pr-win32-test.yml` does not run it yet. Every shard must register the same suites; otherwise suites can be skipped or run twice. Don't make suite registration depend on anything that differs between shards. diff --git a/build/azure-pipelines/win32/steps/product-build-win32-test.yml b/build/azure-pipelines/win32/steps/product-build-win32-test.yml index a18094caf687f0..0a40a330e10680 100644 --- a/build/azure-pipelines/win32/steps/product-build-win32-test.yml +++ b/build/azure-pipelines/win32/steps/product-build-win32-test.yml @@ -336,23 +336,30 @@ steps: WSL_SMOKE_DISTRO: $(WSL_SMOKE_DISTRO) condition: and(succeeded(), or(ne(variables['TEST_CHECKPOINT_SMOKE_WSL_KERBEROS_PROXY_HIT'], 'true'), ne(variables['TEST_CHECKPOINT_SMOKE_WSL_BASIC_PROXY_HIT'], 'true'), and(${{ containsValue(parameters.VSCODE_TEST_IDS, 'smoke-wsl-basic-pac-proxy') }}, ne(variables['TEST_CHECKPOINT_SMOKE_WSL_BASIC_PAC_PROXY_HIT'], 'true')))) - # The script configures a test Kerberos realm, CA and PAC on the elevated agent and reverts them. + # The script configures a test Kerberos realm, CA and PAC on the elevated agent and reverts them. With the server of + # this run, whose Copilot runtime proxies sandboxed commands with the client's Kerberos tickets, the sandbox suite + # runs as well. - ${{ if and(eq(parameters.VSCODE_ARCH, 'x64'), containsValue(parameters.VSCODE_TEST_IDS, 'smoke-wsl-kerberos-proxy')) }}: - template: ../../common/run-test-with-checkpoint.yml@self parameters: testId: smoke-wsl-kerberos-proxy testStep: - pwsh: .\test\smoke\scripts\run-agents-window-wsl-kerberos-proxy.ps1 -Distribution $env:WSL_SMOKE_DISTRO -WslServerPath $env:WSL_KERBEROS_SERVER_PATH -Suites $env:WSL_KERBEROS_SUITES --build "$(agent.builddirectory)\test\VSCode-win32-$(VSCODE_ARCH)" --skip-stable-build + pwsh: | + .\test\smoke\scripts\run-agents-window-wsl-kerberos-proxy.ps1 -Distribution $env:WSL_SMOKE_DISTRO -WslServerPath $env:WSL_KERBEROS_SERVER_PATH -Suites $env:WSL_KERBEROS_SUITES --build "$(agent.builddirectory)\test\VSCode-win32-$(VSCODE_ARCH)" --skip-stable-build + if ($env:WSL_KERBEROS_SANDBOX) { + .\test\smoke\scripts\run-agents-window-wsl-kerberos-proxy.ps1 -Distribution $env:WSL_SMOKE_DISTRO -WslServerPath $env:WSL_KERBEROS_SERVER_PATH -Suites AgentsWindow -Sandbox --build "$(agent.builddirectory)\test\VSCode-win32-$(VSCODE_ARCH)" --skip-stable-build + } env: WSL_SMOKE_DISTRO: $(WSL_SMOKE_DISTRO) ${{ if eq(parameters.VSCODE_LINUX_X64_COMPILATION_ARTIFACT, true) }}: WSL_KERBEROS_SERVER_PATH: $(WSL_SMOKE_BUILD_SERVER_PATH) WSL_KERBEROS_SUITES: All + WSL_KERBEROS_SANDBOX: '1' ${{ else }}: WSL_KERBEROS_SERVER_PATH: $(WSL_SMOKE_SERVER_PATH) WSL_KERBEROS_SUITES: AgentsWindow displayName: 🧪 Run WSL Kerberos proxy smoke tests (Electron) - timeoutInMinutes: 30 + timeoutInMinutes: 40 # Only the editor window suite runs, with the proxy and its credentials in the http.proxy setting. The script trusts a # test CA on the elevated agent and reverts it. @@ -370,21 +377,27 @@ steps: # Only the Agents Window suites run, with a local Agent Host and with one in WSL, which use the PAC and type the proxy's # credentials into the proxy login dialog. The script trusts a test CA and configures a PAC on the elevated agent and - # reverts them. + # reverts them. With the server of this run, whose Copilot runtime proxies sandboxed commands with the client's + # credentials, the sandbox suites run as well. - ${{ if and(eq(parameters.VSCODE_ARCH, 'x64'), containsValue(parameters.VSCODE_TEST_IDS, 'smoke-wsl-basic-pac-proxy')) }}: - template: ../../common/run-test-with-checkpoint.yml@self parameters: testId: smoke-wsl-basic-pac-proxy testStep: - pwsh: .\test\smoke\scripts\run-agents-window-wsl-kerberos-proxy.ps1 -ProxyAuth BasicPac -Distribution $env:WSL_SMOKE_DISTRO -WslServerPath $env:WSL_BASIC_PAC_SERVER_PATH --build "$(agent.builddirectory)\test\VSCode-win32-$(VSCODE_ARCH)" --skip-stable-build + pwsh: | + .\test\smoke\scripts\run-agents-window-wsl-kerberos-proxy.ps1 -ProxyAuth BasicPac -Distribution $env:WSL_SMOKE_DISTRO -WslServerPath $env:WSL_BASIC_PAC_SERVER_PATH --build "$(agent.builddirectory)\test\VSCode-win32-$(VSCODE_ARCH)" --skip-stable-build + if ($env:WSL_BASIC_PAC_SANDBOX) { + .\test\smoke\scripts\run-agents-window-wsl-kerberos-proxy.ps1 -ProxyAuth BasicPac -Sandbox -Distribution $env:WSL_SMOKE_DISTRO -WslServerPath $env:WSL_BASIC_PAC_SERVER_PATH --build "$(agent.builddirectory)\test\VSCode-win32-$(VSCODE_ARCH)" --skip-stable-build + } env: WSL_SMOKE_DISTRO: $(WSL_SMOKE_DISTRO) ${{ if eq(parameters.VSCODE_LINUX_X64_COMPILATION_ARTIFACT, true) }}: WSL_BASIC_PAC_SERVER_PATH: $(WSL_SMOKE_BUILD_SERVER_PATH) + WSL_BASIC_PAC_SANDBOX: '1' ${{ else }}: WSL_BASIC_PAC_SERVER_PATH: $(WSL_SMOKE_SERVER_PATH) displayName: 🧪 Run WSL Basic PAC proxy smoke tests (Electron) - timeoutInMinutes: 30 + timeoutInMinutes: 40 - ${{ if and(eq(parameters.VSCODE_ARCH, 'x64'), or(containsValue(parameters.VSCODE_TEST_IDS, 'smoke-electron'), containsValue(parameters.VSCODE_TEST_IDS, 'smoke-wsl-kerberos-proxy'), containsValue(parameters.VSCODE_TEST_IDS, 'smoke-wsl-basic-proxy'), containsValue(parameters.VSCODE_TEST_IDS, 'smoke-wsl-basic-pac-proxy'))) }}: - pwsh: .\test\smoke\wslDevContainer.ps1 -CI AzureDevOps -Operation Cleanup -Distribution $env:WSL_SMOKE_DISTRO -Root $env:WSL_SMOKE_ROOT diff --git a/scripts/chat-simulation/common/mock-llm-server.ts b/scripts/chat-simulation/common/mock-llm-server.ts index d8568eb39a1775..cab6f3fc95dc53 100644 --- a/scripts/chat-simulation/common/mock-llm-server.ts +++ b/scripts/chat-simulation/common/mock-llm-server.ts @@ -874,6 +874,8 @@ function handleRequest(req: import('http').IncomingMessage, res: import('http'). } // -- Catch-all GET → empty success -------------------------------- + // Captured so tests can assert that a request of their own, such as a sandboxed command's, reached the server. + serverEvents.emit('capturedRequest', { path, method: req.method ?? 'GET', body: '' }); json(200, {}); } @@ -1990,6 +1992,8 @@ interface MockLlmServerHandle { * `body` is the JSON-parsed request payload (or the raw string when parsing * fails). Used by tests to assert what the client forwarded to the server * (e.g. `reasoning.effort` or the context-management `compact_threshold`). + * Requests to paths the server does not serve are included with an empty + * `body`, so tests can assert that a request of their own reached it. * * Returns an empty array unless the server was started with * {@link StartServerOptions.captureRequests} set — request capture is off by diff --git a/test/automation/src/chat.ts b/test/automation/src/chat.ts index 89d198ebf981d4..e15eea772cebe6 100644 --- a/test/automation/src/chat.ts +++ b/test/automation/src/chat.ts @@ -574,11 +574,14 @@ export class Chat { * * The terminal confirmation renders as a `.chat-confirmation-widget2` whose * action buttons are `.monaco-button.monaco-text-button` anchors — the primary - * "Allow" (rendered first), then "Skip". The dropdown chevron next to "Allow" + * "Allow" (rendered first), then "Skip". A URL confirmation, such as the one + * the Copilot runtime requests for a URL in a shell command, labels its primary + * button "Allow Once" instead. The dropdown chevron next to "Allow" * is a `.monaco-dropdown-button.codicon` (no `.monaco-text-button`) and the * carousel's "Allow All" lives on `.chat-tool-carousel-allow-all-button`, so * neither is matched here. We verify the first text button actually reads - * "Allow" before clicking to avoid ever hitting "Skip". + * "Allow", "Allow Once" or "Allow in this Session" before clicking to avoid + * ever hitting "Skip". * * Uses the VS Code driver (`getElements`/`click`) rather than a raw Playwright * locator: the confirmation renders outside the chat response/editor @@ -587,11 +590,12 @@ export class Chat { export async function acceptToolConfirmationIfPresent(code: Code): Promise { const allowButtonSelector = '.chat-confirmation-widget2 .monaco-button.monaco-text-button'; // Agent Host client tools offer "Allow in this Session" as their primary action. - const allowLabel = /^Allow( in this Session)?$/; + const allowLabel = /^Allow(?: Once| in this Session)?$/; try { const buttons = await code.driver.getElements(allowButtonSelector, /* recursive */ true); - // The first text button in the widget is "Allow"; only proceed when - // that holds so we never accidentally hit "Skip". + // The first text button in the widget is "Allow", "Allow Once" or + // "Allow in this Session"; only proceed when that holds so we never + // accidentally hit "Skip". if (!buttons || buttons.length === 0 || !allowLabel.test((buttons[0].textContent ?? '').trim())) { return; } diff --git a/test/smoke/README.md b/test/smoke/README.md index ea939aefc7a8d1..b674aec56b8ab7 100644 --- a/test/smoke/README.md +++ b/test/smoke/README.md @@ -130,6 +130,19 @@ No setting or environment variable of VS Code carries the current credentials: e The Agents Window suites accept a WSL server of another commit, provided its Agent Host asks the client for Basic proxy credentials. In CI, the Windows Electron smoke job that runs the WSL Dev Container suite runs this mode after the Kerberos run, with the pinned server of `test/smoke/wslDevContainer.ps1`. The Azure product build runs it as `smoke-wsl-basic-pac-proxy`, with the Linux server of the same run's Linux x64 compile job, or the pinned server without one. +#### Sandboxed commands through the proxy + +`-Sandbox` runs Agents Window suites with the Copilot runtime's sandbox on instead: with `-ProxyAuth BasicPac`, the `Agents Window (local AgentHost, Basic PAC proxy, sandbox)` and `Agents Window (WSL AgentHost, Basic PAC proxy, sandbox)` suites, and with `-ProxyAuth Kerberos`, the `Agents Window (WSL AgentHost, Kerberos proxy, sandbox)` suite: + +```powershell +.\test\smoke\scripts\run-agents-window-wsl-kerberos-proxy.ps1 -ProxyAuth BasicPac -Sandbox -Distribution Ubuntu -WslServerPath ~/devel/vscode -WslNodePath ~/.local/node/bin/node +.\test\smoke\scripts\run-agents-window-wsl-kerberos-proxy.ps1 -ProxyAuth Kerberos -Sandbox -Suites AgentsWindow -Distribution Ubuntu -WslServerPath ~/devel/vscode -WslNodePath ~/.local/node/bin/node +``` + +Each suite sends a prompt whose scenario runs `curl` against a fresh path of the mock server in the Copilot runtime's own shell tool. The sandbox settings allow only the mock host, forbid unsandboxed commands and, on Windows, allow local network access so that the command reaches the sandbox's network proxy over loopback. Only Squid resolves the mock host, so the command reaches the mock server only when the sandbox's network proxy forwards it to the proxy the client resolves, with the credentials typed into the single proxy login dialog or with the client's Kerberos ticket. The suites accept the runtime's URL confirmation, check that the mock server got the request, and check in the Agent Host log that the runtime's shell tool ran the command with the sandbox configuration of the Agent Host. The WSL suites also check that the client served the PAC proxy and the credentials or Kerberos token. The local suite skips itself when the Copilot runtime reports that the Windows host has no sandbox backend, as on the Azure Windows agents. The distribution additionally needs the `bubblewrap`, `slirp4netns` and `iptables` packages. With the legacy iptables backend, which the Dev Container smoke tests select for Docker, the sandbox installs its network rules without privilege only when `/run/xtables.lock` is writable, so the script lets the default user own that lock during the run. `-CopilotRuntimePath` selects a Windows `copilot-runtime.exe`, next to its matching `runtime.node`, for the local Agent Host, like `-WslCopilotRuntimePath` for the WSL one. `-ProxyAuth Basic` and `-Suites EditorWindow` are not supported in this mode. Logs are kept in `.build/logs/agents-window-wsl--proxy-sandbox`, and the JUnit report goes to `test-results/*-desktop-smoke-tests-wsl--proxy-sandbox-results.xml`. + +The Azure product build runs these suites after the Kerberos and Basic PAC runs of `smoke-wsl-kerberos-proxy` and `smoke-wsl-basic-pac-proxy`, only with the Linux server of the same run's Linux x64 compile job, since the Copilot runtime of the pinned server does not proxy sandboxed commands with the client's credentials. Pull request CI does not run them until the pinned server's runtime does. + ### Dev Container sessions over SSH, Tunnels, and WSL The Agents Window Dev Container suites require a reachable Linux Docker daemon. The SSH suite runs by default on Linux, and locally on macOS when Docker is available. SSH/Tunnel suites are limited to Linux in CI. The SSH fixture uses a loopback SSH server with an ephemeral port, password, and host key; it does not require system `sshd` or change your SSH configuration. diff --git a/test/smoke/scripts/run-agents-window-wsl-kerberos-proxy.ps1 b/test/smoke/scripts/run-agents-window-wsl-kerberos-proxy.ps1 index 6f71c1dd98a5c0..f91594f228033e 100644 --- a/test/smoke/scripts/run-agents-window-wsl-kerberos-proxy.ps1 +++ b/test/smoke/scripts/run-agents-window-wsl-kerberos-proxy.ps1 @@ -28,7 +28,16 @@ new one when the proxy rejects the remembered credentials. Another local Agent Host suite sets the proxy with a stale password in the http.proxy setting, and types the credentials when the proxy rejects it. - Every change is reverted afterwards, and logs are kept in .build/logs/agents-window-wsl--proxy. + With -Sandbox, the Agents Window suites run with the Copilot runtime's sandbox on instead, with -ProxyAuth BasicPac + for a local Agent Host and one in WSL, and with -ProxyAuth Kerberos for one in WSL. A sandboxed shell command fetches + a URL of the mock server, which only Squid can reach, through the network proxy of the sandbox, which forwards it to + the proxy the client resolves, with the credentials or Kerberos ticket of the client. The distribution additionally + needs bubblewrap, slirp4netns and iptables. With the legacy iptables backend, which the Dev Container smoke tests + select for Docker, the sandbox installs its network rules without privilege only when /run/xtables.lock is writable, + so the default user owns that lock during the run. + + Every change is reverted afterwards, and logs are kept in .build/logs/agents-window-wsl--proxy, with a -sandbox + suffix for -Sandbox. The distribution needs squid-openssl, openssl and curl, krb5-kdc and krb5-admin-server for Kerberos, and NAT networking. @@ -41,6 +50,9 @@ .EXAMPLE .\test\smoke\scripts\run-agents-window-wsl-kerberos-proxy.ps1 -ProxyAuth BasicPac -WslServerPath ~/devel/vscode -WslNodePath ~/.local/node/bin/node + +.EXAMPLE + .\test\smoke\scripts\run-agents-window-wsl-kerberos-proxy.ps1 -ProxyAuth BasicPac -Sandbox -WslServerPath ~/devel/vscode -WslNodePath ~/.local/node/bin/node #> [CmdletBinding(PositionalBinding = $false)] param( @@ -51,6 +63,9 @@ param( [string]$WslNodePath, # A Linux `copilot-runtime`, next to its `runtime.node`, for the Agent Host to use instead of its bundled one. [string]$WslCopilotRuntimePath, + # A Windows `copilot-runtime.exe`, next to its `runtime.node`, for the local Agent Host to use instead of its bundled + # one. + [string]$CopilotRuntimePath, # How the proxy authenticates clients: Kerberos, with the system proxy settings, Basic, with the http.proxy setting, or # BasicPac, with the system proxy settings and the proxy login dialog. [ValidateSet('Kerberos', 'Basic', 'BasicPac')][string]$ProxyAuth = 'Kerberos', @@ -59,6 +74,8 @@ param( # The editor window suite connects to the server in WSL. A packaged server only accepts a packaged client of its commit. # With Basic authentication, only the editor window suite runs, and with BasicPac only the Agents Window suites. [ValidateSet('All', 'AgentsWindow', 'EditorWindow')][string]$Suites = 'All', + # Runs the Agents Window suites whose sandboxed shell command fetches a URL through the proxy instead. + [switch]$Sandbox, # Further smoke test arguments, such as `--build `. [Parameter(ValueFromRemainingArguments)][string[]]$SmokeTestArguments = @() ) @@ -84,7 +101,15 @@ if ($ProxyAuth -eq 'Basic' -and $Suites -eq 'AgentsWindow') { if ($BasicPac -and $Suites -eq 'EditorWindow') { throw 'With BasicPac authentication, only the Agents Window suites run.' } -$SmokeTestGrep = if ($BasicPac) { +if ($Sandbox -and ($ProxyAuth -eq 'Basic' -or $Suites -eq 'EditorWindow')) { + throw 'With -Sandbox, only the Agents Window suites run, with BasicPac or Kerberos authentication.' +} +if ($CopilotRuntimePath) { + $CopilotRuntimePath = (Resolve-Path $CopilotRuntimePath).Path +} +$SmokeTestGrep = if ($Sandbox) { + if ($BasicPac) { 'AgentHost, Basic PAC proxy, sandbox' } else { 'WSL AgentHost, Kerberos proxy, sandbox' } +} elseif ($BasicPac) { 'AgentHost, Basic PAC proxy' } else { switch ($Suites) { @@ -93,7 +118,7 @@ $SmokeTestGrep = if ($BasicPac) { default { if ($Kerberos) { 'AgentHost, Kerberos proxy' } else { 'WSL remote AgentHost, Basic proxy' } } } } -$RunName = "wsl-$($ProxyAuth.ToLowerInvariant())-proxy" +$RunName = "wsl-$($ProxyAuth.ToLowerInvariant())-proxy$(if ($Sandbox) { '-sandbox' })" $ProxyUrl = "$($ProxyScheme.ToLowerInvariant())://localhost:$ProxyPort" $SquidPort = if ($ProxyScheme -eq 'Https') { 'https_port 127.0.0.1:{0} tls-cert=$WSL_ROOT/server.pem tls-key=$WSL_ROOT/server.key' -f $ProxyPort @@ -558,6 +583,8 @@ $savedProxySettings = $null $script:WindowsConfigured = $false $kdcProcess = $null $squidProcess = $null +# The owner and mode of /run/xtables.lock, or 'absent', before the default user took it over. +$xtablesLock = $null $pacProcess = $null $smokeProcess = $null $smokeStarted = $false @@ -568,6 +595,10 @@ $succeeded = $false try { $wslTools = if ($Kerberos) { 'krb5kdc kdb5_util kadmin.local squid openssl curl ip ss' } else { 'squid openssl curl ip ss' } $wslPackages = if ($Kerberos) { 'krb5-kdc krb5-admin-server squid-openssl openssl curl iproute2' } else { 'squid-openssl openssl curl iproute2' } + if ($Sandbox) { + $wslTools += ' bwrap slirp4netns iptables' + $wslPackages += ' bubblewrap slirp4netns iptables' + } $authHelper = if ($Kerberos) { '/usr/lib/squid/negotiate_kerberos_auth' } else { '/usr/lib/squid/basic_ncsa_auth' } $wslPorts = if ($Kerberos) { "88 $ProxyPort" } else { "$ProxyPort" } $network = Invoke-WslScript @" @@ -726,6 +757,26 @@ chown "`$WSL_USER" "`$WSL_ROOT" "`$WSL_ROOT"/*.* "`$WSL_ROOT/hosts" if (-not (Test-TcpPort '127.0.0.1' $ProxyPort)) { throw "Windows cannot reach Squid at localhost:$ProxyPort; WSL localhost forwarding must be enabled" } + if ($Sandbox) { + # The Copilot runtime checks the lock when it starts. /run is reset when the distribution stops, which Squid + # prevents until the cleanup. + $state = (Invoke-WslScript -AsRoot @" +WSL_USER=$(ConvertTo-ShellLiteral $wslUser) +legacy= +for tool in iptables ip6tables; do + case "`$("`$tool" -V)" in *nf_tables*) ;; *) legacy=1 ;; esac +done +if [ -n "`$legacy" ]; then + if [ -e /run/xtables.lock ]; then stat -c '%u:%g %a' /run/xtables.lock; else echo absent; fi + touch /run/xtables.lock + chown "`$WSL_USER" /run/xtables.lock +fi +"@) -join '' + if ($state -and $state -notmatch '^(absent|\d+:\d+ [0-7]+)$') { + throw "Unexpected /run/xtables.lock state in WSL: $state" + } + $xtablesLock = $state + } Invoke-ElevatedConfiguration 'Setup' @@ -783,6 +834,12 @@ chown "`$WSL_USER" "`$WSL_ROOT" "`$WSL_ROOT"/*.* "`$WSL_ROOT/hosts" if ($WslCopilotRuntimePath) { $environment['VSCODE_SMOKE_TEST_WSL_COPILOT_RUNTIME_PATH'] = $WslCopilotRuntimePath } + if ($CopilotRuntimePath) { + $environment['VSCODE_SMOKE_TEST_COPILOT_RUNTIME_PATH'] = $CopilotRuntimePath + } + if ($Sandbox) { + $environment['VSCODE_SMOKE_TEST_SANDBOX_PROXY'] = '1' + } $environment['VSCODE_SMOKE_TEST_MOCK_HOST'] = $MockHost $environment['VSCODE_SMOKE_TEST_PROXY_HEADER'] = $proxyHeader $environment['VSCODE_SMOKE_TEST_MOCK_CERT'] = Join-Path $TempRoot 'server.pem' @@ -913,6 +970,18 @@ exit `$LASTEXITCODE if ($pacProcess -and -not $pacProcess.HasExited) { $pacProcess.Kill() } + if ($xtablesLock) { + try { + # Before Squid stops, while /run still has the lock. + $restore = if ($xtablesLock -eq 'absent') { 'rm -f /run/xtables.lock' } else { + $owner, $mode = $xtablesLock -split ' ' + "if [ -e /run/xtables.lock ]; then chown $owner /run/xtables.lock; chmod $mode /run/xtables.lock; fi" + } + Invoke-WslScript -AsRoot $restore | Out-Null + } catch { + Write-Warning "Could not restore /run/xtables.lock in WSL: $_" + } + } Stop-WslProcess $squidProcess "$WslRoot/wrapper.pid" Stop-WslProcess -AsRoot $kdcProcess "$WslRoot/kdc/wrapper.pid" if ($script:WindowsConfigured) { diff --git a/test/smoke/src/areas/agentsWindow/agentsWindow.test.ts b/test/smoke/src/areas/agentsWindow/agentsWindow.test.ts index aff413eb23aa5b..5c7bfb9b45e3a1 100644 --- a/test/smoke/src/areas/agentsWindow/agentsWindow.test.ts +++ b/test/smoke/src/areas/agentsWindow/agentsWindow.test.ts @@ -10,7 +10,7 @@ import * as fs from 'fs'; import * as path from 'path'; import { Application, ApplicationOptions, Logger, Quality } from '../../../../automation'; import { createApp, dumpFailureDiagnostics, getCopilotSmokeTestEnv, getMockLlmServerPath, getMockLlmServerUrl, installAppAfterHandler, installDiagnosticsHandler, latestUserInputCarriesTag, MockLlmServer, preseedChatExtensionEnablement, suiteCrashPath, suiteLogsPath } from '../../utils'; -import { shellEchoResponseMatcher, shellEchoScenario } from '../chat/shellScenarios'; +import { shellEchoResponseMatcher, shellEchoScenario, shellNetworkProbeScenario } from '../chat/shellScenarios'; import { CONFIGURED_PROXY_CREDENTIALS_ANSWERED_LOG, createRemoteDevContainerFixture, getDevContainerCliInstallCommand, getTunnelSmokeTestAvailability, IRemoteDevContainerFixture, RemoteDevContainerTransport } from './remoteDevContainerFixtures'; // Selector for the send button in the Agents Window new-session homepage. @@ -826,6 +826,170 @@ export function setup(logger: Logger, quality: Quality) { }); }); + // Run by test/smoke/scripts/run-agents-window-wsl-kerberos-proxy.ps1 -Sandbox: a sandboxed shell command fetches a + // URL of the mock server, which only the proxy of the PAC script can reach, through the sandbox's network proxy. + // That proxy forwards to the proxy the client resolves, with the credentials or Kerberos ticket the client returns. + const sandboxProxy = process.env.VSCODE_SMOKE_TEST_SANDBOX_PROXY === '1'; + if (!sandboxProxy) { + logger.log('Skipping the AgentHost sandbox proxy suites: run test/smoke/scripts/run-agents-window-wsl-kerberos-proxy.ps1 -Sandbox on Windows'); + } + const localCopilotRuntimePath = process.env.VSCODE_SMOKE_TEST_COPILOT_RUNTIME_PATH; + (sandboxProxy && basicPacProxyScheme ? describe : describe.skip)('Agents Window (local AgentHost, Basic PAC proxy, sandbox)', () => { + const scenario = 'smoke-local-basic-pac-proxy-sandbox-agent-host'; + const reply = 'LOCAL_BASIC_PAC_PROXY_SANDBOX_RESPONSE'; + const probePath = `/sandbox-probe/${randomUUID()}`; + const context = setupAgentHostSuite(logger, { + serverLabel: 'Local Basic PAC proxy sandbox AgentHost', + mockServerHost: '0.0.0.0', + proxyLoginCredentials: basicPacProxyCredentials, + registerScenarios: ({ registerScenario }) => registerScenario(scenario, shellNetworkProbeScenario(() => getMockLlmServerUrl(context.mockServer) + probePath, reply, process.platform === 'win32' ? 'powershell' : 'bash')), + settings: { + ...sandboxProxySettings(process.platform), + ...(localCopilotRuntimePath ? { 'chat.agentHost.copilot.runtimePath': localCopilotRuntimePath } : {}), + }, + }); + + it('Fetches a URL from a sandboxed command through the PAC proxy of a local AgentHost', async function () { + this.timeout(10 * 60 * 1000); + const app = this.app as Application; + const agentHostLogPath = path.join(context.logsPath, 'agenthost.log'); + const logins = context.proxyLogins; + assert.ok(logins, 'Expected the suite to fill the proxy login dialogs'); + let unsupportedBackend: string | undefined; + try { + await app.workbench.agentsWindow.waitForNewSessionView(); + await app.workbench.agentsWindow.selectSessionType('Copilot'); + unsupportedBackend = await assertSandboxedNetworkProbe(app, context.mockServer, { + prompt: `fetch through the sandbox and the PAC proxy [scenario:${scenario}]`, + reply, + probePath, + readAgentHostLog: () => readFileIfExists(agentHostLogPath), + allowUnsupportedBackend: true, + }); + if (localCopilotRuntimePath) { + assert.ok(readFileIfExists(agentHostLogPath).includes(`[Copilot] Using configured runtime path: ${localCopilotRuntimePath}`), `Expected the Agent Host to use the Copilot runtime at ${localCopilotRuntimePath}`); + } + assertProxyLoginDialogs(await logins.stop(), 1); + } catch (error) { + logger.log(`Agents Window (local Basic PAC proxy, sandbox) FAILURE: ${error instanceof Error ? error.stack ?? error.message : String(error)}`); + await dumpFailureDiagnostics(app, logger, 'Agents Window (local Basic PAC proxy, sandbox)', { sendButtonSelector: AGENTS_SEND_BUTTON_SELECTOR }); + throw error; + } finally { + await logins.stop(); + } + if (unsupportedBackend !== undefined) { + logger.log(`Skipping Agents Window (local Basic PAC proxy, sandbox): the Copilot runtime has no sandbox backend on this host: ${unsupportedBackend}`); + this.skip(); + } + }); + }); + + (sandboxProxy && basicPacProxyScheme ? describe : describe.skip)('Agents Window (WSL AgentHost, Basic PAC proxy, sandbox)', () => { + const scenario = 'smoke-wsl-basic-pac-proxy-sandbox-agent-host'; + const reply = 'WSL_BASIC_PAC_PROXY_SANDBOX_RESPONSE'; + const probePath = `/sandbox-probe/${randomUUID()}`; + const context = setupAgentHostSuite(logger, { + serverLabel: 'WSL Basic PAC proxy sandbox AgentHost', + mockServerHost: '0.0.0.0', + remoteTransport: 'wsl', + wslClientProxy: 'agentHost', + proxyLoginCredentials: basicPacProxyCredentials, + registerScenarios: ({ registerScenario }) => registerScenario(scenario, shellNetworkProbeScenario(() => getMockLlmServerUrl(context.mockServer) + probePath, reply, 'bash')), + settings: { + ...sandboxProxySettings('linux'), + 'chat.remoteAgentHostsEnabled': true, + }, + }); + + it('Fetches a URL from a sandboxed command through the Windows PAC proxy of a WSL AgentHost', async function () { + this.timeout(10 * 60 * 1000); + const app = this.app as Application; + const fixture = context.remoteFixture; + assert.ok(fixture, 'Expected the WSL connection fixture'); + const readAgentHostLog = fixture.readAgentHostLog; + assert.ok(readAgentHostLog, 'Expected the WSL fixture to read the AgentHost log'); + const logins = context.proxyLogins; + assert.ok(logins, 'Expected the suite to fill the proxy login dialogs'); + try { + await app.workbench.agentsWindow.waitForNewSessionView(); + await app.workbench.agentsWindow.connectWSLHost(fixture.name, fixture.workspacePath ?? app.workspacePathOrFolder, '.git'); + await app.workbench.agentsWindow.selectSessionType('Copilot', { providerLabel: fixture.name }); + await assertSandboxedNetworkProbe(app, context.mockServer, { + prompt: `fetch through the sandbox and the Windows PAC proxy [scenario:${scenario}]`, + reply, + probePath, + readAgentHostLog, + }); + assertProxyLoginDialogs(await logins.stop(), 1); + await fixture.verifyMockServerRouting?.(); + await assertClientNetworkServed(context.logsPath, 'wsl', basicPacProxyScheme === 'https' ? 'HTTPS' : 'PROXY', { basicUsername: basicPacProxyCredentials.username }); + } catch (error) { + logger.log(`Agents Window (WSL Basic PAC proxy, sandbox) FAILURE: ${error instanceof Error ? error.stack ?? error.message : String(error)}`); + if (fixture.dumpConnectionDiagnostics) { + try { + await fixture.dumpConnectionDiagnostics(await app.workbench.agentsWindow.getRemoteConnectionDiagnostics()); + } catch (diagnosticError) { + logger.log(`Agents Window (WSL Basic PAC proxy, sandbox) connection diagnostics failed: ${diagnosticError instanceof Error ? diagnosticError.message : String(diagnosticError)}`); + } + } + await dumpFailureDiagnostics(app, logger, 'Agents Window (WSL Basic PAC proxy, sandbox)', { sendButtonSelector: AGENTS_SEND_BUTTON_SELECTOR }); + throw error; + } finally { + await logins.stop(); + } + }); + }); + + (sandboxProxy && wslKerberosProxyScheme ? describe : describe.skip)('Agents Window (WSL AgentHost, Kerberos proxy, sandbox)', () => { + const scenario = 'smoke-wsl-kerberos-proxy-sandbox-agent-host'; + const reply = 'WSL_KERBEROS_PROXY_SANDBOX_RESPONSE'; + const probePath = `/sandbox-probe/${randomUUID()}`; + const context = setupAgentHostSuite(logger, { + serverLabel: 'WSL Kerberos proxy sandbox AgentHost', + mockServerHost: '0.0.0.0', + remoteTransport: 'wsl', + wslClientProxy: 'agentHost', + registerScenarios: ({ registerScenario }) => registerScenario(scenario, shellNetworkProbeScenario(() => getMockLlmServerUrl(context.mockServer) + probePath, reply, 'bash')), + settings: { + ...sandboxProxySettings('linux'), + 'chat.remoteAgentHostsEnabled': true, + }, + }); + + it('Fetches a URL from a sandboxed command through the Windows proxy, with the Windows Kerberos ticket, of a WSL AgentHost', async function () { + this.timeout(10 * 60 * 1000); + const app = this.app as Application; + const fixture = context.remoteFixture; + assert.ok(fixture, 'Expected the WSL connection fixture'); + const readAgentHostLog = fixture.readAgentHostLog; + assert.ok(readAgentHostLog, 'Expected the WSL fixture to read the AgentHost log'); + try { + await app.workbench.agentsWindow.waitForNewSessionView(); + await app.workbench.agentsWindow.connectWSLHost(fixture.name, fixture.workspacePath ?? app.workspacePathOrFolder, '.git'); + await app.workbench.agentsWindow.selectSessionType('Copilot', { providerLabel: fixture.name }); + await assertSandboxedNetworkProbe(app, context.mockServer, { + prompt: `fetch through the sandbox and the Windows proxy [scenario:${scenario}]`, + reply, + probePath, + readAgentHostLog, + }); + await fixture.verifyMockServerRouting?.(); + await assertClientNetworkServed(context.logsPath, 'wsl', wslKerberosProxyScheme === 'https' ? 'HTTPS' : 'PROXY', 'Kerberos'); + } catch (error) { + logger.log(`Agents Window (WSL Kerberos proxy, sandbox) FAILURE: ${error instanceof Error ? error.stack ?? error.message : String(error)}`); + if (fixture.dumpConnectionDiagnostics) { + try { + await fixture.dumpConnectionDiagnostics(await app.workbench.agentsWindow.getRemoteConnectionDiagnostics()); + } catch (diagnosticError) { + logger.log(`Agents Window (WSL Kerberos proxy, sandbox) connection diagnostics failed: ${diagnosticError instanceof Error ? diagnosticError.message : String(diagnosticError)}`); + } + } + await dumpFailureDiagnostics(app, logger, 'Agents Window (WSL Kerberos proxy, sandbox)', { sendButtonSelector: AGENTS_SEND_BUTTON_SELECTOR }); + throw error; + } + }); + }); + describe('Agents Window (local AgentHost, SDK sandbox)', () => { // Variant of the AgentHost suite that leaves @@ -1502,6 +1666,66 @@ function assertProxyLoginDialogs(details: readonly string[], count: number): voi assert.deepStrictEqual(details.map(detail => detail.replace(/^The proxy localhost:\d+ /, 'The proxy localhost: ')), Array.from({ length: count }, () => 'The proxy localhost: requires a username and password.')); } +/** + * Settings that run the Copilot runtime's shell commands in its sandbox, allow them to reach only the host of the mock + * server and don't let them leave the sandbox, so a command can only reach the mock server through the sandbox's + * network proxy. On Windows, sandboxed commands reach that proxy over host loopback, so they need local network access + * to launch at all. + */ +function sandboxProxySettings(agentHostPlatform: NodeJS.Platform): Record { + return { + 'chat.agent.sandbox.enabled': 'on', + 'chat.agent.sandbox.network.allowedDomains': [process.env.VSCODE_SMOKE_TEST_MOCK_HOST], + 'chat.agent.sandbox.allowUnsandboxedCommands': false, + ...(agentHostPlatform === 'win32' ? { 'chat.agent.sandbox.network.allowLocalNetwork': true } : {}), + }; +} + +/** + * Sends `prompt`, whose scenario fetches `probePath` of the mock server from a shell command, and asserts that the + * Copilot runtime's own shell tool ran the command in its sandbox, and that the command fetched the URL. Only the + * proxy of the PAC script resolves the mock server's host, so the request shows that the sandbox's network proxy + * forwarded it there. + * + * With `allowUnsupportedBackend`, returns the reason the Copilot runtime gives when the host has no sandbox backend, + * such as a Windows version without one, instead of waiting for a probe that cannot run in the sandbox. + */ +async function assertSandboxedNetworkProbe(app: Application, mockServer: MockLlmServer, options: { + readonly prompt: string; + readonly reply: string; + readonly probePath: string; + readonly readAgentHostLog: () => string | Promise; + readonly allowUnsupportedBackend?: boolean; +}): Promise { + assert.ok(process.env.VSCODE_SMOKE_TEST_MOCK_HOST, 'Expected the mock server host that only the proxy resolves, from run-agents-window-wsl-kerberos-proxy.ps1'); + await app.workbench.agentsWindow.submitNewSessionPrompt(options.prompt); + await app.workbench.agentsWindow.waitForActiveSessionView(5 * 60 * 1000); + const sdkShellRun = /\[Copilot:[^\]]+\] Tool started: (bash|powershell|pwsh)\b/; + if (options.allowUnsupportedBackend) { + // The Agent Host logs the runtime's sandbox host support while it starts a session, before a turn runs the shell tool. + const unsupportedBackend = /\] Sandbox backend unavailable (?.*)/; + const startLog = await waitForLogContent(options.readAgentHostLog, content => sdkShellRun.test(content) || unsupportedBackend.test(content), 2 * 60 * 1000); + const unsupported = unsupportedBackend.exec(startLog); + if (unsupported) { + return unsupported.groups?.reason ?? ''; + } + } + // The command echoes the reply only after curl fetched the URL. Starting the sandbox can take minutes on Windows. + await app.workbench.agentsWindow.waitForAssistantText(shellEchoResponseMatcher(options.reply), 5 * 60 * 1000, { acceptToolConfirmations: true }); + assert.ok(mockServer.getRequests().some(request => request.method === 'GET' && request.path === options.probePath), `Expected the sandboxed command to fetch ${options.probePath} from the mock server`); + const log = await waitForLogContent(options.readAgentHostLog, sdkShellRun, 30_000); + assert.deepStrictEqual({ + sandboxConfigApplied: /\[Copilot:[^\]]+\] Applied SDK sandboxConfig via session\.options\.update/.test(log), + sdkShellRun: sdkShellRun.test(log), + agentHostShellRun: /\[ShellManager\] Created \w+ shell /.test(log), + }, { + sandboxConfigApplied: true, + sdkShellRun: true, + agentHostShellRun: false, + }, 'Expected the Copilot runtime\'s own shell tool to run the command with the sandbox configuration of the Agent Host'); + return undefined; +} + async function assertRemoteDevContainerRouting(logsPath: string, transport: RemoteDevContainerTransport, workspacePath: string, reply: string): Promise { interface IFrame { readonly _ahpLog?: { readonly transport?: string }; diff --git a/test/smoke/src/areas/chat/shellScenarios.ts b/test/smoke/src/areas/chat/shellScenarios.ts index 6f986a4705bd6a..fafd64ebc64bc1 100644 --- a/test/smoke/src/areas/chat/shellScenarios.ts +++ b/test/smoke/src/areas/chat/shellScenarios.ts @@ -9,17 +9,19 @@ * 1. The tool actually ran (the tool result contains the echoed marker), and * 2. The reply appears in the chat (the same marker is rendered). * - * Two variants are provided to cover the different tool names advertised by + * Three variants are provided to cover the different tool names advertised by * each surface: * - {@link shellEchoScenario} matches SDK-based sessions (Copilot CLI, * Claude, AgentHost), which expose `bash` / `pwsh` / `powershell` tools. + * - {@link shellNetworkProbeScenario} matches the same tools, but echoes the + * reply only after the command fetched a URL. * - {@link runInTerminalScenario} matches the VS Code built-in chat agent * (used by the "Local" session), which exposes the `run_in_terminal` * tool. * - * Both scenarios use a two-turn protocol: + * All three scenarios use a two-turn protocol: * - Turn 1 (`tool-calls`): the model asks the tool to execute - * `echo `. + * `echo ` (after `curl` for {@link shellNetworkProbeScenario}). * - Turn 2 (`echo-last-message`): the model replays the last * (tool-result) message back as a ```json fenced block, so the reply * appears in the assistant rendering. @@ -46,6 +48,32 @@ export function shellEchoScenario(reply: string): unknown { }; } +/** + * Like {@link shellEchoScenario}, but the command fetches `url()` with curl and echoes `reply` only when that + * succeeded, so a sandboxed command proves that it reached the URL through the sandbox's network proxy. The URL is + * read when the model asks for the tool call, after the mock server started. + */ +export function shellNetworkProbeScenario(url: () => string, reply: string, shell: 'bash' | 'powershell'): unknown { + const command = () => shell === 'bash' + ? `curl -fsSk -o /dev/null '${url()}' && echo ${reply}` + : `curl.exe -fsSk -o NUL '${url()}'; if ($LASTEXITCODE -eq 0) { echo ${reply} }`; + return { + type: 'multi-turn', + turns: [ + { + kind: 'tool-calls', + toolCalls: [ + { + toolNamePattern: /^(bash|pwsh|powershell)$/i, + arguments: () => ({ command: command() }), + }, + ], + }, + { kind: 'echo-last-message' }, + ], + }; +} + export function runInTerminalScenario(reply: string): unknown { return { type: 'multi-turn', @@ -70,9 +98,10 @@ export function runInTerminalScenario(reply: string): unknown { } /** - * Matcher for the assistant text produced by {@link shellEchoScenario} or - * {@link runInTerminalScenario}. The final response renders the tool result - * as a ```json block; the exact format varies by surface: + * Matcher for the assistant text produced by {@link shellEchoScenario}, + * {@link shellNetworkProbeScenario} or {@link runInTerminalScenario}. The final + * response renders the tool result as a ```json block; the exact format varies + * by surface: * - Copilot CLI (responses-API): `{ "output": "" }` * - Local `run_in_terminal`: `{ "output": "..." }` * - Claude SDK Bash (messages-API): `{ "content": "" }` diff --git a/test/smoke/wslDevContainer.ps1 b/test/smoke/wslDevContainer.ps1 index ef7803923190a3..862081fcaf8d3c 100644 --- a/test/smoke/wslDevContainer.ps1 +++ b/test/smoke/wslDevContainer.ps1 @@ -41,7 +41,7 @@ $rootfsSha256 = '1483cc5c1dce13064f774834cbffdff226559fd522a67a381a8ea77d63fb410 # tests need a server with the agent host's client proxy, Kerberos and certificate support, and the WSL Basic PAC proxy # smoke tests one with its Basic proxy authentication through the client. $serverCommit = '54ab79431a5858c9546c7161e5afe5fd9e8570d6' -$aptPackages = 'ca-certificates curl git iproute2 procps docker.io libatomic1 libkrb5-3 krb5-kdc krb5-admin-server squid-openssl openssl' +$aptPackages = 'ca-certificates curl git iproute2 procps docker.io libatomic1 libkrb5-3 krb5-kdc krb5-admin-server squid-openssl openssl bubblewrap slirp4netns iptables' $devContainerImage = 'mcr.microsoft.com/devcontainers/base:ubuntu-24.04' $serverPath = '/opt/vscode-smoke-server'