upstreamguard: share the link-local dial guard with activator and host
Astra R1 P1: the activator's wake health check (waitHealthyAddr) and the host's readiness checks (routeReady's connect and HTTP probe, which proofRouteReady feeds each of a route's Addrs through) dialed a route's TCP upstream with no guard. The guard moves to the leaf package internal/upstreamguard (Control, ErrLinkLocal, Dialer) and those three dials use it; the edge's three sites use it unchanged. The activator wait now stops at once on a refusal, and its transport drops the environment proxy so the guard judges the upstream itself.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+405
−98
internal/activator/backend_unit.go+20 −1internal/activator/healthaddr_guard_test.go+49 −0internal/edge/cname_steering_test.go+6 −13internal/edge/upstreamdial.go+6 −44internal/edge/upstreamdial_test.go+13 −36internal/host/unitsettle.go+16 −4internal/host/unitsettle_guard_test.go+61 −0internal/upstreamguard/guardtest/resolver.go+69 −0internal/upstreamguard/upstreamguard.go+76 −0internal/upstreamguard/upstreamguard_test.go+89 −0
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go| index 7da200c49..5dff27268 100644 |
| --- a/internal/activator/backend_unit.go |
| +++ b/internal/activator/backend_unit.go |
| @@ -51,6 +51,7 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| + "net" |
| "net/http" |
| "os/exec" |
| "strings" |
| @@ -64,6 +65,7 @@ import ( |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/upstreamguard" |
| ) |
| // UnitName is the systemd unit backing a unit-backed tenant's route — |
| @@ -264,14 +266,31 @@ func (unitRep) Close(context.Context) error { return nil } |
| // that can't accept a unix listener yet; see the carlos-app@.socket unit's |
| // fallback note). |
| func waitHealthyAddr(addr string, timeout time.Duration) error { |
| + return waitHealthyAddrVia(net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}, addr, timeout) |
| +} |
| + |
| +// waitHealthyAddrVia is waitHealthyAddr dialing with base (a test sets its |
| +// Resolver) behind upstreamguard: rt.Addr is route-supplied, so a link-local |
| +// or IMDS destination is refused after resolution and before connect, and |
| +// that refusal ends the wait at once. The transport is the default one's |
| +// settings without the environment proxy, so the guard judges the upstream |
| +// itself rather than a proxy. |
| +func waitHealthyAddrVia(base net.Dialer, addr string, timeout time.Duration) error { |
| + tr := http.DefaultTransport.(*http.Transport).Clone() |
| + tr.Proxy = nil |
| + tr.DialContext = upstreamguard.Dialer(base).DialContext |
| + defer tr.CloseIdleConnections() |
| deadline := time.Now().Add(timeout) |
| - client := healthClient(&http.Client{Timeout: 3 * time.Second}) |
| + client := healthClient(&http.Client{Timeout: 3 * time.Second, Transport: tr}) |
| var last error |
| var poll time.Duration |
| for time.Now().Before(deadline) { |
| if last = probeHealth(client, "http://"+addr+"/"); last == nil { |
| return nil |
| } |
| + if errors.Is(last, upstreamguard.ErrLinkLocal) { |
| + return fmt.Errorf("instance health check: %w", last) |
| + } |
| poll = nextHealthPoll(poll) |
| time.Sleep(poll) |
| } |
diff --git a/internal/activator/healthaddr_guard_test.go b/internal/activator/healthaddr_guard_test.go| new file mode 100644 |
| index 000000000..38b44aad1 |
| --- /dev/null |
| +++ b/internal/activator/healthaddr_guard_test.go |
| @@ -0,0 +1,49 @@ |
| +package activator |
| + |
| +import ( |
| + "errors" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/upstreamguard" |
| + "github.com/carlosframework/platform/internal/upstreamguard/guardtest" |
| +) |
| + |
| +// TestWaitHealthyAddrRefusesLinkLocal: a unit route's TCP upstream is |
| +// health-checked on wake before the edge proxies to it, so the check dials |
| +// through upstreamguard too. A name resolving to 169.254.169.254 is refused |
| +// after resolution (nothing is connected), and the refusal ends the wait at |
| +// once instead of polling a destination that can never be allowed. |
| +func TestWaitHealthyAddrRefusesLinkLocal(t *testing.T) { |
| + base := net.Dialer{Resolver: guardtest.Resolver(t, "imds.test", "169.254.169.254")} |
| + for _, tc := range []struct { |
| + name string |
| + wait func() error |
| + }{ |
| + {"name resolving to IMDS", func() error { return waitHealthyAddrVia(base, "imds.test:80", 5*time.Second) }}, |
| + {"IMDS literal, production dialer", func() error { return waitHealthyAddr("169.254.169.254:80", 5*time.Second) }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + start := time.Now() |
| + err := tc.wait() |
| + if !errors.Is(err, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("wait = %v, want ErrLinkLocal", err) |
| + } |
| + if d := time.Since(start); d > 2*time.Second { |
| + t.Fatalf("wait took %v; a refused destination must end the wait at once", d) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestWaitHealthyAddrLoopbackStillWorks(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) |
| + t.Cleanup(srv.Close) |
| + if err := waitHealthyAddr(strings.TrimPrefix(srv.URL, "http://"), 2*time.Second); err != nil { |
| + t.Fatalf("waitHealthyAddr on loopback: %v", err) |
| + } |
| +} |
diff --git a/internal/edge/cname_steering_test.go b/internal/edge/cname_steering_test.go| index d7bce3afa..959b3adbe 100644 |
| --- a/internal/edge/cname_steering_test.go |
| +++ b/internal/edge/cname_steering_test.go |
| @@ -33,18 +33,6 @@ func TestCertWarmGateFollowsACNAMEToTheSteeringHost(t *testing.T) { |
| // the lookup under test is the production LookupHost, CNAME-following and |
| // all, with only the network swapped. |
| func cnameDNS(t *testing.T, chain []string, ips []string) func(string) ([]string, error) { |
| - t.Helper() |
| - r := cnameResolver(t, chain, ips) |
| - return func(host string) ([]string, error) { |
| - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| - defer cancel() |
| - return r.LookupHost(ctx, host) |
| - } |
| -} |
| - |
| -// cnameResolver is cnameDNS's fake zone as the net.Resolver itself, for a |
| -// test that hands it to a net.Dialer. |
| -func cnameResolver(t *testing.T, chain []string, ips []string) *net.Resolver { |
| t.Helper() |
| pc, err := net.ListenPacket("udp", "127.0.0.1:0") |
| if err != nil { |
| @@ -104,8 +92,13 @@ func cnameResolver(t *testing.T, chain []string, ips []string) *net.Resolver { |
| _, _ = pc.WriteTo(msg, addr) |
| } |
| }() |
| - return &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + r := &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| var d net.Dialer |
| return d.DialContext(ctx, "udp", pc.LocalAddr().String()) |
| }} |
| + return func(host string) ([]string, error) { |
| + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| + defer cancel() |
| + return r.LookupHost(ctx, host) |
| + } |
| } |
diff --git a/internal/edge/upstreamdial.go b/internal/edge/upstreamdial.go| index dd435928e..28857146e 100644 |
| --- a/internal/edge/upstreamdial.go |
| +++ b/internal/edge/upstreamdial.go |
| @@ -1,54 +1,16 @@ |
| package edge |
| import ( |
| - "errors" |
| - "fmt" |
| "net" |
| - "net/netip" |
| - "syscall" |
| -) |
| - |
| -// errLinkLocalUpstream is the dial error for an upstream whose address is |
| -// link-local or the AWS instance metadata service. A route's addr is |
| -// operator- or tenant-supplied, and a name can resolve anywhere, so without |
| -// this an upstream of 169.254.169.254 (or a name pointing at it) would have |
| -// the edge fetch the box's own instance credentials for whoever asked. |
| -var errLinkLocalUpstream = errors.New("edge: refusing a link-local upstream address") |
| - |
| -// linkLocalUpstreams are the destinations no upstream may have: |
| -// 169.254.0.0/16 and fe80::/10 (link-local, IMDS's IPv4 address among them) |
| -// and fd00:ec2::254, IMDS's IPv6 address, which is not link-local. |
| -var linkLocalUpstreams = []netip.Prefix{ |
| - netip.MustParsePrefix("169.254.0.0/16"), |
| - netip.MustParsePrefix("fe80::/10"), |
| - netip.MustParsePrefix("fd00:ec2::254/128"), |
| -} |
| -// refuseLinkLocalUpstream is a net.Dialer Control hook. The dialer calls it |
| -// with the address it has already resolved, after creating the socket and |
| -// before connecting it, so a refusal here means nothing was connected, and a |
| -// name is judged by what it resolved to rather than by how it is spelled. |
| -// IPv4-mapped IPv6 is unmapped first, so ::ffff:169.254.169.254 is refused |
| -// too. An address that does not parse as ip:port (not something a TCP dial |
| -// passes) is let through. |
| -func refuseLinkLocalUpstream(network, address string, _ syscall.RawConn) error { |
| - ap, err := netip.ParseAddrPort(address) |
| - if err != nil { |
| - return nil |
| - } |
| - ip := ap.Addr().WithZone("").Unmap() |
| - for _, p := range linkLocalUpstreams { |
| - if p.Contains(ip) { |
| - return fmt.Errorf("%w: %s %s", errLinkLocalUpstream, network, address) |
| - } |
| - } |
| - return nil |
| -} |
| + "github.com/carlosframework/platform/internal/upstreamguard" |
| +) |
| // upstreamDialer is the dialer for a TCP upstream when no test dialer is set |
| // (hold.dialer nil, as in production): the plain net.Dialer the transports |
| -// used before, plus the link-local refusal. tcpProxy, multiProxy and the |
| -// prober use it; unix sockets, backhaul hops and tunnels do not. |
| +// used before, behind upstreamguard, which refuses link-local and IMDS |
| +// addresses after resolution and before connect. tcpProxy, multiProxy and |
| +// the prober use it; unix sockets, backhaul hops and tunnels do not. |
| func upstreamDialer() *net.Dialer { |
| - return &net.Dialer{Control: refuseLinkLocalUpstream} |
| + return upstreamguard.Dialer(net.Dialer{}) |
| } |
diff --git a/internal/edge/upstreamdial_test.go b/internal/edge/upstreamdial_test.go| index accf06d5c..4c2d367b2 100644 |
| --- a/internal/edge/upstreamdial_test.go |
| +++ b/internal/edge/upstreamdial_test.go |
| @@ -9,33 +9,10 @@ import ( |
| "strings" |
| "testing" |
| "time" |
| -) |
| -// TestRefuseLinkLocalUpstream is the Control hook's table: link-local |
| -// (IPv4 and IPv6, mapped or not) and the AWS IMDS IPv6 address are refused; |
| -// loopback and private addresses, which real upstreams use, are not. |
| -func TestRefuseLinkLocalUpstream(t *testing.T) { |
| - for _, tc := range []struct { |
| - address string |
| - refused bool |
| - }{ |
| - {"169.254.169.254:80", true}, |
| - {"[::ffff:169.254.169.254]:80", true}, |
| - {"169.254.0.1:8080", true}, |
| - {"[fe80::1]:80", true}, |
| - {"[fe80::1%eth0]:80", true}, |
| - {"[fd00:ec2::254]:80", true}, |
| - {"127.0.0.1:80", false}, |
| - {"10.0.0.5:80", false}, |
| - {"[::1]:80", false}, |
| - {"[fd00:ec2::253]:80", false}, |
| - } { |
| - err := refuseLinkLocalUpstream("tcp", tc.address, nil) |
| - if got := errors.Is(err, errLinkLocalUpstream); got != tc.refused { |
| - t.Errorf("refuseLinkLocalUpstream(%q) = %v, want refused=%v", tc.address, err, tc.refused) |
| - } |
| - } |
| -} |
| + "github.com/carlosframework/platform/internal/upstreamguard" |
| + "github.com/carlosframework/platform/internal/upstreamguard/guardtest" |
| +) |
| // proxyErr serves one request through p and returns the status and the |
| // error p's ErrorHandler was handed (nil if it was not called), keeping the |
| @@ -55,19 +32,19 @@ func proxyErr(t *testing.T, p *httputil.ReverseProxy) (int, error) { |
| // TestTCPProxyRefusesNameResolvingToIMDS: an upstream NAME is checked after |
| // resolution, at the address the dialer is about to connect to. imds.test |
| -// resolves (through a fake DNS zone, cnameResolver) to 169.254.169.254; the |
| +// resolves (through a fake DNS zone, guardtest.Resolver) to 169.254.169.254; the |
| // Control hook runs before connect, so nothing is connected and the request |
| // answers 502 with the refusal as its cause. |
| func TestTCPProxyRefusesNameResolvingToIMDS(t *testing.T) { |
| d := upstreamDialer() |
| - d.Resolver = cnameResolver(t, []string{"imds.test"}, []string{"169.254.169.254"}) |
| + d.Resolver = guardtest.Resolver(t, "imds.test", "169.254.169.254") |
| p := tcpProxy("imds.test:80", localHold{dialer: d.DialContext}) |
| code, err := proxyErr(t, p) |
| if code != http.StatusBadGateway { |
| t.Fatalf("status = %d, want 502", code) |
| } |
| - if !errors.Is(err, errLinkLocalUpstream) { |
| - t.Fatalf("proxy error = %v, want one wrapping errLinkLocalUpstream", err) |
| + if !errors.Is(err, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("proxy error = %v, want one wrapping upstreamguard.ErrLinkLocal", err) |
| } |
| } |
| @@ -89,8 +66,8 @@ func TestUpstreamDialSitesRefuseLinkLocal(t *testing.T) { |
| t.Fatal("tcpProxy transport has no DialContext: it would dial with the stdlib's unguarded default") |
| } |
| code, err := proxyErr(t, p) |
| - if code != http.StatusBadGateway || !errors.Is(err, errLinkLocalUpstream) { |
| - t.Fatalf("status = %d, err = %v; want 502 wrapping errLinkLocalUpstream", code, err) |
| + if code != http.StatusBadGateway || !errors.Is(err, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("status = %d, err = %v; want 502 wrapping upstreamguard.ErrLinkLocal", code, err) |
| } |
| }) |
| @@ -106,8 +83,8 @@ func TestUpstreamDialSitesRefuseLinkLocal(t *testing.T) { |
| if conn != nil { |
| conn.Close() |
| } |
| - if !errors.Is(err, errLinkLocalUpstream) { |
| - t.Fatalf("probe dial err = %v, want errLinkLocalUpstream", err) |
| + if !errors.Is(err, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("probe dial err = %v, want upstreamguard.ErrLinkLocal", err) |
| } |
| }) |
| @@ -130,8 +107,8 @@ func TestUpstreamDialSitesRefuseLinkLocal(t *testing.T) { |
| if conn != nil { |
| conn.Close() |
| } |
| - if !errors.Is(err, errNoLiveUpstream) || !strings.Contains(err.Error(), errLinkLocalUpstream.Error()) { |
| - t.Fatalf("multi dial err = %v, want errNoLiveUpstream naming errLinkLocalUpstream", err) |
| + if !errors.Is(err, errNoLiveUpstream) || !strings.Contains(err.Error(), upstreamguard.ErrLinkLocal.Error()) { |
| + t.Fatalf("multi dial err = %v, want errNoLiveUpstream naming upstreamguard.ErrLinkLocal", err) |
| } |
| }) |
diff --git a/internal/host/unitsettle.go b/internal/host/unitsettle.go| index 54767a4b1..cf82a9793 100644 |
| --- a/internal/host/unitsettle.go |
| +++ b/internal/host/unitsettle.go |
| @@ -29,6 +29,7 @@ import ( |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/upstreamguard" |
| ) |
| type unitProps struct { |
| @@ -296,6 +297,14 @@ func unitSettleTimeout(getenv func(string) string) time.Duration { |
| // one, a connect. nil when the route has no upstream: settle then requires |
| // the unit to stay active for its Hold. |
| func routeReady(rt registry.Route, timeout time.Duration) func() error { |
| + return routeReadyVia(net.Dialer{}, rt, timeout) |
| +} |
| + |
| +// routeReadyVia is routeReady dialing with base (a test sets its Resolver) |
| +// behind upstreamguard: a TCP upstream is route-supplied, so both the |
| +// connect and the probe refuse a link-local or IMDS destination after |
| +// resolution and before connect. A unix socket path passes the guard. |
| +func routeReadyVia(base net.Dialer, rt registry.Route, timeout time.Duration) func() error { |
| network, address := "unix", rt.Socket |
| if address == "" { |
| network, address = "tcp", rt.Addr |
| @@ -304,8 +313,11 @@ func routeReady(rt registry.Route, timeout time.Duration) func() error { |
| return nil |
| } |
| if rt.Health == "" { |
| + d := base |
| + d.Timeout = timeout |
| + dialer := upstreamguard.Dialer(d) |
| return func() error { |
| - c, err := net.DialTimeout(network, address, timeout) |
| + c, err := dialer.Dial(network, address) |
| if err != nil { |
| return fmt.Errorf("connect %s: %w", address, err) |
| } |
| @@ -321,10 +333,10 @@ func routeReady(rt registry.Route, timeout time.Duration) func() error { |
| if hostHdr == "" { |
| hostHdr = rt.Host |
| } |
| + dialer := upstreamguard.Dialer(base) |
| client := &http.Client{Timeout: timeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Transport: &http.Transport{ |
| DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| - var d net.Dialer |
| - return d.DialContext(ctx, network, address) |
| + return dialer.DialContext(ctx, network, address) |
| }, |
| }} |
| return func() error { |
| @@ -335,7 +347,7 @@ func routeReady(rt registry.Route, timeout time.Duration) func() error { |
| req.Host = hostHdr |
| resp, err := client.Do(req) |
| if err != nil { |
| - return fmt.Errorf("dial: %v", err) |
| + return fmt.Errorf("dial: %w", err) |
| } |
| io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10)) |
| resp.Body.Close() |
diff --git a/internal/host/unitsettle_guard_test.go b/internal/host/unitsettle_guard_test.go| new file mode 100644 |
| index 000000000..55e63cca3 |
| --- /dev/null |
| +++ b/internal/host/unitsettle_guard_test.go |
| @@ -0,0 +1,61 @@ |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/upstreamguard" |
| + "github.com/carlosframework/platform/internal/upstreamguard/guardtest" |
| +) |
| + |
| +// TestRouteReadyRefusesLinkLocal: the host's readiness checks dial a |
| +// route's TCP upstream (a bare connect without a health probe, an HTTP GET |
| +// with one), so both go through upstreamguard. A name resolving to |
| +// 169.254.169.254 is refused after resolution, and proofRouteReady, which |
| +// checks each of a route's Addrs, refuses an IMDS literal among them. |
| +func TestRouteReadyRefusesLinkLocal(t *testing.T) { |
| + base := net.Dialer{Resolver: guardtest.Resolver(t, "imds.test", "169.254.169.254")} |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { ln.Close() }) |
| + probe := `{"path":"/healthz","status":200}` |
| + for _, tc := range []struct { |
| + name string |
| + ready func() error |
| + }{ |
| + {"connect, name resolving to IMDS", routeReadyVia(base, registry.Route{Host: "x", Addr: "imds.test:80"}, time.Second)}, |
| + {"probe, name resolving to IMDS", routeReadyVia(base, registry.Route{Host: "x", Addr: "imds.test:80", Health: probe}, time.Second)}, |
| + {"connect, IMDS literal, production dialer", routeReady(registry.Route{Host: "x", Addr: "169.254.169.254:80"}, time.Second)}, |
| + {"probe, IMDS literal, production dialer", routeReady(registry.Route{Host: "x", Addr: "169.254.169.254:80", Health: probe}, time.Second)}, |
| + {"proof, IMDS among Addrs", proofRouteReady(registry.Route{Host: "x", Addrs: ln.Addr().String() + ",169.254.169.254:80"}, time.Second)}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + if err := tc.ready(); !errors.Is(err, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("ready = %v, want ErrLinkLocal", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRouteReadyLoopbackStillWorks(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })) |
| + t.Cleanup(srv.Close) |
| + addr := strings.TrimPrefix(srv.URL, "http://") |
| + for _, rt := range []registry.Route{ |
| + {Host: "x", Addr: addr}, |
| + {Host: "x", Addr: addr, Health: `{"path":"/healthz","status":200}`}, |
| + {Host: "x", Addrs: addr + "," + addr}, |
| + } { |
| + if err := proofRouteReady(rt, time.Second)(); err != nil { |
| + t.Fatalf("ready(%+v) = %v, want nil", rt, err) |
| + } |
| + } |
| +} |
diff --git a/internal/upstreamguard/guardtest/resolver.go b/internal/upstreamguard/guardtest/resolver.go| new file mode 100644 |
| index 000000000..81a24d2fc |
| --- /dev/null |
| +++ b/internal/upstreamguard/guardtest/resolver.go |
| @@ -0,0 +1,69 @@ |
| +// Package guardtest is a test helper for upstreamguard's callers: a |
| +// net.Resolver backed by a one-name fake DNS server on loopback, so a test |
| +// can make a hostname resolve to 169.254.169.254 without touching real DNS |
| +// or connecting there. Only tests import it. |
| +package guardtest |
| + |
| +import ( |
| + "context" |
| + "net" |
| + "net/netip" |
| + "strings" |
| + "testing" |
| + |
| + "golang.org/x/net/dns/dnsmessage" |
| +) |
| + |
| +// Resolver answers A queries for name with ip (an IPv4 literal), AAAA |
| +// queries for name with nothing, and anything else with NXDOMAIN. Pass it |
| +// as a net.Dialer's Resolver. |
| +func Resolver(t testing.TB, name, ip string) *net.Resolver { |
| + t.Helper() |
| + addr := netip.MustParseAddr(ip).As4() |
| + fq := strings.ToLower(strings.TrimSuffix(name, ".")) + "." |
| + pc, err := net.ListenPacket("udp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { pc.Close() }) |
| + go func() { |
| + buf := make([]byte, 1500) |
| + for { |
| + n, from, err := pc.ReadFrom(buf) |
| + if err != nil { |
| + return |
| + } |
| + var p dnsmessage.Parser |
| + h, err := p.Start(buf[:n]) |
| + if err != nil { |
| + continue |
| + } |
| + q, err := p.Question() |
| + if err != nil { |
| + continue |
| + } |
| + hdr := dnsmessage.Header{ID: h.ID, Response: true, Authoritative: true} |
| + known := strings.ToLower(q.Name.String()) == fq |
| + if !known { |
| + hdr.RCode = dnsmessage.RCodeNameError |
| + } |
| + b := dnsmessage.NewBuilder(nil, hdr) |
| + _ = b.StartQuestions() |
| + _ = b.Question(q) |
| + if known && q.Type == dnsmessage.TypeA { |
| + _ = b.StartAnswers() |
| + _ = b.AResource(dnsmessage.ResourceHeader{Name: q.Name, Class: dnsmessage.ClassINET, TTL: 60}, |
| + dnsmessage.AResource{A: addr}) |
| + } |
| + msg, err := b.Finish() |
| + if err != nil { |
| + continue |
| + } |
| + _, _ = pc.WriteTo(msg, from) |
| + } |
| + }() |
| + return &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + var d net.Dialer |
| + return d.DialContext(ctx, "udp", pc.LocalAddr().String()) |
| + }} |
| +} |
diff --git a/internal/upstreamguard/upstreamguard.go b/internal/upstreamguard/upstreamguard.go| new file mode 100644 |
| index 000000000..4b5eb932d |
| --- /dev/null |
| +++ b/internal/upstreamguard/upstreamguard.go |
| @@ -0,0 +1,76 @@ |
| +// Package upstreamguard refuses connections to link-local addresses and the |
| +// AWS instance metadata service. Every dial to a route's TCP upstream (the |
| +// edge's proxies and prober, the activator's wake health check, the host's |
| +// readiness checks) goes through Dialer, so an upstream of 169.254.169.254, |
| +// or a name resolving to it, is never connected. It imports only the |
| +// standard library. |
| +package upstreamguard |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net" |
| + "net/netip" |
| + "syscall" |
| +) |
| + |
| +// ErrLinkLocal is the dial error for a refused destination. |
| +var ErrLinkLocal = errors.New("upstreamguard: refusing a link-local upstream address") |
| + |
| +// refused are the destinations no upstream may have: 169.254.0.0/16 and |
| +// fe80::/10 (link-local, IMDS's IPv4 address among them) and fd00:ec2::254, |
| +// IMDS's IPv6 address, which is not link-local. |
| +var refused = []netip.Prefix{ |
| + netip.MustParsePrefix("169.254.0.0/16"), |
| + netip.MustParsePrefix("fe80::/10"), |
| + netip.MustParsePrefix("fd00:ec2::254/128"), |
| +} |
| + |
| +// Control is a net.Dialer Control hook. The dialer calls it with the |
| +// address it has already resolved, after creating the socket and before |
| +// connecting it, so a refusal means nothing was connected, and a name is |
| +// judged by what it resolved to rather than how it is spelled. IPv4-mapped |
| +// IPv6 is unmapped first. An address that is not ip:port (a unix socket |
| +// path) is let through. |
| +func Control(network, address string, _ syscall.RawConn) error { |
| + ap, err := netip.ParseAddrPort(address) |
| + if err != nil { |
| + return nil |
| + } |
| + ip := ap.Addr().WithZone("").Unmap() |
| + for _, p := range refused { |
| + if p.Contains(ip) { |
| + return fmt.Errorf("%w: %s %s", ErrLinkLocal, network, address) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// Dialer returns a copy of base with Control in front of base's own hook: |
| +// Timeout, KeepAlive, Resolver and the rest are kept. A base ControlContext |
| +// (which net.Dialer prefers over Control) is chained the same way. |
| +func Dialer(base net.Dialer) *net.Dialer { |
| + d := base |
| + switch { |
| + case base.ControlContext != nil: |
| + next := base.ControlContext |
| + d.ControlContext = func(ctx context.Context, network, address string, c syscall.RawConn) error { |
| + if err := Control(network, address, c); err != nil { |
| + return err |
| + } |
| + return next(ctx, network, address, c) |
| + } |
| + case base.Control != nil: |
| + next := base.Control |
| + d.Control = func(network, address string, c syscall.RawConn) error { |
| + if err := Control(network, address, c); err != nil { |
| + return err |
| + } |
| + return next(network, address, c) |
| + } |
| + default: |
| + d.Control = Control |
| + } |
| + return &d |
| +} |
diff --git a/internal/upstreamguard/upstreamguard_test.go b/internal/upstreamguard/upstreamguard_test.go| new file mode 100644 |
| index 000000000..d2d8f76e0 |
| --- /dev/null |
| +++ b/internal/upstreamguard/upstreamguard_test.go |
| @@ -0,0 +1,89 @@ |
| +package upstreamguard_test |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/upstreamguard" |
| + "github.com/carlosframework/platform/internal/upstreamguard/guardtest" |
| +) |
| + |
| +// TestControl is the hook's table: link-local (IPv4 and IPv6, mapped or |
| +// zoned) and the AWS IMDS IPv6 address are refused; loopback and private |
| +// addresses, which real upstreams use, and unix paths are not. |
| +func TestControl(t *testing.T) { |
| + for _, tc := range []struct { |
| + network, address string |
| + refused bool |
| + }{ |
| + {"tcp4", "169.254.169.254:80", true}, |
| + {"tcp6", "[::ffff:169.254.169.254]:80", true}, |
| + {"tcp4", "169.254.0.1:8080", true}, |
| + {"tcp6", "[fe80::1]:80", true}, |
| + {"tcp6", "[fe80::1%eth0]:80", true}, |
| + {"tcp6", "[fd00:ec2::254]:80", true}, |
| + {"tcp4", "127.0.0.1:80", false}, |
| + {"tcp4", "10.0.0.5:80", false}, |
| + {"tcp6", "[::1]:80", false}, |
| + {"tcp6", "[fd00:ec2::253]:80", false}, |
| + {"unix", "/run/carlos/app.sock", false}, |
| + } { |
| + err := upstreamguard.Control(tc.network, tc.address, nil) |
| + if got := errors.Is(err, upstreamguard.ErrLinkLocal); got != tc.refused { |
| + t.Errorf("Control(%q, %q) = %v, want refused=%v", tc.network, tc.address, err, tc.refused) |
| + } |
| + } |
| +} |
| + |
| +// TestDialerKeepsBaseAndChainsControl: Dialer keeps the caller's settings |
| +// and runs the caller's own Control (and ControlContext) after the guard. |
| +func TestDialerKeepsBaseAndChainsControl(t *testing.T) { |
| + r := guardtest.Resolver(t, "imds.test", "169.254.169.254") |
| + var ran int |
| + base := net.Dialer{Timeout: 7 * time.Second, KeepAlive: 11 * time.Second, Resolver: r, |
| + Control: func(string, string, syscall.RawConn) error { ran++; return nil }} |
| + d := upstreamguard.Dialer(base) |
| + if d.Timeout != base.Timeout || d.KeepAlive != base.KeepAlive || d.Resolver != r { |
| + t.Fatalf("Dialer lost the base settings: %+v", d) |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| + defer cancel() |
| + if _, err := d.DialContext(ctx, "tcp", "imds.test:80"); !errors.Is(err, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("dial imds.test = %v, want ErrLinkLocal after resolution", err) |
| + } |
| + if ran != 0 { |
| + t.Fatalf("base Control ran %d times on a refused address, want 0", ran) |
| + } |
| + |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ln.Close() |
| + c, err := d.DialContext(ctx, "tcp", ln.Addr().String()) |
| + if err != nil { |
| + t.Fatalf("dial loopback: %v", err) |
| + } |
| + c.Close() |
| + if ran != 1 { |
| + t.Fatalf("base Control ran %d times on loopback, want 1", ran) |
| + } |
| + |
| + var ranCtx int |
| + dc := upstreamguard.Dialer(net.Dialer{ControlContext: func(context.Context, string, string, syscall.RawConn) error { ranCtx++; return nil }}) |
| + if _, err := dc.DialContext(ctx, "tcp", "169.254.169.254:80"); !errors.Is(err, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("dial with a base ControlContext = %v, want ErrLinkLocal", err) |
| + } |
| + if c, err := dc.DialContext(ctx, "tcp", ln.Addr().String()); err != nil { |
| + t.Fatalf("dial loopback with a base ControlContext: %v", err) |
| + } else { |
| + c.Close() |
| + } |
| + if ranCtx != 1 { |
| + t.Fatalf("base ControlContext ran %d times, want 1", ranCtx) |
| + } |
| +} |