diff --git a/docs/wsl/wsl-container-getting-started.md b/docs/wsl/wsl-container-getting-started.md index 37438918f4..eed047461f 100644 --- a/docs/wsl/wsl-container-getting-started.md +++ b/docs/wsl/wsl-container-getting-started.md @@ -355,17 +355,23 @@ inherits its provisioned network posture. ### Per-host filtering is not supported -WSLC **cannot** enforce per-host egress filtering. Directional allow/deny rules -would require in-container `iptables` +WSLC **cannot** enforce per-host egress filtering. Directional allow/deny rules — +and, on the published contracts, any allowlist (`allowedHosts` with +`defaultPolicy: "block"`) or blocklist (`blockedHosts` with +`defaultPolicy: "allow"`) — would require in-container `iptables` rules, but a WSLC container runs **without** `CAP_NET_ADMIN` (the SDK's `Privileged` flag does not grant it), so those rules cannot be applied — and MXC has no VM-level enforcement hook either (WSLC cannot expose one without breaking -other security promises such as MDE). Rather than fail the run at exec time, -such configs are **rejected at config-parse time**: +other security promises such as Microsoft Defender for Endpoint). Because the +lists cannot be honoured, **any** non-empty `allowedHosts` or `blockedHosts` is +rejected — including a list that is redundant with the default (`blockedHosts` +under `block`, `allowedHosts` under `allow`), which would otherwise be silently +ignored. Rather than fail the run at exec time, such configs are **rejected up +front** (a config-parse error for one-shot runs; a `policy_validation` error for +the state-aware lifecycle): ``` -WSLc: per-host egress filtering (allowedHosts with defaultPolicy='block', or -blockedHosts with defaultPolicy='allow') is not supported. ... +WSLc: per-host egress filtering (allowedHosts/blockedHosts) is not supported. ... ``` Use a runtime proxy with unrestricted bridged networking for cooperative host diff --git a/docs/wsl/wslc-state-aware.md b/docs/wsl/wslc-state-aware.md index a01a64b914..9f7b8311a5 100644 --- a/docs/wsl/wslc-state-aware.md +++ b/docs/wsl/wslc-state-aware.md @@ -137,6 +137,14 @@ The legacy `defaultPolicy`/`network.proxy` vocabulary documented in older published contracts is not a v0.9 compatibility fallback. The new v0.9 directional requirements do not change those published contracts. +## Port forwarding + +`experimental.wslc.provision.portMappings` forwards host (Windows) ports to the container, mirroring +the one-shot `experimental.wslc.portMappings` surface. Each entry is `{ windowsPort, containerPort }` +(both 1–65535; `protocol` defaults to and only accepts `tcp` — `udp` is rejected because the WSLC +SDK runtime returns `E_NOTIMPL`). Port mappings are per-container, applied at `WslcCreateContainer` +during `provision`, and frozen for the sandbox's lifetime. A duplicate `windowsPort` is rejected with +`policy_validation`. Post-provision phases carry no port config. ## Error mapping Exact-contract `malformed_request` failures occur before daemon connection and @@ -196,6 +204,20 @@ should be exercised **through the harness**, not by pointing `wxc-exec --config` ## Known limitations +- **No per-sandbox session sizing.** `cpuCount`, `memoryMb`, `gpu`, and `storagePath` are absent from + the provision contract and rejected as unknown fields. They configure the WSLc *session*, and the + daemon shares one session across every sandbox, so no phase caller can set them per sandbox. MXC + calls none of the optional `WslcSetSessionSettings*` entry points on this path, so every sandbox + runs on the SDK session defaults: **2 CPUs, 2000 MB**, a 300,000 ms boot timeout, and a ~1 GB VHD. + The one-shot surface still honors all four, since each run owns its session. + +- **The image store is pinned** to `%TEMP%\mxc-wslc-sessions`. Pre-pull images there: a one-shot + config can point `experimental.wslc.storagePath` at another location and match it with + `setup-wslc.ps1 -StoragePath`, but state-aware has no such field, and images cached elsewhere are + not found. A store also admits only one live session, so while a sandbox is provisioned a one-shot + run on the same store fails with `ERROR_SHARING_VIOLATION` until the daemon idles out; give the + one-shot run its own `storagePath` to run the two concurrently. + - **Serialized exec (deferred).** Because the daemon's single worker thread blocks on `WaitForSingleObject` for the whole `exec`, no other sandbox can provision or exec while one command runs, and a per-container single-flight `Busy` guard is not yet meaningful. The intended diff --git a/schemas/dev/mxc-config.schema.0.9.0-alpha.json b/schemas/dev/mxc-config.schema.0.9.0-alpha.json index be6d9e49fa..e98ca1b061 100644 --- a/schemas/dev/mxc-config.schema.0.9.0-alpha.json +++ b/schemas/dev/mxc-config.schema.0.9.0-alpha.json @@ -1475,6 +1475,13 @@ "imageTarPath": { "description": "Optional path to a local container image archive.", "type": "string" + }, + "portMappings": { + "description": "Optional host-to-container TCP port mappings. Per-container, so unlike the one-shot sizing knobs it is honored on the shared daemon session.", + "items": { + "$ref": "#/definitions/PortMapping" + }, + "type": "array" } }, "type": "object" diff --git a/schemas/dev/mxc-config.schema.0.9.0-dev.json b/schemas/dev/mxc-config.schema.0.9.0-dev.json index 78714b3899..9de0e35bde 100644 --- a/schemas/dev/mxc-config.schema.0.9.0-dev.json +++ b/schemas/dev/mxc-config.schema.0.9.0-dev.json @@ -699,7 +699,7 @@ "type": "string" }, "PortMapping": { - "description": "A single host → container port forward. Reachable only under the permissive `experimental` surface, so unknown fields are tolerated (forward-compat).", + "description": "A single host -> container port forward. Reachable only under the permissive `experimental` surface, so unknown fields are tolerated (forward-compat).", "properties": { "containerPort": { "description": "Container port.", @@ -1106,7 +1106,7 @@ ] }, "portMappings": { - "description": "Host → container port forwards. Only TCP is currently supported; the parser rejects `udp` because the WSLC SDK runtime returns `E_NOTIMPL` for UDP port mappings.", + "description": "Host -> container port forwards. Only TCP is currently supported; the parser rejects `udp` because the WSLC SDK runtime returns `E_NOTIMPL` for UDP port mappings.", "items": { "$ref": "#/definitions/PortMapping" }, @@ -1144,7 +1144,7 @@ "type": "object" }, "WslcProvisionPhase": { - "description": "Per-phase WSLc **provision** configuration (state-aware lifecycle), nested under `experimental.wslc.provision`. Carries only what the amortized daemon session honors: the container image (or a local tarball to import).\n\nFilesystem mounts and network mode derive from the top-level `policy` section (readwrite / readonly paths, network), not from here. The one-shot-only sizing knobs (`cpuCount` / `memoryMb` / `gpu` / `storagePath` / `portMappings`) are deliberately absent: the daemon shares a single session across sandboxes and does not apply per-sandbox sizing. start / exec / stop / deprovision carry no backend-specific config (the exec command flows through the top-level `process` section), so they have no phase struct.", + "description": "Per-phase WSLc **provision** configuration (state-aware lifecycle), nested under `experimental.wslc.provision`. Carries what the amortized daemon session honors: the container image (or a local tarball to import) and the host -> container port forwards.\n\nFilesystem mounts and network mode derive from the top-level `policy` section (readwrite / readonly paths, network), not from here. The one-shot fields `cpuCount` / `memoryMb` / `gpu` / `storagePath` are deliberately absent: they are properties of the WSLC session, and the daemon shares one session across every sandbox, so no phase caller can set them per sandbox. `portMappings`, by contrast, is per-container, so it is honored here, matching the one-shot surface. start / exec / stop / deprovision carry no backend-specific config (the exec command flows through the top-level `process` section), so they have no phase struct.", "properties": { "image": { "description": "Container image reference (e.g. `alpine:latest`). Defaults to `alpine:latest` when omitted.", @@ -1159,6 +1159,16 @@ "string", "null" ] + }, + "portMappings": { + "description": "Host -> container port forwards. Only TCP is currently supported; the parser rejects `udp` because the WSLC SDK runtime returns `E_NOTIMPL` for UDP port mappings. Mirrors the one-shot `Wslc::port_mappings`.", + "items": { + "$ref": "#/definitions/PortMapping" + }, + "type": [ + "array", + "null" + ] } }, "type": "object" diff --git a/sdk/dotnet/Microsoft.Mxc.Sdk.Tests/MxcLifecycleTests.cs b/sdk/dotnet/Microsoft.Mxc.Sdk.Tests/MxcLifecycleTests.cs index 45b8dd2198..ca5f2a829f 100644 --- a/sdk/dotnet/Microsoft.Mxc.Sdk.Tests/MxcLifecycleTests.cs +++ b/sdk/dotnet/Microsoft.Mxc.Sdk.Tests/MxcLifecycleTests.cs @@ -3,6 +3,7 @@ using System.Reflection; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; using Microsoft.Mxc.Sdk; using Xunit; @@ -193,6 +194,58 @@ public void CompatibilityProvisionOptions_RejectsLegacyNetwork( Assert.Contains("directional egress, ingress, and host-loopback", error.Message); } + [Fact] + public void WslcProvisionOptions_PortMappingsLandOnTheProvisionPhase() + { + var envelope = MxcLifecycle.BuildProvisionEnvelope( + StateAwareContainment.Wslc, + new WslcProvisionOptions + { + PortMappings = + [ + new WslcPortMapping(8080, 80), + new WslcPortMapping(8443, 443), + ], + }); + + var mappings = envelope["experimental"]?["wslc"]?["provision"]?["portMappings"] as JsonArray; + Assert.NotNull(mappings); + Assert.Equal(2, mappings!.Count); + Assert.Equal(8080, (int)mappings[0]!["windowsPort"]!); + Assert.Equal(80, (int)mappings[0]!["containerPort"]!); + Assert.Equal(8443, (int)mappings[1]!["windowsPort"]!); + Assert.Equal(443, (int)mappings[1]!["containerPort"]!); + } + + [Fact] + public void WslcProvisionOptions_OmittedPortMappingsEmitNoKey() + { + var envelope = MxcLifecycle.BuildProvisionEnvelope( + StateAwareContainment.Wslc, + new WslcProvisionOptions { Image = "alpine:latest" }); + + Assert.Null(envelope["experimental"]?["wslc"]?["provision"]?["portMappings"]); + } + + [Fact] + public void WslcProvisionOptions_RoundTripPreservesPortMappings() + { + var jsonOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + var json = JsonSerializer.Serialize( + new WslcProvisionOptions { PortMappings = [new WslcPortMapping(8080, 80)] }, + jsonOptions); + + var roundTripped = JsonSerializer.Deserialize(json, jsonOptions)!; + + var mapping = Assert.Single(roundTripped.PortMappings!); + Assert.Equal(8080, mapping.WindowsPort); + Assert.Equal(80, mapping.ContainerPort); + } + [Fact] public void WslcProvisionOptions_RoundTripDoesNotInventLegacyNetworkFields() { diff --git a/sdk/dotnet/Microsoft.Mxc.Sdk/MxcLifecycle.cs b/sdk/dotnet/Microsoft.Mxc.Sdk/MxcLifecycle.cs index d3a2963332..14e50e9eb6 100644 --- a/sdk/dotnet/Microsoft.Mxc.Sdk/MxcLifecycle.cs +++ b/sdk/dotnet/Microsoft.Mxc.Sdk/MxcLifecycle.cs @@ -132,6 +132,26 @@ internal static JsonObject BuildProvisionEnvelope( "provision", "imageTarPath", wslc.ImageTarPath); + if (wslc.PortMappings is { Count: > 0 }) + { + var portMappings = new JsonArray(); + foreach (var mapping in wslc.PortMappings) + { + portMappings.Add(new JsonObject + { + ["windowsPort"] = (int)mapping.WindowsPort, + ["containerPort"] = (int)mapping.ContainerPort, + }); + } + + SetBackendConfig( + envelope, + backend, + "provision", + "portMappings", + portMappings); + } + break; } diff --git a/sdk/dotnet/Microsoft.Mxc.Sdk/SandboxRequest.cs b/sdk/dotnet/Microsoft.Mxc.Sdk/SandboxRequest.cs index 5c6556c99f..5c1fefb163 100644 --- a/sdk/dotnet/Microsoft.Mxc.Sdk/SandboxRequest.cs +++ b/sdk/dotnet/Microsoft.Mxc.Sdk/SandboxRequest.cs @@ -231,6 +231,14 @@ public WslcPortMapping(int windowsPort, int containerPort) ContainerPort = ValidatePort(containerPort, nameof(containerPort)); } + // System.Text.Json binds constructor parameters to properties by name and + // type, so the int overload above cannot deserialize into ushort members. + [JsonConstructor] + private WslcPortMapping(ushort windowsPort, ushort containerPort) + : this((int)windowsPort, (int)containerPort) + { + } + /// The listening port on the Windows host. [JsonPropertyName("windowsPort")] public ushort WindowsPort { get; } diff --git a/sdk/dotnet/Microsoft.Mxc.Sdk/StateAwareTypes.cs b/sdk/dotnet/Microsoft.Mxc.Sdk/StateAwareTypes.cs index b5b4ef9195..8c7faee7f7 100644 --- a/sdk/dotnet/Microsoft.Mxc.Sdk/StateAwareTypes.cs +++ b/sdk/dotnet/Microsoft.Mxc.Sdk/StateAwareTypes.cs @@ -182,6 +182,12 @@ public sealed class WslcProvisionOptions : StateAwareProvisionOptions /// Optional local image archive to import instead of pulling. public string? ImageTarPath { get; set; } + + /// + /// Host-to-container TCP port forwards, applied at provision and fixed for + /// the sandbox's life. + /// + public List? PortMappings { get; set; } } /// diff --git a/sdk/dotnet/README.md b/sdk/dotnet/README.md index 3762e0852f..5a594a5e2e 100644 --- a/sdk/dotnet/README.md +++ b/sdk/dotnet/README.md @@ -790,6 +790,7 @@ var wslc = new WslcProvisionOptions { Image = "alpine:latest", ImageTarPath = @"C:\images\alpine.tar", // optional local import + PortMappings = [new WslcPortMapping(8080, 80)], // host 8080 -> container 80 Network = new StateAwareNetworkPolicy { Egress = new NetworkEgressPolicy { Default = NetworkAction.Allow }, @@ -802,6 +803,11 @@ var wslc = new WslcProvisionOptions }; ``` +`PortMappings` forwards host TCP ports into the container. It is applied when +the container is created and fixed for the sandbox's life, so later phases +carry no port configuration. `WindowsPort` must be unique across the list, and +TCP is the only supported protocol. + All state-aware backends use the exact development schema `0.9.0-alpha`. `Version` may be omitted or explicitly set to that registered value; the SDK rejects other values rather than emitting an envelope for an unregistered diff --git a/sdk/node/README.md b/sdk/node/README.md index bd2a0a317f..36d1481b1e 100644 --- a/sdk/node/README.md +++ b/sdk/node/README.md @@ -407,8 +407,11 @@ const provisioned = await provisionSandbox('wslc', { Provision may also supply `filesystem.readwritePaths` / `readonlyPaths` (mounted for the sandbox's lifetime) and a backend-specific `image` / -`imageTarPath`. Inject a cooperative proxy during exec with -`runtimeConfig.networkProxy`: +`imageTarPath` / `portMappings`. `portMappings` wires host → container TCP +forwards (`{ windowsPort, containerPort, protocol: 'tcp' }`), applied at +provision and fixed for the life of the sandbox; `protocol` defaults to `'tcp'` +and `'udp'` is rejected, and `windowsPort` must be unique and non-zero. Inject a +cooperative proxy during exec with `runtimeConfig.networkProxy`: ```typescript await execInSandboxAsync(provisioned.sandboxId, { @@ -417,8 +420,9 @@ await execInSandboxAsync(provisioned.sandboxId, { }); ``` -All state-aware requests default to the exact development schema -`0.9.0-alpha`. See +Per-host egress filtering (`allowedHosts` / `blockedHosts`) is not supported on +WSLc and is rejected rather than ignored. All state-aware requests default to +the exact development schema `0.9.0-alpha`. See [`docs/wsl/wslc-state-aware.md`](https://github.com/microsoft/mxc/blob/main/docs/wsl/wslc-state-aware.md) for the per-phase config matrix. diff --git a/sdk/node/src/generated/v0_9_0_alpha/wire.ts b/sdk/node/src/generated/v0_9_0_alpha/wire.ts index 51040530d1..4d2207923d 100644 --- a/sdk/node/src/generated/v0_9_0_alpha/wire.ts +++ b/sdk/node/src/generated/v0_9_0_alpha/wire.ts @@ -900,6 +900,10 @@ export interface WslcProvision { * Optional path to a local container image archive. */ imageTarPath?: string; + /** + * Optional host-to-container TCP port mappings. Per-container, so unlike the one-shot sizing knobs it is honored on the shared daemon session. + */ + portMappings?: PortMapping[]; } /** diff --git a/sdk/node/src/generated/wire.ts b/sdk/node/src/generated/wire.ts index 51faf3f0f8..5c37c80bc0 100644 --- a/sdk/node/src/generated/wire.ts +++ b/sdk/node/src/generated/wire.ts @@ -327,7 +327,7 @@ export interface NetworkRule { export type Phase = "provision" | "start" | "exec" | "stop" | "deprovision"; /** - * A single host → container port forward. Reachable only under the permissive `experimental` surface, so unknown fields are tolerated (forward-compat). + * A single host -> container port forward. Reachable only under the permissive `experimental` surface, so unknown fields are tolerated (forward-compat). */ export interface PortMapping { /** @@ -566,7 +566,7 @@ export interface Wslc { */ memoryMb?: number | null; /** - * Host → container port forwards. Only TCP is currently supported; the parser rejects `udp` because the WSLC SDK runtime returns `E_NOTIMPL` for UDP port mappings. + * Host -> container port forwards. Only TCP is currently supported; the parser rejects `udp` because the WSLC SDK runtime returns `E_NOTIMPL` for UDP port mappings. */ portMappings?: PortMapping[] | null; /** @@ -585,9 +585,9 @@ export interface Wslc { } /** - * Per-phase WSLc **provision** configuration (state-aware lifecycle), nested under `experimental.wslc.provision`. Carries only what the amortized daemon session honors: the container image (or a local tarball to import). + * Per-phase WSLc **provision** configuration (state-aware lifecycle), nested under `experimental.wslc.provision`. Carries what the amortized daemon session honors: the container image (or a local tarball to import) and the host -> container port forwards. * - * Filesystem mounts and network mode derive from the top-level `policy` section (readwrite / readonly paths, network), not from here. The one-shot-only sizing knobs (`cpuCount` / `memoryMb` / `gpu` / `storagePath` / `portMappings`) are deliberately absent: the daemon shares a single session across sandboxes and does not apply per-sandbox sizing. start / exec / stop / deprovision carry no backend-specific config (the exec command flows through the top-level `process` section), so they have no phase struct. + * Filesystem mounts and network mode derive from the top-level `policy` section (readwrite / readonly paths, network), not from here. The one-shot fields `cpuCount` / `memoryMb` / `gpu` / `storagePath` are deliberately absent: they are properties of the WSLC session, and the daemon shares one session across every sandbox, so no phase caller can set them per sandbox. `portMappings`, by contrast, is per-container, so it is honored here, matching the one-shot surface. start / exec / stop / deprovision carry no backend-specific config (the exec command flows through the top-level `process` section), so they have no phase struct. */ export interface WslcProvisionPhase { /** @@ -598,6 +598,10 @@ export interface WslcProvisionPhase { * Path to a local image tarball to import instead of pulling. */ imageTarPath?: string | null; + /** + * Host -> container port forwards. Only TCP is currently supported; the parser rejects `udp` because the WSLC SDK runtime returns `E_NOTIMPL` for UDP port mappings. Mirrors the one-shot `Wslc::port_mappings`. + */ + portMappings?: PortMapping[] | null; [k: string]: unknown; } diff --git a/sdk/node/src/state-aware-types.ts b/sdk/node/src/state-aware-types.ts index 80bbae88a5..48a27c6b9f 100644 --- a/sdk/node/src/state-aware-types.ts +++ b/sdk/node/src/state-aware-types.ts @@ -5,6 +5,7 @@ import { ContainmentBackend, FilesystemConfig, DirectionalNetworkConfig, + PortMapping, RuntimeConfig, ProcessConfig, TelemetryConfig, @@ -180,6 +181,13 @@ export interface WslcProvisionConfig extends StateAwareConfig { * `experimental.wslc.provision.imageTarPath` on the wire. */ imageTarPath?: string; + /** + * Host -> container port mappings, applied at provision and fixed for the + * life of the sandbox. Only TCP is supported: `protocol` defaults to `"tcp"` + * and `"udp"` is rejected. Nested under + * `experimental.wslc.provision.portMappings` on the wire. + */ + portMappings?: PortMapping[]; } export type WslcStartConfig = StateAwareConfig; diff --git a/sdk/node/tests/unit/wire-conformance-state-aware.test.ts b/sdk/node/tests/unit/wire-conformance-state-aware.test.ts index 4db0a4f533..827f713f68 100644 --- a/sdk/node/tests/unit/wire-conformance-state-aware.test.ts +++ b/sdk/node/tests/unit/wire-conformance-state-aware.test.ts @@ -32,7 +32,7 @@ import { test } from 'node:test'; -import type { ProcessConfig } from '../../src/types.js'; +import type { ProcessConfig, PortMapping as PublicPortMapping } from '../../src/types.js'; import type { Phase, @@ -159,10 +159,11 @@ type _ProvisionWireKeysNonVacuous = AssertTrue< // WSLc is the second state-aware backend, so the oracle must cover it too or a // wire-model change to the WSLc surface would regenerate `wire.ts`, pass the // codegen gate, and leave the SDK silently lagging with no CI signal. WSLc's -// only per-phase wire object is provision (`image` / `imageTarPath`); start, -// exec, stop, and deprovision have wire associated type `()` and must expose no -// backend-specific field. `filesystem` and `network` are lifted top-level wire -// fields (see `LiftedPhaseKey`), so they are excluded from the backend-key sets. +// only per-phase wire object is provision (`image` / `imageTarPath` / +// `portMappings`); start, exec, stop, and deprovision have wire associated type +// `()` and must expose no backend-specific field. `filesystem` and `network` +// are lifted top-level wire fields (see `LiftedPhaseKey`), so they are excluded +// from the backend-key sets. type _WslcProvisionPublicKeys = AssertTrue< Equivalent, WireKeys>, never> >; @@ -171,11 +172,21 @@ type _WslcProvisionWireKeys = AssertTrue< >; type _WslcProvisionFieldValueTypes = AssertTrue< Equivalent< - PublicFieldValues, - WireFieldValues + PublicFieldValues, + WireFieldValues > >; +// `portMappings` is excluded from the structural value comparison above: the +// generated wire element carries a `[k: string]: unknown` index signature and a +// nullable `protocol` that strict `Equivalent` trips on. It is instead asserted +// to REUSE the public one-shot leaf, whose shape the one-shot oracle already +// pins, mirroring the `process` delegation. +type WslcProvisionValueKeys = Exclude, 'portMappings'>; +type _WslcProvisionPortMappingsReuse = AssertTrue< + Equivalent, PublicPortMapping[]> +>; + type _WslcStartNoBackendKeys = AssertTrue, never>>; type _WslcExecNoBackendKeys = AssertTrue, never>>; type _WslcStopNoBackendKeys = AssertTrue, never>>; @@ -186,10 +197,10 @@ type _WslcDeprovisionNoBackendKeys = AssertTrue< // Non-vacuity guards (see the isolation_session pins above): pin the derived key // sets so a derivation bug fails the oracle rather than silently disabling it. type _WslcProvisionKeysNonVacuous = AssertTrue< - Equivalent, 'image' | 'imageTarPath'> + Equivalent, 'image' | 'imageTarPath' | 'portMappings'> >; type _WslcProvisionWireKeysNonVacuous = AssertTrue< - Equivalent, 'image' | 'imageTarPath'> + Equivalent, 'image' | 'imageTarPath' | 'portMappings'> >; // --- delegation to the one-shot oracle (documented, asserted) -------------- @@ -220,6 +231,7 @@ export type StateAwareWireConformanceAssertions = [ _WslcProvisionPublicKeys, _WslcProvisionWireKeys, _WslcProvisionFieldValueTypes, + _WslcProvisionPortMappingsReuse, _WslcStartNoBackendKeys, _WslcExecNoBackendKeys, _WslcStopNoBackendKeys, diff --git a/src/backends/wslc/common/src/container_steps.rs b/src/backends/wslc/common/src/container_steps.rs index 6901a7e695..067d6e003e 100644 --- a/src/backends/wslc/common/src/container_steps.rs +++ b/src/backends/wslc/common/src/container_steps.rs @@ -806,22 +806,24 @@ pub unsafe fn resolve_image( /// /// # Safety /// `sdk` must hold valid function pointers and `session` must be a live handle. +#[allow(clippy::too_many_arguments)] pub unsafe fn create_daemon_container( sdk: &WslcSdk, session: WslcSession, image: &str, mounts: &[VolumeMount], + port_mappings: &[PortMapping], net_mode: WslcContainerNetworkingMode, keepalive: &mut ProcessSettings, logger: &mut Logger, ) -> Result { - // Daemon containers never forward ports (no state-aware port-mapping config) - // and set no container flags (auto-remove/gpu/privileged are one-shot-only). + // Daemon containers set no container flags (auto-remove / gpu / privileged + // are one-shot-only). let mut container_settings = ContainerSettings::build( sdk, image, mounts, - &[], + port_mappings, net_mode, WslcContainerFlags::WSLC_CONTAINER_FLAG_NONE, logger, diff --git a/src/backends/wslc/common/src/daemon_protocol.rs b/src/backends/wslc/common/src/daemon_protocol.rs index def14663d2..a27981a5f5 100644 --- a/src/backends/wslc/common/src/daemon_protocol.rs +++ b/src/backends/wslc/common/src/daemon_protocol.rs @@ -37,13 +37,13 @@ pub const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024; /// from the same build, so in normal operation both sides always match; the /// version guards against a stale daemon left running by a different mxc /// install. Bump only for incompatible changes to framing or message shape. -pub const PROTOCOL_VERSION: u32 = 2; +pub const PROTOCOL_VERSION: u32 = 3; // --------------------------------------------------------------------------- // Per-phase config structs (daemon-internal; NOT the public wire schema) // --------------------------------------------------------------------------- -/// One host→container directory mount, mirroring the one-shot runner's volume +/// One host -> container directory mount, mirroring the one-shot runner's volume /// handling. Paths are host-absolute; `container` is the in-container mount /// point. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -53,6 +53,15 @@ pub struct VolumeMount { pub read_only: bool, } +/// One host -> container port forward, mirroring the one-shot runner's port +/// handling. Only TCP is supported (the wire model rejects `udp`), so no +/// protocol field is carried. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PortMapping { + pub windows_port: u16, + pub container_port: u16, +} + /// Container network mode. Mirrors exactly what the one-shot WSLc runner /// supports — no host-filtering / egress allow-deny (the SDK grants no /// `CAP_NET_ADMIN` and cannot give VM-level enforcement without breaking other @@ -84,6 +93,9 @@ pub struct ProvisionConfig { /// Container network mode. #[serde(default)] pub network: NetworkMode, + /// Host↔container port forwards (TCP). + #[serde(default)] + pub port_mappings: Vec, } /// Inputs to `start`: the container was created at provision; start boots it. @@ -330,6 +342,10 @@ mod tests { read_only: true, }], network: NetworkMode::Bridged, + port_mappings: vec![PortMapping { + windows_port: 8080, + container_port: 80, + }], })); } diff --git a/src/backends/wslc/common/src/state_aware.rs b/src/backends/wslc/common/src/state_aware.rs index 29483aca86..df0add859d 100644 --- a/src/backends/wslc/common/src/state_aware.rs +++ b/src/backends/wslc/common/src/state_aware.rs @@ -24,13 +24,15 @@ use wxc_common::state_aware_backend::{ null_pipe_handle, DeprovisionResult, ExecHandle, ExecOutcome, ExecStdio, ProvisionResult, StartResult, StatefulSandboxBackend, StopResult, }; -use wxc_common::validator::validate_state_aware_network_policy_support; +use wxc_common::validator::{ + validate_state_aware_network_policy_support, validate_wslc_port_mappings, +}; use crate::container_steps::OutStream; use crate::daemon_client::{DaemonClient, DaemonError}; use crate::daemon_protocol::{ - DeprovisionConfig, ErrKind, ExecConfig, NetworkMode, ProvisionConfig, StartConfig, StopConfig, - VolumeMount, + DeprovisionConfig, ErrKind, ExecConfig, NetworkMode, PortMapping, ProvisionConfig, StartConfig, + StopConfig, VolumeMount, }; use crate::policy::{ exec_proxy_url, validate_exec_policy, validate_post_provision_policy, validate_provision_policy, @@ -230,12 +232,15 @@ impl StatefulSandboxBackend for WslcStateAwareRunner { fn validate_provision( &self, request: &ExecutionRequest, - _config: Option<&WslcProvisionConfig>, + config: Option<&WslcProvisionConfig>, ) -> Result<(), MxcError> { validate_state_aware_network_policy_support( request, crate::policy::network_policy_support(), )?; + // `--dry-run` stops here, so it must reject the same port mappings + // `provision` does. + map_provision_port_mappings(config)?; validate_provision_policy(request) } @@ -356,6 +361,7 @@ fn build_provision_config( .as_ref() .and_then(|c| c.image.clone()) .unwrap_or_else(|| DEFAULT_IMAGE.to_string()); + let port_mappings = map_provision_port_mappings(config.as_ref())?; let image_tar_path = config.and_then(|c| c.image_tar_path); // WSLc provision-time filesystem-policy gate (D6 normalization → D3 @@ -384,9 +390,29 @@ fn build_provision_config( image_tar_path, volumes, network, + port_mappings, }) } +/// Map and validate the provision phase's port mappings (wire → daemon). +fn map_provision_port_mappings( + config: Option<&WslcProvisionConfig>, +) -> Result, MxcError> { + let Some(mappings) = config.and_then(|c| c.port_mappings.as_ref()) else { + return Ok(Vec::new()); + }; + let validated = + validate_wslc_port_mappings(mappings, "experimental.wslc.provision.portMappings") + .map_err(MxcError::policy_validation)?; + Ok(validated + .into_iter() + .map(|pm| PortMapping { + windows_port: pm.windows_port, + container_port: pm.container_port, + }) + .collect()) +} + /// State-aware adapter over the shared WSLc provision policy gate /// ([`crate::policy_mapping::apply_provision_policy_gate`]): runs the full /// three-step gate (D6 normalization → D3 delegation → denied-path overlap), @@ -455,6 +481,7 @@ mod tests { use wxc_common::models::{ ContainerPolicy, NetworkAction, NetworkEgressPolicy, NetworkIngressPolicy, }; + use wxc_common::wire::{PortMapping as WirePortMapping, TransportProtocol}; /// A `Piped` exec is refused before the backend touches the daemon. /// @@ -734,6 +761,7 @@ mod tests { let phase = WslcProvisionConfig { image: Some("custom/image:tag".to_string()), image_tar_path: Some("C:\\images\\custom.tar".to_string()), + port_mappings: None, }; let cfg = build_provision_config(&ExecutionRequest::default(), Some(phase)).unwrap(); assert_eq!(cfg.image, "custom/image:tag"); @@ -741,6 +769,153 @@ mod tests { cfg.image_tar_path.as_deref(), Some("C:\\images\\custom.tar") ); + assert!(cfg.port_mappings.is_empty()); + } + + #[test] + fn build_provision_config_forwards_port_mappings() { + let phase = WslcProvisionConfig { + image: None, + image_tar_path: None, + port_mappings: Some(vec![ + WirePortMapping { + windows_port: 8080, + container_port: 80, + protocol: None, + }, + WirePortMapping { + windows_port: 8443, + container_port: 443, + protocol: Some(TransportProtocol::Tcp), + }, + ]), + }; + let cfg = build_provision_config(&ExecutionRequest::default(), Some(phase)).unwrap(); + assert_eq!(cfg.port_mappings.len(), 2); + assert_eq!(cfg.port_mappings[0].windows_port, 8080); + assert_eq!(cfg.port_mappings[0].container_port, 80); + assert_eq!(cfg.port_mappings[1].windows_port, 8443); + assert_eq!(cfg.port_mappings[1].container_port, 443); + } + + #[test] + fn build_provision_config_rejects_duplicate_windows_port() { + let phase = WslcProvisionConfig { + image: None, + image_tar_path: None, + port_mappings: Some(vec![ + WirePortMapping { + windows_port: 8080, + container_port: 80, + protocol: None, + }, + WirePortMapping { + windows_port: 8080, + container_port: 8080, + protocol: None, + }, + ]), + }; + let err = build_provision_config(&ExecutionRequest::default(), Some(phase)).unwrap_err(); + assert_eq!( + err.code, + wxc_common::mxc_error::MxcErrorCode::PolicyValidation + ); + assert!( + err.message.contains("duplicate windowsPort"), + "got: {}", + err.message + ); + } + + #[test] + fn build_provision_config_rejects_zero_port() { + let phase = WslcProvisionConfig { + image: None, + image_tar_path: None, + port_mappings: Some(vec![WirePortMapping { + windows_port: 0, + container_port: 80, + protocol: None, + }]), + }; + let err = build_provision_config(&ExecutionRequest::default(), Some(phase)).unwrap_err(); + assert_eq!( + err.code, + wxc_common::mxc_error::MxcErrorCode::PolicyValidation + ); + assert!(err.message.contains("windowsPort"), "got: {}", err.message); + } + + /// `--dry-run` stops after `validate_provision`, so the port checks must + /// fire there too — not only inside `provision`. + #[test] + fn validate_provision_rejects_duplicate_windows_port() { + let phase = WslcProvisionConfig { + image: None, + image_tar_path: None, + port_mappings: Some(vec![ + WirePortMapping { + windows_port: 8080, + container_port: 80, + protocol: None, + }, + WirePortMapping { + windows_port: 8080, + container_port: 8080, + protocol: None, + }, + ]), + }; + let err = WslcStateAwareRunner + .validate_provision(&ExecutionRequest::default(), Some(&phase)) + .unwrap_err(); + assert_eq!( + err.code, + wxc_common::mxc_error::MxcErrorCode::PolicyValidation + ); + assert!( + err.message.contains("duplicate windowsPort"), + "got: {}", + err.message + ); + } + + #[test] + fn validate_provision_rejects_zero_port() { + let phase = WslcProvisionConfig { + image: None, + image_tar_path: None, + port_mappings: Some(vec![WirePortMapping { + windows_port: 0, + container_port: 80, + protocol: None, + }]), + }; + let err = WslcStateAwareRunner + .validate_provision(&ExecutionRequest::default(), Some(&phase)) + .unwrap_err(); + assert_eq!( + err.code, + wxc_common::mxc_error::MxcErrorCode::PolicyValidation + ); + assert!(err.message.contains("windowsPort"), "got: {}", err.message); + } + + #[test] + fn validate_provision_accepts_valid_port_mappings() { + let phase = WslcProvisionConfig { + image: None, + image_tar_path: None, + port_mappings: Some(vec![WirePortMapping { + windows_port: 8080, + container_port: 80, + protocol: None, + }]), + }; + WslcStateAwareRunner + .validate_provision(&ExecutionRequest::default(), Some(&phase)) + .unwrap(); } #[test] @@ -749,6 +924,7 @@ mod tests { let cfg = build_provision_config(&ExecutionRequest::default(), phase).unwrap(); assert_eq!(cfg.image, "alpine:latest"); assert!(cfg.image_tar_path.is_none()); + assert!(cfg.port_mappings.is_empty()); } } @@ -759,6 +935,7 @@ mod tests { WslcProvisionConfig { image: Some("custom/image:tag".to_string()), image_tar_path: None, + port_mappings: None, }, "custom/image:tag", None, @@ -767,6 +944,7 @@ mod tests { WslcProvisionConfig { image: None, image_tar_path: Some("C:\\images\\custom.tar".to_string()), + port_mappings: None, }, "alpine:latest", Some("C:\\images\\custom.tar"), @@ -775,6 +953,7 @@ mod tests { WslcProvisionConfig { image: Some(String::new()), image_tar_path: Some(String::new()), + port_mappings: None, }, "", Some(""), diff --git a/src/backends/wslc/common/src/wsl_container_runner.rs b/src/backends/wslc/common/src/wsl_container_runner.rs index a3a68dbbf6..ac1f391702 100644 --- a/src/backends/wslc/common/src/wsl_container_runner.rs +++ b/src/backends/wslc/common/src/wsl_container_runner.rs @@ -662,14 +662,13 @@ impl ScriptRunner for WSLContainerRunner { fn validate_runner(&self, request: &ExecutionRequest) -> Result<(), ScriptResponse> { reject_unsupported_lifecycle(request)?; policy::reject_ui_policy(request).map_err(as_wslc_rejection)?; - if request.policy.needs_host_filtering() { + if request.policy.has_host_lists() { return Err(WslcError::Rejected( - "WSLc: per-host egress filtering (allowedHosts with \ - defaultPolicy='block', or blockedHosts with defaultPolicy='allow') \ - is not supported. A WSL container has no CAP_NET_ADMIN for in-container \ - iptables, and VM-level enforcement is not available without breaking other \ - security guarantees (e.g. MDE). Use network.proxy (defaultPolicy='allow') \ - for cooperative host filtering, or remove the host lists." + "WSLc: per-host egress filtering (allowedHosts/blockedHosts) is not supported. \ + A WSL container has no CAP_NET_ADMIN for in-container iptables, and VM-level \ + enforcement is not available without breaking other security guarantees (e.g. \ + MDE). Use network.proxy (defaultPolicy='allow') for cooperative host filtering, \ + or remove the host lists." .to_string(), ) .into_response()); @@ -2428,6 +2427,40 @@ mod tests { assert!(runner.validate_runner(&request).is_err()); } + #[test] + fn validate_runner_rejects_redundant_block_with_blocked_hosts() { + let request = ExecutionRequest { + containment: wxc_common::models::ContainmentBackend::Wslc, + policy: wxc_common::models::ContainerPolicy { + default_network_policy: NetworkPolicy::Block, + blocked_hosts: vec!["evil.com".to_string()], + ..Default::default() + }, + ..Default::default() + }; + let runner = WSLContainerRunner::new(&WslcConfig::default()); + let err = runner.validate_runner(&request).unwrap_err(); + assert!(err.error_message.contains("per-host egress filtering")); + } + + #[test] + fn validate_runner_rejects_redundant_allow_with_allowed_hosts() { + // An allowlist under an `allow` default reads as a restriction but + // enforces none: accepting it leaves all egress open (#824). + let request = ExecutionRequest { + containment: wxc_common::models::ContainmentBackend::Wslc, + policy: wxc_common::models::ContainerPolicy { + default_network_policy: NetworkPolicy::Allow, + allowed_hosts: vec!["github.com".to_string()], + ..Default::default() + }, + ..Default::default() + }; + let runner = WSLContainerRunner::new(&WslcConfig::default()); + let err = runner.validate_runner(&request).unwrap_err(); + assert!(err.error_message.contains("per-host egress filtering")); + } + #[test] fn validate_runner_rejects_allow_local_network() { let request = ExecutionRequest { diff --git a/src/backends/wslc/daemon/src/session_manager.rs b/src/backends/wslc/daemon/src/session_manager.rs index a6fd2793e6..fe2853364a 100644 --- a/src/backends/wslc/daemon/src/session_manager.rs +++ b/src/backends/wslc/daemon/src/session_manager.rs @@ -41,7 +41,7 @@ use wslc_common::wslc_bindings::{ WslcContainer, WslcContainerGuard, WslcContainerNetworkingMode, WslcSdk, WslcSessionGuard, }; use wxc_common::logger::{Logger, Mode}; -use wxc_common::models::ScriptResponse; +use wxc_common::models::{PortMapping, ScriptResponse}; /// Fixed name of the single WSL2 utility-VM session the daemon owns. const SESSION_NAME: &str = "mxc-wslc-daemon"; @@ -390,6 +390,17 @@ impl Worker { read_only: v.read_only, }) .collect(); + // Daemon port mappings carry only ports (TCP-only today); map to the + // domain `PortMapping` that `ContainerSettings::build` consumes. + let port_mappings: Vec = config + .port_mappings + .iter() + .map(|p| PortMapping { + windows_port: p.windows_port, + container_port: p.container_port, + protocol: "tcp".to_string(), + }) + .collect(); let net_mode = match config.network { NetworkMode::None => WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_NONE, NetworkMode::Bridged => { @@ -419,6 +430,7 @@ impl Worker { session, &config.image, &mounts, + &port_mappings, net_mode, &mut keepalive, &mut self.logger, @@ -877,6 +889,7 @@ mod tests { image_tar_path: None, volumes: Vec::new(), network: Default::default(), + port_mappings: Vec::new(), }) .await .unwrap(); diff --git a/src/backends/wslc/daemon/tests/daemon_ipc.rs b/src/backends/wslc/daemon/tests/daemon_ipc.rs index ca27a8b0c2..292d6ccf93 100644 --- a/src/backends/wslc/daemon/tests/daemon_ipc.rs +++ b/src/backends/wslc/daemon/tests/daemon_ipc.rs @@ -112,6 +112,7 @@ fn full_lifecycle_over_pipe() { image_tar_path: None, volumes: Vec::new(), network: Default::default(), + port_mappings: Vec::new(), }) .expect("provision"); diff --git a/src/core/mxc_config_contract/src/dev/request.rs b/src/core/mxc_config_contract/src/dev/request.rs index 54820de840..af7e7f1f89 100644 --- a/src/core/mxc_config_contract/src/dev/request.rs +++ b/src/core/mxc_config_contract/src/dev/request.rs @@ -72,7 +72,9 @@ fn parse_provision(json: &str) -> Result { Containment::IsolationSession => { deserialize(json, "IsolationSession provision").map(ProvisionRequest::IsolationSession) } - Containment::Wslc => deserialize(json, "WSLC provision").map(ProvisionRequest::Wslc), + Containment::Wslc => { + deserialize(json, "WSLC provision").map(|r| ProvisionRequest::Wslc(Box::new(r))) + } } } diff --git a/src/core/mxc_config_contract/src/dev/state_aware/provision/mod.rs b/src/core/mxc_config_contract/src/dev/state_aware/provision/mod.rs index 4a64106854..16b518e5b1 100644 --- a/src/core/mxc_config_contract/src/dev/state_aware/provision/mod.rs +++ b/src/core/mxc_config_contract/src/dev/state_aware/provision/mod.rs @@ -13,8 +13,8 @@ pub enum ProvisionRequest { IsolationSession(IsolationSessionProvisionRequest), /// A Windows Sandbox provision request. WindowsSandbox(WindowsSandboxProvisionRequest), - /// A WSLC provision request. - Wslc(WslcProvisionRequest), + /// A WSLC provision request. Boxed to keep the enum small. + Wslc(Box), } mod containment; diff --git a/src/core/mxc_config_contract/src/dev/state_aware/provision/wslc.rs b/src/core/mxc_config_contract/src/dev/state_aware/provision/wslc.rs index b6634e0fea..f53ec2b78e 100644 --- a/src/core/mxc_config_contract/src/dev/state_aware/provision/wslc.rs +++ b/src/core/mxc_config_contract/src/dev/state_aware/provision/wslc.rs @@ -2,7 +2,7 @@ // Licensed under the MIT License. use crate::dev::state_aware::provision::ProvisionPhase; -use crate::dev::{Filesystem, Network, Telemetry}; +use crate::dev::{Filesystem, Network, PortMapping, Telemetry}; use crate::dev::{OptionalField, Version}; use serde::Deserialize; @@ -22,6 +22,10 @@ pub struct WslcProvision { /// Optional path to a local container image archive. #[serde(default)] pub image_tar_path: OptionalField, + /// Optional host-to-container TCP port mappings. Per-container, so unlike + /// the one-shot sizing knobs it is honored on the shared daemon session. + #[serde(default)] + pub port_mappings: OptionalField>, } /// State-aware WSLC experimental settings. diff --git a/src/core/mxc_engine/src/policy.rs b/src/core/mxc_engine/src/policy.rs index 4c368d5568..c5858c7f54 100644 --- a/src/core/mxc_engine/src/policy.rs +++ b/src/core/mxc_engine/src/policy.rs @@ -533,13 +533,14 @@ impl Containment { /// /// # Network policy /// -/// WSLC derives its networking mode from `allowOutbound` alone (bridged when -/// true, isolated when false). Per-host rules (`allowedHosts`/`blockedHosts`) -/// are accepted, but the backend currently enforces them with in-container -/// `iptables`, which the container lacks `CAP_NET_ADMIN` to install — so such a -/// policy **fails the run at spawn** rather than silently going unenforced. -/// Until enforcement moves to a VM-level API, prefer expressing WSLC network -/// intent with `allowOutbound`. +/// WSLC requires schema `0.9.0-alpha`, which authors networking through the +/// directional `egress` / `ingress` sections; the legacy `allowOutbound` / +/// `allowedHosts` / `blockedHosts` fields are refused at the version gate. +/// Only a uniform posture is accepted — all-allow (bridged) or all-deny +/// (isolated) across egress, ingress, and host-loopback. A mixed posture or any +/// per-host rule is rejected when the request is built: the container lacks +/// `CAP_NET_ADMIN` for the in-container `iptables` such rules would need, and +/// WSLC exposes no VM-level alternative. #[derive(Debug, Clone, PartialEq, Eq)] pub struct WslcSection { /// Container image reference (e.g. `"alpine:latest"`, `"python:3.12"`). diff --git a/src/core/wxc_common/src/config_contract_adapters/dev/common.rs b/src/core/wxc_common/src/config_contract_adapters/dev/common.rs index 0a7ff2de46..72d82ab16e 100644 --- a/src/core/wxc_common/src/config_contract_adapters/dev/common.rs +++ b/src/core/wxc_common/src/config_contract_adapters/dev/common.rs @@ -154,3 +154,22 @@ pub(super) fn convert_telemetry(value: contract::Telemetry) -> wire::Telemetry { enabled: enabled.into_option(), } } + +fn convert_protocol(value: contract::TransportProtocol) -> wire::TransportProtocol { + match value { + contract::TransportProtocol::Tcp => wire::TransportProtocol::Tcp, + } +} + +pub(super) fn convert_wslc_port_mapping(value: contract::PortMapping) -> wire::PortMapping { + let contract::PortMapping { + windows_port, + container_port, + protocol, + } = value; + wire::PortMapping { + windows_port: windows_port.get(), + container_port: container_port.get(), + protocol: protocol.into_option().map(convert_protocol), + } +} diff --git a/src/core/wxc_common/src/config_contract_adapters/dev/one_shot.rs b/src/core/wxc_common/src/config_contract_adapters/dev/one_shot.rs index d755cbe391..fc36612c21 100644 --- a/src/core/wxc_common/src/config_contract_adapters/dev/one_shot.rs +++ b/src/core/wxc_common/src/config_contract_adapters/dev/one_shot.rs @@ -3,7 +3,7 @@ use crate::config_contract_adapters::dev::common::{ convert_filesystem, convert_network, convert_process, convert_runtime_config, - convert_telemetry, convert_version, + convert_telemetry, convert_version, convert_wslc_port_mapping, }; use crate::wire; use mxc_config_contract::dev as contract; @@ -197,25 +197,6 @@ fn convert_windows_sandbox(value: contract::OneShotWindowsSandbox) -> wire::Wind } } -fn convert_protocol(value: contract::TransportProtocol) -> wire::TransportProtocol { - match value { - contract::TransportProtocol::Tcp => wire::TransportProtocol::Tcp, - } -} - -fn convert_wslc_port_mapping(value: contract::PortMapping) -> wire::PortMapping { - let contract::PortMapping { - windows_port, - container_port, - protocol, - } = value; - wire::PortMapping { - windows_port: windows_port.get(), - container_port: container_port.get(), - protocol: protocol.into_option().map(convert_protocol), - } -} - fn convert_wslc(value: contract::OneShotWslc) -> wire::Wslc { let contract::OneShotWslc { target_os, diff --git a/src/core/wxc_common/src/config_contract_adapters/dev/state_aware.rs b/src/core/wxc_common/src/config_contract_adapters/dev/state_aware.rs index 2dc36e9468..da146c44a1 100644 --- a/src/core/wxc_common/src/config_contract_adapters/dev/state_aware.rs +++ b/src/core/wxc_common/src/config_contract_adapters/dev/state_aware.rs @@ -3,7 +3,7 @@ use crate::config_contract_adapters::dev::common::{ convert_filesystem, convert_network, convert_process, convert_runtime_config, - convert_telemetry, convert_version, + convert_telemetry, convert_version, convert_wslc_port_mapping, }; use crate::error::WxcError; use crate::models::{IsolationSessionProvisionConfig, WslcProvisionConfig}; @@ -75,10 +75,17 @@ fn convert_wslc_provision(value: contract::WslcProvision) -> WslcProvisionConfig let contract::WslcProvision { image, image_tar_path, + port_mappings, } = value; WslcProvisionConfig { image: image.into_option(), image_tar_path: image_tar_path.into_option(), + port_mappings: port_mappings.into_option().map(|mappings| { + mappings + .into_iter() + .map(convert_wslc_port_mapping) + .collect() + }), } } @@ -149,7 +156,7 @@ pub(super) fn provision_into_input( contract::ProvisionRequest::WindowsSandbox(request) => { windows_sandbox_provision_into_input(request) } - contract::ProvisionRequest::Wslc(request) => wslc_provision_into_input(request), + contract::ProvisionRequest::Wslc(request) => wslc_provision_into_input(*request), } } diff --git a/src/core/wxc_common/src/config_contract_adapters/dev/state_aware_tests/provision.rs b/src/core/wxc_common/src/config_contract_adapters/dev/state_aware_tests/provision.rs index 617784bf92..d121fa77dd 100644 --- a/src/core/wxc_common/src/config_contract_adapters/dev/state_aware_tests/provision.rs +++ b/src/core/wxc_common/src/config_contract_adapters/dev/state_aware_tests/provision.rs @@ -197,6 +197,33 @@ fn wslc_configuration_matches_explicit_values_without_wire_conversion() { } } +#[test] +fn wslc_provision_port_mappings_map_without_wire_conversion() { + let fields = r#","experimental":{"wslc":{"provision":{"portMappings":[{"windowsPort":8080,"containerPort":80},{"windowsPort":8443,"containerPort":443,"protocol":"tcp"}]}}}"#; + let json = source("wslc", fields); + let (_, operation) = adapt(&json); + let StateAwareOperation::Provision(StateAwareProvision::Wslc(config)) = operation else { + panic!("wrong operation"); + }; + let ports = config + .expect("provision config should be populated") + .port_mappings + .expect("portMappings should be populated"); + assert_eq!(ports.len(), 2); + assert_eq!(ports[0].windows_port, 8080); + assert_eq!(ports[0].container_port, 80); + + // An omitted `protocol` stays absent rather than defaulting here; both arms + // of the contract's optional protocol are covered. + assert!(ports[0].protocol.is_none()); + assert_eq!(ports[1].windows_port, 8443); + assert_eq!(ports[1].container_port, 443); + assert!(matches!( + ports[1].protocol, + Some(wire::TransportProtocol::Tcp) + )); +} + #[test] fn rolling_wslc_conversion_has_independent_expected_fields() { for (image, image_tar_path) in [ @@ -208,6 +235,7 @@ fn rolling_wslc_conversion_has_independent_expected_fields() { let wire = wire::WslcProvisionPhase { image: image.map(str::to_owned), image_tar_path: image_tar_path.map(str::to_owned), + port_mappings: None, }; let runtime = WslcProvisionConfig::from(wire); assert_eq!(runtime.image.as_deref(), image); diff --git a/src/core/wxc_common/src/config_parser.rs b/src/core/wxc_common/src/config_parser.rs index 7740b9df8e..c8515cd673 100644 --- a/src/core/wxc_common/src/config_parser.rs +++ b/src/core/wxc_common/src/config_parser.rs @@ -9,7 +9,7 @@ use crate::logger::Logger; use crate::models::{ CaptureDenialsConfig, CaptureDenialsMode, ContainerPolicy, ContainmentBackend, ExecutionRequest, ExperimentalConfig, LifecycleConfig, LxcConfig, NetworkEnforcementMode, - NetworkPolicy, PortMapping, SeatbeltConfig, TelemetryConfig, TestFeatureConfig, UiPolicy, + NetworkPolicy, SeatbeltConfig, TelemetryConfig, TestFeatureConfig, UiPolicy, WindowsSandboxConfig, WslcConfig, }; use crate::mxc_error::MxcError; @@ -1360,15 +1360,15 @@ fn validate_capture_denials_output_path(path: &str, logger: &mut Logger) -> Resu } } -// `state_aware_wslc_exec` identifies the state-aware exec exception: network -// mode was fixed at provision, so a proxy-only exec inherits that mode rather -// than restating `defaultPolicy`. Backend phase validation still rejects every -// post-provision network-mode or host-filtering field. +// `state_aware` marks the state-aware lifecycle, where the WSLc network checks +// below are skipped: the mode is fixed at provision, so a later phase omits +// `defaultPolicy`, and the backend's per-phase gates reject the same inputs as +// `policy_validation` rather than a parse error. fn convert_wire_config( cfg: wire::MxcConfig, logger: &mut Logger, require_process: bool, - state_aware_wslc_exec: bool, + state_aware: bool, ) -> Result { // `phase` / `sandboxId` are state-aware-only fields. The state-aware path // consumes them before delegating here, so if either is still present the @@ -1648,7 +1648,12 @@ fn convert_wire_config( // MXC-run host-loopback proxy is unreachable. Accept only the // caller-supplied `url` form (which carries `original_url`); reject // the `localhost` / `builtinTestServer` forms. - if containment == ContainmentBackend::Wslc && proxy_config.is_enabled() { + // + // One-shot only: the state-aware path reaches the same rejection + // through the backend exec gate (`validate_exec_policy`), which + // reports it as `policy_validation` rather than a parse error. + if !state_aware && containment == ContainmentBackend::Wslc && proxy_config.is_enabled() + { let is_url_form = proxy_config .address .as_ref() @@ -1697,9 +1702,12 @@ fn convert_wire_config( // host lists to it, and a 'block' default (the WSLc default) yields no // outbound networking / a drop-floor that can't even reach the proxy. // Require an 'allow' default with no host lists so the proxy is reachable. - if containment == ContainmentBackend::Wslc + // + // One-shot only: state-aware binds the network mode at provision, so a + // later phase omits `defaultPolicy`; its own per-phase gates cover proxy. + if !state_aware + && containment == ContainmentBackend::Wslc && policy.network_proxy.is_enabled() - && !state_aware_wslc_exec && (policy.default_network_policy == NetworkPolicy::Block || !policy.allowed_hosts.is_empty() || !policy.blocked_hosts.is_empty()) @@ -1715,18 +1723,24 @@ fn convert_wire_config( // WSLc cannot enforce per-host egress filtering: containers lack // CAP_NET_ADMIN (so in-container iptables aborts at exec), and WSLc // cannot expose VM-level enforcement without breaking other security - // guarantees (e.g. MDE). Reject up front; the backend's validate_runner + // guarantees (e.g. MDE). Reject any non-empty host list up front, + // including one redundant with the default — an accepted-then-ignored + // list misstates what is enforced. The backend's validate_runner // enforces the same for requests that bypass this parser. Bare defaults - // with no host lists (full cutoff / full NAT) are enforceable, left as-is. + // with no host lists (full cutoff / full NAT) are enforceable, left + // as-is. + // + // One-shot only: the state-aware path reaches the same rejection through + // the backend policy gate (`reject_host_filtering`), which reports it as + // `policy_validation` rather than a parse error. if containment == ContainmentBackend::Wslc { - if policy.needs_host_filtering() { - let msg = "WSLc: per-host egress filtering (allowedHosts with \ - defaultPolicy='block', or blockedHosts with \ - defaultPolicy='allow') is not supported. A WSLc container has \ - no CAP_NET_ADMIN for in-container iptables, and VM-level \ - enforcement is not available without breaking other security \ - guarantees (e.g. MDE). Use network.proxy (defaultPolicy='allow') \ - for cooperative host filtering, or remove the host lists."; + if !state_aware && policy.has_host_lists() { + let msg = "WSLc: per-host egress filtering (allowedHosts/blockedHosts) is not \ + supported. A WSLc container has no CAP_NET_ADMIN for in-container \ + iptables, and VM-level enforcement is not available without breaking \ + other security guarantees (e.g. MDE). Use network.proxy \ + (defaultPolicy='allow') for cooperative host filtering, or remove the \ + host lists."; logger.log_line(msg); return Err(WxcError::ConfigParse(msg.to_string())); } @@ -1906,49 +1920,11 @@ fn convert_wire_config( } config.storage_path = cc.storage_path; if let Some(mappings) = cc.port_mappings { - let mut converted = Vec::with_capacity(mappings.len()); - for (idx, m) in mappings.into_iter().enumerate() { - if m.windows_port == 0 { - let msg = format!( - "experimental.wslc.portMappings[{idx}]: 'windowsPort' must be > 0" - ); - return Err(WxcError::ConfigParse(msg)); - } - if m.container_port == 0 { - let msg = format!( - "experimental.wslc.portMappings[{idx}]: 'containerPort' must be > 0" - ); - return Err(WxcError::ConfigParse(msg)); - } - // Only TCP is representable in the wire model - // (TransportProtocol is tcp-only); a `udp` value is rejected - // at deserialize. The WSLC SDK runtime returns E_NOTIMPL for - // UDP, so only TCP is currently supported. - let protocol = "tcp".to_string(); - converted.push(PortMapping { - windows_port: m.windows_port, - container_port: m.container_port, - protocol, - }); - } - // Reject duplicate (windowsPort, protocol) entries. Same host - // port on TCP+UDP would in principle be legal, but UDP is - // rejected at deserialize (the wire model is tcp-only); the - // second protocol dimension is retained in the dedupe key in - // case UDP support is enabled later. - let mut seen: std::collections::HashSet<(u16, &str)> = - std::collections::HashSet::new(); - for pm in &converted { - if !seen.insert((pm.windows_port, pm.protocol.as_str())) { - let msg = format!( - "experimental.wslc.portMappings: duplicate windowsPort {} \ - for protocol '{}'", - pm.windows_port, pm.protocol - ); - return Err(WxcError::ConfigParse(msg)); - } - } - config.port_mappings = converted; + config.port_mappings = crate::validator::validate_wslc_port_mappings( + &mappings, + "experimental.wslc.portMappings", + ) + .map_err(WxcError::ConfigParse)?; } Some(config) } else { @@ -2239,12 +2215,7 @@ fn normalize_state_aware_common( context.sandbox_id.and_then(state_aware_containment_from_id) }; let require_process = context.phase == Phase::Exec; - let state_aware_wslc_exec = require_process - && common - .containment - .as_ref() - .is_some_and(|value| map_wire_containment(Some(value)) == ContainmentBackend::Wslc); - let mut request = convert_wire_config(common, logger, require_process, state_aware_wslc_exec)?; + let mut request = convert_wire_config(common, logger, require_process, true)?; if context.phase != Phase::Provision && !network_supplied { request.policy.network_egress = None; request.policy.network_ingress = None; @@ -4717,7 +4688,7 @@ mod tests { observed_counts, expected_counts, "explicit divergence inventory and observed category totals differ" ); - let expected_inventory = (353, 329, 14); + let expected_inventory = (354, 330, 14); assert_eq!( (files.len(), equivalent_accepts, shared_rejections), expected_inventory, @@ -5945,6 +5916,7 @@ mod tests { StateAwareProvision::Wslc(Some(crate::models::WslcProvisionConfig { image: Some("alpine:latest".into()), image_tar_path: None, + port_mappings: None, })), ), ] { @@ -9473,6 +9445,52 @@ mod tests { ); } + #[test] + fn wslc_rejects_redundant_block_with_blocked_hosts() { + // A blocklist under a `block` default changes nothing, but accepting it + // would report per-host filtering the container never gets (#824). + let json = r#"{ + "version": "0.6.0-alpha", + "containment": "wslc", + "process": {"commandLine": "echo hi"}, + "network": { + "defaultPolicy": "block", + "blockedHosts": ["evil.example"] + } + }"#; + let encoded = base64_encode(json.as_bytes()); + let mut logger = test_logger(); + + let err = load_request(&encoded, &mut logger, true).unwrap_err(); + assert!( + format!("{err}").contains("per-host egress filtering"), + "unexpected error: {err}" + ); + } + + #[test] + fn wslc_rejects_redundant_allow_with_allowed_hosts() { + // An allowlist under an `allow` default reads as a restriction but + // enforces none: accepting it leaves all egress open (#824). + let json = r#"{ + "version": "0.6.0-alpha", + "containment": "wslc", + "process": {"commandLine": "echo hi"}, + "network": { + "defaultPolicy": "allow", + "allowedHosts": ["github.com"] + } + }"#; + let encoded = base64_encode(json.as_bytes()); + let mut logger = test_logger(); + + let err = load_request(&encoded, &mut logger, true).unwrap_err(); + assert!( + format!("{err}").contains("per-host egress filtering"), + "unexpected error: {err}" + ); + } + #[test] fn wslc_accepts_block_default_without_host_lists() { // 'block' with no allowlist is a full cutoff (NetworkingMode::None) -- diff --git a/src/core/wxc_common/src/models.rs b/src/core/wxc_common/src/models.rs index 69ac76b8c4..9cc2bfd86d 100644 --- a/src/core/wxc_common/src/models.rs +++ b/src/core/wxc_common/src/models.rs @@ -291,6 +291,8 @@ pub struct WslcProvisionConfig { pub image: Option, /// Local image tarball to import instead of pulling an image. pub image_tar_path: Option, + /// Host -> container port forwards, validated by the backend at provision. + pub port_mappings: Option>, } #[cfg(test)] @@ -299,10 +301,12 @@ impl From for WslcProvisionConfig { let crate::wire::WslcProvisionPhase { image, image_tar_path, + port_mappings, } = config; Self { image, image_tar_path, + port_mappings, } } } @@ -841,6 +845,12 @@ impl ContainerPolicy { &self.blocked_hosts, ) } + + /// Unlike [`needs_host_filtering`], also true for a list that is redundant + /// with the default (`block` + `blockedHosts`, `allow` + `allowedHosts`). + pub fn has_host_lists(&self) -> bool { + !self.allowed_hosts.is_empty() || !self.blocked_hosts.is_empty() + } } /// Windows denial-capture settings (from `processContainer.captureDenials`). @@ -888,7 +898,8 @@ pub struct PortMapping { pub windows_port: u16, /// Port inside the Linux container. pub container_port: u16, - /// Protocol: "tcp" or "udp". Default: "tcp". + /// Transport protocol, lowercase. Always `"tcp"`: this carries a WSLc port + /// forward, whose `wire::TransportProtocol` has no `udp` variant. pub protocol: String, } @@ -1281,6 +1292,7 @@ mod tests { crate::wire::WslcProvisionPhase { image: None, image_tar_path: None, + port_mappings: None, }, None, None, @@ -1289,6 +1301,7 @@ mod tests { crate::wire::WslcProvisionPhase { image: Some(String::new()), image_tar_path: None, + port_mappings: None, }, Some(""), None, @@ -1297,6 +1310,7 @@ mod tests { crate::wire::WslcProvisionPhase { image: None, image_tar_path: Some(String::new()), + port_mappings: None, }, None, Some(""), @@ -1305,6 +1319,7 @@ mod tests { crate::wire::WslcProvisionPhase { image: Some(String::new()), image_tar_path: Some(String::new()), + port_mappings: None, }, Some(""), Some(""), @@ -1313,6 +1328,7 @@ mod tests { crate::wire::WslcProvisionPhase { image: Some("custom/image:tag".to_string()), image_tar_path: None, + port_mappings: None, }, Some("custom/image:tag"), None, @@ -1321,6 +1337,7 @@ mod tests { crate::wire::WslcProvisionPhase { image: None, image_tar_path: Some("C:\\images\\custom.tar".to_string()), + port_mappings: None, }, None, Some("C:\\images\\custom.tar"), @@ -1329,6 +1346,7 @@ mod tests { crate::wire::WslcProvisionPhase { image: Some("custom/image:tag".to_string()), image_tar_path: Some("C:\\images\\custom.tar".to_string()), + port_mappings: None, }, Some("custom/image:tag"), Some("C:\\images\\custom.tar"), @@ -1367,6 +1385,7 @@ mod tests { WslcProvisionConfig { image: None, image_tar_path: None, + port_mappings: None, } ); } diff --git a/src/core/wxc_common/src/policy_identity.rs b/src/core/wxc_common/src/policy_identity.rs index 3c0bb79377..cfccdfbeee 100644 --- a/src/core/wxc_common/src/policy_identity.rs +++ b/src/core/wxc_common/src/policy_identity.rs @@ -135,6 +135,7 @@ fn state_aware_config_projection(operation: &StateAwareOperation) -> Value { StateAwareOperation::Provision(StateAwareProvision::Wslc(Some(WslcProvisionConfig { image, image_tar_path, + port_mappings, }))) => { let mut config = Map::new(); if let Some(image) = image { @@ -143,6 +144,11 @@ fn state_aware_config_projection(operation: &StateAwareOperation) -> Value { if let Some(image_tar_path) = image_tar_path { config.insert("imageTarPath".into(), Value::String(image_tar_path.clone())); } + if let Some(port_mappings) = port_mappings { + if let Ok(value) = serde_json::to_value(port_mappings) { + config.insert("portMappings".into(), value); + } + } Value::Object(config) } StateAwareOperation::Provision( diff --git a/src/core/wxc_common/src/validator.rs b/src/core/wxc_common/src/validator.rs index d840f4d8f3..07c6a8a3b4 100644 --- a/src/core/wxc_common/src/validator.rs +++ b/src/core/wxc_common/src/validator.rs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use crate::models::{ExecutionRequest, NetworkAction, NetworkPolicy, ScriptResponse}; +use crate::models::{ExecutionRequest, NetworkAction, NetworkPolicy, PortMapping, ScriptResponse}; use crate::mxc_error::MxcError; /// Declares which optional network policy features a backend enforces. @@ -218,6 +218,42 @@ pub fn validate_exec_common(request: &ExecutionRequest) -> Result<(), MxcError> Ok(()) } +/// Validate and convert WSLc wire port mappings. Shared by the one-shot parser +/// and the state-aware provision phase so the two cannot drift. `path` is the +/// caller's JSON location; the error is a bare message each caller wraps. +pub fn validate_wslc_port_mappings( + mappings: &[crate::wire::PortMapping], + path: &str, +) -> Result, String> { + let mut converted = Vec::with_capacity(mappings.len()); + for (idx, m) in mappings.iter().enumerate() { + if m.windows_port == 0 { + return Err(format!("{path}[{idx}]: 'windowsPort' must be > 0")); + } + if m.container_port == 0 { + return Err(format!("{path}[{idx}]: 'containerPort' must be > 0")); + } + // Only TCP is representable: the wire model is tcp-only and `udp` is + // rejected at deserialize (the WSLC SDK returns E_NOTIMPL for UDP). + converted.push(PortMapping { + windows_port: m.windows_port, + container_port: m.container_port, + protocol: "tcp".to_string(), + }); + } + // Protocol stays in the key so enabling UDP later needs no change here. + let mut seen: std::collections::HashSet<(u16, &str)> = std::collections::HashSet::new(); + for pm in &converted { + if !seen.insert((pm.windows_port, pm.protocol.as_str())) { + return Err(format!( + "{path}: duplicate windowsPort {} for protocol '{}'", + pm.windows_port, pm.protocol + )); + } + } + Ok(converted) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/core/wxc_common/src/wire.rs b/src/core/wxc_common/src/wire.rs index a68ac432a6..fb345f0b75 100644 --- a/src/core/wxc_common/src/wire.rs +++ b/src/core/wxc_common/src/wire.rs @@ -649,7 +649,7 @@ pub struct Wslc { pub gpu: Option, /// Storage path override. pub storage_path: Option, - /// Host → container port forwards. Only TCP is currently supported; the + /// Host -> container port forwards. Only TCP is currently supported; the /// parser rejects `udp` because the WSLC SDK runtime returns `E_NOTIMPL` /// for UDP port mappings. pub port_mappings: Option>, @@ -661,16 +661,19 @@ pub struct Wslc { } /// Per-phase WSLc **provision** configuration (state-aware lifecycle), nested -/// under `experimental.wslc.provision`. Carries only what the amortized daemon -/// session honors: the container image (or a local tarball to import). +/// under `experimental.wslc.provision`. Carries what the amortized daemon +/// session honors: the container image (or a local tarball to import) and the +/// host -> container port forwards. /// /// Filesystem mounts and network mode derive from the top-level `policy` -/// section (readwrite / readonly paths, network), not from here. The -/// one-shot-only sizing knobs (`cpuCount` / `memoryMb` / `gpu` / `storagePath` -/// / `portMappings`) are deliberately absent: the daemon shares a single session -/// across sandboxes and does not apply per-sandbox sizing. start / exec / stop / -/// deprovision carry no backend-specific config (the exec command flows through -/// the top-level `process` section), so they have no phase struct. +/// section (readwrite / readonly paths, network), not from here. The one-shot +/// fields `cpuCount` / `memoryMb` / `gpu` / `storagePath` are deliberately +/// absent: they are properties of the WSLC session, and the daemon shares one +/// session across every sandbox, so no phase caller can set them per sandbox. +/// `portMappings`, by contrast, is per-container, so it is honored here, +/// matching the one-shot surface. start / exec / stop / deprovision carry no +/// backend-specific config (the exec command flows through the top-level +/// `process` section), so they have no phase struct. #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase")] @@ -680,11 +683,15 @@ pub struct WslcProvisionPhase { pub image: Option, /// Path to a local image tarball to import instead of pulling. pub image_tar_path: Option, + /// Host -> container port forwards. Only TCP is currently supported; the + /// parser rejects `udp` because the WSLC SDK runtime returns `E_NOTIMPL` + /// for UDP port mappings. Mirrors the one-shot `Wslc::port_mappings`. + pub port_mappings: Option>, } -/// A single host → container port forward. Reachable only under the permissive +/// A single host -> container port forward. Reachable only under the permissive /// `experimental` surface, so unknown fields are tolerated (forward-compat). -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase")] pub struct PortMapping { @@ -700,7 +707,7 @@ pub struct PortMapping { /// Port-forward transport protocol. Only `tcp` is currently supported by the /// vendored WSLC SDK runtime; `udp` is rejected at parse time. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))] #[serde(rename_all = "lowercase")] pub enum TransportProtocol { diff --git a/tests/configs/wslc_state_aware_provision_ports.json b/tests/configs/wslc_state_aware_provision_ports.json new file mode 100644 index 0000000000..feee0d89aa --- /dev/null +++ b/tests/configs/wslc_state_aware_provision_ports.json @@ -0,0 +1,19 @@ +{ + "version": "0.9.0-alpha", + "phase": "provision", + "containment": "wslc", + "network": { + "egress": { "default": "allow" }, + "ingress": { "default": "allow", "hostLoopback": "allow" } + }, + "experimental": { + "wslc": { + "provision": { + "image": "alpine:latest", + "portMappings": [ + { "windowsPort": 18080, "containerPort": 80, "protocol": "tcp" } + ] + } + } + } +} diff --git a/tests/scripts/run_wslc_state_aware_tests.ps1 b/tests/scripts/run_wslc_state_aware_tests.ps1 index 6b95515d18..69432c1ca2 100644 --- a/tests/scripts/run_wslc_state_aware_tests.ps1 +++ b/tests/scripts/run_wslc_state_aware_tests.ps1 @@ -711,6 +711,140 @@ try { } } +# ---------------- Lifecycle C2: port mappings at provision ---------------- + +# Ask the OS for a free ephemeral port, then release it: a fixed port would fail +# this test whenever an unrelated process or a stale sandbox already owns one. +function Get-FreeTcpPort { + $listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0) + $listener.Start() + try { return [int]$listener.LocalEndpoint.Port } finally { $listener.Stop() } +} + +# Connect to a TCP port on the Windows host and return the bytes the peer sends +# on connect (ASCII), or $null if no listener answers within the retry budget. +function Get-TcpResponse { + param( + [string]$HostName, + [int]$Port, + [int]$Retries = 15, + [int]$DelayMs = 1000 + ) + for ($i = 0; $i -lt $Retries; $i++) { + $client = $null + try { + $client = [System.Net.Sockets.TcpClient]::new() + $iar = $client.BeginConnect($HostName, $Port, $null, $null) + if (-not $iar.AsyncWaitHandle.WaitOne(2000)) { throw "connect timeout" } + $client.EndConnect($iar) + $stream = $client.GetStream() + $stream.ReadTimeout = 3000 + # Read until the peer closes; a single Read may return only part of + # the payload even when forwarding works. + $ms = New-Object System.IO.MemoryStream + $buf = New-Object byte[] 256 + while (($n = $stream.Read($buf, 0, $buf.Length)) -gt 0) { + $ms.Write($buf, 0, $n) + } + if ($ms.Length -gt 0) { + return [System.Text.Encoding]::ASCII.GetString($ms.ToArray()) + } + } catch { + Start-Sleep -Milliseconds $DelayMs + } finally { + if ($client) { $client.Close() } + } + } + return $null +} + +# Drives a real host->container round-trip rather than only checking that the +# config parses: an implementation that silently drops portMappings leaves +# nothing listening, so the host connect fails (#824). The request is built +# inline so the host port can be chosen at runtime; the fixture still covers +# schema validation. The listener script is base64-piped to `sh` to keep the +# argv-split commandLine free of nested quotes. +$script:portSandboxId = $null +$script:portHostPort = Get-FreeTcpPort +$portDeprovisionedOk = $false +try { + $portProvisionedOk = Run-StateAwareTest "C2: provision (port mappings)" { + $req = @{ + version = '0.9.0-alpha' + phase = 'provision' + containment = 'wslc' + network = @{ + egress = @{ default = 'allow' } + ingress = @{ default = 'allow'; hostLoopback = 'allow' } + } + experimental = @{ + wslc = @{ + provision = @{ + image = 'alpine:latest' + portMappings = @( + @{ windowsPort = $script:portHostPort; containerPort = 80; protocol = 'tcp' } + ) + } + } + } + } + $r = Invoke-StateAware -Request $req + $envObj = Assert-ResultEnvelope $r "port-mapped provision" + if ($envObj) { $script:portSandboxId = [string]$envObj.result.sandboxId } + } + + $portStartedOk = $false + if ($portProvisionedOk) { + $portStartedOk = Run-StateAwareTest "C2: start" { + $r = Invoke-StateAware -ConfigFile 'wslc_state_aware_start.json' -SandboxId $script:portSandboxId + $null = Assert-ResultEnvelope $r "port-mapped start" + } + } + + $portListenerOk = $false + if ($portStartedOk) { + $portListenerOk = Run-StateAwareTest "C2: exec starts detached listener on container port 80" { + $listenerScript = @' +setsid sh -c 'while true; do printf MXC_PORTMAP_OK | nc -l -p 80 || sleep 1; done' /dev/null 2>&1 & +sleep 1 +echo LISTENER_UP +'@ + $listenerB64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($listenerScript)) + $listenerCmd = "sh -c 'echo $listenerB64 | base64 -d | sh'" + $req = @{ phase = 'exec'; sandboxId = $script:portSandboxId; process = @{ commandLine = $listenerCmd; timeout = 30000 } } + $r = Invoke-StateAware -Request $req + Assert-True ($r.ExitCode -eq 0) "listener-start exec exit code = 0" + Assert-True ($r.Stdout -match 'LISTENER_UP') "listener reported ready ($($r.Stdout.Trim()))" + } + } + + if ($portListenerOk) { + Run-StateAwareTest "C2: port forward round-trip (windows $script:portHostPort -> container 80)" { + $payload = Get-TcpResponse -HostName '127.0.0.1' -Port $script:portHostPort + Assert-True ($payload -eq 'MXC_PORTMAP_OK') ` + "host port $script:portHostPort forwards to the container listener (got '$payload')" + } | Out-Null + } + + if ($portProvisionedOk) { + Run-StateAwareTest "C2: stop" { + $r = Invoke-StateAware -ConfigFile 'wslc_state_aware_stop.json' -SandboxId $script:portSandboxId + $null = Assert-ResultEnvelope $r "port-mapped stop" + } | Out-Null + $portDeprovPassed = Run-StateAwareTest "C2: deprovision" { + $r = Invoke-StateAware -ConfigFile 'wslc_state_aware_deprovision.json' -SandboxId $script:portSandboxId + $null = Assert-ResultEnvelope $r "port-mapped deprovision" + } + if ($portDeprovPassed) { $portDeprovisionedOk = $true } + } +} finally { + if ($null -ne $script:portSandboxId -and -not $portDeprovisionedOk) { + Write-Host "" + Write-Host "[cleanup] best-effort deprovision of $script:portSandboxId" -ForegroundColor DarkGray + try { $null = Invoke-StateAware -ConfigFile 'wslc_state_aware_deprovision.json' -SandboxId $script:portSandboxId } catch { } + } +} + # ---------------- Lifecycle D: validation rejections ---------------- # Validation runs before any daemon call, so these never provision a real