| new file mode 100644 |
| index 000000000..8ed2bd7a0 |
| --- /dev/null |
| +++ b/internal/edge/proxyingress_test.go |
| @@ -0,0 +1,755 @@ |
| +package edge |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "encoding/binary" |
| + "errors" |
| + "io" |
| + "log" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/netip" |
| + "os" |
| + "reflect" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hairpin" |
| + "github.com/carlosframework/platform/internal/lbhealth" |
| + "github.com/carlosframework/platform/internal/proxyproto" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +var ppLoopback = []netip.Addr{netip.MustParseAddr("127.0.0.1")} |
| + |
| +// ppv2Proxy is a PPv2 PROXY header for an INET client at src. |
| +func ppv2Proxy(src string) []byte { |
| + ap := netip.MustParseAddrPort(src) |
| + b := append([]byte(proxyproto.Signature), 0x21, 0x11, 0, 12) |
| + s := ap.Addr().As4() |
| + b = append(b, s[:]...) |
| + b = append(b, 10, 0, 0, 1) |
| + b = binary.BigEndian.AppendUint16(b, ap.Port()) |
| + return binary.BigEndian.AppendUint16(b, 443) |
| +} |
| + |
| +// ppv2Local is the header an NLB health check carries: LOCAL, UNSPEC. |
| +func ppv2Local() []byte { |
| + return append([]byte(proxyproto.Signature), 0x20, 0x00, 0, 0) |
| +} |
| + |
| +// proxyOpts shapes a proxyEdge. Nil handlers are production's: the Edge |
| +// itself on :443 and its :80 fallback (health, redirect) on :80. |
| +type proxyOpts struct { |
| + https, challenge http.Handler |
| + hairpin *hairpin.Config |
| + connState func(net.Conn, http.ConnState) |
| +} |
| + |
| +// proxyEdge is the edge's two public servers wired as Serve wires them: |
| +// publicServers, loopback listeners, the hairpin when a fixture is given, |
| +// wrapProxyIngress, connDrain.serve. The edge is armed (or not) by the |
| +// caller before it is built, as Serve arms it before binding. |
| +type proxyEdge struct { |
| + e *Edge |
| + https, http *http.Server |
| + httpsAddr, httpAddr string |
| + pool *x509.CertPool |
| +} |
| + |
| +func newProxyEdge(t *testing.T, e *Edge, o proxyOpts) *proxyEdge { |
| + t.Helper() |
| + cert, pool := loopbackCert(t) |
| + https, challenge := o.https, o.challenge |
| + if https == nil { |
| + https = e |
| + } |
| + if challenge == nil { |
| + challenge = e.httpFallbackHandler() |
| + } |
| + httpsSrv, httpSrv := e.publicServers(https, challenge, &tls.Config{Certificates: []tls.Certificate{cert}}, "", "") |
| + httpsSrv.ConnState, httpSrv.ConnState = o.connState, o.connState |
| + var httpsLn, httpLn net.Listener |
| + var err error |
| + if httpsLn, err = net.Listen("tcp", "127.0.0.1:0"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if httpLn, err = net.Listen("tcp", "127.0.0.1:0"); err != nil { |
| + t.Fatal(err) |
| + } |
| + pe := &proxyEdge{e: e, https: httpsSrv, http: httpSrv, pool: pool, |
| + httpsAddr: httpsLn.Addr().String(), httpAddr: httpLn.Addr().String()} |
| + if o.hairpin != nil { |
| + // Loopback cannot bind 80 and 443; the socket's destination port |
| + // is all the hairpin classifier reads from them. |
| + httpLn = configureHairpin(httpSrv, portAs(httpLn, 80), *o.hairpin) |
| + httpsLn = configureHairpin(httpsSrv, portAs(httpsLn, 443), *o.hairpin) |
| + } |
| + httpsLn, httpLn = e.wrapProxyIngress(httpsSrv, httpSrv, httpsLn, httpLn) |
| + e.conns.serve(httpsSrv, httpSrv) |
| + go func() { _ = httpSrv.Serve(httpLn) }() |
| + go func() { _ = httpsSrv.ServeTLS(httpsLn, "", "") }() |
| + t.Cleanup(func() { |
| + _ = httpsSrv.Close() |
| + _ = httpSrv.Close() |
| + }) |
| + return pe |
| +} |
| + |
| +// portListener reports every accepted socket's local port as port. |
| +type portListener struct { |
| + net.Listener |
| + port int |
| +} |
| + |
| +type portConn struct { |
| + net.Conn |
| + local net.Addr |
| +} |
| + |
| +func (c portConn) LocalAddr() net.Addr { return c.local } |
| + |
| +func portAs(ln net.Listener, port int) net.Listener { return portListener{ln, port} } |
| + |
| +func (l portListener) Accept() (net.Conn, error) { |
| + c, err := l.Listener.Accept() |
| + if err != nil { |
| + return nil, err |
| + } |
| + a := *c.LocalAddr().(*net.TCPAddr) |
| + a.Port = l.port |
| + return portConn{c, &a}, nil |
| +} |
| + |
| +type rawResult struct { |
| + status int |
| + connClose bool |
| + body string |
| +} |
| + |
| +// dial opens a connection to :443 (secure) or :80 and writes prefix. |
| +func (pe *proxyEdge) dial(t *testing.T, secure bool, prefix []byte) net.Conn { |
| + t.Helper() |
| + addr := pe.httpAddr |
| + if secure { |
| + addr = pe.httpsAddr |
| + } |
| + c, err := net.DialTimeout("tcp", addr, 5*time.Second) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { c.Close() }) |
| + _ = c.SetDeadline(time.Now().Add(15 * time.Second)) |
| + if len(prefix) > 0 { |
| + if _, err := c.Write(prefix); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return c |
| +} |
| + |
| +// request sends one HTTP/1.1 request over c (after TLS when secure) and |
| +// reads the whole answer. The request never asks to close, so a |
| +// Connection: close in the answer is the server's own. |
| +func (pe *proxyEdge) request(t *testing.T, c net.Conn, secure bool, method, host, path string) rawResult { |
| + t.Helper() |
| + rw := c |
| + if secure { |
| + rw = tls.Client(c, &tls.Config{RootCAs: pe.pool, ServerName: "127.0.0.1"}) |
| + } |
| + req, err := http.NewRequest(method, "http://"+host+path, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Accept-Encoding", "identity") |
| + if err := req.Write(rw); err != nil { |
| + t.Fatalf("%s %s%s: write: %v", method, host, path, err) |
| + } |
| + resp, err := http.ReadResponse(bufio.NewReader(rw), req) |
| + if err != nil { |
| + t.Fatalf("%s %s%s: read: %v", method, host, path, err) |
| + } |
| + defer resp.Body.Close() |
| + b, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return rawResult{status: resp.StatusCode, connClose: resp.Close, body: string(b)} |
| +} |
| + |
| +// exchange is one request on a fresh connection that starts with prefix. |
| +func (pe *proxyEdge) exchange(t *testing.T, secure bool, prefix []byte, method, host, path string) rawResult { |
| + t.Helper() |
| + c := pe.dial(t, secure, prefix) |
| + defer c.Close() |
| + return pe.request(t, c, secure, method, host, path) |
| +} |
| + |
| +// echoXFF is an upstream that answers the X-Forwarded-For it was sent, |
| +// counting hits. |
| +func echoXFF(t *testing.T) (addr string, hits *atomic.Int64) { |
| + t.Helper() |
| + hits = new(atomic.Int64) |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + hits.Add(1) |
| + io.WriteString(w, r.Header.Get("X-Forwarded-For")) |
| + })) |
| + t.Cleanup(ts.Close) |
| + return ts.Listener.Addr().String(), hits |
| +} |
| + |
| +func ppEdge(t *testing.T, routes ...registry.Route) *Edge { |
| + t.Helper() |
| + reg := openReg(t) |
| + for _, rt := range routes { |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + return e |
| +} |
| + |
| +func armed(t *testing.T, e *Edge, trusted []netip.Addr, dataDir string) *proxyIngress { |
| + t.Helper() |
| + if err := e.armProxyIngress(trusted, dataDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + return e.proxy.Load() |
| +} |
| + |
| +func counters(t *testing.T, e *Edge) proxyproto.Counters { |
| + t.Helper() |
| + c, ok := e.ProxyCounters() |
| + if !ok { |
| + t.Fatal("ProxyCounters: not armed") |
| + } |
| + return c |
| +} |
| + |
| +func wantNoClientRefused(t *testing.T, res rawResult, what string) { |
| + t.Helper() |
| + if res.status != http.StatusServiceUnavailable || !res.connClose { |
| + t.Fatalf("%s: status %d, Connection: close %v, want 503 and close", what, res.status, res.connClose) |
| + } |
| +} |
| + |
| +// A trusted PROXY header's source is the client everywhere the edge reads |
| +// one: the upstream's X-Forwarded-For and the rate limiter's key. |
| +func TestProxiedRequestReachesLimiterAndXFF(t *testing.T) { |
| + t.Setenv("CARLOS_RATE_LIMIT", "enforce") |
| + up, hits := echoXFF(t) |
| + e := ppEdge(t, rlRoute(up, `{"rate":1,"burst":1}`)) |
| + armed(t, e, ppLoopback, t.TempDir()) |
| + logs := &lockedBuffer{} |
| + prev := log.Writer() |
| + log.SetOutput(logs) |
| + t.Cleanup(func() { log.SetOutput(prev) }) |
| + pe := newProxyEdge(t, e, proxyOpts{}) |
| + |
| + res := pe.exchange(t, true, ppv2Proxy("203.0.113.7:51000"), http.MethodGet, rlHost, "/") |
| + if res.status != http.StatusOK || res.body != "203.0.113.7" { |
| + t.Fatalf("first request: %d %q, want 200 and X-Forwarded-For 203.0.113.7", res.status, res.body) |
| + } |
| + // The same client from another port, over another connection from the |
| + // same node: its bucket is empty. |
| + res = pe.exchange(t, true, ppv2Proxy("203.0.113.7:51001"), http.MethodGet, rlHost, "/") |
| + if res.status != http.StatusTooManyRequests { |
| + t.Fatalf("second request from the same client: %d %q, want 429", res.status, res.body) |
| + } |
| + if !strings.Contains(logs.String(), "client 203.0.113.7/32") { |
| + t.Fatalf("the limiter did not key on 203.0.113.7/32; log:\n%s", logs.String()) |
| + } |
| + // Another client through the same node has its own bucket. |
| + res = pe.exchange(t, true, ppv2Proxy("198.51.100.7:40000"), http.MethodGet, rlHost, "/") |
| + if res.status != http.StatusOK || res.body != "198.51.100.7" { |
| + t.Fatalf("other client: %d %q, want 200 and X-Forwarded-For 198.51.100.7", res.status, res.body) |
| + } |
| + if n := hits.Load(); n != 2 { |
| + t.Fatalf("upstream hits = %d, want 2", n) |
| + } |
| + c := counters(t, e) |
| + if c.Proxied != 3 || c.ProxiedByNode[ppLoopback[0]] != 3 { |
| + t.Fatalf("Proxied = %d, by node %v, want 3 from 127.0.0.1", c.Proxied, c.ProxiedByNode) |
| + } |
| +} |
| + |
| +// A connection with no client address reaches lbHealthAnswer for the |
| +// health check whatever its Host, never the ordinary :80 chain, where a |
| +// demo Host is answered before the health branch. |
| +func TestNoClientHealthDispatchIgnoresHost(t *testing.T) { |
| + up, hits := echoXFF(t) |
| + e := ppEdge(t, rlRoute(up, "")) |
| + e.demo.Domain = "demo.example" |
| + e.lbHealth = healthyState() |
| + armed(t, e, ppLoopback, t.TempDir()) |
| + pe := newProxyEdge(t, e, proxyOpts{}) |
| + |
| + demoHost := "x.demo.example" |
| + // The premise: through the ordinary chain (a client connection), the |
| + // demo Host never reaches the health answer. |
| + if res := pe.exchange(t, false, ppv2Proxy("203.0.113.7:51000"), http.MethodGet, demoHost, lbhealth.Path); res.status == http.StatusOK && res.body == "ok\n" { |
| + t.Fatal("setup: a demo Host reached the health answer through the ordinary chain") |
| + } |
| + |
| + for _, host := range []string{rlHost, demoHost, "unknown.example.net", "10.0.1.7"} { |
| + res := pe.exchange(t, false, ppv2Local(), http.MethodGet, host, lbhealth.Path) |
| + if res.status != http.StatusOK || res.body != "ok\n" { |
| + t.Fatalf("GET with Host %s: %d %q, want lbHealthAnswer's 200 ok", host, res.status, res.body) |
| + } |
| + if res = pe.exchange(t, false, ppv2Local(), http.MethodHead, host, lbhealth.Path); res.status != http.StatusOK { |
| + t.Fatalf("HEAD with Host %s: %d, want 200", host, res.status) |
| + } |
| + } |
| + joining := healthyState() |
| + joining.SetHosting(false) |
| + e.lbHealth = joining |
| + if res := pe.exchange(t, false, ppv2Local(), http.MethodGet, demoHost, lbhealth.Path); res.status != http.StatusServiceUnavailable || !strings.Contains(res.body, lbhealth.CondHosting) { |
| + t.Fatalf("joining, demo Host: %d %q, want lbHealthAnswer's 503 naming %s", res.status, res.body, lbhealth.CondHosting) |
| + } |
| + // Region HA off: lbHealthAnswer declines, and the answer is a 503. |
| + e.lbHealth = nil |
| + if res := pe.exchange(t, false, ppv2Local(), http.MethodGet, demoHost, lbhealth.Path); res.status != http.StatusServiceUnavailable { |
| + t.Fatalf("region HA off: %d %q, want 503", res.status, res.body) |
| + } |
| + if n := hits.Load(); n != 0 { |
| + t.Fatalf("upstream hits = %d, want 0", n) |
| + } |
| + if c := counters(t, e); c.NoClientRefused != 0 { |
| + t.Fatalf("NoClientRefused = %d, want 0: health checks are not refusals", c.NoClientRefused) |
| + } |
| +} |
| + |
| +// Anything but :80's health check on a connection with no client address |
| +// is a 503 with Connection: close, before routing; nothing reaches the |
| +// upstream. |
| +func TestNoClientAppRequestRefused(t *testing.T) { |
| + up, hits := echoXFF(t) |
| + e := ppEdge(t, rlRoute(up, "")) |
| + e.lbHealth = healthyState() |
| + armed(t, e, ppLoopback, t.TempDir()) |
| + pe := newProxyEdge(t, e, proxyOpts{}) |
| + |
| + wantNoClientRefused(t, pe.exchange(t, true, ppv2Local(), http.MethodGet, rlHost, "/"), "LOCAL, GET / on :443") |
| + wantNoClientRefused(t, pe.exchange(t, false, ppv2Local(), http.MethodGet, rlHost, "/"), "LOCAL, GET / on :80") |
| + if c := counters(t, e); c.NoClientRefused != 2 { |
| + t.Fatalf("NoClientRefused = %d, want 2", c.NoClientRefused) |
| + } |
| + |
| + // The same for a node connection with no header at all (S3), the |
| + // health path on :443, and a POST of the health path on :80. |
| + wantNoClientRefused(t, pe.exchange(t, true, nil, http.MethodGet, rlHost, "/"), "no header, GET / on :443") |
| + wantNoClientRefused(t, pe.exchange(t, true, ppv2Local(), http.MethodGet, rlHost, lbhealth.Path), "LOCAL, health path on :443") |
| + wantNoClientRefused(t, pe.exchange(t, false, ppv2Local(), http.MethodPost, "10.0.1.7", lbhealth.Path), "LOCAL, POST of the health path on :80") |
| + |
| + // HTTP/2 on :443: refused before routing too. |
| + tr := &http.Transport{ |
| + TLSClientConfig: &tls.Config{RootCAs: pe.pool, ServerName: "127.0.0.1"}, |
| + ForceAttemptHTTP2: true, |
| + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + c, err := (&net.Dialer{}).DialContext(ctx, network, addr) |
| + if err == nil { |
| + _, err = c.Write(ppv2Local()) |
| + } |
| + return c, err |
| + }, |
| + } |
| + t.Cleanup(tr.CloseIdleConnections) |
| + req, _ := http.NewRequest(http.MethodGet, "https://"+pe.httpsAddr+"/", nil) |
| + req.Host = rlHost |
| + resp, err := (&http.Client{Transport: tr, Timeout: 10 * time.Second}).Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.ProtoMajor != 2 || resp.StatusCode != http.StatusServiceUnavailable { |
| + t.Fatalf("HTTP/2: %s %d, want HTTP/2 503", resp.Proto, resp.StatusCode) |
| + } |
| + |
| + if c := counters(t, e); c.NoClientRefused != 6 { |
| + t.Fatalf("NoClientRefused = %d, want 6", c.NoClientRefused) |
| + } |
| + if n := hits.Load(); n != 0 { |
| + t.Fatalf("upstream hits = %d, want 0", n) |
| + } |
| +} |
| + |
| +// A hairpin connection keeps its public-address normalisation through the |
| +// wrap, on :80 and over TLS on :443, exactly as without it. |
| +func TestHairpinSurvivesProxyWrap(t *testing.T) { |
| + cfg := hairpin.Config{V: 1, Region: "ie", PublicIPs: []string{"127.0.0.1"}, PublicIPv4: "1.1.1.1", PrivateCIDR: "172.31.0.0/16", PrimaryIPv4: "172.31.7.19", BootID: "12345678-1234-1234-1234-123456789abc", Account: "123456789012", InstanceID: "i-0123456789abcdef0"} |
| + for _, armedEdge := range []bool{false, true} { |
| + e := ppEdge(t) |
| + if armedEdge { |
| + // A node address no loopback peer has: the hairpin peer is |
| + // untrusted, as it always is in production. |
| + armed(t, e, []netip.Addr{netip.MustParseAddr("10.9.9.9")}, t.TempDir()) |
| + } |
| + seen := make(chan string, 2) |
| + record := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + seen <- r.RemoteAddr |
| + io.WriteString(w, "seen") |
| + }) |
| + pe := newProxyEdge(t, e, proxyOpts{https: record, challenge: record, hairpin: &cfg}) |
| + for _, secure := range []bool{false, true} { |
| + if res := pe.exchange(t, secure, nil, http.MethodGet, "shop.example", "/"); res.status != http.StatusOK { |
| + t.Fatalf("armed %v, secure %v: %d %q", armedEdge, secure, res.status, res.body) |
| + } |
| + got := <-seen |
| + if host, _, _ := net.SplitHostPort(got); host != cfg.PublicIPv4 { |
| + t.Fatalf("armed %v, secure %v: RemoteAddr %s, want the box's public address %s", armedEdge, secure, got, cfg.PublicIPv4) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// connsNew reports each connection the servers move to StateNew. |
| +func connsNew() (chan net.Conn, func(net.Conn, http.ConnState)) { |
| + ch := make(chan net.Conn, 16) |
| + return ch, func(c net.Conn, s http.ConnState) { |
| + if s == http.StateNew { |
| + ch <- c |
| + } |
| + } |
| +} |
| + |
| +func waitNew(t *testing.T, ch chan net.Conn, n int) { |
| + t.Helper() |
| + for i := 0; i < n; i++ { |
| + select { |
| + case <-ch: |
| + case <-time.After(5 * time.Second): |
| + t.Fatalf("connection %d of %d never reached the server", i+1, n) |
| + } |
| + } |
| +} |
| + |
| +func wantClosedWithin(t *testing.T, c net.Conn, d time.Duration, what string) { |
| + t.Helper() |
| + _ = c.SetReadDeadline(time.Now().Add(d)) |
| + _, err := c.Read(make([]byte, 1)) |
| + var ne net.Error |
| + if err == nil || (errors.As(err, &ne) && ne.Timeout()) { |
| + t.Fatalf("%s: still open (%v)", what, err) |
| + } |
| +} |
| + |
| +// A trusted connection still waiting for its header is ended by Shutdown |
| +// (as a connection waiting for request headers is: closed once older than |
| +// 5 s) and by the ingress drain's CloseIngress, both well inside the 10 s |
| +// header deadline. |
| +func TestShutdownEndsPendingHeader(t *testing.T) { |
| + t.Run("Shutdown", func(t *testing.T) { |
| + t.Parallel() |
| + e := ppEdge(t) |
| + armed(t, e, ppLoopback, t.TempDir()) |
| + news, hook := connsNew() |
| + pe := newProxyEdge(t, e, proxyOpts{connState: hook}) |
| + dialed := time.Now() |
| + silent := pe.dial(t, true, nil) |
| + waitNew(t, news, 1) |
| + // Shutdown closes a new connection once its state is more than 5 |
| + // whole seconds old, so up to 6 s and a poll after accept. Started |
| + // two seconds in, it needs at most 4.5 s of its 6 s context. |
| + time.Sleep(2 * time.Second) |
| + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) |
| + defer cancel() |
| + if err := pe.https.Shutdown(ctx); err != nil { |
| + t.Fatalf("Shutdown: %v, want it to return before its 6 s context", err) |
| + } |
| + wantClosedWithin(t, silent, time.Second, "the silent trusted connection") |
| + if d := time.Since(dialed); d >= proxyHeaderTimeout { |
| + t.Fatalf("ended after %s: the header deadline, not Shutdown", d) |
| + } |
| + }) |
| + t.Run("CloseIngress", func(t *testing.T) { |
| + t.Parallel() |
| + e := ppEdge(t) |
| + armed(t, e, ppLoopback, t.TempDir()) |
| + news, hook := connsNew() |
| + pe := newProxyEdge(t, e, proxyOpts{connState: hook}) |
| + dialed := time.Now() |
| + partial := ppv2Proxy("203.0.113.7:51000")[:14] |
| + conns := []net.Conn{pe.dial(t, true, nil), pe.dial(t, false, nil), pe.dial(t, true, partial), pe.dial(t, false, partial)} |
| + waitNew(t, news, len(conns)) |
| + time.Sleep(2 * time.Second) |
| + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) |
| + defer cancel() |
| + start := time.Now() |
| + if _, err := e.CloseIngress(ctx, 6*time.Second); err != nil { |
| + t.Fatalf("CloseIngress: %v", err) |
| + } |
| + if d := time.Since(start); d >= 6*time.Second { |
| + t.Fatalf("CloseIngress took %s, want under its 6 s bound", d) |
| + } |
| + for i, c := range conns { |
| + wantClosedWithin(t, c, time.Second, "pending connection "+string(rune('a'+i))) |
| + } |
| + if d := time.Since(dialed); d >= proxyHeaderTimeout { |
| + t.Fatalf("ended after %s: the header deadline, not CloseIngress", d) |
| + } |
| + }) |
| +} |
| + |
| +// The two mandatory barrier races (spec §9), end to end through this |
| +// task's handler stack: (a) a trusted connection mid-header when the flag |
| +// goes up, which then completes a valid PROXY header; (b) a trusted |
| +// connection opened after RaiseTrustBarrier. Each is no-client: the health |
| +// check on :80 gets lbHealthAnswer's answer, GET / is refused on :80 and |
| +// on :443, and nothing reaches the upstream. |
| +func TestBarrierRacesThroughHandler(t *testing.T) { |
| + up, hits := echoXFF(t) |
| + e := ppEdge(t, rlRoute(up, "")) |
| + e.lbHealth = healthyState() |
| + reached := make(chan string, 1) |
| + release := make(chan struct{}) |
| + if err := e.armProxyIngress(ppLoopback, t.TempDir()); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := e.proxy.Load() |
| + p.parseHook = func(stage string) { |
| + reached <- stage |
| + <-release |
| + } |
| + pe := newProxyEdge(t, e, proxyOpts{}) |
| + |
| + waitHook := func(what string) { |
| + t.Helper() |
| + select { |
| + case stage := <-reached: |
| + if stage != "signature-read" { |
| + t.Fatalf("%s: hook stage %q", what, stage) |
| + } |
| + case <-time.After(5 * time.Second): |
| + t.Fatalf("%s: the parse never reached signature-read", what) |
| + } |
| + } |
| + type step struct { |
| + secure bool |
| + path string |
| + health bool |
| + } |
| + steps := []step{{false, lbhealth.Path, true}, {false, "/", false}, {true, "/", false}} |
| + check := func(res rawResult, s step, what string) { |
| + t.Helper() |
| + if s.health { |
| + if res.status != http.StatusOK || res.body != "ok\n" { |
| + t.Fatalf("%s: %d %q, want lbHealthAnswer's 200 ok", what, res.status, res.body) |
| + } |
| + return |
| + } |
| + wantNoClientRefused(t, res, what) |
| + } |
| + header := ppv2Proxy("203.0.113.7:51000") |
| + |
| + // (a): the flag goes up between the signature and the rest of the |
| + // header, the instant between RaiseTrustBarrier's flag and its sweep. |
| + for _, s := range steps { |
| + what := "(a) " + map[bool]string{false: ":80", true: ":443"}[s.secure] + " " + s.path |
| + p.barrier.Store(false) |
| + c := pe.dial(t, s.secure, header[:12]) |
| + waitHook(what) |
| + p.barrier.Store(true) |
| + if _, err := c.Write(header[12:]); err != nil { |
| + t.Fatal(err) |
| + } |
| + release <- struct{}{} |
| + check(pe.request(t, c, s.secure, http.MethodGet, rlHost, s.path), s, what) |
| + c.Close() |
| + } |
| + |
| + // (b): a connection opened after the barrier is raised. |
| + p.barrier.Store(false) |
| + if _, err := e.RaiseTrustBarrier(); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, s := range steps { |
| + what := "(b) " + map[bool]string{false: ":80", true: ":443"}[s.secure] + " " + s.path |
| + c := pe.dial(t, s.secure, header) |
| + waitHook(what) |
| + release <- struct{}{} |
| + check(pe.request(t, c, s.secure, http.MethodGet, rlHost, s.path), s, what) |
| + c.Close() |
| + } |
| + |
| + if n := hits.Load(); n != 0 { |
| + t.Fatalf("upstream hits = %d, want 0", n) |
| + } |
| + c := counters(t, e) |
| + if c.Proxied != 0 || c.NoClient != 6 || c.NoClientRefused != 4 { |
| + t.Fatalf("Proxied %d NoClient %d NoClientRefused %d, want 0, 6, 4", c.Proxied, c.NoClient, c.NoClientRefused) |
| + } |
| +} |
| + |
| +// RaiseTrustBarrier persists: it writes the file and closes trusted |
| +// connections, open and pending; an edge started over the same data dir |
| +// starts with the barrier up; ResumeTrust removes it. |
| +func TestTrustBarrierPersistsAndResumes(t *testing.T) { |
| + dataDir := t.TempDir() |
| + e := ppEdge(t, rlRoute(func() string { a, _ := echoXFF(t); return a }(), "")) |
| + armed(t, e, ppLoopback, dataDir) |
| + if e.TrustBarrierUp() { |
| + t.Fatal("barrier up on a fresh data dir") |
| + } |
| + news, hook := connsNew() |
| + pe := newProxyEdge(t, e, proxyOpts{connState: hook}) |
| + |
| + // An open proxied connection, idle after its request, and one still |
| + // waiting for the rest of its header. |
| + open := pe.dial(t, true, ppv2Proxy("203.0.113.7:51000")) |
| + waitNew(t, news, 1) |
| + secure := tls.Client(open, &tls.Config{RootCAs: pe.pool, ServerName: "127.0.0.1"}) |
| + if res := pe.request(t, secure, false, http.MethodGet, rlHost, "/"); res.status != http.StatusOK { |
| + t.Fatalf("proxied request: %d %q", res.status, res.body) |
| + } |
| + pending := pe.dial(t, false, ppv2Proxy("203.0.113.7:51001")[:14]) |
| + waitNew(t, news, 1) |
| + |
| + closed, err := e.RaiseTrustBarrier() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if closed != 2 { |
| + t.Fatalf("closed %d, want 2", closed) |
| + } |
| + if !e.TrustBarrierUp() { |
| + t.Fatal("barrier not up after RaiseTrustBarrier") |
| + } |
| + if _, err := os.Stat(barrierFile(dataDir)); err != nil { |
| + t.Fatalf("barrier file: %v", err) |
| + } |
| + wantClosedWithin(t, open, 2*time.Second, "the open proxied connection") |
| + wantClosedWithin(t, pending, 2*time.Second, "the pending connection") |
| + if _, err := e.RaiseTrustBarrier(); err != nil { |
| + t.Fatalf("raising again: %v", err) |
| + } |
| + |
| + // A restart: a new edge over the same data dir, armed the way Serve |
| + // arms it. |
| + e2 := ppEdge(t) |
| + if err := e2.loadProxyIngress(func(k string) string { |
| + if k == "CARLOS_INGRESS_PROXY_SOURCES" { |
| + return "172.31.29.110,172.31.11.189" |
| + } |
| + return "" |
| + }, dataDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !e2.TrustBarrierUp() { |
| + t.Fatal("a restarted edge started with the barrier down") |
| + } |
| + if line := e2.proxy.Load().armedLine(); line != "edge: proxy protocol: armed on :80 and :443, trusting 172.31.11.189,172.31.29.110, barrier up" { |
| + t.Fatalf("armed line: %q", line) |
| + } |
| + if err := e2.ResumeTrust(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if e2.TrustBarrierUp() { |
| + t.Fatal("barrier still up after ResumeTrust") |
| + } |
| + if _, err := os.Stat(barrierFile(dataDir)); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("barrier file after ResumeTrust: %v", err) |
| + } |
| + if err := e.ResumeTrust(); err != nil { |
| + t.Fatalf("resume with the file already gone: %v", err) |
| + } |
| + e3 := ppEdge(t) |
| + armed(t, e3, ppLoopback, dataDir) |
| + if e3.TrustBarrierUp() { |
| + t.Fatal("barrier up at start after ResumeTrust") |
| + } |
| +} |
| + |
| +// Without the key nothing changes: the listeners are returned as given, no |
| +// counters, no barrier, and a PPv2 header on :80 gets today's 400. |
| +func TestUnarmedEdgeUnchanged(t *testing.T) { |
| + dataDir := t.TempDir() |
| + e := ppEdge(t) |
| + if err := e.loadProxyIngress(func(string) string { return "" }, dataDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + if e.proxy.Load() != nil { |
| + t.Fatal("armed without the key") |
| + } |
| + if err := e.loadProxyIngress(func(string) string { return "127.0.0.1" }, dataDir); err == nil || !strings.Contains(err.Error(), "CARLOS_INGRESS_PROXY_SOURCES") || e.proxy.Load() != nil { |
| + t.Fatalf("a bad value: %v, armed %v; want an error naming the key, unarmed", err, e.proxy.Load() != nil) |
| + } |
| + |
| + httpsSrv, httpSrv := e.publicServers(e, e.httpFallbackHandler(), &tls.Config{}, "", "") |
| + hs, h := httpsSrv.Handler, httpSrv.Handler |
| + a, b := portListener{port: 443}, portListener{port: 80} |
| + gotA, gotB := e.wrapProxyIngress(httpsSrv, httpSrv, a, b) |
| + if gotA != net.Listener(a) || gotB != net.Listener(b) || httpsSrv.ConnContext != nil || httpSrv.ConnContext != nil { |
| + t.Fatal("an unarmed edge wrapped its listeners or set a ConnContext") |
| + } |
| + if httpsSrv.Handler != hs || reflect.ValueOf(httpSrv.Handler).Pointer() != reflect.ValueOf(h).Pointer() { |
| + t.Fatal("an unarmed edge replaced a handler") |
| + } |
| + |
| + pe := newProxyEdge(t, e, proxyOpts{}) |
| + // Header and request in one write: net/http answers the header's first |
| + // bytes and closes, and a request sent after that would be met by a |
| + // reset instead of the answer. |
| + c := pe.dial(t, false, append(ppv2Proxy("203.0.113.7:51000"), "GET / HTTP/1.1\r\nHost: 10.0.1.7\r\n\r\n"...)) |
| + resp, err := http.ReadResponse(bufio.NewReader(c), nil) |
| + if err != nil { |
| + t.Fatalf("PPv2 header on :80: %v", err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != http.StatusBadRequest { |
| + t.Fatalf("PPv2 header on :80: %d, want 400", resp.StatusCode) |
| + } |
| + if _, ok := e.ProxyCounters(); ok { |
| + t.Fatal("ProxyCounters armed") |
| + } |
| + if e.TrustBarrierUp() { |
| + t.Fatal("barrier up unarmed") |
| + } |
| + if _, err := e.RaiseTrustBarrier(); !errors.Is(err, ErrProxyProtocolOff) { |
| + t.Fatalf("RaiseTrustBarrier unarmed: %v", err) |
| + } |
| + if err := e.ResumeTrust(); !errors.Is(err, ErrProxyProtocolOff) { |
| + t.Fatalf("ResumeTrust unarmed: %v", err) |
| + } |
| + if _, err := os.Stat(barrierFile(dataDir)); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("barrier file unarmed: %v", err) |
| + } |
| +} |
| + |
| +// The minute's journal: every counter, each node's proxied count, the |
| +// barrier; and a warning when no_client_refused moved. |
| +func TestProxyJournalLines(t *testing.T) { |
| + e := ppEdge(t) |
| + armed(t, e, ppLoopback, t.TempDir()) |
| + pe := newProxyEdge(t, e, proxyOpts{}) |
| + var prev proxyproto.Counters |
| + lines := e.proxyJournalLines(&prev) |
| + want := "edge: proxy protocol: proxied=0 no_client=0 no_client_refused=0 ignored=0 ignored_private=0 marker_trusted=0 malformed=0 timeout=0 proxied_by_node=127.0.0.1:0 barrier=down" |
| + if len(lines) != 1 || lines[0] != want { |
| + t.Fatalf("quiet minute: %q", lines) |
| + } |
| + wantNoClientRefused(t, pe.exchange(t, false, ppv2Local(), http.MethodGet, "10.0.1.7", "/"), "LOCAL GET /") |
| + pe.exchange(t, false, ppv2Proxy("203.0.113.7:51000"), http.MethodGet, "10.0.1.7", "/") |
| + lines = e.proxyJournalLines(&prev) |
| + if len(lines) != 2 || !strings.Contains(lines[0], "proxied=1 no_client=1 no_client_refused=1 ") || !strings.Contains(lines[0], "proxied_by_node=127.0.0.1:1 ") || |
| + !strings.Contains(lines[1], "WARNING") || !strings.Contains(lines[1], "no_client_refused +1 (last peer 127.0.0.1)") { |
| + t.Fatalf("minute with a refusal: %q", lines) |
| + } |
| + if lines = e.proxyJournalLines(&prev); len(lines) != 1 { |
| + t.Fatalf("the warning repeated without a new refusal: %q", lines) |
| + } |
| + var unarmed Edge |
| + if lines := unarmed.proxyJournalLines(&prev); lines != nil { |
| + t.Fatalf("unarmed journal: %q", lines) |
| + } |
| +} |