package egress import ( "context" "errors" "net" "net/http" "net/http/httptest" "strconv" "strings" "testing" "time" ) func TestOriginIsAlwaysALiteral(t *testing.T) { cases := []struct { target Target want string }{ {Target{Port: 8788}, "http://127.0.0.1:8788"}, {Target{Port: 8788, IPv6: true}, "http://[::1]:8788"}, {Target{Port: 1}, "http://127.0.0.1:1"}, {Target{Port: 65535}, "http://127.0.0.1:65535"}, } for _, c := range cases { if got := c.target.Origin(); got != c.want { t.Errorf("Origin() = %q, want %q", got, c.want) } if err := AssertLoopback(c.target.Origin()); err != nil { t.Errorf("AssertLoopback(%q) = %v, want nil", c.want, err) } } } func TestAssertLoopbackRejectsEverythingElse(t *testing.T) { for _, origin := range []string{ "http://simadmin.local:8788", "http://10.0.0.12:8788", "http://192.168.1.1:8788", "http://169.254.169.254/latest/meta-data", "http://[::ffff:8.8.8.8]:8788", "https://127.0.0.1:8788", "http://127.0.0.1:8788/prefix", "http://localhost:8788", "not a url", } { if err := AssertLoopback(origin); err == nil { t.Errorf("AssertLoopback(%q) accepted it", origin) } else if !strings.Contains(err.Error(), "egress:") { t.Errorf("AssertLoopback(%q) returned a foreign error: %v", origin, err) } } } func TestNewTargetValidatesPort(t *testing.T) { for _, port := range []int{0, -1, 70000} { if _, err := NewTarget(port); !errors.Is(err, ErrNoPort) { t.Errorf("NewTarget(%d) err = %v, want ErrNoPort", port, err) } } target, err := NewTarget(8788) if err != nil || target.Origin() != "http://127.0.0.1:8788" { t.Fatalf("NewTarget(8788) = %v, %v", target, err) } } // TestDialRewritesTheHost is the central property: whatever address a caller believes it is // connecting to, the socket lands on loopback. If this ever fails, the blast radius of a policy // bug goes from "one node" back to "the whole subnet". func TestDialRewritesTheHost(t *testing.T) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) defer upstream.Close() _, port, err := net.SplitHostPort(strings.TrimPrefix(upstream.URL, "http://")) if err != nil { t.Fatalf("test server address unparseable: %v", err) } for _, address := range []string{ "example.com:" + port, "8.8.8.8:" + port, "169.254.169.254:" + port, "10.255.255.255:" + port, } { conn, err := Dial(context.Background(), "tcp", address) if err != nil { t.Fatalf("Dial(%q): %v", address, err) } local := conn.LocalAddr().(*net.TCPAddr) if !local.IP.IsLoopback() { t.Errorf("Dial(%q) landed on %s, which is not loopback", address, local.IP) } remote := conn.RemoteAddr().(*net.TCPAddr) if !remote.IP.IsLoopback() { t.Errorf("Dial(%q) connected to %s", address, remote.IP) } if err := conn.Close(); err != nil { t.Fatal(err) } } } func TestDialRefusesNonTCPNetworks(t *testing.T) { for _, network := range []string{"udp", "unix", "ip", ""} { if _, err := Dial(context.Background(), network, "127.0.0.1:8788"); err == nil { t.Errorf("Dial accepted network %q", network) } } } func TestDialRefusesMalformedOrUndialableTargets(t *testing.T) { // The port escapes into a syscall argument, so garbage must be rejected before dialing. for _, address := range []string{"", "no-separator", "host:notaport", "127.0.0.1:99999", "127.0.0.1:0"} { if _, err := Dial(context.Background(), "tcp", address); err == nil { t.Errorf("Dial accepted address %q", address) } } } func TestClientFollowsNoRedirects(t *testing.T) { var redirectAttempts int upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/api/health": redirectAttempts++ // A pivot attempt: bounce the agent at an address the policy never listed. http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusFound) default: t.Errorf("client followed a redirect to %s", r.URL.Path) } })) defer upstream.Close() client, err := NewClient(Target{Port: portOf(t, upstream.URL)}, 2*time.Second) if err != nil { t.Fatal(err) } resp, err := client.Get(upstream.URL + "/api/health") if err != nil { t.Fatalf("GET: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusFound { t.Fatalf("status = %d, want the 302 passed through unread", resp.StatusCode) } if redirectAttempts != 1 { t.Fatalf("upstream saw %d requests, want 1", redirectAttempts) } } // TestClientIgnoresProxyEnvironment matters on shared nodes: an operator exporting HTTP_PROXY for // apt must not be able to relocate what the agent considers a loopback call. func TestClientIgnoresProxyEnvironment(t *testing.T) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"ok":true}`)) })) defer upstream.Close() t.Setenv("HTTP_PROXY", "http://127.0.0.1:1") t.Setenv("http_proxy", "http://127.0.0.1:1") client, err := NewClient(Target{Port: portOf(t, upstream.URL)}, 2*time.Second) if err != nil { t.Fatal(err) } resp, err := client.Get(upstream.URL + "/api/health") if err != nil { t.Fatalf("GET routed through the environment proxy: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { t.Fatalf("status = %d, want 200", resp.StatusCode) } } func TestClientRefusesAnUnsetTarget(t *testing.T) { if _, err := NewClient(Target{}, time.Second); !errors.Is(err, ErrNoPort) { t.Fatalf("NewClient(Target{}) err = %v, want ErrNoPort", err) } } func portOf(t *testing.T, origin string) int { t.Helper() _, port, err := net.SplitHostPort(strings.TrimPrefix(strings.TrimPrefix(origin, "http://"), "https://")) if err != nil { t.Fatalf("origin %q has no port: %v", origin, err) } n, err := strconv.Atoi(port) if err != nil { t.Fatalf("port %q: %v", port, err) } return n }