carlos / platform Public

proxyproto: listener with lazy parse state and barrier hook

Listener wraps accepted connections in *Conn, whose PPv2 parse state
resolves once on the serving goroutine (first Read, trusted RemoteAddr,
or State). Trusted peers get a header deadline from accept, rewrite
RemoteAddr for usable PROXY sources, and close on marker or unusable
sources. The barrier is checked once, at resolution. CloseTrusted closes
live trusted conns, pending ones included. Config.ParseHook is a test
seam that holds a parse after the signature.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev abe11a77a1c489fbcf2f57c1a99423e03ea1e01e parent 21eda90
5 files changed, +1,119 −0
  • internal/proxyproto/conn.go +344 −0
  • internal/proxyproto/counters.go +79 −0
  • internal/proxyproto/export_test.go +11 −0
  • internal/proxyproto/listener.go +159 −0
  • internal/proxyproto/listener_test.go +526 −0
diff --git a/internal/proxyproto/conn.go b/internal/proxyproto/conn.go
new file mode 100644
index 000000000..22dcd8d39
--- /dev/null
+++ b/internal/proxyproto/conn.go
@@ -0,0 +1,344 @@
+package proxyproto
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/netip"
+ "os"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+// State is a connection's parse state (spec §4.3). It starts pending and
+// resolves exactly once.
+type State int
+
+const (
+ // StatePending: nothing resolved yet.
+ StatePending State = iota
+ // StateProxied: a trusted peer sent a PROXY header with a usable
+ // source; RemoteAddr is that source.
+ StateProxied
+ // StateNoClient: a trusted peer sent LOCAL, PROXY with UNSPEC, or no
+ // header, or completed a header while the barrier was up. RemoteAddr
+ // is the kernel peer and there is no client address.
+ StateNoClient
+ // StatePlain: an untrusted peer. Any well-formed header was consumed
+ // and ignored; RemoteAddr is the kernel peer.
+ StatePlain
+ // StateFailed: the connection was closed (malformed header, unusable
+ // or marker source, timeout, or Close while pending).
+ StateFailed
+)
+
+func (s State) String() string {
+ switch s {
+ case StatePending:
+ return "pending"
+ case StateProxied:
+ return "proxied"
+ case StateNoClient:
+ return "no-client"
+ case StatePlain:
+ return "plain"
+ case StateFailed:
+ return "failed"
+ }
+ return fmt.Sprintf("State(%d)", int(s))
+}
+
+var (
+ errMarker = errors.New("proxyproto: marker source on a trusted connection")
+ errUnusable = errors.New("proxyproto: unusable source on a trusted connection")
+)
+
+// Conn is a connection accepted by a Listener. Its parse state resolves on
+// the first Read, RemoteAddr (trusted only) or State, on the calling
+// goroutine; Accept and Close never wait for it.
+type Conn struct {
+ inner net.Conn
+ l *Listener
+ peer netip.AddrPort
+ remote net.Addr // the kernel peer as a net.Addr
+ trusted bool
+ accepted time.Time
+
+ // parseMu serialises resolution. Close never takes it.
+ parseMu sync.Mutex
+ state atomic.Int64
+ // Written under parseMu before state is stored, read only after a
+ // resolved state is loaded.
+ source net.Addr
+ failErr error
+
+ // readMu guards what the parse read but the caller has not: bytes that
+ // were not a header, then the read error that came with them.
+ readMu sync.Mutex
+ replay []byte
+ readErr error
+
+ // dlMu guards the caller's read deadline, kept so the header deadline
+ // can sit under it while the parse runs and be replaced by it after.
+ dlMu sync.Mutex
+ userRead time.Time
+ parsing bool
+ headerDL time.Time
+
+ closeOnce sync.Once
+ closeErr error
+}
+
+// NetConn returns the wrapped connection, the same shape as tls.Conn's.
+func (c *Conn) NetConn() net.Conn { return c.inner }
+
+// Peer is the kernel's peer address (or the test override); it never blocks.
+func (c *Conn) Peer() netip.AddrPort { return c.peer }
+
+// Trusted reports whether the peer is in Config.Trusted; it never blocks.
+func (c *Conn) Trusted() bool { return c.trusted }
+
+// State resolves the parse if it is pending and returns the result. It may
+// read from the connection, so call it on the goroutine that serves it.
+func (c *Conn) State() State { return c.resolve() }
+
+// RemoteAddr is the kernel peer for an untrusted connection, at once. For a
+// trusted one it resolves the parse first and is the header's source when
+// the state is StateProxied, the kernel peer otherwise.
+func (c *Conn) RemoteAddr() net.Addr {
+ if !c.trusted {
+ return c.remote
+ }
+ if c.resolve() == StateProxied {
+ return c.source
+ }
+ return c.remote
+}
+
+// Read resolves the parse, then returns any bytes the parse read that were
+// not a header, then reads the connection.
+func (c *Conn) Read(p []byte) (int, error) {
+ if c.resolve() == StateFailed {
+ return 0, c.failErr
+ }
+ c.readMu.Lock()
+ if len(c.replay) > 0 || c.readErr != nil {
+ n := copy(p, c.replay)
+ c.replay = c.replay[n:]
+ var err error
+ if len(c.replay) == 0 {
+ err, c.readErr = c.readErr, nil
+ }
+ c.readMu.Unlock()
+ return n, err
+ }
+ c.readMu.Unlock()
+ return c.inner.Read(p)
+}
+
+func (c *Conn) Write(p []byte) (int, error) { return c.inner.Write(p) }
+
+func (c *Conn) LocalAddr() net.Addr { return c.inner.LocalAddr() }
+
+// Close closes the connection without waiting for a pending parse: closing
+// the socket fails the parse's read, which then resolves to StateFailed.
+func (c *Conn) Close() error {
+ _, err := c.closeInner()
+ return err
+}
+
+// closeInner closes the connection once and reports whether this call did.
+func (c *Conn) closeInner() (bool, error) {
+ did := false
+ c.closeOnce.Do(func() {
+ did = true
+ c.closeErr = c.inner.Close()
+ if c.trusted {
+ c.l.forget(c)
+ }
+ })
+ return did, c.closeErr
+}
+
+func (c *Conn) SetDeadline(t time.Time) error {
+ c.dlMu.Lock()
+ defer c.dlMu.Unlock()
+ c.userRead = t
+ if err := c.inner.SetWriteDeadline(t); err != nil {
+ return err
+ }
+ return c.inner.SetReadDeadline(c.readDeadlineLocked())
+}
+
+func (c *Conn) SetReadDeadline(t time.Time) error {
+ c.dlMu.Lock()
+ defer c.dlMu.Unlock()
+ c.userRead = t
+ return c.inner.SetReadDeadline(c.readDeadlineLocked())
+}
+
+func (c *Conn) SetWriteDeadline(t time.Time) error { return c.inner.SetWriteDeadline(t) }
+
+// readDeadlineLocked is the read deadline to apply: the caller's, or while
+// a trusted parse runs, the earlier of it and the header deadline.
+func (c *Conn) readDeadlineLocked() time.Time {
+ if !c.parsing {
+ return c.userRead
+ }
+ if c.userRead.IsZero() || c.headerDL.Before(c.userRead) {
+ return c.headerDL
+ }
+ return c.userRead
+}
+
+func (c *Conn) beginHeaderDeadline() {
+ c.dlMu.Lock()
+ defer c.dlMu.Unlock()
+ c.parsing = true
+ c.headerDL = c.accepted.Add(c.l.cfg.HeaderTimeout)
+ c.inner.SetReadDeadline(c.readDeadlineLocked())
+}
+
+func (c *Conn) endHeaderDeadline() {
+ c.dlMu.Lock()
+ defer c.dlMu.Unlock()
+ c.parsing = false
+ c.inner.SetReadDeadline(c.userRead)
+}
+
+// resolve runs the parse once. Callers that find it running wait on
+// parseMu; Close does not, and its close ends the running parse.
+func (c *Conn) resolve() State {
+ if s := State(c.state.Load()); s != StatePending {
+ return s
+ }
+ c.parseMu.Lock()
+ defer c.parseMu.Unlock()
+ if s := State(c.state.Load()); s != StatePending {
+ return s
+ }
+ s := c.parse()
+ c.state.Store(int64(s))
+ return s
+}
+
+// parse reads the signature byte by byte, stopping at the first byte that
+// differs, then at most one header, and decides the state (spec §4.3, §4.4).
+func (c *Conn) parse() State {
+ if c.trusted {
+ c.beginHeaderDeadline()
+ defer c.endHeaderDeadline()
+ }
+
+ var sig [len(Signature)]byte
+ n, full, err := c.detect(sig[:])
+ if !full {
+ if c.trusted && !mismatched(sig[:n]) {
+ // The read failed (err is set) before the stream could be
+ // told apart from a header: a trusted connection closes.
+ return c.fail(err)
+ }
+ // Not a header (or, untrusted, a read error before it could be
+ // told): hand the bytes and any error to the caller as they came.
+ c.readMu.Lock()
+ c.replay = append([]byte(nil), sig[:n]...)
+ c.readErr = err
+ c.readMu.Unlock()
+ if !c.trusted {
+ return StatePlain
+ }
+ c.l.c.noClient.Add(1)
+ return StateNoClient
+ }
+
+ if hook := c.l.cfg.ParseHook; hook != nil {
+ hook("signature-read")
+ }
+ // ReadHeader checks the signature again, so give it back the bytes
+ // already consumed ahead of the rest of the stream.
+ h, err := ReadHeader(io.MultiReader(bytes.NewReader(sig[:]), c.inner))
+ if err != nil {
+ return c.fail(err)
+ }
+
+ if !c.trusted {
+ c.l.c.ignored.Add(1)
+ if a := c.peer.Addr(); a.Is4() && a.IsPrivate() {
+ c.l.c.ignoredPrivate.Add(1)
+ }
+ return StatePlain
+ }
+ if h.Command != CommandProxy || !h.HasAddresses {
+ c.l.c.noClient.Add(1)
+ return StateNoClient
+ }
+ src := netip.AddrPortFrom(h.Source.Addr().Unmap(), h.Source.Port())
+ if !UsableSource(src.Addr()) {
+ c.l.c.malformed.Add(1)
+ return c.fail(fmt.Errorf("%w: %s", errUnusable, src.Addr()))
+ }
+ if c.l.cfg.Marker.Contains(src.Addr()) {
+ c.l.c.markerTrusted.Add(1)
+ return c.fail(fmt.Errorf("%w: %s", errMarker, src.Addr()))
+ }
+ // The barrier (spec §4.7): checked here, when the state resolves, so a
+ // header that completes after the barrier went up grants nothing.
+ if b := c.l.cfg.Barrier; b != nil && b() {
+ c.l.c.noClient.Add(1)
+ return StateNoClient
+ }
+ c.source = net.TCPAddrFromAddrPort(src)
+ c.l.c.addProxied(c.peer.Addr())
+ return StateProxied
+}
+
+// detect reads one byte at a time into sig until a byte differs from the
+// signature, the signature is complete, or a read fails. It returns the
+// bytes read, whether they are the full signature, and the read error.
+func (c *Conn) detect(sig []byte) (n int, full bool, err error) {
+ for n < len(sig) {
+ m, rerr := c.inner.Read(sig[n : n+1])
+ n += m
+ if m == 1 && sig[n-1] != Signature[n-1] {
+ return n, false, rerr
+ }
+ if rerr != nil {
+ return n, false, rerr
+ }
+ }
+ return n, true, nil
+}
+
+// mismatched reports whether b's last byte departs from the signature.
+func mismatched(b []byte) bool {
+ n := len(b)
+ return n > 0 && b[n-1] != Signature[n-1]
+}
+
+// fail closes the connection, counts a timeout or a refused header, and
+// returns StateFailed. A failure caused by our own Close is not counted.
+// Callers count marker and unusable-source refusals themselves.
+func (c *Conn) fail(cause error) State {
+ switch {
+ case errors.Is(cause, errMarker), errors.Is(cause, errUnusable):
+ case isTimeout(cause):
+ c.l.c.timeout.Add(1)
+ case errors.Is(cause, net.ErrClosed):
+ case errors.Is(cause, ErrMalformed):
+ c.l.c.malformed.Add(1)
+ }
+ c.failErr = fmt.Errorf("proxyproto: connection closed: %w", cause)
+ c.closeInner()
+ return StateFailed
+}
+
+func isTimeout(err error) bool {
+ if errors.Is(err, os.ErrDeadlineExceeded) {
+ return true
+ }
+ var ne net.Error
+ return errors.As(err, &ne) && ne.Timeout()
+}
diff --git a/internal/proxyproto/counters.go b/internal/proxyproto/counters.go
new file mode 100644
index 000000000..ef885901f
--- /dev/null
+++ b/internal/proxyproto/counters.go
@@ -0,0 +1,79 @@
+package proxyproto
+
+import (
+ "net/netip"
+ "sync"
+ "sync/atomic"
+)
+
+// Counters is a snapshot of one listener's counters since it was made
+// (spec §4.5).
+type Counters struct {
+ // Proxied: trusted connections that resolved to StateProxied.
+ Proxied uint64
+ // NoClient: trusted connections that resolved to StateNoClient (LOCAL,
+ // UNSPEC, no header, or a header completed while the barrier was up).
+ NoClient uint64
+ // NoClientRefused: requests refused on a no-client connection, counted
+ // by the caller through NoteRefused.
+ NoClientRefused uint64
+ // Ignored: untrusted connections whose well-formed header was consumed
+ // and ignored.
+ Ignored uint64
+ // IgnoredPrivate: the Ignored ones whose peer is an RFC 1918 address,
+ // most likely an NLB node missing from Trusted.
+ IgnoredPrivate uint64
+ // MarkerTrusted: trusted headers whose source is in Config.Marker.
+ MarkerTrusted uint64
+ // Malformed: headers refused (bad header, or an unusable source on a
+ // trusted connection).
+ Malformed uint64
+ // Timeout: headers not complete by their deadline.
+ Timeout uint64
+ // ProxiedByNode splits Proxied by the trusted peer address.
+ ProxiedByNode map[netip.Addr]uint64
+}
+
+type counters struct {
+ proxied atomic.Uint64
+ noClient atomic.Uint64
+ noClientRefused atomic.Uint64
+ ignored atomic.Uint64
+ ignoredPrivate atomic.Uint64
+ markerTrusted atomic.Uint64
+ malformed atomic.Uint64
+ timeout atomic.Uint64
+
+ mu sync.Mutex
+ byNode map[netip.Addr]uint64
+}
+
+func (c *counters) addProxied(node netip.Addr) {
+ c.proxied.Add(1)
+ c.mu.Lock()
+ if c.byNode == nil {
+ c.byNode = make(map[netip.Addr]uint64)
+ }
+ c.byNode[node]++
+ c.mu.Unlock()
+}
+
+func (c *counters) snapshot() Counters {
+ s := Counters{
+ Proxied: c.proxied.Load(),
+ NoClient: c.noClient.Load(),
+ NoClientRefused: c.noClientRefused.Load(),
+ Ignored: c.ignored.Load(),
+ IgnoredPrivate: c.ignoredPrivate.Load(),
+ MarkerTrusted: c.markerTrusted.Load(),
+ Malformed: c.malformed.Load(),
+ Timeout: c.timeout.Load(),
+ }
+ c.mu.Lock()
+ s.ProxiedByNode = make(map[netip.Addr]uint64, len(c.byNode))
+ for k, v := range c.byNode {
+ s.ProxiedByNode[k] = v
+ }
+ c.mu.Unlock()
+ return s
+}
diff --git a/internal/proxyproto/export_test.go b/internal/proxyproto/export_test.go
new file mode 100644
index 000000000..3362bacd3
--- /dev/null
+++ b/internal/proxyproto/export_test.go
@@ -0,0 +1,11 @@
+package proxyproto
+
+import "net/netip"
+
+// withPeer makes the listener see f(kernel peer) as each accepted
+// connection's peer, for trust and counters, so a test on loopback can
+// play an NLB node or a private-address client. Set it before Accept.
+func (l *Listener) withPeer(f func(kernel netip.AddrPort) netip.AddrPort) *Listener {
+ l.peerFor = f
+ return l
+}
diff --git a/internal/proxyproto/listener.go b/internal/proxyproto/listener.go
new file mode 100644
index 000000000..aa8dc26e7
--- /dev/null
+++ b/internal/proxyproto/listener.go
@@ -0,0 +1,159 @@
+package proxyproto
+
+import (
+ "net"
+ "net/netip"
+ "sync"
+ "time"
+)
+
+// DefaultHeaderTimeout is used when Config.HeaderTimeout is zero: the edge
+// listeners' ReadHeaderTimeout (spec §4.3).
+const DefaultHeaderTimeout = 10 * time.Second
+
+// Config sets how a Listener treats its connections.
+type Config struct {
+ // Trusted lists the peer addresses (the kernel's, before any rewrite)
+ // whose header is believed: the NLB nodes' private addresses. A peer
+ // not in the list is untrusted, whatever it sends.
+ Trusted []netip.Addr
+ // HeaderTimeout bounds, from accept, how long a trusted connection may
+ // take to send its header. Zero means DefaultHeaderTimeout.
+ HeaderTimeout time.Duration
+ // Marker is the forgery probe's source range (spec §6.4). A trusted
+ // header whose source is inside it closes the connection.
+ Marker netip.Prefix
+ // Barrier reports whether the trust barrier is up (spec §4.7). It is
+ // asked once, when a trusted connection's state resolves; while it is
+ // up a header grants no identity. Nil means never up.
+ Barrier func() bool
+ // Now gives the accept time. Nil means time.Now.
+ Now func() time.Time
+ // ParseHook is a test seam and is nil in production. When set, the
+ // parser calls it on the connection's goroutine with "signature-read"
+ // after it has consumed the 12-byte signature and before it reads the
+ // header's fixed part, so a test can hold a parse mid-header.
+ ParseHook func(stage string)
+}
+
+// Listener wraps a net.Listener so that each accepted connection resolves a
+// PPv2 parse state on its own goroutine (spec §4.3). Accept never reads.
+type Listener struct {
+ inner net.Listener
+ cfg Config
+ trusted map[netip.Addr]struct{}
+ c counters
+
+ mu sync.Mutex
+ live map[*Conn]struct{} // trusted connections not yet closed
+
+ // peerFor replaces the kernel peer; set only by tests.
+ peerFor func(kernel netip.AddrPort) netip.AddrPort
+}
+
+// NewListener wraps inner with cfg.
+func NewListener(inner net.Listener, cfg Config) *Listener {
+ if cfg.HeaderTimeout <= 0 {
+ cfg.HeaderTimeout = DefaultHeaderTimeout
+ }
+ if cfg.Now == nil {
+ cfg.Now = time.Now
+ }
+ trusted := make(map[netip.Addr]struct{}, len(cfg.Trusted))
+ for _, a := range cfg.Trusted {
+ trusted[a.Unmap()] = struct{}{}
+ }
+ return &Listener{
+ inner: inner,
+ cfg: cfg,
+ trusted: trusted,
+ live: make(map[*Conn]struct{}),
+ }
+}
+
+// Accept returns the next connection as a *Conn at once; it reads nothing.
+// A trusted connection is registered for CloseTrusted until it is closed.
+func (l *Listener) Accept() (net.Conn, error) {
+ inner, err := l.inner.Accept()
+ if err != nil {
+ return nil, err
+ }
+ remote := inner.RemoteAddr()
+ peer := addrPortOf(remote)
+ if l.peerFor != nil {
+ peer = l.peerFor(peer)
+ remote = net.TCPAddrFromAddrPort(peer)
+ }
+ _, trusted := l.trusted[peer.Addr()]
+ c := &Conn{
+ inner: inner,
+ l: l,
+ peer: peer,
+ remote: remote,
+ trusted: trusted,
+ accepted: l.cfg.Now(),
+ }
+ if trusted {
+ l.mu.Lock()
+ l.live[c] = struct{}{}
+ l.mu.Unlock()
+ }
+ return c, nil
+}
+
+// Close closes the inner listener. Accepted connections are not closed.
+func (l *Listener) Close() error { return l.inner.Close() }
+
+// Addr is the inner listener's address.
+func (l *Listener) Addr() net.Addr { return l.inner.Addr() }
+
+// CloseTrusted closes every live trusted connection, pending ones included,
+// and returns how many it closed. Untrusted connections are left alone.
+// Callers raise the barrier first, so a connection accepted after the
+// snapshot resolves to no-client anyway (spec §4.7).
+func (l *Listener) CloseTrusted() int {
+ l.mu.Lock()
+ conns := make([]*Conn, 0, len(l.live))
+ for c := range l.live {
+ conns = append(conns, c)
+ }
+ l.mu.Unlock()
+ n := 0
+ for _, c := range conns {
+ if closed, _ := c.closeInner(); closed {
+ n++
+ }
+ }
+ return n
+}
+
+// Counters returns a copy of the listener's counters.
+func (l *Listener) Counters() Counters { return l.c.snapshot() }
+
+// NoteRefused counts one request refused on a no-client connection.
+func (l *Listener) NoteRefused() { l.c.noClientRefused.Add(1) }
+
+func (l *Listener) forget(c *Conn) {
+ l.mu.Lock()
+ delete(l.live, c)
+ l.mu.Unlock()
+}
+
+// addrPortOf is the address and port of a, with an IPv4-mapped IPv6 address
+// unmapped. Anything unparsable is the zero value, which is never trusted.
+func addrPortOf(a net.Addr) netip.AddrPort {
+ var ap netip.AddrPort
+ switch t := a.(type) {
+ case *net.TCPAddr:
+ ap = t.AddrPort()
+ case nil:
+ return netip.AddrPort{}
+ default:
+ p, err := netip.ParseAddrPort(a.String())
+ if err != nil {
+ return netip.AddrPort{}
+ }
+ ap = p
+ }
+ return netip.AddrPortFrom(ap.Addr().Unmap(), ap.Port())
+}
diff --git a/internal/proxyproto/listener_test.go b/internal/proxyproto/listener_test.go
new file mode 100644
index 000000000..71366bd40
--- /dev/null
+++ b/internal/proxyproto/listener_test.go
@@ -0,0 +1,526 @@
+package proxyproto
+
+import (
+ "bytes"
+ "io"
+ "net"
+ "net/netip"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+var loopback = []netip.Addr{netip.MustParseAddr("127.0.0.1")}
+
+// listen wraps a real loopback listener with cfg.
+func listen(t *testing.T, cfg Config) *Listener {
+ t.Helper()
+ inner, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("listen: %v", err)
+ }
+ l := NewListener(inner, cfg)
+ t.Cleanup(func() { l.Close() })
+ return l
+}
+
+// dial connects a client to l.
+func dial(t *testing.T, l *Listener) net.Conn {
+ t.Helper()
+ c, err := net.Dial("tcp", l.Addr().String())
+ if err != nil {
+ t.Fatalf("dial: %v", err)
+ }
+ t.Cleanup(func() { c.Close() })
+ return c
+}
+
+// accept returns the next wrapped connection, failing if Accept takes
+// longer than a second (it must never wait on the client).
+func accept(t *testing.T, l *Listener) *Conn {
+ t.Helper()
+ type res struct {
+ c net.Conn
+ err error
+ }
+ ch := make(chan res, 1)
+ go func() {
+ c, err := l.Accept()
+ ch <- res{c, err}
+ }()
+ select {
+ case r := <-ch:
+ if r.err != nil {
+ t.Fatalf("accept: %v", r.err)
+ }
+ pc, ok := r.c.(*Conn)
+ if !ok {
+ t.Fatalf("accept returned %T, want *Conn", r.c)
+ }
+ t.Cleanup(func() { pc.Close() })
+ return pc
+ case <-time.After(time.Second):
+ t.Fatal("accept did not return within 1s")
+ return nil
+ }
+}
+
+// pair dials l and accepts the connection.
+func pair(t *testing.T, l *Listener) (client net.Conn, server *Conn) {
+ t.Helper()
+ client = dial(t, l)
+ return client, accept(t, l)
+}
+
+func write(t *testing.T, c net.Conn, b []byte) {
+ t.Helper()
+ if _, err := c.Write(b); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+}
+
+// readExactly reads len(want) bytes from c within a second and compares.
+func readExactly(t *testing.T, c net.Conn, want []byte) {
+ t.Helper()
+ c.SetReadDeadline(time.Now().Add(time.Second))
+ defer c.SetReadDeadline(time.Time{})
+ got := make([]byte, len(want))
+ if _, err := io.ReadFull(c, got); err != nil {
+ t.Fatalf("read: %v (got %q)", err, got)
+ }
+ if !bytes.Equal(got, want) {
+ t.Fatalf("read %q, want %q", got, want)
+ }
+}
+
+// stateWithin resolves c's state on another goroutine and fails if that
+// takes longer than d.
+func stateWithin(t *testing.T, c *Conn, d time.Duration) State {
+ t.Helper()
+ ch := make(chan State, 1)
+ go func() { ch <- c.State() }()
+ select {
+ case s := <-ch:
+ return s
+ case <-time.After(d):
+ t.Fatalf("State() did not resolve within %v", d)
+ return StatePending
+ }
+}
+
+// expectClosed checks the client side sees the server close the connection.
+func expectClosed(t *testing.T, client net.Conn) {
+ t.Helper()
+ client.SetReadDeadline(time.Now().Add(time.Second))
+ var b [1]byte
+ n, err := client.Read(b[:])
+ if err == nil || n != 0 {
+ t.Fatalf("client read = %d, %v; want the connection closed", n, err)
+ }
+ if ne, ok := err.(net.Error); ok && ne.Timeout() {
+ t.Fatalf("client read timed out; want the connection closed")
+ }
+}
+
+func proxyHeader(src string) []byte {
+ return build(0x1, 0x11, src, "54.77.110.223:443", nil)
+}
+
+func TestTrustedProxyRewritesRemoteAddr(t *testing.T) {
+ l := listen(t, Config{Trusted: loopback, HeaderTimeout: 5 * time.Second})
+ client, c := pair(t, l)
+ write(t, client, append(proxyHeader("203.0.113.7:51000"), "GET"...))
+
+ if got := c.RemoteAddr().String(); got != "203.0.113.7:51000" {
+ t.Fatalf("RemoteAddr = %s, want 203.0.113.7:51000", got)
+ }
+ if s := c.State(); s != StateProxied {
+ t.Fatalf("State = %v, want proxied", s)
+ }
+ if !c.Trusted() {
+ t.Fatal("Trusted = false, want true")
+ }
+ if got, want := c.Peer().String(), client.LocalAddr().String(); got != want {
+ t.Fatalf("Peer = %s, want the kernel peer %s", got, want)
+ }
+ readExactly(t, c, []byte("GET"))
+ cn := l.Counters()
+ if cn.Proxied != 1 {
+ t.Fatalf("Proxied = %d, want 1", cn.Proxied)
+ }
+ if n := cn.ProxiedByNode[netip.MustParseAddr("127.0.0.1")]; n != 1 {
+ t.Fatalf("ProxiedByNode[127.0.0.1] = %d, want 1", n)
+ }
+}
+
+func TestUntrustedHeaderIgnored(t *testing.T) {
+ l := listen(t, Config{HeaderTimeout: 5 * time.Second})
+ client, c := pair(t, l)
+ write(t, client, append(proxyHeader("203.0.113.7:51000"), "GET"...))
+
+ if got, want := c.RemoteAddr().String(), client.LocalAddr().String(); got != want {
+ t.Fatalf("RemoteAddr = %s, want the kernel peer %s", got, want)
+ }
+ readExactly(t, c, []byte("GET"))
+ if s := c.State(); s != StatePlain {
+ t.Fatalf("State = %v, want plain", s)
+ }
+ cn := l.Counters()
+ if cn.Ignored != 1 || cn.IgnoredPrivate != 0 || cn.Proxied != 0 {
+ t.Fatalf("counters = %+v, want Ignored 1 only", cn)
+ }
+}
+
+func TestUntrustedPrivateHeaderCounted(t *testing.T) {
+ l := listen(t, Config{HeaderTimeout: 5 * time.Second}).withPeer(func(k netip.AddrPort) netip.AddrPort {
+ return netip.AddrPortFrom(netip.MustParseAddr("172.31.99.9"), k.Port())
+ })
+ client, c := pair(t, l)
+ write(t, client, append(proxyHeader("203.0.113.7:51000"), "GET"...))
+
+ readExactly(t, c, []byte("GET"))
+ if got := c.Peer().Addr().String(); got != "172.31.99.9" {
+ t.Fatalf("Peer = %s, want 172.31.99.9", got)
+ }
+ if c.Trusted() {
+ t.Fatal("Trusted = true, want false")
+ }
+ cn := l.Counters()
+ if cn.Ignored != 1 || cn.IgnoredPrivate != 1 {
+ t.Fatalf("Ignored = %d, IgnoredPrivate = %d, want 1 and 1", cn.Ignored, cn.IgnoredPrivate)
+ }
+}
+
+func TestUntrustedMalformedClosed(t *testing.T) {
+ l := listen(t, Config{HeaderTimeout: 5 * time.Second})
+ client, c := pair(t, l)
+ bad := proxyHeader("203.0.113.7:51000")
+ bad[12] = 0x11 // version 1
+ write(t, client, bad)
+
+ if s := stateWithin(t, c, time.Second); s != StateFailed {
+ t.Fatalf("State = %v, want failed", s)
+ }
+ expectClosed(t, client)
+ if n := l.Counters().Malformed; n != 1 {
+ t.Fatalf("Malformed = %d, want 1", n)
+ }
+}
+
+func TestNoSignaturePassthrough(t *testing.T) {
+ data := []byte("\x16\x03\x01\x02\x00hello")
+ for _, tc := range []struct {
+ name string
+ trusted []netip.Addr
+ want State
+ }{
+ {"untrusted", nil, StatePlain},
+ {"trusted", loopback, StateNoClient},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ l := listen(t, Config{Trusted: tc.trusted, HeaderTimeout: 5 * time.Second})
+ client, c := pair(t, l)
+ write(t, client, data)
+ readExactly(t, c, data)
+ if s := c.State(); s != tc.want {
+ t.Fatalf("State = %v, want %v", s, tc.want)
+ }
+ if got, want := c.RemoteAddr().String(), client.LocalAddr().String(); got != want {
+ t.Fatalf("RemoteAddr = %s, want the kernel peer %s", got, want)
+ }
+ cn := l.Counters()
+ if tc.want == StateNoClient && cn.NoClient != 1 {
+ t.Fatalf("NoClient = %d, want 1", cn.NoClient)
+ }
+ if cn.Proxied != 0 || cn.Ignored != 0 || cn.Malformed != 0 {
+ t.Fatalf("counters = %+v, want no header counted", cn)
+ }
+ })
+ }
+}
+
+// TestSignaturePrefixReplayed: a stream that matches the signature for
+// several bytes and then differs is replayed whole, on a trusted connection.
+func TestTrustedSignaturePrefixReplayed(t *testing.T) {
+ data := []byte("\r\n\r\nGET / HTTP/1.1\r\n")
+ l := listen(t, Config{Trusted: loopback, HeaderTimeout: 5 * time.Second})
+ client, c := pair(t, l)
+ write(t, client, data)
+ readExactly(t, c, data)
+ if s := c.State(); s != StateNoClient {
+ t.Fatalf("State = %v, want no-client", s)
+ }
+}
+
+func TestLocalHeaderNoClient(t *testing.T) {
+ l := listen(t, Config{Trusted: loopback, HeaderTimeout: 5 * time.Second})
+ client, c := pair(t, l)
+ write(t, client, append(build(0x0, 0x00, "", "", nil), "GET"...))
+
+ if s := c.State(); s != StateNoClient {
+ t.Fatalf("State = %v, want no-client", s)
+ }
+ if got, want := c.RemoteAddr().String(), client.LocalAddr().String(); got != want {
+ t.Fatalf("RemoteAddr = %s, want the kernel peer %s", got, want)
+ }
+ readExactly(t, c, []byte("GET"))
+ if n := l.Counters().NoClient; n != 1 {
+ t.Fatalf("NoClient = %d, want 1", n)
+ }
+}
+
+func TestSecondHeaderIsPayload(t *testing.T) {
+ l := listen(t, Config{Trusted: loopback, HeaderTimeout: 5 * time.Second})
+ client, c := pair(t, l)
+ second := proxyHeader("198.51.100.4:4000")
+ write(t, client, append(proxyHeader("203.0.113.7:51000"), second...))
+
+ if got := c.RemoteAddr().String(); got != "203.0.113.7:51000" {
+ t.Fatalf("RemoteAddr = %s, want the first header's source", got)
+ }
+ readExactly(t, c, second)
+ if n := l.Counters().Proxied; n != 1 {
+ t.Fatalf("Proxied = %d, want 1", n)
+ }
+}
+
+func TestMarkerSourceClosed(t *testing.T) {
+ l := listen(t, Config{
+ Trusted: loopback,
+ HeaderTimeout: 5 * time.Second,
+ Marker: netip.MustParsePrefix("192.0.2.0/24"),
+ })
+ client, c := pair(t, l)
+ write(t, client, append(proxyHeader("192.0.2.1:4000"), "GET"...))
+
+ if s := stateWithin(t, c, time.Second); s != StateFailed {
+ t.Fatalf("State = %v, want failed", s)
+ }
+ expectClosed(t, client)
+ cn := l.Counters()
+ if cn.MarkerTrusted != 1 || cn.Proxied != 0 {
+ t.Fatalf("MarkerTrusted = %d, Proxied = %d, want 1 and 0", cn.MarkerTrusted, cn.Proxied)
+ }
+}
+
+func TestTrustedUnusableSourceClosed(t *testing.T) {
+ l := listen(t, Config{Trusted: loopback, HeaderTimeout: 5 * time.Second})
+ client, c := pair(t, l)
+ write(t, client, append(proxyHeader("127.0.0.9:4000"), "GET"...))
+
+ if s := stateWithin(t, c, time.Second); s != StateFailed {
+ t.Fatalf("State = %v, want failed", s)
+ }
+ expectClosed(t, client)
+ cn := l.Counters()
+ if cn.Malformed != 1 || cn.Proxied != 0 {
+ t.Fatalf("Malformed = %d, Proxied = %d, want 1 and 0", cn.Malformed, cn.Proxied)
+ }
+}
+
+func TestTrustedHeaderTimeout(t *testing.T) {
+ l := listen(t, Config{Trusted: loopback, HeaderTimeout: 50 * time.Millisecond})
+ client, c := pair(t, l)
+
+ if s := stateWithin(t, c, time.Second); s != StateFailed {
+ t.Fatalf("State = %v, want failed", s)
+ }
+ expectClosed(t, client)
+ if n := l.Counters().Timeout; n != 1 {
+ t.Fatalf("Timeout = %d, want 1", n)
+ }
+}
+
+// TestTrustedHeaderTimeoutPartial: half a header, then silence.
+func TestTrustedHeaderTimeoutPartial(t *testing.T) {
+ l := listen(t, Config{Trusted: loopback, HeaderTimeout: 50 * time.Millisecond})
+ client, c := pair(t, l)
+ write(t, client, proxyHeader("203.0.113.7:51000")[:20])
+
+ if s := stateWithin(t, c, time.Second); s != StateFailed {
+ t.Fatalf("State = %v, want failed", s)
+ }
+ expectClosed(t, client)
+ cn := l.Counters()
+ if cn.Timeout != 1 || cn.Malformed != 0 {
+ t.Fatalf("Timeout = %d, Malformed = %d, want 1 and 0", cn.Timeout, cn.Malformed)
+ }
+}
+
+func TestSilentTrustedDoesNotBlockAccept(t *testing.T) {
+ l := listen(t, Config{Trusted: loopback, HeaderTimeout: 10 * time.Second})
+ _, silent := pair(t, l)
+
+ client, c := pair(t, l)
+ write(t, client, append(proxyHeader("203.0.113.7:51000"), "GET"...))
+ if s := stateWithin(t, c, time.Second); s != StateProxied {
+ t.Fatalf("second connection State = %v, want proxied", s)
+ }
+ if s := State(silent.state.Load()); s != StatePending {
+ t.Fatalf("silent connection state = %v, want still pending", s)
+ }
+}
+
+func TestCloseDuringPendingParse(t *testing.T) {
+ l := listen(t, Config{Trusted: loopback, HeaderTimeout: 10 * time.Second})
+ client, c := pair(t, l)
+ write(t, client, []byte(Signature)[:5]) // a partial signature, then silence
+
+ got := make(chan State, 1)
+ go func() { got <- c.State() }()
+ time.Sleep(50 * time.Millisecond) // let State() block in the read
+
+ closed := make(chan error, 1)
+ go func() { closed <- c.Close() }()
+ select {
+ case <-closed:
+ case <-time.After(100 * time.Millisecond):
+ t.Fatal("Close did not return within 100ms")
+ }
+ select {
+ case s := <-got:
+ if s != StateFailed {
+ t.Fatalf("State = %v, want failed", s)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("State() did not return after Close")
+ }
+ cn := l.Counters()
+ if cn.Timeout != 0 || cn.Malformed != 0 {
+ t.Fatalf("counters = %+v, want a local close counted nowhere", cn)
+ }
+}
+
+// TestBarrierPendingHeaderCompletesAsNoClient is mandatory race test (a),
+// spec §9: a trusted connection is mid-header (signature consumed, fixed
+// part not yet read) when the barrier goes up; it then completes a valid
+// PROXY header and must resolve to no-client, without CloseTrusted.
+func TestBarrierPendingHeaderCompletesAsNoClient(t *testing.T) {
+ var barrier atomic.Bool
+ reached := make(chan string, 1)
+ release := make(chan struct{})
+ l := listen(t, Config{
+ Trusted: loopback,
+ HeaderTimeout: 10 * time.Second,
+ Barrier: barrier.Load,
+ ParseHook: func(stage string) {
+ reached <- stage
+ <-release
+ },
+ })
+ client, c := pair(t, l)
+ header := proxyHeader("203.0.113.7:51000")
+ write(t, client, header[:12]) // the signature only
+
+ got := make(chan State, 1)
+ go func() { got <- c.State() }()
+ select {
+ case stage := <-reached:
+ if stage != "signature-read" {
+ t.Fatalf("hook stage = %q, want signature-read", stage)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("the parse never reached signature-read")
+ }
+ if s := State(c.state.Load()); s != StatePending {
+ t.Fatalf("state at the hook = %v, want pending", s)
+ }
+
+ barrier.Store(true)
+ write(t, client, append(header[12:], "GET"...))
+ close(release)
+
+ select {
+ case s := <-got:
+ if s != StateNoClient {
+ t.Fatalf("State = %v, want no-client", s)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("State() did not resolve")
+ }
+ if got, want := c.RemoteAddr().String(), client.LocalAddr().String(); got != want {
+ t.Fatalf("RemoteAddr = %s, want the kernel peer %s", got, want)
+ }
+ readExactly(t, c, []byte("GET"))
+ cn := l.Counters()
+ if cn.Proxied != 0 || len(cn.ProxiedByNode) != 0 {
+ t.Fatalf("Proxied = %d, ProxiedByNode = %v, want none", cn.Proxied, cn.ProxiedByNode)
+ }
+ if cn.NoClient != 1 {
+ t.Fatalf("NoClient = %d, want 1", cn.NoClient)
+ }
+}
+
+// TestBarrierLaterAcceptIsNoClient is mandatory race test (b), spec §9: a
+// trusted connection accepted after the barrier is up, with a valid header,
+// resolves to no-client.
+func TestBarrierLaterAcceptIsNoClient(t *testing.T) {
+ l := listen(t, Config{
+ Trusted: loopback,
+ HeaderTimeout: 10 * time.Second,
+ Barrier: func() bool { return true },
+ })
+ client, c := pair(t, l)
+ write(t, client, append(proxyHeader("203.0.113.7:51000"), "GET"...))
+
+ if s := stateWithin(t, c, time.Second); s != StateNoClient {
+ t.Fatalf("State = %v, want no-client", s)
+ }
+ if got, want := c.RemoteAddr().String(), client.LocalAddr().String(); got != want {
+ t.Fatalf("RemoteAddr = %s, want the kernel peer %s", got, want)
+ }
+ readExactly(t, c, []byte("GET"))
+ if n := l.Counters().Proxied; n != 0 {
+ t.Fatalf("Proxied = %d, want 0", n)
+ }
+}
+
+func TestCloseTrustedClosesPendingAndOpen(t *testing.T) {
+ untrustedPort := make(chan uint16, 1)
+ l := listen(t, Config{Trusted: loopback, HeaderTimeout: 10 * time.Second})
+ l.withPeer(func(k netip.AddrPort) netip.AddrPort {
+ select {
+ case p := <-untrustedPort:
+ if p == k.Port() {
+ return netip.AddrPortFrom(netip.MustParseAddr("198.51.100.9"), k.Port())
+ }
+ untrustedPort <- p
+ default:
+ }
+ return k
+ })
+
+ pendingClient, pending := pair(t, l)
+
+ openClient, open := pair(t, l)
+ write(t, openClient, append(proxyHeader("203.0.113.7:51000"), "GET"...))
+ if s := stateWithin(t, open, time.Second); s != StateProxied {
+ t.Fatalf("open State = %v, want proxied", s)
+ }
+
+ plainClient := dial(t, l)
+ untrustedPort <- netip.MustParseAddrPort(plainClient.LocalAddr().String()).Port()
+ plain := accept(t, l)
+ if plain.Trusted() {
+ t.Fatal("the third connection is trusted; want untrusted")
+ }
+
+ if n := l.CloseTrusted(); n != 2 {
+ t.Fatalf("CloseTrusted = %d, want 2", n)
+ }
+ expectClosed(t, pendingClient)
+ expectClosed(t, openClient)
+ if s := stateWithin(t, pending, time.Second); s != StateFailed {
+ t.Fatalf("pending State = %v, want failed", s)
+ }
+
+ write(t, plainClient, []byte("hello"))
+ readExactly(t, plain, []byte("hello"))
+ if s := plain.State(); s != StatePlain {
+ t.Fatalf("plain State = %v, want plain", s)
+ }
+
+ if n := l.CloseTrusted(); n != 0 {
+ t.Fatalf("second CloseTrusted = %d, want 0 (closed conns leave the registry)", n)
+ }
+}