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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion docs/amcd-bootstrap.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ task launches the local WSL `amcd` process automatically without storing a passw
token. It is host-control infrastructure; it does not select, enroll, start, stop, or otherwise
mutate a virtual machine.

For Linux-local state, the automatic listener prefers IPv6 loopback with IPv4 fallback. Shared
Windows-backed state and native Windows keep IPv4 so both environments can reach the daemon.
This avoids IPv4 loopback relays for local WSL clients while preserving shared-state compatibility.
Clients discover the selected address from the protected endpoint record; an explicit
`amcd run --listen` address remains exact. The generated bootstrap wrapper leaves this selection
automatic. Existing installations retain their exact IPv4 wrapper and matching old controller
until the explicit package-upgrade procedure below.

## Package companion

WSL bootstrap requires the matching architecture's `amcd-launcher.exe` beside the immutable Linux
Expand Down Expand Up @@ -119,7 +127,7 @@ so its initial process does not allocate a console or activate Windows Terminal.
Windows PowerShell through `GetSystemDirectoryW` and starts it with `CREATE_NO_WINDOW` and fixed
non-interactive `-File` arguments. The wrapper uses `ProcessStartInfo` with `UseShellExecute=false`
and `CreateNoWindow=true` for the exact Windows `wsl.exe` path, validated WSL distribution and Linux
user, exact Linux `amcd` path, state directory, loopback listen address, and fixed daemon flags.
user, exact Linux `amcd` path, state directory, optional explicit loopback address, and fixed daemon flags.
Both launchers wait and return the child's exit code. No Terminal preferences or unrelated windows
or processes are changed. The three files
and their directory have a canonical protected DACL with exactly two explicit FullControl allow
Expand Down
6 changes: 6 additions & 0 deletions docs/guest-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,9 @@ installed revision and intended Windows target. Measure cold preparation separat
commands, upload, download and owned deletion. Include payload size, digest verification, durable
commit, final receipt and cleanup time. Report RPC overhead separately from guest execution where
the evidence permits; retain compact receipts and remove owned fixtures after each run.

Measure any host TCP forwarding separately from the guest's direct, operator-provisioned SSH
endpoint. A forwarding service can limit throughput even when guest disk writes and hashing are
fast. Verify the exact enrolled VM and its existing SSH host-key pin before changing the protected
endpoint. Retire the original worker under its original configuration first; a changed route starts
a new authority generation. Existing authenticated terminal connections can retain their own route.
2 changes: 1 addition & 1 deletion internal/app/bootstrap_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func (s BootstrapSpec) validateSettings() error {
if s.ExecutionTimeLimit != "PT0S" || !s.AllowStartOnBatteries || !s.DontStopOnBatteries {
return fmt.Errorf("%w: task settings can interrupt the daemon", ErrBootstrapDrift)
}
if s.ListenAddress != "127.0.0.1:0" {
if s.ListenAddress != "" && s.ListenAddress != "127.0.0.1:0" {
return fmt.Errorf("%w: daemon listen address must be ephemeral loopback", ErrBootstrapDrift)
}
return nil
Expand Down
12 changes: 7 additions & 5 deletions internal/bootstrap/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ func buildSpec(host hostContext, identity app.BootstrapIdentity, distro, linuxUs
Distro: distro, LinuxUser: linuxUser, StateDir: stateRoot,
WrapperPath: wrapperPath, MetadataPath: metadataPath,
BinaryPath: binaryPath, BinarySHA256: binaryHash,
WSLExecutable: host.WSLExecutable, ListenAddress: "127.0.0.1:0",
WSLExecutable: host.WSLExecutable,
}
wrapper, err := wrapperBytes(spec)
if err != nil {
Expand All @@ -366,6 +366,10 @@ func wrapperBytes(spec app.BootstrapSpec) ([]byte, error) {
return nil, fmt.Errorf("%w: unsafe %s", app.ErrBootstrapUnsupported, label)
}
}
listenArguments := ""
if spec.ListenAddress != "" {
listenArguments = fmt.Sprintf(" '--listen',\n '%s',\n", quoteWindowsArgument(spec.ListenAddress))
}
launcher := fmt.Sprintf(`$ErrorActionPreference = 'Stop'
$arguments = @(
'-d',
Expand All @@ -377,9 +381,7 @@ $arguments = @(
'run',
'--state-dir',
'%s',
'--listen',
'%s',
'--json'
%s '--json'
)
$start = [Diagnostics.ProcessStartInfo]::new()
$start.FileName = '%s'
Expand All @@ -389,7 +391,7 @@ $start.CreateNoWindow = $true
$child = [Diagnostics.Process]::Start($start)
$child.WaitForExit()
exit $child.ExitCode
`, quoteWindowsArgument(spec.Distro), quoteWindowsArgument(spec.LinuxUser), quoteWindowsArgument(spec.BinaryPath), quoteWindowsArgument(spec.StateDir), quoteWindowsArgument(spec.ListenAddress), spec.WSLExecutable)
`, quoteWindowsArgument(spec.Distro), quoteWindowsArgument(spec.LinuxUser), quoteWindowsArgument(spec.BinaryPath), quoteWindowsArgument(spec.StateDir), listenArguments, spec.WSLExecutable)
return []byte(launcher), nil
}

Expand Down
3 changes: 3 additions & 0 deletions internal/bootstrap/adapter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,9 @@ func TestBuildSpecProducesExactInteractiveLimitedFingerprint(t *testing.T) {
if spec.MultipleInstances != "IgnoreNew" || spec.ExecutionTimeLimit != "PT0S" {
t.Fatalf("unsafe lifecycle settings: %#v", spec)
}
if spec.ListenAddress != "" {
t.Fatalf("bootstrap must leave listener selection automatic: %q", spec.ListenAddress)
}
if err := spec.Validate(identity); err != nil {
t.Fatalf("spec.Validate() error = %v", err)
}
Expand Down
25 changes: 25 additions & 0 deletions internal/bootstrap/wrapper_listen_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package bootstrap

import (
"strings"
"testing"

"github.com/Horcag/agent-machine-control/internal/app"
)

func TestWrapperAutomaticListenerOmitsAddressArguments(t *testing.T) {
spec := app.BootstrapSpec{WSLExecutable: `C:\Windows\System32\wsl.exe`, Distro: "Synthetic-WSL", LinuxUser: "operator", BinaryPath: "/bin/amcd", StateDir: "/state"}
for _, address := range []string{"", "127.0.0.1:0"} {
spec.ListenAddress = address
body, err := wrapperBytes(spec)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), "'--listen'") != (address != "") {
t.Fatalf("wrong automatic/explicit listener arguments for %q", address)
}
if !strings.Contains(string(body), "'--state-dir',\n '/state',") || !strings.Contains(string(body), "'--json'") {
t.Fatal("automatic listener lost adjacent native arguments")
}
}
}
16 changes: 14 additions & 2 deletions internal/bootstrap/wrapper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,15 @@ func TestWrapperStartsConsolelessChildAndPreservesExitAndArguments(t *testing.T)
return strings.TrimSpace(string(out))
}
dir, binary, launcher := buildWindowsTestExecutables(t)
for _, address := range []string{"", "127.0.0.1:0"} {
t.Run("listen="+address, func(t *testing.T) { checkWrapperInvocation(t, dir, binary, launcher, address, winPath) })
}
}

func checkWrapperInvocation(t *testing.T, dir, binary, launcher, address string, winPath func(string) string) {
t.Helper()
output := filepath.Join(dir, "child observation.json")
spec := app.BootstrapSpec{WSLExecutable: winPath(binary), Distro: "Synthetic WSL", LinuxUser: "operator", BinaryPath: "/synthetic path/amcd", StateDir: winPath(output), ListenAddress: "127.0.0.1:0"}
spec := app.BootstrapSpec{WSLExecutable: winPath(binary), Distro: "Synthetic WSL", LinuxUser: "operator", BinaryPath: "/synthetic path/amcd", StateDir: winPath(output), ListenAddress: address}
wrapper, err := wrapperBytes(spec)
if err != nil {
t.Fatal(err)
Expand All @@ -46,6 +53,7 @@ func TestWrapperStartsConsolelessChildAndPreservesExitAndArguments(t *testing.T)
if _, _, err := launcherArtifact(filepath.Join(dir, "amcd"), "Synthetic-WSL"); err != nil {
t.Fatal(err)
}
// #nosec G204 -- launcher is built from repository-owned source in this test's private directory.
command := exec.CommandContext(t.Context(), launcher, "-NoLogo", "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-ExecutionPolicy", "Bypass", "-File", winPath(wrapperPath))
out, err := command.CombinedOutput()
var exit *exec.ExitError
Expand All @@ -66,7 +74,11 @@ func TestWrapperStartsConsolelessChildAndPreservesExitAndArguments(t *testing.T)
if observation.Console != 0 {
t.Fatal("launcher allocated a console for its child")
}
want := []string{"-d", spec.Distro, "--user", spec.LinuxUser, "--exec", spec.BinaryPath, "run", "--state-dir", spec.StateDir, "--listen", spec.ListenAddress, "--json"}
want := []string{"-d", spec.Distro, "--user", spec.LinuxUser, "--exec", spec.BinaryPath, "run", "--state-dir", spec.StateDir}
if address != "" {
want = append(want, "--listen", address)
}
want = append(want, "--json")
if !reflect.DeepEqual(observation.Args, want) {
t.Fatalf("child arguments: %q, want %q", observation.Args, want)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/daemon/handlers_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ func TestServer_StartDefaultListenAddr(t *testing.T) {
dir := missingDaemonStateRoot(t)
srv, err := NewServer(Config{
StateDir: dir,
ListenAddr: "", // tests default 127.0.0.1:0
ListenAddr: "", // tests automatic IPv6/IPv4 loopback selection
})
if err != nil {
t.Fatalf("NewServer failed: %v", err)
Expand Down
48 changes: 48 additions & 0 deletions internal/daemon/listen.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package daemon

import (
"errors"
"fmt"
"net"
)

// Shared Windows/WSL state retains IPv4 reachability across both environments.
// Only positively identified Linux-local state opts into the faster local path.
func preferIPv6Loopback(platform, statePath string, inspect func(string) (bool, error)) bool {
if platform != "linux" {
return false
}
shared, err := inspect(statePath)
return err == nil && !shared
}

// Explicit addresses remain exact and never fall back to another endpoint.
func listenLoopback(addr string, preferIPv6 bool, bind func(string, string) (net.Listener, error)) (net.Listener, error) {
if addr == "" {
var ipv6Err error
if preferIPv6 {
var listener net.Listener
listener, ipv6Err = bind("tcp6", "[::1]:0")
if ipv6Err == nil {
return listener, nil
}
}
listener, ipv4Err := bind("tcp4", "127.0.0.1:0")
if ipv4Err != nil {
return nil, fmt.Errorf("daemon: failed to listen on loopback: %w", errors.Join(ipv6Err, ipv4Err))
}
return listener, nil
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("daemon: invalid listen address %q: %w", addr, err)
}
if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
return nil, fmt.Errorf("daemon: listen address host %q must be a loopback IP literal", host)
}
listener, err := bind("tcp", addr)
if err != nil {
return nil, fmt.Errorf("daemon: failed to listen on %s: %w", addr, err)
}
return listener, nil
}
109 changes: 109 additions & 0 deletions internal/daemon/listen_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package daemon

import (
"errors"
"net"
"reflect"
"testing"
)

type loopbackSelectionCase struct {
name, address string
preferIPv6 bool
failures []error
want []string
}

func TestLoopbackListenerSelection(t *testing.T) {
available, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer available.Close()
v6, v4 := errors.New("IPv6 unavailable"), errors.New("IPv4 unavailable")
cases := []loopbackSelectionCase{
{"automatic_ipv6", "", true, []error{nil}, []string{"tcp6 [::1]:0"}},
{"shared_ipv4", "", false, []error{nil}, []string{"tcp4 127.0.0.1:0"}},
{"automatic_ipv4_fallback", "", true, []error{v6, nil}, []string{"tcp6 [::1]:0", "tcp4 127.0.0.1:0"}},
{"automatic_both_fail", "", true, []error{v6, v4}, []string{"tcp6 [::1]:0", "tcp4 127.0.0.1:0"}},
{"explicit_ipv4", "127.0.0.1:42", true, []error{nil}, []string{"tcp 127.0.0.1:42"}},
{"explicit_ipv6", "[::1]:42", false, []error{nil}, []string{"tcp [::1]:42"}},
{"explicit_failure_never_falls_back", "127.0.0.1:42", true, []error{v4}, []string{"tcp 127.0.0.1:42"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) { checkLoopbackSelection(t, tc, available) })
}
}

func checkLoopbackSelection(t *testing.T, tc loopbackSelectionCase, available net.Listener) {
t.Helper()
var calls []string
listener, gotErr := listenLoopback(tc.address, tc.preferIPv6, func(network, address string) (net.Listener, error) {
calls = append(calls, network+" "+address)
failure := tc.failures[len(calls)-1]
if failure != nil {
return nil, failure
}
return available, nil
})
if !reflect.DeepEqual(calls, tc.want) {
t.Fatalf("bound %v; want %v", calls, tc.want)
}
if tc.failures[len(tc.failures)-1] == nil {
if gotErr != nil || listener != available {
t.Fatalf("successful bind lost: %v", gotErr)
}
return
}
if listener != nil {
t.Fatal("failed bind returned listener")
}
for _, wantErr := range tc.failures {
if wantErr != nil && !errors.Is(gotErr, wantErr) {
t.Fatalf("bind failure %v lost: %v", wantErr, gotErr)
}
}
}

func TestIPv6PreferenceRequiresLinuxLocalState(t *testing.T) {
for _, tc := range []struct {
name, platform string
shared bool
err error
want bool
}{
{"windows", "windows", false, nil, false},
{"other_platform", "darwin", false, nil, false},
{"linux_local", "linux", false, nil, true},
{"shared_windows_mount", "linux", true, nil, false},
{"unknown_mount", "linux", false, errors.New("mount inspection failed"), false},
} {
t.Run(tc.name, func(t *testing.T) {
called := false
got := preferIPv6Loopback(tc.platform, "/synthetic/state", func(path string) (bool, error) {
called = true
if path != "/synthetic/state" {
t.Fatal("wrong state inspected")
}
return tc.shared, tc.err
})
if got != tc.want || called != (tc.platform == "linux") {
t.Fatalf("preference=%v inspection=%v", got, called)
}
})
}
}

func TestLoopbackListenerRejectsUnsafeAddressesBeforeBind(t *testing.T) {
for _, address := range []string{"0.0.0.0:0", "[::]:0", "192.0.2.10:0", "localhost:0", "malformed"} {
t.Run(address, func(t *testing.T) {
_, err := listenLoopback(address, true, func(string, string) (net.Listener, error) {
t.Fatal("unsafe address reached bind")
return nil, nil
})
if err == nil {
t.Fatal("unsafe address accepted")
}
})
}
}
27 changes: 5 additions & 22 deletions internal/daemon/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net"
"net/http"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
Expand All @@ -28,6 +29,7 @@ import (
"github.com/Horcag/agent-machine-control/internal/receipt"
"github.com/Horcag/agent-machine-control/internal/sessions"
"github.com/Horcag/agent-machine-control/internal/statedir"
"github.com/Horcag/agent-machine-control/internal/wslruntime"
)

type contextKey string
Expand Down Expand Up @@ -365,32 +367,13 @@ func (s *Server) dispatchReceiptSubroute(w http.ResponseWriter, r *http.Request,

// Start opens the network listener and records the daemon endpoint.
func (s *Server) Start() error {
addr := s.cfg.ListenAddr
if addr == "" {
addr = "127.0.0.1:0"
}

host, _, err := net.SplitHostPort(addr)
if err != nil {
if s.singletonLock != nil {
_ = s.singletonLock.Release()
}
return fmt.Errorf("daemon: invalid listen address %q: %w", addr, err)
}
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
if s.singletonLock != nil {
_ = s.singletonLock.Release()
}
return fmt.Errorf("daemon: listen address host %q must be a loopback IP literal", host)
}

ln, err := net.Listen("tcp", addr)
preferIPv6 := preferIPv6Loopback(runtime.GOOS, s.stateDir.Root(), wslruntime.IsWindowsHostPath)
ln, err := listenLoopback(s.cfg.ListenAddr, preferIPv6, net.Listen)
if err != nil {
if s.singletonLock != nil {
_ = s.singletonLock.Release()
}
return fmt.Errorf("daemon: failed to listen on %s: %w", addr, err)
return err
}

s.listener = ln
Expand Down
4 changes: 2 additions & 2 deletions internal/daemoncli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func runDaemon(args []string, stdout, stderr io.Writer) int {
fs.SetOutput(stderr)

stateDir := fs.String("state-dir", "", "state directory path")
listenAddr := fs.String("listen", "127.0.0.1:0", "HTTP listen address")
listenAddr := fs.String("listen", "", "HTTP loopback address (automatic; shared Windows state uses IPv4)")
jsonOutput := fs.Bool("json", false, "emit machine-readable JSON")

if err := fs.Parse(args); err != nil {
Expand Down Expand Up @@ -225,7 +225,7 @@ func printDaemonUsage(w io.Writer) {
fmt.Fprintln(w, "")
fmt.Fprintln(w, "Flags:")
fmt.Fprintln(w, " --state-dir <path> Override state directory path")
fmt.Fprintln(w, " --listen <addr> Listen address (default 127.0.0.1:0)")
fmt.Fprintln(w, " --listen <addr> Exact loopback address (default: automatic; shared Windows state uses IPv4)")
fmt.Fprintln(w, " --json Emit machine-readable JSON")
fmt.Fprintln(w, " --help, -h Show help")
fmt.Fprintln(w, " --version, -v Show version")
Expand Down
Loading
Loading