carlos / platform Public

edge: barrier holds on write failure, bars open proxied conns

RaiseTrustBarrier sets the flag and sweeps even when the barrier file
cannot be written, returning ErrBarrierNotPersisted. The gate treats any
trusted connection as no-client while the barrier is up, so a proxied
keep-alive or HTTP/2 connection the sweep has not reached gets no
identity past the flag. Tests pin flag and file before every sweep
close, the unwritable data dir, and the open proxied connection; the
limiter test runs on a fixed clock.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 45bfd14e08fad3524cbb7af0a29d6b4bcd88937c parent 8992f0c
2 files changed, +191 −6
  • internal/edge/proxyingress.go +19 −6
  • internal/edge/proxyingress_test.go +172 −0
diff --git a/internal/edge/proxyingress.go b/internal/edge/proxyingress.go
index 97a7b738b..906ae7a4f 100644
--- a/internal/edge/proxyingress.go
+++ b/internal/edge/proxyingress.go
@@ -46,6 +46,11 @@ const proxyJournalEvery = time.Minute
// armed for PROXY protocol at start.
var ErrProxyProtocolOff = errors.New("edge: this box is not armed for PROXY protocol")
+// ErrBarrierNotPersisted is RaiseTrustBarrier's error when the barrier is
+// up in the running edge but its file could not be written: a restart
+// would come up with it down.
+var ErrBarrierNotPersisted = errors.New("edge: trust barrier raised in the running edge, not persisted")
+
// proxyIngress is an armed edge's PROXY protocol state.
type proxyIngress struct {
trusted []netip.Addr // sorted
@@ -175,7 +180,9 @@ func proxyConnOf(c net.Conn) *proxyproto.Conn {
// 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
+// no header from a node, or any header while the barrier is up), or on any
+// trusted connection while the barrier is up (a proxied one the sweep has
+// not closed yet keeps no identity past the flag), 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
@@ -188,7 +195,7 @@ func proxyConnOf(c net.Conn) *proxyproto.Conn {
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 {
+ if pc != nil && pc.State() != proxyproto.StateNoClient && !(pc.Trusted() && p.barrier.Load()) {
next.ServeHTTP(w, r)
return
}
@@ -215,7 +222,13 @@ func (e *Edge) noClientGate(p *proxyIngress, l *proxyproto.Listener, health bool
// 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.
+// grants nothing, and a proxied connection the sweep has not reached yet
+// is refused by the gate. Calling it again rewrites the file and sweeps
+// again.
+//
+// A failed write does not stop the raise: the flag is set and the sweep
+// runs all the same, so the live edge is barred, and the error (wrapping
+// ErrBarrierNotPersisted) says a restart may come up without it.
func (e *Edge) RaiseTrustBarrier() (closed int, err error) {
p := e.proxy.Load()
if p == nil {
@@ -223,8 +236,8 @@ func (e *Edge) RaiseTrustBarrier() (closed int, err error) {
}
p.mu.Lock()
defer p.mu.Unlock()
- if err := writeBarrierFile(p.barrierPath); err != nil {
- return 0, err
+ if werr := writeBarrierFile(p.barrierPath); werr != nil {
+ err = fmt.Errorf("%w: %w", ErrBarrierNotPersisted, werr)
}
p.barrier.Store(true)
for _, l := range []*proxyproto.Listener{p.http.Load(), p.https.Load()} {
@@ -232,7 +245,7 @@ func (e *Edge) RaiseTrustBarrier() (closed int, err error) {
closed += l.CloseTrusted()
}
}
- return closed, nil
+ return closed, err
}
// ResumeTrust lowers the barrier: it removes the file (and syncs its
diff --git a/internal/edge/proxyingress_test.go b/internal/edge/proxyingress_test.go
index 8ed2bd7a0..1d513ca79 100644
--- a/internal/edge/proxyingress_test.go
+++ b/internal/edge/proxyingress_test.go
@@ -14,8 +14,10 @@ import (
"net/http/httptest"
"net/netip"
"os"
+ "path/filepath"
"reflect"
"strings"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -23,6 +25,7 @@ import (
"github.com/carlosframework/platform/internal/hairpin"
"github.com/carlosframework/platform/internal/lbhealth"
"github.com/carlosframework/platform/internal/proxyproto"
+ "github.com/carlosframework/platform/internal/ratelimit"
"github.com/carlosframework/platform/internal/registry"
)
@@ -50,6 +53,8 @@ type proxyOpts struct {
https, challenge http.Handler
hairpin *hairpin.Config
connState func(net.Conn, http.ConnState)
+ // inner, when set, wraps each raw listener before anything else.
+ inner func(net.Listener) net.Listener
}
// proxyEdge is the edge's two public servers wired as Serve wires them:
@@ -85,6 +90,9 @@ func newProxyEdge(t *testing.T, e *Edge, o proxyOpts) *proxyEdge {
}
pe := &proxyEdge{e: e, https: httpsSrv, http: httpSrv, pool: pool,
httpsAddr: httpsLn.Addr().String(), httpAddr: httpLn.Addr().String()}
+ if o.inner != nil {
+ httpsLn, httpLn = o.inner(httpsLn), o.inner(httpLn)
+ }
if o.hairpin != nil {
// Loopback cannot bind 80 and 443; the socket's destination port
// is all the hairpin classifier reads from them.
@@ -250,6 +258,10 @@ func TestProxiedRequestReachesLimiterAndXFF(t *testing.T) {
t.Setenv("CARLOS_RATE_LIMIT", "enforce")
up, hits := echoXFF(t)
e := ppEdge(t, rlRoute(up, `{"rate":1,"burst":1}`))
+ // A fixed clock: the bucket never refills between the two requests,
+ // however slow the handshakes are.
+ fixed := time.Now()
+ e.rateLimiter = ratelimit.NewLimiter(func() time.Time { return fixed }, 100_000)
armed(t, e, ppLoopback, t.TempDir())
logs := &lockedBuffer{}
prev := log.Writer()
@@ -753,3 +765,163 @@ func TestProxyJournalLines(t *testing.T) {
t.Fatalf("unarmed journal: %q", lines)
}
}
+
+// closeSpy wraps a raw listener so each accepted connection records, when
+// it is closed, whether the barrier was up and its file present: what the
+// sweep inside RaiseTrustBarrier saw.
+type closeSpy struct {
+ net.Listener
+ e *Edge
+ dataDir string
+ mu sync.Mutex
+ seen []closeSeen
+}
+
+type closeSeen struct{ barrier, file bool }
+
+type spyConn struct {
+ net.Conn
+ s *closeSpy
+ once sync.Once
+}
+
+func (l *closeSpy) Accept() (net.Conn, error) {
+ c, err := l.Listener.Accept()
+ if err != nil {
+ return nil, err
+ }
+ return &spyConn{Conn: c, s: l}, nil
+}
+
+func (c *spyConn) Close() error {
+ c.once.Do(func() {
+ _, err := os.Stat(barrierFile(c.s.dataDir))
+ c.s.mu.Lock()
+ c.s.seen = append(c.s.seen, closeSeen{barrier: c.s.e.TrustBarrierUp(), file: err == nil})
+ c.s.mu.Unlock()
+ })
+ return c.Conn.Close()
+}
+
+func (l *closeSpy) closes() []closeSeen {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return append([]closeSeen(nil), l.seen...)
+}
+
+// The barrier is persisted and up before the sweep closes anything: every
+// connection RaiseTrustBarrier closes, open or pending, sees both.
+func TestRaiseTrustBarrierFlagBeforeSweep(t *testing.T) {
+ dataDir := t.TempDir()
+ e := ppEdge(t, rlRoute(func() string { a, _ := echoXFF(t); return a }(), ""))
+ armed(t, e, ppLoopback, dataDir)
+ var spies []*closeSpy
+ news, hook := connsNew()
+ pe := newProxyEdge(t, e, proxyOpts{connState: hook, inner: func(ln net.Listener) net.Listener {
+ s := &closeSpy{Listener: ln, e: e, dataDir: dataDir}
+ spies = append(spies, s)
+ return s
+ }})
+ open := pe.dial(t, false, ppv2Proxy("203.0.113.7:51000"))
+ waitNew(t, news, 1)
+ // :80's ordinary answer for an instance host is the https redirect.
+ if res := pe.request(t, open, false, http.MethodGet, rlHost, "/"); res.status != http.StatusFound || res.connClose {
+ t.Fatalf("proxied request: %d close %v %q, want the redirect, kept open", res.status, res.connClose, res.body)
+ }
+ pending := pe.dial(t, true, ppv2Proxy("203.0.113.7:51001")[:14])
+ waitNew(t, news, 1)
+
+ closed, err := e.RaiseTrustBarrier()
+ if err != nil || closed != 2 {
+ t.Fatalf("RaiseTrustBarrier: %d, %v; want 2 closed", closed, err)
+ }
+ var seen []closeSeen
+ for _, s := range spies {
+ seen = append(seen, s.closes()...)
+ }
+ if len(seen) != 2 {
+ t.Fatalf("closes seen during the sweep: %v, want 2", seen)
+ }
+ for i, c := range seen {
+ if !c.barrier || !c.file {
+ t.Fatalf("close %d: barrier up %v, file present %v; want both before the sweep", i, c.barrier, c.file)
+ }
+ }
+ wantClosedWithin(t, open, 2*time.Second, "the open proxied connection")
+ wantClosedWithin(t, pending, 2*time.Second, "the pending connection")
+}
+
+// A barrier whose file cannot be written still bars the running edge: the
+// flag is up and trusted connections are closed, and the error says it was
+// not persisted.
+func TestRaiseTrustBarrierUnwritableStillRaises(t *testing.T) {
+ dataDir := t.TempDir()
+ e := ppEdge(t, rlRoute(func() string { a, _ := echoXFF(t); return a }(), ""))
+ armed(t, e, ppLoopback, dataDir)
+ // <data>/edge is a file, so the barrier's directory cannot be made,
+ // whoever the test runs as.
+ if err := os.WriteFile(filepath.Join(dataDir, "edge"), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ news, hook := connsNew()
+ pe := newProxyEdge(t, e, proxyOpts{connState: hook})
+ open := pe.dial(t, false, ppv2Proxy("203.0.113.7:51000"))
+ waitNew(t, news, 1)
+ // :80's ordinary answer for an instance host is the https redirect.
+ if res := pe.request(t, open, false, http.MethodGet, rlHost, "/"); res.status != http.StatusFound || res.connClose {
+ t.Fatalf("proxied request: %d close %v %q, want the redirect, kept open", res.status, res.connClose, res.body)
+ }
+ pending := pe.dial(t, true, ppv2Proxy("203.0.113.7:51001")[:14])
+ waitNew(t, news, 1)
+
+ closed, err := e.RaiseTrustBarrier()
+ if !errors.Is(err, ErrBarrierNotPersisted) {
+ t.Fatalf("RaiseTrustBarrier error: %v, want ErrBarrierNotPersisted", err)
+ }
+ if closed != 2 {
+ t.Fatalf("closed %d, want 2", closed)
+ }
+ if !e.TrustBarrierUp() {
+ t.Fatal("barrier down after a raise whose file failed")
+ }
+ wantClosedWithin(t, open, 2*time.Second, "the open proxied connection")
+ wantClosedWithin(t, pending, 2*time.Second, "the pending connection")
+ wantNoClientRefused(t, pe.exchange(t, false, ppv2Proxy("203.0.113.7:51002"), http.MethodGet, rlHost, "/"), "a proxied request after the raise")
+}
+
+// A proxied connection the sweep has not reached yet gets no identity
+// past the flag: its next request is refused, on :80 and on :443, while
+// :80's health check is still answered.
+func TestBarrierRefusesOpenProxiedConnection(t *testing.T) {
+ up, hits := echoXFF(t)
+ e := ppEdge(t, rlRoute(up, ""))
+ e.lbHealth = healthyState()
+ p := armed(t, e, ppLoopback, t.TempDir())
+ pe := newProxyEdge(t, e, proxyOpts{})
+
+ plain := pe.dial(t, false, ppv2Proxy("203.0.113.7:51000"))
+ secureRaw := pe.dial(t, true, ppv2Proxy("203.0.113.7:51001"))
+ secure := tls.Client(secureRaw, &tls.Config{RootCAs: pe.pool, ServerName: "127.0.0.1"})
+ // Before the flag, each is served by the ordinary chain: :80
+ // redirects to https, :443 reaches the upstream.
+ if res := pe.request(t, plain, false, http.MethodGet, rlHost, "/"); res.status != http.StatusFound || res.connClose {
+ t.Fatalf("before the flag on :80: %d close %v %q, want the redirect, kept open", res.status, res.connClose, res.body)
+ }
+ if res := pe.request(t, secure, false, http.MethodGet, rlHost, "/"); res.status != http.StatusOK || res.connClose {
+ t.Fatalf("before the flag on :443: %d close %v %q, want 200 kept open", res.status, res.connClose, res.body)
+ }
+ // The flag alone: the instant between RaiseTrustBarrier's flag and
+ // its sweep.
+ p.barrier.Store(true)
+ if res := pe.request(t, plain, false, http.MethodGet, "10.0.1.7", lbhealth.Path); res.status != http.StatusOK || res.body != "ok\n" {
+ t.Fatalf("health on the open :80 connection: %d %q, want 200 ok", res.status, res.body)
+ }
+ wantNoClientRefused(t, pe.request(t, plain, false, http.MethodGet, rlHost, "/"), "next request on the open :80 connection")
+ wantNoClientRefused(t, pe.request(t, secure, false, http.MethodGet, rlHost, "/"), "next request on the open :443 connection")
+ if n := hits.Load(); n != 1 {
+ t.Fatalf("upstream hits = %d, want 1 (before the flag only)", n)
+ }
+ if c := counters(t, e); c.NoClientRefused != 2 {
+ t.Fatalf("NoClientRefused = %d, want 2", c.NoClientRefused)
+ }
+}