carlos / platform Public

edge: parse PPv2 from the NLB, health-only gate, trust barrier

Armed only by a non-empty CARLOS_INGRESS_PROXY_SOURCES (a bad value is
fatal at start): both public listeners are wrapped outermost, after the
hairpin, and a gate outside each handler lets a connection with no
client address answer :80's health check through lbHealthAnswer and
nothing else (503, Connection: close, counted). hairpinConnContext
unwraps every NetConn() layer. RaiseTrustBarrier writes and syncs
<data>/edge/trust-barrier, sets the flag, then sweeps trusted
connections; the file is read before bind. Journal: an armed line at
start and a counters line each minute, with a warning when refusals or
ignored private headers move. Unarmed, nothing changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8992f0cf5503a09966b293b0221dd23fe5e3a16a parent 8bfe012
5 files changed, +1,176 −9
  • internal/edge/edge.go +20 −0
  • internal/edge/hairpin.go +23 −8
  • internal/edge/ingressdrain.go +4 −1
  • internal/edge/proxyingress.go +374 −0
  • internal/edge/proxyingress_test.go +755 −0
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index de4e77091..d498b623b 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -391,6 +391,9 @@ type Edge struct {
// plain tracks :80's requests for the fixed box's ingress drain only
// (ingressdrain.go); §25's connection drain never touches it.
plain connDrain
+ // proxy is the PROXY protocol v2 ingress (proxyingress.go): nil unless
+ // CARLOS_INGRESS_PROXY_SOURCES armed it at start.
+ proxy atomic.Pointer[proxyIngress]
// certs is the certificate mirror newCertMirror built, which control
// requests choose their TLS name from (hadrain.go).
certs atomic.Pointer[certMirror]
@@ -5108,6 +5111,16 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
+ // PROXY protocol on the public listeners (proxyingress.go): armed only
+ // by a non-empty CARLOS_INGRESS_PROXY_SOURCES, and never in dev mode.
+ // The barrier file is read here, before either listener binds and
+ // before the ready hook hands the Edge to the agent's socket.
+ if !*dev {
+ if err := e.loadProxyIngress(os.Getenv, dataDir); err != nil {
+ log.Fatal(err)
+ }
+ }
+
// The Edge is fully configured here — every EnableXxx applied and the
// route table rebuilt behind them — and nothing is listening yet.
if ready != nil {
@@ -5308,8 +5321,15 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
if err != nil {
log.Fatal(err)
}
+ // Outermost, after the hairpin: hairpinListener.Accept still classifies
+ // the raw socket and never waits on a header. Unarmed, a no-op.
+ httpsLn, httpLn = e.wrapProxyIngress(httpsSrv, httpSrv, httpsLn, httpLn)
e.conns.serve(httpsSrv, httpSrv)
log.Print(listenersLine(httpLn, *httpAddr, httpsLn, *httpsAddr))
+ if p := e.proxy.Load(); p != nil {
+ log.Print(p.armedLine())
+ go e.runProxyJournal() // process-lifetime; never stopped
+ }
// :80 serves the ACME HTTP-01 challenge and redirects everything else.
go func() {
diff --git a/internal/edge/hairpin.go b/internal/edge/hairpin.go
index 64c3c3e92..fdf35b9d8 100644
--- a/internal/edge/hairpin.go
+++ b/internal/edge/hairpin.go
@@ -2,7 +2,6 @@ package edge
import (
"context"
- "crypto/tls"
"fmt"
"net"
"net/http"
@@ -80,12 +79,21 @@ func (l *hairpinListener) Accept() (net.Conn, error) {
return c, nil
}
}
+
+// hairpinConnContext marks a hairpin connection's requests. The mark sits
+// under every wrapper the accept path adds (TLS on :443, the PROXY
+// protocol connection on an armed edge), so each NetConn() layer is
+// unwrapped until the hairpin connection or the raw socket.
func hairpinConnContext(ctx context.Context, c net.Conn) context.Context {
- if secure, ok := c.(*tls.Conn); ok {
- c = secure.NetConn()
- }
- if h, ok := c.(*hairpinConnection); ok {
- return context.WithValue(ctx, hairpinContextKey{}, h.public)
+ for c != nil {
+ if h, ok := c.(*hairpinConnection); ok {
+ return context.WithValue(ctx, hairpinContextKey{}, h.public)
+ }
+ u, ok := c.(interface{ NetConn() net.Conn })
+ if !ok {
+ break
+ }
+ c = u.NetConn()
}
return ctx
}
@@ -120,7 +128,14 @@ func ConfigureGroupHairpin(srv *http.Server, ln net.Listener) (net.Listener, err
if err := hairpinSupported(); err != nil {
return nil, err
}
- h := &hairpinIngress{config: *c}
+ return configureHairpin(srv, ln, *c), nil
+}
+
+// configureHairpin is ConfigureGroupHairpin once the configuration is
+// loaded and checked: it marks connections on ln and normalises their
+// requests on srv.
+func configureHairpin(srv *http.Server, ln net.Listener, c hairpin.Config) net.Listener {
+ h := &hairpinIngress{config: c}
previous := srv.ConnContext
srv.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
if previous != nil {
@@ -130,5 +145,5 @@ func ConfigureGroupHairpin(srv *http.Server, ln net.Listener) (net.Listener, err
}
handler := srv.Handler
srv.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { normalizeHairpin(r); handler.ServeHTTP(w, r) })
- return &hairpinListener{Listener: ln, ingress: h}, nil
+ return &hairpinListener{Listener: ln, ingress: h}
}
diff --git a/internal/edge/ingressdrain.go b/internal/edge/ingressdrain.go
index 6134455d2..54370928f 100644
--- a/internal/edge/ingressdrain.go
+++ b/internal/edge/ingressdrain.go
@@ -83,7 +83,10 @@ func (e *Edge) plainTracked(h http.Handler) http.Handler {
// publicServers builds the edge's two public servers: :443 serving
// https (the edge itself in production) and :80 serving challenge
// through plainTracked. The caller registers both with e.conns.serve
-// after any other ConnContext (the hairpin) is set.
+// after any other ConnContext (the hairpin, then on an armed edge the
+// PROXY protocol wrap, wrapProxyIngress) is set. The wrap puts its
+// no-client gate outside both handlers, so on a connection with no client
+// address :80's health check never reaches plainTracked or the challenge.
//
// ReadHeaderTimeout guards the public front door against Slowloris-style
// slow-header connection exhaustion. No ReadTimeout/WriteTimeout: those
diff --git a/internal/edge/proxyingress.go b/internal/edge/proxyingress.go
new file mode 100644
index 000000000..97a7b738b
--- /dev/null
+++ b/internal/edge/proxyingress.go
@@ -0,0 +1,374 @@
+package edge
+
+// PROXY protocol v2 on the public :80 and :443 listeners (edge PPv2 spec
+// §4). Dormant unless CARLOS_INGRESS_PROXY_SOURCES names the region NLB's
+// node addresses: without it nothing here is built and the listeners are
+// exactly today's. Armed, each listener is wrapped outermost (after the
+// hairpin), every connection resolves a parse state on its own goroutine
+// (internal/proxyproto), and a gate in front of each server's handler lets
+// a connection with no client address answer the health check and nothing
+// else (§4.6). The trust barrier (§4.7) is a flag every trusted parse asks
+// when it resolves, backed by a file so a restart keeps it up.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "net"
+ "net/http"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hostenv"
+ "github.com/carlosframework/platform/internal/lbhealth"
+ "github.com/carlosframework/platform/internal/proxyproto"
+)
+
+// proxyMarker is the forgery probe's source range (spec §6.4): a trusted
+// header from it closes the connection and counts marker_trusted.
+var proxyMarker = netip.MustParsePrefix("192.0.2.0/24")
+
+// proxyHeaderTimeout bounds a trusted connection's header, from accept: the
+// public listeners' ReadHeaderTimeout (publicServers).
+const proxyHeaderTimeout = 10 * time.Second
+
+// proxyJournalEvery is how often an armed edge writes its counters line.
+const proxyJournalEvery = time.Minute
+
+// ErrProxyProtocolOff refuses a trust barrier verb on an edge that was not
+// armed for PROXY protocol at start.
+var ErrProxyProtocolOff = errors.New("edge: this box is not armed for PROXY protocol")
+
+// proxyIngress is an armed edge's PROXY protocol state.
+type proxyIngress struct {
+ trusted []netip.Addr // sorted
+ barrierPath string
+ barrier atomic.Bool
+
+ // parseHook is proxyproto.Config.ParseHook; nil in production, set by
+ // tests before the listeners are wrapped.
+ parseHook func(stage string)
+
+ // mu serialises the barrier verbs.
+ mu sync.Mutex
+ // The wrapped listeners, nil until Serve wraps them; the agent's
+ // socket may reach the verbs before that. A listener stored after a
+ // raise asks the same flag, so it needs no sweep.
+ http, https atomic.Pointer[proxyproto.Listener]
+
+ // lastRefused is the socket peer of the latest refused request, for
+ // the minute's warning line.
+ lastRefused atomic.Pointer[netip.Addr]
+}
+
+// proxyConnKey holds a request's *proxyproto.Conn in its context.
+type proxyConnKey struct{}
+
+// barrierFile is where the trust barrier persists under the data dir.
+func barrierFile(dataDir string) string {
+ return filepath.Join(dataDir, "edge", "trust-barrier")
+}
+
+// loadProxyIngress arms the edge when CARLOS_INGRESS_PROXY_SOURCES parses
+// to a non-empty list, and leaves it unarmed (byte for byte today's edge)
+// when it is empty or absent. A value that does not parse is an error
+// naming the key; Serve treats it as fatal. Called once, before either
+// public listener binds.
+func (e *Edge) loadProxyIngress(getenv func(string) string, dataDir string) error {
+ trusted, err := hostenv.ParseProxySources(getenv("CARLOS_INGRESS_PROXY_SOURCES"))
+ if err != nil {
+ return fmt.Errorf("edge: proxy protocol: %w", err)
+ }
+ if len(trusted) == 0 {
+ return nil
+ }
+ return e.armProxyIngress(trusted, dataDir)
+}
+
+// armProxyIngress builds the armed state for trusted and reads the barrier
+// file once: present means the barrier is up from the first connection.
+// Any error other than its absence is returned, so an unreadable state
+// directory never lowers a barrier by accident.
+func (e *Edge) armProxyIngress(trusted []netip.Addr, dataDir string) error {
+ p := &proxyIngress{
+ trusted: slices.Clone(trusted),
+ barrierPath: barrierFile(dataDir),
+ }
+ slices.SortFunc(p.trusted, netip.Addr.Compare)
+ switch _, err := os.Lstat(p.barrierPath); {
+ case err == nil:
+ p.barrier.Store(true)
+ case errors.Is(err, os.ErrNotExist):
+ default:
+ return fmt.Errorf("edge: read trust barrier %s: %w", p.barrierPath, err)
+ }
+ e.proxy.Store(p)
+ return nil
+}
+
+// wrapProxyIngress is Serve's last step on the two public listeners, after
+// ConfigureGroupHairpin and before connDrain.serve: on an armed edge it
+// wraps both listeners outermost, records each connection in its request
+// context, and puts the no-client gate outermost on both handlers. Unarmed
+// it returns the listeners untouched and changes nothing.
+func (e *Edge) wrapProxyIngress(httpsSrv, httpSrv *http.Server, httpsLn, httpLn net.Listener) (net.Listener, net.Listener) {
+ p := e.proxy.Load()
+ if p == nil {
+ return httpsLn, httpLn
+ }
+ cfg := proxyproto.Config{
+ Trusted: p.trusted,
+ HeaderTimeout: proxyHeaderTimeout,
+ Marker: proxyMarker,
+ Barrier: p.barrier.Load,
+ ParseHook: p.parseHook,
+ }
+ wrappedHTTPS := proxyproto.NewListener(httpsLn, cfg)
+ wrappedHTTP := proxyproto.NewListener(httpLn, cfg)
+ p.https.Store(wrappedHTTPS)
+ p.http.Store(wrappedHTTP)
+ for _, s := range []struct {
+ srv *http.Server
+ l *proxyproto.Listener
+ health bool
+ }{{httpsSrv, wrappedHTTPS, false}, {httpSrv, wrappedHTTP, true}} {
+ previous := s.srv.ConnContext
+ s.srv.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
+ if previous != nil {
+ ctx = previous(ctx, c)
+ }
+ // No RemoteAddr or State here: this runs on the accept
+ // goroutine, and a trusted connection's parse may wait for
+ // its header (spec §4.3).
+ if pc := proxyConnOf(c); pc != nil {
+ ctx = context.WithValue(ctx, proxyConnKey{}, pc)
+ }
+ return ctx
+ }
+ s.srv.Handler = e.noClientGate(p, s.l, s.health, s.srv.Handler)
+ }
+ return wrappedHTTPS, wrappedHTTP
+}
+
+// proxyConnOf finds the *proxyproto.Conn under c (a *tls.Conn on :443),
+// unwrapping NetConn() layers. It reads nothing.
+func proxyConnOf(c net.Conn) *proxyproto.Conn {
+ for c != nil {
+ if pc, ok := c.(*proxyproto.Conn); ok {
+ return pc
+ }
+ u, ok := c.(interface{ NetConn() net.Conn })
+ if !ok {
+ return nil
+ }
+ c = u.NetConn()
+ }
+ return nil
+}
+
+// noClientGate is the outermost handler on an armed public server (spec
+// §4.6). A request on a connection with no client address (LOCAL, UNSPEC,
+// no header from a node, or any header while the barrier is up) is served
+// only when it is the health check on :80 (health), answered by
+// lbHealthAnswer directly, never through the ordinary chain, where a demo
+// Host is redirected before the health branch. Everything else on such a
+// connection is a 503 with Connection: close, counted no_client_refused,
+// before any routing, limit, analytics or forwarding.
+//
+// State is read here, after net/http has read the request, so it is
+// resolved and costs no read. A request whose connection was not recorded
+// cannot occur on a wrapped listener; it is refused all the same.
+func (e *Edge) noClientGate(p *proxyIngress, l *proxyproto.Listener, health bool, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ pc, _ := r.Context().Value(proxyConnKey{}).(*proxyproto.Conn)
+ if pc != nil && pc.State() != proxyproto.StateNoClient {
+ next.ServeHTTP(w, r)
+ return
+ }
+ if pc != nil && health && r.URL.Path == lbhealth.Path && (r.Method == http.MethodGet || r.Method == http.MethodHead) {
+ if !e.lbHealthAnswer(w, r) {
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(http.StatusServiceUnavailable)
+ }
+ return
+ }
+ l.NoteRefused()
+ if pc != nil {
+ peer := pc.Peer().Addr()
+ p.lastRefused.Store(&peer)
+ }
+ w.Header().Set("Connection", "close")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(http.StatusServiceUnavailable)
+ })
+}
+
+// RaiseTrustBarrier raises the trust barrier (spec §4.7): it writes the
+// barrier file (synced, with its directory), then sets the flag, then
+// closes every trusted connection on both public listeners, pending ones
+// included, and returns how many it closed. The order is the guarantee:
+// a connection the sweep misses resolves after the flag, so its header
+// grants nothing. Calling it again rewrites the file and sweeps again.
+func (e *Edge) RaiseTrustBarrier() (closed int, err error) {
+ p := e.proxy.Load()
+ if p == nil {
+ return 0, ErrProxyProtocolOff
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if err := writeBarrierFile(p.barrierPath); err != nil {
+ return 0, err
+ }
+ p.barrier.Store(true)
+ for _, l := range []*proxyproto.Listener{p.http.Load(), p.https.Load()} {
+ if l != nil {
+ closed += l.CloseTrusted()
+ }
+ }
+ return closed, nil
+}
+
+// ResumeTrust lowers the barrier: it removes the file (and syncs its
+// directory), then clears the flag. If the file cannot be removed the
+// barrier stays up.
+func (e *Edge) ResumeTrust() error {
+ p := e.proxy.Load()
+ if p == nil {
+ return ErrProxyProtocolOff
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if err := os.Remove(p.barrierPath); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("edge: remove trust barrier %s: %w", p.barrierPath, err)
+ }
+ if err := syncDir(filepath.Dir(p.barrierPath)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("edge: sync %s: %w", filepath.Dir(p.barrierPath), err)
+ }
+ p.barrier.Store(false)
+ return nil
+}
+
+// TrustBarrierUp reports whether the trust barrier is up; false unarmed.
+func (e *Edge) TrustBarrierUp() bool {
+ p := e.proxy.Load()
+ return p != nil && p.barrier.Load()
+}
+
+// ProxyCounters sums both public listeners' counters since start. It
+// reports false on an edge that is not armed.
+func (e *Edge) ProxyCounters() (proxyproto.Counters, bool) {
+ p := e.proxy.Load()
+ if p == nil {
+ return proxyproto.Counters{}, false
+ }
+ sum := proxyproto.Counters{ProxiedByNode: map[netip.Addr]uint64{}}
+ for _, l := range []*proxyproto.Listener{p.http.Load(), p.https.Load()} {
+ if l == nil {
+ continue
+ }
+ c := l.Counters()
+ sum.Proxied += c.Proxied
+ sum.NoClient += c.NoClient
+ sum.NoClientRefused += c.NoClientRefused
+ sum.Ignored += c.Ignored
+ sum.IgnoredPrivate += c.IgnoredPrivate
+ sum.MarkerTrusted += c.MarkerTrusted
+ sum.Malformed += c.Malformed
+ sum.Timeout += c.Timeout
+ for a, n := range c.ProxiedByNode {
+ sum.ProxiedByNode[a] += n
+ }
+ }
+ return sum, true
+}
+
+// writeBarrierFile writes the barrier file and syncs it, its directory and
+// the data dir (which holds the directory's entry if it was just made).
+func writeBarrierFile(path string) error {
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return fmt.Errorf("edge: trust barrier directory %s: %w", dir, err)
+ }
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
+ if err != nil {
+ return fmt.Errorf("edge: write trust barrier %s: %w", path, err)
+ }
+ _, werr := fmt.Fprintf(f, "raised %s\n", time.Now().UTC().Format(time.RFC3339))
+ serr := f.Sync()
+ cerr := f.Close()
+ if err := errors.Join(werr, serr, cerr); err != nil {
+ return fmt.Errorf("edge: write trust barrier %s: %w", path, err)
+ }
+ for _, d := range []string{dir, filepath.Dir(dir)} {
+ if err := syncDir(d); err != nil {
+ return fmt.Errorf("edge: sync %s: %w", d, err)
+ }
+ }
+ return nil
+}
+
+func barrierWord(up bool) string {
+ if up {
+ return "up"
+ }
+ return "down"
+}
+
+// armedLine is the start line of an armed edge.
+func (p *proxyIngress) armedLine() string {
+ addrs := make([]string, len(p.trusted))
+ for i, a := range p.trusted {
+ addrs[i] = a.String()
+ }
+ return fmt.Sprintf("edge: proxy protocol: armed on :80 and :443, trusting %s, barrier %s",
+ strings.Join(addrs, ","), barrierWord(p.barrier.Load()))
+}
+
+// proxyJournalLines is one minute's journal: the counters line, and a
+// warning when no_client_refused or ignored_private moved since prev,
+// which it then advances. Nil unarmed.
+func (e *Edge) proxyJournalLines(prev *proxyproto.Counters) []string {
+ p := e.proxy.Load()
+ c, ok := e.ProxyCounters()
+ if !ok {
+ return nil
+ }
+ nodes := make([]string, 0, len(p.trusted))
+ for _, a := range p.trusted {
+ nodes = append(nodes, fmt.Sprintf("%s:%d", a, c.ProxiedByNode[a]))
+ }
+ lines := []string{fmt.Sprintf("edge: proxy protocol: proxied=%d no_client=%d no_client_refused=%d ignored=%d ignored_private=%d marker_trusted=%d malformed=%d timeout=%d proxied_by_node=%s barrier=%s",
+ c.Proxied, c.NoClient, c.NoClientRefused, c.Ignored, c.IgnoredPrivate, c.MarkerTrusted, c.Malformed, c.Timeout,
+ strings.Join(nodes, ","), barrierWord(p.barrier.Load()))}
+ refused := c.NoClientRefused - prev.NoClientRefused
+ private := c.IgnoredPrivate - prev.IgnoredPrivate
+ if refused > 0 || private > 0 {
+ last := "none"
+ if a := p.lastRefused.Load(); a != nil {
+ last = a.String()
+ }
+ lines = append(lines, fmt.Sprintf("edge: WARNING: proxy protocol: in the last minute no_client_refused +%d (last peer %s), ignored_private +%d (a header from a private address not in CARLOS_INGRESS_PROXY_SOURCES)",
+ refused, last, private))
+ }
+ *prev = c
+ return lines
+}
+
+// runProxyJournal writes the minute's journal for the process's life.
+func (e *Edge) runProxyJournal() {
+ t := time.NewTicker(proxyJournalEvery)
+ defer t.Stop()
+ var prev proxyproto.Counters
+ for range t.C {
+ for _, line := range e.proxyJournalLines(&prev) {
+ log.Print(line)
+ }
+ }
+}
diff --git a/internal/edge/proxyingress_test.go b/internal/edge/proxyingress_test.go
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)
+ }
+}