From 52f788308c73b01fb9a8d9c7f7475b6fd8ba8daa Mon Sep 17 00:00:00 2001 From: edwardowens Date: Mon, 9 Nov 2026 16:02:41 -0800 Subject: [PATCH 1/2] fix(intercept): resolve bridge's own lookups without the tunnel it's redialing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the gRPC connection to the proxy drops, the k8spf redial needs real DNS: resolvePod → K8s API → aws eks get-token → STS. The _bridge group was meant to skip the DNS redirect for this, but since /etc/resolv.conf names only 127.0.0.1, its lookups still reached the DNS server that asks the tunnel. With --forward-domains "*" that includes the API server itself, so every redial failed and the intercept never recovered: all DNS in the container stayed SERVFAIL until it was torn down. - Start a bypass DNS server that only asks the original nameserver, and redirect the _bridge group's UDP :53 to it instead of RETURN. The app's lookups still go through the tunnel, with no fallback around it. - Replace a pooled SPDY port-forward dialer once its connection closes. The pool handed the dead one back forever, so redials would fail even with DNS working. Co-Authored-By: Claude Opus 5.5 --- e2e/Dockerfile.devcontainer | 7 +- e2e/intercept_test.go | 67 ++++++++++++++++++ pkg/commands/intercept.go | 32 ++++++--- pkg/commands/intercept_dns.go | 27 ++++++++ pkg/commands/intercept_proxy.go | 74 +++++++++++--------- pkg/commands/intercept_proxy_test.go | 56 +++++++++++++++ pkg/k8s/k8spf/pool.go | 53 ++++++++++++--- pkg/k8s/k8spf/pool_test.go | 90 +++++++++++++++++++++++++ pkg/k8s/portforward/portforward.go | 11 +++ pkg/k8s/portforward/portforward_test.go | 30 +++++++++ 10 files changed, 397 insertions(+), 50 deletions(-) create mode 100644 pkg/commands/intercept_proxy_test.go create mode 100644 pkg/k8s/k8spf/pool_test.go create mode 100644 pkg/k8s/portforward/portforward_test.go diff --git a/e2e/Dockerfile.devcontainer b/e2e/Dockerfile.devcontainer index 9c2d579..353003a 100644 --- a/e2e/Dockerfile.devcontainer +++ b/e2e/Dockerfile.devcontainer @@ -3,7 +3,12 @@ FROM alpine:3.20 # Install runtime dependencies # iptables is needed for traffic interception # openssh-client is needed for SSH connections -RUN apk add --no-cache ca-certificates iptables openssh-client busybox-extras curl +# shadow-login provides sg, which the bridge feature runs intercept under +RUN apk add --no-cache ca-certificates iptables openssh-client busybox-extras curl shadow-login + +# The group the bridge feature runs intercept as, so iptables can tell +# bridge's own traffic apart from the app's. +RUN addgroup -S _bridge # Copy the pre-built binary COPY bridge /usr/local/bin/bridge diff --git a/e2e/intercept_test.go b/e2e/intercept_test.go index ea519c0..3462718 100644 --- a/e2e/intercept_test.go +++ b/e2e/intercept_test.go @@ -346,6 +346,73 @@ func (s *InterceptSuite) TestIngress() { require.Contains(t, wgetOutput, "ok", "expected 'ok' from test server via ingress tunnel") } +// startWitness starts a container on the bridge network under the alias +// "witness", a name the intercept container's own Docker DNS can answer +// without the tunnel. It returns the witness's IP. +func (s *InterceptSuite) startWitness(t *testing.T) string { + witnessC, err := testcontainers.GenericContainer(s.ctx, testcontainers.GenericContainerRequest{ + ContainerRequest: testcontainers.ContainerRequest{ + Image: s.interceptImg, + Cmd: []string{"sleep", "300"}, + Networks: []string{s.bridgeNet.Name}, + NetworkAliases: map[string][]string{ + s.bridgeNet.Name: {"witness"}, + }, + }, + Started: true, + }) + require.NoError(t, err, "failed to start witness container") + t.Cleanup(func() { testcontainers.TerminateContainer(witnessC) }) + + inspect, err := witnessC.Inspect(s.ctx) + require.NoError(t, err, "failed to inspect witness container") + ip := inspect.NetworkSettings.Networks[s.bridgeNet.Name].IPAddress + require.NotEmpty(t, ip, "witness container has no IP on bridge network") + return ip +} + +// TestBridgeResolvesWhileTunnelIsDown drops the tunnel under a running +// intercept. Redialing the proxy needs real DNS (in a cluster: the API server, +// then aws eks get-token → STS), so bridge's own group must still resolve +// names while the tunnel is down, or the redial asks the broken tunnel and the +// intercept never recovers. The app must not: its names belong to the tunnel. +func (s *InterceptSuite) TestBridgeResolvesWhileTunnelIsDown() { + t := s.T() + + proxyC, proxyIP := s.startProxy(t, []string{"bridge", "--log-paths", "stderr", "server", "--addr", ":9090"}) + interceptC := s.startIntercept(t) + witnessIP := s.startWitness(t) + + // Run intercept the way the bridge feature does: as root, under _bridge. + exitCode, reader, err := interceptC.Exec(s.ctx, []string{ + "sh", "-c", + fmt.Sprintf(`sg _bridge -c 'bridge --log-paths stderr intercept --server-addr %s:9090 --forward-domains "*"' > /tmp/bridge-intercept.log 2>&1 &`, proxyIP), + }) + require.NoError(t, err, "failed to exec bridge intercept") + io.Copy(io.Discard, reader) + require.Equal(t, 0, exitCode, "bridge intercept exec failed") + + ct := container.NewDockerClient() + require.NoError(t, intercept.WaitForReady(s.ctx, ct, interceptC.GetContainerID()), "bridge intercept did not become ready") + + stopTimeout := 5 * time.Second + require.NoError(t, proxyC.Stop(s.ctx, &stopTimeout), "failed to stop proxy") + t.Log("Proxy stopped; the tunnel is down") + + lookup := func(cmd string) string { + _, reader, err := interceptC.Exec(s.ctx, []string{"sh", "-c", cmd}) + require.NoError(t, err, "lookup exec failed: %s", cmd) + data, _ := io.ReadAll(reader) + t.Logf("[%s]\n%s", cmd, strings.TrimSpace(string(data))) + return string(data) + } + + require.Contains(t, lookup(`sg _bridge -c 'nslookup witness'`), witnessIP, + "bridge's own lookups must not depend on the tunnel") + require.NotContains(t, lookup(`nslookup witness`), witnessIP, + "the app's lookups must still go through the tunnel, not around it") +} + func TestInterceptSuite(t *testing.T) { suite.Run(t, new(InterceptSuite)) } diff --git a/pkg/commands/intercept.go b/pkg/commands/intercept.go index 7d44a04..3a94ca4 100644 --- a/pkg/commands/intercept.go +++ b/pkg/commands/intercept.go @@ -212,7 +212,7 @@ func doIntercept(ctx context.Context, c *cli.Command) error { registry := conntrack.New(pool) // Start DNS (optional) - var dns *DNSComponent + var dns, bypassDNS *DNSComponent var originalResolvConf []byte if len(forwardDomains) > 0 { // Read the original nameserver before we modify /etc/resolv.conf @@ -228,6 +228,13 @@ func doIntercept(ctx context.Context, c *cli.Command) error { return fmt.Errorf("failed to start DNS: %w", err) } + bypassDNS, err = StartBypassDNS(originalNS) + if err != nil { + dns.Stop() + registry.Stop() + return fmt.Errorf("failed to start bypass DNS: %w", err) + } + // Point /etc/resolv.conf at our DNS server originalResolvConf, err = updateResolvConf("127.0.0.1") if err != nil { @@ -236,21 +243,25 @@ func doIntercept(ctx context.Context, c *cli.Command) error { } // Start proxy (transparent proxy + tunnel) - var dnsPortForIPTables int + var dnsPortForIPTables, bypassDNSPort int if dns != nil { dnsPortForIPTables = dns.Port() } + if bypassDNS != nil { + bypassDNSPort = bypassDNS.Port() + } - // Pass the current process GID so iptables can exclude bridge's own DNS - // traffic from the UDP redirect. This prevents a circular dependency when + // Pass the current process GID so iptables can send bridge's own DNS + // traffic to the bypass server. This prevents a circular dependency when // gRPC reconnects and needs real DNS for EKS auth. GID 0 (root) is not // excluded since that would bypass the redirect for most container processes. proxyComp, err := StartProxy(ProxyConfig{ - Tunnel: tun, - ProxyPort: proxyPort, - Registry: registry, - DNSPort: dnsPortForIPTables, - ExcludeGID: os.Getgid(), + Tunnel: tun, + ProxyPort: proxyPort, + Registry: registry, + DNSPort: dnsPortForIPTables, + ExcludeGID: os.Getgid(), + BypassDNSPort: bypassDNSPort, }) if err != nil { return fmt.Errorf("failed to start proxy listener: %w", err) @@ -317,6 +328,9 @@ func doIntercept(ctx context.Context, c *cli.Command) error { if dns != nil { dns.Stop() } + if bypassDNS != nil { + bypassDNS.Stop() + } restoreResolvConf(originalResolvConf) registry.Stop() proxyComp.Stop() diff --git a/pkg/commands/intercept_dns.go b/pkg/commands/intercept_dns.go index da6c5c7..fba16cf 100644 --- a/pkg/commands/intercept_dns.go +++ b/pkg/commands/intercept_dns.go @@ -47,6 +47,33 @@ func StartDNS(cfg DNSConfig) (*DNSComponent, error) { }, nil } +// StartBypassDNS starts a DNS server on a random loopback port that only asks +// upstream, never the tunnel. SetupIptables sends the intercept's own group's +// DNS here, so re-establishing a dropped tunnel never waits on that tunnel. +func StartBypassDNS(upstream string) (*DNSComponent, error) { + dnsServer, err := bridgedns.New(bridgedns.Config{ + ListenAddr: "127.0.0.1:0", + Client: bridgedns.NewSystemExchangeClient(upstream), + }) + if err != nil { + return nil, fmt.Errorf("failed to create bypass DNS server: %w", err) + } + + go func() { + if err := dnsServer.ListenAndServe(); err != nil { + slog.Error("Bypass DNS server error", "error", err) + } + }() + + port := dnsServer.Port() + slog.Info("Bypass DNS enabled for bridge's own lookups", "port", port, "upstream", upstream) + + return &DNSComponent{ + server: dnsServer, + port: port, + }, nil +} + // Port returns the port the DNS server is listening on. func (d *DNSComponent) Port() int { return d.port diff --git a/pkg/commands/intercept_proxy.go b/pkg/commands/intercept_proxy.go index ca357cd..e772ce4 100644 --- a/pkg/commands/intercept_proxy.go +++ b/pkg/commands/intercept_proxy.go @@ -19,21 +19,23 @@ const ( // ProxyComponent manages the transparent proxy listener, tunnel client, and iptables rules. type ProxyComponent struct { - tunnel tunnel.Tunnel - listener net.Listener - port int - registry *conntrack.Registry - dnsPort int - excludeGID int + tunnel tunnel.Tunnel + listener net.Listener + port int + registry *conntrack.Registry + dnsPort int + excludeGID int + bypassDNSPort int } // ProxyConfig holds configuration for starting the proxy component. type ProxyConfig struct { - Tunnel tunnel.Tunnel - ProxyPort int // 0 = random - Registry *conntrack.Registry - DNSPort int // If >0, redirect all UDP :53 traffic to this port - ExcludeGID int // If >0, exclude this GID from DNS redirect + Tunnel tunnel.Tunnel + ProxyPort int // 0 = random + Registry *conntrack.Registry + DNSPort int // If >0, redirect all UDP :53 traffic to this port + ExcludeGID int // If >0, send this GID's UDP :53 traffic to BypassDNSPort instead + BypassDNSPort int // Upstream-only DNS server for ExcludeGID } // StartProxy creates a transparent proxy listener and initializes the tunnel client. @@ -46,12 +48,13 @@ func StartProxy(cfg ProxyConfig) (*ProxyComponent, error) { addr := listener.Addr().(*net.TCPAddr) p := &ProxyComponent{ - tunnel: cfg.Tunnel, - listener: listener, - port: addr.Port, - registry: cfg.Registry, - dnsPort: cfg.DNSPort, - excludeGID: cfg.ExcludeGID, + tunnel: cfg.Tunnel, + listener: listener, + port: addr.Port, + registry: cfg.Registry, + dnsPort: cfg.DNSPort, + excludeGID: cfg.ExcludeGID, + bypassDNSPort: cfg.BypassDNSPort, } return p, nil @@ -69,6 +72,19 @@ func (p *ProxyComponent) SetupIptables() error { return fmt.Errorf("iptables not found: %w", err) } + for _, args := range p.iptablesRules() { + cmd := exec.Command(args[0], args[1:]...) + if output, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("iptables %v failed: %w: %s", args[1:], err, output) + } + } + + slog.Info("iptables rules configured", "proxy_port", p.port, "proxy_cidr", proxyCIDR) + return nil +} + +// iptablesRules returns the iptables commands SetupIptables runs, in order. +func (p *ProxyComponent) iptablesRules() [][]string { cmds := [][]string{ // Create a new chain for our rules {"iptables", "-t", "nat", "-N", "BRIDGE_INTERCEPT"}, @@ -85,17 +101,19 @@ func (p *ProxyComponent) SetupIptables() error { // instead of /etc/resolv.conf. The DNS server's own fallback queries use // TCP, so they are not affected by this rule. if p.dnsPort > 0 { - // Exclude bridge's own GID from the DNS redirect. When the gRPC - // connection drops and reconnects, the k8spf dialer calls + // Send bridge's own GID to the bypass DNS server instead. When the + // gRPC connection drops and reconnects, the k8spf dialer calls // resolvePod → K8s API → aws eks get-token, which needs real DNS - // to reach sts.amazonaws.com. Without this exclusion, the query - // loops back to our DNS server which depends on the broken tunnel. - if p.excludeGID > 0 { + // for the API server and sts.amazonaws.com. /etc/resolv.conf names + // only our DNS server, which asks the broken tunnel, so a RETURN + // here isn't enough: the query still reaches 127.0.0.1:53 and the + // intercept never recovers. + if p.excludeGID > 0 && p.bypassDNSPort > 0 { cmds = append(cmds, []string{"iptables", "-t", "nat", "-A", "BRIDGE_INTERCEPT", "-p", "udp", "--dport", "53", "-m", "owner", "--gid-owner", fmt.Sprintf("%d", p.excludeGID), - "-j", "RETURN"}, + "-j", "REDIRECT", "--to-ports", fmt.Sprintf("%d", p.bypassDNSPort)}, ) } cmds = append(cmds, @@ -104,15 +122,7 @@ func (p *ProxyComponent) SetupIptables() error { ) } - for _, args := range cmds { - cmd := exec.Command(args[0], args[1:]...) - if output, err := cmd.CombinedOutput(); err != nil { - return fmt.Errorf("iptables %v failed: %w: %s", args[1:], err, output) - } - } - - slog.Info("iptables rules configured", "proxy_port", p.port, "proxy_cidr", proxyCIDR) - return nil + return cmds } // Start begins the transparent proxy accept loop in the background. diff --git a/pkg/commands/intercept_proxy_test.go b/pkg/commands/intercept_proxy_test.go new file mode 100644 index 0000000..dd9d985 --- /dev/null +++ b/pkg/commands/intercept_proxy_test.go @@ -0,0 +1,56 @@ +package commands + +import ( + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func ruleIndex(rules [][]string, contains ...string) int { + return slices.IndexFunc(rules, func(rule []string) bool { + joined := strings.Join(rule, " ") + for _, s := range contains { + if !strings.Contains(joined, s) { + return false + } + } + return true + }) +} + +// The intercept's own lookups (the k8spf redial: API server, then aws eks +// get-token → STS) must reach the bypass DNS server, never the one that asks +// the tunnel they are trying to rebuild. /etc/resolv.conf names only +// 127.0.0.1, so letting the group skip the redirect isn't enough. +func TestIptablesRules_SendsBridgesOwnDNSToTheBypassServer(t *testing.T) { + p := &ProxyComponent{port: 15001, dnsPort: 53, excludeGID: 999, bypassDNSPort: 40123} + rules := p.iptablesRules() + + own := ruleIndex(rules, "--gid-owner 999", "-p udp --dport 53", "-j REDIRECT --to-ports 40123") + require.NotEqual(t, -1, own, "bridge's group must be redirected to the bypass DNS server") + assert.Equal(t, -1, ruleIndex(rules, "--gid-owner 999", "-j RETURN"), + "RETURN leaves the query going to 127.0.0.1:53, which asks the broken tunnel") + + everyone := ruleIndex(rules, "BRIDGE_INTERCEPT -p udp --dport 53 -j REDIRECT --to-ports 53") + require.NotEqual(t, -1, everyone) + assert.Less(t, own, everyone, "bridge's rule must come first or the general redirect wins") +} + +func TestIptablesRules_NoGroupRuleWithoutABypassServerOrGroup(t *testing.T) { + for name, p := range map[string]*ProxyComponent{ + "root group": {port: 15001, dnsPort: 53, excludeGID: 0, bypassDNSPort: 40123}, + "no bypass server": {port: 15001, dnsPort: 53, excludeGID: 999, bypassDNSPort: 0}, + } { + t.Run(name, func(t *testing.T) { + assert.Equal(t, -1, ruleIndex(p.iptablesRules(), "--gid-owner")) + }) + } +} + +func TestIptablesRules_NoDNSRulesWithoutDNS(t *testing.T) { + p := &ProxyComponent{port: 15001, excludeGID: 999, bypassDNSPort: 40123} + assert.Equal(t, -1, ruleIndex(p.iptablesRules(), "--dport 53")) +} diff --git a/pkg/k8s/k8spf/pool.go b/pkg/k8s/k8spf/pool.go index 84e7139..c53f2da 100644 --- a/pkg/k8s/k8spf/pool.go +++ b/pkg/k8s/k8spf/pool.go @@ -1,7 +1,9 @@ package k8spf import ( + "context" "fmt" + "net" "github.com/puzpuzpuz/xsync/v3" "github.com/vercel/bridge/pkg/k8s/portforward" @@ -9,29 +11,52 @@ import ( "k8s.io/client-go/rest" ) +// podDialer is the part of portforward.Dialer the pool depends on. +type podDialer interface { + DialContext(ctx context.Context, addr string) (net.Conn, error) + Closed() bool + Close() error +} + +type newPodDialerFunc func(restConfig *rest.Config, clientset kubernetes.Interface, namespace, podName string, port int) (podDialer, error) + // dialerPool caches SPDY portforward.Dialer instances by target key so // multiple gRPC streams to the same pod share one SPDY connection. type dialerPool struct { - dialers *xsync.MapOf[string, *portforward.Dialer] // key: "pod.namespace:port" + dialers *xsync.MapOf[string, podDialer] // key: "pod.namespace:port" + newDialer newPodDialerFunc } func newDialerPool() *dialerPool { return &dialerPool{ - dialers: xsync.NewMapOf[string, *portforward.Dialer](), + dialers: xsync.NewMapOf[string, podDialer](), + newDialer: func(restConfig *rest.Config, clientset kubernetes.Interface, namespace, podName string, port int) (podDialer, error) { + d, err := portforward.NewDialer(restConfig, clientset, namespace, podName, port) + if err != nil { + return nil, err + } + return d, nil + }, } } -// Get returns an existing dialer for the target or creates a new one. -func (p *dialerPool) Get(t Target, restConfig *rest.Config, clientset kubernetes.Interface) (*portforward.Dialer, error) { +// Get returns an open dialer for the target, creating one if there is none or +// the cached one's SPDY connection has closed. gRPC redials through here after +// a dropped connection, so handing back the dead dialer would fail every +// redial for as long as the pod lives. +func (p *dialerPool) Get(t Target, restConfig *rest.Config, clientset kubernetes.Interface) (podDialer, error) { key := t.String() - // Fast path: dialer already exists. + // Fast path: an open dialer already exists. if d, ok := p.dialers.Load(key); ok { - return d, nil + if !d.Closed() { + return d, nil + } + p.evict(key, d) } // Slow path: create a new dialer outside the map, then store-or-load. - d, err := portforward.NewDialer(restConfig, clientset, t.Namespace, t.Name, t.Port) + d, err := p.newDialer(restConfig, clientset, t.Namespace, t.Name, t.Port) if err != nil { return nil, fmt.Errorf("k8spf pool: create dialer for %s: %w", key, err) } @@ -44,9 +69,21 @@ func (p *dialerPool) Get(t Target, restConfig *rest.Config, clientset kubernetes return actual, nil } +// evict removes dead from the pool unless another goroutine already replaced +// it, and closes it. +func (p *dialerPool) evict(key string, dead podDialer) { + p.dialers.Compute(key, func(current podDialer, loaded bool) (podDialer, bool) { + if loaded && current != dead { + return current, false + } + return nil, true + }) + dead.Close() +} + // Close closes all cached dialers. func (p *dialerPool) Close() { - p.dialers.Range(func(key string, d *portforward.Dialer) bool { + p.dialers.Range(func(key string, d podDialer) bool { d.Close() p.dialers.Delete(key) return true diff --git a/pkg/k8s/k8spf/pool_test.go b/pkg/k8s/k8spf/pool_test.go new file mode 100644 index 0000000..ee967eb --- /dev/null +++ b/pkg/k8s/k8spf/pool_test.go @@ -0,0 +1,90 @@ +package k8spf + +import ( + "context" + "net" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/rest" +) + +type fakePodDialer struct { + closed bool + closeCalls int +} + +func (f *fakePodDialer) DialContext(context.Context, string) (net.Conn, error) { return nil, nil } +func (f *fakePodDialer) Closed() bool { return f.closed } +func (f *fakePodDialer) Close() error { + f.closeCalls++ + f.closed = true + return nil +} + +// newFakePool returns a pool whose dialers are fakes, and the fakes it made in +// order. +func newFakePool() (*dialerPool, *[]*fakePodDialer) { + made := &[]*fakePodDialer{} + p := newDialerPool() + p.newDialer = func(*rest.Config, kubernetes.Interface, string, string, int) (podDialer, error) { + d := &fakePodDialer{} + *made = append(*made, d) + return d, nil + } + return p, made +} + +var testTarget = Target{Name: "bridge-proxy-abc", Namespace: "default", Port: 8080, Workload: "pod"} + +func TestPoolReusesAnOpenDialer(t *testing.T) { + p, made := newFakePool() + + first, err := p.Get(testTarget, nil, nil) + require.NoError(t, err) + second, err := p.Get(testTarget, nil, nil) + require.NoError(t, err) + + assert.Same(t, first, second) + assert.Len(t, *made, 1, "an open SPDY connection is shared, not redialed") +} + +// After the API server or kubelet drops the SPDY connection, gRPC redials +// through the pool. Handing back the dead dialer would fail every redial for +// as long as the pod lives. +func TestPoolReplacesADialerWhoseConnectionClosed(t *testing.T) { + p, made := newFakePool() + + first, err := p.Get(testTarget, nil, nil) + require.NoError(t, err) + (*made)[0].closed = true + + second, err := p.Get(testTarget, nil, nil) + require.NoError(t, err) + + require.Len(t, *made, 2, "a closed connection must be replaced") + assert.NotSame(t, first, second) + assert.False(t, second.Closed()) + assert.Equal(t, 1, (*made)[0].closeCalls, "the dead dialer is closed") + + third, err := p.Get(testTarget, nil, nil) + require.NoError(t, err) + assert.Same(t, second, third, "the replacement is what the pool hands out next") +} + +func TestPoolEvictKeepsAReplacementAnotherCallerStored(t *testing.T) { + p, _ := newFakePool() + dead := &fakePodDialer{closed: true} + fresh := &fakePodDialer{} + key := testTarget.String() + p.dialers.Store(key, fresh) + + p.evict(key, dead) + + got, ok := p.dialers.Load(key) + require.True(t, ok) + assert.Same(t, fresh, got) + assert.Equal(t, 0, fresh.closeCalls) +} diff --git a/pkg/k8s/portforward/portforward.go b/pkg/k8s/portforward/portforward.go index 2ce4dff..5202f59 100644 --- a/pkg/k8s/portforward/portforward.go +++ b/pkg/k8s/portforward/portforward.go @@ -136,6 +136,17 @@ func (d *Dialer) Close() error { return d.conn.Close() } +// Closed reports whether the SPDY connection has gone away, e.g. because the +// API server or kubelet dropped it. A closed Dialer can't create streams. +func (d *Dialer) Closed() bool { + select { + case <-d.conn.CloseChan(): + return true + default: + return false + } +} + // spdyConn wraps an SPDY data stream as a net.Conn. type spdyConn struct { dataStream httpstream.Stream diff --git a/pkg/k8s/portforward/portforward_test.go b/pkg/k8s/portforward/portforward_test.go new file mode 100644 index 0000000..b2949bf --- /dev/null +++ b/pkg/k8s/portforward/portforward_test.go @@ -0,0 +1,30 @@ +package portforward + +import ( + "net/http" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "k8s.io/apimachinery/pkg/util/httpstream" +) + +type fakeConn struct { + closeCh chan bool +} + +func (c *fakeConn) CreateStream(http.Header) (httpstream.Stream, error) { return nil, nil } +func (c *fakeConn) Close() error { return nil } +func (c *fakeConn) CloseChan() <-chan bool { return c.closeCh } +func (c *fakeConn) SetIdleTimeout(time.Duration) {} +func (c *fakeConn) RemoveStreams(...httpstream.Stream) {} + +func TestDialerClosedFollowsTheSPDYConnection(t *testing.T) { + conn := &fakeConn{closeCh: make(chan bool)} + d := &Dialer{conn: conn} + + assert.False(t, d.Closed()) + + close(conn.closeCh) + assert.True(t, d.Closed()) +} From 9ff80d44a185e9c2b3f141cf77ae84f89cf12de3 Mon Sep 17 00:00:00 2001 From: edwardowens Date: Mon, 9 Nov 2026 16:29:03 -0800 Subject: [PATCH 2/2] test(e2e): look up the witness as a FQDN so runner search domains don't apply GitHub runners give containers an Azure search domain, and busybox nslookup then queries only witness..internal.cloudapp.net. Co-Authored-By: Claude Opus 5.5 --- e2e/intercept_test.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/e2e/intercept_test.go b/e2e/intercept_test.go index 3462718..b0e41f1 100644 --- a/e2e/intercept_test.go +++ b/e2e/intercept_test.go @@ -407,9 +407,11 @@ func (s *InterceptSuite) TestBridgeResolvesWhileTunnelIsDown() { return string(data) } - require.Contains(t, lookup(`sg _bridge -c 'nslookup witness'`), witnessIP, + // The trailing dot stops busybox nslookup from trying only the host's + // search domain (GitHub runners inherit an Azure one). + require.Contains(t, lookup(`sg _bridge -c 'nslookup witness.'`), witnessIP, "bridge's own lookups must not depend on the tunnel") - require.NotContains(t, lookup(`nslookup witness`), witnessIP, + require.NotContains(t, lookup(`nslookup witness.`), witnessIP, "the app's lookups must still go through the tunnel, not around it") }