package egress import ( "bufio" "context" "crypto/sha256" "crypto/tls" "encoding/hex" "errors" "fmt" "io" "net" "net/http" "net/http/httptest" "net/netip" "net/url" "os" "path/filepath" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" ) func scratch(t *testing.T) string { t.Helper() dir, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e3-") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(dir) }) return dir } func fixtureProxy(t *testing.T, addresses []netip.Addr, dial func(context.Context, string, string) (net.Conn, error)) *Proxy { t.Helper() d := defaults() d.lookup = func(context.Context, string) ([]netip.Addr, error) { return addresses, nil } d.dial = dial p, err := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d) if err != nil { t.Fatal(err) } t.Cleanup(func() { p.Close() }) return p } func connect(t *testing.T, p *Proxy, request string) (net.Conn, *bufio.Reader, string) { t.Helper() c, err := net.Dial("unix", p.SocketPath()) if err != nil { t.Fatal(err) } t.Cleanup(func() { c.Close() }) c.SetDeadline(time.Now().Add(3 * time.Second)) if _, err = io.WriteString(c, request); err != nil { t.Fatal(err) } r := bufio.NewReader(c) line, _ := r.ReadString('\n') return c, r, line } func request(host string) string { return "CONNECT " + host + " HTTP/1.1\r\nHost: " + host + "\r\n\r\n" } func TestEgressRejectsHostServices(t *testing.T) { var calls atomic.Int32 dial := func(context.Context, string, string) (net.Conn, error) { calls.Add(1) return nil, errors.New("unexpected dial") } p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, dial) for _, host := range []string{"localhost:443", "127.0.0.1:443", "[::1]:443", "100.64.0.1:443", "192.168.1.1:443", "169.254.169.254:443", "metadata.google.internal:443", "fixture.example:80", "other.example:443", "sub.fixture.example:443", "fixture.example.evil:443", "fixture.example.:443", "FIXTURE.EXAMPLE:443", "fixture.example:0443", "fixture.example:443@other.example:443"} { t.Run(host, func(t *testing.T) { _, _, line := connect(t, p, request(host)) if strings.Contains(line, "200") { t.Fatal("forbidden authority accepted") } }) } if calls.Load() != 0 { t.Fatal("denied request reached dialer") } for _, ip := range []string{"127.0.0.1", "10.0.0.1", "172.16.0.1", "192.168.0.1", "100.64.0.1", "100.127.255.254", "169.254.169.254", "0.0.0.0", "224.0.0.1", "240.0.0.1", "192.0.0.8", "198.18.0.1", "192.0.2.1", "198.51.100.1", "203.0.113.1", "::1", "::", "fc00::1", "fe80::1", "ff02::1", "::ffff:127.0.0.1", "64:ff9b::7f00:1", "2002:7f00:1::", "2001:db8::1"} { t.Run(ip, func(t *testing.T) { before := calls.Load() q := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr(ip)}, dial) _, _, line := connect(t, q, request("fixture.example:443")) if strings.Contains(line, "200") || calls.Load() != before { t.Fatal("nonpublic DNS answer reached dialer") } }) } t.Run("resolver_error", func(t *testing.T) { d := defaults() d.lookup = func(context.Context, string) ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, errors.New("dns unavailable") } d.dial = dial q, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d) if e != nil { t.Fatal(e) } defer q.Close() before := calls.Load() connect(t, q, request("fixture.example:443")) if calls.Load() != before { t.Fatal("DNS error dialled") } }) } func TestEgressAllowsOnlyProviderTLS(t *testing.T) { server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "fixture TLS") })) defer server.Close() var lookups, dials atomic.Int32 d := defaults() d.lookup = func(_ context.Context, host string) ([]netip.Addr, error) { if host != "fixture.example" { t.Errorf("unexpected lookup: %s", host) } if lookups.Add(1) > 1 { return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil } return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil } d.dial = func(ctx context.Context, network, address string) (net.Conn, error) { dials.Add(1) if network != "tcp" || address != "8.8.8.8:443" { t.Errorf("unvalidated dial: %s %s", network, address) } return (&net.Dialer{}).DialContext(ctx, "tcp", server.Listener.Addr().String()) } p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d) if e != nil { t.Fatal(e) } defer p.Close() c, r, line := connect(t, p, request("fixture.example:443")) if !strings.Contains(line, "200") { t.Fatalf("CONNECT: %q", line) } if line, e = r.ReadString('\n'); e != nil || line != "\r\n" { t.Fatalf("response headers: %q %v", line, e) } tlsConfig := server.Client().Transport.(*http.Transport).TLSClientConfig.Clone() tlsConfig.ServerName = "127.0.0.1" tlsConn := tls.Client(c, tlsConfig) if e = tlsConn.Handshake(); e != nil { t.Fatal(e) } io.WriteString(tlsConn, "GET / HTTP/1.1\r\nHost: fixture.example\r\nConnection: close\r\n\r\n") b, e := io.ReadAll(tlsConn) if e != nil || !strings.Contains(string(b), "fixture TLS") { t.Fatalf("TLS tunnel: %q %v", b, e) } connect(t, p, request("fixture.example:443")) if lookups.Load() != 2 || dials.Load() != 1 { t.Fatalf("rebinding guard: lookups=%d dials=%d", lookups.Load(), dials.Load()) } } func TestEgressRejectsSmuggling(t *testing.T) { var calls atomic.Int32 p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, func(context.Context, string, string) (net.Conn, error) { calls.Add(1); return nil, errors.New("dial") }) for _, raw := range []string{ "GET https://fixture.example/ HTTP/1.1\r\n\r\n", "POST fixture.example:443 HTTP/1.1\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\r\nContent-Length: 0\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\r\nHost: other.example:443\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\r\nHost: fixture.example:443\r\nHost: fixture.example:443\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\r\nUser-Agent: a\r\nUser-Agent: b\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\r\n Host: fixture.example:443\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\r\nX: a\x00b\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\n\n", "CONNECT fixture.example:443 HTTP/2.0\r\n\r\n", request("fixture.example:443") + "GET / HTTP/1.1\r\n\r\n", } { t.Run(fmt.Sprintf("case%d", calls.Load())+fmt.Sprint(len(raw)), func(t *testing.T) { before := calls.Load() _, _, line := connect(t, p, raw) if strings.Contains(line, "200") || calls.Load() != before { t.Fatalf("smuggling reached dial: %q", raw) } }) } } func closePromptly(t *testing.T, p *Proxy, connections ...net.Conn) { t.Helper() done := make(chan struct{}) go func() { p.Close(); close(done) }() select { case <-done: case <-time.After(time.Second): for _, c := range connections { c.Close() } <-done t.Fatal("proxy close did not interrupt sockets") } } func TestEgressDiesWithAttempt(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() p, e := Open(ctx, scratch(t), Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}) if e != nil { t.Fatal(e) } defer p.Close() c, e := net.Dial("unix", p.SocketPath()) if e != nil { t.Fatal(e) } defer c.Close() cancel() select { case <-p.Done(): case <-time.After(time.Second): t.Fatal("proxy outlived context") } closePromptly(t, p, c) c.SetReadDeadline(time.Now().Add(time.Second)) b := make([]byte, 1) if _, e = c.Read(b); e == nil { t.Fatal("connection survived close") } if _, e = os.Stat(p.SocketPath()); !os.IsNotExist(e) { t.Fatalf("socket survived: %v", e) } if c, e = net.Dial("unix", p.SocketPath()); e == nil { c.Close() t.Fatal("listener survived") } } func TestEgressLimits(t *testing.T) { if MaxHeaders != 8*1024 || MaxTunnels != 16 || ConnectTimeout != 15*time.Second || IdleTimeout != 60*time.Second { t.Fatal("limits differ from brief") } t.Run("headers", func(t *testing.T) { var called atomic.Bool p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, func(context.Context, string, string) (net.Conn, error) { called.Store(true) return nil, errors.New("dial") }) _, _, line := connect(t, p, "CONNECT fixture.example:443 HTTP/1.1\r\nUser-Agent: "+strings.Repeat("x", MaxHeaders)+"\r\n\r\n") if strings.Contains(line, "200") || called.Load() { t.Fatal("oversized headers dialled") } }) t.Run("concurrent", func(t *testing.T) { p := fixtureProxy(t, nil, nil) var cs []net.Conn defer func() { for _, c := range cs { c.Close() } }() for i := 0; i < MaxTunnels; i++ { c, e := net.Dial("unix", p.SocketPath()) if e != nil { t.Fatal(e) } cs = append(cs, c) } deadline := time.Now().Add(time.Second) for p.active() != MaxTunnels && time.Now().Before(deadline) { time.Sleep(time.Millisecond) } if p.active() != MaxTunnels { t.Fatal("slots not occupied") } c, e := net.Dial("unix", p.SocketPath()) if e != nil { t.Fatal(e) } defer c.Close() c.SetReadDeadline(time.Now().Add(time.Second)) _, e = c.Read(make([]byte, 1)) if e == nil { t.Fatal("extra connection survived") } if ne, ok := e.(net.Error); ok && ne.Timeout() { t.Fatal("extra socket remained open") } }) t.Run("idle", func(t *testing.T) { d := defaults() d.idle = 80 * time.Millisecond d.lookup = func(context.Context, string) ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil } d.dial = func(context.Context, string, string) (net.Conn, error) { a, b := net.Pipe() t.Cleanup(func() { b.Close() }) return a, nil } p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d) if e != nil { t.Fatal(e) } defer p.Close() c, r, line := connect(t, p, request("fixture.example:443")) if !strings.Contains(line, "200") { t.Fatal(line) } r.ReadString('\n') c.SetReadDeadline(time.Now().Add(time.Second)) _, e = r.ReadByte() if e == nil { t.Fatal("idle tunnel survived") } if ne, ok := e.(net.Error); ok && ne.Timeout() { t.Fatal("idle tunnel not closed") } }) t.Run("connect", func(t *testing.T) { d := defaults() d.connect = 80 * time.Millisecond d.lookup = func(context.Context, string) ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil } d.dial = func(ctx context.Context, _, _ string) (net.Conn, error) { <-ctx.Done(); return nil, ctx.Err() } p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d) if e != nil { t.Fatal(e) } defer p.Close() start := time.Now() connect(t, p, request("fixture.example:443")) if time.Since(start) > time.Second { t.Fatal("connect timeout missing") } }) } func TestEgressPolicy(t *testing.T) { for _, name := range []string{"claude", "codex"} { want := "api.anthropic.com" if name == "codex" { want = "chatgpt.com" } p, e := ProviderPolicy(provider.NetworkContract{Provider: name}, false) if e != nil || len(p.Hosts) != 1 || p.Hosts[0] != want { t.Fatalf("default: %+v %v", p, e) } p, e = ProviderPolicy(provider.NetworkContract{Provider: name, AuthHost: "refresh.example"}, false) if e == nil { t.Fatal("shared home got refresh") } p, e = ProviderPolicy(provider.NetworkContract{Provider: name, AuthHost: "refresh.example"}, true) if e == nil { t.Fatal("dedicated refresh admitted") } } for _, p := range []Policy{{Provider: "other", Hosts: []string{"fixture.example"}}, {Provider: "claude"}, {Provider: "claude", Hosts: []string{"*.example"}}, {Provider: "claude", Hosts: []string{"127.0.0.1"}}, {Provider: "claude", Hosts: []string{"localhost"}}, {Provider: "claude", Hosts: []string{"fixture.example", "fixture.example"}}} { if _, e := p.Hash(); e == nil { t.Fatalf("invalid policy accepted: %+v", p) } } a, _ := (Policy{Provider: "claude", Hosts: []string{"a.example", "b.example"}}).Hash() b, _ := (Policy{Provider: "claude", Hosts: []string{"b.example", "a.example"}}).Hash() c, _ := (Policy{Provider: "claude", Hosts: []string{"a.example"}}).Hash() d, _ := (Policy{Provider: "codex", Hosts: []string{"a.example", "b.example"}}).Hash() if len(a) != 64 || a != b || a == c || a == d { t.Fatal("policy hash does not bind exact host set and provider") } } func TestEgressPrivateSocket(t *testing.T) { dir := scratch(t) p, e := Open(context.Background(), dir, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}) if e != nil { t.Fatal(e) } defer p.Close() info, e := os.Stat(p.SocketPath()) if e != nil || info.Mode().Perm() != 0600 { t.Fatalf("socket mode: %v %v", info, e) } if _, e = Open(context.Background(), dir, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}); e == nil { t.Fatal("existing socket replaced") } bad := scratch(t) os.Chmod(bad, 0755) if q, e := Open(context.Background(), bad, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}); e == nil { q.Close() t.Fatal("nonprivate directory accepted") } link := filepath.Join(scratch(t), "link") os.Symlink(scratch(t), link) if q, e := Open(context.Background(), link, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}); e == nil { q.Close() t.Fatal("symlink directory accepted") } } func TestEgressSocketDirectoryPinned(t *testing.T) { root := scratch(t) dir := filepath.Join(root, "private") if e := os.Mkdir(dir, 0700); e != nil { t.Fatal(e) } p, e := Open(context.Background(), dir, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}) if e != nil { t.Fatal(e) } defer p.Close() moved := filepath.Join(root, "moved") if e = os.Rename(dir, moved); e != nil { t.Fatal(e) } if e = os.Mkdir(dir, 0700); e != nil { t.Fatal(e) } decoy := filepath.Join(dir, "proxy.sock") if e = os.WriteFile(decoy, []byte("replacement"), 0600); e != nil { t.Fatal(e) } if e = p.Close(); e != nil { t.Fatal(e) } if _, e = os.Stat(filepath.Join(moved, "proxy.sock")); !os.IsNotExist(e) { t.Errorf("socket survived close in verified directory: %v", e) } if b, e := os.ReadFile(decoy); e != nil || string(b) != "replacement" { t.Fatalf("close touched replacement directory: %q %v", b, e) } } func TestEgressActiveTunnelClose(t *testing.T) { for _, mode := range []string{"close", "cancel", "listener_failure"} { t.Run(mode, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() a, b := net.Pipe() defer b.Close() d := defaults() d.lookup = func(context.Context, string) ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil } d.dial = func(context.Context, string, string) (net.Conn, error) { return a, nil } p, e := open(ctx, scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d) if e != nil { t.Fatal(e) } defer p.Close() c, r, line := connect(t, p, request("fixture.example:443")) if !strings.Contains(line, "200") { t.Fatal(line) } r.ReadString('\n') switch mode { case "close": closePromptly(t, p, c, b) case "cancel": cancel() case "listener_failure": p.listener.Close() } select { case <-p.Done(): case <-time.After(time.Second): t.Fatal("proxy failure not reported") } closePromptly(t, p, c, b) for _, conn := range []net.Conn{c, b} { conn.SetReadDeadline(time.Now().Add(time.Second)) _, e := conn.Read(make([]byte, 1)) if e == nil { t.Fatal("socket survived shutdown") } if ne, ok := e.(net.Error); ok && ne.Timeout() { t.Fatal("socket not closed") } } }) } } func TestEgressPolicyFrozen(t *testing.T) { hosts := []string{"fixture.example"} var called atomic.Bool d := defaults() d.lookup = func(context.Context, string) ([]netip.Addr, error) { called.Store(true); return nil, errors.New("dns") } p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: hosts}, d) if e != nil { t.Fatal(e) } defer p.Close() hosts[0] = "other.example" connect(t, p, request("other.example:443")) if called.Load() { t.Fatal("policy changed after open") } for _, ip := range []string{"8.8.8.8", "2606:4700:4700::1111", "::ffff:8.8.8.8"} { if !publicAddress(netip.MustParseAddr(ip)) { t.Fatalf("public address rejected: %s", ip) } } } func TestEgressHeaderTimeout(t *testing.T) { d := defaults() d.connect = 80 * time.Millisecond p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d) if e != nil { t.Fatal(e) } defer p.Close() c, e := net.Dial("unix", p.SocketPath()) if e != nil { t.Fatal(e) } defer c.Close() c.SetReadDeadline(time.Now().Add(time.Second)) _, e = io.ReadAll(c) if ne, ok := e.(net.Error); ok && ne.Timeout() { t.Fatal("incomplete header kept socket open") } } // TestEgressTableKeyedByHarnessAndProvider: the egress table (connectors // spec ยง2.2) gives a metered connection exactly its provider's host, and // nothing for a harness and provider that are not a row; the Claude and // Codex policies hash as they always did; and each API-key provider's // row is its upstream's host. func TestEgressTableKeyedByHarnessAndProvider(t *testing.T) { p, e := ProviderPolicy(provider.NetworkContract{Provider: "tensorx", Harness: "pi"}, true) if e != nil || p.Provider != "tensorx" || p.Harness != "pi" || len(p.Hosts) != 1 || p.Hosts[0] != "api.tensorx.ai" { t.Fatalf("tensorx through pi: %+v %v", p, e) } if _, e := p.Hash(); e != nil { t.Fatal(e) } // OpenCode Go through OpenCode reaches opencode.ai only (slice S5); // the OpenCode to TensorX fallback row is not in the table. if p, e := ProviderPolicy(provider.NetworkContract{Provider: "opencode-go", Harness: "opencode"}, true); e != nil || len(p.Hosts) != 1 || p.Hosts[0] != "opencode.ai" || p.Harness != "opencode" { t.Fatalf("opencode-go through opencode: %+v %v", p, e) } for _, c := range []provider.NetworkContract{{Provider: "opencode-go"}, {Provider: "opencode-go", Harness: "pi"}, {Provider: "tensorx", Harness: "opencode"}, {Provider: "claude", Harness: "opencode"}} { if p, e := ProviderPolicy(c, true); e == nil { t.Fatalf("%+v admitted: %+v", c, p) } } for _, c := range []provider.NetworkContract{{Provider: "tensorx"}, {Provider: "tensorx", Harness: "claude"}, {Provider: "claude", Harness: "pi"}, {Provider: "codex", Harness: "pi"}, {Provider: "tensorx", Harness: "codex"}, {Provider: "tensorx", Harness: "pi", AuthHost: "auth.tensorx.ai"}} { if p, e := ProviderPolicy(c, true); e == nil { t.Fatalf("%+v admitted: %+v", c, p) } } for _, bad := range []Policy{{Provider: "tensorx", Hosts: []string{"api.tensorx.ai"}}, {Provider: "claude", Harness: "pi", Hosts: []string{"api.anthropic.com"}}, {Provider: "claude", Harness: "claude", Hosts: []string{"api.anthropic.com"}}} { if _, e := bad.Hash(); e == nil { t.Fatalf("hash of %+v", bad) } } // The Claude and Codex policies' hashes are those of the policy before // the table: the manifests that pin them stay valid. for name, host := range map[string]string{"claude": "api.anthropic.com", "codex": "chatgpt.com"} { p, _ := ProviderPolicy(provider.NetworkContract{Provider: name}, true) got, _ := p.Hash() sum := sha256.Sum256([]byte(`{"Provider":"` + name + `","Hosts":["` + host + `"]}`)) if got != hex.EncodeToString(sum[:]) || p.Harness != "" { t.Fatalf("%s policy hash changed: %s", name, got) } } a, _ := (Policy{Provider: "tensorx", Harness: "pi", Hosts: []string{"api.tensorx.ai"}}).Hash() b, _ := (Policy{Provider: "tensorx", Harness: "pi", Hosts: []string{"api.tensorx.ai", "other.example"}}).Hash() if a == "" || a == b { t.Fatal("hash does not bind the host set") } for name, kp := range wire.APIKeyProviders { u, err := url.Parse(kp.Upstream) if err != nil { t.Fatal(err) } hosts := Routes()[Route{Harness: kp.Harness, Provider: name}] if len(hosts) != 1 || hosts[0] != u.Hostname() || u.Scheme != "https" || kp.Endpoint != "https://"+u.Hostname()+":443" { t.Fatalf("%s: table %v, upstream %s, endpoint %s", name, hosts, kp.Upstream, kp.Endpoint) } } } // Node's fetch (undici, which Pi uses) names the host without its port // when it is 443, as RFC 9110 allows for the default port: that is the // same authority and is carried. Another host, or another port, is not. func TestEgressAcceptsNodeConnect(t *testing.T) { var calls atomic.Int32 p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, func(context.Context, string, string) (net.Conn, error) { calls.Add(1) a, b := net.Pipe() go func() { io.Copy(io.Discard, b) }() return a, nil }) node := "CONNECT fixture.example:443 HTTP/1.1\r\nhost: fixture.example\r\nconnection: close\r\nproxy-connection: keep-alive\r\n\r\n" if _, _, line := connect(t, p, node); !strings.Contains(line, "200") || calls.Load() != 1 { t.Fatalf("Node's CONNECT refused: %q", line) } for _, raw := range []string{ "CONNECT fixture.example:443 HTTP/1.1\r\nhost: other.example\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\r\nhost: fixture.example:8443\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\r\nhost: fixture.example:\r\n\r\n", "CONNECT fixture.example:443 HTTP/1.1\r\nhost: FIXTURE.EXAMPLE\r\n\r\n", } { before := calls.Load() if _, _, line := connect(t, p, raw); strings.Contains(line, "200") || calls.Load() != before { t.Fatalf("carried %q", raw) } } }