edge: keep :80 redirects on-host; refuse link-local upstream dials
The :80 fallback built Location from the raw RequestURI, so a rootless request-target (GET x:@evil.example/p) redirected to another host. It now redirects anything unrooted to "/" (twin of console.redirectTarget). New internal/upstreamguard: a net.Dialer Control hook that refuses 169.254/16, fe80::/10 and fd00:ec2::254 after resolution. Used by the edge proxies and prober, the activator wake health check and the host readiness probes, so a route hostname resolving to IMDS is never dialled. Hostname Addr stays allowed (production uses it). From the 2026-11-16 security review (discussion 1096). Reviewed by Astra (2 rounds) and Fable; census approved on #280. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from sec-edge-redirect-linklocal into main.
15 files changed,
+690
−24
docs/superpowers/notes/census-proposal-sec-edge-redirect-linklocal.md+19 −0internal/activator/backend_unit.go+20 −1internal/activator/healthaddr_guard_test.go+49 −0internal/edge/edge.go+16 −8internal/edge/http_fallback_redirect_test.go+85 −0internal/edge/prober.go+10 −4internal/edge/upstreamdial.go+16 −0internal/edge/upstreamdial_test.go+143 −0internal/host/unitsettle.go+28 −11internal/host/unitsettle_guard_test.go+62 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-sec-edge-redirect-linklocal.tsv+7 −0internal/upstreamguard/guardtest/resolver.go+69 −0internal/upstreamguard/upstreamguard.go+76 −0internal/upstreamguard/upstreamguard_test.go+89 −0
CI passed — run details
diff --git a/docs/superpowers/notes/census-proposal-sec-edge-redirect-linklocal.md b/docs/superpowers/notes/census-proposal-sec-edge-redirect-linklocal.md| new file mode 100644 |
| index 000000000..336857b17 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-sec-edge-redirect-linklocal.md |
| @@ -0,0 +1,19 @@ |
| +# Census approval: sec-edge-redirect-linklocal |
| + |
| +Ruling `census-ruling-sec-edge-redirect-linklocal`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/host/unitsettle.go` `routeReady` | body | unchanged (5) | same reads (Socket, Addr, Health, Host); the connect and the HTTP probe move into readyConnect/readyProbe, which dial through upstreamguard and so refuse a link-local or IMDS upstream after resolution, before connect; unix sockets, timeout and probe unchanged; no read added | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/edge`, `internal/host`, `internal/upstreamguard`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/host/unitsettle.go` `routeReady`: authority, task B3,J1,J4. Basis: root-route |
| + |
| +Seal: `4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b` → `4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-sec-edge-redirect-linklocal.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
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/edge.go b/internal/edge/edge.go| index 8169239ed..6eeba4de1 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -3864,7 +3864,14 @@ func (e *Edge) httpFallbackHandler() http.Handler { |
| http.Error(w, "Use HTTPS", http.StatusBadRequest) |
| return |
| } |
| - http.Redirect(w, r, "https://"+host+r.URL.RequestURI(), http.StatusFound) |
| + // Only a rooted path may follow the host: a rootless target |
| + // ("x:@evil.example/p", "*") would otherwise splice itself onto the |
| + // authority. Twin of console.redirectTarget (console imports edge). |
| + uri := r.URL.RequestURI() |
| + if !strings.HasPrefix(uri, "/") { |
| + uri = "/" |
| + } |
| + http.Redirect(w, r, "https://"+host+uri, http.StatusFound) |
| }) |
| } |
| @@ -4002,18 +4009,19 @@ func unixProxy(socketPath string) *httputil.ReverseProxy { |
| // A loopback upstream is this box's own process, so a refused dial there is |
| // a restart in progress: the dial is retried for hold.dial (one deadline |
| // fixed per dial) instead of 502ing at once. hold.dial <= 0, or a remote |
| -// addr, keeps the stock dialer (hold.dialer is nil in production). |
| +// addr, dials once. Either way the dial is upstreamDialer's (hold.dialer is |
| +// nil in production), which refuses link-local and IMDS addresses. |
| func tcpProxy(addr string, hold localHold) *httputil.ReverseProxy { |
| + dial := hold.dialer |
| + if dial == nil { |
| + dial = upstreamDialer().DialContext |
| + } |
| tr := &http.Transport{ |
| MaxIdleConns: 32, |
| IdleConnTimeout: 90 * time.Second, |
| - DialContext: hold.dialer, |
| + DialContext: dial, |
| } |
| if hold.dial > 0 && isLocalUpstream(addr) { |
| - dial := hold.dialer |
| - if dial == nil { |
| - dial = (&net.Dialer{}).DialContext |
| - } |
| tr.DialContext = func(ctx context.Context, network, a string) (net.Conn, error) { |
| return retryLocalDial(ctx, time.Now().Add(hold.dial), func(actx context.Context) (net.Conn, error) { |
| return dial(actx, network, a) |
| @@ -4108,7 +4116,7 @@ func multiProxy(host string, p *proberSet, hold localHold) *httputil.ReverseProx |
| var cursor atomic.Uint64 |
| dial := hold.dialer |
| if dial == nil { |
| - dial = (&net.Dialer{}).DialContext |
| + dial = upstreamDialer().DialContext // refuses link-local and IMDS |
| } |
| return &httputil.ReverseProxy{ |
| Rewrite: func(pr *httputil.ProxyRequest) { |
diff --git a/internal/edge/http_fallback_redirect_test.go b/internal/edge/http_fallback_redirect_test.go| new file mode 100644 |
| index 000000000..bce6fcf27 |
| --- /dev/null |
| +++ b/internal/edge/http_fallback_redirect_test.go |
| @@ -0,0 +1,85 @@ |
| +package edge |
| + |
| +import ( |
| + "bufio" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// TestHTTPFallbackRedirectRootlessTarget pins the :80 redirect to its own |
| +// authority. The redirect is "https://" + host + the request-target, and a |
| +// request-target that does not start with "/" (a rootless "x:@evil.example/p" |
| +// keeps "@evil.example/p" as its opaque part; "*" stays "*") would splice |
| +// itself onto the host and turn the Location into userinfo@another-host. The |
| +// rule is console.redirectTarget's: anything not rooted becomes "/". |
| +// |
| +// The requests are parsed off the wire with http.ReadRequest, as the :80 |
| +// server parses them, because httptest.NewRequest cannot express a rootless |
| +// target. |
| +func TestHTTPFallbackRedirectRootlessTarget(t *testing.T) { |
| + const host = "shop.example.com" |
| + backend, _ := hostEchoBackend(t, "primary") |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{ |
| + Host: host, Kind: "service", |
| + Addr: backend.Listener.Addr().String(), Status: "ready", |
| + }); err != nil { |
| + t.Fatalf("upsert: %v", err) |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatalf("New: %v", err) |
| + } |
| + h := e.httpFallbackHandler() |
| + |
| + serve := func(t *testing.T, requestLine string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + req, err := http.ReadRequest(bufio.NewReader(strings.NewReader( |
| + requestLine + "\r\nHost: " + host + "\r\n\r\n"))) |
| + if err != nil { |
| + t.Fatalf("ReadRequest(%q): %v", requestLine, err) |
| + } |
| + rec := httptest.NewRecorder() |
| + h.ServeHTTP(rec, req) |
| + return rec |
| + } |
| + |
| + for _, tc := range []struct { |
| + name, requestLine, want string |
| + }{ |
| + {"rootless", "GET x:@evil.example/p HTTP/1.1", "https://" + host + "/"}, |
| + {"asterisk", "GET * HTTP/1.1", "https://" + host + "/"}, |
| + // The absolute form's authority replaces the Host header (RFC 9112 |
| + // §3.2.2, and net/http does the same), so naming this box's own host |
| + // there is an ordinary redirect. |
| + {"absolute form, own host", "GET http://" + host + "/p?q=1 HTTP/1.1", "https://" + host + "/p?q=1"}, |
| + {"origin form", "GET /a/b?c=1 HTTP/1.1", "https://" + host + "/a/b?c=1"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + rec := serve(t, tc.requestLine) |
| + if rec.Code != http.StatusFound { |
| + t.Fatalf("status = %d, want 302", rec.Code) |
| + } |
| + if loc := rec.Header().Get("Location"); loc != tc.want { |
| + t.Fatalf("Location = %q, want %q", loc, tc.want) |
| + } |
| + }) |
| + } |
| + |
| + // An absolute-form target naming a host this box does not serve is that |
| + // host's request, not shop's: it gets unknownHost (404, no fallback URL |
| + // configured), never a Location pointing at the foreign authority. |
| + t.Run("absolute form, foreign host", func(t *testing.T) { |
| + rec := serve(t, "GET http://evil.example/p HTTP/1.1") |
| + if rec.Code != http.StatusNotFound { |
| + t.Fatalf("status = %d, want 404 (unknownHost)", rec.Code) |
| + } |
| + if loc := rec.Header().Get("Location"); loc != "" { |
| + t.Fatalf("Location = %q, want none", loc) |
| + } |
| + }) |
| +} |
diff --git a/internal/edge/prober.go b/internal/edge/prober.go| index 3463a34fa..4dc10dd7e 100644 |
| --- a/internal/edge/prober.go |
| +++ b/internal/edge/prober.go |
| @@ -128,13 +128,19 @@ type proberSet struct { |
| // newProberSet builds the set with hold.probe as the probe timeout (T in |
| // the readmission formula, spec §3), and hold.dialer, when set, as the |
| -// probes' dialer, so a test's instrumented dialer sees the probes too. A |
| -// non-positive probe falls back to probeTimeout: an unbounded probe would |
| -// stall every tick behind one black-holed upstream. |
| +// probes' dialer, so a test's instrumented dialer sees the probes too; |
| +// unset (production), the probes dial with upstreamDialer, which refuses |
| +// link-local and IMDS addresses. A non-positive probe falls back to |
| +// probeTimeout: an unbounded probe would stall every tick behind one |
| +// black-holed upstream. |
| func newProberSet(hold localHold) *proberSet { |
| if hold.probe <= 0 { |
| hold.probe = probeTimeout |
| } |
| + dial := hold.dialer |
| + if dial == nil { |
| + dial = upstreamDialer().DialContext |
| + } |
| return &proberSet{ |
| hosts: make(map[string]*hostProber), |
| hold: hold, |
| @@ -153,7 +159,7 @@ func newProberSet(hold localHold) *proberSet { |
| MaxIdleConnsPerHost: 1, |
| IdleConnTimeout: 90 * time.Second, |
| ResponseHeaderTimeout: hold.probe, |
| - DialContext: hold.dialer, // nil: the default dialer |
| + DialContext: dial, |
| }, |
| }, |
| } |
diff --git a/internal/edge/upstreamdial.go b/internal/edge/upstreamdial.go| new file mode 100644 |
| index 000000000..28857146e |
| --- /dev/null |
| +++ b/internal/edge/upstreamdial.go |
| @@ -0,0 +1,16 @@ |
| +package edge |
| + |
| +import ( |
| + "net" |
| + |
| + "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, 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 upstreamguard.Dialer(net.Dialer{}) |
| +} |
diff --git a/internal/edge/upstreamdial_test.go b/internal/edge/upstreamdial_test.go| new file mode 100644 |
| index 000000000..4c2d367b2 |
| --- /dev/null |
| +++ b/internal/edge/upstreamdial_test.go |
| @@ -0,0 +1,143 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/http/httputil" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "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 |
| +// production ErrorHandler's answer. |
| +func proxyErr(t *testing.T, p *httputil.ReverseProxy) (int, error) { |
| + t.Helper() |
| + var got error |
| + orig := p.ErrorHandler |
| + p.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { |
| + got = err |
| + orig(w, r, err) |
| + } |
| + rec := httptest.NewRecorder() |
| + p.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://shop.example.com/", nil)) |
| + return rec.Code, got |
| +} |
| + |
| +// 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, 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 = 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, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("proxy error = %v, want one wrapping upstreamguard.ErrLinkLocal", err) |
| + } |
| +} |
| + |
| +// TestUpstreamDialSitesRefuseLinkLocal checks the production wiring: with |
| +// hold.dialer nil, as New leaves it, each of the three upstream dial sites |
| +// (tcpProxy, multiProxy, the prober's transport) dials through the guarded |
| +// dialer rather than the stdlib's default. Each nil check comes before any |
| +// dial, so a missing guard fails the test without connecting anywhere. |
| +func TestUpstreamDialSitesRefuseLinkLocal(t *testing.T) { |
| + hold := defaultLocalHold() |
| + if hold.dialer != nil { |
| + t.Fatal("defaultLocalHold has a dialer; this test is about the nil (production) path") |
| + } |
| + |
| + t.Run("tcpProxy", func(t *testing.T) { |
| + p := tcpProxy("169.254.169.254:80", hold) |
| + tr, ok := p.Transport.(*http.Transport) |
| + if !ok || tr.DialContext == nil { |
| + 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, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("status = %d, err = %v; want 502 wrapping upstreamguard.ErrLinkLocal", code, err) |
| + } |
| + }) |
| + |
| + t.Run("prober", func(t *testing.T) { |
| + ps := newProberSet(hold) |
| + tr, ok := ps.client.Transport.(*http.Transport) |
| + if !ok || tr.DialContext == nil { |
| + t.Fatal("prober transport has no DialContext: it would dial with the stdlib's unguarded default") |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| + defer cancel() |
| + conn, err := tr.DialContext(ctx, "tcp", "169.254.169.254:80") |
| + if conn != nil { |
| + conn.Close() |
| + } |
| + if !errors.Is(err, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("probe dial err = %v, want upstreamguard.ErrLinkLocal", err) |
| + } |
| + }) |
| + |
| + // multiProxy's fallback dialer is a closure variable the test cannot |
| + // inspect, so its upstream is fe80::1 with no zone: unguarded, the kernel |
| + // refuses that connect locally (no interface to send on); guarded, the |
| + // Control hook refuses it first. Either way nothing leaves the box. |
| + t.Run("multiProxy", func(t *testing.T) { |
| + const host = "ha.example.com" |
| + ps := newProberSet(hold) |
| + defer ps.Stop() |
| + ps.Sync(map[string]probeSpec{host: {Host: host, Addrs: []string{"[fe80::1]:80"}, Health: frozenHealth()}}) |
| + tr, ok := multiProxy(host, ps, hold).Transport.(*http.Transport) |
| + if !ok { |
| + t.Fatal("multiProxy transport is not an *http.Transport") |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| + defer cancel() |
| + conn, err := tr.DialContext(ctx, "tcp", multiDialHost) |
| + if conn != nil { |
| + conn.Close() |
| + } |
| + if !errors.Is(err, errNoLiveUpstream) || !strings.Contains(err.Error(), upstreamguard.ErrLinkLocal.Error()) { |
| + t.Fatalf("multi dial err = %v, want errNoLiveUpstream naming upstreamguard.ErrLinkLocal", err) |
| + } |
| + }) |
| + |
| + // The guard must not cost a real upstream anything: loopback, through |
| + // tcpProxy's local-hold path and through the prober. |
| + t.Run("loopback allowed", func(t *testing.T) { |
| + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusOK) |
| + })) |
| + defer backend.Close() |
| + addr := backend.Listener.Addr().String() |
| + |
| + p := tcpProxy(addr, hold) |
| + code, err := proxyErr(t, p) |
| + if code != http.StatusOK || err != nil { |
| + t.Fatalf("tcpProxy to %s: status = %d, err = %v; want 200", addr, code, err) |
| + } |
| + |
| + ps := newProberSet(hold) |
| + tr := ps.client.Transport.(*http.Transport) |
| + if tr.DialContext == nil { |
| + t.Fatal("prober transport has no DialContext") |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| + defer cancel() |
| + conn, err := tr.DialContext(ctx, "tcp", addr) |
| + if err != nil { |
| + t.Fatalf("probe dial %s: %v", addr, err) |
| + } |
| + conn.Close() |
| + }) |
| +} |
diff --git a/internal/host/unitsettle.go b/internal/host/unitsettle.go| index 54767a4b1..6dfe95d79 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 { |
| @@ -294,7 +295,8 @@ func unitSettleTimeout(getenv func(string) string) time.Duration { |
| // routeReady is the readiness check for rt's effective upstream (spec §2.4): |
| // Socket wins over Addr. With a configured probe it is an HTTP GET; without |
| // one, a connect. nil when the route has no upstream: settle then requires |
| -// the unit to stay active for its Hold. |
| +// the unit to stay active for its Hold. Both dial through upstreamguard |
| +// (readyConnect, readyProbe). |
| func routeReady(rt registry.Route, timeout time.Duration) func() error { |
| network, address := "unix", rt.Socket |
| if address == "" { |
| @@ -304,13 +306,7 @@ func routeReady(rt registry.Route, timeout time.Duration) func() error { |
| return nil |
| } |
| if rt.Health == "" { |
| - return func() error { |
| - c, err := net.DialTimeout(network, address, timeout) |
| - if err != nil { |
| - return fmt.Errorf("connect %s: %w", address, err) |
| - } |
| - return c.Close() |
| - } |
| + return readyConnect(net.Dialer{}, network, address, timeout) |
| } |
| var h provision.Health |
| if err := json.Unmarshal([]byte(rt.Health), &h); err != nil { |
| @@ -321,10 +317,31 @@ func routeReady(rt registry.Route, timeout time.Duration) func() error { |
| if hostHdr == "" { |
| hostHdr = rt.Host |
| } |
| + return readyProbe(net.Dialer{}, network, address, h, hostHdr, timeout) |
| +} |
| + |
| +// readyConnect is routeReady's connect check, dialing with base (a test sets |
| +// its Resolver) behind upstreamguard: a TCP upstream is route-supplied, so a |
| +// link-local or IMDS destination is refused after resolution and before |
| +// connect. A unix socket path passes the guard. |
| +func readyConnect(base net.Dialer, network, address string, timeout time.Duration) func() error { |
| + base.Timeout = timeout |
| + dialer := upstreamguard.Dialer(base) |
| + return func() error { |
| + c, err := dialer.Dial(network, address) |
| + if err != nil { |
| + return fmt.Errorf("connect %s: %w", address, err) |
| + } |
| + return c.Close() |
| + } |
| +} |
| + |
| +// readyProbe is routeReady's HTTP probe, dialing as readyConnect does. |
| +func readyProbe(base net.Dialer, network, address string, h provision.Health, hostHdr string, timeout time.Duration) func() error { |
| + 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 +352,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..dcce93f51 |
| --- /dev/null |
| +++ b/internal/host/unitsettle_guard_test.go |
| @@ -0,0 +1,62 @@ |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "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", readyConnect(base, "tcp", "imds.test:80", time.Second)}, |
| + {"probe, name resolving to IMDS", readyProbe(base, "tcp", "imds.test:80", provision.Health{Path: "/healthz", Status: 200}, "x", 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/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 60fa52cca..cf4ca8783 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -232,3 +232,4 @@ plan14-root-reads-omr-run.tsv f82b5e513d7434e1440c13aa4aa8bc06348745749a21593cf4 |
| plan14-root-reads-fleet-first-reconcile-speed.tsv 9206205b2a3bf27b8b85310f4a44f94ef0c5886d85d6e55dbf2f22e073a8af11 |
| plan14-root-reads-free-storage-250.tsv 9206205b2a3bf27b8b85310f4a44f94ef0c5886d85d6e55dbf2f22e073a8af11 |
| plan14-root-reads-fleet-first-reconcile-speed-4.tsv 4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b |
| +plan14-root-reads-sec-edge-redirect-linklocal.tsv 4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b |
diff --git a/internal/provision/testdata/plan14-root-reads-sec-edge-redirect-linklocal.tsv b/internal/provision/testdata/plan14-root-reads-sec-edge-redirect-linklocal.tsv| new file mode 100644 |
| index 000000000..b45c288e4 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-sec-edge-redirect-linklocal.tsv |
| @@ -0,0 +1,7 @@ |
| +# Census overlay sec-edge-redirect-linklocal, written by census-propose (#369). census-ruling-sec-edge-redirect-linklocal, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-sec-edge-redirect-linklocal.md. |
| +# 1 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +internal/host/unitsettle.go routeReady authority B3,J1,J4 root-route;rev3=census-ruling-sec-edge-redirect-linklocal;basis=same reads (Socket, Addr, Health, Host); the connect and the HTTP probe move into readyConnect/readyProbe, which dial through upstreamguard and so refuse a link-local or IMDS upstream after resolution, before connect; unix sockets, timeout and probe unchanged; no read added registry:Addr@160,registry:Health@211,registry:Health@352,registry:Host@554,registry:Socket@102 28727e6d1982928fec940b8b4be5ff0f70a88cd74818f027b7f0510d9209ddf8 |
| +@coverage internal/activator b638116af5b710dd44ac56956f6cf627d881f87f22ed48de22c057d4efc94ada |
| +@coverage internal/edge 489fb5122e86036adb06ffb77fb8aaa79767d3dbb64458dd718fa5b667945edf |
| +@coverage internal/host 80e3a350373509c6d7d074c2b06512206200a3369a86298d4cdae3ca42eafa1c |
| +@coverage internal/upstreamguard 2da6f647eb21296c5af4af7496adf65340a6cc9f82ab4501ff8f4e92063fc6b9 |
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) |
| + } |
| +} |